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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c8ee658b2eb718175f8005dbf2eeb983ce7bcbd8 | 14,933 | c | C | trans/src/x86/operand.c | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | trans/src/x86/operand.c | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | trans/src/x86/operand.c | dj3vande/tendra | 86981ad5574f55821853e3bdf5f82e373f91edb2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2011, The TenDRA Project.
* Copyright 1997, United Kingdom Secretary of State for Defence.
*
* See doc/copyright/ for the full copyright terms.
*/
/*
* operand outputs a 80386 operand, given a "where" and the number of
* bits the operand occupies.
*/
#include <shared/bool.h>
#include <shared/error.h>
#include <local/out.h>
#include <local/code.h>
#include <tdf/shape.h>
#include <tdf/tag.h>
#include <reader/exp.h>
#include <reader/basicread.h>
#include <reader/externs.h>
#include <reader/table_fns.h>
#include <construct/exp.h>
#include <construct/install_fns.h>
#include <flpt/flpt.h>
#include <main/flags.h>
#include <main/print.h>
#ifdef TDF_DIAG3
#include <diag3/diag_fns.h>
#endif
#ifdef TDF_DIAG4
#include <diag4/diag_fns.h>
#endif
#include "localtypes.h"
#include "instr.h"
#include "ops.h"
#include "assembler.h"
#include "operand.h"
/* All variables initialised */
int crt_proc_id; /* init by cproc */
int stack_dec; /* init by cproc */
/* current stack decrement */
exp const_list; /* init by init_all */
/* list of constants belonging to current
procedure */
/*
* Turns an exp and an offset (in bits) into a where
*/
where
mw(exp e, int off)
{
where w;
w.where_exp = e;
w.where_off = off;
return w;
}
/*
* Compares wheres for equality of operand.
*
* This is also used by equiv_reg to detect invalidity of register copy,
* in which case we need to detect overlaps, this case determined by 'overlap'
*/
int
eq_where_exp(exp a, exp b, int first, int overlap)
{
unsigned char na;
unsigned char nb;
rept:
na = a->tag;
nb = b->tag;
if (a == b) {
return 1;
}
if (na == nb) { /* same kind of operation "equal names" */
if (na == val_tag && !isbigval(a) && !isbigval(b)) {
return no(a) == no(b);
}
if (na == ident_tag) {
int good = child(a) != NULL && child(b) != NULL &&
next(child(a)) != NULL && next(child(b)) != NULL;
if (good) {
exp bsa = next(child(a));
exp bsb = next(child(b));
if (bsa->tag == name_tag && child(bsa) == a &&
bsb->tag == name_tag && child(bsb) == b) {
a = child(a);
b = child(b);
first = 0;
goto rept;
}
if (bsa->tag == reff_tag &&
bsb->tag == reff_tag &&
(overlap ? (no(bsa) & -32) == (no(bsb) & -32) : no(bsa) == no(bsb)) &&
child(bsa)->tag == name_tag &&
child(child(bsa)) == a &&
child(bsb)->tag == name_tag &&
child(child(bsb)) == b) {
a = child(a);
b = child(b);
first = 0;
goto rept;
}
}
if (isglob(a) || isglob(b)) {
return 0;
}
return pt(a) == pt(b) &&
(overlap ? (no(a) & -32) == (no(b) & -32) : no(a) == no(b));
}
if (na == name_tag) {
if ((overlap ? (no(a) & -32) != (no(b) & -32) : no(a) != no(b)) ||
(isvar(child(a)) != isvar(child(b)))) {
return 0;
}
a = child(a);
b = child(b);
first = 0;
goto rept;
}
if (na == cont_tag || na == ass_tag) {
a = child(a);
b = child(b);
first = 0;
goto rept;
}
if (na == field_tag || na == reff_tag) {
if (overlap ? (no(a) & -32) != (no(b) & -32) : no(a) != no(b)) {
return 0;
}
a = child(a);
b = child(b);
first = 0;
goto rept;
}
if (na == real_tag && sh(a)->tag == sh(b)->tag) {
flt fa, fb;
int i;
int is_zero = 1;
fa = flptnos[no(a)];
fb = flptnos[no(b)];
for (i = 0; i < MANT_SIZE && fa.mant[i] == fb.mant[i]; i++) {
if (fa.mant[i] != 0) {
is_zero = 0;
}
}
return i == MANT_SIZE &&
(is_zero || (fa.exp == fb.exp &&
fa.sign == fb.sign));
}
return 0;
} /* end equal names */
if (na == name_tag && nb == ident_tag && first) {
if (overlap ? (no(a) & -32) != 0 : no(a) != 0) {
return 0;
}
a = child(a);
first = 0;
goto rept;
}
if (na == ident_tag && nb == name_tag && first) {
if (overlap ? (no(b) & -32) != 0 : no(b) != 0) {
return 0;
}
b = child(b);
first = 0;
goto rept;
}
if (na == cont_tag && child(a)->tag == name_tag &&
isvar(child(child(a))) && nb == ident_tag && first) {
if (overlap ? (no(child(a)) & -32) != 0 : no(child(a)) != 0) {
return 0;
}
a = child(child(a));
first = 0;
goto rept;
}
if (na == ident_tag && nb == cont_tag && child(b)->tag == name_tag
&& isvar(child(child(b))) && first) {
if (overlap ? (no(child(b)) & -32) != 0 : no(child(b)) != 0) {
return 0;
}
b = child(b);
first = 0;
goto rept;
}
if ((na == cont_tag || na == ass_tag) &&
child(a)->tag == name_tag &&
isvar(child(child(a))) && nb == name_tag && !isvar(child(b))) {
if (overlap ? (no(child(a)) & -32) != (no(b) & -32) : no(child(a)) != no(b)) {
return 0;
}
a = child(child(a));
b = child(b);
first = 0;
goto rept;
}
if ((nb == cont_tag || nb == ass_tag) &&
child(b)->tag == name_tag &&
isvar(child(child(b))) && na == name_tag && !isvar(child(a))) {
if (overlap ? (no(child(b)) & -32) != (no(a) & -32) : no(child(b)) != no(a)) {
return 0;
}
a = child(a);
b = child(child(b));
first = 0;
goto rept;
}
if ((na == ass_tag && nb == cont_tag) ||
(nb == ass_tag && na == cont_tag)) {
a = child(a);
b = child(b);
first = 0;
goto rept;
}
return 0;
}
/*
* Compares wheres for equality of operand
*/
int
eq_where(where wa, where wb)
{
exp a = wa.where_exp;
exp b = wb.where_exp;
if (a == NULL || b == NULL) {
return 0;
}
if (wa.where_off != wb.where_off) {
return 0;
}
return eq_where_exp(a, b, 1, 0);
}
/*
* Find the first register in the register bit pattern r
*/
frr
first_reg(int r)
{
frr t;
t.regno = 1;
t.fr_no = 0;
if (r == 0) {
error(ERR_INTERNAL, "illegal register");
return t;
}
while (!(t.regno & r)) {
t.regno = t.regno << 1;
++t.fr_no;
}
return t;
}
/*
* Output operand, wh is a where
*
* Note that the pt field of a declaration now hold a code for the position of
* the value (eg. reg_pl for in a register, local_pl for relative to sp etc.).
*
* The no field hold the location, bit pattern for register, offset (in bits)
* for local etc. stack_dec hold the amount the stack is decremented from its
* position at the start of the procedure (ie the place where no is measured
* from). This is to allow for push operations. b is passed to extn to control
* whether a bracket is output (index instructions). addr is true if we need
* a literal address.
*/
void
operand(int le, where wh, int b, int addr)
{
exp w = wh.where_exp;
int off = wh.where_off;
unsigned char n = w->tag;
if (n == val_tag && !isbigval(w)) { /* integer constant */
int k = no(w) + off;
if (sh(w)->tag == offsethd && al2(sh(w)) != 1) {
k = k / 8;
}
int_operand(k, le);
return;
}
if (n == ident_tag || n == labst_tag) {/* can only be dest */
switch (ptno(w)) {
case local_pl:
rel_sp((no(w) + off - stack_dec) / 8, b);
return;
case reg_pl:
regn(no(w), off, w, le);
return;
default:
error(ERR_INTERNAL, "illegal operand");
return;
}
}
if (n == name_tag) {
exp ident = child(w);
int noff = no(w) + off;
int ni = no(ident);
if (isglob(ident)) {
if (sh(w)->tag == prokhd) { /* special treatment for procedures */
const_extn(ident, noff);
return;
}
if (isvar(ident)) {
const_extn(ident, noff);
} else {
extn(ident, noff, b);
}
return;
}
switch (ptno(ident)) {
case local_pl: /* local so relative to stack pointer or fp */
rel_sp((ni + noff - stack_dec) / 8, b);
return;
case callstack_pl: /* caller arg so relative to stack pointer */
rel_cp((ni + noff - stack_dec) / 8, b);
return;
case par_pl: /* parameter so relative to fp */
rel_ap((ni + noff + 32) / 8, b);
return;
case reg_pl: /* in a register */
regn(ni, noff, w, le);
return;
case ferr_pl: /* relative to fp, depending on push space */
rel_ap1((ni + noff) / 8, b);
return;
default: /* doesnt happen */
error(ERR_INTERNAL, "illegal operand");
return;
}
}
if (n == cont_tag || n == ass_tag) {
exp ref = child(w);
unsigned char s = ref->tag;
if (addr) {
operand(le, mw(child(w), 0), b, 0);
return;
}
if (s == name_tag) { /* content of id */
if (!isvar(child(ref))) {
exp ident = child(ref);
if (ptno(ident) != reg_pl && off != 0) {
error(ERR_INTERNAL, "illegal operand");
}
if (isglob(ident)) {
if (sh(w)->tag != prokhd) {
error(ERR_INTERNAL, "illegal operand");
} else {
if (PIC_code) {
proc_extn(ident, no(ref));
} else {
extn(ident, no(ref), b);
}
}
return;
}
switch (ptno(ident)) {
case reg_pl: /* indirect from register */
ind_reg(no(ident), no(ref), off, ref, b);
return;
default:
error(ERR_INTERNAL, "illegal operand");
return;
}
} else { /* variable */
exp ident = child(ref);
int noff = no(ref) + off;
int ni = no(ident);
if (isglob(ident)) {
extn(ident, noff, b);
return;
}
switch (ptno(ident)) {
case local_pl:
/* local so relative to stack pointer or fp */
rel_sp((ni + noff - stack_dec) / 8, b);
return;
case callstack_pl:
/* caller arg so relative to stack pointer */
rel_cp((ni + noff - stack_dec) / 8, b);
return;
case par_pl: /* parameter so relative to fp */
rel_ap((ni + noff + 32) / 8, b);
return;
case reg_pl: /* in a register */
regn(ni, noff, ref, le);
return;
default: /* doesnt happen */
error(ERR_INTERNAL, "illegal operand");
return;
}
}
} /* end of cont(name) */
if (s == cont_tag && child(ref)->tag == name_tag &&
isvar(child(child(ref)))) {
exp ident = child(child(ref));
if (ptno(ident) != reg_pl && off != 0) {
error(ERR_INTERNAL, "illegal operand");
}
if (isglob(ident)) {
if (sh(w)->tag != prokhd) {
error(ERR_INTERNAL, "illegal operand");
} else {
extn(ident, no(child(ref)), b);
}
return;
}
switch (ptno(ident)) {
case reg_pl: /* indirect from register */
ind_reg(no(ident), no(child(ref)), off, ref, b);
return;
default:
error(ERR_INTERNAL, "illegal operand");
return;
}
} /* end of cont(cont(var)) */
if (s == reff_tag) {
exp et = child(ref);
unsigned char t = et->tag;
if (t == name_tag) {
if (isglob(child(et))) {
extn(child(et), no(ref), b);
return;
}
switch (ptno(child(et))) {
case reg_pl:
ind_reg(no(child(et)), no(et), (no(ref) + off), et, b);
return;
default:
error(ERR_INTERNAL, "illegal operand");
return;
}
} /* end of cont(reff(name)) */
if (t == cont_tag) {
switch (ptno(child(child(et)))) {
case reg_pl:
ind_reg(no(child(child(et))), no(child(et)),
(no(ref) + off), child(et), b);
return;
default:
error(ERR_INTERNAL, "illegal operand");
return;
}
} /* end of cont(ref(cont())) */
if (t == addptr_tag) {
where new_w;
new_w.where_exp = et;
new_w.where_off = off + no(ref);
operand(le, new_w, b, 0);
return;
} /* end of cont(reff(addptr())) */
error(ERR_INTERNAL, "illegal operand");
} /* end of cont(reff()) */
if (s == addptr_tag) {
exp u = next(child(ref));
exp c = getexp(f_bottom, NULL, 0, child(ref), NULL, 0, 0, cont_tag);
where wc, wu;
wc.where_exp = c;
wc.where_off = off;
wu.where_exp = u;
wu.where_off = 0;
if (u->tag == name_tag || u->tag == cont_tag) {
index_opnd(wc, wu, 1);
return;
} /* end of cont(addptr(-, name)) */
if (u->tag == offset_mult_tag) {
int k = no(next(child (u))) / 8; /* cannot be bitfield */
wu.where_exp = child(u);
index_opnd(wc, wu, k);
return;
} /* end of cont(addptr(-, mult)) */
} /* end of cont(addptr()) */
} /* end of cont */
if (n == reff_tag) {
exp se = child(w);
unsigned char s = se->tag;
if (s == name_tag) {
if (isglob(child(se))) {
extn(child(se), no(w), b);
return;
}
switch (ptno(child(se))) {
case reg_pl:
ind_reg(no(child(se)), no(child(se)), no(w), se, b);
return;
default:
error(ERR_INTERNAL, "illegal operand");
return;
}
} /* end of reff(name) */
if (s == cont_tag) {
if (isglob(child(child(se)))) {
extn(child(child(se)), no(w), b);
return;
}
switch (ptno(child(child(se)))) {
case reg_pl:
ind_reg(no(child(child(se))), no(child(se)), no(w), child(se), b);
return;
default:
error(ERR_INTERNAL, "illegal operand");
return;
}
} /* end of reff(cont()) */
if (s == addptr_tag) {
where ww;
ww.where_exp = se;
ww.where_off = off + no(w);
operand(le, ww, b, 0);
return;
} /* end of reff(addptr()) */
} /* end of reff() */
if (n == addptr_tag) {
exp u = next(child(w));
exp c = getexp(f_bottom, NULL, 0, child(w), NULL, 0, 0, cont_tag);
where wc, wu;
wc.where_exp = c;
wc.where_off = off;
wu.where_exp = u;
wu.where_off = 0;
if (u->tag == name_tag || u->tag == cont_tag) {
index_opnd(wc, wu, 1);
return;
} /* end of addptr(-, name) */
if (u->tag == offset_mult_tag) {
int k = no(next(child (u))) / 8; /* cannot be bitfield */
wu.where_exp = child(u);
index_opnd(wc, wu, k);
return;
} /* end of addptr(-, mult) */
} /* end of addptr() */
if (n == real_tag || n == val_tag || n == string_tag ||
n == proc_tag || n == general_proc_tag) {
int ln;
if (off == 0 || addr) {
ln = next_lab();
const_list = getexp(f_bottom, const_list, 0, w, NULL, 0, ln, 0);
const_intnl((addr || n == proc_tag || n == general_proc_tag), ln, 0);
return;
}
/* assumes this is only used just after using the first part of the constant */
const_intnl(0, no(const_list), off);
return;
}
if (n == res_tag) {
const_intnl(0, no(w), off);
return;
}
if (n == null_tag) {
int_operand(no(w), le);
return;
}
if (n == field_tag) {
operand(le, mw(child(w), off + no(w)), b, addr);
return;
}
if (n == make_lv_tag) {
label_operand(w);
return;
}
if (n == current_env_tag) {
outbp();
return;
}
if (n == env_offset_tag) {
if (child(w)->tag == 0) { /* must be caller arg with var_callees */
int_operand(no(child(w)) / 8, le);
return;
}
asm_printf("$");
envoff_operand(child(w), no(w));
return;
}
if (n == env_size_tag) {
asm_printf("$");
envsize_operand(child(child(w)));
return;
}
if (n == local_free_all_tag) {
ldisp();
return;
}
if (n == clear_tag) {
/* any legal operand will do! */
if (sh(w)->tag >= shrealhd && sh(w)->tag <= doublehd) {
asm_printf("%s", "%st");
return;
}
switch (shape_size(sh(w))) {
case 8: asm_printf("%s", "%al"); return;
case 16: asm_printf("%s", "%ax"); return;
default: asm_printf("%s", "%eax"); return;
}
}
error(ERR_INTERNAL, "illegal operand");
}
| 20.289402 | 81 | 0.546508 | [
"shape"
] |
c8f0bfd20929f6d503efed8881465526d278186f | 6,086 | c | C | book/tlpi/tlpi-book/procexec/execlp.c | deevarvar/myLab | 7a5019f5f7fc11e173d350e6e2a7d2c80504782d | [
"MIT"
] | null | null | null | book/tlpi/tlpi-book/procexec/execlp.c | deevarvar/myLab | 7a5019f5f7fc11e173d350e6e2a7d2c80504782d | [
"MIT"
] | null | null | null | book/tlpi/tlpi-book/procexec/execlp.c | deevarvar/myLab | 7a5019f5f7fc11e173d350e6e2a7d2c80504782d | [
"MIT"
] | 3 | 2016-10-08T15:01:49.000Z | 2018-05-24T03:14:24.000Z | /*************************************************************************\
* Copyright (C) Michael Kerrisk, 2014. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU Affero General Public License as published *
* by the Free Software Foundation, either version 3 or (at your option) *
* any later version. This program is distributed without any warranty. *
* See the file COPYING.agpl-v3 for details. *
\*************************************************************************/
/* Solution for Exercise 27-2 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
extern char **environ;
#define max(x,y) ((x) > (y) ? (x) : (y))
#define SHELL_PATH "/bin/sh" /* pathname for the standard shell */
/* Exec a script file using the standard shell */
static void
execShScript(int argc, char *argv[], char *envp[])
{
char *shArgv[argc + 1];
int j;
shArgv[0] = SHELL_PATH;
for (j = 0; j <= argc; j++)
shArgv[j + 1] = argv[j];
execve(SHELL_PATH, shArgv, envp);
/* Only get here, if execve() fails, in which case we return
to our caller. */
}
int
execlp(const char *filename, const char *arg, ...)
{
char **argv; /* Argument vector for new program */
int argc; /* Number of items used in argv */
int argvSize; /* Currently allocated size of argv */
va_list argList; /* For variable argument list parsing */
char **envp; /* Environment for new program */
char *PATH; /* Value of PATH environment variable */
char *pathname; /* Path prefix + '/' + filename */
char *prStart, *prEnd; /* Start and end of prefix currently
being processed from PATH */
int savedErrno;
int morePrefixes; /* True if there are more prefixes in PATH */
char *p;
int j;
int fndEACCES; /* True if any execve() returned EACCES */
fndEACCES = 0;
/***** Build argument vector from variable length argument list *****/
argvSize = 100;
argv = calloc(argvSize, sizeof(void *));
if (argv == NULL) return -1;
argv[0] = (char *) arg;
argc = 1;
/* Walk variable length argument list until NULL terminator is found,
building argv as we go. */
va_start(argList, arg);
while (argv[argc - 1] != NULL) {
if (argc + 1 >= argvSize) { /* Resize argv if required */
argvSize += 100;
argv = realloc(argv, sizeof(void *));
if (argv == NULL) return -1;
}
argv[argc] = va_arg(argList, char *);
argc++;
}
va_end(argList);
/***** Use caller's environment to create envp vector *****/
for (j = 0; environ[j] != NULL; ) /* Calculate size of environ */
j++;
envp = calloc(sizeof(void *), j + 1);
if (envp == NULL) return -1;
for (j = 0; environ[j] != NULL; j++) /* Duplicate environ in envp */
envp[j] = strdup(environ[j]);
envp[j] = NULL; /* List must be terminated by NULL pointer */
/***** Now try to exec filename *****/
if (strchr(filename, '/') != NULL) {
/* If file contains a slash, it's a pathname and we don't do
a search using PATH */
pathname = strdup(filename);
execve(pathname, argv, envp);
savedErrno = errno; /* So we can return correct errno */
if (errno == ENOEXEC)
execShScript(argc, argv, envp);
free(pathname); /* Avoid memory leaks */
} else { /* Use PATH */
/* Treat undefined PATH as "." */
p = getenv("PATH");
PATH = (p == NULL || strlen(p) == 0) ? strdup(".") : strdup(p);
/* For each prefix in PATH, try to exec 'filename' in that
directory. The loop will terminate either when we successfully
exec or when we run out of path prefixes. */
prStart = PATH;
morePrefixes = 1;
while (morePrefixes) {
/* Locate end of prefix */
prEnd = strchr(prStart, ':');
if (prEnd == NULL) /* Handle last prefix */
prEnd = prStart + strlen(prStart);
/* Build complete pathname from path prefix and filename */
pathname = malloc(max(1, prEnd - prStart) + strlen(filename)
+ 2);
pathname[0] = '\0';
if (prEnd == prStart) /* Last prefix */
strcat(pathname, ".");
else
strncat(pathname, prStart, prEnd - prStart);
strcat(pathname, "/");
strcat(pathname, filename);
if (*prEnd == '\0') /* No more prefixes */
morePrefixes = 0;
else
prStart = prEnd + 1; /* Move to start of next prefix */
/* Try to exec pathname; execve() returns only if we failed. */
execve(pathname, argv, envp);
savedErrno = errno; /* So we can return correct errno */
if (errno == EACCES)
fndEACCES = 1;
else if (errno == ENOEXEC)
execShScript(argc, argv, envp);
/* Avoid memory leaks, in case no execve() succeeds! */
free(pathname);
}
free(PATH);
}
/* If we get here, execve() failed; clean up and return -1, ensuring
that errno contains the value returned by (the last) execve() */
free(argv);
for (j = 0; envp[j] != NULL; j++)
free(envp[j]);
free(envp);
/* SUSv3 says that if any execve failed with EACCES then that
is the error that should be returned by exec[lv]p() */
errno = fndEACCES ? EACCES : savedErrno;
return -1;
}
| 32.545455 | 77 | 0.509201 | [
"vector"
] |
c8f8cbf7bbebca9132224f0f39922b24f0f28293 | 103,674 | c | C | compilers/maru/maru/eval2.c | danielgavrilov/nile | 8c7690313642652c7361dded5464279929fa7412 | [
"MIT"
] | 499 | 2015-01-08T17:49:25.000Z | 2022-03-13T07:32:46.000Z | compilers/maru/maru/eval2.c | arturtamborski/nile | 52e24b9c429b36c548ba98f705aa7539701f32f9 | [
"MIT"
] | 6 | 2015-01-09T05:25:56.000Z | 2020-09-01T13:23:35.000Z | compilers/maru/maru/eval2.c | arturtamborski/nile | 52e24b9c429b36c548ba98f705aa7539701f32f9 | [
"MIT"
] | 42 | 2015-01-08T18:43:38.000Z | 2022-03-10T18:11:35.000Z | // last edited: 2012-12-23 23:25:00 by piumarta on emilia.local
#define DEMO_BITS 1
#define _ISOC99_SOURCE 1
#define _BSD_SOURCE 1
#include <stdio.h>
#include <locale.h>
#include <stdarg.h>
#include <errno.h>
#include <math.h>
#include <signal.h>
// #include <stddef.h>
// #include <string.h>
// #include <sys/types.h>
#if defined(__MACH__)
# include <ffi/ffi.h>
#else
# include <ffi.h>
#endif
// #include <assert.h>
extern int isatty(int);
#if defined(WIN32)
# include <malloc.h>
# define swnprintf(BUF, SIZE, FMT, ARG) swprintf(BUF, FMT, ARG)
#else
# define swnprintf swprintf
#endif
// #define TAG_INT 1
// //#define LIB_GC 1
#if defined(NDEBUG)
# define GC_APP_HEADER int type;
#else
# define GC_APP_HEADER int printing, type;
#endif
#define GC_SAVE 1
#if (LIB_GC)
# include "libgc.c"
#else
# include "gc.c"
#endif
#include "wcs.c"
#include "buffer.c"
union Object;
typedef union Object *oop;
typedef oop (*imp_t)(oop args, oop env);
typedef union {
int arg_int;
int32_t arg_int32;
int64_t arg_int64;
long arg_long;
float arg_float;
double arg_double;
void *arg_pointer;
char *arg_string;
wchar_t *arg_String;
} arg_t;
typedef void (*cast_t)(oop arg, void **argp, arg_t *buf);
typedef struct {
int arg_count;
int arg_rest;
ffi_type *arg_types[32];
cast_t arg_casts[32];
} proto_t;
#define nil ((oop)0)
enum {
Undefined, Data, Long, Double, String, Symbol, Pair, _Array, Array, Expr, Form, Fixed, Subr,
// Variable, Env, Context
};
typedef long long_t;
struct Data { };
struct Long { long_t bits; };
struct Double { double bits; };
struct String { oop size; wchar_t *bits; }; /* bits is in managed memory */
struct Symbol { wchar_t *bits; int flags};
struct Pair { oop head, tail, source; };
struct Array { oop size, _array; };
struct Expr { oop name, definition, environment, profile; };
struct Form { oop function, symbol; };
struct Fixed { oop function; };
struct Subr { wchar_t *name; imp_t imp; proto_t *sig; int profile; };
// struct Variable { oop name, value, env, index, type; };
// struct Env { oop parent, level, offset, bindings, stable; };
// struct Context { oop home, env, bindings, callee, pc; };
union Object {
struct Data Data;
struct Long Long;
struct Double Double;
struct String String;
struct Symbol Symbol;
struct Pair Pair;
struct Array Array;
struct Expr Expr;
struct Form Form;
struct Fixed Fixed;
struct Subr Subr;
// struct Variable Variable;
// struct Env Env;
// struct Context Context;
};
static void fatal(char *reason, ...);
#if !defined(NDEBUG)
# define setType(OBJ, TYPE) ptr2hdr(OBJ)->printing= 0; (ptr2hdr(OBJ)->type= (TYPE))
#else
# define setType(OBJ, TYPE) (ptr2hdr(OBJ)->type= (TYPE))
#endif
#if (TAG_INT)
static inline int getType(oop obj) { return obj ? (((long)obj & 1) ? Long : ptr2hdr(obj)->type) : Undefined; }
#else
static inline int getType(oop obj) { return obj ? ptr2hdr(obj)->type : Undefined; }
#endif
#define is(TYPE, OBJ) ((OBJ) && (TYPE == getType(OBJ)))
#if defined(NDEBUG)
# define checkType(OBJ, TYPE) OBJ
#else
# define checkType(OBJ, TYPE) _checkType(OBJ, TYPE, #TYPE, __FILE__, __LINE__)
static inline oop _checkType(oop obj, int type, char *name, char *file, int line)
{
if (obj && !((long)obj & 1) && !ptr2hdr(obj)->used) fatal("%s:%i: attempt to access dead object %s\n", file, line, name);
if (!is(type, obj)) fatal("%s:%i: typecheck failed for %s (%i != %i)\n", file, line, name, type, getType(obj));
return obj;
}
#endif
#define get(OBJ, TYPE, FIELD) (checkType(OBJ, TYPE)->TYPE.FIELD)
#define set(OBJ, TYPE, FIELD, VALUE) (checkType(OBJ, TYPE)->TYPE.FIELD= (VALUE))
#define getHead(OBJ) get(OBJ, Pair,head)
#define getTail(OBJ) get(OBJ, Pair,tail)
#define setHead(OBJ, VAL) set(OBJ, Pair,head, VAL)
#define setTail(OBJ, VAL) set(OBJ, Pair,tail, VAL)
static oop car(oop obj) { return is(Pair, obj) ? getHead(obj) : nil; }
static oop cdr(oop obj) { return is(Pair, obj) ? getTail(obj) : nil; }
static oop caar(oop obj) { return car(car(obj)); }
static oop cadr(oop obj) { return car(cdr(obj)); }
static oop cdar(oop obj) { return cdr(car(obj)); }
static oop cddr(oop obj) { return cdr(cdr(obj)); }
// //static oop caaar(oop obj) { return car(car(car(obj))); }
// //static oop cadar(oop obj) { return car(cdr(car(obj))); }
static oop caddr(oop obj) { return car(cdr(cdr(obj))); }
// static oop cadddr(oop obj) { return car(cdr(cdr(cdr(obj)))); }
#define getVar(X) getTail(X)
#define setVar(X, V) setTail(X, V)
static oop _newBits(int type, size_t size) { oop obj= GC_malloc_atomic(size); setType(obj, type); return obj; }
static oop _newOops(int type, size_t size) { oop obj= GC_malloc(size); setType(obj, type); return obj; }
#define newBits(TYPE) _newBits(TYPE, sizeof(struct TYPE))
#define newOops(TYPE) _newOops(TYPE, sizeof(struct TYPE))
static char *argv0;
static oop symbols= nil, globals= nil, globalNamespace= nil, expanders= nil, encoders= nil, evaluators= nil, applicators= nil, backtrace= nil, arguments= nil, input= nil, output= nil;
static int traceDepth= 0;
static oop traceStack= nil, currentPath= nil, currentLine= nil, currentSource= nil;
static oop s_locals= nil, s_set= nil, s_define= nil, s_let= nil, s_lambda= nil, s_quote= nil, s_quasiquote= nil, s_unquote= nil, s_unquote_splicing= nil, s_t= nil, s_dot= nil, s_etc= nil, s_bracket= nil, s_brace= nil, s_main= nil;
// static oop f_set= nil, f_quote= nil, f_lambda= nil, f_let= nil, f_define;
static int opt_b= 0, opt_g= 0, opt_O= 0, opt_p= 0, opt_v= 0;
// static oop newData(size_t len) { return _newBits(Data, len); }
#if (TAG_INT)
static inline int isLong(oop x) { return (((long)x & 1) || Long == getType(x)); }
static inline oop newLong(long x) { if ((x ^ (x << 1)) < 0) { oop obj= newBits(Long); set(obj, Long,bits, x); return obj; } return ((oop)((x << 1) | 1)); }
static inline long getLong(oop x) { if ((long)x & 1) return (long)x >> 1; return get(x, Long,bits); }
#else
# define isLong(X) is(Long, (X))
static oop newLong(long bits) { oop obj= newBits(Long); set(obj, Long,bits, bits); return obj; }
# define getLong(X) get((X), Long,bits)
#endif
static void setDouble(oop obj, double bits) { memcpy(&obj->Double.bits, &bits, sizeof(bits)); }
static double getDouble(oop obj) { double bits; memcpy(&bits, &obj->Double.bits, sizeof(bits)); return bits; }
#define isDouble(X) is(Double, (X))
#define isPair(X) is(Pair, (X))
static inline int isNumeric(oop obj) { return isLong(obj) || isDouble(obj); }
static oop newDouble(double bits) { oop obj= newBits(Double); setDouble(obj, bits); return obj; }
static oop _newString(size_t len)
{
wchar_t *gstr= (wchar_t *)_newBits(-1, sizeof(wchar_t) * (len + 1)); GC_PROTECT(gstr); /* + 1 to ensure null terminator */
oop obj= newOops(String); GC_PROTECT(obj);
set(obj, String,size, newLong(len)); GC_UNPROTECT(obj);
set(obj, String,bits, gstr); GC_UNPROTECT(gstr);
return obj;
}
static oop newStringN(wchar_t *cstr, size_t len)
{
oop obj= _newString(len);
memcpy(get(obj, String,bits), cstr, sizeof(wchar_t) * len);
return obj;
}
static oop newString(wchar_t *cstr)
{
return newStringN(cstr, wcslen(cstr));
}
static int stringLength(oop string)
{
return getLong(get(string, String,size));
}
static oop newSymbol(wchar_t *cstr) { oop obj= newBits(Symbol); set(obj, Symbol,bits, wcsdup(cstr)); return obj; }
static int symbolLength(oop symbol)
{
return wcslen(get(symbol, Symbol,bits));
}
static oop cons(oop head, oop tail) { oop obj= newOops(Pair); set(obj, Pair,head, head); set(obj, Pair,tail, tail); return obj; }
static oop newPairFrom(oop head, oop tail, oop source)
{
oop obj= newOops(Pair);
set(obj, Pair,head, head);
set(obj, Pair,tail, tail);
set(obj, Pair,source, get(source, Pair,source));
return obj;
}
static oop newArray(int size)
{
int cap= size ? size : 1;
oop elts= _newOops(_Array, sizeof(oop) * cap); GC_PROTECT(elts);
oop obj= newOops( Array); GC_PROTECT(obj);
set(obj, Array,_array, elts);
set(obj, Array,size, newLong(size)); GC_UNPROTECT(obj); GC_UNPROTECT(elts);
return obj;
}
static int arrayLength(oop obj)
{
return is(Array, obj) ? getLong(get(obj, Array,size)) : 0;
}
static oop arrayAt(oop array, int index)
{
if (is(Array, array)) {
oop elts= get(array, Array,_array);
int size= arrayLength(array);
if ((unsigned)index < (unsigned)size)
return ((oop *)elts)[index];
}
return nil;
}
static oop arrayAtPut(oop array, int index, oop val)
{
if (is(Array, array)) {
int size= arrayLength(array);
oop elts= get(array, Array,_array);
if ((unsigned)index >= (unsigned)size) {
GC_PROTECT(array);
int cap= GC_size(elts) / sizeof(oop);
if (index >= cap) {
while (cap <= index) cap *= 2;
oop oops= _newOops(_Array, sizeof(oop) * cap);
memcpy((oop *)oops, (oop *)elts, sizeof(oop) * size);
elts= set(array, Array,_array, oops);
}
set(array, Array,size, newLong(index + 1));
GC_UNPROTECT(array);
}
return ((oop *)elts)[index]= val;
}
return nil;
}
static oop arrayAppend(oop array, oop val)
{
return arrayAtPut(array, arrayLength(array), val);
}
static oop arrayInsert(oop obj, size_t index, oop value)
{
size_t len= arrayLength(obj);
arrayAppend(obj, value);
if (index < len) {
oop elts= get(obj, Array,_array);
oop *oops= (oop *)elts + index;
memmove(oops + 1, oops, sizeof(oop) * (len - index));
}
arrayAtPut(obj, index, value);
return value;
}
static oop oopAt(oop obj, int index)
{
if (obj && !isLong(obj) && !GC_atomic(obj)) {
int size= GC_size(obj) / sizeof(oop);
if ((unsigned)index < (unsigned)size) return ((oop *)obj)[index];
}
return nil;
}
static oop oopAtPut(oop obj, int index, oop value)
{
if (obj && !isLong(obj) && !GC_atomic(obj)) {
int size= GC_size(obj) / sizeof(oop);
if ((unsigned)index < (unsigned)size) return ((oop *)obj)[index]= value;
}
return nil;
}
static oop newExpr(oop defn, oop env)
{
oop obj= newOops(Expr); GC_PROTECT(obj);
set(obj, Expr,definition, defn);
set(obj, Expr,environment, env);
set(obj, Expr,profile, newLong(0)); GC_UNPROTECT(obj);
return obj;
}
static oop newForm(oop fn, oop sym) { oop obj= newOops(Form); set(obj, Form,function, fn); set(obj, Form,symbol, sym); return obj; }
static oop newFixed(oop function) { oop obj= newOops(Fixed); set(obj, Fixed,function, function); return obj; }
static oop newSubr(wchar_t *name, imp_t imp, proto_t *sig)
{
oop obj= newBits(Subr);
set(obj, Subr,name, name);
set(obj, Subr,imp, imp);
set(obj, Subr,sig, sig);
set(obj, Subr,profile, 0);
return obj;
}
// static oop newVariable(oop name, oop value, oop env, int index)
// {
// oop obj= newOops(Variable); GC_PROTECT(obj);
// set(obj, Variable,name, name);
// set(obj, Variable,value, value);
// set(obj, Variable,env, env);
// set(obj, Variable,index, newLong(index));
// set(obj, Variable,type, 0); GC_UNPROTECT(obj);
// return obj;
// }
// static oop newEnv(oop parent, int level, int offset)
// {
// oop obj= newOops(Env); GC_PROTECT(obj);
// set(obj, Env,parent, parent);
// set(obj, Env,level, newLong((nil == parent) ? 0 : getLong(get(parent, Env,level)) + level));
// set(obj, Env,offset, newLong(offset));
// set(obj, Env,bindings, newArray(0)); GC_UNPROTECT(obj);
// return obj;
// }
// static oop newBaseContext(oop home, oop caller, oop env)
// {
// oop obj= newOops(Context); GC_PROTECT(obj);
// set(obj, Context,home, home);
// set(obj, Context,env, env);
// set(obj, Context,bindings, newArray(0)); GC_UNPROTECT(obj);
// return obj;
// }
// static oop newContext(oop home, oop caller, oop env)
// {
// oop obj= nil;
// //xxx fix escape analysis for nested lambdas with free variables
// #if 0
// if ((nil != caller) && (nil != (obj= get(caller, Context,callee)))) {
// set(obj, Context,home, home);
// set(obj, Context,env, env);
// return obj;
// }
// #endif
// obj= newBaseContext(home, caller, env);
// if (nil != caller) set(caller, Context,callee, obj);
// return obj;
// }
static void dump(oop);
static void dumpln(oop);
// static oop findLocalVariable(oop env, oop name)
// {
// oop bindings= get(env, Env,bindings);
// int index= arrayLength(bindings);
// while (--index >= 0) {
// oop var= arrayAt(bindings, index);
// if (get(var, Variable,name) == name)
// return var;
// }
// return nil;
// }
static void oprintf(char *fmt, ...);
static oop findEnvironment(oop env)
{
while (is(Pair, env)) {
//oprintf("findEnv: %P\n", caar(env));
oop ass= getHead(env);
if (is(Pair, ass) && getTail(ass) == env) return env;
env= getTail(env);
}
return nil;
}
static oop findVariable2(oop env, oop name)
{
while (env) {
oop ass= getHead(env);
if (name == car(ass)) return ass;
env= getTail(env);
}
return nil;
}
#define GLOBAL_CACHE_SIZE 2003 // 257 // 1021 // 7919
static oop _globalCache= 0;
static oop findVariable(oop env, oop name)
{
while (env) {
if (env == globalNamespace) {
long hash= ((long)name) % GLOBAL_CACHE_SIZE;
oop ent= ((oop *)_globalCache)[hash];
if ((nil != ent) && (name == getHead(ent))) return ent;
return ((oop *)_globalCache)[hash]= findVariable2(env, name);
}
oop ass= getHead(env);
if (name == car(ass)) return ass;
env= getTail(env);
}
return nil;
}
static oop findNamespaceVariable(oop env, oop name)
{
oop beg= findEnvironment(env);
oop end= findEnvironment(cdr(env));
while (beg != end) {
if (beg == globalNamespace) {
long hash= ((long)name) % GLOBAL_CACHE_SIZE;
oop ent= ((oop *)_globalCache)[hash];
if ((nil != ent) && (name == getHead(ent))) return ent;
return ((oop *)_globalCache)[hash]= findVariable2(env, name);
}
oop ass= car(beg);
if (name == car(ass)) return ass;
beg= getTail(beg);
}
return nil;
}
static oop lookup(oop env, oop name)
{
return cdr(findVariable(env, name));
}
static oop define(oop env, oop name, oop value)
{
env= findEnvironment(env); if (!env) fatal("failed to find an environment");
#if 0
oop binding= findVariable(env, name);
if (binding) {
setTail(binding, value);
}
else {
binding= cons(nil, getTail(env));
setTail(env, binding);
binding= setHead(binding, cons(name, value));
}
#else
oop binding= cons(nil, getTail(env));
setTail(env, binding);
binding= setHead(binding, cons(name, value));
#endif
return binding;
}
// static int isGlobal(oop var)
// {
// oop env= get(var, Variable,env);
// return (nil != env) && (0 == getLong(get(env, Env,level)));
// }
static oop newBool(int b) { return b ? s_t : nil; }
static oop intern(wchar_t *string)
{
ssize_t lo= 0, hi= arrayLength(symbols) - 1, c= 0;
oop s= nil;
while (lo <= hi) {
size_t m= (lo + hi) / 2;
s= arrayAt(symbols, m);
c= wcscmp(string, get(s, Symbol,bits));
if (c < 0) hi= m - 1;
else if (c > 0) lo= m + 1;
else return s;
}
GC_PROTECT(s);
s= newSymbol(string);
arrayInsert(symbols, lo, s);
GC_UNPROTECT(s);
return s;
}
#include "chartab.h"
static int isPrint(int c) { return (0 <= c && c <= 127 && (CHAR_PRINT & chartab[c])) || (c >= 128); }
static int isAlpha(int c) { return (0 <= c && c <= 127 && (CHAR_ALPHA & chartab[c])) || (c >= 128); }
static int isDigit10(int c) { return (0 <= c && c <= 127 && (CHAR_DIGIT10 & chartab[c])); }
static int isDigit16(int c) { return (0 <= c && c <= 127 && (CHAR_DIGIT16 & chartab[c])); }
static int isLetter(int c) { return (0 <= c && c <= 127 && (CHAR_LETTER & chartab[c])) || (c >= 128); }
#define DONE ((oop)-4) /* cannot be a tagged immediate */
static void beginSource(wchar_t *path)
{
currentPath= newString(path);
currentLine= newLong(1);
currentSource= cons(currentSource, nil);
set(currentSource, Pair,source, cons(currentPath, currentLine));
}
static void advanceSource(void)
{
currentLine= newLong(getLong(currentLine) + 1);
set(currentSource, Pair,source, cons(currentPath, currentLine));
}
static void endSource(void)
{
currentSource= get(currentSource, Pair,head);
oop src= get(currentSource, Pair,source);
currentPath= car(src);
currentLine= cdr(src);
}
static oop readExpr(FILE *fp);
static oop readList(FILE *fp, int delim)
{
oop head= nil, tail= head, obj= nil;
GC_PROTECT(head);
GC_PROTECT(obj);
obj= readExpr(fp);
if (obj == DONE) goto eof;
head= tail= newPairFrom(obj, nil, currentSource);
for (;;) {
obj= readExpr(fp);
if (obj == DONE) goto eof;
if (obj == s_dot) {
obj= readExpr(fp);
if (obj == DONE) fatal("missing item after .");
tail= set(tail, Pair,tail, obj);
obj= readExpr(fp);
if (obj != DONE) fatal("extra item after .");
goto eof;
}
obj= newPairFrom(obj, nil, currentSource);
tail= set(tail, Pair,tail, obj);
}
eof:;
int c= getwc(fp);
if (c != delim) {
if (c < 0) fatal("EOF while reading list");
fatal("mismatched delimiter: expected '%c' found '%c'", delim, c);
}
GC_UNPROTECT(obj);
GC_UNPROTECT(head);
return head;
}
static int digitValue(wint_t c)
{
switch (c) {
case '0' ... '9': return c - '0';
case 'A' ... 'Z': return c - 'A' + 10;
case 'a' ... 'z': return c - 'a' + 10;
}
fatal("illegal digit in character escape");
return 0;
}
static int isHexadecimal(wint_t c)
{
switch (c) {
case '0' ... '9':
case 'A' ... 'F':
case 'a' ... 'f':
return 1;
}
return 0;
}
static int isOctal(wint_t c)
{
return '0' <= c && c <= '7';
}
static int readChar(wint_t c, FILE *fp)
{
if ('\\' == c) {
c= getwc(fp);
switch (c) {
case 'a': return '\a';
case 'b': return '\b';
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case 'v': return '\v';
case 'u': {
wint_t a= getwc(fp), b= getwc(fp), c= getwc(fp), d= getwc(fp);
return (digitValue(a) << 12) + (digitValue(b) << 8) + (digitValue(c) << 4) + digitValue(d);
}
case 'x': {
int x= 0;
if (isHexadecimal(c= getwc(fp))) {
x= digitValue(c);
if (isHexadecimal(c= getwc(fp))) {
x= x * 16 + digitValue(c);
c= getwc(fp);
}
}
ungetwc(c, fp);
return x;
}
case '0' ... '7': {
int x= digitValue(c);
if (isOctal(c= getwc(fp))) {
x= x * 8 + digitValue(c);
if (isOctal(c= getwc(fp))) {
x= x * 8 + digitValue(c);
c= getwc(fp);
}
}
ungetwc(c, fp);
return x;
}
default:
if (isAlpha(c) || isDigit10(c)) fatal("illegal character escape: \\%c", c);
return c;
}
}
return c;
}
static oop readExpr(FILE *fp)
{
for (;;) {
wint_t c= getwc(fp);
switch (c) {
case WEOF: {
return DONE;
}
case '\n': {
while ('\r' == (c= getwc(fp)));
if (c >= 0) ungetwc(c, fp);
advanceSource();
continue;
}
case '\r': {
while ('\n' == (c= getwc(fp)));
ungetwc(c, fp);
advanceSource();
continue;
}
case '\t': case ' ': {
continue;
}
case ';': {
for (;;) {
c= getwc(fp);
if (EOF == c) break;
if ('\n' == c || '\r' == c) {
ungetwc(c, fp);
break;
}
}
continue;
}
case '"': {
static struct buffer buf= BUFFER_INITIALISER;
buffer_reset(&buf);
for (;;) {
c= getwc(fp);
if ('"' == c) break;
c= readChar(c, fp);
if (EOF == c) fatal("EOF in string literal");
buffer_append(&buf, c);
}
oop obj= newString(buffer_contents(&buf));
//buffer_free(&buf);
return obj;
}
case '?': {
return newLong(readChar(getwc(fp), fp));
}
case '\'': {
oop obj= readExpr(fp);
if (obj == DONE)
obj= s_quote;
else {
GC_PROTECT(obj);
obj= newPairFrom(obj, nil, currentSource);
obj= newPairFrom(s_quote, obj, currentSource);
GC_UNPROTECT(obj);
}
return obj;
}
case '`': {
oop obj= readExpr(fp);
if (obj == DONE)
obj= s_quasiquote;
else {
GC_PROTECT(obj);
obj= newPairFrom(obj, nil, currentSource);
obj= newPairFrom(s_quasiquote, obj, currentSource);
GC_UNPROTECT(obj);
}
return obj;
}
case ',': {
oop sym= s_unquote;
c= getwc(fp);
if ('@' == c) sym= s_unquote_splicing;
else ungetwc(c, fp);
oop obj= readExpr(fp);
if (obj == DONE)
obj= sym;
else {
GC_PROTECT(obj);
obj= newPairFrom(obj, nil, currentSource);
obj= newPairFrom(sym, obj, currentSource);
GC_UNPROTECT(obj);
}
return obj;
}
case '0' ... '9':
doDigits: {
static struct buffer buf= BUFFER_INITIALISER;
buffer_reset(&buf);
do {
buffer_append(&buf, c);
c= getwc(fp);
} while (isDigit10(c));
if (('.' == c) || ('e' == c)) {
if ('.' == c) {
do {
buffer_append(&buf, c);
c= getwc(fp);
} while (isDigit10(c));
}
if ('e' == c) {
buffer_append(&buf, c);
c= getwc(fp);
if ('-' == c) {
buffer_append(&buf, c);
c= getwc(fp);
}
while (isDigit10(c)) {
buffer_append(&buf, c);
c= getwc(fp);
}
}
ungetwc(c, fp);
oop obj= newDouble(wcstod(buffer_contents(&buf), 0));
return obj;
}
if (('x' == c) && ((1 == buf.position)
|| ((2 == buf.position) && (buf.buffer[0] == '-'))
))
do {
buffer_append(&buf, c);
c= getwc(fp);
} while (isDigit16(c));
ungetwc(c, fp);
oop obj= newLong(wcstoul(buffer_contents(&buf), 0, 0));
return obj;
}
case '(': return readList(fp, ')'); case ')': ungetwc(c, fp); return DONE;
case '[': {
oop obj= readList(fp, ']'); GC_PROTECT(obj);
obj= newPairFrom(s_bracket, obj, obj); GC_UNPROTECT(obj);
return obj;
}
case ']': ungetwc(c, fp); return DONE;
case '{': {
oop obj= readList(fp, '}'); GC_PROTECT(obj);
obj= newPairFrom(s_brace, obj, obj); GC_UNPROTECT(obj);
return obj;
}
case '}': ungetwc(c, fp); return DONE;
case '-': {
wint_t d= getwc(fp);
ungetwc(d, fp);
if (isDigit10(d)) goto doDigits;
/* fall through... */
}
default: {
if (isLetter(c)) {
static struct buffer buf= BUFFER_INITIALISER;
oop obj= nil; GC_PROTECT(obj);
//oop in= nil; GC_PROTECT(in);
buffer_reset(&buf);
while (isLetter(c) || isDigit10(c)) {
// if (('.' == c) && buf.position) {
// c= getwc(fp);
// if (!isLetter(c) && !isDigit10(c)) {
// ungetwc(c, fp);
// c= '.';
// }
// else {
// obj= intern(buffer_contents(&buf));
// in= newPair(obj, in);
// buffer_reset(&buf);
// }
// }
buffer_append(&buf, c);
c= getwc(fp);
}
ungetwc(c, fp);
obj= intern(buffer_contents(&buf));
// while (nil != in) {
// obj= newPair(obj, nil);
// obj= newPair(getHead(in), obj);
// obj= newPair(s_in, obj);
// in= getTail(in);
// }
//GC_UNPROTECT(in);
GC_UNPROTECT(obj);
return obj;
}
fatal(isPrint(c) ? "illegal character: 0x%02x '%c'" : "illegal character: 0x%02x", c, c);
}
}
}
}
static void doprint(FILE *stream, oop obj, int storing)
{
if (!obj) {
fprintf(stream, "()");
return;
}
if (obj == globals) {
fprintf(stream, "<the global environment>");
return;
}
#if !defined(NDEBUG)
if (ptr2hdr(obj)->printing) {
fprintf(stream, "<loop>%i %i", getType(obj), ptr2hdr(obj)->printing);
return;
}
ptr2hdr(obj)->printing += 1;
#endif
switch (getType(obj)) {
case Undefined: fprintf(stream, "UNDEFINED"); break;
case Data: {
//int i, j= GC_size(obj);
fprintf(stream, "<data[%i]", (int)GC_size(obj));
//for (i= 0; i < j; ++i) fprintf(stream, " %02x", ((unsigned char *)obj)[i]);
fprintf(stream, ">");
break;
}
case Long: fprintf(stream, "%ld", getLong(obj)); break;
case Double: fprintf(stream, "%lf", getDouble(obj)); break;
case String: {
if (!storing)
fprintf(stream, "%ls", get(obj, String,bits));
else {
wchar_t *p= get(obj, String,bits);
int c;
putc('"', stream);
while ((c= *p++)) {
if (c >= ' ')
switch (c) {
case '"': printf("\\\""); break;
case '\\': printf("\\\\"); break;
default: putwc(c, stream); break;
}
else fprintf(stream, "\\%03o", c);
}
putc('"', stream);
}
break;
}
case Symbol: fprintf(stream, "%ls", get(obj, Symbol,bits)); break;
case Pair: {
oop head= obj;
#if 0
if (nil != get(head, Pair,source)) {
oop source= get(head, Pair,source);
oop path= car(source);
oop line= cdr(source);
fprintf(stream, "<%ls:%ld>", get(path, String,bits), getLong(line));
}
#endif
fprintf(stream, "(");
for (;;) {
assert(is(Pair, head));
if (head == getVar(globals)) {
fprintf(stream, "<...all the globals...>");
head= nil;
}
else if (head == globals) {
fprintf(stream, "<the global association>");
head= nil;
}
else if (is(Pair, getHead(head))
&& is(Symbol, getHead(getHead(head)))
&& head == getTail(getHead(head))) {
fprintf(stream, "<%ls>", get(getHead(getHead(head)), Symbol,bits));
}
else
doprint(stream, getHead(head), storing);
head= cdr(head);
if (!is(Pair, head)) break;
fprintf(stream, " ");
}
if (nil != head) {
fprintf(stream, " . ");
doprint(stream, head, storing);
}
fprintf(stream, ")");
break;
}
case Array: {
int i, len= arrayLength(obj);
fprintf(stream, "Array<%d>(", arrayLength(obj));
for (i= 0; i < len; ++i) {
if (i) fprintf(stream, " ");
doprint(stream, arrayAt(obj, i), storing);
}
fprintf(stream, ")");
break;
}
case Expr: {
fprintf(stream, "Expr");
if (nil != (get(obj, Expr,name))) {
fprintf(stream, ".");
doprint(stream, get(obj, Expr,name), storing);
}
fprintf(stream, "=");
doprint(stream, car(get(obj, Expr,definition)), storing);
break;
}
case Form: {
fprintf(stream, "Form(");
doprint(stream, get(obj, Form,function), storing);
fprintf(stream, ", ");
doprint(stream, get(obj, Form,symbol), storing);
fprintf(stream, ")");
break;
}
case Fixed: {
if (isatty(1)) {
fprintf(stream, "[1m");
doprint(stream, get(obj, Fixed,function), storing);
fprintf(stream, "[m");
}
else {
fprintf(stream, "Fixed<");
doprint(stream, get(obj, Fixed,function), storing);
fprintf(stream, ">");
}
break;
}
case Subr: {
if (get(obj, Subr,name))
fprintf(stream, "%ls", get(obj, Subr,name));
else
fprintf(stream, "Subr<%p>", get(obj, Subr,imp));
break;
}
// case Variable: {
// if (!isGlobal(obj) && isatty(1)) fprintf(stream, "[4m");
// doprint(stream, get(obj, Variable,name), 0);
// if (!isGlobal(obj) && isatty(1)) fprintf(stream, "[m");
// #if !defined(NDEBUG)
// oop env= get(obj, Variable,env);
// if (nil != env) fprintf(stream, ";%ld+%ld", getLong(get(env, Env,level)), getLong(get(obj, Variable,index)));
// #endif
// break;
// }
// case Env: {
// oop level= get(obj, Env,level);
// oop offset= get(obj, Env,offset);
// fprintf(stream, "Env%s%s<%ld+%ld:", ((nil == get(obj, Env,parent)) ? "*" : ""), ((nil == get(obj, Env,stable)) ? "=" : ""),
// is(Long, level) ? getLong(level) : -1, is(Long, offset) ? getLong(offset) : -1);
// #if 0
// oop bnd= get(obj, Env,bindings);
// int idx= arrayLength(bnd);
// while (--idx >= 0) {
// doprint(stream, arrayAt(bnd, idx), storing);
// if (idx) fprintf(stream, " ");
// }
// #endif
// fprintf(stream, ">");
// break;
// }
// case Context: {
// fprintf(stream, "Context<");
// doprint(stream, get(obj, Context,env), storing);
// fprintf(stream, "=");
// doprint(stream, get(obj, Context,bindings), storing);
// fprintf(stream, ">");
// break;
// }
default: {
oop name= lookup(getVar(globals), intern(L"%type-names"));
if (is(Array, name)) {
name= arrayAt(name, getType(obj));
if (is(Symbol, name)) {
fprintf(stream, "[34m%ls[m", get(name, Symbol,bits));
break;
}
}
fprintf(stream, "<type=%i>", getType(obj));
break;
}
}
#if !defined(NDEBUG)
ptr2hdr(obj)->printing= 0;
#endif
}
static void fprint(FILE *stream, oop obj) { doprint(stream, obj, 0); fflush(stream); }
static void print(oop obj) { fprint(stdout, obj); }
static void fdump(FILE *stream, oop obj) { doprint(stream, obj, 1); fflush(stream); }
static void dump(oop obj) { fdump(stdout, obj); }
static void fdumpln(FILE *stream, oop obj)
{
fdump(stream, obj);
fprintf(stream, "\n");
fflush(stream);
}
static void dumpln(oop obj) { fdumpln(stdout, obj); }
static oop apply(oop fun, oop args, oop ctx);
static oop concat(oop head, oop tail)
{
if (!is(Pair, head)) return tail;
tail= concat(getTail(head), tail); GC_PROTECT(tail);
head= newPairFrom(getHead(head), tail, head); GC_UNPROTECT(tail);
return head;
}
static void setSource(oop obj, oop src)
{
if (!is(Pair, obj)) return;
if (nil == get(obj, Pair,source)) set(obj, Pair,source, src);
setSource(getHead(obj), src);
setSource(getTail(obj), src);
}
static oop getSource(oop exp)
{
if (is(Pair, exp)) {
oop src= get(exp, Pair,source);
if (nil != src) {
oop path= car(src);
oop line= cdr(src);
if (is(String, path) && is(Long, line))
return src;
}
}
return nil;
}
static int fprintSource(FILE *stream, oop src)
{
if (nil != src) {
return fprintf(stream, "%ls:%ld", get(car(src), String,bits), getLong(cdr(src)));
}
return 0;
}
static int printSource(oop exp)
{
return fprintSource(stdout, getSource(exp));
}
static oop exlist(oop obj, oop env);
static oop findFormFunction(oop env, oop var)
{ if (!is(Symbol, var)) return nil;
var= findVariable(env, var); if (nil == var) return nil;
var= getVar(var); if (!is(Form, var)) return nil;
return get(var, Form,function);
}
static oop findFormSymbol(oop env, oop var)
{ assert(is(Symbol, var));
var= findVariable(env, var); if (nil == var) return nil;
var= getVar(var); if (!is(Form, var)) return nil;
return get(var, Form,symbol);
}
static oop expand(oop expr, oop env)
{
if (opt_v > 1) { printf("EXPAND "); dumpln(expr); }
if (is(Pair, expr)) {
oop head= expand(getHead(expr), env); GC_PROTECT(head);
oop form= findFormFunction(env, head);
if (nil != form) {
head= apply(form, getTail(expr), env);
head= expand(head, env); GC_UNPROTECT(head);
if (opt_v > 1) { printf("EXPAND => "); dumpln(head); }
setSource(head, get(expr, Pair,source));
return head;
}
oop tail= getTail(expr); GC_PROTECT(tail);
if (s_quote != head) tail= exlist(tail, env);
if (s_set == head && is(Pair, car(tail)) && is(Symbol, caar(tail)) /*&& s_in != caar(tail)*/) {
static struct buffer buf= BUFFER_INITIALISER;
buffer_reset(&buf);
buffer_appendAll(&buf, L"set-");
buffer_appendAll(&buf, get(getHead(getHead(tail)), Symbol,bits));
head= intern(buffer_contents(&buf));
tail= concat(getTail(getHead(tail)), getTail(tail));
}
expr= newPairFrom(head, tail, expr); GC_UNPROTECT(tail); GC_UNPROTECT(head);
}
else if (is(Symbol, expr)) {
oop form= findFormSymbol(env, expr);
if (form) {
oop args= cons(expr, nil); GC_PROTECT(args);
args= apply(form, args, nil);
args= expand(args, env); GC_UNPROTECT(args);
setSource(args, expr);
if (opt_v > 1) { printf("EXPAND => "); dumpln(args); }
return args;
}
}
// else {
// oop fn= arrayAt(get(expanders, Variable,value), getType(expr));
// if (nil != fn) {
// oop args= newPair(expr, nil); GC_PROTECT(args);
// args= apply(fn, args, nil); GC_UNPROTECT(args);
// setSource(args, expr);
// return args;
// }
// }
if (opt_v > 1) { printf("EXPAND => "); dumpln(expr); }
return expr;
}
static oop exlist(oop list, oop env)
{
if (!is(Pair, list)) return expand(list, env);
oop head= expand(getHead(list), env); GC_PROTECT(head);
oop tail= exlist(getTail(list), env); GC_PROTECT(tail);
head= newPairFrom(head, tail, list); GC_UNPROTECT(tail); GC_UNPROTECT(head);
return head;
}
static int encodeIndent= 16;
static oop enlist(oop obj, oop env);
static oop encodeFrom(oop from, oop obj, oop env)
{
switch (getType(obj)) {
case Symbol: {
if (nil == findVariable(env, obj)) {
int flags= get(obj, Symbol,flags);
if (0 == (1 & flags)) {
set(obj, Symbol,flags, 1 | flags);
oop src= getSource(from);
if (nil != src) {
int i= fprintSource(stderr, getSource(from));
if (i > encodeIndent) encodeIndent= i;
while (i++ <= encodeIndent) putc(' ', stderr);
}
oprintf("warning: possibly undefined: %P\n", obj);
}
}
break;
}
case Pair: {
oop head= getHead(obj);
if (head == s_quote) {
}
else if (head == s_define) { GC_PROTECT(env);
env= cons(nil, env);
setHead(env, cons(cadr(obj), nil));
enlist(cddr(obj), env); GC_UNPROTECT(env);
}
else if (head == s_lambda) { GC_PROTECT(env);
oop bindings= cadr(obj);
while (isPair(bindings)) {
oop id= bindings;
while (isPair(id)) id= car(id);
env= cons(nil, env);
setHead(env, cons(id, nil));
bindings= getTail(bindings);
}
if (is(Symbol, bindings)) {
env= cons(nil, env);
setHead(env, cons(bindings, nil));
}
enlist(cddr(obj), env); GC_UNPROTECT(env);
}
else if (head == s_let) { GC_PROTECT(env);
oop bindings= cadr(obj);
while (isPair(bindings)) {
enlist(cdar(bindings), env);
bindings= getTail(bindings);
}
bindings= cadr(obj);
while (isPair(bindings)) {
oop id= bindings;
while (isPair(id)) id= car(id);
env= cons(nil, env);
setHead(env, cons(id, nil));
bindings= getTail(bindings);
}
enlist(cddr(obj), env); GC_UNPROTECT(env);
}
else {
enlist(obj, env);
if (is(Symbol, head)) {
oop val= lookup(getVar(globals), head);
if (is(Expr, val)) {
oop formal= car(get(val, Expr,definition));
oop actual= cdr(obj);
while (isPair(formal) && isPair(actual)) {
if (s_etc == car(formal)) {
formal= actual= nil;
}
else {
formal= cdr(formal);
actual= cdr(actual);
}
}
if (is(Symbol, formal))
formal= actual= nil;
if (nil != formal || nil != actual) {
oop src= getSource(obj);
if (nil != src) {
int i= fprintSource(stderr, getSource(from));
if (i > encodeIndent) encodeIndent= i;
while (i++ <= encodeIndent) putc(' ', stderr);
}
oprintf("warning: argument mismatch: %P -> %P\n", obj, car(get(val, Expr,definition)));
}
// CHECK ARG LIST HERE
}
}
}
break;
}
}
return obj;
}
static oop encode(oop obj, oop env)
{
return encodeFrom(nil, obj, env);
}
static oop enlist(oop obj, oop env)
{
while (isPair(obj)) {
encodeFrom(obj, getHead(obj), env);
obj= getTail(obj);
}
return obj;
}
// static void define_bindings(oop bindings, oop innerEnv)
// { GC_PROTECT(bindings);
// while (is(Pair, bindings))
// {
// oop var= getHead(bindings); GC_PROTECT(var);
// if (!is(Symbol, var)) var= car(var);
// var= define(innerEnv, var, nil); GC_UNPROTECT(var);
// bindings= getTail(bindings);
// } GC_UNPROTECT(bindings);
// }
// static oop encode_bindings(oop expr, oop bindings, oop outerEnv, oop innerEnv)
// {
// if (is(Pair, bindings))
// { GC_PROTECT(bindings);
// oop binding= getHead(bindings); GC_PROTECT(binding);
// if (is(Symbol, binding)) binding= newPairFrom(binding, nil, expr);
// oop var= car(binding); GC_PROTECT(var);
// oop val= cdr(binding); GC_PROTECT(val);
// var= findLocalVariable(innerEnv, var); assert(nil != var);
// val= enlist(val, outerEnv);
// binding= newPairFrom(var, val, expr); GC_UNPROTECT(val); GC_UNPROTECT(var);
// oop rest= encode_bindings(expr, getTail(bindings), outerEnv, innerEnv); GC_PROTECT(rest);
// bindings= newPairFrom(binding, rest, expr); GC_UNPROTECT(rest); GC_UNPROTECT(binding); GC_UNPROTECT(bindings);
// }
// return bindings;
// }
// static oop encode_let(oop expr, oop tail, oop env)
// {
// oop args= car(tail); GC_PROTECT(tail); GC_PROTECT(env);
// oop env2= newEnv(env, 0, getLong(get(env, Env,offset))); GC_PROTECT(env2);
// define_bindings(args, env2);
// set(env, Env,offset, newLong(getLong(get(env2, Env,offset))));
// oop bindings= encode_bindings(expr, args, env, env2); GC_PROTECT(bindings);
// oop body= cdr(tail); GC_PROTECT(body);
// body= enlist(body, env2);
// tail= newPairFrom(bindings, body, expr); GC_UNPROTECT(body); GC_UNPROTECT(bindings);
// tail= newPairFrom(env2, tail, expr); GC_UNPROTECT(env2); GC_UNPROTECT(env); GC_UNPROTECT(tail);
// return tail;
// }
// static oop encode(oop expr, oop env)
// {
// if (opt_O < 2) arrayAtPut(traceStack, traceDepth++, expr);
// if (opt_v > 1) { printf("ENCODE "); dumpln(expr); }
// if (is(Pair, expr)) {
// oop head= encode(getHead(expr), env); GC_PROTECT(head);
// oop tail= getTail(expr); GC_PROTECT(tail);
// if (f_let == head) { // (let ENV (bindings...) . body)
// tail= encode_let(expr, tail, env);
// }
// else if (f_lambda == head) { // (lambda ENV params . body)
// oop args= car(tail);
// env= newEnv(env, 1, 0); GC_PROTECT(env);
// while (is(Pair, args)) {
// if (!is(Symbol, getHead(args))) {
// fprintf(stderr, "\nerror: non-symbol parameter name: ");
// fdumpln(stderr, getHead(args));
// fatal(0);
// }
// define(env, getHead(args), nil);
// args= getTail(args);
// }
// if (nil != args) {
// if (!is(Symbol, args)) {
// fprintf(stderr, "\nerror: non-symbol parameter name: ");
// fdumpln(stderr, args);
// fatal(0);
// }
// define(env, args, nil);
// }
// tail= enlist(tail, env);
// tail= newPairFrom(env, tail, expr); GC_UNPROTECT(env);
// }
// else if (f_define == head) {
// oop var= define(get(globals, Variable,value), car(tail), nil);
// tail= enlist(cdr(tail), env);
// tail= newPairFrom(var, tail, expr);
// }
// else if (f_set == head) {
// oop var= findVariable(env, car(tail));
// if (nil == var) fatal("set: undefined variable: %ls", get(car(tail), Symbol,bits));
// tail= enlist(cdr(tail), env);
// tail= newPairFrom(var, tail, expr);
// }
// else if (f_quote != head)
// tail= enlist(tail, env);
// expr= newPairFrom(head, tail, expr); GC_UNPROTECT(tail); GC_UNPROTECT(head);
// }
// else if (is(Symbol, expr)) {
// oop val= findVariable(env, expr);
// if (nil == val) fatal("undefined variable: %ls", get(expr, Symbol,bits));
// expr= val;
// if (isGlobal(expr)) {
// val= get(expr, Variable,value);
// if (is(Form, val) || is(Fixed, val))
// expr= val;
// }
// else {
// oop venv= get(val, Variable,env);
// if (getLong(get(venv, Env,level)) != getLong(get(env, Env,level)))
// set(venv, Env,stable, s_t);
// }
// }
// else {
// oop fn= arrayAt(get(encoders, Variable,value), getType(expr));
// if (nil != fn) {
// oop args= newPair(env, nil); GC_PROTECT(args);
// args= newPair(expr, args);
// expr= apply(fn, args, nil); GC_UNPROTECT(args);
// }
// }
// if (opt_v > 1) { printf("ENCODE => "); dumpln(expr); }
// --traceDepth;
// return expr;
// }
// static oop enlist(oop list, oop env)
// {
// if (!is(Pair, list)) return encode(list, env);
// oop head= encode(getHead(list), env); GC_PROTECT(head);
// oop tail= enlist(getTail(list), env); GC_PROTECT(tail);
// head= newPairFrom(head, tail, list); GC_UNPROTECT(tail); GC_UNPROTECT(head);
// return head;
// }
static void vfoprintf(FILE *out, char *fmt, va_list ap)
{
int c;
while ((c= *fmt++)) {
if ('%' == c) {
char fbuf[32];
int index= 0;
fbuf[index++]= '%';
while (index < sizeof(fbuf) - 1) {
c= *fmt++;
fbuf[index++]= c;
if (strchr("PdiouxXDOUeEfFgGaACcSspn%", c)) break;
}
fbuf[index]= 0;
switch (c) { // cannot call vfprintf(out, fbuf, ap) because ap can be passed by copy
case 'e': case 'E': case 'f': case 'F':
case 'g': case 'G': case 'a': case 'A': { double arg= va_arg(ap, double); fprintf(out, fbuf, arg); break; }
case 'd': case 'i': case 'o': case 'u':
case 'x': case 'X': case 'c': { int arg= va_arg(ap, int); fprintf(out, fbuf, arg); break; }
case 'D': case 'O': case 'U': { long arg= va_arg(ap, long int); fprintf(out, fbuf, arg); break; }
case 'C': { wint_t arg= va_arg(ap, wint_t); fprintf(out, fbuf, arg); break; }
case 's': case 'S': case 'p': { void *arg= va_arg(ap, void *); fprintf(out, fbuf, arg); break; }
case 'P': { oop arg= va_arg(ap, oop); fdump (out, arg); break; }
case '%': { putc('%', out); break; }
default:
fprintf(stderr, "\nimplementation error: cannot convert format '%c'\n", c);
exit(1);
break;
}
}
else
fputc(c, out);
}
}
static void oprintf(char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfoprintf(stderr, fmt, ap);
va_end(ap);
}
static void fatal(char *reason, ...)
{
if (reason) {
va_list ap;
va_start(ap, reason);
fprintf(stderr, "\nerror: ");
vfoprintf(stderr, reason, ap);
fprintf(stderr, "\n");
va_end(ap);
}
oop tracer= getVar(backtrace);
if (nil != tracer) {
oop args= newLong(traceDepth); GC_PROTECT(args);
args= cons(args, nil);
args= cons(traceStack, args);
apply(tracer, args, nil); GC_UNPROTECT(args);
}
else {
if (traceDepth) {
int i= traceDepth;
int j= 12;
while (i-- > 0) {
//printf("%3d: ", i);
oop exp= arrayAt(traceStack, i);
printf("[32m[?7l");
int l= printSource(exp);
if (l >= j) j= l;
if (!l) while (l < 3) l++, putchar('.');
while (l++ < j) putchar(' ');
printf("[0m ");
dumpln(arrayAt(traceStack, i));
printf("[?7h");
}
}
else {
printf("no backtrace\n");
}
}
exit(1);
}
static oop evlist(oop obj, oop env);
static oop eval(oop obj, oop env)
{
if (opt_v > 2) { printf("EVAL "); dumpln(obj); }
switch (getType(obj)) {
case Undefined:
case Long:
case Double:
case String:
case Form:
case Subr:
case Fixed: {
return obj;
}
case Pair: {
if (opt_O < 2) arrayAtPut(traceStack, traceDepth++, obj);
oop head= eval(getHead(obj), env); GC_PROTECT(head);
if (is(Fixed, head))
head= apply(get(head, Fixed,function), getTail(obj), env);
else {
oop args= evlist(getTail(obj), env); GC_PROTECT(args);
if (opt_g) arrayAtPut(traceStack, traceDepth++, cons(head, args));
head= apply(head, args, env); GC_UNPROTECT(args);
if (opt_g) --traceDepth;
} GC_UNPROTECT(head);
--traceDepth;
return head;
}
case Symbol: {
oop ass= findVariable(env, obj);
if (nil == ass) fatal("eval: undefined variable: %P", obj);
return getTail(ass);
}
// case Variable: {
// if (isGlobal(obj)) return get(obj, Variable,value);
// int delta= getLong(get(get(ctx, Context,env), Env,level)) - getLong(get(get(obj, Variable,env), Env,level));
// oop cx= ctx;
// while (delta--) cx= get(cx, Context,home);
// return arrayAt(get(cx, Context,bindings), getLong(get(obj, Variable,index)));
// }
default: {
fatal("cannot eval (%i): %P", getType(obj), obj);
// if (opt_g) arrayAtPut(traceStack, traceDepth++, obj);
// oop ev= arrayAt(get(evaluators, Variable,value), getType(obj));
// if (nil != ev) {
// oop args= newPair(obj, nil); GC_PROTECT(args);
// obj= apply(ev, args, ctx); GC_UNPROTECT(args);
// }
// if (opt_g) --traceDepth;
// return obj;
}
}
return nil;
}
static oop evlist(oop obj, oop env)
{
if (!is(Pair, obj)) return obj;
oop head= eval(getHead(obj), env); GC_PROTECT(head);
oop tail= evlist(getTail(obj), env); GC_PROTECT(tail);
//head= newPairFrom(head, tail, obj); GC_UNPROTECT(tail); GC_UNPROTECT(head);
head= cons(head, tail); GC_UNPROTECT(tail); GC_UNPROTECT(head);
return head;
}
static oop ffcall(oop subr, oop arguments);
static oop apply(oop fun, oop arguments, oop env)
{
if (opt_v > 2) oprintf("APPLY %P TO %P\n", fun, arguments);
int funType= getType(fun);
switch (funType) {
case Expr: {
if (opt_p) arrayAtPut(traceStack, traceDepth++, fun);
oop defn = get(fun, Expr,definition); GC_PROTECT(defn);
oop formals = car(defn);
oop actuals = arguments;
oop caller = env; GC_PROTECT(caller);
oop callee = get(fun, Expr,environment); GC_PROTECT(callee);
oop tmp = nil; GC_PROTECT(tmp);
while (is(Pair, formals)) {
if (!is(Pair, actuals)) fatal("too few arguments applying %P to %P", fun, arguments);
tmp= cons(getHead(formals), getHead(actuals));
callee= cons(tmp, callee);
formals= getTail(formals);
actuals= getTail(actuals);
}
if (is(Symbol, formals)) {
tmp= cons(formals, actuals);
callee= cons(tmp, callee);
actuals= nil;
}
if (nil != actuals) fatal("too many arguments applying %P to %P", fun, arguments);
#if LOCALS_ARE_NAMESPACE
tmp= cons(s_locals, nil);
callee= cons(tmp, callee);
setTail(tmp, callee);
#endif
oop ans= nil;
oop body= cdr(defn);
if (opt_g) {
arrayAtPut(traceStack, traceDepth++, body);
if (traceDepth > 2000) fatal("infinite recursion suspected");
}
while (is(Pair, body)) {
// if (opt_g) arrayAtPut(traceStack, traceDepth - 1, getHead(body));
// set(ctx, Context,pc, body);
ans= eval(getHead(body), callee);
body= getTail(body);
}
if (opt_g || opt_p) --traceDepth;
GC_UNPROTECT(tmp);
GC_UNPROTECT(callee);
GC_UNPROTECT(caller);
GC_UNPROTECT(defn);
// if (nil != get(env, Env,stable)) set(ctx, Context,callee, nil);
return ans;
}
case Fixed: {
return apply(get(fun, Fixed,function), arguments, env);
}
case Subr: {
if (opt_p) arrayAtPut(traceStack, traceDepth++, fun);
oop ans= get(fun, Subr,sig) ? ffcall(fun, arguments) : get(fun, Subr,imp)(arguments, env);
if (opt_p) --traceDepth;
return ans;
}
default: {
oop args= arguments;
oop ap= arrayAt(getVar(applicators), funType);
if (nil != ap) { GC_PROTECT(args);
if (opt_g) arrayAtPut(traceStack, traceDepth++, fun);
args= cons(fun, args);
args= apply(ap, args, env); GC_UNPROTECT(args);
if (opt_g) --traceDepth;
return args;
}
fatal("error: cannot apply: %P", fun);
}
}
return nil;
}
static ffi_type ffi_type_long;
// #define ffcast(NAME, OTYPE) \
// static void ff##NAME(oop arg, void **argp, arg_t *buf) \
// { \
// switch (getType(arg)) { \
// case OTYPE: buf->arg_##NAME= get##OTYPE(arg); *argp= &buf->arg_##NAME; break; \
// default: fprintf(stderr, "\nnon-"#OTYPE" argument in foreign call: "); fdumpln(stderr, arg); fatal(0); break; \
// } \
// }
// ffcast(int, Long)
// ffcast(int32, Long)
// ffcast(int64, Long)
// ffcast(long, Long)
// ffcast(float, Double)
// ffcast(double, Double)
// #undef ffcast
// static void ffpointer(oop arg, void **argp, arg_t *buf)
// {
// void *ptr= 0;
// switch (getType(arg)) {
// case Undefined: ptr= 0; break;
// case Data: ptr= (void *)arg; break;
// case Long: ptr= (void *)getLong(arg); break;
// case Double: ptr= (void *)arg; break;
// case String: ptr= get(arg, String,bits); break;
// case Symbol: ptr= get(arg, Symbol,bits); break;
// case Expr: ptr= (void *)arg; break;
// case Subr: ptr= get(arg, Subr,imp); break;
// case Variable: ptr= &get(arg, Variable,value); break;
// default:
// if (GC_atomic(arg))
// ptr= (void *)arg;
// else {
// fprintf(stderr, "\ninvalid pointer argument: ");
// fdumpln(stderr, arg);
// fatal(0);
// }
// break;
// }
// buf->arg_pointer= ptr;
// *argp= &buf->arg_pointer;
// }
// static void ffstring(oop arg, void **argp, arg_t *buf)
// {
// if (!is(String, arg)) {
// fprintf(stderr, "\nnon-String argument in foreign call: ");
// fdumpln(stderr, arg);
// fatal(0);
// }
// buf->arg_string= wcs2mbs(get(arg, String,bits));
// *argp= &buf->arg_string;
// }
// static ffi_type *ffdefault(oop arg, void **argp, arg_t *buf)
// {
// switch (getType(arg))
// {
// case Undefined: buf->arg_pointer= 0; *argp= &buf->arg_pointer; return &ffi_type_pointer;
// case Long: buf->arg_long= getLong(arg); *argp= &buf->arg_long; return &ffi_type_long;
// case Double: buf->arg_double= getDouble(arg); *argp= &buf->arg_double; return &ffi_type_double;
// case String: buf->arg_string= wcs2mbs(get(arg, String,bits)); *argp= &buf->arg_string; return &ffi_type_pointer;
// case Subr: buf->arg_pointer= get(arg, Subr,imp); *argp= &buf->arg_pointer; return &ffi_type_pointer;
// }
// fprintf(stderr, "\ncannot pass object through '...': ");
// fdumpln(stderr, arg);
// fatal(0);
// return 0;
// }
static oop ffcall(oop subr, oop arguments)
{
fatal("ffcall");
// proto_t *sig= get(subr, Subr,sig);
// imp_t imp= get(subr, Subr,imp);
// oop argp= arguments;
// int arg_count= 0;
// void *args[32];
// arg_t bufs[32];
// ffi_cif cif;
// ffi_type ret_type= ffi_type_pointer;
// ffi_arg result;
// ffi_type *arg_types[32];
// while ((arg_count < sig->arg_count) && (nil != argp)) {
// sig->arg_casts[arg_count](car(argp), &args[arg_count], &bufs[arg_count]);
// arg_types[arg_count]= sig->arg_types[arg_count];
// ++arg_count;
// argp= getTail(argp);
// }
// if (arg_count != sig->arg_count) fatal("too few arguments (%i < %i) in call to %S", arg_count, sig->arg_count, get(subr, Subr,name));
// if (sig->arg_rest) {
// while ((nil != argp) && (arg_count < 32)) {
// arg_types[arg_count]= ffdefault(car(argp), &args[arg_count], &bufs[arg_count]);
// ++arg_count;
// argp= getTail(argp);
// }
// }
// if (nil != argp) fatal("too many arguments in call to %S", get(subr, Subr,name));
// if (FFI_OK != ffi_prep_cif(&cif, FFI_DEFAULT_ABI, arg_count, &ret_type, arg_types)) fatal("FFI call setup failed");
// ffi_call(&cif, FFI_FN(imp), &result, args);
// return newLong((long)result);
return nil;
}
static int length(oop list)
{
if (!is(Pair, list)) return 0;
return 1 + length(getTail(list));
}
static void arity(oop args, char *name)
{
fatal("wrong number of arguments (%i) in: %s\n", length(args), name);
}
static void arity1(oop args, char *name)
{
if (!is(Pair, args) || is(Pair, getTail(args))) arity(args, name);
}
static void arity2(oop args, char *name)
{
if (!is(Pair, args) || !is(Pair, getTail(args)) || is(Pair, getTail(getTail(args)))) arity(args, name);
}
static void arity3(oop args, char *name)
{
if (!is(Pair, args) || !is(Pair, getTail(args)) || !is(Pair, getTail(getTail(args))) || is(Pair, getTail(getTail(getTail(args))))) arity(args, name);
}
#define subr(NAME) oop subr_##NAME(oop args, oop env)
static subr(if)
{
if (nil != eval(car(args), env))
return eval(cadr(args), env);
oop ans= nil;
args= cddr(args);
while (is(Pair, args)) {
ans= eval(getHead(args), env);
args= cdr(args);
}
return ans;
}
static subr(and)
{
oop ans= s_t;
for (; is(Pair, args); args= getTail(args))
if (nil == (ans= eval(getHead(args), env)))
break;
return ans;
}
static subr(or)
{
oop ans= nil;
for (; is(Pair, args); args= getTail(args))
if (nil != (ans= eval(getHead(args), env)))
break;
return ans;
}
static subr(set)
{
oop sym= car(args); if (!is(Symbol, sym)) fatal("non-symbol in set: %P", sym);
oop var= findVariable(env, sym); if (nil == var) fatal("set: undefined variable: %P", sym);
oop val= eval(cadr(args), env); if (is(Expr, val) && (nil == get(val, Expr,name))) set(val, Expr,name, sym);
setTail(var, val);
// if (isGlobal(var)) return set(var, Variable,value, val);
// int delta= getLong(get(get(ctx, Context,env), Env,level)) - getLong(get(get(var, Variable,env), Env,level));
// oop cx= ctx;
// while (delta--) cx= get(cx, Context,home);
// return arrayAtPut(get(cx, Context,bindings), getLong(get(var, Variable,index)), val);
return val;
}
static subr(let)
{
oop bound= cons(nil, nil); GC_PROTECT(bound);
oop ptr= bound;
oop bindings= car(args);
oop tmp= nil; GC_PROTECT(tmp);
while (isPair(bindings)) {
oop binding= getHead(bindings);
oop name= 0;
if (isPair(binding)) {
name= car(binding);
tmp= eval(cadr(binding), env);
}
else {
if (!is(Symbol, binding)) fatal("let: non-symbol identifier: %P", binding);
name= binding;
tmp= nil;
}
ptr= setTail(ptr, cons(nil, nil));
setHead(ptr, cons(name, tmp));
bindings= getTail(bindings);
}
setTail(ptr, env);
#if LOCALS_ARE_NAMESPACE
setHead(bound, cons(s_locals, bound));
#else
bound= getTail(bound);
#endif
oop body= cdr(args);
tmp= nil; GC_UNPROTECT(tmp);
while (is(Pair, body)) {
oop exp= getHead(body);
tmp= eval(exp, bound);
body= getTail(body);
} GC_UNPROTECT(bound);
return tmp;
}
static subr(while)
{
oop tst= car(args);
while (nil != eval(tst, env)) {
oop body= cdr(args);
while (is(Pair, body)) {
eval(getHead(body), env);
body= getTail(body);
}
}
return nil;
}
static subr(quote)
{
return car(args);
}
static subr(lambda)
{
return newExpr(args, env);
}
static subr(define)
{
oop sym= car(args);
oop val= eval(cadr(args), env); GC_PROTECT(val);
oop var= findNamespaceVariable(env, sym);
if (nil == var)
var= define(env, sym, val);
else
setTail(var, val);
if (is(Form, val)) val= get(val, Form,function);
if (is(Expr, val) && (nil == get(val, Expr,name)))
set(val, Expr,name, sym); GC_UNPROTECT(val);
return val;
}
static subr(definedP)
{
oop symbol= car(args);
oop theenv= cadr(args);
if (nil == theenv) theenv= getVar(globals);
return findVariable(theenv, symbol);
}
// #define _do_unary() \
// _do(com, ~)
// #define _do(NAME, OP) \
// static subr(NAME) \
// { \
// arity1(args, #OP); \
// oop rhs= getHead(args); \
// if (isLong(rhs)) return newLong(OP getLong(rhs)); \
// fprintf(stderr, "%s: non-integer argument: ", #OP); \
// fdumpln(stderr, rhs); \
// fatal(0); \
// return nil; \
// }
// _do_unary()
// #undef _do
#define _do_ibinary() \
_do(bitand, &) _do(bitor, |) _do(bitxor, ^) _do(shl, <<) _do(shr, >>)
#define _do(NAME, OP) \
static subr(NAME) \
{ \
arity2(args, #OP); \
oop lhs= getHead(args); \
oop rhs= getHead(getTail(args)); \
if (isLong(lhs) && isLong(rhs)) \
return newLong(getLong(lhs) OP getLong(rhs)); \
fprintf(stderr, "%s: non-integer argument: ", #OP); \
if (!isLong(lhs)) fdumpln(stderr, lhs); \
else fdumpln(stderr, rhs); \
fatal(0); \
return nil; \
}
_do_ibinary()
#undef _do
#define _do_binary() \
_do(add, +) _do(mul, *) _do(div, /)
#define _do(NAME, OP) \
static subr(NAME) \
{ \
arity2(args, #OP); \
oop lhs= getHead(args); \
oop rhs= getHead(getTail(args)); \
if (isLong(lhs)) { \
if (isLong(rhs)) return newLong(getLong(lhs) OP getLong(rhs)); \
if (isDouble(rhs)) return newDouble((double)getLong(lhs) OP getDouble(rhs)); \
} \
else if (isDouble(lhs)) { \
if (isDouble(rhs)) return newDouble(getDouble(lhs) OP getDouble(rhs)); \
if (isLong(rhs)) return newDouble(getDouble(lhs) OP (double)getLong(rhs)); \
} \
fatal("%s: non-numeric argument: %P", #OP, (isNumeric(lhs) ? rhs : lhs)); \
return nil; \
}
_do_binary()
#undef _do
static subr(sub)
{
if (!is(Pair, args)) arity(args, "-");
oop lhs= getHead(args); args= getTail(args);
if (!is(Pair, args)) {
if (isLong (lhs)) return newLong (- getLong (lhs));
if (isDouble(lhs)) return newDouble(- getDouble(lhs));
fprintf(stderr, "-: non-numeric argument: ");
fdumpln(stderr, lhs);
fatal(0);
}
oop rhs= getHead(args); args= getTail(args);
if (is(Pair, args)) arity(args, "-");
if (isLong(lhs)) {
if (isLong(rhs)) return newLong(getLong(lhs) - getLong(rhs));
if (isDouble(rhs)) return newDouble((double)getLong(lhs) - getDouble(rhs));
}
if (isDouble(lhs)) {
if (isDouble(rhs)) return newDouble(getDouble(lhs) - getDouble(rhs));
if (isLong(rhs)) return newDouble(getDouble(lhs) - (double)getLong(rhs));
lhs= rhs; // for error msg
}
fprintf(stderr, "-: non-numeric argument: ");
fdumpln(stderr, lhs);
fatal(0);
return nil;
}
static subr(mod)
{
if (!is(Pair, args)) arity(args, "%");
oop lhs= getHead(args); args= getTail(args);
if (!is(Pair, args)) arity(args, "%");
oop rhs= getHead(args); args= getTail(args);
if (is(Pair, args)) arity(args, "%");
if (isLong(lhs)) {
if (isLong(rhs)) return newLong(getLong(lhs) % getLong(rhs));
if (isDouble(rhs)) return newDouble(fmod((double)getLong(lhs), getDouble(rhs)));
}
else if (isDouble(lhs)) {
if (isDouble(rhs)) return newDouble(fmod(getDouble(lhs), getDouble(rhs)));
if (isLong(rhs)) return newDouble(fmod(getDouble(lhs), (double)getLong(rhs)));
}
fprintf(stderr, "%%: non-numeric argument: ");
if (!isNumeric(lhs)) fdumpln(stderr, lhs);
else fdumpln(stderr, rhs);
fatal(0);
return nil;
}
#define _do_relation() \
_do(lt, <) _do(le, <=) _do(ge, >=) _do(gt, >)
#define _do(NAME, OP) \
static subr(NAME) \
{ \
arity2(args, #OP); \
oop lhs= getHead(args); \
oop rhs= getHead(getTail(args)); \
if (isLong(lhs)) { \
if (isLong(rhs)) return newBool(getLong(lhs) OP getLong(rhs)); \
if (isDouble(rhs)) return newBool((double)getLong(lhs) OP getDouble(rhs)); \
lhs= rhs; \
} \
else if (isDouble(lhs)) { \
if (isDouble(rhs)) return newBool(getDouble(lhs) OP getDouble(rhs)); \
if (isLong(rhs)) return newBool(getDouble(lhs) OP (double)getLong(rhs)); \
lhs= rhs; \
} \
fatal("%s: non-numeric argument: %P", #OP, lhs); \
return nil; \
}
_do_relation()
#undef _do
static int equal(oop lhs, oop rhs)
{
int ans= 0;
switch (getType(lhs)) {
case Long:
switch (getType(rhs)) {
case Long: ans= ( getLong (lhs) == getLong (rhs)); break;
case Double: ans= ((double)getLong (lhs) == getDouble(rhs)); break;
}
break;
case Double:
switch (getType(rhs)) {
case Long: ans= ( getDouble(lhs) == (double)getLong (rhs)); break;
case Double: ans= ( getDouble(lhs) == getDouble(rhs)); break;
}
break;
case String: ans= (is(String, rhs) && !wcscmp(get(lhs, String,bits), get(rhs, String,bits))); break;
default: ans= (lhs == rhs); break;
}
return ans;
}
static subr(eq)
{
arity2(args, "=");
oop lhs= getHead(args);
oop rhs= getHead(getTail(args));
return newBool(equal(lhs, rhs));
}
static subr(ne)
{
arity2(args, "!=");
oop lhs= getHead(args);
oop rhs= getHead(getTail(args));
return newBool(!equal(lhs, rhs));
}
// #if !defined(WIN32) && (!LIB_GC)
// static void profilingDisable(int);
// #endif
static subr(exit)
{
oop n= car(args);
// #if !defined(WIN32) && (!LIB_GC)
// if (opt_p) profilingDisable(1);
// #endif
exit(isLong(n) ? getLong(n) : 0);
}
static subr(abort)
{
fatal("aborting");
return nil;
}
static subr(open)
{
oop arg= car(args);
if (!is(String, arg)) { fprintf(stderr, "open: non-string argument: "); fdumpln(stderr, arg); fatal(0); }
char *name= strdup(wcs2mbs(get(arg, String,bits)));
char *mode= "r";
long wide= 1;
if (is(String, cadr(args))) mode= wcs2mbs(get(cadr(args), String,bits));
if (is(Long, caddr(args))) wide= getLong(caddr(args));
FILE *stream= (FILE *)fopen(name, mode);
free(name);
if (stream) fwide(stream, wide);
return stream ? newLong((long)stream) : nil;
}
static subr(close)
{
oop arg= car(args);
if (!isLong(arg)) { fprintf(stderr, "close: non-integer argument: "); fdumpln(stderr, arg); fatal(0); }
fclose((FILE *)getLong(arg));
return arg;
}
// static subr(getb)
// {
// oop arg= car(args);
// if (nil == arg) arg= get(input, Variable,value);
// if (!isLong(arg)) { fprintf(stderr, "getb: non-integer argument: "); fdumpln(stderr, arg); fatal(0); }
// FILE *stream= (FILE *)getLong(arg);
// int c= getc(stream);
// return (EOF == c) ? nil : newLong(c);
// }
static subr(getc)
{
oop arg= car(args);
if (nil == arg) arg= getVar(input);
if (!isLong(arg)) { fprintf(stderr, "getc: non-integer argument: "); fdumpln(stderr, arg); fatal(0); }
FILE *stream= (FILE *)getLong(arg);
int c= getwc(stream);
return (WEOF == c) ? nil : newLong(c);
}
// static subr(putb)
// {
// oop chr= car(args);
// oop arg= cadr(args);
// if (nil == arg) arg= get(output, Variable,value);
// if (!isLong(chr)) { fprintf(stderr, "putb: non-integer character: "); fdumpln(stderr, chr); fatal(0); }
// if (!isLong(arg)) { fprintf(stderr, "putb: non-integer argument: "); fdumpln(stderr, arg); fatal(0); }
// FILE *stream= (FILE *)getLong(arg);
// int c= putc(getLong(chr), stream);
// return (EOF == c) ? nil : chr;
// }
static subr(putc)
{
oop chr= car(args);
oop arg= cadr(args);
if (nil == arg) arg= getVar(output);
if (!isLong(chr)) { fprintf(stderr, "putc: non-integer character: "); fdumpln(stderr, chr); fatal(0); }
if (!isLong(arg)) { fprintf(stderr, "putc: non-integer argument: "); fdumpln(stderr, arg); fatal(0); }
FILE *stream= (FILE *)getLong(arg);
int c= putwc(getLong(chr), stream);
return (WEOF == c) ? nil : chr;
}
static subr(read)
{
FILE *stream= stdin;
oop head= nil;
if (nil == args) {
beginSource(L"<stdin>");
oop obj= readExpr(stdin);
endSource();
if (obj == DONE) obj= nil;
return obj;
}
oop arg= car(args);
if (is(String, arg)) {
wchar_t *path= get(arg, String,bits);
stream= fopen(wcs2mbs(path), "r");
if (!stream) return nil;
fwide(stream, 1);
beginSource(path);
head= newPairFrom(nil, nil, currentSource); GC_PROTECT(head);
oop tail= head;
oop obj= nil; GC_PROTECT(obj);
for (;;) {
obj= readExpr(stream);
if (obj == DONE) break;
tail= setTail(tail, newPairFrom(obj, nil, currentSource));
if (stdin == stream) break;
}
head= getTail(head); GC_UNPROTECT(obj);
fclose(stream); GC_UNPROTECT(head);
endSource();
}
else if (isLong(arg)) {
stream= (FILE *)getLong(arg);
if (stream) head= readExpr(stream);
if (head == DONE) head= nil;
}
else {
fprintf(stderr, "read: non-String/Long argument: ");
fdumpln(stderr, arg);
fatal(0);
}
return head;
}
static subr(expand)
{
oop x= car(args); args= cdr(args); GC_PROTECT(x);
oop e= car(args);
if (nil == e) e= env;
x= expand(x, e); GC_UNPROTECT(x);
return x;
}
// static subr(encode)
// {
// oop x= car(args); args= cdr(args); GC_PROTECT(x);
// oop e= car(args);
// if (nil == e) e= get(ctx, Context,env);
// x= encode(x, e); GC_UNPROTECT(x);
// return x;
// }
static subr(eval)
{
oop x= car(args); args= cdr(args); GC_PROTECT(x);
oop e= car(args);
if (nil == e) e= getVar(globals); GC_PROTECT(e);
x= expand(x, e);
if (opt_g) encode(x, e);
x= eval (x, e); GC_UNPROTECT(e); GC_UNPROTECT(x);
return x;
}
static subr(apply)
{
if (!is(Pair, args)) fatal("too few arguments in: apply");
oop f= car(args);
oop a= args; assert(is(Pair, a));
oop b= getTail(a);
oop c= cdr(b);
while (is(Pair, c)) a= b, c= cdr(b= c); assert(is(Pair, a));
setTail(a, car(b));
return apply(f, cdr(args), env);
}
static subr(current_environment)
{
return env;
}
static subr(type_of)
{
arity1(args, "type-of");
return newLong(getType(getHead(args)));
}
// static subr(warn)
// {
// while (is(Pair, args)) {
// doprint(stderr, getHead(args), 0);
// args= getTail(args);
// }
// return nil;
// }
static subr(print)
{
while (is(Pair, args)) {
print(getHead(args));
args= getTail(args);
}
return nil;
}
static subr(dump)
{
while (is(Pair, args)) {
dump(getHead(args));
args= getTail(args);
}
return nil;
}
static subr(format)
{
arity2(args, "format");
oop ofmt= car(args); if (!is(String, ofmt)) fatal("format is not a string");
oop oarg= cadr(args);
wchar_t *fmt= get(ofmt, String,bits);
int farg= 0;
union { long l; void *p; double d; } arg;
switch (getType(oarg)) {
case Undefined: break;
case Long: arg.l= getLong(oarg); break;
case Double: arg.d= getDouble(oarg); ++farg; break;
case String: arg.p= get(oarg, String,bits); break;
case Symbol: arg.p= get(oarg, Symbol,bits); break;
default: arg.p= oarg; break;
}
size_t size= 100;
wchar_t *p, *np;
oop ans= nil;
if (!(p= malloc(sizeof(wchar_t) * size))) return nil;
for (;;) {
int n= farg ? swnprintf(p, size, fmt, arg.d) : swnprintf(p, size, fmt, arg);
if (0 <= n && n < size) {
ans= newString(p);
free(p);
break;
}
if (n < 0 && errno == EILSEQ) return nil;
if (n >= 0) size= n + 1;
else size *= 2;
if (!(np= realloc(p, sizeof(wchar_t) * size))) {
free(p);
break;
}
p= np;
}
return ans;
}
static subr(form)
{
return newForm(car(args), cadr(args));
}
// static subr(fixedP)
// {
// arity1(args, "fixed?");
// return newBool(is(Fixed, getHead(args)));
// }
static subr(cons)
{
oop lhs= car(args);
oop rhs= cadr(args);
return cons(lhs, rhs); // (is(Pair, rhs) ? newPairFrom(lhs, rhs, rhs) : newPair(lhs, rhs));
}
static subr(pairP)
{
arity1(args, "pair?");
return newBool(is(Pair, getHead(args)));
}
static subr(car)
{
arity1(args, "car");
return car(getHead(args));
}
static subr(set_car)
{
arity2(args, "set-car");
oop arg= getHead(args); if (!is(Pair, arg)) return nil;
return setHead(arg, getHead(getTail(args)));
}
static subr(cdr)
{
arity1(args, "cdr");
return cdr(getHead(args));
}
static subr(set_cdr)
{
arity2(args, "set-cdr");
oop arg= getHead(args); if (!is(Pair, arg)) return nil;
return setTail(arg, getHead(getTail(args)));
}
// static subr(formP)
// {
// arity1(args, "form?");
// return newBool(is(Form, getHead(args)));
// }
static subr(symbolP)
{
arity1(args, "symbol?");
return newBool(is(Symbol, getHead(args)));
}
static subr(stringP)
{
arity1(args, "string?");
return newBool(is(String, getHead(args)));
}
static subr(string)
{
oop arg= car(args);
int num= isLong(arg) ? getLong(arg) : 0;
return _newString(num);
}
static subr(string_length)
{
arity1(args, "string-length");
oop arg= getHead(args);
int len= 0;
switch (getType(arg)) {
case String: len= stringLength(arg); break;
case Symbol: len= symbolLength(arg); break;
default: fatal("string-length: non-String argument: %P", arg);
}
return newLong(len);
}
static subr(string_at)
{
arity2(args, "string-at");
oop arr= getHead(args);
oop arg= getHead(getTail(args)); if (!isLong(arg)) return nil;
int idx= getLong(arg);
switch (getType(arr)) {
case String: if (0 <= idx && idx < stringLength(arr)) return newLong(get(arr, String,bits)[idx]); break;
case Symbol: if (0 <= idx && idx < symbolLength(arr)) return newLong(get(arr, Symbol,bits)[idx]); break;
default: fatal("string-at: non-String argument: %P", arr);
}
return nil;
}
static subr(set_string_at)
{
arity3(args, "set-string-at");
oop arr= getHead(args); if (!is(String, arr)) { fprintf(stderr, "set-string-at: non-string argument: "); fdumpln(stderr, arr); fatal(0); }
oop arg= getHead(getTail(args)); if (!isLong(arg)) { fprintf(stderr, "set-string-at: non-integer index: "); fdumpln(stderr, arg); fatal(0); }
oop val= getHead(getTail(getTail(args))); if (!isLong(val)) { fprintf(stderr, "set-string-at: non-integer value: "); fdumpln(stderr, val); fatal(0); }
int idx= getLong(arg);
if (idx < 0) return nil;
int len= stringLength(arr);
if (len <= idx) {
if (len < 2) len= 2;
while (len <= idx) len *= 2;
set(arr, String,bits, (wchar_t *)GC_realloc(get(arr, String,bits), sizeof(wchar_t) * (len + 1)));
set(arr, String,size, newLong(len));
}
get(arr, String,bits)[idx]= getLong(val);
return val;
}
// static subr(string_copy) // string from len
// {
// oop str= car(args); if (!is(String, str)) { fprintf(stderr, "string-copy: non-string argument: "); fdumpln(stderr, str); fatal(0); }
// int ifr= 0;
// int sln= stringLength(str);
// oop ofr= cadr(args);
// if (nil != ofr) { if (!isLong(ofr)) { fprintf(stderr, "string-copy: non-integer start: "); fdumpln(stderr, ofr); fatal(0); }
// ifr= getLong(ofr);
// if (ifr < 0 ) ifr= 0;
// if (ifr > sln) ifr= sln; assert(ifr >= 0 && ifr <= sln);
// sln -= ifr; assert(sln >= 0);
// }
// oop oln= caddr(args);
// if (nil != oln) { if (!isLong(oln)) { fprintf(stderr, "string-copy: non-integer length: "); fdumpln(stderr, oln); fatal(0); }
// int iln= getLong(oln);
// if (iln < 0) iln= 0;
// if (iln > sln) iln= sln; assert(iln >= 0 && ifr + iln <= sln);
// sln= iln;
// }
// return newStringN(get(str, String,bits) + ifr, sln);
// }
// static subr(string_compare) // string substring offset=0 length=strlen(substring)
// {
// oop str= car(args); if (!is(String, str)) { fprintf(stderr, "string-compare: non-string argument: "); fdumpln(stderr, str); fatal(0); }
// oop arg= cadr(args); if (!is(String, arg)) { fprintf(stderr, "string-compare: non-string argument: "); fdumpln(stderr, arg); fatal(0); }
// oop oof= caddr(args);
// int off= 0;
// if (nil != oof) { if (!isLong(oof)) { fprintf(stderr, "string-compare: non-integer offset: "); fdumpln(stderr, oof); fatal(0); }
// off= getLong(oof);
// }
// oop oln= cadddr(args);
// int len= stringLength(str);
// if (nil != oln) { if (!isLong(oln)) { fprintf(stderr, "string-compare: non-integer length: "); fdumpln(stderr, oln); fatal(0); }
// len= getLong(oln);
// }
// if (off < 0 || len < 0) return newLong(-1);
// if (off >= stringLength(str)) return newLong(-1);
// return newLong(wcsncmp(get(str, String,bits) + off, get(arg, String,bits), len));
// }
// static subr(symbol_compare)
// {
// arity2(args, "symbol-compare");
// oop str= getHead(args); if (!is(Symbol, str)) { fprintf(stderr, "symbol-compare: non-symbol argument: "); fdumpln(stderr, str); fatal(0); }
// oop arg= getHead(getTail(args)); if (!is(Symbol, arg)) { fprintf(stderr, "symbol-compare: non-symbol argument: "); fdumpln(stderr, arg); fatal(0); }
// return newLong(wcscmp(get(str, Symbol,bits), get(arg, Symbol,bits)));
// }
static subr(string_symbol)
{
oop arg= car(args); if (is(Symbol, arg)) return arg; if (!is(String, arg)) return nil;
return intern(get(arg, String,bits));
}
static subr(symbol_string)
{
oop arg= car(args); if (is(String, arg)) return arg; if (!is(Symbol, arg)) return nil;
return newString(get(arg, Symbol,bits));
}
static subr(long_double)
{
oop arg= car(args); if (is(Double, arg)) return arg; if (!isLong(arg)) return nil;
return newDouble(getLong(arg));
}
// static subr(long_string)
// {
// oop arg= car(args); if (is(String, arg)) return arg; if (!isLong(arg)) return nil;
// wchar_t buf[32];
// swnprintf(buf, 32, L"%ld", getLong(arg));
// return newString(buf);
// }
// static subr(string_long)
// {
// oop arg= car(args); if (isLong(arg)) return arg; if (!is(String, arg)) return nil;
// return newLong(wcstol(get(arg, String,bits), 0, 0));
// }
static subr(double_long)
{
oop arg= car(args); if (isLong(arg)) return arg; if (!isDouble(arg)) return nil;
return newLong((long)getDouble(arg));
}
// static subr(double_string)
// {
// oop arg= car(args); if (is(String, arg)) return arg; if (!isDouble(arg)) return nil;
// wchar_t buf[32];
// swnprintf(buf, 32, L"%f", getDouble(arg));
// return newString(buf);
// }
static subr(string_double)
{
oop arg= car(args); if (is(Double, arg)) return arg; if (!is(String, arg)) return nil;
return newDouble(wcstod(get(arg, String,bits), 0));
}
static subr(array)
{
oop arg= car(args);
int num= isLong(arg) ? getLong(arg) : 0;
return newArray(num);
}
static subr(arrayP)
{
return is(Array, car(args)) ? s_t : nil;
}
static subr(array_length)
{
arity1(args, "array-length");
oop arg= getHead(args); if (!is(Array, arg)) { fprintf(stderr, "array-length: non-Array argument: "); fdumpln(stderr, arg); fatal(0); }
return get(arg, Array,size);
}
static subr(array_at)
{
arity2(args, "array-at");
oop arr= getHead(args);
oop arg= getHead(getTail(args)); if (!isLong(arg)) return nil;
return arrayAt(arr, getLong(arg));
}
static subr(set_array_at)
{
arity3(args, "set-array-at");
oop arr= getHead(args);
oop arg= getHead(getTail(args)); if (!isLong(arg)) return nil;
oop val= getHead(getTail(getTail(args)));
return arrayAtPut(arr, getLong(arg), val);
}
// static subr(array_compare) // array subarray offset=0 length=arrlen(subarray)
// {
// oop arr= car(args); if (!is(Array, arr)) { fprintf(stderr, "array-compare: non-array argument: "); fdumpln(stderr, arr); fatal(0); }
// oop brr= cadr(args); if (!is(Array, brr)) { fprintf(stderr, "array-compare: non-array argument: "); fdumpln(stderr, brr); fatal(0); }
// int off= 0;
// int len= 0;
// int aln= arrayLength(arr);
// int bln= arrayLength(brr);
// oop oof= caddr(args);
// if (nil != oof) { if (!isLong(oof)) { fprintf(stderr, "array-compare: non-integer offset: "); fdumpln(stderr, oof); fatal(0); }
// off= getLong(oof);
// if (off < 0) off += aln;
// if (off < 0 || off >= aln) return newLong(-1);
// }
// oop oln= cadddr(args);
// if (nil != oln) { if (!isLong(oln)) { fprintf(stderr, "array-compare: non-integer length: "); fdumpln(stderr, oln); fatal(0); }
// len= getLong(oln);
// if (len < 0 || len > bln
// || off + len >= aln) return newLong(-1);
// }
// else {
// len= arrayLength(arr) - off;
// }
// long *aptr= (long *)get(arr, Array,_array) + off;
// long *bptr= (long *)get(brr, Array,_array);
// long cmp = 0;
// while (!cmp && len--) cmp= *aptr++ - *bptr++;
// return newLong(cmp);
// }
// static subr(data)
// {
// oop arg= car(args);
// int num= isLong(arg) ? getLong(arg) : 0;
// return newData(num);
// }
// static subr(data_length)
// {
// arity1(args, "data-length");
// oop arg= getHead(args); if (!is(Data, arg)) { fprintf(stderr, "data-length: non-Data argument: "); fdumpln(stderr, arg); fatal(0); }
// return newLong(GC_size(arg));
// }
static void idxtype(oop args, char *who)
{
fprintf(stderr, "\n%s: non-integer index: ", who);
fdumpln(stderr, args);
fatal(0);
}
static void valtype(oop args, char *who)
{
fprintf(stderr, "\n%s: improper store: ", who);
fdumpln(stderr, args);
fatal(0);
}
static inline unsigned long checkRange(oop obj, unsigned long offset, unsigned long eltsize, oop args, char *who)
{
if (isLong(obj)) return getLong(obj) + offset;
if (offset + eltsize > GC_size(obj)) {
fprintf(stderr, "\n%s: index (%ld) out of range: ", who, offset);
fdumpln(stderr, args);
fatal(0);
}
return (unsigned long)obj + offset;
}
#define accessor(name, otype, ctype) \
static subr(name##_at) \
{ \
oop arg= args; if (!isPair(arg)) arity(args, #name"-at"); \
oop obj= getHead(arg); arg= getTail(arg); if (!isPair(arg)) arity(args, #name"-at"); \
oop idx= getHead(arg); arg= getTail(arg); if (!isLong(idx)) idxtype(args, #name"-at"); \
unsigned long off= getLong(idx); \
if (isPair(arg)) { \
oop mul= getHead(arg); if (!isLong(mul)) idxtype(args, #name"-at"); \
off *= getLong(mul); if (nil != getTail(arg)) arity(args, #name"-at"); \
} \
else \
off *= sizeof(ctype); \
return new##otype(*(ctype *)checkRange(obj, off, sizeof(ctype), args, #name"-at")); \
} \
\
static subr(set_##name##_at) \
{ \
oop arg= args; if (!isPair(arg)) arity(args, "set-"#name"-at"); \
oop obj= getHead(arg); arg= getTail(arg); if (!isPair(arg)) arity(args, "set-"#name"-at"); \
oop idx= getHead(arg); arg= getTail(arg); if (!isPair(arg)) arity(args, "set-"#name"-at"); \
oop val= getHead(arg); arg= getTail(arg); if (!isLong(idx)) idxtype(args, "set-"#name"-at"); \
unsigned long off= getLong(idx); \
if (isPair(arg)) { if (!isLong(val)) idxtype(args, "set-"#name"-at"); \
off *= getLong(val); \
val= getHead(arg); if (nil != getTail(arg)) arity(args, "set-"#name"-at"); \
} \
else \
off *= sizeof(ctype); if (!is##otype(val)) valtype(args, "set-"#name"-at"); \
*(ctype *)checkRange(obj, off, sizeof(ctype), args, "set-"#name"-at")= get##otype(val); \
return val; \
}
// accessor(byte, Long, unsigned char)
// accessor(char, Long, char)
// accessor(short, Long, short)
// accessor(wchar, Long, wchar_t)
// accessor(int, Long, int)
accessor(int32, Long, int32_t)
// accessor(int64, Long, int64_t)
// accessor(long, Long, long)
// accessor(longlong, Long, long long)
// accessor(pointer, Long, long)
accessor(float, Double, float)
// accessor(double, Double, double)
// accessor(longdouble, Double, long double)
// #undef accessor
// #if !defined(WIN32)
// # include <sys/mman.h>
// #endif
// static subr(native_call)
// {
// oop obj= car(args);
// union { long l[34]; float f[34]; double d[17]; } argv;
// int argc= 0;
// args= cdr(args);
// while (is(Pair, args) && argc < 32)
// {
// oop arg= getHead(args);
// args= getTail(args);
// switch (getType(arg))
// {
// case Undefined: argv.l[argc]= 0; break;
// case Long: argv.l[argc]= getLong(arg); break;
// case Double:
// #if 1
// argc= (argc + 1) & -2; argv.d[argc++ >> 2]= getDouble(arg); break;
// #else
// argv.f[argc]= getDouble(arg); break;
// #endif
// case String: argv.l[argc]= (long)wcs2mbs(get(arg, String,bits)); break;
// case Subr: argv.l[argc]= (long)get(arg, Subr,imp); break;
// default: argv.l[argc]= (long)arg; break;
// }
// ++argc;
// }
// void *addr= 0;
// size_t size= 0;
// switch (getType(obj))
// {
// case Data: addr= obj; size= GC_size(obj); break;
// case Long: addr= (void *)getLong(obj); break;
// case Subr: addr= get(obj, Subr,imp); break;
// default: fatal("call: cannot call object of type %i", getType(obj));
// }
// if (size) {
// # if !defined(WIN32)
// extern int getpagesize();
// void *start = (void *)((long)addr & -(long)getpagesize()); // round down to page boundary for Darwin
// size_t len = (addr + size) - start;
// if (mprotect(start, len, PROT_READ | PROT_WRITE | PROT_EXEC)) perror("mprotect");
// # endif
// }
// return newLong(((int (*)())addr)(argv));
// }
// #if defined(WIN32)
// # include "w32dlfcn.h"
// #else
// # define __USE_GNU
// # include <dlfcn.h>
// # undef __USE_GNU
// #endif
// static subr(subr)
// {
// oop arg= car(args);
// wchar_t *name= 0;
// switch (getType(arg))
// {
// case String: name= get(arg, String,bits); break;
// case Symbol: name= get(arg, Symbol,bits); break;
// default: fatal("subr: argument must be string or symbol");
// }
// char *sym= wcs2mbs(name);
// void *addr= dlsym(RTLD_DEFAULT, sym);
// if (!addr) fatal("could not find symbol: %s", sym);
// proto_t *sig= 0;
// arg= cadr(args);
// if (nil != arg) { if (!is(String, arg)) { fprintf(stderr, "subr: non-String signature: "); fdumpln(stderr, arg); fatal(0); }
// wchar_t *spec = get(arg, String,bits);
// int mode = 0;
// cast_t cast = 0;
// ffi_type *type = 0;
// sig= calloc(1, sizeof(proto_t));
// sig->arg_count= 0;
// sig->arg_rest= 0;
// while ((mode= *spec++)) {
// switch (mode) {
// case 'd': type= &ffi_type_double; cast= ffdouble; break;
// case 'f': type= &ffi_type_float; cast= fffloat; break;
// case 'i': type= &ffi_type_sint; cast= ffint; break;
// case 'j': type= &ffi_type_sint32; cast= ffint32; break;
// case 'k': type= &ffi_type_sint64; cast= ffint64; break;
// case 'l': type= &ffi_type_slong; cast= fflong; break;
// case 'p': type= &ffi_type_pointer; cast= ffpointer; break;
// case 's': type= &ffi_type_pointer; cast= ffstring; break;
// case 'S': type= &ffi_type_pointer; cast= ffpointer; break;
// case '.': sig->arg_rest++; break;
// default: fatal("illegal type specification: %s", get(arg, String,bits));
// }
// if (sig->arg_rest) break;
// sig->arg_types[sig->arg_count]= type;
// sig->arg_casts[sig->arg_count]= cast;
// sig->arg_count++;
// }
// }
// return newSubr(name, addr, sig);
// }
// static subr(subr_name)
// {
// oop arg= car(args); if (!is(Subr, arg)) { fprintf(stderr, "subr-name: non-Subr argument: "); fdumpln(stderr, arg); fatal(0); }
// return newString(get(arg, Subr,name));
// }
static subr(allocate)
{
arity2(args, "allocate");
oop type= getHead(args); if (!isLong(type)) return nil;
oop size= getHead(getTail(args)); if (!isLong(size)) return nil;
return _newOops(getLong(type), sizeof(oop) * getLong(size));
}
// static subr(allocate_atomic)
// {
// arity2(args, "allocate-atomic");
// oop type= getHead(args); if (!isLong(type)) return nil;
// oop size= getHead(getTail(args)); if (!isLong(size)) return nil;
// return _newBits(getLong(type), getLong(size));
// }
static subr(oop_at)
{
arity2(args, "oop-at");
oop obj= getHead(args);
oop arg= getHead(getTail(args)); if (!isLong(arg)) return nil;
return oopAt(obj, getLong(arg));
}
static subr(set_oop_at)
{
arity3(args, "set-oop-at");
oop obj= getHead(args);
oop arg= getHead(getTail(args)); if (!isLong(arg)) return nil;
oop val= getHead(getTail(getTail(args)));
return oopAtPut(obj, getLong(arg), val);
}
static subr(not)
{
arity1(args, "not");
oop obj= getHead(args);
return (nil == obj) ? s_t : nil;
}
static subr(verbose)
{
oop obj= car(args);
if (nil == obj) return newLong(opt_v);
if (!isLong(obj)) return nil;
opt_v= getLong(obj);
return obj;
}
static subr(optimised)
{
oop obj= car(args);
if (nil == obj) return newLong(opt_O);
if (!isLong(obj)) return nil;
opt_O= getLong(obj);
return obj;
}
#if defined(DEMO_BITS)
static subr(sin)
{
oop obj= getHead(args);
double arg= 0.0;
if (isDouble(obj)) arg= getDouble(obj);
else if (isLong (obj)) arg= (double)getLong (obj);
else {
fprintf(stderr, "sin: non-numeric argument: ");
fdumpln(stderr, obj);
fatal(0);
}
return newDouble(sin(arg));
}
static subr(cos)
{
oop obj= getHead(args);
double arg= 0.0;
if (isDouble(obj)) arg= getDouble(obj);
else if (isLong (obj)) arg= (double)getLong (obj);
else {
fprintf(stderr, "cos: non-numeric argument: ");
fdumpln(stderr, obj);
fatal(0);
}
return newDouble(cos(arg));
}
static subr(log)
{
oop obj= getHead(args);
double arg= 0.0;
if (isDouble(obj)) arg= getDouble(obj);
else if (isLong (obj)) arg= (double)getLong (obj);
else {
fprintf(stderr, "log: non-numeric argument: ");
fdumpln(stderr, obj);
fatal(0);
}
return newDouble(log(arg));
}
#endif
static subr(address_of)
{
oop arg= car(args);
return newLong((long)arg);
}
// #include <sys/time.h>
// #if defined(WIN32)
// struct rusage {
// struct timeval ru_utime;
// struct timeval ru_stime;
// };
// # define RUSAGE_SELF 0
// # define timersub(a, b, result) \
// do { \
// (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
// (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
// if ((result)->tv_usec < 0) { \
// --(result)->tv_sec; \
// (result)->tv_usec += 1000000; \
// } \
// } while (0)
// static void getrusage(int who, struct rusage *ru)
// {
// clock_t cl= clock();
// long ms= cl * 1000 / CLOCKS_PER_SEC;
// ru->ru_utime.tv_sec= (ms / 1000);
// ru->ru_utime.tv_usec= (ms % 1000) * 1000;
// ru->ru_stime.tv_sec= 0;
// ru->ru_stime.tv_usec= 0;
// }
// #else
// # include <sys/resource.h>
// #endif
// static struct timeval epoch;
// static void init_times(void)
// {
// gettimeofday(&epoch, 0);
// }
// static subr(times)
// {
// struct timeval tv;
// struct rusage ru;
// gettimeofday(&tv, 0);
// getrusage(RUSAGE_SELF, &ru);
// oop secs= newLong(tv.tv_sec); GC_PROTECT(secs);
// timersub(&tv, &epoch, &tv);
// oop real= newLong(tv.tv_sec * 1000 + tv.tv_usec / 1000); GC_PROTECT(real);
// oop user= newLong(ru.ru_utime.tv_sec * 1000 + ru.ru_utime.tv_usec / 1000); GC_PROTECT(user);
// oop syst= newLong(ru.ru_stime.tv_sec * 1000 + ru.ru_stime.tv_usec / 1000); GC_PROTECT(syst);
// secs= newPair(secs, nil);
// syst= newPair(syst, secs);
// user= newPair(user, syst); GC_UNPROTECT(syst);
// real= newPair(real, user); GC_UNPROTECT(user);
// GC_UNPROTECT(real);
// GC_UNPROTECT(secs);
// return real;
// }
typedef struct { char *name; imp_t imp; } subr_ent_t;
static subr_ent_t subr_tab[];
// #if !defined(LIB_GC)
// static void saver(FILE *out, void *ptr)
// {
// oop obj= (oop)ptr; assert(ptr && !((long)ptr & 1));
// int type= ptr2hdr(ptr)->type;
// if (out) put32(out, type);
// switch (type) {
// case Symbol: {
// wchar_t *str= get(obj, Symbol,bits);
// int len= wcslen(str);
// if (out) {
// int i;
// put32(out, len);
// for (i= 0; i < len; ++i) put32(out, str[i]);
// }
// break;
// }
// case Subr: {
// wchar_t *str= get(obj, Subr,name);
// int len= wcslen(str);
// if (out) {
// int i;
// put32(out, len);
// for (i= 0; i < len; ++i) put32(out, str[i]);
// }
// break;
// }
// default:
// GC_saver(out, ptr);
// break;
// }
// }
// static void loader(FILE *in, void *ptr)
// {
// oop obj= (oop)ptr; assert(ptr && !((long)ptr & 1));
// int tmp32;
// int type= get32(in, &tmp32);
// ptr2hdr(ptr)->type= type;
// switch (type) {
// case Symbol: {
// int len= get32(in, &tmp32);
// wchar_t *str= (wchar_t *)alloca(4 * len + 4);
// int i;
// for (i= 0; i < len; ++i) str[i]= get32(in, &tmp32);
// str[i]= 0;
// //wprintf(L"loading Symbol %ls\n", str);
// set(obj, Symbol,bits, wcsdup(str));
// break;
// }
// case Subr: {
// int i, len= get32(in, &tmp32);
// wchar_t *str= (wchar_t *)alloca(4 * len + 4);
// for (i= 0; i < len; ++i) str[i]= get32(in, &tmp32);
// str[i]= 0;
// //wprintf(L"loading Subr %ls\n", str);
// set(obj, Subr,name, wcsdup(str));
// set(obj, Subr,imp, 0);
// char *sym= wcs2mbs(str);
// void *addr= 0;
// subr_ent_t *ptr= subr_tab;
// for (ptr= subr_tab; ptr->name; ++ptr) {
// if (!strcmp(sym, ptr->name + 1)) {
// addr= ptr->imp;
// break;
// }
// }
// if (!addr) {
// addr= dlsym(RTLD_DEFAULT, sym);
// if (!addr) fatal("loader: could not find Subr name: %s", sym);
// }
// set(obj, Subr,imp, addr);
// break;
// }
// default:
// GC_loader(in, ptr);
// break;
// }
// }
// #include <sys/stat.h>
// static subr(save)
// {
// oop arg= car(args); if (!is(String, arg)) { fprintf(stderr, "save: non-String argument: "); fdumpln(stderr, arg); fatal(0); }
// wchar_t *name= get(arg, String,bits);
// char *path= wcs2mbs(name);
// FILE *stream= fopen(path, "wb");
// if (!stream) return nil;
// fprintf(stream, "#!%s -l\n", argv0);
// GC_save(stream, saver);
// fclose(stream);
// chmod(path, 0755);
// return arg;
// }
// #endif
// #undef subr
static void replFile(FILE *stream, wchar_t *path)
{
setVar(input, newLong((long)stream));
beginSource(path);
oop obj= nil; GC_PROTECT(obj);
for (;;) {
if (stream == stdin) {
printf(".");
fflush(stdout);
}
obj= readExpr(stream);
if (obj == DONE) break;
if (opt_v) {
dumpln(obj);
fflush(stdout);
}
obj= expand(obj, getVar(globals));
if (opt_g) encode(obj, getVar(globals));
obj= eval (obj, getVar(globals));
if ((stream == stdin) || (opt_v > 0)) {
printf(" => ");
fflush(stdout);
dumpln(obj);
fflush(stdout);
}
if (opt_v) {
#if (!LIB_GC)
GC_gcollect();
printf("%ld collections, %ld objects, %ld bytes, %4.1f%% fragmentation\n",
(long)GC_collections, (long)GC_count_objects(), (long)GC_count_bytes(),
GC_count_fragments() * 100.0);
#endif
}
} GC_UNPROTECT(obj);
int c= getwc(stream);
if (WEOF != c) fatal("unexpected character 0x%02x '%c'\n", c, c);
endSource();
}
static void replPath(wchar_t *path)
{
FILE *stream= fopen(wcs2mbs(path), "r");
if (!stream) {
int err= errno;
fprintf(stderr, "\nerror: ");
errno= err;
perror(wcs2mbs(path));
fatal(0);
}
fwide(stream, 1);
if (fscanf(stream, "#!%*[^\012\015]"));
replFile(stream, path);
fclose(stream);
}
static void sigint(int signo)
{
fatal("\nInterrupt");
}
// #if !defined(WIN32) && (!LIB_GC)
// static int profilerCount= 0;
// static void sigvtalrm(int signo)
// {
// if (traceDepth < 1) return;
// ++profilerCount;
// oop func= arrayAt(traceStack, traceDepth - 1);
// switch (getType(func))
// {
// case Expr: {
// oop profile= get(func, Expr,profile);
// if ((long)profile & 1) {
// set(func, Expr,profile, (oop)((long)profile + 2));
// }
// else printf("? %p\n", func);
// break;
// }
// case Subr: {
// set(func, Subr,profile, 1 + get(func, Subr,profile));
// break;
// }
// }
// }
// #include <sys/time.h>
// static void profilingEnable(void)
// {
// struct itimerval itv= { { 0, opt_p }, { 0, opt_p } }; /* VTALARM every opt_p mSecs */
// setitimer(ITIMER_VIRTUAL, &itv, 0);
// }
// static void profilingDisable(int stats)
// {
// struct itimerval itv= { { 0, 0 }, { 0, 0 } };
// setitimer(ITIMER_VIRTUAL, &itv, 0);
// if (stats)
// {
// struct profile { int profile; oop object, source; } profiles[64];
// int nprofiles= 0;
// fprintf(stderr, "%i profiles\n", profilerCount);
// GC_gcollect();
// oop obj;
// for (obj= GC_first_object(); obj; obj= GC_next_object(obj)) {
// int profile= 0;
// oop source= nil;
// switch (getType(obj))
// {
// case Expr: {
// oop oprof= get(obj, Expr,profile);
// if (isLong(oprof)) {
// profile= getLong(get(obj, Expr,profile));
// source= cddr(get(obj, Expr,defn));
// }
// break;
// }
// case Subr: {
// profile= get(obj, Subr,profile);
// break;
// }
// }
// if (profile) {
// int index= 0;
// while (index < nprofiles && profile <= profiles[index].profile) ++index;
// if (nprofiles < 64) ++nprofiles;
// int jndex;
// for (jndex= nprofiles - 1; jndex > index; --jndex) profiles[jndex] = profiles[jndex - 1];
// profiles[index]= (struct profile){ profile, obj, source };
// }
// }
// int i;
// for (i= 0; i < nprofiles; ++i) {
// fprintf(stderr, "%i\t", profiles[i].profile);
// int l= fprintSource(stderr, profiles[i].source);
// if (l < 20) fprintf(stderr, "%*s", 20 - l, "");
// fprintf(stderr, " ");
// fdumpln(stderr, profiles[i].object);
// }
// }
// }
// #endif
static subr_ent_t subr_tab[] = {
# define _do(NAME, OP) \
{ " "#OP, subr_##NAME },
// _do_unary()
_do_ibinary()
_do_binary()
{ " -", subr_sub },
{ " %", subr_mod },
_do_relation()
{ " =", subr_eq },
{ " !=", subr_ne },
# undef _do
{ ".if", subr_if },
{ ".and", subr_and },
{ ".or", subr_or },
{ ".set", subr_set },
{ ".let", subr_let },
{ ".while", subr_while },
{ ".quote", subr_quote },
{ ".lambda", subr_lambda },
{ ".define", subr_define },
{ " defined?", subr_definedP },
{ " exit", subr_exit },
{ " abort", subr_abort },
// // { " current-environment", subr_current_environment },
{ " open", subr_open },
{ " close", subr_close },
// { " getb", subr_getb },
{ " getc", subr_getc },
// { " putb", subr_putb },
{ " putc", subr_putc },
{ " read", subr_read },
{ " expand", subr_expand },
{ " eval", subr_eval },
{ " apply", subr_apply },
{ " current-environment", subr_current_environment },
{ " type-of", subr_type_of },
// { " warn", subr_warn },
{ " print", subr_print },
{ " dump", subr_dump },
{ " format", subr_format },
{ " form", subr_form },
// { " fixed?", subr_fixedP },
{ " cons", subr_cons },
{ " pair?", subr_pairP },
{ " car", subr_car },
{ " set-car", subr_set_car },
{ " cdr", subr_cdr },
{ " set-cdr", subr_set_cdr },
// { " form?", subr_formP },
{ " symbol?", subr_symbolP },
{ " string?", subr_stringP },
{ " string", subr_string },
{ " string-length", subr_string_length },
{ " string-at", subr_string_at },
{ " set-string-at", subr_set_string_at },
// { " string-copy", subr_string_copy },
// { " string-compare", subr_string_compare },
{ " symbol->string", subr_symbol_string },
{ " string->symbol", subr_string_symbol },
// { " symbol-compare", subr_symbol_compare },
{ " long->double", subr_long_double },
// { " long->string", subr_long_string },
// { " string->long", subr_string_long },
{ " double->long", subr_double_long },
// { " double->string", subr_double_string },
{ " string->double", subr_string_double },
{ " array", subr_array },
{ " array?", subr_arrayP },
{ " array-length", subr_array_length },
{ " array-at", subr_array_at },
{ " set-array-at", subr_set_array_at },
// { " array-compare", subr_array_compare },
// { " data", subr_data },
// { " data-length", subr_data_length },
// { " byte-at", subr_byte_at },
// { " set-byte-at", subr_set_byte_at },
// { " char-at", subr_char_at },
// { " set-char-at", subr_set_char_at },
// { " short-at", subr_short_at },
// { " set-short-at", subr_set_short_at },
// { " wchar-at", subr_wchar_at },
// { " set-wchar-at", subr_set_wchar_at },
// { " int-at", subr_int_at },
// { " set-int-at", subr_set_int_at },
{ " int32-at", subr_int32_at },
{ " set-int32-at", subr_set_int32_at },
// { " int64-at", subr_int64_at },
// { " set-int64-at", subr_set_int64_at },
// { " long-at", subr_long_at },
// { " set-long-at", subr_set_long_at },
// { " longlong-at", subr_longlong_at },
// { " set-longlong-at", subr_set_longlong_at },
// { " pointer-at", subr_pointer_at },
// { " set-pointer-at", subr_set_pointer_at },
{ " float-at", subr_float_at },
{ " set-float-at", subr_set_float_at },
// { " double-at", subr_double_at },
// { " set-double-at", subr_set_double_at },
// { " longdouble-at", subr_longdouble_at },
// { " set-longdouble-at", subr_set_longdouble_at },
// { " native-call", subr_native_call },
// { " subr", subr_subr },
// { " subr-name", subr_subr_name },
{ " allocate", subr_allocate },
// { " allocate-atomic", subr_allocate_atomic },
{ " oop-at", subr_oop_at },
{ " set-oop-at", subr_set_oop_at },
{ " not", subr_not },
{ " verbose", subr_verbose },
{ " optimised", subr_optimised },
#if defined(DEMO_BITS)
{ " sin", subr_sin },
{ " cos", subr_cos },
{ " log", subr_log },
#endif
{ " address-of", subr_address_of },
// { " times", subr_times },
// #if !defined(LIB_GC)
// { " save", subr_save },
// #endif
{ 0, 0 }};
int main(int argc, char **argv)
{
switch (sizeof(long)) {
case 4: ffi_type_long= ffi_type_sint32; break;
case 8: ffi_type_long= ffi_type_sint64; break;
case 16: fatal("I cannot run here"); break;
}
argv0= argv[0];
// init_times();
if ((fwide(stdin, 1) <= 0) || (fwide(stdout, -1) >= 0) || (fwide(stderr, -1) >= 0)) {
fprintf(stderr, "Cannot set stream widths.\n");
return 1;
}
if (!setlocale(LC_CTYPE, "")) {
fprintf(stderr, "Cannot set the locale. Verify your LANG, LC_CTYPE, LC_ALL.\n");
return 1;
}
GC_INIT();
_globalCache= _newOops(0, sizeof(oop) * GLOBAL_CACHE_SIZE); GC_add_root(&_globalCache);
GC_add_root(&symbols);
GC_add_root(&globals);
GC_add_root(&globalNamespace);
GC_add_root(&expanders);
GC_add_root(&encoders);
GC_add_root(&evaluators);
GC_add_root(&applicators);
GC_add_root(&backtrace);
GC_add_root(&arguments);
GC_add_root(&input);
GC_add_root(&output);
symbols= newArray(0);
s_locals = intern(L"*locals*"); GC_add_root(&s_locals );
s_set = intern(L"set"); GC_add_root(&s_set );
s_define = intern(L"define"); GC_add_root(&s_define );
s_let = intern(L"let"); GC_add_root(&s_let );
s_lambda = intern(L"lambda"); GC_add_root(&s_lambda );
s_quote = intern(L"quote"); GC_add_root(&s_quote );
s_quasiquote = intern(L"quasiquote"); GC_add_root(&s_quasiquote );
s_unquote = intern(L"unquote"); GC_add_root(&s_unquote );
s_unquote_splicing = intern(L"unquote-splicing"); GC_add_root(&s_unquote_splicing );
s_t = intern(L"t"); GC_add_root(&s_t );
s_dot = intern(L"."); GC_add_root(&s_dot );
s_etc = intern(L"..."); GC_add_root(&s_etc );
s_bracket = intern(L"bracket"); GC_add_root(&s_bracket );
s_brace = intern(L"brace"); GC_add_root(&s_brace );
s_main = intern(L"*main*"); GC_add_root(&s_main );
oop tmp= nil; GC_PROTECT(tmp);
globalNamespace= cons(intern(L"*global-namespace*"), nil);
globalNamespace= setTail(globalNamespace, cons(globalNamespace, nil));
globals= define(globalNamespace, intern(L"*globals*"), globalNamespace);
expanders= define(globalNamespace, intern(L"*expanders*"), nil);
encoders= define(globalNamespace, intern(L"*encoders*"), nil);
evaluators= define(globalNamespace, intern(L"*evaluators*"), nil);
applicators= define(globalNamespace, intern(L"*applicators*"), nil);
traceStack= newArray(32); GC_add_root(&traceStack);
backtrace= define(globalNamespace, intern(L"*backtrace*"), nil);
input= define(globalNamespace, intern(L"*input*"), nil);
output= define(globalNamespace, intern(L"*output*"), nil);
currentPath= nil; GC_add_root(¤tPath);
currentLine= nil; GC_add_root(¤tLine);
currentSource= cons(nil, nil); GC_add_root(¤tSource);
{
subr_ent_t *ptr;
for (ptr= subr_tab; ptr->name; ++ptr) {
wchar_t *name= wcsdup(mbs2wcs(ptr->name + 1));
tmp= newSubr(name, ptr->imp, 0);
if ('.' == ptr->name[0]) tmp= newFixed(tmp);
define(globalNamespace, intern(name), tmp);
}
}
tmp= nil; GC_UNPROTECT(tmp);
// f_set= lookup(getVar(globals), s_set ); GC_add_root(&f_set);
// f_quote= lookup(getVar(globals), s_quote ); GC_add_root(&f_quote);
// f_lambda= lookup(getVar(globals), s_lambda); GC_add_root(&f_lambda);
// f_let= lookup(getVar(globals), s_let ); GC_add_root(&f_let);
// f_define= lookup(getVar(globals), s_define); GC_add_root(&f_define);
int repled= 0;
// #if !defined(LIB_GC)
// if (argc > 2 && !strcmp(argv[1], "-l")) {
// FILE *stream= fopen(argv[2], "rb");
// //printf("load memory from %s %p\n", argv[2], stream);
// if (!stream) {
// perror(argv[2]);
// exit(1);
// }
// while ('\n' != getc(stream));
// GC_load(stream, loader);
// fclose(stream);
// argc -= 2;
// argv += 2;
// opt_b= 1; // don't load boot.l
// GC_gcollect();
// }
// #endif
{
tmp= nil; GC_PROTECT(tmp);
while (--argc) {
tmp= cons(nil, tmp);
setHead(tmp, newString(mbs2wcs(argv[argc])));
}
arguments= define(globalNamespace, intern(L"*arguments*"), tmp);
tmp= nil; GC_UNPROTECT(tmp);
signal(SIGINT, sigint);
}
// #if !defined(WIN32) && (!LIB_GC)
// {
// struct sigaction sa;
// sa.sa_handler= sigvtalrm;
// sigemptyset(&sa.sa_mask);
// sa.sa_flags= 0;
// if (sigaction(SIGVTALRM, &sa, 0)) perror("vtalrm");
// }
// #endif
// {
// oop func= findVariable(get(globals, Variable,value), s_main);
// if (is(Variable, func)) {
// apply(get(func, Variable,value), nil, nil);
// exit(0);
// }
// }
while (is(Pair, getVar(arguments))) {
oop argl= getVar(arguments); GC_PROTECT(argl);
oop args= getHead(argl);
oop argt= getTail(argl);
wchar_t *arg= get(args, String,bits);
if (!wcscmp (arg, L"-v")) { ++opt_v; }
else if (!wcscmp (arg, L"-b")) { ++opt_b; }
else if (!wcscmp (arg, L"-g")) { ++opt_g; opt_p= 0; }
else if (!wcscmp (arg, L"-O")) { ++opt_O; }
// # if !defined(WIN32) && (!LIB_GC)
// else if (!wcsncmp(arg, L"-p", 2)) {
// opt_g= 0;
// opt_p= wcstoul(arg + 2, 0, 0);
// if (!opt_p) opt_p= 1000;
// printf("profiling every %i uSec(s)\n", opt_p);
// }
// # endif
else {
if (!opt_b) {
replPath(L"boot2.l");
opt_b= 1;
}
else {
// # if !defined(WIN32) && (!LIB_GC)
// if (opt_p) profilingEnable();
// # endif
setVar(arguments, argt);
replPath(arg);
repled= 1;
// # if !defined(WIN32) && (!LIB_GC)
// if (opt_p) profilingDisable(0);
// # endif
}
argt= getVar(arguments);
}
setVar(arguments, argt); GC_UNPROTECT(argl);
}
// if (opt_v) {
// #if (!LIB_GC)
// GC_gcollect();
// printf("%ld collections, %ld objects, %ld bytes, %4.1f%% fragmentation\n",
// (long)GC_collections, (long)GC_count_objects(), (long)GC_count_bytes(),
// GC_count_fragments() * 100.0);
// #endif
// }
setVar(output, newLong((long)stdout));
if (!repled) {
if (!opt_b) replPath(L"boot2.l");
replFile(stdin, L"<stdin>");
printf("\nmorituri te salutant\n");
}
// #if !defined(WIN32) && (!LIB_GC)
// if (opt_p) profilingDisable(1);
// #endif
return 0;
}
// Local Variables:
// comment-start: "// "
// comment-end: ""
// End:
| 28.774355 | 230 | 0.582875 | [
"object",
"3d"
] |
c8fa604873834e13bb95d2739c2fa3f7d45ebec6 | 4,415 | h | C | CCDebugMenu.h | yassy0413/cocos2dx-3.x-util | 2369924a92b5fad9df3f0919f6d4769798590c2f | [
"MIT"
] | 11 | 2015-02-02T16:33:54.000Z | 2021-03-16T00:47:08.000Z | CCDebugMenu.h | yassy0413/cocos2dx-3.x-util | 2369924a92b5fad9df3f0919f6d4769798590c2f | [
"MIT"
] | null | null | null | CCDebugMenu.h | yassy0413/cocos2dx-3.x-util | 2369924a92b5fad9df3f0919f6d4769798590c2f | [
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) Yassy
https://github.com/yassy0413/cocos2dx-3.x-util
****************************************************************************/
#ifndef __CCDEBUGMENU_H__
#define __CCDEBUGMENU_H__
#include "cocos2d.h"
#include "cocos-ext.h"
#if COCOS2D_DEBUG > 0
NS_CC_EXT_BEGIN
/**
* デバッグメニュー
*/
class DebugMenu
: public cocos2d::Ref
{
public:
class Container;
class Component;
virtual void update(float delta);
DebugMenu();
virtual ~DebugMenu();
virtual bool init();
/**
* Returns a shared instance of the director.
* @js _getInstance
*/
static DebugMenu* getInstance();
/**
* ロングタップでメニューを開くようにする
* @param seconds 必要なホールド秒数
*/
void enableLongTap(float seconds = 1.0f);
/**
* キー入力でメニューを開くようにする
*/
void enableKeyboard(EventKeyboard::KeyCode keycode);
/**
* 加速度センサーでメニューを開くようにする
* @param threshold 加速量の閾値
*/
void enableAccele(float threshold = 4.0f);
/**
* デバッグメニュー表示を開始
*/
virtual void open();
/**
* デバッグメニュー表示を終了
*/
virtual void close();
/**
* Return a root container.
*/
Container* getRootContainer() const { return _rootContainer; }
private:
Container* _rootContainer;
LayerColor* _background;
float _thresholdAccele;
float _thresholdLongTap;
bool _touching;
std::chrono::system_clock::time_point _touchBeganTime;
cocos2d::Vec2 _touchBeganPoint;
cocos2d::Vec2 _touchCurrentPoint;
public:
/**
* デバッグメニュー項目
*/
class Component
: public cocos2d::Node
{
public:
friend class Container;
class Preset;
Component(const std::string& key);
virtual ~Component();
const std::string& getKey() const { return _key; }
typedef std::function<void(Component* sender)> OnValueChenged;
OnValueChenged onValueChenged;
protected:
Container* _container;
std::string _key;
private:
virtual void setContainer(Container* container);
};
/**
* 項目のリスト管理とイベント処理
*/
class Container
: public cocos2d::Node
{
public:
Container();
virtual ~Container();
// cocos2d::Node
virtual void onEnter() override;
virtual void onExit() override;
/// Add component.
virtual void add(Component* target, Component::OnValueChenged onValueChanged = nullptr);
private:
cocos2d::extension::ScrollView* _scrollView;
std::vector<Component*> _components;
float _offsetY;
};
};
/**
* コンポーネントのプリセット
*/
class DebugMenu::Component::Preset
{
public:
/**
* スイッチ式のフラグ
*/
class Flag
: public Component
{
public:
Flag(const std::string& key) : Component(key){}
private:
virtual void setContainer(Container* container) override;
virtual void onControlEvent(cocos2d::Ref* sender, cocos2d::extension::Control::EventType controlEvent);
};
/**
* ボタン
*/
class Button
: public Component
{
public:
Button(const std::string& key) : Component(key){}
virtual void onEnter() override;
private:
virtual void setContainer(Container* container) override;
virtual void onControlEvent(cocos2d::Ref* sender, cocos2d::extension::Control::EventType controlEvent);
};
/**
* スライダー
*/
class Slider
: public Component
{
public:
Slider(const std::string& key, float min, float max)
: Component(key)
, _minValue(min)
, _maxValue(max)
{}
private:
virtual void setContainer(Container* container) override;
virtual void onControlEvent(cocos2d::Ref* sender, cocos2d::extension::Control::EventType controlEvent);
virtual void updateLabel();
protected:
Label* _label;
float _minValue;
float _maxValue;
};
class SliderI
: public Slider
{
public:
SliderI(const std::string& key, float min, float max)
: Slider(key, min, max)
{}
private:
virtual void updateLabel() override;
};
};
NS_CC_EXT_END
#endif
#endif
| 21.965174 | 111 | 0.571234 | [
"vector"
] |
c8fb1273806fdb35d820252fdf67bb768633e442 | 19,273 | h | C | uppsrc/ide/Debuggers/Pdb.h | UltimateScript/Forgotten | ac59ad21767af9628994c0eecc91e9e0e5680d95 | [
"BSD-3-Clause"
] | null | null | null | uppsrc/ide/Debuggers/Pdb.h | UltimateScript/Forgotten | ac59ad21767af9628994c0eecc91e9e0e5680d95 | [
"BSD-3-Clause"
] | null | null | null | uppsrc/ide/Debuggers/Pdb.h | UltimateScript/Forgotten | ac59ad21767af9628994c0eecc91e9e0e5680d95 | [
"BSD-3-Clause"
] | null | null | null | #include <winver.h>
#include <dbghelp.h>
#include <psapi.h>
#include "cvconst.h"
#include <plugin/ndisasm/ndisasm.h>
using namespace PdbKeys;
struct Pdb : Debugger, ParentCtrl {
virtual void Stop();
virtual bool IsFinished();
virtual bool Key(dword key, int count);
virtual void DebugBar(Bar& bar);
virtual bool SetBreakpoint(const String& filename, int line, const String& bp);
virtual bool RunTo();
virtual void Run();
virtual bool Tip(const String& exp, CodeEditor::MouseTip& mt);
virtual void Serialize(Stream& s);
struct ModuleInfo : Moveable<ModuleInfo> {
adr_t base;
dword size;
String path;
bool symbols;
ModuleInfo() { base = size = 0; symbols = false; }
};
struct FilePos {
String path;
int line;
adr_t address;
operator bool() const { return !IsNull(path); }
FilePos() { line = 0; address = 0; }
FilePos(const String& p, int l) : path(p), line(l) { address = 0; }
};
enum CpuRegisterKind {
REG_L, REG_H, REG_X, REG_E, REG_R
};
struct CpuRegister : Moveable<CpuRegister> {
int sym; // DbgHelp register symbol
const char *name; // NULL: Do not list (e.g. al, as it is printed as EAX or RAX
int kind; // CpuRegisterKind
dword flags; // Unused
};
struct MemPg : Moveable<MemPg> {
char data[1024];
};
struct PdbHexView : HexView {
Pdb *pdb;
virtual int Byte(int64 addr) { return pdb ? pdb->Byte((adr_t)addr) : 0; }
PdbHexView() { pdb = NULL; }
}
memory;
struct FnInfo : Moveable<FnInfo> {
String name;
adr_t address;
dword size;
dword pdbtype;
FnInfo() { address = size = pdbtype = 0; }
};
enum { UNKNOWN = -99, BOOL1, SINT1, UINT1, SINT2, UINT2, SINT4, UINT4, SINT8, UINT8, FLT, DBL, PFUNC };
struct Context {
#ifdef CPU_64
union {
CONTEXT context64;
WOW64_CONTEXT context32;
};
#else
CONTEXT context32;
#endif
};
struct TypeInfo : Moveable<TypeInfo> {
int type = UNKNOWN;
int ref = 0; // this is pointer or reference
bool reference = false; // this is reference
};
struct Val : Moveable<Val, TypeInfo> {
bool array = false;
bool rvalue = false; // data is loaded from debugee (if false, data pointed to by address)
bool udt = false; // user defined type (e.g. struct..)
byte bitpos = 0;
byte bitcnt = 0;
int reported_size = 0; // size of symbol, can be 0 - unknown, useful for C fixed size arrays
union {
adr_t address;
int64 ival;
double fval;
};
Context *context = NULL; // needed to retrieve register variables
#ifdef _DEBUG
String ToString() const;
#endif
Val() { address = 0; }
};
struct NamedVal : Moveable<NamedVal> {
String name;
Val val;
Val key;
int64 from = 0;
bool exp = false;
};
struct Type : Moveable<Type> {
Type() : size(-1), vtbl_typeindex(-1) {}
adr_t modbase;
String name;
int size;
int vtbl_typeindex;
int vtbl_offset;
Vector<Val> base;
VectorMap<String, Val> member;
VectorMap<String, Val> static_member;
};
struct Frame : Moveable<Frame> {
adr_t pc, frame, stack;
FnInfo fn;
VectorMap<String, Val> param;
VectorMap<String, Val> local;
String text;
};
struct VisualPart : Moveable<VisualPart> {
String text;
Color ink;
bool mark;
Size GetSize() const;
};
struct Visual {
int length;
Vector<VisualPart> part;
void Cat(const String& text, Color ink = SColorText);
void Cat(const char *text, Color ink = SColorText);
String GetString() const;
void Clear() { part.Clear(); length = 0; }
Size GetSize() const;
Visual() { length = 0; }
};
struct VisualDisplay : Display {
Pdb *pdb;
virtual Size GetStdSize(const Value& q) const;
virtual void Paint(Draw& w, const Rect& r, const Value& q,
Color ink, Color paper, dword style) const;
VisualDisplay(Pdb *pdb) : pdb(pdb) {}
} visual_display;
struct PrettyImage {
Size size;
adr_t pixels;
};
struct Thread : Context {
HANDLE hThread;
adr_t sp;
};
int lock;
bool running;
bool stop;
HANDLE hProcess;
HANDLE mainThread;
DWORD processid;
DWORD hProcessId;
DWORD mainThreadId;
ArrayMap<dword, Thread> threads;
bool terminated;
bool refreshmodules;
Vector<ModuleInfo> module;
DEBUG_EVENT event;
DWORD debug_threadid;
HWND hWnd;
VectorMap<adr_t, byte> bp_set; // breakpoints active for single RunToException
bool clang; // we are in clang toolchain
bool win64; // debugee is 64-bit, always false in 32-bit exe
Context context;
Index<adr_t> invalidpage;
VectorMap<adr_t, MemPg> mempage;
Index<adr_t> breakpoint;
Vector<String> breakpoint_cond;
ArrayMap<int, Type> type; // maps pdb pSym->TypeIndex to type data
VectorMap<String, int> type_name; // maps the name of type to above 'type' index
Index<adr_t> type_bases; // index of modbases for types (usually one)
VectorMap<String, int> type_index; // maps the name of type to TypeIndex, loaded by SymEnumTypes
String disas_name;
Array<Frame> frame;
Frame *current_frame;
String autotext;
VectorMap<adr_t, FnInfo> fninfo_cache;
DbgDisas disas;
EditString watchedit;
enum { // Order in this enum has to be same as order of tab.Add
TAB_AUTOS, TAB_LOCALS, TAB_THIS, TAB_WATCHES, TAB_CPU, TAB_MEMORY, TAB_BTS
};
TabCtrl tab;
DropList threadlist;
DropList framelist;
Button frame_up, frame_down;
Label dlock;
ArrayCtrl locals;
ArrayCtrl self;
ArrayCtrl watches;
ArrayCtrl autos;
ColumnList cpu;
EditString expexp;
Button exback, exfw;
StaticRect explorer_pane;
StaticRect pane, rpane;
TreeCtrl tree;
String tree_exp;
bool first_exception = true;
TreeCtrl bts; // backtraces of all threads
VectorMap<String, String> treetype;
int restoring_tree = 0;
Vector<String> exprev, exnext;
Index<String> noglobal;
VectorMap<String, Val> global;
adr_t current_modbase; // so that we do not need to pass it as parameter to GetTypeInfo
VectorMap<String, TypeInfo> typeinfo_cache;
enum { SINGLE_VALUE, TEXT, CONTAINER };
struct LengthLimit {};
struct Pretty {
int kind; // VARIABLE, TEXT or CONTAINER
int64 data_count = 0; // number of entries
Vector<String> data_type; // type of data items (usually type_param)
Vector<adr_t> data_ptr; // pointer to items (data_count.GetCount() * data_type.GetCount() items)
Visual text;
void Text(const char *s, Color color = SRed) { text.Cat(s, color); }
void Text(const String& s, Color color = SRed) { text.Cat(s, color); }
void SetNull() { Text("Null", SCyan); }
};
VectorMap<String, Tuple<int, Event<Val, const Vector<String>&, int64, int, Pdb::Pretty&>>> pretty;
bool break_running; // Needed for Wow64 BreakRunning to avoid ignoring breakpoint
bool show_type = false;
bool raw = false;
int bc_lvl = 0; // For coloring { } in pretty container display
void Error(const char *s = NULL);
String Hex(adr_t);
// CPU registers
uint32 GetRegister32(const Context& ctx, int sym);
uint64 GetRegister64(const Context& ctx, int sym);
const VectorMap<int, CpuRegister>& GetRegisterList();
uint64 GetCpuRegister(const Context& ctx, int sym);
// debug
Context ReadContext(HANDLE hThread);
void WriteContext(HANDLE hThread, Context& context);
void LoadModuleInfo();
int FindModuleIndex(adr_t base);
void UnloadModuleSymbols();
void AddThread(dword dwThreadId, HANDLE hThread);
void RemoveThread(dword dwThreadId);
void Lock();
void Unlock();
void ToForeground();
bool RunToException();
bool AddBp(adr_t address);
bool RemoveBp(adr_t address);
bool RemoveBp();
bool IsBpSet(adr_t address) const { return bp_set.Find(address) >= 0; }
bool Continue();
bool SingleStep();
void BreakRunning();
bool ConditionalPass();
void SetBreakpoints();
void SaveForeground();
void RestoreForeground();
void SyncFrameButtons();
adr_t GetIP();
void WriteContext();
// mem
int Byte(adr_t addr);
bool Copy(adr_t addr, void *ptr, int count);
String ReadString(adr_t addr, int maxlen, bool allowzero = false);
WString ReadWString(adr_t addr, int maxlen, bool allowzero = false);
// sym
struct LocalsCtx;
static BOOL CALLBACK EnumLocals(PSYMBOL_INFO pSymInfo, ULONG SymbolSize, PVOID UserContext);
static BOOL CALLBACK EnumGlobals(PSYMBOL_INFO pSymInfo, ULONG SymbolSize, PVOID UserContext);
void TypeVal(Pdb::Val& v, int typeId, adr_t modbase);
String GetSymName(adr_t modbase, dword typeindex);
dword GetSymInfo(adr_t modbase, dword typeindex, IMAGEHLP_SYMBOL_TYPE_INFO info);
const Type& GetType(int ti);
int GetTypeIndex(adr_t modbase, dword typeindex);
Val GetGlobal(const String& name);
adr_t GetAddress(FilePos p);
FilePos GetFilePos(adr_t address);
FnInfo GetFnInfo0(adr_t address);
FnInfo GetFnInfo(adr_t address);
void GetLocals(Frame& frame, Context& context,
VectorMap<String, Pdb::Val>& param,
VectorMap<String, Pdb::Val>& local);
String TypeAsString(int ti, bool deep = true);
int FindType(adr_t modbase, const String& name);
String TypeInfoAsString(TypeInfo tf);
TypeInfo GetTypeInfo(adr_t modbase, const String& name);
TypeInfo GetTypeInfo(const String& name) { return GetTypeInfo(current_modbase, name); } // only in Pretty...
static String FormatString(const String& x) { return AsCString(x, INT_MAX, NULL, CheckUtf8(x) ? 0 : ASCSTRING_OCTALHI); }
// exp
Val MakeVal(const String& type, adr_t address);
void ThrowError(const char *s);
int SizeOfType(int ti);
int SizeOfType(const String& name);
adr_t PeekPtr(adr_t address);
byte PeekByte(adr_t address);
word PeekWord(adr_t address);
dword PeekDword(adr_t address);
Val GetRVal(Val v);
Val DeRef(Val v);
Val Ref(Val v);
int64 GetInt64(Val v);
int GetInt(Val v) { return (int)GetInt64(v); }
double GetFlt(Val v);
void ZeroDiv(double x);
Val Compute(Val v1, Val v2, int oper);
Val RValue(int64 v);
Val Field0(Pdb::Val v, const String& field);
Val Field(Pdb::Val v, const String& field);
Val Term(CParser& p);
Val Post(CParser& p);
Val Unary(CParser& p);
Val Additive(CParser& p);
Val Multiplicative(CParser& p);
Val Compare(Val v, CParser& p, int r1, int r2);
void GetBools(Val v1, Val v2, bool& a, bool& b);
Val LogAnd(CParser& p);
Val LogOr(CParser& p);
Val Comparison(CParser& p);
Val Exp0(CParser& p);
Val Exp(CParser& p);
bool HasAttr(Pdb::Val record, const String& id);
Val GetAttr(Pdb::Val record, int i);
Val GetAttr(Pdb::Val record, const String& id);
int64 GetInt64Attr(Pdb::Val v, const char *a);
int GetIntAttr(Pdb::Val v, const char *a) { return (int)GetInt64Attr(v, a); }
byte GetByteAttr(Pdb::Val v, const char *a) { return (byte)GetInt64Attr(v, a); }
Val At(Pdb::Val val, int i);
Val At(Pdb::Val record, const char *id, int i);
int IntAt(Pdb::Val record, const char *id, int i);
void CatInt(Visual& result, int64 val, dword flags = 0);
enum { MEMBER = 1, RAW = 2 };
void BaseFields(Visual& result, const Type& t, Pdb::Val val, dword flags, bool& cm, int depth);
void Visualise(Visual& result, Pdb::Val val, dword flags);
Visual Visualise(Val v, dword flags = 0);
Visual Visualise(const String& rexp, dword flags = 0);
bool VisualisePretty(Visual& result, Pdb::Val val, dword flags);
bool PrettyVal(Pdb::Val val, int64 from, int count, Pretty& p);
void PrettyString(Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyWString(Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyVector(Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyArray(Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyBiVector(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyBiArray(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyIndex(Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyMap(Pretty& p, Pretty& key, Pretty& value);
void PrettyVectorMap(Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyArrayMap(Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyDate(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyTime(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyColor(Pdb::Val val, const Vector<String>&, int64 from, int count, Pdb::Pretty& p);
void PrettyRGBA(Pdb::Val val, const Vector<String>&, int64 from, int count, Pdb::Pretty& p);
void PrettyImageBuffer(Pdb::Val val, const Vector<String>&, int64 from, int count, Pdb::Pretty& p);
void PrettyImg(Pdb::Val val, const Vector<String>&, int64 from, int count, Pdb::Pretty& p);
void PrettyFont(Pdb::Val val, const Vector<String>&, int64 from, int count, Pdb::Pretty& p);
void PrettyValueArray_(adr_t a, Pdb::Pretty& p);
void PrettyValueArray(Pdb::Val val, const Vector<String>&, int64 from, int count, Pdb::Pretty& p);
void PrettyValue(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pretty& p);
void PrettyValueMap_(adr_t a, Pdb::Pretty& p, int64 from, int count);
void PrettyValueMap(Pdb::Val val, const Vector<String>&, int64 from, int count, Pdb::Pretty& p);
void PrettyStdVector(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyStdString(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void TraverseTree(bool set, Val head, Val node, int64& from, int& count, Pdb::Pretty& p, int depth);
void TraverseTreeClang(bool set, int nodet, Val node, int64& from, int& count, Pdb::Pretty& p, int depth);
void PrettyStdTree(Pdb::Val val, bool set, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyStdListM(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p, bool map = false);
void PrettyStdList(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyStdForwardList(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyStdDeque(Pdb::Val val, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
void PrettyStdUnordered(Pdb::Val val, bool set, const Vector<String>& tparam, int64 from, int count, Pdb::Pretty& p);
// code
Thread& Current();
Array<Frame> Backtrace(Thread& ctx, bool single_frame = false);
int Disassemble(adr_t ip);
bool IsValidFrame(adr_t eip);
void Sync0(Thread& ctx);
void Sync();
void SetThread();
void FrameUpDown(int dir);
void SetFrame();
bool Step(bool over);
void Trace(bool over);
void StepOut();
void DoRunTo() { RunTo(); }
adr_t CursorAdr();
void SetIp();
void Break();
// data
static VectorMap<String, Value> DataMap(const ArrayCtrl& a);
static Value Vis(const String& key, const VectorMap<String, Value>& prev,
Visual&& vis, bool& ch);
static void Vis(ArrayCtrl& a, const String& key,
const VectorMap<String, Value>& prev, Visual&& vis);
void DisasCursor() {}
void DisasFocus() {}
void Locals();
void Watches();
void TryAuto(const String& exp, const VectorMap<String, Value>& prev);
void Autos();
void AddThis(const VectorMap<String, Val>& m, adr_t address, const VectorMap<String, Value>& prev);
void AddThis(int type, adr_t address, const VectorMap<String, Value>& prev);
void This();
void Data();
void ClearWatches();
void DropWatch(PasteClip& clip);
void AddWatch();
void AddWatch(const String& s);
void EditWatch();
void BTs();
void SetTab(int i);
void SetTree(const String& exp);
void SetTreeA(ArrayCtrl *data);
void PrettyTreeNode(int parent, Pdb::Val val, int64 from = 0);
bool TreeNode(int parent, const String& name, Val val, int64 from = 0, Color ink = SColorText(), bool exp = false);
bool TreeNodeExp(int parent, const String& name, Val val, int64 from = 0, Color ink = SColorText());
void TreeExpand(int node);
String GetTreeText(int id);
void GetTreeText(String& r, int id, int depth);
void TreeMenu(Bar& bar);
void TreeWatch();
void StoreTree(StringBuffer& r, int parent);
void SaveTree();
int FindChild(int parent, String id);
void ExpandTreeType(int parent, CParser& p);
void CopyStack();
void CopyStackAll();
void CopyDisas();
void CopyModules();
void MemoryGoto(const String& exp);
void CopyMenu(ArrayCtrl& array, Bar& bar);
void MemMenu(ArrayCtrl& array, Bar& bar, const String& exp);
void DataMenu(ArrayCtrl& array, Bar& bar);
void WatchMenu(Bar& bar, const String& exp);
void WatchesMenu(Bar& bar);
void SyncTreeDisas();
void Tab();
bool Create(One<Host> local, const String& exefile, const String& cmdline, bool clang_);
void SerializeSession(Stream& s);
typedef Pdb CLASSNAME;
Pdb();
virtual ~Pdb();
void LoadGlobals(DWORD64 base);
};
bool EditPDBExpression(const char *title, String& brk, Pdb *pdb);
| 35.493554 | 128 | 0.616406 | [
"vector"
] |
c8fb473b23ec7593c0eb9791f81c9aecc8285938 | 2,083 | c | C | convert/tinymush3/do_detail.c | lashtear/tinymux | f8bc593d77889e8ace0c8a5fd063816bdc65548b | [
"RSA-MD"
] | 2 | 2016-03-26T17:48:50.000Z | 2017-05-23T20:16:15.000Z | convert/tinymush3/do_detail.c | lashtear/tinymux | f8bc593d77889e8ace0c8a5fd063816bdc65548b | [
"RSA-MD"
] | 9 | 2015-01-03T16:01:23.000Z | 2017-05-23T21:51:25.000Z | convert/tinymush3/do_detail.c | lashtear/tinymux | f8bc593d77889e8ace0c8a5fd063816bdc65548b | [
"RSA-MD"
] | 1 | 2016-09-18T16:15:28.000Z | 2016-09-18T16:15:28.000Z | #include <stdio.h>
#include <stdlib.h>
#include <strings.h>
void v_fold_obj(FILE *, int);
void v_fold_atr(FILE *, int, int);
void main(int argc, char **argv)
{
FILE *fp;
int type;
type = atoi(argv[1]);
if ((type == 1) && argv[3] && *argv[3])
{
if ((fp = fopen(argv[3], "r")) == NULL)
{
return;
}
}
else if ((type == 2) && argv[4] && *argv[4])
{
if ((fp = fopen(argv[4], "r")) == NULL)
{
return;
}
}
else
{
return;
}
if (type == 1)
{
v_fold_obj(fp, atoi(argv[2]));
fclose(fp);
return;
}
if (type == 2)
{
v_fold_atr(fp, atoi(argv[2]), atoi(argv[3]));
fclose(fp);
return;
}
}
void v_fold_obj(FILE *fp, int line)
{
char inbuf[10000], obj_buff[100], atr_buff[100];
int cur_line;
cur_line = 0;
memset(inbuf, '\0', sizeof(inbuf));
memset(obj_buff, '\0', sizeof(obj_buff));
memset(atr_buff, '\0', sizeof(atr_buff));
fgets(inbuf, 9999, fp);
while (!feof(fp))
{
cur_line++;
if (inbuf[0] == '!')
{
sprintf(obj_buff, "%.99s", inbuf+1);
}
if (line == cur_line)
{
if (atr_buff[0] != '\0')
{
printf("%d %d\n", atoi(obj_buff), atoi(atr_buff));
}
else
{
printf("%d -1\n", atoi(obj_buff));
}
return;
}
if (inbuf[0] == '>')
{
sprintf(atr_buff, "%.99s", inbuf+1);
}
fgets(inbuf, 9999, fp);
}
}
void v_fold_atr(FILE *fp, int obj, int atr)
{
char inbuf[10000], *atrname_ret, atrname[100];
int found;
if (atr > 255)
{
found = 0;
fgets(inbuf, 9999, fp);
memset(inbuf, '\0', sizeof(inbuf));
memset(atrname, '\0', sizeof(atrname));
sprintf(atrname, "+A%d", atr);
while (!feof(fp))
{
inbuf[strlen(inbuf)-1]='\0';
if (found)
{
inbuf[strlen(inbuf)-1]='\0';
atrname_ret = inbuf+3;
printf(" >Object #%d Attrib: %s\n", obj, atrname_ret);
return;
}
if (strcmp(atrname, inbuf) == 0)
{
found = 1;
}
fgets(inbuf, 9999, fp);
}
}
printf(" >Object #%d INTERNAL Attrib: #%d (refer to attrs.h for attribute)\n", obj, atr);
}
| 17.504202 | 98 | 0.520883 | [
"object"
] |
c8ff41e833e46a341982713bff3a39e5dc034f89 | 11,765 | h | C | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/telephony/SmsCbMessage.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/telephony/SmsCbMessage.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/telephony/SmsCbMessage.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#ifndef __ELASTOS_DROID_TELEPHONY_SMSCBMESSAGE_H__
#define __ELASTOS_DROID_TELEPHONY_SMSCBMESSAGE_H__
#include "Elastos.Droid.Telephony.h"
#include "elastos/droid/ext/frameworkext.h"
#include "elastos/core/Object.h"
namespace Elastos {
namespace Droid {
namespace Telephony {
/**
* Parcelable object containing a received cell broadcast message. There are four different types
* of Cell Broadcast messages:
*
* <ul>
* <li>opt-in informational broadcasts, e.g. news, weather, stock quotes, sports scores</li>
* <li>cell information messages, broadcast on channel 50, indicating the current cell name for
* roaming purposes (required to display on the idle screen in Brazil)</li>
* <li>emergency broadcasts for the Japanese Earthquake and Tsunami Warning System (ETWS)</li>
* <li>emergency broadcasts for the American Commercial Mobile Alert Service (CMAS)</li>
* </ul>
*
* <p>There are also four different CB message formats: GSM, ETWS Primary Notification (GSM only),
* UMTS, and CDMA. Some fields are only applicable for some message formats. Other fields were
* unified under a common name, avoiding some names, such as "Message Identifier", that refer to
* two completely different concepts in 3GPP and CDMA.
*
* <p>The GSM/UMTS Message Identifier field is available via {@link #getServiceCategory}, the name
* of the equivalent field in CDMA. In both cases the service category is a 16-bit value, but 3GPP
* and 3GPP2 have completely different meanings for the respective values. For ETWS and CMAS, the
* application should
*
* <p>The CDMA Message Identifier field is available via {@link #getSerialNumber}, which is used
* to detect the receipt of a duplicate message to be discarded. In CDMA, the message ID is
* unique to the current PLMN. In GSM/UMTS, there is a 16-bit serial number containing a 2-bit
* Geographical Scope field which indicates whether the 10-bit message code and 4-bit update number
* are considered unique to the PLMN, to the current cell, or to the current Location Area (or
* Service Area in UMTS). The relevant values are concatenated into a single String which will be
* unique if the messages are not duplicates.
*
* <p>The SMS dispatcher does not detect duplicate messages. However, it does concatenate the
* pages of a GSM multi-page cell broadcast into a single SmsCbMessage object.
*
* <p>Interested applications with {@code RECEIVE_SMS_PERMISSION} can register to receive
* {@code SMS_CB_RECEIVED_ACTION} broadcast intents for incoming non-emergency broadcasts.
* Only system applications such as the CellBroadcastReceiver may receive notifications for
* emergency broadcasts (ETWS and CMAS). This is intended to prevent any potential for delays or
* interference with the immediate display of the alert message and playing of the alert sound and
* vibration pattern, which could be caused by poorly written or malicious non-system code.
*
* @hide
*/
class SmsCbMessage
: public Object
, public ISmsCbMessage
, public IParcelable
{
public:
CAR_INTERFACE_DECL();
SmsCbMessage();
/**
* Create a new SmsCbMessage with the specified data.
*/
CARAPI constructor(
/* [in] */ Int32 messageFormat,
/* [in] */ Int32 geographicalScope,
/* [in] */ Int32 serialNumber,
/* [in] */ ISmsCbLocation* location,
/* [in] */ Int32 serviceCategory,
/* [in] */ const String& language,
/* [in] */ const String& body,
/* [in] */ Int32 priority,
/* [in] */ ISmsCbEtwsInfo* etwsWarningInfo,
/* [in] */ ISmsCbCmasInfo* cmasWarningInfo);
/** Create a new SmsCbMessage object from a Parcel. */
CARAPI constructor(
/* [in] */ IParcel* in);
CARAPI constructor();
CARAPI WriteToParcel(
/* [in] */ IParcel* dest);
CARAPI ReadFromParcel(
/* [in] */ IParcel* source);
/**
* Return the geographical scope of this message (GSM/UMTS only).
*
* @return Geographical scope
*/
virtual CARAPI GetGeographicalScope(
/* [out] */ Int32* result);
/**
* Return the broadcast serial number of broadcast (message identifier for CDMA, or
* geographical scope + message code + update number for GSM/UMTS). The serial number plus
* the location code uniquely identify a cell broadcast for duplicate detection.
*
* @return the 16-bit CDMA message identifier or GSM/UMTS serial number
*/
virtual CARAPI GetSerialNumber(
/* [out] */ Int32* result);
/**
* Return the location identifier for this message, consisting of the MCC/MNC as a
* 5 or 6-digit decimal string. In addition, for GSM/UMTS, if the Geographical Scope of the
* message is not binary 01, the Location Area is included. If the GS is 00 or 11, the
* cell ID is also included. The {@link SmsCbLocation} object includes a method to test
* if the location is included within another location area or within a PLMN and CellLocation.
*
* @return the geographical location code for duplicate message detection
*/
virtual CARAPI GetLocation(
/* [out] */ ISmsCbLocation** result);
/**
* Return the 16-bit CDMA service category or GSM/UMTS message identifier. The interpretation
* of the category is radio technology specific. For ETWS and CMAS warnings, the information
* provided by the category is available via {@link #getEtwsWarningInfo()} or
* {@link #getCmasWarningInfo()} in a radio technology independent format.
*
* @return the radio technology specific service category
*/
virtual CARAPI GetServiceCategory(
/* [out] */ Int32* result);
/**
* Get the ISO-639-1 language code for this message, or null if unspecified
*
* @return Language code
*/
virtual CARAPI GetLanguageCode(
/* [out] */ String* result);
/**
* Get the body of this message, or null if no body available
*
* @return Body, or null
*/
virtual CARAPI GetMessageBody(
/* [out] */ String* result);
/**
* Get the message format ({@link #MESSAGE_FORMAT_3GPP} or {@link #MESSAGE_FORMAT_3GPP2}).
* @return an integer representing 3GPP or 3GPP2 message format
*/
virtual CARAPI GetMessageFormat(
/* [out] */ Int32* result);
/**
* Get the message priority. Normal broadcasts return {@link #MESSAGE_PRIORITY_NORMAL}
* and emergency broadcasts return {@link #MESSAGE_PRIORITY_EMERGENCY}. CDMA also may return
* {@link #MESSAGE_PRIORITY_INTERACTIVE} or {@link #MESSAGE_PRIORITY_URGENT}.
* @return an integer representing the message priority
*/
virtual CARAPI GetMessagePriority(
/* [out] */ Int32* result);
/**
* If this is an ETWS warning notification then this method will return an object containing
* the ETWS warning type, the emergency user alert flag, and the popup flag. If this is an
* ETWS primary notification (GSM only), there will also be a 7-byte timestamp and 43-byte
* digital signature. As of Release 10, 3GPP TS 23.041 states that the UE shall ignore the
* ETWS primary notification timestamp and digital signature if received.
*
* @return an SmsCbEtwsInfo object, or null if this is not an ETWS warning notification
*/
virtual CARAPI GetEtwsWarningInfo(
/* [out] */ ISmsCbEtwsInfo** result);
/**
* If this is a CMAS warning notification then this method will return an object containing
* the CMAS message class, category, response type, severity, urgency and certainty.
* The message class is always present. Severity, urgency and certainty are present for CDMA
* warning notifications containing a type 1 elements record and for GSM and UMTS warnings
* except for the Presidential-level alert category. Category and response type are only
* available for CDMA notifications containing a type 1 elements record.
*
* @return an SmsCbCmasInfo object, or null if this is not a CMAS warning notification
*/
virtual CARAPI GetCmasWarningInfo(
/* [out] */ ISmsCbCmasInfo** result);
/**
* Return whether this message is an emergency (PWS) message type.
* @return true if the message is a public warning notification; false otherwise
*/
virtual CARAPI IsEmergencyMessage(
/* [out] */ Boolean* result);
/**
* Return whether this message is an ETWS warning alert.
* @return true if the message is an ETWS warning notification; false otherwise
*/
virtual CARAPI IsEtwsMessage(
/* [out] */ Boolean* result);
/**
* Return whether this message is a CMAS warning alert.
* @return true if the message is a CMAS warning notification; false otherwise
*/
virtual CARAPI IsCmasMessage(
/* [out] */ Boolean* result);
// @Override
CARAPI ToString(
/* [out] */ String* str);
protected:
static const String LOGTAG;
private:
/** Format of this message (for interpretation of service category values). */
/*const*/ Int32 mMessageFormat;
/** Geographical scope of broadcast. */
/*const*/ Int32 mGeographicalScope;
/**
* Serial number of broadcast (message identifier for CDMA, geographical scope + message code +
* update number for GSM/UMTS). The serial number plus the location code uniquely identify
* a cell broadcast for duplicate detection.
*/
/*const*/ Int32 mSerialNumber;
/**
* Location identifier for this message. It consists of the current operator MCC/MNC as a
* 5 or 6-digit decimal string. In addition, for GSM/UMTS, if the Geographical Scope of the
* message is not binary 01, the Location Area is included for comparison. If the GS is
* 00 or 11, the Cell ID is also included. LAC and Cell ID are -1 if not specified.
*/
/*const*/ AutoPtr<ISmsCbLocation> mLocation;
/**
* 16-bit CDMA service category or GSM/UMTS message identifier. For ETWS and CMAS warnings,
* the information provided by the category is also available via {@link #getEtwsWarningInfo()}
* or {@link #getCmasWarningInfo()}.
*/
/*const*/ Int32 mServiceCategory;
/** Message language, as a two-character string, e.g. "en". */
/*const*/ String mLanguage;
/** Message body, as a String. */
/*const*/ String mBody;
/** Message priority (including emergency priority). */
/*const*/ Int32 mPriority;
/** ETWS warning notification information (ETWS warnings only). */
/*const*/ AutoPtr<ISmsCbEtwsInfo> mEtwsWarningInfo;
/** CMAS warning notification information (CMAS warnings only). */
/*const*/ AutoPtr<ISmsCbCmasInfo> mCmasWarningInfo;
};
} // namespace Telephony
} // namespace Droid
} // namespace Elastos
#endif // __ELASTOS_DROID_TELEPHONY_SMSCBMESSAGE_H__
| 42.781818 | 100 | 0.678708 | [
"object"
] |
7400337912dc3f0d14ca1ebc474af41ff29e908a | 336,661 | c | C | src/bin/e_border.c | Elive/enlightenment | 0a5ff4bd5adea88f70347354eabd93fdad63eed6 | [
"BSD-2-Clause"
] | 3 | 2019-03-16T11:11:24.000Z | 2021-03-23T17:10:52.000Z | src/bin/e_border.c | Elive/enlightenment | 0a5ff4bd5adea88f70347354eabd93fdad63eed6 | [
"BSD-2-Clause"
] | 2 | 2017-03-03T06:45:52.000Z | 2018-04-22T20:11:17.000Z | src/bin/e_border.c | Elive/enlightenment | 0a5ff4bd5adea88f70347354eabd93fdad63eed6 | [
"BSD-2-Clause"
] | 1 | 2018-04-06T10:06:39.000Z | 2018-04-06T10:06:39.000Z | #include "e.h"
//#define INOUTDEBUG_MOUSE 1
//#define INOUTDEBUG_FOCUS 1
/* These are compatible with netwm */
#define RESIZE_TL 0
#define RESIZE_T 1
#define RESIZE_TR 2
#define RESIZE_R 3
#define RESIZE_BR 4
#define RESIZE_B 5
#define RESIZE_BL 6
#define RESIZE_L 7
#define MOVE 8
#define RESIZE_NONE 11
/* local subsystem functions */
static void _e_border_pri_raise(E_Border *bd);
static void _e_border_pri_norm(E_Border *bd);
static void _e_border_free(E_Border *bd);
static void _e_border_del(E_Border *bd);
#ifdef PRINT_LOTS_OF_DEBUG
#define E_PRINT_BORDER_INFO(X) \
_e_border_print(X, __PRETTY_FUNC__)
static void _e_border_print(E_Border *bd,
const char *func);
#endif
/* FIXME: these likely belong in a separate icccm/client handler */
/* and the border needs to become a dumb object that just does what its */
/* told to do */
static Eina_Bool _e_border_cb_window_show_request(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_destroy(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_hide(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_reparent(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_configure_request(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_resize_request(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_gravity(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_stack_request(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_property(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_colormap(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_shape(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_focus_in(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_focus_out(void *data,
int ev_type,
void *ev);
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
static Eina_Bool _e_border_cb_client_message(void *data,
int ev_type,
void *ev);
#endif
static Eina_Bool _e_border_cb_window_state_request(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_window_move_resize_request(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_desktop_change(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_sync_alarm(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_efreet_cache_update(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_config_icon_theme(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_config_mode(void *data,
int ev_type,
void *ev);
static Eina_Bool _e_border_cb_pointer_warp(void *data,
int ev_type,
void *ev);
static void _e_border_cb_signal_bind(void *data,
Evas_Object *obj,
const char *emission,
const char *source);
static Eina_Bool _e_border_cb_mouse_in(void *data,
int type,
void *event);
static Eina_Bool _e_border_cb_mouse_out(void *data,
int type,
void *event);
static Eina_Bool _e_border_cb_mouse_wheel(void *data,
int type,
void *event);
static Eina_Bool _e_border_cb_mouse_down(void *data,
int type,
void *event);
static Eina_Bool _e_border_cb_mouse_up(void *data,
int type,
void *event);
static Eina_Bool _e_border_cb_mouse_move(void *data,
int type,
void *event);
static Eina_Bool _e_border_cb_grab_replay(void *data,
int type,
void *event);
static void _e_border_cb_drag_finished(E_Drag *drag,
int dropped);
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
static Eina_Bool _e_border_cb_desk_window_profile_change(void *data,
int ev_type,
void *ev);
#endif
static void _e_border_eval(E_Border *bd);
static void _e_border_eval0(E_Border *bd);
static void _e_border_container_layout_hook(E_Container *con);
static void _e_border_moveinfo_gather(E_Border *bd,
const char *source);
static void _e_border_resize_handle(E_Border *bd);
static Eina_Bool _e_border_shade_animator(void *data);
static void _e_border_event_border_add_free(void *data,
void *ev);
static void _e_border_event_border_remove_free(void *data,
void *ev);
static void _e_border_event_border_zone_set_free(void *data,
void *ev);
static void _e_border_event_border_desk_set_free(void *data,
void *ev);
static void _e_border_event_border_stack_free(void *data,
void *ev);
static void _e_border_event_border_icon_change_free(void *data,
void *ev);
static void _e_border_event_border_urgent_change_free(void *data,
void *ev);
static void _e_border_event_border_focus_in_free(void *data,
void *ev);
static void _e_border_event_border_focus_out_free(void *data,
void *ev);
static void _e_border_event_border_resize_free(void *data,
void *ev);
static void _e_border_event_border_move_free(void *data,
void *ev);
static void _e_border_event_border_show_free(void *data,
void *ev);
static void _e_border_event_border_hide_free(void *data,
void *ev);
static void _e_border_event_border_iconify_free(void *data,
void *ev);
static void _e_border_event_border_uniconify_free(void *data,
void *ev);
static void _e_border_event_border_stick_free(void *data,
void *ev);
static void _e_border_event_border_unstick_free(void *data,
void *ev);
static void _e_border_event_border_property_free(void *data,
void *ev);
static void _e_border_event_border_fullscreen_free(void *data,
void *ev);
static void _e_border_event_border_unfullscreen_free(void *data,
void *ev);
static void _e_border_zone_update(E_Border *bd);
static int _e_border_resize_begin(E_Border *bd);
static int _e_border_resize_end(E_Border *bd);
static void _e_border_resize_update(E_Border *bd);
static int _e_border_move_begin(E_Border *bd);
static int _e_border_move_end(E_Border *bd);
static void _e_border_move_update(E_Border *bd);
static Eina_Bool _e_border_cb_ping_poller(void *data);
static Eina_Bool _e_border_cb_kill_timer(void *data);
static void _e_border_pointer_resize_begin(E_Border *bd);
static void _e_border_pointer_resize_end(E_Border *bd);
static void _e_border_pointer_move_begin(E_Border *bd);
static void _e_border_pointer_move_end(E_Border *bd);
static void _e_border_hook_call(E_Border_Hook_Point hookpoint,
void *bd);
static void _e_border_client_move_resize_send(E_Border *bd);
static void _e_border_frame_replace(E_Border *bd,
Eina_Bool argb);
static void _e_border_shape_input_rectangle_set(E_Border *bd);
static void _e_border_show(E_Border *bd);
static void _e_border_hide(E_Border *bd);
static void _e_border_move_lost_window_to_center(E_Border *bd);
static void _e_border_reset_lost_window(E_Border *bd);
static Eina_Bool _e_border_pointer_warp_to_center_timer(void *data);
/* local subsystem globals */
static Eina_List *handlers = NULL;
static Eina_List *borders = NULL;
static Eina_Hash *borders_hash = NULL;
static E_Border *focused = NULL;
static E_Border *focusing = NULL;
static Eina_List *focus_next = NULL;
static Ecore_X_Time focus_time = 0;
static E_Border *bdresize = NULL;
static E_Border *bdmove = NULL;
static E_Drag *drag_border = NULL;
static int grabbed = 0;
static Eina_List *focus_stack = NULL;
static Eina_List *raise_stack = NULL;
static E_Border *warp_timer_border = NULL;
static Eina_Bool focus_locked = EINA_FALSE;
static Ecore_X_Randr_Screen_Size screen_size = { -1, -1 };
static int screen_size_index = -1;
static int focus_track_frozen = 0;
static int warp_to = 0;
static int warp_to_x = 0;
static int warp_to_y = 0;
static int warp_x[2] = {0}; //{cur,prev}
static int warp_y[2] = {0}; //{cur,prev}
static Ecore_X_Window warp_to_win;
static Ecore_Timer *warp_timer = NULL;
EAPI int E_EVENT_BORDER_ADD = 0;
EAPI int E_EVENT_BORDER_REMOVE = 0;
EAPI int E_EVENT_BORDER_ZONE_SET = 0;
EAPI int E_EVENT_BORDER_DESK_SET = 0;
EAPI int E_EVENT_BORDER_RESIZE = 0;
EAPI int E_EVENT_BORDER_MOVE = 0;
EAPI int E_EVENT_BORDER_SHOW = 0;
EAPI int E_EVENT_BORDER_HIDE = 0;
EAPI int E_EVENT_BORDER_ICONIFY = 0;
EAPI int E_EVENT_BORDER_UNICONIFY = 0;
EAPI int E_EVENT_BORDER_STICK = 0;
EAPI int E_EVENT_BORDER_UNSTICK = 0;
EAPI int E_EVENT_BORDER_STACK = 0;
EAPI int E_EVENT_BORDER_ICON_CHANGE = 0;
EAPI int E_EVENT_BORDER_URGENT_CHANGE = 0;
EAPI int E_EVENT_BORDER_FOCUS_IN = 0;
EAPI int E_EVENT_BORDER_FOCUS_OUT = 0;
EAPI int E_EVENT_BORDER_PROPERTY = 0;
EAPI int E_EVENT_BORDER_FULLSCREEN = 0;
EAPI int E_EVENT_BORDER_UNFULLSCREEN = 0;
#define GRAV_SET(bd, grav) \
ecore_x_window_gravity_set(bd->bg_win, grav); \
ecore_x_window_gravity_set(bd->client.shell_win, grav); \
if (bd->client.lock_win) ecore_x_window_gravity_set(bd->client.lock_win, grav); \
ecore_x_window_gravity_set(bd->client.win, grav);
static Eina_List *
_e_border_sub_borders_new(E_Border *bd)
{
Eina_List *list = NULL, *l;
E_Border *child;
EINA_LIST_FOREACH(bd->transients, l, child)
{
if (!eina_list_data_find(list, child))
list = eina_list_append(list, child);
}
return list;
}
/* externally accessible functions */
EINTERN int
e_border_init(void)
{
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_SHOW_REQUEST,
_e_border_cb_window_show_request, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_DESTROY,
_e_border_cb_window_destroy, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_HIDE,
_e_border_cb_window_hide, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_REPARENT,
_e_border_cb_window_reparent, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_CONFIGURE_REQUEST,
_e_border_cb_window_configure_request, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_RESIZE_REQUEST,
_e_border_cb_window_resize_request, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_GRAVITY,
_e_border_cb_window_gravity, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_STACK_REQUEST,
_e_border_cb_window_stack_request, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_PROPERTY,
_e_border_cb_window_property, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_COLORMAP,
_e_border_cb_window_colormap, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_SHAPE,
_e_border_cb_window_shape, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_FOCUS_IN,
_e_border_cb_window_focus_in, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_FOCUS_OUT,
_e_border_cb_window_focus_out, NULL);
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_CLIENT_MESSAGE,
_e_border_cb_client_message, NULL);
#endif
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_STATE_REQUEST,
_e_border_cb_window_state_request, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_WINDOW_MOVE_RESIZE_REQUEST,
_e_border_cb_window_move_resize_request, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_DESKTOP_CHANGE,
_e_border_cb_desktop_change, NULL);
E_LIST_HANDLER_APPEND(handlers, ECORE_X_EVENT_SYNC_ALARM,
_e_border_cb_sync_alarm, NULL);
ecore_x_passive_grab_replay_func_set(_e_border_cb_grab_replay, NULL);
E_LIST_HANDLER_APPEND(handlers, E_EVENT_POINTER_WARP,
_e_border_cb_pointer_warp, NULL);
E_LIST_HANDLER_APPEND(handlers, EFREET_EVENT_DESKTOP_CACHE_UPDATE,
_e_border_cb_efreet_cache_update, NULL);
E_LIST_HANDLER_APPEND(handlers, EFREET_EVENT_ICON_CACHE_UPDATE,
_e_border_cb_efreet_cache_update, NULL);
E_LIST_HANDLER_APPEND(handlers, E_EVENT_CONFIG_ICON_THEME,
_e_border_cb_config_icon_theme, NULL);
E_LIST_HANDLER_APPEND(handlers, E_EVENT_CONFIG_MODE_CHANGED,
_e_border_cb_config_mode, NULL);
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
E_LIST_HANDLER_APPEND(handlers, E_EVENT_DESK_WINDOW_PROFILE_CHANGE,
_e_border_cb_desk_window_profile_change, NULL);
#endif
if (!borders_hash) borders_hash = eina_hash_string_superfast_new(NULL);
E_EVENT_BORDER_ADD = ecore_event_type_new();
E_EVENT_BORDER_REMOVE = ecore_event_type_new();
E_EVENT_BORDER_DESK_SET = ecore_event_type_new();
E_EVENT_BORDER_ZONE_SET = ecore_event_type_new();
E_EVENT_BORDER_RESIZE = ecore_event_type_new();
E_EVENT_BORDER_MOVE = ecore_event_type_new();
E_EVENT_BORDER_SHOW = ecore_event_type_new();
E_EVENT_BORDER_HIDE = ecore_event_type_new();
E_EVENT_BORDER_ICONIFY = ecore_event_type_new();
E_EVENT_BORDER_UNICONIFY = ecore_event_type_new();
E_EVENT_BORDER_STICK = ecore_event_type_new();
E_EVENT_BORDER_UNSTICK = ecore_event_type_new();
E_EVENT_BORDER_STACK = ecore_event_type_new();
E_EVENT_BORDER_ICON_CHANGE = ecore_event_type_new();
E_EVENT_BORDER_URGENT_CHANGE = ecore_event_type_new();
E_EVENT_BORDER_FOCUS_IN = ecore_event_type_new();
E_EVENT_BORDER_FOCUS_OUT = ecore_event_type_new();
E_EVENT_BORDER_PROPERTY = ecore_event_type_new();
E_EVENT_BORDER_FULLSCREEN = ecore_event_type_new();
E_EVENT_BORDER_UNFULLSCREEN = ecore_event_type_new();
// e_init_undone();
return 1;
}
EINTERN int
e_border_shutdown(void)
{
E_FREE_LIST(handlers, ecore_event_handler_del);
if (borders_hash) eina_hash_free(borders_hash);
borders_hash = NULL;
e_int_border_menu_hooks_clear();
focus_locked = EINA_FALSE;
warp_timer_border = NULL;
return 1;
}
EAPI void
e_border_focus_lock_set(Eina_Bool lock)
{
focus_locked = !!lock;
}
EAPI Eina_Bool
e_border_focus_lock_get(void)
{
return focus_locked;
}
EAPI E_Border *
e_border_new(E_Container *con,
Ecore_X_Window win,
int first_map,
int internal)
{
E_Border *bd, *bd2;
Ecore_X_Window_Attributes *att;
unsigned int managed, desk[2];
int deskx, desky;
bd = E_OBJECT_ALLOC(E_Border, E_BORDER_TYPE, _e_border_free);
if (!bd) return NULL;
ecore_x_window_shadow_tree_flush();
e_object_del_func_set(E_OBJECT(bd), E_OBJECT_CLEANUP_FUNC(_e_border_del));
bd->focus_policy_override = E_FOCUS_LAST;
bd->w = 1;
bd->h = 1;
/* FIXME: ewww - round trip */
bd->client.argb = ecore_x_window_argb_get(win);
if (bd->client.argb)
bd->win = ecore_x_window_manager_argb_new(con->win, 0, 0, bd->w, bd->h);
else
{
bd->win = ecore_x_window_override_new(con->win, 0, 0, bd->w, bd->h);
ecore_x_window_shape_events_select(bd->win, 1);
}
e_bindings_mouse_grab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_bindings_wheel_grab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_focus_setup(bd);
bd->bg_ecore_evas = e_canvas_new(bd->win,
0, 0, bd->w, bd->h, 1, 0,
&(bd->bg_win));
ecore_evas_ignore_events_set(bd->bg_ecore_evas, EINA_TRUE);
e_canvas_add(bd->bg_ecore_evas);
bd->event_win = ecore_x_window_input_new(bd->win, 0, 0, bd->w, bd->h);
bd->bg_evas = ecore_evas_get(bd->bg_ecore_evas);
ecore_x_window_shape_events_select(bd->bg_win, 1);
ecore_evas_name_class_set(bd->bg_ecore_evas, "E", "Frame_Window");
ecore_evas_title_set(bd->bg_ecore_evas, "Enlightenment Frame");
if (bd->client.argb)
bd->client.shell_win = ecore_x_window_manager_argb_new(bd->win, 0, 0, 1, 1);
else
bd->client.shell_win = ecore_x_window_override_new(bd->win, 0, 0, 1, 1);
ecore_x_window_container_manage(bd->client.shell_win);
if (!internal) ecore_x_window_client_manage(win);
/* FIXME: Round trip. XCB */
/* fetch needed to avoid grabbing the server as window may vanish */
att = &bd->client.initial_attributes;
if ((!ecore_x_window_attributes_get(win, att)) || (att->input_only))
{
// printf("##- ATTR FETCH FAILED/INPUT ONLY FOR 0x%x - ABORT MANAGE\n", win);
e_canvas_del(bd->bg_ecore_evas);
ecore_evas_free(bd->bg_ecore_evas);
ecore_x_window_free(bd->client.shell_win);
e_bindings_mouse_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_bindings_wheel_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
ecore_x_window_free(bd->win);
free(bd);
return NULL;
}
/* printf("##- ON MAP CLIENT 0x%x SIZE %ix%i %i:%i\n",
* bd->client.win, bd->client.w, bd->client.h, att->x, att->y); */
/* FIXME: if first_map is 1 then we should ignore the first hide event
* or ensure the window is already hidden and events flushed before we
* create a border for it */
if (first_map)
{
// printf("##- FIRST MAP\n");
bd->x = att->x;
bd->y = att->y;
bd->changes.pos = 1;
bd->re_manage = 1;
// needed to be 1 for internal windw and on restart.
// bd->ignore_first_unmap = 2;
}
bd->client.win = win;
bd->zone = e_zone_current_get(con);
_e_border_hook_call(E_BORDER_HOOK_NEW_BORDER, bd);
E_LIST_HANDLER_APPEND(bd->handlers, ECORE_X_EVENT_MOUSE_IN,
_e_border_cb_mouse_in, bd);
E_LIST_HANDLER_APPEND(bd->handlers, ECORE_X_EVENT_MOUSE_OUT,
_e_border_cb_mouse_out, bd);
E_LIST_HANDLER_APPEND(bd->handlers, ECORE_EVENT_MOUSE_BUTTON_DOWN,
_e_border_cb_mouse_down, bd);
E_LIST_HANDLER_APPEND(bd->handlers, ECORE_EVENT_MOUSE_BUTTON_UP,
_e_border_cb_mouse_up, bd);
E_LIST_HANDLER_APPEND(bd->handlers, ECORE_EVENT_MOUSE_MOVE,
_e_border_cb_mouse_move, bd);
E_LIST_HANDLER_APPEND(bd->handlers, ECORE_EVENT_MOUSE_WHEEL,
_e_border_cb_mouse_wheel, bd);
bd->client.icccm.title = NULL;
bd->client.icccm.name = NULL;
bd->client.icccm.class = NULL;
bd->client.icccm.icon_name = NULL;
bd->client.icccm.machine = NULL;
bd->client.icccm.min_w = 1;
bd->client.icccm.min_h = 1;
bd->client.icccm.max_w = 32767;
bd->client.icccm.max_h = 32767;
bd->client.icccm.base_w = 0;
bd->client.icccm.base_h = 0;
bd->client.icccm.step_w = -1;
bd->client.icccm.step_h = -1;
bd->client.icccm.min_aspect = 0.0;
bd->client.icccm.max_aspect = 0.0;
bd->client.icccm.accepts_focus = 1;
bd->client.netwm.pid = 0;
bd->client.netwm.name = NULL;
bd->client.netwm.icon_name = NULL;
bd->client.netwm.desktop = 0;
bd->client.netwm.state.modal = 0;
bd->client.netwm.state.sticky = 0;
bd->client.netwm.state.shaded = 0;
bd->client.netwm.state.hidden = 0;
bd->client.netwm.state.maximized_v = 0;
bd->client.netwm.state.maximized_h = 0;
bd->client.netwm.state.skip_taskbar = 0;
bd->client.netwm.state.skip_pager = 0;
bd->client.netwm.state.fullscreen = 0;
bd->client.netwm.state.stacking = E_STACKING_NONE;
bd->client.netwm.action.move = 0;
bd->client.netwm.action.resize = 0;
bd->client.netwm.action.minimize = 0;
bd->client.netwm.action.shade = 0;
bd->client.netwm.action.stick = 0;
bd->client.netwm.action.maximized_h = 0;
bd->client.netwm.action.maximized_v = 0;
bd->client.netwm.action.fullscreen = 0;
bd->client.netwm.action.change_desktop = 0;
bd->client.netwm.action.close = 0;
bd->client.netwm.type = ECORE_X_WINDOW_TYPE_UNKNOWN;
{
int at_num = 0, i;
Ecore_X_Atom *atoms;
atoms = ecore_x_window_prop_list(bd->client.win, &at_num);
bd->client.icccm.fetch.command = 1;
if (atoms)
{
Eina_Bool video_parent = EINA_FALSE;
Eina_Bool video_position = EINA_FALSE;
/* icccm */
for (i = 0; i < at_num; i++)
{
if (atoms[i] == ECORE_X_ATOM_WM_NAME)
bd->client.icccm.fetch.title = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_CLASS)
bd->client.icccm.fetch.name_class = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_ICON_NAME)
bd->client.icccm.fetch.icon_name = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_CLIENT_MACHINE)
bd->client.icccm.fetch.machine = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_HINTS)
bd->client.icccm.fetch.hints = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_NORMAL_HINTS)
bd->client.icccm.fetch.size_pos_hints = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_PROTOCOLS)
bd->client.icccm.fetch.protocol = 1;
else if (atoms[i] == ECORE_X_ATOM_MOTIF_WM_HINTS)
bd->client.mwm.fetch.hints = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_TRANSIENT_FOR)
{
bd->client.icccm.fetch.transient_for = 1;
bd->client.netwm.fetch.type = 1;
}
else if (atoms[i] == ECORE_X_ATOM_WM_CLIENT_LEADER)
bd->client.icccm.fetch.client_leader = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_WINDOW_ROLE)
bd->client.icccm.fetch.window_role = 1;
else if (atoms[i] == ECORE_X_ATOM_WM_STATE)
bd->client.icccm.fetch.state = 1;
}
/* netwm, loop again, netwm will ignore some icccm, so we
* have to be sure that netwm is checked after */
for (i = 0; i < at_num; i++)
{
if (atoms[i] == ECORE_X_ATOM_NET_WM_NAME)
{
/* Ignore icccm */
bd->client.icccm.fetch.title = 0;
bd->client.netwm.fetch.name = 1;
}
else if (atoms[i] == ECORE_X_ATOM_NET_WM_ICON_NAME)
{
/* Ignore icccm */
bd->client.icccm.fetch.icon_name = 0;
bd->client.netwm.fetch.icon_name = 1;
}
else if (atoms[i] == ECORE_X_ATOM_NET_WM_ICON)
{
bd->client.netwm.fetch.icon = 1;
}
else if (atoms[i] == ECORE_X_ATOM_NET_WM_USER_TIME)
{
bd->client.netwm.fetch.user_time = 1;
}
else if (atoms[i] == ECORE_X_ATOM_NET_WM_STRUT)
{
DBG("ECORE_X_ATOM_NET_WM_STRUT");
bd->client.netwm.fetch.strut = 1;
}
else if (atoms[i] == ECORE_X_ATOM_NET_WM_STRUT_PARTIAL)
{
DBG("ECORE_X_ATOM_NET_WM_STRUT_PARTIAL");
bd->client.netwm.fetch.strut = 1;
}
else if (atoms[i] == ECORE_X_ATOM_NET_WM_WINDOW_TYPE)
{
/* Ignore mwm
bd->client.mwm.fetch.hints = 0;
*/
bd->client.netwm.fetch.type = 1;
}
else if (atoms[i] == ECORE_X_ATOM_NET_WM_STATE)
{
bd->client.netwm.fetch.state = 1;
}
}
/* other misc atoms */
for (i = 0; i < at_num; i++)
{
/* loop to check for own atoms */
if (atoms[i] == E_ATOM_WINDOW_STATE)
{
bd->client.e.fetch.state = 1;
}
/* loop to check for qtopia atoms */
if (atoms[i] == ATM__QTOPIA_SOFT_MENU)
bd->client.qtopia.fetch.soft_menu = 1;
else if (atoms[i] == ATM__QTOPIA_SOFT_MENUS)
bd->client.qtopia.fetch.soft_menus = 1;
/* loop to check for vkbd atoms */
else if (atoms[i] == ECORE_X_ATOM_E_VIRTUAL_KEYBOARD_STATE)
bd->client.vkbd.fetch.state = 1;
else if (atoms[i] == ECORE_X_ATOM_E_VIRTUAL_KEYBOARD)
bd->client.vkbd.fetch.vkbd = 1;
/* loop to check for illume atoms */
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_CONFORMANT)
bd->client.illume.conformant.fetch.conformant = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_STATE)
bd->client.illume.quickpanel.fetch.state = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_QUICKPANEL)
bd->client.illume.quickpanel.fetch.quickpanel = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_PRIORITY_MAJOR)
bd->client.illume.quickpanel.fetch.priority.major = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_PRIORITY_MINOR)
bd->client.illume.quickpanel.fetch.priority.minor = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_ZONE)
bd->client.illume.quickpanel.fetch.zone = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_DRAG_LOCKED)
bd->client.illume.drag.fetch.locked = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_DRAG)
bd->client.illume.drag.fetch.drag = 1;
else if (atoms[i] == ECORE_X_ATOM_E_ILLUME_WINDOW_STATE)
bd->client.illume.win_state.fetch.state = 1;
else if (atoms[i] == ECORE_X_ATOM_E_VIDEO_PARENT)
video_parent = EINA_TRUE;
else if (atoms[i] == ECORE_X_ATOM_E_VIDEO_POSITION)
video_position = EINA_TRUE;
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
/* loop to check for window profile list atom */
else if (atoms[i] == ECORE_X_ATOM_E_WINDOW_PROFILE_SUPPORTED)
bd->client.e.fetch.profile = 1;
#endif
}
if (video_position && video_parent)
{
bd->client.e.state.video = 1;
bd->client.e.fetch.video_parent = 1;
bd->client.e.fetch.video_position = 1;
ecore_x_window_lower(bd->win);
ecore_x_composite_window_events_disable(bd->win);
ecore_x_window_ignore_set(bd->win, EINA_TRUE);
fprintf(stderr, "We found a video window \\o/ %x\n", win);
}
free(atoms);
}
}
bd->client.border.changed = 1;
bd->client.w = att->w;
bd->client.h = att->h;
bd->w = bd->client.w;
bd->h = bd->client.h;
bd->resize_mode = RESIZE_NONE;
bd->layer = 100;
bd->saved.layer = bd->layer;
bd->changes.icon = 1;
bd->changes.size = 1;
bd->changes.shape = 1;
bd->changes.shape_input = 1;
bd->offer_resistance = 1;
/* just to friggin make java happy - we're DELAYING the reparent until
* eval time...
*/
/* ecore_x_window_reparent(win, bd->client.shell_win, 0, 0); */
bd->need_reparent = 1;
ecore_x_window_border_width_set(win, 0);
ecore_x_window_show(bd->event_win);
ecore_x_window_show(bd->client.shell_win);
bd->shape = e_container_shape_add(con);
bd->take_focus = 1;
bd->new_client = 1;
bd->changed = 1;
// bd->zone = e_zone_current_get(con);
bd->desk = e_desk_current_get(bd->zone);
e_container_border_add(bd);
borders = eina_list_append(borders, bd);
bd2 = eina_hash_find(borders_hash, e_util_winid_str_get(bd->client.win));
if (bd2)
{
#ifdef E_LOGGING
WRN("EEEEK! 2 borders with same client window id in them! very bad!\n"
"optimisations failing due to bizarre client behavior. will\n"
"work around.\n"
"bd=%p, bd->references=%i, bd->deleted=%i, bd->client.win=%x",
bd2, bd2->e_obj_inherit.references, bd2->e_obj_inherit.deleted,
bd2->client.win);
#else
printf("EEEEK! 2 borders with same client window id in them! very bad!\n");
printf("optimisations failing due to bizarre client behavior. will\n");
printf("work around.\n");
printf("bd=%p, bd->references=%i, bd->deleted=%i, bd->client.win=%x\n",
bd2, bd2->e_obj_inherit.references, bd2->e_obj_inherit.deleted,
bd2->client.win);
#endif
eina_hash_del(borders_hash, e_util_winid_str_get(bd->client.win), bd2);
eina_hash_del(borders_hash, e_util_winid_str_get(bd2->bg_win), bd2);
eina_hash_del(borders_hash, e_util_winid_str_get(bd2->win), bd2);
}
eina_hash_add(borders_hash, e_util_winid_str_get(bd->client.win), bd);
eina_hash_add(borders_hash, e_util_winid_str_get(bd->bg_win), bd);
eina_hash_add(borders_hash, e_util_winid_str_get(bd->win), bd);
managed = 1;
ecore_x_window_prop_card32_set(win, E_ATOM_MANAGED, &managed, 1);
ecore_x_window_prop_card32_set(win, E_ATOM_CONTAINER, &bd->zone->container->num, 1);
ecore_x_window_prop_card32_set(win, E_ATOM_ZONE, &bd->zone->num, 1);
{
unsigned int zgeom[4];
zgeom[0] = bd->zone->x;
zgeom[1] = bd->zone->y;
zgeom[2] = bd->zone->w;
zgeom[3] = bd->zone->h;
ecore_x_window_prop_card32_set(win, E_ATOM_ZONE_GEOMETRY, zgeom, 4);
}
e_desk_xy_get(bd->desk, &deskx, &desky);
desk[0] = deskx;
desk[1] = desky;
ecore_x_window_prop_card32_set(win, E_ATOM_DESK, desk, 2);
focus_stack = eina_list_append(focus_stack, bd);
bd->pointer = e_pointer_window_new(bd->win, 0);
return bd;
}
EAPI void
e_border_res_change_geometry_save(E_Border *bd)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->pre_res_change.valid) return;
bd->pre_res_change.valid = 1;
bd->pre_res_change.x = bd->x;
bd->pre_res_change.y = bd->y;
bd->pre_res_change.w = bd->w;
bd->pre_res_change.h = bd->h;
bd->pre_res_change.saved.x = bd->saved.x;
bd->pre_res_change.saved.y = bd->saved.y;
bd->pre_res_change.saved.w = bd->saved.w;
bd->pre_res_change.saved.h = bd->saved.h;
}
EAPI void
e_border_res_change_geometry_restore(E_Border *bd)
{
struct
{
unsigned char valid : 1;
int x, y, w, h;
struct
{
int x, y, w, h;
} saved;
} pre_res_change;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (!bd->pre_res_change.valid) return;
if (bd->new_client) return;
ecore_x_window_shadow_tree_flush();
memcpy(&pre_res_change, &bd->pre_res_change, sizeof(pre_res_change));
if (bd->fullscreen)
{
e_border_unfullscreen(bd);
e_border_fullscreen(bd, e_config->fullscreen_policy);
}
else if (bd->maximized != E_MAXIMIZE_NONE)
{
E_Maximize max;
max = bd->maximized;
e_border_unmaximize(bd, E_MAXIMIZE_BOTH);
e_border_maximize(bd, max);
}
else
{
int x, y, w, h, zx, zy, zw, zh;
bd->saved.x = bd->pre_res_change.saved.x;
bd->saved.y = bd->pre_res_change.saved.y;
bd->saved.w = bd->pre_res_change.saved.w;
bd->saved.h = bd->pre_res_change.saved.h;
e_zone_useful_geometry_get(bd->zone, &zx, &zy, &zw, &zh);
if (bd->saved.w > zw)
bd->saved.w = zw;
if ((bd->saved.x + bd->saved.w) > (zx + zw))
bd->saved.x = zx + zw - bd->saved.w;
if (bd->saved.h > zh)
bd->saved.h = zh;
if ((bd->saved.y + bd->saved.h) > (zy + zh))
bd->saved.y = zy + zh - bd->saved.h;
x = bd->pre_res_change.x;
y = bd->pre_res_change.y;
w = bd->pre_res_change.w;
h = bd->pre_res_change.h;
if (w > zw)
w = zw;
if (h > zh)
h = zh;
if ((x + w) > (zx + zw))
x = zx + zw - w;
if ((y + h) > (zy + zh))
y = zy + zh - h;
e_border_move_resize(bd, x, y, w, h);
}
memcpy(&bd->pre_res_change, &pre_res_change, sizeof(pre_res_change));
}
EAPI void
e_border_zone_set(E_Border *bd,
E_Zone *zone)
{
E_Event_Border_Zone_Set *ev;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
E_OBJECT_CHECK(zone);
E_OBJECT_TYPE_CHECK(zone, E_ZONE_TYPE);
if (!zone) return;
if (bd->zone == zone) return;
/* if the window does not lie in the new zone, move it so that it does */
if (!E_INTERSECTS(bd->x, bd->y, bd->w, bd->h, zone->x, zone->y, zone->w, zone->h))
{
int x, y;
/* first guess -- get offset from old zone, and apply to new zone */
x = zone->x + (bd->x - bd->zone->x);
y = zone->y + (bd->y - bd->zone->y);
/* keep window from hanging off bottom and left */
if (x + bd->w > zone->x + zone->w) x += (zone->x + zone->w) - (x + bd->w);
if (y + bd->h > zone->y + zone->h) y += (zone->y + zone->h) - (y + bd->h);
/* make sure to and left are on screen (if the window is larger than the zone, it will hang off the bottom / right) */
if (x < zone->x) x = zone->x;
if (y < zone->y) y = zone->y;
if (!E_INTERSECTS(x, y, bd->w, bd->h, zone->x, zone->y, zone->w, zone->h))
{
/* still not in zone at all, so just move it to closest edge */
if (x < zone->x) x = zone->x;
if (x >= zone->x + zone->w) x = zone->x + zone->w - bd->w;
if (y < zone->y) y = zone->y;
if (y >= zone->y + zone->h) y = zone->y + zone->h - bd->h;
}
e_border_move(bd, x, y);
}
bd->zone = zone;
if (bd->desk->zone != bd->zone)
e_border_desk_set(bd, e_desk_current_get(bd->zone));
ev = E_NEW(E_Event_Border_Zone_Set, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_zone_set_event");
ev->zone = zone;
e_object_ref(E_OBJECT(zone));
ecore_event_add(E_EVENT_BORDER_ZONE_SET, ev, _e_border_event_border_zone_set_free, NULL);
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_ZONE, &bd->zone->num, 1);
// XXXXXXXXXXXXXXXXXXXXXXXXX
// XXX ZZZZZZZZZZZZZZZZZZZzz
// need to adjust this if zone pos/size changes
{
unsigned int zgeom[4];
zgeom[0] = bd->zone->x;
zgeom[1] = bd->zone->y;
zgeom[2] = bd->zone->w;
zgeom[3] = bd->zone->h;
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_ZONE_GEOMETRY, zgeom, 4);
}
e_remember_update(bd);
}
EAPI void
e_border_desk_set(E_Border *bd,
E_Desk *desk)
{
E_Event_Border_Desk_Set *ev;
E_Desk *old_desk;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
E_OBJECT_CHECK(desk);
E_OBJECT_TYPE_CHECK(desk, E_DESK_TYPE);
if (bd->desk == desk) return;
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
if ((e_config->use_desktop_window_profile) &&
(bd->client.e.state.profile.use))
{
if (bd->client.e.state.profile.wait_for_done) return;
if (e_util_strcmp(bd->client.e.state.profile.name, desk->window_profile))
{
ecore_x_e_window_profile_change_request_send(bd->client.win,
desk->window_profile);
bd->client.e.state.profile.wait_for_done = 1;
return;
}
}
#endif
ecore_x_window_shadow_tree_flush();
if (bd->fullscreen)
{
bd->desk->fullscreen_borders--;
desk->fullscreen_borders++;
}
old_desk = bd->desk;
bd->desk = desk;
e_border_zone_set(bd, desk->zone);
_e_border_hook_call(E_BORDER_HOOK_SET_DESK, bd);
e_hints_window_desktop_set(bd);
ev = E_NEW(E_Event_Border_Desk_Set, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_desk_set_event");
ev->desk = old_desk;
e_object_ref(E_OBJECT(old_desk));
ecore_event_add(E_EVENT_BORDER_DESK_SET, ev, _e_border_event_border_desk_set_free, NULL);
if (bd->ignore_first_unmap != 1)
{
if ((bd->desk->visible) || (bd->sticky))
e_border_show(bd);
else
e_border_hide(bd, 1);
}
if (e_config->transient.desktop)
{
E_Border *child;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_FREE(list, child)
e_border_desk_set(child, bd->desk);
}
e_remember_update(bd);
}
EAPI void
e_border_show(E_Border *bd)
{
E_Event_Border_Show *ev;
unsigned int visible;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->visible) return;
ecore_x_window_shadow_tree_flush();
e_container_shape_show(bd->shape);
if (!bd->need_reparent)
ecore_x_window_show(bd->client.win);
e_hints_window_visible_set(bd);
bd->hidden = 0;
bd->visible = 1;
bd->changes.visible = 1;
visible = 1;
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_MAPPED, &visible, 1);
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_MANAGED, &visible, 1);
ev = E_NEW(E_Event_Border_Show, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_show_event");
ecore_event_add(E_EVENT_BORDER_SHOW, ev, _e_border_event_border_show_free, NULL);
}
EAPI void
e_border_hide(E_Border *bd,
int manage)
{
unsigned int visible;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (!bd->visible) goto send_event;
ecore_x_window_shadow_tree_flush();
if (bd->moving)
_e_border_move_end(bd);
if (bd->resize_mode != RESIZE_NONE)
{
_e_border_pointer_resize_end(bd);
bd->resize_mode = RESIZE_NONE;
_e_border_resize_end(bd);
}
e_container_shape_hide(bd->shape);
if (!bd->iconic) e_hints_window_hidden_set(bd);
bd->visible = 0;
bd->changes.visible = 1;
if (!bd->need_reparent)
{
if (bd->focused)
{
e_border_focus_set(bd, 0, 1);
if (manage != 2)
{
E_Border *pbd;
E_Zone *zone;
E_Desk *desk;
zone = e_util_zone_current_get(e_manager_current_get());
desk = e_desk_current_get(zone);
if ((bd->parent) &&
(bd->parent->desk == desk) && (bd->parent->modal == bd))
e_border_focus_set(bd->parent, 1, 1);
else if (e_config->focus_revert_on_hide_or_close)
{
Eina_Bool unlock = bd->lock_focus_out;
bd->lock_focus_out = 1;
e_desk_last_focused_focus(desk);
bd->lock_focus_out = unlock;
}
else if (e_config->focus_policy == E_FOCUS_MOUSE)
{
pbd = e_border_under_pointer_get(desk, bd);
if (pbd)
e_border_focus_set(pbd, 1, 1);
}
}
}
switch (manage)
{
case 2: break;
case 3:
bd->hidden = 1;
case 1:
default:
if (!e_manager_comp_evas_get(bd->zone->container->manager))
{
/* Make sure that this border isn't deleted */
bd->await_hide_event++;
ecore_x_window_hide(bd->client.win);
}
}
}
visible = 0;
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_MAPPED, &visible, 1);
if (!manage)
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_MANAGED, &visible, 1);
bd->post_show = 0;
send_event:
if (!stopping)
{
E_Event_Border_Hide *ev;
ev = E_NEW(E_Event_Border_Hide, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_hide_event");
ecore_event_add(E_EVENT_BORDER_HIDE, ev, _e_border_event_border_hide_free, NULL);
}
}
static void
_pri_adj(int pid, int set, int adj, Eina_Bool use_adj, Eina_Bool adj_children, Eina_Bool do_children)
{
int newpri = set;
if (use_adj) newpri = getpriority(PRIO_PROCESS, pid) + adj;
setpriority(PRIO_PROCESS, pid, newpri);
// shouldnt need to do this as default ionice class is "none" (0), and
// this inherits io priority FROM nice level
// ioprio_set(IOPRIO_WHO_PROCESS, pid,
// IOPRIO_PRIO_VALUE(2, 5));
if (do_children)
{
Eina_List *files;
char *file, buf[PATH_MAX];
FILE *f;
int pid2, ppid;
// yes - this is /proc specific... so this may not work on some
// os's - works on linux. too bad for others.
files = ecore_file_ls("/proc");
EINA_LIST_FREE(files, file)
{
if (isdigit(file[0]))
{
snprintf(buf, sizeof(buf), "/proc/%s/stat", file);
f = fopen(buf, "r");
if (f)
{
pid2 = -1;
ppid = -1;
if (fscanf(f, "%i %*s %*s %i %*s", &pid2, &ppid) == 2)
{
fclose(f);
if (ppid == pid)
{
if (adj_children)
_pri_adj(pid2, set, adj, EINA_TRUE,
adj_children, do_children);
else
_pri_adj(pid2, set, adj, use_adj,
adj_children, do_children);
}
}
else fclose(f);
}
}
free(file);
}
}
}
static void
_e_border_pri_raise(E_Border *bd)
{
if (bd->client.netwm.pid <= 0) return;
if (bd->client.netwm.pid == getpid()) return;
_pri_adj(bd->client.netwm.pid,
e_config->priority - 1, -1, EINA_FALSE,
// EINA_TRUE, EINA_TRUE);
EINA_TRUE, EINA_FALSE);
// printf("WIN: pid %i, title %s (HI!!!!!!!!!!!!!!!!!!)\n",
// bd->client.netwm.pid, e_border_name_get(bd));
}
static void
_e_border_pri_norm(E_Border *bd)
{
if (bd->client.netwm.pid <= 0) return;
if (bd->client.netwm.pid == getpid()) return;
_pri_adj(bd->client.netwm.pid,
e_config->priority, 1, EINA_FALSE,
// EINA_TRUE, EINA_TRUE);
EINA_TRUE, EINA_FALSE);
// printf("WIN: pid %i, title %s (NORMAL)\n",
// bd->client.netwm.pid, e_border_name_get(bd));
}
static void
_e_border_frame_replace(E_Border *bd, Eina_Bool argb)
{
Ecore_X_Window win;
Ecore_Evas *bg_ecore_evas;
char buf[4096];
bd->argb = argb;
win = bd->win;
bg_ecore_evas = bd->bg_ecore_evas;
/* unregister old frame window */
eina_hash_del(borders_hash, e_util_winid_str_get(bd->bg_win), bd);
eina_hash_del(borders_hash, e_util_winid_str_get(bd->win), bd);
e_focus_setdown(bd);
e_bindings_mouse_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_bindings_wheel_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
if (bd->icon_object)
evas_object_del(bd->icon_object);
evas_object_del(bd->bg_object);
e_canvas_del(bg_ecore_evas);
ecore_evas_free(bg_ecore_evas);
if (bd->pointer)
e_object_del(E_OBJECT(bd->pointer));
/* create new frame */
if (argb)
bd->win = ecore_x_window_manager_argb_new(bd->zone->container->win,
bd->x, bd->y, bd->w, bd->h);
else
{
bd->win = ecore_x_window_override_new(bd->zone->container->win,
bd->x, bd->y, bd->w, bd->h);
ecore_x_window_shape_events_select(bd->win, 1);
}
ecore_x_window_configure(bd->win,
ECORE_X_WINDOW_CONFIGURE_MASK_SIBLING |
ECORE_X_WINDOW_CONFIGURE_MASK_STACK_MODE,
0, 0, 0, 0, 0,
win, ECORE_X_WINDOW_STACK_BELOW);
e_bindings_mouse_grab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_bindings_wheel_grab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_focus_setup(bd);
bd->bg_ecore_evas = e_canvas_new(bd->win,
0, 0, bd->w, bd->h, 1, 0,
&(bd->bg_win));
e_canvas_add(bd->bg_ecore_evas);
ecore_x_window_reparent(bd->event_win, bd->win, 0, 0);
bd->bg_evas = ecore_evas_get(bd->bg_ecore_evas);
ecore_evas_name_class_set(bd->bg_ecore_evas, "E", "Frame_Window");
ecore_evas_title_set(bd->bg_ecore_evas, "Enlightenment Frame");
ecore_x_window_shape_events_select(bd->bg_win, 1);
/* move client with shell win over to new frame */
ecore_x_window_reparent(bd->client.shell_win, bd->win,
bd->client_inset.l, bd->client_inset.t);
bd->pointer = e_pointer_window_new(bd->win, 0);
eina_hash_add(borders_hash, e_util_winid_str_get(bd->bg_win), bd);
eina_hash_add(borders_hash, e_util_winid_str_get(bd->win), bd);
if (bd->visible)
{
E_Border *tmp;
Eina_List *l;
ecore_evas_show(bd->bg_ecore_evas);
ecore_x_window_show(bd->win);
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
ecore_x_window_show(tmp->win);
}
bd->bg_object = edje_object_add(bd->bg_evas);
snprintf(buf, sizeof(buf), "e/widgets/border/%s/border", bd->client.border.name);
e_theme_edje_object_set(bd->bg_object, "base/theme/borders", buf);
bd->icon_object = e_border_icon_add(bd, bd->bg_evas);
/* cleanup old frame */
ecore_x_window_free(win);
}
static void
_e_border_client_move_resize_send(E_Border *bd)
{
if (bd->internal_ecore_evas)
ecore_evas_managed_move(bd->internal_ecore_evas,
bd->x + bd->fx.x + bd->client_inset.l,
bd->y + bd->fx.y + bd->client_inset.t);
ecore_x_icccm_move_resize_send(bd->client.win,
bd->x + bd->fx.x + bd->client_inset.l,
bd->y + bd->fx.y + bd->client_inset.t,
bd->client.w,
bd->client.h);
}
static void
_e_border_pending_move_resize_add(E_Border *bd,
int move,
int resize,
int x,
int y,
int w,
int h,
Eina_Bool without_border,
unsigned int serial)
{
E_Border_Pending_Move_Resize *pnd;
pnd = E_NEW(E_Border_Pending_Move_Resize, 1);
if (!pnd) return;
pnd->resize = resize;
pnd->move = move;
pnd->without_border = without_border;
pnd->x = x;
pnd->y = y;
pnd->w = w;
pnd->h = h;
pnd->serial = serial;
bd->pending_move_resize = eina_list_append(bd->pending_move_resize, pnd);
}
static void
_e_border_move_internal(E_Border *bd,
int x,
int y,
Eina_Bool without_border)
{
E_Event_Border_Move *ev;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
ecore_x_window_shadow_tree_flush();
if (bd->new_client)
{
_e_border_pending_move_resize_add(bd, 1, 0, x, y, 0, 0, without_border, 0);
return;
}
if (bd->maximized)
{
if ((bd->maximized & E_MAXIMIZE_DIRECTION) != E_MAXIMIZE_BOTH)
{
if (e_config->allow_manip)
bd->maximized = 0;
if ((bd->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_HORIZONTAL)
{
x = bd->x;
}
else
if ((bd->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_VERTICAL)
{
y = bd->y;
}
}
else if (e_config->allow_manip)
bd->maximized = 0;
else
return;
}
if (without_border)
{
x -= bd->client_inset.l;
y -= bd->client_inset.t;
}
if (bd->move_intercept_cb)
{
int px, py;
px = bd->x, py = bd->y;
bd->move_intercept_cb(bd, x, y);
if ((bd->x == px) && (bd->y == py)) return;
}
else if ((x == bd->x) && (y == bd->y))
return;
bd->pre_res_change.valid = 0;
bd->x = x;
bd->y = y;
bd->changed = 1;
bd->changes.pos = 1;
#if 0
if (bd->client.netwm.sync.request)
{
bd->client.netwm.sync.wait++;
ecore_x_netwm_sync_request_send(bd->client.win, bd->client.netwm.sync.serial++);
}
#endif
_e_border_client_move_resize_send(bd);
_e_border_move_update(bd);
ev = E_NEW(E_Event_Border_Move, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_move_event");
ecore_event_add(E_EVENT_BORDER_MOVE, ev, _e_border_event_border_move_free, NULL);
_e_border_zone_update(bd);
}
/**
* Move window to coordinates that already account border decorations.
*
* This call will consider given position already accounts border
* decorations, so it will not be considered later. This will just
* work properly with borders that have being evaluated and border
* decorations are known (border->client_inset).
*
* @parm x horizontal position to place window.
* @parm y vertical position to place window.
*
* @see e_border_move_without_border()
*/
EAPI void
e_border_move(E_Border *bd,
int x,
int y)
{
if (bd->fullscreen)
return;
_e_border_move_internal(bd, x, y, 0);
}
/**
* Set a callback which will be called just prior to updating the
* move coordinates for a border
*/
EAPI void
e_border_move_intercept_cb_set(E_Border *bd, E_Border_Move_Intercept_Cb cb)
{
bd->move_intercept_cb = cb;
}
/**
* Move window to coordinates that do not account border decorations yet.
*
* This call will consider given position does not account border
* decoration, so these values (border->client_inset) will be
* accounted automatically. This is specially useful when it is a new
* client and has not be evaluated yet, in this case
* border->client_inset will be zeroed and no information is known. It
* will mark pending requests so border will be accounted on
* evalutation phase.
*
* @parm x horizontal position to place window.
* @parm y vertical position to place window.
*
* @see e_border_move()
*/
EAPI void
e_border_move_without_border(E_Border *bd,
int x,
int y)
{
if (bd->fullscreen)
return;
_e_border_move_internal(bd, x, y, 1);
}
EAPI void
e_border_center(E_Border *bd)
{
int x, y, w, h;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
e_zone_useful_geometry_get(bd->zone, &x, &y, &w, &h);
e_border_move(bd, x + (w - bd->w) / 2, y + (h - bd->h) / 2);
}
EAPI void
e_border_center_pos_get(E_Border *bd,
int *x,
int *y)
{
int zx, zy, zw, zh;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
e_zone_useful_geometry_get(bd->zone, &zx, &zy, &zw, &zh);
if (x) *x = zx + (zw - bd->w) / 2;
if (y) *y = zy + (zh - bd->h) / 2;
}
EAPI void
e_border_fx_offset(E_Border *bd,
int x,
int y)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((x == bd->fx.x) && (y == bd->fx.y)) return;
bd->fx.x = x;
bd->fx.y = y;
bd->changes.pos = 1;
bd->changed = 1;
if (bd->moving) _e_border_move_update(bd);
}
static void
_e_border_move_resize_internal(E_Border *bd,
int x,
int y,
int w,
int h,
Eina_Bool without_border,
Eina_Bool move)
{
E_Event_Border_Move *mev;
E_Event_Border_Resize *rev;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
ecore_x_window_shadow_tree_flush();
if (bd->new_client)
{
_e_border_pending_move_resize_add(bd, move, 1, x, y, w, h, without_border, 0);
return;
}
if (bd->maximized)
{
if ((bd->maximized & E_MAXIMIZE_DIRECTION) != E_MAXIMIZE_BOTH)
{
if (e_config->allow_manip)
bd->maximized = 0;
if ((bd->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_HORIZONTAL)
{
x = bd->x;
w = bd->w;
}
else
if ((bd->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_VERTICAL)
{
y = bd->y;
h = bd->h;
}
}
else
if (e_config->allow_manip)
bd->maximized = 0;
else
return;
}
if (without_border)
{
x -= bd->client_inset.l;
y -= bd->client_inset.t;
w += (bd->client_inset.l + bd->client_inset.r);
h += (bd->client_inset.t + bd->client_inset.b);
}
if ((!move || ((x == bd->x) && (y == bd->y))) &&
(w == bd->w) && (h == bd->h))
return;
bd->pre_res_change.valid = 0;
if (move)
{
bd->changes.pos = 1;
bd->x = x;
bd->y = y;
}
bd->w = w;
bd->h = h;
bd->client.w = bd->w - (bd->client_inset.l + bd->client_inset.r);
bd->client.h = bd->h - (bd->client_inset.t + bd->client_inset.b);
if ((bd->shaped) || (bd->client.shaped))
{
bd->need_shape_merge = 1;
bd->need_shape_export = 1;
}
if (bd->shaped_input)
{
bd->need_shape_merge = 1;
}
if (bd->internal_ecore_evas)
{
bd->changed = 1;
bd->changes.size = 1;
}
else
{
if (bdresize && bd->client.netwm.sync.request)
{
bd->client.netwm.sync.wait++;
/* Don't use x and y as supplied to this function, as it is called with 0, 0
* when no move is intended. The border geometry is set above anyways.
*/
_e_border_pending_move_resize_add(bd, move, 1, bd->x, bd->y, bd->w, bd->h, without_border,
bd->client.netwm.sync.serial);
ecore_x_netwm_sync_request_send(bd->client.win,
bd->client.netwm.sync.serial++);
}
else
{
bd->changed = 1;
bd->changes.size = 1;
}
}
_e_border_client_move_resize_send(bd);
_e_border_resize_update(bd);
if (move)
{
mev = E_NEW(E_Event_Border_Move, 1);
mev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_move_event");
ecore_event_add(E_EVENT_BORDER_MOVE, mev, _e_border_event_border_move_free, NULL);
}
rev = E_NEW(E_Event_Border_Resize, 1);
rev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_resize_event");
ecore_event_add(E_EVENT_BORDER_RESIZE, rev, _e_border_event_border_resize_free, NULL);
_e_border_zone_update(bd);
}
/**
* Move and resize window to values that already account border decorations.
*
* This call will consider given values already accounts border
* decorations, so it will not be considered later. This will just
* work properly with borders that have being evaluated and border
* decorations are known (border->client_inset).
*
* @parm x horizontal position to place window.
* @parm y vertical position to place window.
* @parm w horizontal window size.
* @parm h vertical window size.
*
* @see e_border_move_resize_without_border()
*/
EAPI void
e_border_move_resize(E_Border *bd,
int x,
int y,
int w,
int h)
{
if (bd->fullscreen)
return;
_e_border_move_resize_internal(bd, x, y, w, h, 0, 1);
}
/**
* Move and resize window to values that do not account border decorations yet.
*
* This call will consider given values already accounts border
* decorations, so it will not be considered later. This will just
* work properly with borders that have being evaluated and border
* decorations are known (border->client_inset).
*
* @parm x horizontal position to place window.
* @parm y vertical position to place window.
* @parm w horizontal window size.
* @parm h vertical window size.
*
* @see e_border_move_resize()
*/
EAPI void
e_border_move_resize_without_border(E_Border *bd,
int x,
int y,
int w,
int h)
{
if (bd->fullscreen)
return;
_e_border_move_resize_internal(bd, x, y, w, h, 1, 1);
}
/**
* Resize window to values that already account border decorations.
*
* This call will consider given size already accounts border
* decorations, so it will not be considered later. This will just
* work properly with borders that have being evaluated and border
* decorations are known (border->client_inset).
*
* @parm w horizontal window size.
* @parm h vertical window size.
*
* @see e_border_resize_without_border()
*/
EAPI void
e_border_resize(E_Border *bd,
int w,
int h)
{
if (bd->fullscreen)
return;
_e_border_move_resize_internal(bd, 0, 0, w, h, 0, 0);
}
/**
* Resize window to values that do not account border decorations yet.
*
* This call will consider given size does not account border
* decoration, so these values (border->client_inset) will be
* accounted automatically. This is specially useful when it is a new
* client and has not be evaluated yet, in this case
* border->client_inset will be zeroed and no information is known. It
* will mark pending requests so border will be accounted on
* evalutation phase.
*
* @parm w horizontal window size.
* @parm h vertical window size.
*
* @see e_border_resize()
*/
EAPI void
e_border_resize_without_border(E_Border *bd,
int w,
int h)
{
if (bd->fullscreen)
return;
_e_border_move_resize_internal(bd, 0, 0, w, h, 1, 0);
}
EAPI void
e_border_layer_set(E_Border *bd,
E_Layer layer)
{
int oldraise;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
ecore_x_window_shadow_tree_flush();
oldraise = e_config->transient.raise;
if (bd->fullscreen)
{
bd->saved.layer = layer;
return;
}
bd->layer = layer;
if (e_config->transient.layer)
{
E_Border *child;
Eina_List *list = _e_border_sub_borders_new(bd);
/* We need to set raise to one, else the child wont
* follow to the new layer. It should be like this,
* even if the user usually doesn't want to raise
* the transients.
*/
e_config->transient.raise = 1;
EINA_LIST_FREE(list, child)
e_border_layer_set(child, layer);
}
e_border_raise(bd);
if (layer == E_LAYER_BELOW)
e_hints_window_stacking_set(bd, E_STACKING_BELOW);
else if (layer == E_LAYER_ABOVE)
e_hints_window_stacking_set(bd, E_STACKING_ABOVE);
else
e_hints_window_stacking_set(bd, E_STACKING_NONE);
e_config->transient.raise = oldraise;
}
EAPI void
e_border_raise(E_Border *bd)
{
E_Event_Border_Stack *ev;
E_Border *last = NULL, *child;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
ecore_x_window_shadow_tree_flush();
if (e_config->transient.raise)
{
Eina_List *l, *l_prev;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_REVERSE_FOREACH_SAFE(list, l, l_prev, child)
{
/* Don't stack iconic transients. If the user wants these shown,
* thats another option.
*/
if (!child->iconic)
{
if (last)
e_border_stack_below(child, last);
else
{
E_Border *above;
/* First raise the border to find out which border we will end up above */
above = e_container_border_raise(child);
if (above)
{
/* We ended up above a border, now we must stack this border to
* generate the stacking event, and to check if this transient
* has other transients etc.
*/
e_border_stack_above(child, above);
}
else
{
/* If we didn't end up above any border, we are on the bottom! */
e_border_lower(child);
}
}
last = child;
}
list = eina_list_remove_list(list, l);
}
}
ev = E_NEW(E_Event_Border_Stack, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
if (last)
{
e_container_border_stack_below(bd, last);
ev->stack = last;
e_object_ref(E_OBJECT(last));
ev->type = E_STACKING_BELOW;
}
else
{
E_Border *above;
/* If we don't have any children, raise this border */
above = e_container_border_raise(bd);
e_border_raise_latest_set(bd);
if (above)
{
/* We ended up above a border */
ev->stack = above;
e_object_ref(E_OBJECT(above));
ev->type = E_STACKING_ABOVE;
}
else
{
/* No border to raise above, same as a lower! */
ev->stack = NULL;
ev->type = E_STACKING_ABOVE;
}
}
ecore_event_add(E_EVENT_BORDER_STACK, ev, _e_border_event_border_stack_free, NULL);
e_remember_update(bd);
}
EAPI void
e_border_lower(E_Border *bd)
{
E_Event_Border_Stack *ev;
E_Border *last = NULL, *child;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
ecore_x_window_shadow_tree_flush();
if (e_config->transient.lower)
{
Eina_List *l, *l_prev;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_REVERSE_FOREACH_SAFE(list, l, l_prev, child)
{
/* Don't stack iconic transients. If the user wants these shown,
* thats another option.
*/
if (!child->iconic)
{
if (last)
e_border_stack_below(child, last);
else
{
E_Border *below;
/* First lower the border to find out which border we will end up below */
below = e_container_border_lower(child);
if (below)
{
/* We ended up below a border, now we must stack this border to
* generate the stacking event, and to check if this transient
* has other transients etc.
*/
e_border_stack_below(child, below);
}
else
{
/* If we didn't end up below any border, we are on top! */
e_border_raise(child);
}
}
last = child;
}
list = eina_list_remove_list(list, l);
}
}
ev = E_NEW(E_Event_Border_Stack, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
if (last)
{
e_container_border_stack_below(bd, last);
ev->stack = last;
e_object_ref(E_OBJECT(last));
ev->type = E_STACKING_BELOW;
}
else
{
E_Border *below;
/* If we don't have any children, lower this border */
below = e_container_border_lower(bd);
if (below)
{
/* We ended up below a border */
ev->stack = below;
e_object_ref(E_OBJECT(below));
ev->type = E_STACKING_BELOW;
}
else
{
/* No border to hide under, same as a raise! */
ev->stack = NULL;
ev->type = E_STACKING_BELOW;
}
}
ecore_event_add(E_EVENT_BORDER_STACK, ev, _e_border_event_border_stack_free, NULL);
e_remember_update(bd);
}
EAPI void
e_border_stack_above(E_Border *bd,
E_Border *above)
{
/* TODO: Should stack above allow the border to change level */
E_Event_Border_Stack *ev;
E_Border *last = NULL, *child;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
ecore_x_window_shadow_tree_flush();
if (e_config->transient.raise)
{
Eina_List *l, *l_prev;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_REVERSE_FOREACH_SAFE(list, l, l_prev, child)
{
/* Don't stack iconic transients. If the user wants these shown,
* thats another option.
*/
if (!child->iconic)
{
if (last)
e_border_stack_below(child, last);
else
e_border_stack_above(child, above);
last = child;
}
list = eina_list_remove_list(list, l);
}
}
ev = E_NEW(E_Event_Border_Stack, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
if (last)
{
e_container_border_stack_below(bd, last);
ev->stack = last;
e_object_ref(E_OBJECT(last));
ev->type = E_STACKING_BELOW;
}
else
{
e_container_border_stack_above(bd, above);
ev->stack = above;
e_object_ref(E_OBJECT(above));
ev->type = E_STACKING_ABOVE;
}
ecore_event_add(E_EVENT_BORDER_STACK, ev, _e_border_event_border_stack_free, NULL);
e_remember_update(bd);
}
EAPI void
e_border_stack_below(E_Border *bd,
E_Border *below)
{
/* TODO: Should stack below allow the border to change level */
E_Event_Border_Stack *ev;
E_Border *last = NULL, *child;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
ecore_x_window_shadow_tree_flush();
if (e_config->transient.lower)
{
Eina_List *l, *l_prev;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_REVERSE_FOREACH_SAFE(list, l, l_prev, child)
{
/* Don't stack iconic transients. If the user wants these shown,
* thats another option.
*/
if (!child->iconic)
{
if (last)
e_border_stack_below(child, last);
else
e_border_stack_below(child, below);
last = child;
}
list = eina_list_remove_list(list, l);
}
}
ev = E_NEW(E_Event_Border_Stack, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
if (last)
{
e_container_border_stack_below(bd, last);
ev->stack = last;
e_object_ref(E_OBJECT(last));
ev->type = E_STACKING_BELOW;
}
else
{
e_container_border_stack_below(bd, below);
ev->stack = below;
e_object_ref(E_OBJECT(below));
ev->type = E_STACKING_BELOW;
}
ecore_event_add(E_EVENT_BORDER_STACK, ev, _e_border_event_border_stack_free, NULL);
e_remember_update(bd);
}
EAPI void
e_border_focus_latest_set(E_Border *bd)
{
focus_stack = eina_list_remove(focus_stack, bd);
focus_stack = eina_list_prepend(focus_stack, bd);
}
EAPI void
e_border_raise_latest_set(E_Border *bd)
{
raise_stack = eina_list_remove(raise_stack, bd);
raise_stack = eina_list_prepend(raise_stack, bd);
}
/*
* Sets the focus to the given border if necessary
* There are 3 cases of different focus_policy-configurations:
*
* - E_FOCUS_CLICK: just set the focus, the most simple one
*
* - E_FOCUS_MOUSE: focus is where the mouse is, so try to
* warp the pointer to the window. If this fails (because
* the pointer is already in the window), just set the focus.
*
* - E_FOCUS_SLOPPY: focus is where the mouse is or on the
* last window which was focused, if the mouse is on the
* desktop. So, we need to look if there is another window
* under the pointer and warp to pointer to the right
* one if so (also, we set the focus afterwards). In case
* there is no window under pointer, the pointer is on the
* desktop and so we just set the focus.
*
*
* This function is to be called when setting the focus was not
* explicitly triggered by the user (by moving the mouse or
* clicking for example), but implicitly (by closing a window,
* the last focused window should get focus).
*
*/
EAPI void
e_border_focus_set_with_pointer(E_Border *bd)
{
#ifdef PRINT_LOTS_OF_DEBUG
E_PRINT_BORDER_INFO(bd);
#endif
/* note: this is here as it seems there are enough apps that do not even
* expect us to emulate a look of focus but not actually set x input
* focus as we do - so simply abort any focuse set on such windows */
/* be strict about accepting focus hint */
if ((!bd->client.icccm.accepts_focus) &&
(!bd->client.icccm.take_focus)) return;
if (bd->lock_focus_out) return;
if (bd == focused) return;
e_border_focus_set(bd, 1, 1);
if (e_config->focus_policy == E_FOCUS_CLICK) return;
if (!bd->visible) return;
if (e_config->focus_policy == E_FOCUS_SLOPPY)
{
E_Border *pbd;
pbd = e_border_under_pointer_get(bd->desk, bd);
if (pbd && (pbd != bd)) e_border_pointer_warp_to_center(bd);
else e_border_focus_set(bd, 1, 0);
}
else
{
e_border_pointer_warp_to_center(bd);
}
}
EAPI void
e_border_focus_set(E_Border *bd,
int focus,
int set)
{
E_Border *bd_unfocus = NULL;
Eina_Bool focus_changed = EINA_FALSE;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
/* note: this is here as it seems there are enough apps that do not even
* expect us to emulate a look of focus but not actually set x input
* focus as we do - so simply abort any focuse set on such windows */
/* be strict about accepting focus hint */
if ((!bd->client.icccm.accepts_focus) &&
(!bd->client.icccm.take_focus))
return;
if ((set) && (focus) && (bd->lock_focus_out)) return;
/* dont focus an iconified window. that's silly! */
if (focus)
{
if ((bd->iconic) && (!bd->deskshow))
{
e_border_uniconify(bd);
if (!focus_track_frozen)
e_border_focus_latest_set(bd);
return;
}
else if (!bd->visible)
{
return;
}
/* FIXME: hack for deskflip animation:
* dont update focus when sliding previous desk */
else if ((!bd->sticky) &&
(bd->desk != e_desk_current_get(bd->desk->zone)))
{
return;
}
}
if ((bd->modal) && (bd->modal != bd) && (bd->modal->visible))
{
e_border_focus_set(bd->modal, focus, set);
return;
}
else if ((bd->leader) && (bd->leader->modal) && (bd->leader->modal != bd))
{
e_border_focus_set(bd->leader->modal, focus, set);
return;
}
if (focus)
{
if (set)
{
if (bd->visible && bd->changes.visible)
{
bd->want_focus = 1;
bd->changed = 1;
}
else if ((!bd->focused) ||
(focus_next && (bd != eina_list_data_get(focus_next))))
{
Eina_List *l;
if ((l = eina_list_data_find_list(focus_next, bd)))
focus_next = eina_list_promote_list(focus_next, l);
else
focus_next = eina_list_prepend(focus_next, bd);
}
if ((bd->client.icccm.take_focus) &&
(bd->client.icccm.accepts_focus))
{
e_grabinput_focus(bd->client.win, E_FOCUS_METHOD_LOCALLY_ACTIVE);
/* TODO what if the client didn't take focus ? */
}
else if (!bd->client.icccm.accepts_focus)
{
e_grabinput_focus(bd->client.win, E_FOCUS_METHOD_GLOBALLY_ACTIVE);
}
else if (!bd->client.icccm.take_focus)
{
e_grabinput_focus(bd->client.win, E_FOCUS_METHOD_PASSIVE);
/* e_border_focus_set(bd, 1, 0); */
}
return;
}
if (!bd->focused)
{
if (focused) bd_unfocus = focused;
if (focusing == bd) focusing = NULL;
bd->focused = 1;
focused = bd;
if ((!e_config->allow_above_fullscreen) && (!bd_unfocus))
{
Eina_List *l;
E_Border *bd2;
EINA_LIST_FOREACH(e_border_client_list(), l, bd2)
{
if ((bd2->fullscreen) &&
(bd2 != bd) &&
(bd2->zone == bd->zone) &&
((bd2->desk == bd->desk) ||
(bd2->sticky) || (bd->sticky)))
{
Eina_Bool unfocus_is_parent = EINA_FALSE;
E_Border *bd_parent;
bd_parent = bd->parent;
while (bd_parent)
{
if (bd_parent == bd2)
{
unfocus_is_parent = EINA_TRUE;
break;
}
bd_parent = bd->parent;
}
if (!unfocus_is_parent)
e_border_unfullscreen(bd2);
}
}
}
focus_changed = EINA_TRUE;
}
}
else
{
bd->want_focus = 0;
focus_next = eina_list_remove(focus_next, bd);
if (bd == focusing) focusing = NULL;
if (bd->focused)
{
Eina_Bool wasfocused = EINA_FALSE;
bd_unfocus = bd;
/* should always be the case. anyway */
if (bd == focused)
{
focused = NULL;
wasfocused = EINA_TRUE;
}
if ((set) && (!focus_next) && (!focusing))
{
e_grabinput_focus(bd->zone->container->bg_win,
E_FOCUS_METHOD_PASSIVE);
}
if ((!e_config->allow_above_fullscreen) &&
(bd->fullscreen) && (wasfocused) &&
((bd->desk == e_desk_current_get(bd->zone)) || (bd->sticky)))
{
Eina_Bool have_vis_child = EINA_FALSE;
Eina_List *l;
E_Border *bd2;
EINA_LIST_FOREACH(e_border_client_list(), l, bd2)
{
if ((bd2 != bd) &&
(bd2->zone == bd->zone) &&
((bd2->desk == bd->desk) ||
(bd2->sticky) || (bd->sticky)))
{
if (bd2->parent == bd)
{
have_vis_child = EINA_TRUE;
break;
}
}
}
if (!have_vis_child)
e_border_unfullscreen(bd);
}
}
}
if ((bd_unfocus) &&
(!e_object_is_del(E_OBJECT(bd_unfocus)) &&
(e_object_ref_get(E_OBJECT(bd_unfocus)) > 0)))
{
E_Event_Border_Focus_Out *ev;
bd_unfocus->focused = 0;
e_focus_event_focus_out(bd_unfocus);
if (bd_unfocus->raise_timer)
ecore_timer_del(bd_unfocus->raise_timer);
bd_unfocus->raise_timer = NULL;
edje_object_signal_emit(bd_unfocus->bg_object, "e,state,unfocused", "e");
if (bd_unfocus->icon_object)
edje_object_signal_emit(bd_unfocus->icon_object, "e,state,unfocused", "e");
ev = E_NEW(E_Event_Border_Focus_Out, 1);
ev->border = bd_unfocus;
e_object_ref(E_OBJECT(bd_unfocus));
ecore_event_add(E_EVENT_BORDER_FOCUS_OUT, ev,
_e_border_event_border_focus_out_free, NULL);
if ((!e_config->allow_above_fullscreen) &&
(bd_unfocus->fullscreen) &&
(bd != bd_unfocus) &&
(bd->zone == bd_unfocus->zone) &&
((bd->desk == bd_unfocus->desk) ||
(bd->sticky) || (bd_unfocus->sticky)))
{
Eina_Bool unfocus_is_parent = EINA_FALSE;
E_Border *bd_parent;
bd_parent = bd->parent;
while (bd_parent)
{
if (bd_parent == bd_unfocus)
{
unfocus_is_parent = EINA_TRUE;
break;
}
bd_parent = bd_parent->parent;
}
if (!unfocus_is_parent)
e_border_unfullscreen(bd_unfocus);
}
}
if (focus_changed)
{
E_Event_Border_Focus_In *ev;
e_focus_event_focus_in(bd);
if (!focus_track_frozen)
e_border_focus_latest_set(bd);
e_hints_active_window_set(bd->zone->container->manager, bd);
edje_object_signal_emit(bd->bg_object, "e,state,focused", "e");
if (bd->icon_object)
edje_object_signal_emit(bd->icon_object, "e,state,focused", "e");
ev = E_NEW(E_Event_Border_Focus_In, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
ecore_event_add(E_EVENT_BORDER_FOCUS_IN, ev,
_e_border_event_border_focus_in_free, NULL);
}
}
EAPI void
e_border_shade(E_Border *bd,
E_Direction dir)
{
E_Event_Border_Resize *ev;
Eina_List *l;
E_Border *tmp;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((bd->shaded) || (bd->shading) || (bd->fullscreen) ||
((bd->maximized) && (!e_config->allow_manip))) return;
if ((bd->client.border.name) &&
(!strcmp("borderless", bd->client.border.name))) return;
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
ecore_x_window_hide(tmp->win);
ecore_x_window_shadow_tree_flush();
bd->take_focus = 0;
bd->shade.x = bd->x;
bd->shade.y = bd->y;
bd->shade.dir = dir;
e_hints_window_shaded_set(bd, 1);
e_hints_window_shade_direction_set(bd, dir);
if (e_config->border_shade_animate)
{
bd->shade.start = ecore_loop_time_get();
bd->shading = 1;
bd->changes.shading = 1;
bd->changed = 1;
if (bd->shade.dir == E_DIRECTION_UP ||
bd->shade.dir == E_DIRECTION_LEFT)
{
ecore_x_window_gravity_set(bd->client.win, ECORE_X_GRAVITY_SW);
if (bd->client.lock_win) ecore_x_window_gravity_set(bd->client.lock_win, ECORE_X_GRAVITY_SW);
}
else
{
ecore_x_window_gravity_set(bd->client.win, ECORE_X_GRAVITY_NE);
if (bd->client.lock_win) ecore_x_window_gravity_set(bd->client.lock_win, ECORE_X_GRAVITY_NE);
}
bd->shade.anim = ecore_animator_add(_e_border_shade_animator, bd);
edje_object_signal_emit(bd->bg_object, "e,state,shading", "e");
}
else
{
if (bd->shade.dir == E_DIRECTION_UP)
{
bd->h = bd->client_inset.t + bd->client_inset.b;
}
else if (bd->shade.dir == E_DIRECTION_DOWN)
{
bd->h = bd->client_inset.t + bd->client_inset.b;
bd->y = bd->y + bd->client.h;
bd->changes.pos = 1;
}
else if (bd->shade.dir == E_DIRECTION_LEFT)
{
bd->w = bd->client_inset.l + bd->client_inset.r;
}
else if (bd->shade.dir == E_DIRECTION_RIGHT)
{
bd->w = bd->client_inset.l + bd->client_inset.r;
bd->x = bd->x + bd->client.w;
bd->changes.pos = 1;
}
if ((bd->shaped) || (bd->client.shaped))
{
bd->need_shape_merge = 1;
bd->need_shape_export = 1;
}
if (bd->shaped_input)
{
bd->need_shape_merge = 1;
}
bd->changes.size = 1;
bd->shaded = 1;
bd->changes.shaded = 1;
bd->changed = 1;
edje_object_signal_emit(bd->bg_object, "e,state,shaded", "e");
e_border_frame_recalc(bd);
ev = E_NEW(E_Event_Border_Resize, 1);
ev->border = bd;
/* The resize is added in the animator when animation complete */
/* For non-animated, we add it immediately with the new size */
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_resize_event");
ecore_event_add(E_EVENT_BORDER_RESIZE, ev, _e_border_event_border_resize_free, NULL);
}
e_remember_update(bd);
}
EAPI void
e_border_unshade(E_Border *bd,
E_Direction dir)
{
E_Event_Border_Resize *ev;
Eina_List *l;
E_Border *tmp;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((!bd->shaded) || (bd->shading))
return;
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
ecore_x_window_show(tmp->win);
ecore_x_window_shadow_tree_flush();
bd->shade.dir = dir;
e_hints_window_shaded_set(bd, 0);
e_hints_window_shade_direction_set(bd, dir);
if (bd->shade.dir == E_DIRECTION_UP ||
bd->shade.dir == E_DIRECTION_LEFT)
{
bd->shade.x = bd->x;
bd->shade.y = bd->y;
}
else
{
bd->shade.x = bd->x - bd->client.w;
bd->shade.y = bd->y - bd->client.h;
}
if (e_config->border_shade_animate)
{
bd->shade.start = ecore_loop_time_get();
bd->shading = 1;
bd->changes.shading = 1;
bd->changed = 1;
if (bd->shade.dir == E_DIRECTION_UP)
{
ecore_x_window_gravity_set(bd->client.win, ECORE_X_GRAVITY_SW);
ecore_x_window_move_resize(bd->client.win, 0,
bd->h - (bd->client_inset.t + bd->client_inset.b) -
bd->client.h,
bd->client.w, bd->client.h);
if (bd->client.lock_win)
{
ecore_x_window_gravity_set(bd->client.lock_win, ECORE_X_GRAVITY_SW);
ecore_x_window_move_resize(bd->client.lock_win, 0,
bd->h - (bd->client_inset.t + bd->client_inset.b) -
bd->client.h,
bd->client.w, bd->client.h);
}
}
else if (bd->shade.dir == E_DIRECTION_LEFT)
{
ecore_x_window_gravity_set(bd->client.win, ECORE_X_GRAVITY_SW);
ecore_x_window_move_resize(bd->client.win,
bd->w - (bd->client_inset.l + bd->client_inset.r) -
bd->client.h,
0, bd->client.w, bd->client.h);
if (bd->client.lock_win)
{
ecore_x_window_gravity_set(bd->client.lock_win, ECORE_X_GRAVITY_SW);
ecore_x_window_move_resize(bd->client.lock_win,
bd->w - (bd->client_inset.l + bd->client_inset.r) -
bd->client.h,
0, bd->client.w, bd->client.h);
}
}
else
{
ecore_x_window_gravity_set(bd->client.win, ECORE_X_GRAVITY_NE);
if (bd->client.lock_win) ecore_x_window_gravity_set(bd->client.lock_win, ECORE_X_GRAVITY_NE);
}
bd->shade.anim = ecore_animator_add(_e_border_shade_animator, bd);
edje_object_signal_emit(bd->bg_object, "e,state,unshading", "e");
}
else
{
if (bd->shade.dir == E_DIRECTION_UP)
{
bd->h = bd->client_inset.t + bd->client.h + bd->client_inset.b;
}
else if (bd->shade.dir == E_DIRECTION_DOWN)
{
bd->h = bd->client_inset.t + bd->client.h + bd->client_inset.b;
bd->y = bd->y - bd->client.h;
bd->changes.pos = 1;
}
else if (bd->shade.dir == E_DIRECTION_LEFT)
{
bd->w = bd->client_inset.l + bd->client.w + bd->client_inset.r;
}
else if (bd->shade.dir == E_DIRECTION_RIGHT)
{
bd->w = bd->client_inset.l + bd->client.w + bd->client_inset.r;
bd->x = bd->x - bd->client.w;
bd->changes.pos = 1;
}
if ((bd->shaped) || (bd->client.shaped))
{
bd->need_shape_merge = 1;
bd->need_shape_export = 1;
}
if (bd->shaped_input)
{
bd->need_shape_merge = 1;
}
bd->changes.size = 1;
bd->shaded = 0;
bd->changes.shaded = 1;
bd->changed = 1;
edje_object_signal_emit(bd->bg_object, "e,state,unshaded", "e");
e_border_frame_recalc(bd);
ev = E_NEW(E_Event_Border_Resize, 1);
ev->border = bd;
/* The resize is added in the animator when animation complete */
/* For non-animated, we add it immediately with the new size */
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_resize_event");
ecore_event_add(E_EVENT_BORDER_RESIZE, ev, _e_border_event_border_resize_free, NULL);
}
e_remember_update(bd);
}
static void
_e_border_client_inset_calc(E_Border *bd)
{
int cx, cy, cw, ch;
if (bd->bg_object)
{
evas_object_resize(bd->bg_object, MAX(bd->w, 500), MAX(bd->h, 500));
edje_object_message_signal_process(bd->bg_object);
edje_object_calc_force(bd->bg_object);
edje_object_part_geometry_get(bd->bg_object, "e.swallow.client", &cx, &cy, &cw, &ch);
bd->client_inset.l = cx;
bd->client_inset.r = MAX(bd->w, 500) - (cx + cw);
bd->client_inset.t = cy;
bd->client_inset.b = MAX(bd->h, 500) - (cy + ch);
}
else
{
bd->client_inset.l = 0;
bd->client_inset.r = 0;
bd->client_inset.t = 0;
bd->client_inset.b = 0;
}
ecore_x_netwm_frame_size_set(bd->client.win,
bd->client_inset.l, bd->client_inset.r,
bd->client_inset.t, bd->client_inset.b);
ecore_x_e_frame_size_set(bd->client.win,
bd->client_inset.l, bd->client_inset.r,
bd->client_inset.t, bd->client_inset.b);
}
static void
_e_border_maximize(E_Border *bd, E_Maximize max)
{
int x1, yy1, x2, y2;
int w, h, pw, ph;
int zx, zy, zw, zh;
zx = zy = zw = zh = 0;
switch (max & E_MAXIMIZE_TYPE)
{
case E_MAXIMIZE_NONE:
/* Ignore */
break;
case E_MAXIMIZE_FULLSCREEN:
w = bd->zone->w;
h = bd->zone->h;
if (bd->bg_object)
{
edje_object_signal_emit(bd->bg_object, "e,action,maximize,fullscreen", "e");
_e_border_client_inset_calc(bd);
}
e_border_resize_limit(bd, &w, &h);
/* center x-direction */
x1 = bd->zone->x + (bd->zone->w - w) / 2;
/* center y-direction */
yy1 = bd->zone->y + (bd->zone->h - h) / 2;
switch (max & E_MAXIMIZE_DIRECTION)
{
case E_MAXIMIZE_BOTH:
e_border_move_resize(bd, x1, yy1, w, h);
break;
case E_MAXIMIZE_VERTICAL:
e_border_move_resize(bd, bd->x, yy1, bd->w, h);
break;
case E_MAXIMIZE_HORIZONTAL:
e_border_move_resize(bd, x1, bd->y, w, bd->h);
break;
case E_MAXIMIZE_LEFT:
e_border_move_resize(bd, bd->zone->x, bd->zone->y, w / 2, h);
break;
case E_MAXIMIZE_RIGHT:
e_border_move_resize(bd, x1, bd->zone->y, w / 2, h);
break;
}
break;
case E_MAXIMIZE_SMART:
case E_MAXIMIZE_EXPAND:
if (bd->zone)
e_zone_useful_geometry_get(bd->zone, &zx, &zy, &zw, &zh);
w = zw, h = zh;
if (bd->bg_object)
{
edje_object_signal_emit(bd->bg_object, "e,action,maximize", "e");
_e_border_client_inset_calc(bd);
}
e_border_resize_limit(bd, &w, &h);
if (bd->w < zw)
w = bd->w;
else
w = zw;
if (bd->h < zh)
h = bd->h;
else
h = zh;
if (bd->x < zx) // window left not useful coordinates
x1 = zx;
else if (bd->x + bd->w > zx + zw) // window right not useful coordinates
x1 = zx + zw - bd->w;
else // window normal position
x1 = bd->x;
if (bd->y < zy) // window top not useful coordinates
yy1 = zy;
else if (bd->y + bd->h > zy + zh) // window bottom not useful coordinates
yy1 = zy + zh - bd->h;
else // window normal position
yy1 = bd->y;
switch (max & E_MAXIMIZE_DIRECTION)
{
case E_MAXIMIZE_BOTH:
e_border_move_resize(bd, zx, zy, zw, zh);
break;
case E_MAXIMIZE_VERTICAL:
e_border_move_resize(bd, x1, zy, w, zh);
break;
case E_MAXIMIZE_HORIZONTAL:
e_border_move_resize(bd, zx, yy1, zw, h);
break;
case E_MAXIMIZE_LEFT:
e_border_move_resize(bd, zx, zy, zw / 2, zh);
break;
case E_MAXIMIZE_RIGHT:
e_border_move_resize(bd, zx + zw / 2, zy, zw / 2, zh);
break;
}
break;
case E_MAXIMIZE_FILL:
x1 = bd->zone->x;
yy1 = bd->zone->y;
x2 = bd->zone->x + bd->zone->w;
y2 = bd->zone->y + bd->zone->h;
/* walk through all shelves */
e_maximize_border_shelf_fill(bd, &x1, &yy1, &x2, &y2, max);
/* walk through all windows */
e_maximize_border_border_fill(bd, &x1, &yy1, &x2, &y2, max);
w = x2 - x1;
h = y2 - yy1;
pw = w;
ph = h;
e_border_resize_limit(bd, &w, &h);
/* center x-direction */
x1 = x1 + (pw - w) / 2;
/* center y-direction */
yy1 = yy1 + (ph - h) / 2;
switch (max & E_MAXIMIZE_DIRECTION)
{
case E_MAXIMIZE_BOTH:
e_border_move_resize(bd, x1, yy1, w, h);
break;
case E_MAXIMIZE_VERTICAL:
e_border_move_resize(bd, bd->x, yy1, bd->w, h);
break;
case E_MAXIMIZE_HORIZONTAL:
e_border_move_resize(bd, x1, bd->y, w, bd->h);
break;
case E_MAXIMIZE_LEFT:
e_border_move_resize(bd, bd->zone->x, bd->zone->y, w / 2, h);
break;
case E_MAXIMIZE_RIGHT:
e_border_move_resize(bd, x1, bd->zone->y, w / 2, h);
break;
}
break;
}
}
EAPI void
e_border_maximize(E_Border *bd,
E_Maximize max)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (!(max & E_MAXIMIZE_DIRECTION)) max |= E_MAXIMIZE_BOTH;
if ((bd->shaded) || (bd->shading)) return;
ecore_x_window_shadow_tree_flush();
if (bd->fullscreen)
e_border_unfullscreen(bd);
/* Only allow changes in vertical/ horizontal maximization */
if (((bd->maximized & E_MAXIMIZE_DIRECTION) == (max & E_MAXIMIZE_DIRECTION)) ||
((bd->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_BOTH)) return;
if (bd->new_client)
{
bd->need_maximize = 1;
bd->maximized &= ~E_MAXIMIZE_TYPE;
bd->maximized |= max;
return;
}
bd->pre_res_change.valid = 0;
if (!(bd->maximized & E_MAXIMIZE_HORIZONTAL))
{
/* Horizontal hasn't been set */
bd->saved.x = bd->x - bd->zone->x;
bd->saved.w = bd->w;
}
if (!(bd->maximized & E_MAXIMIZE_VERTICAL))
{
/* Vertical hasn't been set */
bd->saved.y = bd->y - bd->zone->y;
bd->saved.h = bd->h;
}
bd->saved.zone = bd->zone->num;
e_hints_window_size_set(bd);
e_border_raise(bd);
_e_border_maximize(bd, max);
/* Remove previous type */
bd->maximized &= ~E_MAXIMIZE_TYPE;
/* Add new maximization. It must be added, so that VERTICAL + HORIZONTAL == BOTH */
bd->maximized |= max;
if ((bd->maximized & E_MAXIMIZE_DIRECTION) > E_MAXIMIZE_BOTH)
/* left/right maximize */
e_hints_window_maximized_set(bd, 0,
((bd->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_LEFT) ||
((bd->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_RIGHT));
else
e_hints_window_maximized_set(bd, bd->maximized & E_MAXIMIZE_HORIZONTAL,
bd->maximized & E_MAXIMIZE_VERTICAL);
e_remember_update(bd);
}
EAPI void
e_border_unmaximize(E_Border *bd,
E_Maximize max)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (!(max & E_MAXIMIZE_DIRECTION))
{
CRI("BUG: Unmaximize call without direction!");
return;
}
if ((bd->shaded) || (bd->shading)) return;
ecore_x_window_shadow_tree_flush();
/* Remove directions not used */
max &= (bd->maximized & E_MAXIMIZE_DIRECTION);
/* Can only remove existing maximization directions */
if (!max) return;
if (bd->maximized & E_MAXIMIZE_TYPE)
{
bd->pre_res_change.valid = 0;
bd->need_maximize = 0;
if ((bd->maximized & E_MAXIMIZE_TYPE) == E_MAXIMIZE_FULLSCREEN)
{
if (bd->bg_object)
{
edje_object_signal_emit(bd->bg_object, "e,action,unmaximize,fullscreen", "e");
_e_border_client_inset_calc(bd);
}
bd->maximized = E_MAXIMIZE_NONE;
_e_border_move_resize_internal(bd,
bd->zone->x + bd->saved.x,
bd->zone->y + bd->saved.y,
bd->saved.w, bd->saved.h, 0, 1);
bd->saved.x = bd->saved.y = bd->saved.w = bd->saved.h = 0;
e_hints_window_size_unset(bd);
}
else
{
int w, h, x, y;
w = bd->w;
h = bd->h;
x = bd->x;
y = bd->y;
if (((bd->maximized & E_MAXIMIZE_TYPE) == E_MAXIMIZE_SMART) ||
((bd->maximized & E_MAXIMIZE_TYPE) == E_MAXIMIZE_EXPAND))
{
if (bd->bg_object)
{
edje_object_signal_emit(bd->bg_object, "e,action,unmaximize,fullscreen", "e");
_e_border_client_inset_calc(bd);
}
}
if (max & E_MAXIMIZE_VERTICAL)
{
/* Remove vertical */
h = bd->saved.h;
y = bd->saved.y + bd->zone->y;
bd->saved.h = bd->saved.y = 0;
bd->maximized &= ~E_MAXIMIZE_VERTICAL;
bd->maximized &= ~E_MAXIMIZE_LEFT;
bd->maximized &= ~E_MAXIMIZE_RIGHT;
}
if (max & E_MAXIMIZE_HORIZONTAL)
{
/* Remove horizontal */
w = bd->saved.w;
x = bd->saved.x + bd->zone->x;
bd->saved.w = bd->saved.x = 0;
bd->maximized &= ~E_MAXIMIZE_HORIZONTAL;
}
e_border_resize_limit(bd, &w, &h);
if (!(bd->maximized & E_MAXIMIZE_DIRECTION))
{
bd->maximized = E_MAXIMIZE_NONE;
_e_border_move_resize_internal(bd, x, y, w, h, 0, 1);
e_hints_window_size_unset(bd);
edje_object_signal_emit(bd->bg_object, "e,action,unmaximize", "e");
}
else
{
_e_border_move_resize_internal(bd, x, y, w, h, 0, 1);
e_hints_window_size_set(bd);
}
}
e_hints_window_maximized_set(bd, bd->maximized & E_MAXIMIZE_HORIZONTAL,
bd->maximized & E_MAXIMIZE_VERTICAL);
}
e_remember_update(bd);
}
EAPI void
e_border_fullscreen(E_Border *bd,
E_Fullscreen policy)
{
E_Event_Border_Fullscreen *ev;
int x, y, w, h;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((bd->shaded) || (bd->shading)) return;
ecore_x_window_shadow_tree_flush();
if (bd->new_client)
{
bd->need_fullscreen = 1;
return;
}
if (!bd->fullscreen)
{
bd->pre_res_change.valid = 0;
if (bd->maximized)
{
x = bd->saved.x;
y = bd->saved.y;
w = bd->saved.w;
h = bd->saved.h;
}
else
{
bd->saved.x = bd->x - bd->zone->x;
bd->saved.y = bd->y - bd->zone->y;
bd->saved.w = bd->client.w;
bd->saved.h = bd->client.h;
}
bd->saved.maximized = bd->maximized;
bd->saved.zone = bd->zone->num;
if (bd->maximized)
{
e_border_unmaximize(bd, E_MAXIMIZE_BOTH);
bd->saved.x = x;
bd->saved.y = y;
bd->saved.w = w;
bd->saved.h = h;
}
e_hints_window_size_set(bd);
bd->client_inset.l = 0;
bd->client_inset.r = 0;
bd->client_inset.t = 0;
bd->client_inset.b = 0;
bd->desk->fullscreen_borders++;
/* e_zone_fullscreen_set(bd->zone, 1); */
bd->saved.layer = bd->layer;
if (!e_config->allow_above_fullscreen)
e_border_layer_set(bd, E_LAYER_FULLSCREEN);
else if (e_config->mode.presentation)
e_border_layer_set(bd, E_LAYER_TOP);
if ((eina_list_count(bd->zone->container->zones) > 1) ||
(policy == E_FULLSCREEN_RESIZE) || (!ecore_x_randr_query()))
{
e_border_move_resize(bd, bd->zone->x, bd->zone->y, bd->zone->w, bd->zone->h);
}
else if (policy == E_FULLSCREEN_ZOOM)
{
Ecore_X_Randr_Screen_Size_MM *sizes;
int num_sizes, i, best_size_index = 0;
ecore_x_randr_screen_primary_output_current_size_get(bd->zone->container->manager->root,
&screen_size.width,
&screen_size.height,
NULL, NULL, NULL);
sizes = ecore_x_randr_screen_primary_output_sizes_get(bd->zone->container->manager->root,
&num_sizes);
if (sizes)
{
Ecore_X_Randr_Screen_Size best_size = { -1, -1 };
int best_dist = INT_MAX, dist;
for (i = 0; i < num_sizes; i++)
{
if ((sizes[i].width > bd->w) && (sizes[i].height > bd->h))
{
dist = (sizes[i].width * sizes[i].height) - (bd->w * bd->h);
if (dist < best_dist)
{
best_size.width = sizes[i].width;
best_size.height = sizes[i].height;
best_dist = dist;
best_size_index = i;
}
}
}
if (((best_size.width != -1) && (best_size.height != -1)) &&
((best_size.width != screen_size.width) ||
(best_size.height != screen_size.height)))
{
if (ecore_x_randr_screen_primary_output_size_set(bd->zone->container->manager->root,
best_size_index))
screen_size_index = best_size_index;
e_border_move_resize(bd, 0, 0, best_size.width, best_size.height);
}
else
{
screen_size.width = -1;
screen_size.height = -1;
e_border_move_resize(bd, 0, 0, bd->zone->w, bd->zone->h);
}
free(sizes);
}
else
e_border_move_resize(bd, bd->zone->x, bd->zone->y, bd->zone->w, bd->zone->h);
}
bd->fullscreen = 1;
e_hints_window_fullscreen_set(bd, 1);
e_hints_window_size_unset(bd);
bd->client.border.changed = 1;
bd->changed = 1;
}
bd->fullscreen_policy = policy;
ev = E_NEW(E_Event_Border_Fullscreen, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_fullscreen_event");
ecore_event_add(E_EVENT_BORDER_FULLSCREEN, ev, _e_border_event_border_fullscreen_free, NULL);
e_remember_update(bd);
}
EAPI void
e_border_unfullscreen(E_Border *bd)
{
E_Event_Border_Unfullscreen *ev;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((bd->shaded) || (bd->shading)) return;
ecore_x_window_shadow_tree_flush();
if (bd->fullscreen)
{
bd->pre_res_change.valid = 0;
bd->fullscreen = 0;
bd->need_fullscreen = 0;
bd->desk->fullscreen_borders--;
if ((screen_size.width != -1) && (screen_size.height != -1))
{
ecore_x_randr_screen_primary_output_size_set(bd->zone->container->manager->root,
screen_size_index);
screen_size.width = -1;
screen_size.height = -1;
}
_e_border_move_resize_internal(bd,
bd->zone->x + bd->saved.x,
bd->zone->y + bd->saved.y,
bd->saved.w, bd->saved.h, 0, 1);
if (bd->saved.maximized)
e_border_maximize(bd, (e_config->maximize_policy & E_MAXIMIZE_TYPE) |
bd->saved.maximized);
e_border_layer_set(bd, bd->saved.layer);
e_hints_window_fullscreen_set(bd, 0);
bd->client.border.changed = 1;
bd->changed = 1;
}
bd->fullscreen_policy = 0;
ev = E_NEW(E_Event_Border_Unfullscreen, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_unfullscreen_event");
ecore_event_add(E_EVENT_BORDER_UNFULLSCREEN, ev, _e_border_event_border_unfullscreen_free, NULL);
e_remember_update(bd);
}
EAPI void
e_border_iconify(E_Border *bd)
{
E_Event_Border_Iconify *ev;
unsigned int iconic;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->shading) return;
ecore_x_window_shadow_tree_flush();
if (!bd->iconic)
{
bd->iconic = 1;
e_border_hide(bd, 1);
if (bd->fullscreen) bd->desk->fullscreen_borders--;
edje_object_signal_emit(bd->bg_object, "e,action,iconify", "e");
}
iconic = 1;
e_hints_window_iconic_set(bd);
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_MAPPED, &iconic, 1);
ev = E_NEW(E_Event_Border_Iconify, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_iconify_event");
ecore_event_add(E_EVENT_BORDER_ICONIFY, ev, _e_border_event_border_iconify_free, NULL);
if (e_config->transient.iconify)
{
E_Border *child;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_FREE(list, child)
e_border_iconify(child);
}
e_remember_update(bd);
}
EAPI void
e_border_uniconify(E_Border *bd)
{
E_Desk *desk;
E_Event_Border_Uniconify *ev;
unsigned int iconic;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->shading) return;
ecore_x_window_shadow_tree_flush();
e_border_show(bd);
if (bd->iconic)
{
bd->iconic = 0;
if (bd->fullscreen) bd->desk->fullscreen_borders++;
desk = e_desk_current_get(bd->desk->zone);
e_border_desk_set(bd, desk);
e_border_raise(bd);
edje_object_signal_emit(bd->bg_object, "e,action,uniconify", "e");
}
iconic = 0;
ecore_x_window_prop_card32_set(bd->client.win, E_ATOM_MAPPED, &iconic, 1);
ev = E_NEW(E_Event_Border_Uniconify, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_uniconify_event");
ecore_event_add(E_EVENT_BORDER_UNICONIFY, ev, _e_border_event_border_uniconify_free, NULL);
if (e_config->transient.iconify)
{
E_Border *child;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_FREE(list, child)
e_border_uniconify(child);
}
e_remember_update(bd);
}
EAPI void
e_border_stick(E_Border *bd)
{
E_Event_Border_Stick *ev;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->sticky) return;
bd->sticky = 1;
e_hints_window_sticky_set(bd, 1);
e_border_show(bd);
if (e_config->transient.desktop)
{
E_Border *child;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_FREE(list, child)
{
child->sticky = 1;
e_hints_window_sticky_set(child, 1);
e_border_show(child);
}
}
edje_object_signal_emit(bd->bg_object, "e,state,sticky", "e");
ev = E_NEW(E_Event_Border_Stick, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_stick_event");
ecore_event_add(E_EVENT_BORDER_STICK, ev, _e_border_event_border_stick_free, NULL);
e_remember_update(bd);
}
EAPI void
e_border_unstick(E_Border *bd)
{
E_Event_Border_Unstick *ev;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
/* Set the desk before we unstick the border */
if (!bd->sticky) return;
bd->sticky = 0;
e_hints_window_sticky_set(bd, 0);
if (e_config->transient.desktop)
{
E_Border *child;
Eina_List *list = _e_border_sub_borders_new(bd);
EINA_LIST_FREE(list, child)
{
child->sticky = 0;
e_hints_window_sticky_set(child, 0);
}
}
edje_object_signal_emit(bd->bg_object, "e,state,unsticky", "e");
ev = E_NEW(E_Event_Border_Unstick, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_unstick_event");
ecore_event_add(E_EVENT_BORDER_UNSTICK, ev, _e_border_event_border_unstick_free, NULL);
e_border_desk_set(bd, e_desk_current_get(bd->zone));
e_remember_update(bd);
}
EAPI void
e_border_pinned_set(E_Border *bd,
int set)
{
E_Layer layer;
if (bd)
{
bd->borderless = set;
bd->user_skip_winlist = set;
if (set)
layer = E_LAYER_BELOW;
else
layer = E_LAYER_NORMAL;
e_border_layer_set(bd, layer);
bd->client.border.changed = 1;
bd->changed = 1;
}
}
EAPI E_Border *
e_border_find_by_client_window(Ecore_X_Window win)
{
E_Border *bd;
bd = eina_hash_find(borders_hash, e_util_winid_str_get(win));
if ((bd) && (!e_object_is_del(E_OBJECT(bd))) &&
(bd->client.win == win))
return bd;
return NULL;
}
EAPI E_Border *
e_border_find_all_by_client_window(Ecore_X_Window win)
{
E_Border *bd;
bd = eina_hash_find(borders_hash, e_util_winid_str_get(win));
if ((bd) && (bd->client.win == win))
return bd;
return NULL;
}
EAPI E_Border *
e_border_find_by_frame_window(Ecore_X_Window win)
{
E_Border *bd;
bd = eina_hash_find(borders_hash, e_util_winid_str_get(win));
if ((bd) && (!e_object_is_del(E_OBJECT(bd))) &&
(bd->bg_win == win))
return bd;
return NULL;
}
EAPI E_Border *
e_border_find_by_window(Ecore_X_Window win)
{
E_Border *bd;
bd = eina_hash_find(borders_hash, e_util_winid_str_get(win));
if ((bd) && (!e_object_is_del(E_OBJECT(bd))) &&
((bd->win == win) || (bd->client.lock_win == win)))
return bd;
return NULL;
}
EAPI E_Border *
e_border_find_by_alarm(Ecore_X_Sync_Alarm al)
{
Eina_List *l;
E_Border *bd;
EINA_LIST_FOREACH(borders, l, bd)
{
if ((bd) && (!e_object_is_del(E_OBJECT(bd))) &&
(bd->client.netwm.sync.alarm == al))
return bd;
}
return NULL;
}
EAPI E_Border *
e_border_focused_get(void)
{
return focused;
}
static void
_e_border_shape_input_rectangle_set(E_Border *bd)
{
if (!bd) return;
if ((bd->visible) && (bd->shaped_input))
{
Ecore_X_Rectangle rects[4];
Ecore_X_Window twin, twin2;
int x, y;
twin = ecore_x_window_override_new(bd->zone->container->scratch_win,
0, 0, bd->w, bd->h);
rects[0].x = 0;
rects[0].y = 0;
rects[0].width = bd->w;
rects[0].height = bd->client_inset.t;
rects[1].x = 0;
rects[1].y = bd->client_inset.t;
rects[1].width = bd->client_inset.l;
rects[1].height = bd->h - bd->client_inset.t - bd->client_inset.b;
rects[2].x = bd->w - bd->client_inset.r;
rects[2].y = bd->client_inset.t;
rects[2].width = bd->client_inset.r;
rects[2].height = bd->h - bd->client_inset.t - bd->client_inset.b;
rects[3].x = 0;
rects[3].y = bd->h - bd->client_inset.b;
rects[3].width = bd->w;
rects[3].height = bd->client_inset.b;
ecore_x_window_shape_input_rectangles_set(twin, rects, 4);
twin2 = ecore_x_window_override_new
(bd->zone->container->scratch_win, 0, 0,
bd->w - bd->client_inset.l - bd->client_inset.r,
bd->h - bd->client_inset.t - bd->client_inset.b);
x = 0;
y = 0;
if ((bd->shading) || (bd->shaded))
{
if (bd->shade.dir == E_DIRECTION_UP)
y = bd->h - bd->client_inset.t - bd->client_inset.b -
bd->client.h;
else if (bd->shade.dir == E_DIRECTION_LEFT)
x = bd->w - bd->client_inset.l - bd->client_inset.r -
bd->client.w;
}
ecore_x_window_shape_input_window_set_xy(twin2, bd->client.win,
x, y);
ecore_x_window_shape_input_rectangle_clip(twin2, 0, 0,
bd->w - bd->client_inset.l - bd->client_inset.r,
bd->h - bd->client_inset.t - bd->client_inset.b);
ecore_x_window_shape_input_window_add_xy(twin, twin2,
bd->client_inset.l,
bd->client_inset.t);
ecore_x_window_shape_input_window_set(bd->win, twin);
ecore_x_window_free(twin2);
ecore_x_window_free(twin);
}
else
{
if (bd->visible) // not shaped input
{
if (!((bd->comp_hidden) || (bd->tmp_input_hidden > 0)))
ecore_x_composite_window_events_enable(bd->win);
else
ecore_x_composite_window_events_disable(bd->win);
}
else
{
if (!e_manager_comp_evas_get(bd->zone->container->manager))
ecore_x_composite_window_events_enable(bd->win);
else
ecore_x_composite_window_events_disable(bd->win);
}
}
}
EAPI void
e_border_idler_before(void)
{
Eina_List *ml, *cl;
E_Manager *man;
E_Container *con;
if (!borders)
return;
EINA_LIST_FOREACH(e_manager_list(), ml, man)
{
EINA_LIST_FOREACH(man->containers, cl, con)
{
E_Border_List *bl;
E_Border *bd;
// pass 1 - eval0. fetch properties on new or on change and
// call hooks to decide what to do - maybe move/resize
bl = e_container_border_list_last(con);
while ((bd = e_container_border_list_prev(bl)))
{
if (bd->changed) _e_border_eval0(bd);
}
e_container_border_list_free(bl);
// layout hook - this is where a hook gets to figure out what to
// do if anything.
_e_border_container_layout_hook(con);
// pass 2 - show windows needing show
bl = e_container_border_list_last(con);
while ((bd = e_container_border_list_prev(bl)))
{
if ((bd->changes.visible) && (bd->visible) &&
(!bd->new_client) && (!bd->changes.pos) &&
(!bd->changes.size))
{
_e_border_show(bd);
bd->changes.visible = 0;
}
if (bd->zone && (!bd->new_client) &&
(!E_INSIDE(bd->x, bd->y, 0, 0, bd->zone->w - 5, bd->zone->h - 5)) &&
(!E_INSIDE(bd->x, bd->y, 0 - bd->w + 5, 0 - bd->h + 5, bd->zone->w - 5, bd->zone->h - 5))
)
{
if (e_config->screen_limits != E_SCREEN_LIMITS_COMPLETELY)
_e_border_move_lost_window_to_center(bd);
}
}
e_container_border_list_free(bl);
// pass 3 - hide windows needing hide and eval (main eval)
bl = e_container_border_list_first(con);
while ((bd = e_container_border_list_next(bl)))
{
if (e_object_is_del(E_OBJECT(bd))) continue;
if ((bd->changes.visible) && (!bd->visible))
{
_e_border_hide(bd);
bd->changes.visible = 0;
}
if (bd->changed) _e_border_eval(bd);
if ((bd->changes.visible) && (bd->visible))
{
_e_border_show(bd);
bd->changes.visible = 0;
}
}
e_container_border_list_free(bl);
}
}
if (focus_next)
{
E_Border *bd = NULL, *bd2;
EINA_LIST_FREE(focus_next, bd2)
if ((!bd) && (bd2->visible)) bd = bd2;
if (!bd)
{
/* TODO revert focus when lost here ? */
return;
}
#if 0
if (bd == focused)
{
/* already focused. but anyway dont be so strict, this
fcks up illume setting focus on internal windows */
return;
}
#endif
focus_time = ecore_x_current_time_get();
focusing = bd;
if ((bd->client.icccm.take_focus) &&
(bd->client.icccm.accepts_focus))
{
e_grabinput_focus(bd->client.win, E_FOCUS_METHOD_LOCALLY_ACTIVE);
/* TODO what if the client didn't take focus ? */
}
else if (!bd->client.icccm.accepts_focus)
{
e_grabinput_focus(bd->client.win, E_FOCUS_METHOD_GLOBALLY_ACTIVE);
}
else if (!bd->client.icccm.take_focus)
{
e_grabinput_focus(bd->client.win, E_FOCUS_METHOD_PASSIVE);
/* e_border_focus_set(bd, 1, 0); */
}
}
}
EAPI Eina_List *
e_border_client_list(void)
{
/* FIXME: This should be a somewhat ordered list */
return borders;
}
static Ecore_X_Window action_input_win = 0;
static E_Border *action_border = NULL;
static Ecore_Event_Handler *action_handler_key = NULL;
static Ecore_Event_Handler *action_handler_mouse = NULL;
static Ecore_Timer *action_timer = NULL;
static Ecore_X_Rectangle action_orig;
static void
_e_border_show(E_Border *bd)
{
Eina_List *l;
E_Border *tmp;
ecore_evas_show(bd->bg_ecore_evas);
if (bd->post_job)
{
bd->post_show = 1;
return;
}
if (!((bd->comp_hidden) || (bd->tmp_input_hidden > 0)))
{
_e_border_shape_input_rectangle_set(bd);
// not anymore
// ecore_x_composite_window_events_enable(bd->win);
ecore_x_window_ignore_set(bd->win, EINA_FALSE);
}
ecore_x_window_show(bd->win);
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
ecore_x_window_show(tmp->win);
}
static void
_e_border_hide(E_Border *bd)
{
E_Border *tmp;
Eina_List *l;
if (!e_manager_comp_evas_get(bd->zone->container->manager))
{
ecore_x_window_hide(bd->win);
ecore_evas_hide(bd->bg_ecore_evas);
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
ecore_x_window_hide(tmp->win);
}
else
{
ecore_x_composite_window_events_disable(bd->win);
ecore_x_window_ignore_set(bd->win, EINA_TRUE);
}
}
static int
_e_border_action_input_win_del(void)
{
if (!action_input_win)
return 0;
e_grabinput_release(action_input_win, action_input_win);
ecore_x_window_free(action_input_win);
action_input_win = 0;
return 1;
}
static int
_e_border_action_input_win_new(E_Border *bd)
{
if (!action_input_win)
{
Ecore_X_Window parent = bd->zone->container->win;
action_input_win = ecore_x_window_input_new(parent, 0, 0, 1, 1);
if (!action_input_win)
return 0;
}
ecore_x_window_show(action_input_win);
if (e_grabinput_get(action_input_win, 0, action_input_win))
return 1;
_e_border_action_input_win_del();
return 0;
}
static void
_e_border_action_finish(void)
{
_e_border_action_input_win_del();
if (action_timer)
{
ecore_timer_del(action_timer);
action_timer = NULL;
}
if (action_handler_key)
{
ecore_event_handler_del(action_handler_key);
action_handler_key = NULL;
}
if (action_handler_mouse)
{
ecore_event_handler_del(action_handler_mouse);
action_handler_mouse = NULL;
}
action_border = NULL;
}
static void
_e_border_action_init(E_Border *bd)
{
action_orig.x = bd->x;
action_orig.y = bd->y;
action_orig.width = bd->w;
action_orig.height = bd->h;
action_border = bd;
}
static void
_e_border_action_restore_orig(E_Border *bd)
{
if (action_border != bd)
return;
e_border_move_resize(bd, action_orig.x, action_orig.y, action_orig.width, action_orig.height);
}
static int
_e_border_key_down_modifier_apply(int modifier,
int value)
{
if (modifier & ECORE_EVENT_MODIFIER_CTRL)
return value * 2;
else if (modifier & ECORE_EVENT_MODIFIER_ALT)
{
value /= 2;
if (value)
return value;
else
return 1;
}
return value;
}
static Eina_Bool
_e_border_action_move_timeout(void *data __UNUSED__)
{
_e_border_move_end(action_border);
_e_border_action_finish();
return ECORE_CALLBACK_CANCEL;
}
static void
_e_border_action_move_timeout_add(void)
{
E_FREE_FUNC(action_timer, ecore_timer_del);
if (e_config->border_keyboard.timeout)
action_timer = ecore_timer_add(e_config->border_keyboard.timeout, _e_border_action_move_timeout, NULL);
}
static Eina_Bool
_e_border_move_key_down(void *data __UNUSED__,
int type __UNUSED__,
void *event)
{
Ecore_Event_Key *ev = event;
int x, y;
if (ev->event_window != action_input_win)
return ECORE_CALLBACK_PASS_ON;
if (!action_border)
{
fputs("ERROR: no action_border!\n", stderr);
goto stop;
}
x = action_border->x;
y = action_border->y;
if ((strcmp(ev->key, "Up") == 0) || (strcmp(ev->key, "k") == 0))
y -= _e_border_key_down_modifier_apply(ev->modifiers, MAX(e_config->border_keyboard.move.dy, 1));
else if ((strcmp(ev->key, "Down") == 0) || (strcmp(ev->key, "j") == 0))
y += _e_border_key_down_modifier_apply(ev->modifiers, MAX(e_config->border_keyboard.move.dy, 1));
else if ((strcmp(ev->key, "Left") == 0) || (strcmp(ev->key, "h") == 0))
x -= _e_border_key_down_modifier_apply(ev->modifiers, MAX(e_config->border_keyboard.move.dx, 1));
else if ((strcmp(ev->key, "Right") == 0) || (strcmp(ev->key, "l") == 0))
x += _e_border_key_down_modifier_apply(ev->modifiers, MAX(e_config->border_keyboard.move.dx, 1));
else if (strcmp(ev->key, "Return") == 0)
goto stop;
else if (strcmp(ev->key, "Escape") == 0)
{
_e_border_action_restore_orig(action_border);
goto stop;
}
else if ((strncmp(ev->key, "Control", sizeof("Control") - 1) != 0) &&
(strncmp(ev->key, "Alt", sizeof("Alt") - 1) != 0))
goto stop;
e_border_move(action_border, x, y);
_e_border_action_move_timeout_add();
return ECORE_CALLBACK_PASS_ON;
stop:
_e_border_move_end(action_border);
_e_border_action_finish();
return ECORE_CALLBACK_DONE;
}
static Eina_Bool
_e_border_move_mouse_down(void *data __UNUSED__,
int type __UNUSED__,
void *event)
{
Ecore_Event_Mouse_Button *ev = event;
if (ev->event_window != action_input_win)
return ECORE_CALLBACK_PASS_ON;
if (!action_border)
fputs("ERROR: no action_border!\n", stderr);
_e_border_move_end(action_border);
_e_border_action_finish();
return ECORE_CALLBACK_DONE;
}
EAPI void
e_border_act_move_keyboard(E_Border *bd)
{
if (!bd)
return;
if (!_e_border_move_begin(bd))
return;
if (!_e_border_action_input_win_new(bd))
{
_e_border_move_end(bd);
return;
}
_e_border_action_init(bd);
_e_border_action_move_timeout_add();
_e_border_move_update(bd);
if (action_handler_key)
ecore_event_handler_del(action_handler_key);
action_handler_key = ecore_event_handler_add(ECORE_EVENT_KEY_DOWN, _e_border_move_key_down, NULL);
if (action_handler_mouse)
ecore_event_handler_del(action_handler_mouse);
action_handler_mouse = ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, _e_border_move_mouse_down, NULL);
}
static Eina_Bool
_e_border_action_resize_timeout(void *data __UNUSED__)
{
_e_border_resize_end(action_border);
_e_border_action_finish();
return ECORE_CALLBACK_CANCEL;
}
static void
_e_border_action_resize_timeout_add(void)
{
E_FREE_FUNC(action_timer, ecore_timer_del);
if (e_config->border_keyboard.timeout)
action_timer = ecore_timer_add(e_config->border_keyboard.timeout, _e_border_action_resize_timeout, NULL);
}
static Eina_Bool
_e_border_resize_key_down(void *data __UNUSED__,
int type __UNUSED__,
void *event)
{
Ecore_Event_Key *ev = event;
int w, h, dx, dy;
if (ev->event_window != action_input_win)
return ECORE_CALLBACK_PASS_ON;
if (!action_border)
{
fputs("ERROR: no action_border!\n", stderr);
goto stop;
}
w = action_border->w;
h = action_border->h;
dx = e_config->border_keyboard.resize.dx;
if (dx < action_border->client.icccm.step_w)
dx = action_border->client.icccm.step_w;
dx = _e_border_key_down_modifier_apply(ev->modifiers, dx);
if (dx < action_border->client.icccm.step_w)
dx = action_border->client.icccm.step_w;
dy = e_config->border_keyboard.resize.dy;
if (dy < action_border->client.icccm.step_h)
dy = action_border->client.icccm.step_h;
dy = _e_border_key_down_modifier_apply(ev->modifiers, dy);
if (dy < action_border->client.icccm.step_h)
dy = action_border->client.icccm.step_h;
if ((strcmp(ev->key, "Up") == 0) || (strcmp(ev->key, "k") == 0))
h -= dy;
else if ((strcmp(ev->key, "Down") == 0) || (strcmp(ev->key, "j") == 0))
h += dy;
else if ((strcmp(ev->key, "Left") == 0) || (strcmp(ev->key, "h") == 0))
w -= dx;
else if ((strcmp(ev->key, "Right") == 0) || (strcmp(ev->key, "l") == 0))
w += dx;
else if (strcmp(ev->key, "Return") == 0)
goto stop;
else if (strcmp(ev->key, "Escape") == 0)
{
_e_border_action_restore_orig(action_border);
goto stop;
}
else if ((strncmp(ev->key, "Control", sizeof("Control") - 1) != 0) &&
(strncmp(ev->key, "Alt", sizeof("Alt") - 1) != 0))
goto stop;
e_border_resize_limit(action_border, &w, &h);
e_border_resize(action_border, w, h);
_e_border_action_resize_timeout_add();
return ECORE_CALLBACK_PASS_ON;
stop:
_e_border_resize_end(action_border);
_e_border_action_finish();
return ECORE_CALLBACK_DONE;
}
static Eina_Bool
_e_border_resize_mouse_down(void *data __UNUSED__,
int type __UNUSED__,
void *event)
{
Ecore_Event_Mouse_Button *ev = event;
if (ev->event_window != action_input_win)
return ECORE_CALLBACK_PASS_ON;
if (!action_border)
fputs("ERROR: no action_border!\n", stderr);
_e_border_resize_end(action_border);
_e_border_action_finish();
return ECORE_CALLBACK_DONE;
}
EAPI void
e_border_act_resize_keyboard(E_Border *bd)
{
if (!bd)
return;
if (!_e_border_resize_begin(bd))
return;
if (!_e_border_action_input_win_new(bd))
{
_e_border_resize_end(bd);
return;
}
_e_border_action_init(bd);
_e_border_action_resize_timeout_add();
_e_border_resize_update(bd);
if (action_handler_key)
ecore_event_handler_del(action_handler_key);
action_handler_key = ecore_event_handler_add(ECORE_EVENT_KEY_DOWN, _e_border_resize_key_down, NULL);
if (action_handler_mouse)
ecore_event_handler_del(action_handler_mouse);
action_handler_mouse = ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, _e_border_resize_mouse_down, NULL);
}
EAPI void
e_border_act_move_begin(E_Border *bd,
Ecore_Event_Mouse_Button *ev)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((bd->resize_mode != RESIZE_NONE) || (bd->moving)) return;
if (!_e_border_move_begin(bd))
return;
e_zone_edge_disable();
bd->moving = 1;
_e_border_pointer_move_begin(bd);
if (ev)
{
char source[256];
snprintf(source, sizeof(source) - 1, "mouse,down,%i", ev->buttons);
_e_border_moveinfo_gather(bd, source);
}
}
EAPI void
e_border_act_move_end(E_Border *bd,
Ecore_Event_Mouse_Button *ev __UNUSED__)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (!bd->moving) return;
bd->moving = 0;
_e_border_pointer_move_end(bd);
e_zone_edge_enable();
_e_border_move_end(bd);
e_zone_flip_coords_handle(bd->zone, -1, -1);
}
EAPI void
e_border_act_resize_begin(E_Border *bd,
Ecore_Event_Mouse_Button *ev)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->lock_user_size) return;
if ((bd->resize_mode != RESIZE_NONE) || (bd->moving)) return;
if (!_e_border_resize_begin(bd))
return;
if (bd->mouse.current.mx < (bd->x + bd->w / 2))
{
if (bd->mouse.current.my < (bd->y + bd->h / 2))
{
bd->resize_mode = RESIZE_TL;
GRAV_SET(bd, ECORE_X_GRAVITY_SE);
}
else
{
bd->resize_mode = RESIZE_BL;
GRAV_SET(bd, ECORE_X_GRAVITY_NE);
}
}
else
{
if (bd->mouse.current.my < (bd->y + bd->h / 2))
{
bd->resize_mode = RESIZE_TR;
GRAV_SET(bd, ECORE_X_GRAVITY_SW);
}
else
{
bd->resize_mode = RESIZE_BR;
GRAV_SET(bd, ECORE_X_GRAVITY_NW);
}
}
_e_border_pointer_resize_begin(bd);
if (ev)
{
char source[256];
snprintf(source, sizeof(source) - 1, "mouse,down,%i", ev->buttons);
_e_border_moveinfo_gather(bd, source);
}
}
EAPI void
e_border_act_resize_end(E_Border *bd,
Ecore_Event_Mouse_Button *ev __UNUSED__)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->resize_mode != RESIZE_NONE)
{
_e_border_pointer_resize_end(bd);
bd->resize_mode = RESIZE_NONE;
_e_border_resize_end(bd);
bd->changes.reset_gravity = 1;
bd->changed = 1;
}
}
EAPI void
e_border_act_menu_begin(E_Border *bd,
Ecore_Event_Mouse_Button *ev,
int key)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->border_menu) return;
if (ev)
{
e_int_border_menu_show(bd,
bd->x + bd->fx.x + ev->x - bd->zone->container->x,
bd->y + bd->fx.y + ev->y - bd->zone->container->y, key,
ev->timestamp);
}
else
{
int x, y;
ecore_x_pointer_xy_get(bd->zone->container->win, &x, &y);
e_int_border_menu_show(bd, x, y, key, 0);
}
}
EAPI void
e_border_act_close_begin(E_Border *bd)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->lock_close) return;
if (bd->client.icccm.delete_request)
{
bd->delete_requested = 1;
ecore_x_window_delete_request_send(bd->client.win);
if (bd->client.netwm.ping)
e_border_ping(bd);
}
else if (e_config->kill_if_close_not_possible)
{
e_border_act_kill_begin(bd);
}
}
EAPI void
e_border_act_kill_begin(E_Border *bd)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->internal) return;
if (bd->lock_close) return;
if ((bd->client.netwm.pid > 1) && (e_config->kill_process))
{
kill(bd->client.netwm.pid, SIGINT);
bd->kill_timer = ecore_timer_add(e_config->kill_timer_wait,
_e_border_cb_kill_timer, bd);
}
else
{
if (!bd->internal) ecore_x_kill(bd->client.win);
}
}
EAPI Evas_Object *
e_border_icon_add(E_Border *bd,
Evas *evas)
{
Evas_Object *o;
E_OBJECT_CHECK_RETURN(bd, NULL);
E_OBJECT_TYPE_CHECK_RETURN(bd, E_BORDER_TYPE, NULL);
o = NULL;
if (bd->internal)
{
if (!bd->internal_icon)
{
o = e_icon_add(evas);
e_util_icon_theme_set(o, "enlightenment");
}
else
{
if (!bd->internal_icon_key)
{
char *ext;
ext = strrchr(bd->internal_icon, '.');
if ((ext) && ((!strcmp(ext, ".edj"))))
{
o = edje_object_add(evas);
if (!edje_object_file_set(o, bd->internal_icon, "icon"))
e_util_icon_theme_set(o, "enlightenment");
}
else if (ext)
{
o = e_icon_add(evas);
e_icon_file_set(o, bd->internal_icon);
}
else
{
o = e_icon_add(evas);
if (!e_util_icon_theme_set(o, bd->internal_icon))
e_util_icon_theme_set(o, "enlightenment");
}
}
else
{
o = edje_object_add(evas);
edje_object_file_set(o, bd->internal_icon,
bd->internal_icon_key);
}
}
return o;
}
if ((e_config->use_app_icon) && (bd->icon_preference != E_ICON_PREF_USER))
{
if (bd->client.netwm.icons)
{
o = e_icon_add(evas);
e_icon_data_set(o, bd->client.netwm.icons[0].data,
bd->client.netwm.icons[0].width,
bd->client.netwm.icons[0].height);
e_icon_alpha_set(o, 1);
return o;
}
}
if (!o)
{
if ((bd->desktop) && (bd->icon_preference != E_ICON_PREF_NETWM))
{
o = e_util_desktop_icon_add(bd->desktop, 64, evas);
if (o)
return o;
}
else if (bd->client.netwm.icons)
{
o = e_icon_add(evas);
e_icon_data_set(o, bd->client.netwm.icons[0].data,
bd->client.netwm.icons[0].width,
bd->client.netwm.icons[0].height);
e_icon_alpha_set(o, 1);
return o;
}
}
o = e_icon_add(evas);
e_util_icon_theme_set(o, "unknown");
return o;
}
EAPI void
e_border_button_bindings_ungrab_all(void)
{
Eina_List *l;
E_Border *bd;
EINA_LIST_FOREACH(borders, l, bd)
{
e_focus_setdown(bd);
e_bindings_mouse_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_bindings_wheel_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
}
}
EAPI void
e_border_button_bindings_grab_all(void)
{
Eina_List *l;
E_Border *bd;
EINA_LIST_FOREACH(borders, l, bd)
{
e_bindings_mouse_grab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_bindings_wheel_grab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_focus_setup(bd);
}
}
EAPI Eina_List *
e_border_focus_stack_get(void)
{
return focus_stack;
}
EAPI Eina_List *
e_border_raise_stack_get(void)
{
return raise_stack;
}
EAPI Eina_List *
e_border_lost_windows_get(E_Zone *zone)
{
Eina_List *list = NULL, *l;
E_Border *bd;
int loss_overlap = 5;
E_OBJECT_CHECK_RETURN(zone, NULL);
E_OBJECT_TYPE_CHECK_RETURN(zone, E_ZONE_TYPE, NULL);
EINA_LIST_FOREACH(borders, l, bd)
{
if (!bd->zone)
continue;
if ((bd->zone != zone) ||
(bd->zone->container != zone->container))
continue;
if (!E_INTERSECTS(bd->zone->x + loss_overlap,
bd->zone->y + loss_overlap,
bd->zone->w - (2 * loss_overlap),
bd->zone->h - (2 * loss_overlap),
bd->x, bd->y, bd->w, bd->h))
{
list = eina_list_append(list, bd);
}
else if ((!E_CONTAINS(bd->zone->x, bd->zone->y,
bd->zone->w, bd->zone->h,
bd->x, bd->y, bd->w, bd->h)) &&
(bd->shaped))
{
Ecore_X_Rectangle *rect;
int i, num;
rect = ecore_x_window_shape_rectangles_get(bd->win, &num);
if (rect)
{
int ok;
ok = 0;
for (i = 0; i < num; i++)
{
if (E_INTERSECTS(bd->zone->x + loss_overlap,
bd->zone->y + loss_overlap,
bd->zone->w - (2 * loss_overlap),
bd->zone->h - (2 * loss_overlap),
rect[i].x, rect[i].y,
(int)rect[i].width, (int)rect[i].height))
{
ok = 1;
break;
}
}
free(rect);
if (!ok)
list = eina_list_append(list, bd);
}
}
}
return list;
}
static void
_e_border_zones_layout_calc(E_Border *bd, int *zx, int *zy, int *zw, int *zh)
{
int x, y, w, h;
E_Zone *zone_above, *zone_below, *zone_left, *zone_right;
x = bd->zone->x;
y = bd->zone->y;
w = bd->zone->w;
h = bd->zone->h;
if (eina_list_count(bd->zone->container->zones) == 1)
{
if (zx) *zx = x;
if (zy) *zy = y;
if (zw) *zw = w;
if (zh) *zh = h;
return;
}
zone_left = e_container_zone_at_point_get(bd->zone->container, (x - w + 5), y);
zone_right = e_container_zone_at_point_get(bd->zone->container, (x + w + 5), y);
zone_above = e_container_zone_at_point_get(bd->zone->container, x, (y - h + 5));
zone_below = e_container_zone_at_point_get(bd->zone->container, x, (y + h + 5));
if (!(zone_above) && (y))
zone_above = e_container_zone_at_point_get(bd->zone->container, x, (h - 5));
if (!(zone_left) &&(x))
zone_left = e_container_zone_at_point_get(bd->zone->container, (x - 5), y);
if (zone_right)
w = zone_right->x + zone_right->w;
if (zone_left)
w = bd->zone->x + bd->zone->w;
if (zone_below)
h = zone_below->y + zone_below->h;
if (zone_above)
h = bd->zone->y + bd->zone->h;
if ((zone_left) && (zone_right))
w = bd->zone->w + zone_right->x;
if ((zone_above) && (zone_below))
h = bd->zone->h + zone_below->y;
if (x) x -= bd->zone->w;
if (y) y -= bd->zone->h;
if (zx) *zx = x > 0 ? x : 0;
if (zy) *zy = y > 0 ? y : 0;
if (zw) *zw = w;
if (zh) *zh = h;
}
static void
_e_border_move_lost_window_to_center(E_Border *bd)
{
int loss_overlap = 5;
int zw, zh, zx, zy;
if (bd->during_lost) return;
if (!(bd->zone)) return;
_e_border_zones_layout_calc(bd, &zx, &zy, &zw, &zh);
if (!E_INTERSECTS(zx + loss_overlap,
zy + loss_overlap,
zw - (2 * loss_overlap),
zh - (2 * loss_overlap),
bd->x, bd->y, bd->w, bd->h))
{
if (e_config->edge_flip_dragging)
{
Eina_Bool lf, rf, tf, bf;
lf = rf = tf = bf = EINA_TRUE;
if (bd->zone->desk_x_count <= 1) lf = rf = EINA_FALSE;
else if (!e_config->desk_flip_wrap)
{
if (bd->zone->desk_x_current == 0) lf = EINA_FALSE;
if (bd->zone->desk_x_current == (bd->zone->desk_x_count - 1)) rf = EINA_FALSE;
}
if (bd->zone->desk_y_count <= 1) tf = bf = EINA_FALSE;
else if (!e_config->desk_flip_wrap)
{
if (bd->zone->desk_y_current == 0) tf = EINA_FALSE;
if (bd->zone->desk_y_current == (bd->zone->desk_y_count - 1)) bf = EINA_FALSE;
}
if (!(lf) && (bd->x <= loss_overlap) && !(bd->zone->flip.switching))
_e_border_reset_lost_window(bd);
if (!(rf) && (bd->x >= (bd->zone->w - loss_overlap)) && !(bd->zone->flip.switching))
_e_border_reset_lost_window(bd);
if (!(tf) && (bd->y <= loss_overlap) && !(bd->zone->flip.switching))
_e_border_reset_lost_window(bd);
if (!(bf) && (bd->y >= (bd->zone->h - loss_overlap)) && !(bd->zone->flip.switching))
_e_border_reset_lost_window(bd);
}
if (!e_config->edge_flip_dragging)
_e_border_reset_lost_window(bd);
}
}
static void
_e_border_reset_lost_window(E_Border *bd)
{
int x, y, w, h;
E_OBJECT_CHECK(bd);
if (bd->during_lost) return ;
bd->during_lost = EINA_TRUE;
if (bd->iconic) e_border_uniconify(bd);
if (!bd->moving) e_border_center(bd);
e_zone_useful_geometry_get(bd->zone, &x, &y, &w, &h);
ecore_x_pointer_xy_get(bd->zone->container->win, &warp_x[0], &warp_y[0]);
warp_to_x = x + ((w / 2) - (bd->w / 2)) + (warp_x[0] - bd->x);
warp_to_y = y + ((h / 2) - (bd->h / 2)) + (warp_y[0] - bd->y);
warp_to = 1;
warp_to_win = bd->zone->container->win;
if (warp_timer) ecore_timer_del(warp_timer);
warp_timer = ecore_timer_add(0.01, _e_border_pointer_warp_to_center_timer, bd);
e_border_raise(bd);
if (!bd->lock_focus_out)
e_border_focus_set(bd, 1, 1);
bd->during_lost = EINA_FALSE;
e_border_focus_lock_set(EINA_TRUE);
warp_timer_border = bd;
}
EAPI void
e_border_ping(E_Border *bd)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (!e_config->ping_clients) return;
bd->ping_ok = 0;
ecore_x_netwm_ping_send(bd->client.win);
bd->ping = ecore_loop_time_get();
if (bd->ping_poller) ecore_poller_del(bd->ping_poller);
bd->ping_poller = ecore_poller_add(ECORE_POLLER_CORE,
e_config->ping_clients_interval,
_e_border_cb_ping_poller, bd);
}
EAPI void
e_border_move_cancel(void)
{
if (bdmove)
{
if (bdmove->cur_mouse_action)
{
E_Border *bd;
bd = bdmove;
e_object_ref(E_OBJECT(bd));
if (bd->cur_mouse_action->func.end_mouse)
bd->cur_mouse_action->func.end_mouse(E_OBJECT(bd), "", NULL);
else if (bd->cur_mouse_action->func.end)
bd->cur_mouse_action->func.end(E_OBJECT(bd), "");
e_object_unref(E_OBJECT(bd->cur_mouse_action));
bd->cur_mouse_action = NULL;
e_object_unref(E_OBJECT(bd));
}
else
_e_border_move_end(bdmove);
}
}
EAPI void
e_border_resize_cancel(void)
{
if (bdresize)
{
if (bdresize->cur_mouse_action)
{
E_Border *bd;
bd = bdresize;
e_object_ref(E_OBJECT(bd));
if (bd->cur_mouse_action->func.end_mouse)
bd->cur_mouse_action->func.end_mouse(E_OBJECT(bd), "", NULL);
else if (bd->cur_mouse_action->func.end)
bd->cur_mouse_action->func.end(E_OBJECT(bd), "");
e_object_unref(E_OBJECT(bd->cur_mouse_action));
bd->cur_mouse_action = NULL;
e_object_unref(E_OBJECT(bd));
}
else
{
bdresize->resize_mode = RESIZE_NONE;
_e_border_resize_end(bdresize);
}
}
}
EAPI void
e_border_frame_recalc(E_Border *bd)
{
if (!bd->bg_object) return;
bd->w -= (bd->client_inset.l + bd->client_inset.r);
bd->h -= (bd->client_inset.t + bd->client_inset.b);
_e_border_client_inset_calc(bd);
bd->w += (bd->client_inset.l + bd->client_inset.r);
bd->h += (bd->client_inset.t + bd->client_inset.b);
bd->changed = 1;
bd->changes.size = 1;
if ((bd->shaped) || (bd->client.shaped))
{
bd->need_shape_merge = 1;
bd->need_shape_export = 1;
}
if (bd->shaped_input)
{
bd->need_shape_merge = 1;
}
_e_border_client_move_resize_send(bd);
}
EAPI Eina_List *
e_border_immortal_windows_get(void)
{
Eina_List *list = NULL, *l;
E_Border *bd;
EINA_LIST_FOREACH(borders, l, bd)
{
if (bd->lock_life)
list = eina_list_append(list, bd);
}
return list;
}
EAPI const char *
e_border_name_get(const E_Border *bd)
{
E_OBJECT_CHECK_RETURN(bd, "");
E_OBJECT_TYPE_CHECK_RETURN(bd, E_BORDER_TYPE, "");
if (bd->client.netwm.name)
return bd->client.netwm.name;
else if (bd->client.icccm.title)
return bd->client.icccm.title;
return "";
}
EAPI void
e_border_signal_move_begin(E_Border *bd,
const char *sig,
const char *src __UNUSED__)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((bd->resize_mode != RESIZE_NONE) || (bd->moving)) return;
if (!_e_border_move_begin(bd)) return;
bd->moving = 1;
_e_border_pointer_move_begin(bd);
e_zone_edge_disable();
_e_border_moveinfo_gather(bd, sig);
if (bd->cur_mouse_action)
{
if ((!bd->cur_mouse_action->func.end_mouse) &&
(!bd->cur_mouse_action->func.end))
bd->cur_mouse_action = NULL;
else
e_object_unref(E_OBJECT(bd->cur_mouse_action));
}
bd->cur_mouse_action = e_action_find("window_move");
if (bd->cur_mouse_action)
e_object_ref(E_OBJECT(bd->cur_mouse_action));
}
EAPI void
e_border_signal_move_end(E_Border *bd,
const char *sig __UNUSED__,
const char *src __UNUSED__)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (!bd->moving) return;
bd->moving = 0;
_e_border_pointer_move_end(bd);
e_zone_edge_enable();
_e_border_move_end(bd);
e_zone_flip_coords_handle(bd->zone, -1, -1);
}
EAPI int
e_border_resizing_get(E_Border *bd)
{
E_OBJECT_CHECK_RETURN(bd, 0);
E_OBJECT_TYPE_CHECK_RETURN(bd, E_BORDER_TYPE, 0);
if (bd->resize_mode == RESIZE_NONE) return 0;
return 1;
}
EAPI void
e_border_signal_resize_begin(E_Border *bd,
const char *dir,
const char *sig,
const char *src __UNUSED__)
{
Ecore_X_Gravity grav = ECORE_X_GRAVITY_NW;
int resize_mode = RESIZE_BR;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if ((bd->resize_mode != RESIZE_NONE) || (bd->moving)) return;
if (!_e_border_resize_begin(bd))
return;
if (!strcmp(dir, "tl"))
{
resize_mode = RESIZE_TL;
grav = ECORE_X_GRAVITY_SE;
}
else if (!strcmp(dir, "t"))
{
resize_mode = RESIZE_T;
grav = ECORE_X_GRAVITY_S;
}
else if (!strcmp(dir, "tr"))
{
resize_mode = RESIZE_TR;
grav = ECORE_X_GRAVITY_SW;
}
else if (!strcmp(dir, "r"))
{
resize_mode = RESIZE_R;
grav = ECORE_X_GRAVITY_W;
}
else if (!strcmp(dir, "br"))
{
resize_mode = RESIZE_BR;
grav = ECORE_X_GRAVITY_NW;
}
else if (!strcmp(dir, "b"))
{
resize_mode = RESIZE_B;
grav = ECORE_X_GRAVITY_N;
}
else if (!strcmp(dir, "bl"))
{
resize_mode = RESIZE_BL;
grav = ECORE_X_GRAVITY_NE;
}
else if (!strcmp(dir, "l"))
{
resize_mode = RESIZE_L;
grav = ECORE_X_GRAVITY_E;
}
bd->resize_mode = resize_mode;
_e_border_pointer_resize_begin(bd);
_e_border_moveinfo_gather(bd, sig);
GRAV_SET(bd, grav);
if (bd->cur_mouse_action)
{
if ((!bd->cur_mouse_action->func.end_mouse) &&
(!bd->cur_mouse_action->func.end))
bd->cur_mouse_action = NULL;
else
e_object_unref(E_OBJECT(bd->cur_mouse_action));
}
bd->cur_mouse_action = e_action_find("window_resize");
if (bd->cur_mouse_action)
e_object_ref(E_OBJECT(bd->cur_mouse_action));
}
EAPI void
e_border_signal_resize_end(E_Border *bd,
const char *dir __UNUSED__,
const char *sig __UNUSED__,
const char *src __UNUSED__)
{
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
if (bd->resize_mode == RESIZE_NONE) return;
_e_border_resize_handle(bd);
_e_border_pointer_resize_end(bd);
bd->resize_mode = RESIZE_NONE;
_e_border_resize_end(bd);
bd->changes.reset_gravity = 1;
bd->changed = 1;
}
EAPI void
e_border_resize_limit(E_Border *bd,
int *w,
int *h)
{
double a;
Eina_Bool inc_h;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
inc_h = (*h - bd->h > 0);
*w -= bd->client_inset.l + bd->client_inset.r;
*h -= bd->client_inset.t + bd->client_inset.b;
if (*h < 1) *h = 1;
if (*w < 1) *w = 1;
if ((bd->client.icccm.base_w >= 0) &&
(bd->client.icccm.base_h >= 0))
{
int tw, th;
tw = *w - bd->client.icccm.base_w;
th = *h - bd->client.icccm.base_h;
if (tw < 1) tw = 1;
if (th < 1) th = 1;
a = (double)(tw) / (double)(th);
if ((bd->client.icccm.min_aspect != 0.0) &&
(a < bd->client.icccm.min_aspect))
{
if (inc_h)
tw = th * bd->client.icccm.min_aspect;
else
th = tw / bd->client.icccm.max_aspect;
*w = tw + bd->client.icccm.base_w;
*h = th + bd->client.icccm.base_h;
}
else if ((bd->client.icccm.max_aspect != 0.0) &&
(a > bd->client.icccm.max_aspect))
{
tw = th * bd->client.icccm.max_aspect;
*w = tw + bd->client.icccm.base_w;
}
}
else
{
a = (double)*w / (double)*h;
if ((bd->client.icccm.min_aspect != 0.0) &&
(a < bd->client.icccm.min_aspect))
{
if (inc_h)
*w = *h * bd->client.icccm.min_aspect;
else
*h = *w / bd->client.icccm.min_aspect;
}
else if ((bd->client.icccm.max_aspect != 0.0) &&
(a > bd->client.icccm.max_aspect))
*w = *h * bd->client.icccm.max_aspect;
}
if (bd->client.icccm.step_w > 0)
{
if (bd->client.icccm.base_w >= 0)
*w = bd->client.icccm.base_w +
(((*w - bd->client.icccm.base_w) / bd->client.icccm.step_w) *
bd->client.icccm.step_w);
else
*w = bd->client.icccm.min_w +
(((*w - bd->client.icccm.min_w) / bd->client.icccm.step_w) *
bd->client.icccm.step_w);
}
if (bd->client.icccm.step_h > 0)
{
if (bd->client.icccm.base_h >= 0)
*h = bd->client.icccm.base_h +
(((*h - bd->client.icccm.base_h) / bd->client.icccm.step_h) *
bd->client.icccm.step_h);
else
*h = bd->client.icccm.min_h +
(((*h - bd->client.icccm.min_h) / bd->client.icccm.step_h) *
bd->client.icccm.step_h);
}
if (*h < 1) *h = 1;
if (*w < 1) *w = 1;
if (*w > bd->client.icccm.max_w) *w = bd->client.icccm.max_w;
else if (*w < bd->client.icccm.min_w)
*w = bd->client.icccm.min_w;
if (*h > bd->client.icccm.max_h) *h = bd->client.icccm.max_h;
else if (*h < bd->client.icccm.min_h)
*h = bd->client.icccm.min_h;
*w += bd->client_inset.l + bd->client_inset.r;
*h += bd->client_inset.t + bd->client_inset.b;
}
/* local subsystem functions */
static void
_e_border_free(E_Border *bd)
{
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
if (bd->client.e.state.profile.use)
{
if (bd->client.e.state.profile.available_list)
{
int i;
for (i = 0; i < bd->client.e.state.profile.num; i++)
{
if (bd->client.e.state.profile.available_list[i])
{
eina_stringshare_del(bd->client.e.state.profile.available_list[i]);
bd->client.e.state.profile.available_list[i] = NULL;
}
}
E_FREE(bd->client.e.state.profile.available_list);
bd->client.e.state.profile.available_list = NULL;
}
bd->client.e.state.profile.num = 0;
if (bd->client.e.state.profile.name)
{
eina_stringshare_del(bd->client.e.state.profile.name);
bd->client.e.state.profile.name = NULL;
}
bd->client.e.state.profile.wait_for_done = 0;
bd->client.e.state.profile.use = 0;
}
#endif
if (bd->client.e.state.video_parent && bd->client.e.state.video_parent_border)
{
bd->client.e.state.video_parent_border->client.e.state.video_child =
eina_list_remove
(bd->client.e.state.video_parent_border->client.e.state.video_child,
bd);
}
if (bd->client.e.state.video_child)
{
E_Border *tmp;
EINA_LIST_FREE(bd->client.e.state.video_child, tmp)
{
tmp->client.e.state.video_parent_border = NULL;
}
}
if (bd->desktop)
{
efreet_desktop_free(bd->desktop);
bd->desktop = NULL;
}
if (bd->post_job)
{
ecore_idle_enterer_del(bd->post_job);
bd->post_job = NULL;
}
if (bd->pointer)
{
e_object_del(E_OBJECT(bd->pointer));
bd->pointer = NULL;
}
if (bdresize == bd)
_e_border_resize_end(bd);
if (bdmove == bd)
_e_border_move_end(bd);
/* TODO: Other states to end before dying? */
if (bd->cur_mouse_action)
{
e_object_unref(E_OBJECT(bd->cur_mouse_action));
bd->cur_mouse_action = NULL;
}
E_FREE(bd->shape_rects);
bd->shape_rects_num = 0;
/*
if (bd->dangling_ref_check)
{
ecore_timer_del(bd->dangling_ref_check);
bd->dangling_ref_check = NULL;
}
*/
if (bd->kill_timer)
{
ecore_timer_del(bd->kill_timer);
bd->kill_timer = NULL;
}
if (bd->ping_poller)
{
ecore_poller_del(bd->ping_poller);
bd->ping_poller = NULL;
}
E_FREE_LIST(bd->pending_move_resize, free);
if (bd->shade.anim) ecore_animator_del(bd->shade.anim);
if (bd->border_menu) e_menu_deactivate(bd->border_menu);
if (bd->border_locks_dialog)
{
e_object_del(E_OBJECT(bd->border_locks_dialog));
bd->border_locks_dialog = NULL;
}
if (bd->border_remember_dialog)
{
e_object_del(E_OBJECT(bd->border_remember_dialog));
bd->border_remember_dialog = NULL;
}
if (bd->border_border_dialog)
{
e_object_del(E_OBJECT(bd->border_border_dialog));
bd->border_border_dialog = NULL;
}
if (bd->border_prop_dialog)
{
e_object_del(E_OBJECT(bd->border_prop_dialog));
bd->border_prop_dialog = NULL;
}
e_int_border_menu_del(bd);
if (focusing == bd)
focusing = NULL;
focus_next = eina_list_remove(focus_next, bd);
if ((focused == bd) ||
(e_grabinput_last_focus_win_get() == bd->client.win))
{
if ((!focus_next) && (!focusing))
{
e_grabinput_focus(bd->zone->container->bg_win,
E_FOCUS_METHOD_PASSIVE);
e_hints_active_window_set(bd->zone->container->manager, NULL);
}
focused = NULL;
}
if (warp_timer_border == bd)
{
warp_to = 0;
warp_timer_border = NULL;
if (warp_timer)
{
ecore_timer_del(warp_timer);
warp_timer = NULL;
e_border_focus_lock_set(EINA_FALSE);
}
}
E_FREE_LIST(bd->handlers, ecore_event_handler_del);
if (bd->remember)
{
E_Remember *rem;
rem = bd->remember;
bd->remember = NULL;
e_remember_unuse(rem);
}
if (!bd->already_unparented)
{
ecore_x_window_reparent(bd->client.win, bd->zone->container->manager->root,
bd->x + bd->client_inset.l, bd->y + bd->client_inset.t);
ecore_x_window_save_set_del(bd->client.win);
bd->already_unparented = 1;
}
if (bd->group) eina_list_free(bd->group);
if (bd->transients) eina_list_free(bd->transients);
if (bd->stick_desks) eina_list_free(bd->stick_desks);
if (bd->client.netwm.icons)
{
int i;
for (i = 0; i < bd->client.netwm.num_icons; i++)
free(bd->client.netwm.icons[i].data);
free(bd->client.netwm.icons);
}
free(bd->client.netwm.extra_types);
if (bd->client.border.name)
eina_stringshare_del(bd->client.border.name);
if (bd->bordername)
eina_stringshare_del(bd->bordername);
if (bd->client.icccm.name)
eina_stringshare_del(bd->client.icccm.name);
if (bd->client.icccm.class)
{
if ((!strcasecmp(bd->client.icccm.class, "vmplayer")) || (!strcasecmp(bd->client.icccm.class, "vmware")))
e_bindings_mapping_change_enable(EINA_TRUE);
eina_stringshare_del(bd->client.icccm.class);
}
if (bd->client.icccm.title)
eina_stringshare_del(bd->client.icccm.title);
if (bd->client.icccm.icon_name)
eina_stringshare_del(bd->client.icccm.icon_name);
if (bd->client.icccm.machine)
eina_stringshare_del(bd->client.icccm.machine);
if (bd->client.icccm.window_role)
eina_stringshare_del(bd->client.icccm.window_role);
if ((bd->client.icccm.command.argc > 0) && (bd->client.icccm.command.argv))
{
int i;
for (i = 0; i < bd->client.icccm.command.argc; i++)
free(bd->client.icccm.command.argv[i]);
free(bd->client.icccm.command.argv);
}
if (bd->client.netwm.name)
eina_stringshare_del(bd->client.netwm.name);
if (bd->client.netwm.icon_name)
eina_stringshare_del(bd->client.netwm.icon_name);
e_object_del(E_OBJECT(bd->shape));
if (bd->internal_icon) eina_stringshare_del(bd->internal_icon);
if (bd->internal_icon_key) eina_stringshare_del(bd->internal_icon_key);
if (bd->icon_object) evas_object_del(bd->icon_object);
evas_object_del(bd->bg_object);
e_canvas_del(bd->bg_ecore_evas);
ecore_evas_free(bd->bg_ecore_evas);
ecore_x_window_free(bd->client.shell_win);
e_focus_setdown(bd);
e_bindings_mouse_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
e_bindings_wheel_ungrab(E_BINDING_CONTEXT_WINDOW, bd->win);
ecore_x_window_free(bd->win);
eina_hash_del(borders_hash, e_util_winid_str_get(bd->client.win), bd);
eina_hash_del(borders_hash, e_util_winid_str_get(bd->bg_win), bd);
eina_hash_del(borders_hash, e_util_winid_str_get(bd->win), bd);
borders = eina_list_remove(borders, bd);
focus_stack = eina_list_remove(focus_stack, bd);
raise_stack = eina_list_remove(raise_stack, bd);
e_container_border_remove(bd);
free(bd);
}
/*
static int
_e_border_del_dangling_ref_check(void *data)
{
E_Border *bd;
bd = data;
printf("---\n");
printf("EEK EEK border still around 1 second after being deleted!\n");
printf("%p, %i, \"%s\" [\"%s\" \"%s\"]\n",
bd, e_object_ref_get(E_OBJECT(bd)), bd->client.icccm.title,
bd->client.icccm.name, bd->client.icccm.class);
// e_object_breadcrumb_debug(E_OBJECT(bd));
printf("---\n");
return 1;
}
*/
static void
_e_border_del(E_Border *bd)
{
E_Event_Border_Remove *ev;
E_Border *child;
bd->take_focus = bd->want_focus = 0;
if (bd == focused)
{
focused = NULL;
}
if (bd == focusing)
focusing = NULL;
focus_next = eina_list_remove(focus_next, bd);
if (warp_timer_border == bd)
{
warp_to = 0;
warp_timer_border = NULL;
if (warp_timer)
{
ecore_timer_del(warp_timer);
warp_timer = NULL;
e_border_focus_lock_set(EINA_FALSE);
}
}
if (bd->fullscreen) bd->desk->fullscreen_borders--;
if ((drag_border) && (drag_border->data == bd))
{
e_object_del(E_OBJECT(drag_border));
drag_border = NULL;
}
if (bd->border_menu) e_menu_deactivate(bd->border_menu);
if (bd->border_locks_dialog)
{
e_object_del(E_OBJECT(bd->border_locks_dialog));
bd->border_locks_dialog = NULL;
}
if (bd->border_remember_dialog)
{
e_object_del(E_OBJECT(bd->border_remember_dialog));
bd->border_remember_dialog = NULL;
}
if (bd->border_border_dialog)
{
e_object_del(E_OBJECT(bd->border_border_dialog));
bd->border_border_dialog = NULL;
}
if (bd->border_prop_dialog)
{
e_object_del(E_OBJECT(bd->border_prop_dialog));
bd->border_prop_dialog = NULL;
}
e_int_border_menu_del(bd);
if (bd->raise_timer)
{
ecore_timer_del(bd->raise_timer);
bd->raise_timer = NULL;
}
if (!bd->already_unparented)
{
ecore_x_window_reparent(bd->client.win,
bd->zone->container->manager->root,
bd->x + bd->client_inset.l,
bd->y + bd->client_inset.t);
ecore_x_window_save_set_del(bd->client.win);
// bd->client.win = 0;
}
bd->already_unparented = 1;
if ((!bd->new_client) && (!stopping))
{
ev = E_NEW(E_Event_Border_Remove, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_remove_event");
ecore_event_add(E_EVENT_BORDER_REMOVE, ev, _e_border_event_border_remove_free, NULL);
}
if (bd->parent)
{
bd->parent->transients = eina_list_remove(bd->parent->transients, bd);
if (bd->parent->modal == bd)
{
if (bd->parent->client.lock_win)
{
eina_hash_del_by_key(borders_hash, e_util_winid_str_get(bd->parent->client.lock_win));
ecore_x_window_hide(bd->parent->client.lock_win);
ecore_x_window_free(bd->parent->client.lock_win);
bd->parent->client.lock_win = 0;
}
bd->parent->lock_close = 0;
bd->parent->modal = NULL;
}
bd->parent = NULL;
}
EINA_LIST_FREE(bd->transients, child)
{
child->parent = NULL;
}
if (bd->leader)
{
bd->leader->group = eina_list_remove(bd->leader->group, bd);
if (bd->leader->modal == bd)
bd->leader->modal = NULL;
bd->leader = NULL;
}
EINA_LIST_FREE(bd->group, child)
{
child->leader = NULL;
}
}
#ifdef PRINT_LOTS_OF_DEBUG
static void
_e_border_print(E_Border *bd,
const char *func)
{
if (!bd) return;
DBG("*Window Info*"
"\tPointer: %p\n"
"\tName: %s\n"
"\tTitle: %s\n"
"\tBorderless: %s\n",
bd, bd->client.icccm.name, bd->client.icccm.title,
bd->borderless ? "TRUE" : "FALSE");
}
#endif
static Eina_Bool
_e_border_cb_window_show_request(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Show_Request *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
if (bd->iconic)
{
if (!bd->lock_client_iconify)
e_border_uniconify(bd);
}
else
{
/* FIXME: make border "urgent" for a bit - it wants attention */
/* e_border_show(bd); */
if (!bd->lock_client_stacking)
e_border_raise(bd);
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_destroy(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Destroy *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
e_border_hide(bd, 0);
e_object_del(E_OBJECT(bd));
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_hide(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Hide *e;
e = ev;
// printf("HIDE: %x, event %x\n", e->win, e->event_win);
// not interested in hide events from windows other than the window in question
if (e->win != e->event_win) return ECORE_CALLBACK_PASS_ON;
bd = e_border_find_by_client_window(e->win);
// printf(" bd = %p\n", bd);
if (!bd) return ECORE_CALLBACK_PASS_ON;
// printf(" bd->ignore_first_unmap = %i\n", bd->ignore_first_unmap);
if (bd->ignore_first_unmap > 0)
{
bd->ignore_first_unmap--;
return ECORE_CALLBACK_PASS_ON;
}
/* Don't delete hidden or iconified windows */
if ((bd->iconic) || (bd->await_hide_event > 0))
{
// printf(" Don't delete hidden or iconified windows\n");
// printf(" bd->iconic = %i, bd->visible = %i, bd->new_client = %i, bd->await_hide_event = %i\n",
// bd->iconic, bd->visible, bd->new_client, bd->await_hide_event);
if (bd->await_hide_event > 0)
{
bd->await_hide_event--;
}
else
{
// printf(" hide really\n");
/* Only hide the border if it is visible */
if (bd->visible) e_border_hide(bd, 1);
}
}
else
{
// printf(" hide2\n");
e_border_hide(bd, 0);
e_object_del(E_OBJECT(bd));
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_reparent(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev __UNUSED__)
{
#if 0
E_Border *bd;
Ecore_X_Event_Window_Reparent *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return 1;
if (e->parent == bd->client.shell_win) return 1;
if (ecore_x_window_parent_get(e->win) == bd->client.shell_win)
{
return 1;
}
e_border_hide(bd, 0);
e_object_del(E_OBJECT(bd));
#endif
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_configure_request(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Configure_Request *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd)
{
if (e_stolen_win_get(e->win)) return ECORE_CALLBACK_PASS_ON;
if (!e_util_container_window_find(e->win))
ecore_x_window_configure(e->win, e->value_mask,
e->x, e->y, e->w, e->h, e->border,
e->abovewin, e->detail);
return ECORE_CALLBACK_PASS_ON;
}
if ((e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_X) ||
(e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_Y))
{
int x, y;
x = bd->x;
y = bd->y;
if (e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_X)
x = e->x;
if (e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_Y)
y = e->y;
if ((e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_W) ||
(e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_H))
{
int w, h;
h = bd->h;
w = bd->w;
if (e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_W)
w = e->w + bd->client_inset.l + bd->client_inset.r;
if (e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_H)
h = e->h + bd->client_inset.t + bd->client_inset.b;
if ((!bd->lock_client_location) && (!bd->lock_client_size))
{
if ((bd->maximized & E_MAXIMIZE_TYPE) != E_MAXIMIZE_NONE)
{
bd->saved.x = x - bd->zone->x;
bd->saved.y = y - bd->zone->y;
bd->saved.w = w;
bd->saved.h = h;
}
else
e_border_move_resize(bd, x, y, w, h);
}
else if (!bd->lock_client_location)
{
if ((bd->maximized & E_MAXIMIZE_TYPE) != E_MAXIMIZE_NONE)
{
bd->saved.x = x - bd->zone->x;
bd->saved.y = y - bd->zone->y;
}
else
e_border_move(bd, x, y);
}
else if (!bd->lock_client_size)
{
if ((bd->shaded) || (bd->shading))
{
int pw, ph;
pw = bd->client.w;
ph = bd->client.h;
if ((bd->shade.dir == E_DIRECTION_UP) ||
(bd->shade.dir == E_DIRECTION_DOWN))
{
e_border_resize(bd, w, bd->h);
bd->client.h = ph;
}
else
{
e_border_resize(bd, bd->w, h);
bd->client.w = pw;
}
}
else
{
if ((bd->maximized & E_MAXIMIZE_TYPE) != E_MAXIMIZE_NONE)
{
bd->saved.w = w;
bd->saved.h = h;
}
else
e_border_resize(bd, w, h);
}
}
}
else
{
if (!bd->lock_client_location)
{
if ((bd->maximized & E_MAXIMIZE_TYPE) != E_MAXIMIZE_NONE)
{
bd->saved.x = x - bd->zone->x;
bd->saved.y = y - bd->zone->y;
}
else
e_border_move(bd, x, y);
}
}
}
else if ((e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_W) ||
(e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_H))
{
int w, h;
h = bd->h;
w = bd->w;
if (e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_W)
w = e->w + bd->client_inset.l + bd->client_inset.r;
if (e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_H)
h = e->h + bd->client_inset.t + bd->client_inset.b;
if (!bd->lock_client_size)
{
if ((bd->shaded) || (bd->shading))
{
int pw, ph;
pw = bd->client.w;
ph = bd->client.h;
if ((bd->shade.dir == E_DIRECTION_UP) ||
(bd->shade.dir == E_DIRECTION_DOWN))
{
e_border_resize(bd, w, bd->h);
bd->client.h = ph;
}
else
{
e_border_resize(bd, bd->w, h);
bd->client.w = pw;
}
}
else
{
if ((bd->maximized & E_MAXIMIZE_TYPE) == E_MAXIMIZE_NONE)
{
int zx, zy, zw, zh;
int rx = bd->x;
int ry = bd->y;
zx = zy = zw = zh = 0;
/*
* This code does resize and move a window on a
* X configure request into an useful geometry.
* This is really useful for size jumping file dialogs.
*/
if (bd->zone)
{
e_zone_useful_geometry_get(bd->zone, &zx, &zy, &zw, &zh);
if (e_config->geometry_auto_resize_limit == 1)
{
if (w > zw)
w = zw;
if (h > zh)
h = zh;
}
}
e_border_resize(bd, w, h);
if (e_config->geometry_auto_move == 1)
{
/* z{x,y,w,h} are only set here; FIXME! */
if (bd->zone)
{
// move window horizontal if resize to not useful geometry
if (bd->x + bd->w > zx + zw)
rx = zx + zw - bd->w;
else if (bd->x < zx)
rx = zx;
// move window vertical if resize to not useful geometry
if (bd->y + bd->h > zy + zh)
ry = zy + zh - bd->h;
else if (bd->y < zy)
ry = zy;
}
e_border_move(bd, rx, ry);
}
}
}
}
}
if (!bd->lock_client_stacking)
{
if ((e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_STACK_MODE) &&
(e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_SIBLING))
{
E_Border *obd;
if (e->detail == ECORE_X_WINDOW_STACK_ABOVE)
{
obd = e_border_find_by_client_window(e->abovewin);
if (obd)
{
e_border_stack_above(bd, obd);
}
else
{
ecore_x_window_configure(bd->win,
ECORE_X_WINDOW_CONFIGURE_MASK_SIBLING |
ECORE_X_WINDOW_CONFIGURE_MASK_STACK_MODE,
0, 0, 0, 0, 0,
e->abovewin, ECORE_X_WINDOW_STACK_ABOVE);
/* FIXME: need to rebuiuld border list from current stacking */
}
}
else if (e->detail == ECORE_X_WINDOW_STACK_BELOW)
{
obd = e_border_find_by_client_window(e->abovewin);
if (obd)
{
e_border_stack_below(bd, obd);
}
else
{
ecore_x_window_configure(bd->win,
ECORE_X_WINDOW_CONFIGURE_MASK_SIBLING |
ECORE_X_WINDOW_CONFIGURE_MASK_STACK_MODE,
0, 0, 0, 0, 0,
e->abovewin, ECORE_X_WINDOW_STACK_BELOW);
/* FIXME: need to rebuiuld border list from current stacking */
}
}
else if (e->detail == ECORE_X_WINDOW_STACK_TOP_IF)
{
/* FIXME: do */
}
else if (e->detail == ECORE_X_WINDOW_STACK_BOTTOM_IF)
{
/* FIXME: do */
}
else if (e->detail == ECORE_X_WINDOW_STACK_OPPOSITE)
{
/* FIXME: do */
}
}
else if (e->value_mask & ECORE_X_WINDOW_CONFIGURE_MASK_STACK_MODE)
{
if (e->detail == ECORE_X_WINDOW_STACK_ABOVE)
{
e_border_raise(bd);
}
else if (e->detail == ECORE_X_WINDOW_STACK_BELOW)
{
e_border_lower(bd);
}
else if (e->detail == ECORE_X_WINDOW_STACK_TOP_IF)
{
/* FIXME: do */
}
else if (e->detail == ECORE_X_WINDOW_STACK_BOTTOM_IF)
{
/* FIXME: do */
}
else if (e->detail == ECORE_X_WINDOW_STACK_OPPOSITE)
{
/* FIXME: do */
}
}
}
/* FIXME: need to send synthetic stacking event too as well as move/resize */
_e_border_client_move_resize_send(bd);
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_resize_request(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Resize_Request *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd)
{
if (e_stolen_win_get(e->win)) return ECORE_CALLBACK_PASS_ON;
ecore_x_window_resize(e->win, e->w, e->h);
return ECORE_CALLBACK_PASS_ON;
}
{
int w, h;
w = e->w + bd->client_inset.l + bd->client_inset.r;
h = e->h + bd->client_inset.t + bd->client_inset.b;
if ((bd->shaded) || (bd->shading))
{
int pw, ph;
pw = bd->client.w;
ph = bd->client.h;
if ((bd->shade.dir == E_DIRECTION_UP) ||
(bd->shade.dir == E_DIRECTION_DOWN))
{
e_border_resize(bd, w, bd->h);
bd->client.h = ph;
}
else
{
e_border_resize(bd, bd->w, h);
bd->client.w = pw;
}
}
else
e_border_resize(bd, w, h);
}
_e_border_client_move_resize_send(bd);
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_gravity(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev __UNUSED__)
{
// E_Border *bd;
// Ecore_X_Event_Window_Gravity *e;
// e = ev;
// bd = e_border_find_by_client_window(e->win);
// if (!bd) return 1;
return 1;
}
static Eina_Bool
_e_border_cb_window_stack_request(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Stack_Request *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd)
{
if (e_stolen_win_get(e->win)) return ECORE_CALLBACK_PASS_ON;
if (!e_util_container_window_find(e->win))
{
if (e->detail == ECORE_X_WINDOW_STACK_ABOVE)
ecore_x_window_raise(e->win);
else if (e->detail == ECORE_X_WINDOW_STACK_BELOW)
ecore_x_window_lower(e->win);
}
return ECORE_CALLBACK_PASS_ON;
}
if (e->detail == ECORE_X_WINDOW_STACK_ABOVE)
e_border_raise(bd);
else if (e->detail == ECORE_X_WINDOW_STACK_BELOW)
e_border_lower(bd);
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_property(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Property *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
if (e->atom == ECORE_X_ATOM_WM_NAME)
{
if ((!bd->client.netwm.name) &&
(!bd->client.netwm.fetch.name))
{
bd->client.icccm.fetch.title = 1;
bd->changed = 1;
}
}
else if (e->atom == ECORE_X_ATOM_NET_WM_NAME)
{
bd->client.netwm.fetch.name = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_CLASS)
{
bd->client.icccm.fetch.name_class = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_ICON_NAME)
{
if ((!bd->client.netwm.icon_name) &&
(!bd->client.netwm.fetch.icon_name))
{
bd->client.icccm.fetch.icon_name = 1;
bd->changed = 1;
}
}
else if (e->atom == ECORE_X_ATOM_NET_WM_ICON_NAME)
{
bd->client.netwm.fetch.icon_name = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_CLIENT_MACHINE)
{
bd->client.icccm.fetch.machine = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_PROTOCOLS)
{
bd->client.icccm.fetch.protocol = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_HINTS)
{
bd->client.icccm.fetch.hints = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_NORMAL_HINTS)
{
bd->client.icccm.fetch.size_pos_hints = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_MOTIF_WM_HINTS)
{
/*
if ((bd->client.netwm.type == ECORE_X_WINDOW_TYPE_UNKNOWN) &&
(!bd->client.netwm.fetch.type))
{
*/
bd->client.mwm.fetch.hints = 1;
bd->changed = 1;
/*
}
*/
}
else if (e->atom == ECORE_X_ATOM_WM_TRANSIENT_FOR)
{
bd->client.icccm.fetch.transient_for = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_CLIENT_LEADER)
{
bd->client.icccm.fetch.client_leader = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_WM_WINDOW_ROLE)
{
bd->client.icccm.fetch.window_role = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_NET_WM_ICON)
{
bd->client.netwm.fetch.icon = 1;
bd->changed = 1;
}
else if (e->atom == ATM__QTOPIA_SOFT_MENU)
{
bd->client.qtopia.fetch.soft_menu = 1;
bd->changed = 1;
}
else if (e->atom == ATM__QTOPIA_SOFT_MENUS)
{
bd->client.qtopia.fetch.soft_menus = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_VIRTUAL_KEYBOARD_STATE)
{
bd->client.vkbd.fetch.state = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_VIRTUAL_KEYBOARD)
{
bd->client.vkbd.fetch.vkbd = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_CONFORMANT)
{
bd->client.illume.conformant.fetch.conformant = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_STATE)
{
bd->client.illume.quickpanel.fetch.state = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_QUICKPANEL)
{
bd->client.illume.quickpanel.fetch.quickpanel = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_PRIORITY_MAJOR)
{
bd->client.illume.quickpanel.fetch.priority.major = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_PRIORITY_MINOR)
{
bd->client.illume.quickpanel.fetch.priority.minor = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_QUICKPANEL_ZONE)
{
bd->client.illume.quickpanel.fetch.zone = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_DRAG_LOCKED)
{
bd->client.illume.drag.fetch.locked = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_DRAG)
{
bd->client.illume.drag.fetch.drag = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_ILLUME_WINDOW_STATE)
{
bd->client.illume.win_state.fetch.state = 1;
bd->changed = 1;
}
/*
else if (e->atom == ECORE_X_ATOM_NET_WM_USER_TIME)
{
bd->client.netwm.fetch.user_time = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_NET_WM_STRUT)
{
bd->client.netwm.fetch.strut = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_NET_WM_STRUT_PARTIAL)
{
bd->client.netwm.fetch.strut = 1;
bd->changed = 1;
}
*/
else if (e->atom == ECORE_X_ATOM_NET_WM_SYNC_REQUEST_COUNTER)
{
//printf("ECORE_X_ATOM_NET_WM_SYNC_REQUEST_COUNTER\n");
}
else if (e->atom == ECORE_X_ATOM_E_VIDEO_POSITION)
{
bd->client.e.fetch.video_position = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_VIDEO_PARENT)
{
bd->client.e.fetch.video_parent = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_NET_WM_STATE)
{
bd->client.netwm.fetch.state = 1;
bd->changed = 1;
}
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
else if (e->atom == ECORE_X_ATOM_E_WINDOW_PROFILE_SUPPORTED)
{
bd->client.e.fetch.profile = 1;
bd->changed = 1;
}
else if (e->atom == ECORE_X_ATOM_E_WINDOW_PROFILE_AVAILABLE_LIST)
{
bd->client.e.fetch.profile = 1;
bd->changed = 1;
}
#endif
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_colormap(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Colormap *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_shape(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Shape *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (e->type == ECORE_X_SHAPE_INPUT)
{
if (bd)
{
bd->need_shape_merge = 1;
// YYY bd->shaped_input = 1;
bd->changes.shape_input = 1;
bd->changed = 1;
}
return ECORE_CALLBACK_PASS_ON;
}
if (bd)
{
bd->changes.shape = 1;
bd->changed = 1;
return ECORE_CALLBACK_PASS_ON;
}
bd = e_border_find_by_window(e->win);
if (bd)
{
bd->need_shape_export = 1;
bd->changed = 1;
return ECORE_CALLBACK_PASS_ON;
}
bd = e_border_find_by_frame_window(e->win);
if (bd)
{
bd->need_shape_merge = 1;
bd->changed = 1;
return ECORE_CALLBACK_PASS_ON;
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_focus_in(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Focus_In *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
/* block refocus attempts on iconic windows
* these result from iconifying a window during a grab */
if (bd->iconic) return ECORE_CALLBACK_RENEW;
#ifdef INOUTDEBUG_FOCUS
{
time_t t;
char *ct;
const char *modes[] = {
"MODE_NORMAL",
"MODE_WHILE_GRABBED",
"MODE_GRAB",
"MODE_UNGRAB"
};
const char *details[] = {
"DETAIL_ANCESTOR",
"DETAIL_VIRTUAL",
"DETAIL_INFERIOR",
"DETAIL_NON_LINEAR",
"DETAIL_NON_LINEAR_VIRTUAL",
"DETAIL_POINTER",
"DETAIL_POINTER_ROOT",
"DETAIL_DETAIL_NONE"
};
t = time(NULL);
ct = ctime(&t);
ct[strlen(ct) - 1] = 0;
DBG("FF ->IN %i 0x%x %s md=%s dt=%s\n",
e->time,
e->win,
ct,
modes[e->mode],
details[e->detail]);
DBG("%s cb focus in %d %d\n",
e_border_name_get(bd),
bd->client.icccm.accepts_focus,
bd->client.icccm.take_focus);
}
#endif
_e_border_pri_raise(bd);
if (e->mode == ECORE_X_EVENT_MODE_GRAB)
{
if (e->detail == ECORE_X_EVENT_DETAIL_POINTER) return ECORE_CALLBACK_PASS_ON;
}
else if (e->mode == ECORE_X_EVENT_MODE_UNGRAB)
{
if (e->detail == ECORE_X_EVENT_DETAIL_POINTER) return ECORE_CALLBACK_PASS_ON;
}
/* ignore focus in from !take_focus windows, we just gave it em */
/* if (!bd->client.icccm.take_focus)
* return ECORE_CALLBACK_PASS_ON; */
/* should be equal, maybe some clients dont reply with the proper timestamp ? */
if (e->time >= focus_time)
e_border_focus_set(bd, 1, 0);
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_focus_out(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Focus_Out *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
#ifdef INOUTDEBUG_FOCUS
{
time_t t;
char *ct;
const char *modes[] = {
"MODE_NORMAL",
"MODE_WHILE_GRABBED",
"MODE_GRAB",
"MODE_UNGRAB"
};
const char *details[] = {
"DETAIL_ANCESTOR",
"DETAIL_VIRTUAL",
"DETAIL_INFERIOR",
"DETAIL_NON_LINEAR",
"DETAIL_NON_LINEAR_VIRTUAL",
"DETAIL_POINTER",
"DETAIL_POINTER_ROOT",
"DETAIL_DETAIL_NONE"
};
t = time(NULL);
ct = ctime(&t);
ct[strlen(ct) - 1] = 0;
DBG("FF <-OUT %i 0x%x %s md=%s dt=%s",
e->time,
e->win,
ct,
modes[e->mode],
details[e->detail]);
DBG("%s cb focus out %d %d",
e_border_name_get(bd),
bd->client.icccm.accepts_focus,
bd->client.icccm.take_focus);
}
#endif
_e_border_pri_norm(bd);
if (e->mode == ECORE_X_EVENT_MODE_NORMAL)
{
if (e->detail == ECORE_X_EVENT_DETAIL_INFERIOR)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_NON_LINEAR)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_NON_LINEAR_VIRTUAL)
return ECORE_CALLBACK_PASS_ON;
}
else if (e->mode == ECORE_X_EVENT_MODE_GRAB)
{
if (e->detail == ECORE_X_EVENT_DETAIL_NON_LINEAR)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_INFERIOR)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_NON_LINEAR_VIRTUAL)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_ANCESTOR)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_VIRTUAL)
return ECORE_CALLBACK_PASS_ON;
}
else if (e->mode == ECORE_X_EVENT_MODE_UNGRAB)
{
/* for firefox/thunderbird (xul) menu walking */
/* NB: why did i disable this before? */
if (e->detail == ECORE_X_EVENT_DETAIL_INFERIOR)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_POINTER)
return ECORE_CALLBACK_PASS_ON;
}
else if (e->mode == ECORE_X_EVENT_MODE_WHILE_GRABBED)
{
if (e->detail == ECORE_X_EVENT_DETAIL_ANCESTOR)
return ECORE_CALLBACK_PASS_ON;
else if (e->detail == ECORE_X_EVENT_DETAIL_INFERIOR)
return ECORE_CALLBACK_PASS_ON;
}
e_border_focus_set(bd, 0, 0);
return ECORE_CALLBACK_PASS_ON;
}
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
static Eina_Bool
_e_border_cb_client_message(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Client_Message *e;
char *profile = NULL;
e = (Ecore_X_Event_Client_Message *)ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
if (e->message_type == ECORE_X_ATOM_E_WINDOW_PROFILE_CHANGE)
{
if (bd->client.e.state.profile.use)
{
profile = ecore_x_atom_name_get(e->data.l[1]);
ecore_x_e_window_profile_change_request_send(bd->client.win,
profile);
bd->client.e.state.profile.wait_for_done = 1;
}
}
else if (e->message_type == ECORE_X_ATOM_E_WINDOW_PROFILE_CHANGE_DONE)
{
if ((bd->client.e.state.profile.use) &&
(bd->client.e.state.profile.wait_for_done))
{
E_Container *con = bd->zone->container;
E_Desk *desk = NULL;
profile = ecore_x_atom_name_get(e->data.l[1]);
if (profile)
{
if (bd->client.e.state.profile.name)
eina_stringshare_del(bd->client.e.state.profile.name);
bd->client.e.state.profile.name = eina_stringshare_add(profile);
}
bd->client.e.state.profile.wait_for_done = 0;
desk = e_container_desk_window_profile_get(con, profile);
if ((desk) && (bd->desk != desk))
e_border_desk_set(bd, desk);
}
}
free(profile);
return ECORE_CALLBACK_PASS_ON;
}
#endif
static Eina_Bool
_e_border_cb_window_state_request(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_State_Request *e;
int i;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
for (i = 0; i < 2; i++)
e_hints_window_state_update(bd, e->state[i], e->action);
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_window_move_resize_request(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Window_Move_Resize_Request *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (!bd) return ECORE_CALLBACK_PASS_ON;
if ((bd->shaded) || (bd->shading) ||
(bd->fullscreen) || (bd->moving) ||
(bd->resize_mode != RESIZE_NONE))
return ECORE_CALLBACK_PASS_ON;
if ((e->button >= 1) && (e->button <= 3))
{
bd->mouse.last_down[e->button - 1].mx = e->x;
bd->mouse.last_down[e->button - 1].my = e->y;
bd->mouse.last_down[e->button - 1].x = bd->x;
bd->mouse.last_down[e->button - 1].y = bd->y;
bd->mouse.last_down[e->button - 1].w = bd->w;
bd->mouse.last_down[e->button - 1].h = bd->h;
}
else
{
bd->moveinfo.down.x = bd->x;
bd->moveinfo.down.y = bd->y;
bd->moveinfo.down.w = bd->w;
bd->moveinfo.down.h = bd->h;
}
bd->mouse.current.mx = e->x;
bd->mouse.current.my = e->y;
bd->moveinfo.down.button = e->button;
bd->moveinfo.down.mx = e->x;
bd->moveinfo.down.my = e->y;
grabbed = 1;
if (!bd->lock_user_stacking)
e_border_raise(bd);
if (e->direction == MOVE)
{
bd->cur_mouse_action = e_action_find("window_move");
if (bd->cur_mouse_action)
{
if ((!bd->cur_mouse_action->func.end_mouse) &&
(!bd->cur_mouse_action->func.end))
bd->cur_mouse_action = NULL;
if (bd->cur_mouse_action)
{
e_object_ref(E_OBJECT(bd->cur_mouse_action));
bd->cur_mouse_action->func.go(E_OBJECT(bd), NULL);
}
}
return ECORE_CALLBACK_PASS_ON;
}
if (!_e_border_resize_begin(bd))
return ECORE_CALLBACK_PASS_ON;
switch (e->direction)
{
case RESIZE_TL:
bd->resize_mode = RESIZE_TL;
GRAV_SET(bd, ECORE_X_GRAVITY_SE);
break;
case RESIZE_T:
bd->resize_mode = RESIZE_T;
GRAV_SET(bd, ECORE_X_GRAVITY_S);
break;
case RESIZE_TR:
bd->resize_mode = RESIZE_TR;
GRAV_SET(bd, ECORE_X_GRAVITY_SW);
break;
case RESIZE_R:
bd->resize_mode = RESIZE_R;
GRAV_SET(bd, ECORE_X_GRAVITY_W);
break;
case RESIZE_BR:
bd->resize_mode = RESIZE_BR;
GRAV_SET(bd, ECORE_X_GRAVITY_NW);
break;
case RESIZE_B:
bd->resize_mode = RESIZE_B;
GRAV_SET(bd, ECORE_X_GRAVITY_N);
break;
case RESIZE_BL:
bd->resize_mode = RESIZE_BL;
GRAV_SET(bd, ECORE_X_GRAVITY_NE);
break;
case RESIZE_L:
bd->resize_mode = RESIZE_L;
GRAV_SET(bd, ECORE_X_GRAVITY_E);
break;
default:
return ECORE_CALLBACK_PASS_ON;
}
bd->cur_mouse_action = e_action_find("window_resize");
if (bd->cur_mouse_action)
{
if ((!bd->cur_mouse_action->func.end_mouse) &&
(!bd->cur_mouse_action->func.end))
bd->cur_mouse_action = NULL;
}
if (bd->cur_mouse_action)
e_object_ref(E_OBJECT(bd->cur_mouse_action));
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_desktop_change(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Desktop_Change *e;
e = ev;
bd = e_border_find_by_client_window(e->win);
if (bd)
{
if (e->desk == 0xffffffff)
e_border_stick(bd);
else if ((int)e->desk < (bd->zone->desk_x_count * bd->zone->desk_y_count))
{
E_Desk *desk;
desk = e_desk_at_pos_get(bd->zone, e->desk);
if (desk)
e_border_desk_set(bd, desk);
}
}
else
{
ecore_x_netwm_desktop_set(e->win, e->desk);
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_sync_alarm(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Border *bd;
Ecore_X_Event_Sync_Alarm *e;
unsigned int serial;
e = ev;
bd = e_border_find_by_alarm(e->alarm);
if (!bd) return ECORE_CALLBACK_PASS_ON;
if (bd->client.netwm.sync.wait)
bd->client.netwm.sync.wait--;
if (ecore_x_sync_counter_query(bd->client.netwm.sync.counter, &serial))
{
E_Border_Pending_Move_Resize *pnd = NULL;
/* skip pending for which we didn't get a reply */
while (bd->pending_move_resize)
{
pnd = bd->pending_move_resize->data;
bd->pending_move_resize = eina_list_remove(bd->pending_move_resize, pnd);
if (serial == pnd->serial)
break;
E_FREE(pnd);
}
if (pnd)
{
bd->x = pnd->x;
bd->y = pnd->y;
bd->w = pnd->w;
bd->h = pnd->h;
bd->client.w = bd->w - (bd->client_inset.l + bd->client_inset.r);
bd->client.h = bd->h - (bd->client_inset.t + bd->client_inset.b);
E_FREE(pnd);
}
}
bd->changes.size = 1;
bd->changes.pos = 1;
_e_border_eval(bd);
evas_render(bd->bg_evas);
ecore_x_pointer_xy_get(e_manager_current_get()->root,
&bd->mouse.current.mx,
&bd->mouse.current.my);
bd->client.netwm.sync.send_time = ecore_loop_time_get();
_e_border_resize_handle(bd);
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_efreet_cache_update(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev __UNUSED__)
{
Eina_List *l;
E_Border *bd;
/* mark all borders for desktop/icon updates */
EINA_LIST_FOREACH(borders, l, bd)
{
if (bd->desktop)
{
efreet_desktop_free(bd->desktop);
bd->desktop = NULL;
}
bd->changes.icon = 1;
bd->changed = 1;
}
/*
e_init_status_set(_("Desktop files scan done"));
e_init_done();
*/
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_config_icon_theme(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev __UNUSED__)
{
Eina_List *l;
E_Border *bd;
/* mark all borders for desktop/icon updates */
EINA_LIST_FOREACH(borders, l, bd)
{
bd->changes.icon = 1;
bd->changed = 1;
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_config_mode(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev __UNUSED__)
{
Eina_List *l;
E_Border *bd;
/* move fullscreen borders above everything */
if (e_config->mode.presentation)
{
EINA_LIST_FOREACH(borders, l, bd)
{
if ((bd->fullscreen) || (bd->need_fullscreen))
{
bd->fullscreen = 0;
e_border_layer_set(bd, E_LAYER_TOP);
bd->fullscreen = 1;
}
}
}
else if (!e_config->allow_above_fullscreen)
{
EINA_LIST_FOREACH(borders, l, bd)
{
if ((bd->fullscreen) || (bd->need_fullscreen))
{
bd->fullscreen = 0;
e_border_layer_set(bd, E_LAYER_FULLSCREEN);
bd->fullscreen = 1;
}
}
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_pointer_warp(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev)
{
E_Event_Pointer_Warp *e;
e = ev;
if (!bdmove) return ECORE_CALLBACK_PASS_ON;
e_border_move(bdmove, bdmove->x + (e->curr.x - e->prev.x), bdmove->y + (e->curr.y - e->prev.y));
return ECORE_CALLBACK_PASS_ON;
}
static void
_e_border_cb_signal_bind(void *data,
Evas_Object *obj __UNUSED__,
const char *emission,
const char *source)
{
E_Border *bd;
bd = data;
if (e_dnd_active()) return;
e_bindings_signal_handle(E_BINDING_CONTEXT_WINDOW, E_OBJECT(bd),
emission, source);
}
static Eina_Bool
_e_border_cb_mouse_in(void *data,
int type __UNUSED__,
void *event)
{
Ecore_X_Event_Mouse_In *ev;
E_Border *bd;
ev = event;
bd = data;
#ifdef INOUTDEBUG_MOUSE
{
time_t t;
char *ct;
const char *modes[] = {
"MODE_NORMAL",
"MODE_WHILE_GRABBED",
"MODE_GRAB",
"MODE_UNGRAB"
};
const char *details[] = {
"DETAIL_ANCESTOR",
"DETAIL_VIRTUAL",
"DETAIL_INFERIOR",
"DETAIL_NON_LINEAR",
"DETAIL_NON_LINEAR_VIRTUAL",
"DETAIL_POINTER",
"DETAIL_POINTER_ROOT",
"DETAIL_DETAIL_NONE"
};
t = time(NULL);
ct = ctime(&t);
ct[strlen(ct) - 1] = 0;
DBG("@@ ->IN 0x%x 0x%x %s md=%s dt=%s",
ev->win, ev->event_win,
ct,
modes[ev->mode],
details[ev->detail]);
}
#endif
if (grabbed) return ECORE_CALLBACK_PASS_ON;
if (focus_locked) return ECORE_CALLBACK_RENEW;
if (ev->event_win == bd->win)
{
if (focus_locked && (bd != warp_timer_border)) return ECORE_CALLBACK_RENEW;
if (!bd->iconic)
e_focus_event_mouse_in(bd);
}
else if (focus_locked) return ECORE_CALLBACK_RENEW;
#if 0
if ((ev->win != bd->win) &&
(ev->win != bd->event_win) &&
(ev->event_win != bd->win) &&
(ev->event_win != bd->event_win))
return ECORE_CALLBACK_PASS_ON;
#else
if (ev->win != bd->event_win) return ECORE_CALLBACK_PASS_ON;
#endif
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
if (!bd->bg_evas_in)
{
evas_event_feed_mouse_in(bd->bg_evas, ev->time, NULL);
bd->bg_evas_in = EINA_TRUE;
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_mouse_out(void *data,
int type __UNUSED__,
void *event)
{
Ecore_X_Event_Mouse_Out *ev;
E_Border *bd;
ev = event;
bd = data;
#ifdef INOUTDEBUG_MOUSE
{
time_t t;
char *ct;
const char *modes[] = {
"MODE_NORMAL",
"MODE_WHILE_GRABBED",
"MODE_GRAB",
"MODE_UNGRAB"
};
const char *details[] = {
"DETAIL_ANCESTOR",
"DETAIL_VIRTUAL",
"DETAIL_INFERIOR",
"DETAIL_NON_LINEAR",
"DETAIL_NON_LINEAR_VIRTUAL",
"DETAIL_POINTER",
"DETAIL_POINTER_ROOT",
"DETAIL_DETAIL_NONE"
};
t = time(NULL);
ct = ctime(&t);
ct[strlen(ct) - 1] = 0;
DBG("@@ <-OUT 0x%x 0x%x %s md=%s dt=%s",
ev->win, ev->event_win,
ct,
modes[ev->mode],
details[ev->detail]);
}
#endif
if (grabbed) return ECORE_CALLBACK_PASS_ON;
if (ev->event_win == bd->win)
{
if (bd->fullscreen)
return ECORE_CALLBACK_PASS_ON;
if ((ev->mode == ECORE_X_EVENT_MODE_UNGRAB) &&
(ev->detail == ECORE_X_EVENT_DETAIL_INFERIOR))
return ECORE_CALLBACK_PASS_ON;
if (ev->mode == ECORE_X_EVENT_MODE_GRAB)
return ECORE_CALLBACK_PASS_ON;
if ((ev->mode == ECORE_X_EVENT_MODE_NORMAL) &&
(ev->detail == ECORE_X_EVENT_DETAIL_INFERIOR))
return ECORE_CALLBACK_PASS_ON;
if (!bd->iconic)
e_focus_event_mouse_out(bd);
}
#if 0
if ((ev->win != bd->win) &&
(ev->win != bd->event_win) &&
(ev->event_win != bd->win) &&
(ev->event_win != bd->event_win))
return ECORE_CALLBACK_PASS_ON;
#else
if (ev->win != bd->event_win) return ECORE_CALLBACK_PASS_ON;
#endif
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
if (bd->bg_evas_in)
{
if (!((evas_event_down_count_get(bd->bg_evas) > 0) &&
(!((ev->mode == ECORE_X_EVENT_MODE_GRAB) &&
(ev->detail == ECORE_X_EVENT_DETAIL_NON_LINEAR)))))
{
if (ev->mode == ECORE_X_EVENT_MODE_GRAB)
evas_event_feed_mouse_cancel(bd->bg_evas, ev->time, NULL);
evas_event_feed_mouse_out(bd->bg_evas, ev->time, NULL);
bd->bg_evas_in = EINA_FALSE;
}
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_mouse_wheel(void *data,
int type __UNUSED__,
void *event)
{
Ecore_Event_Mouse_Wheel *ev;
E_Border *bd;
ev = event;
bd = data;
if ((ev->event_window == bd->win) ||
(ev->event_window == bd->event_win))
{
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
if (!bd->cur_mouse_action)
e_bindings_wheel_event_handle(E_BINDING_CONTEXT_WINDOW,
E_OBJECT(bd), ev);
}
evas_event_feed_mouse_wheel(bd->bg_evas, ev->direction, ev->z, ev->timestamp, NULL);
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_mouse_down(void *data,
int type __UNUSED__,
void *event)
{
Ecore_Event_Mouse_Button *ev;
E_Border *bd;
ev = event;
bd = data;
if ((ev->event_window == bd->win) ||
(ev->event_window == bd->event_win))
{
if ((ev->buttons >= 1) && (ev->buttons <= 3))
{
bd->mouse.last_down[ev->buttons - 1].mx = ev->root.x;
bd->mouse.last_down[ev->buttons - 1].my = ev->root.y;
bd->mouse.last_down[ev->buttons - 1].x = bd->x + bd->fx.x;
bd->mouse.last_down[ev->buttons - 1].y = bd->y + bd->fx.y;
bd->mouse.last_down[ev->buttons - 1].w = bd->w;
bd->mouse.last_down[ev->buttons - 1].h = bd->h;
}
else
{
bd->moveinfo.down.x = bd->x + bd->fx.x;
bd->moveinfo.down.y = bd->y + bd->fx.y;
bd->moveinfo.down.w = bd->w;
bd->moveinfo.down.h = bd->h;
}
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
if (!bd->cur_mouse_action)
{
bd->cur_mouse_action =
e_bindings_mouse_down_event_handle(E_BINDING_CONTEXT_WINDOW,
E_OBJECT(bd), ev);
if (bd->cur_mouse_action)
{
if ((!bd->cur_mouse_action->func.end_mouse) &&
(!bd->cur_mouse_action->func.end))
bd->cur_mouse_action = NULL;
if (bd->cur_mouse_action)
e_object_ref(E_OBJECT(bd->cur_mouse_action));
}
}
e_focus_event_mouse_down(bd);
}
if (ev->window != ev->event_window)
{
return 1;
}
if ((ev->window != bd->event_win) && (ev->event_window != bd->win))
{
return 1;
}
if ((ev->buttons >= 1) && (ev->buttons <= 3))
{
bd->mouse.last_down[ev->buttons - 1].mx = ev->root.x;
bd->mouse.last_down[ev->buttons - 1].my = ev->root.y;
bd->mouse.last_down[ev->buttons - 1].x = bd->x + bd->fx.x;
bd->mouse.last_down[ev->buttons - 1].y = bd->y + bd->fx.y;
bd->mouse.last_down[ev->buttons - 1].w = bd->w;
bd->mouse.last_down[ev->buttons - 1].h = bd->h;
}
else
{
bd->moveinfo.down.x = bd->x + bd->fx.x;
bd->moveinfo.down.y = bd->y + bd->fx.y;
bd->moveinfo.down.w = bd->w;
bd->moveinfo.down.h = bd->h;
}
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
/*
if (bd->moving)
{
}
else if (bd->resize_mode != RESIZE_NONE)
{
}
else
*/
{
Evas_Button_Flags flags = EVAS_BUTTON_NONE;
if (ev->double_click) flags |= EVAS_BUTTON_DOUBLE_CLICK;
if (ev->triple_click) flags |= EVAS_BUTTON_TRIPLE_CLICK;
evas_event_feed_mouse_down(bd->bg_evas, ev->buttons, flags, ev->timestamp, NULL);
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_mouse_up(void *data,
int type __UNUSED__,
void *event)
{
Ecore_Event_Mouse_Button *ev;
E_Border *bd;
ev = event;
bd = data;
if ((ev->event_window == bd->win) ||
(ev->event_window == bd->event_win))
{
if ((ev->buttons >= 1) && (ev->buttons <= 3))
{
bd->mouse.last_up[ev->buttons - 1].mx = ev->root.x;
bd->mouse.last_up[ev->buttons - 1].my = ev->root.y;
bd->mouse.last_up[ev->buttons - 1].x = bd->x + bd->fx.x;
bd->mouse.last_up[ev->buttons - 1].y = bd->y + bd->fx.y;
}
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
/* also we dont pass the same params that went in - then again that */
/* should be ok as we are just ending the action if it has an end */
if (bd->cur_mouse_action)
{
if (bd->cur_mouse_action->func.end_mouse)
bd->cur_mouse_action->func.end_mouse(E_OBJECT(bd), "", ev);
else if (bd->cur_mouse_action->func.end)
bd->cur_mouse_action->func.end(E_OBJECT(bd), "");
e_object_unref(E_OBJECT(bd->cur_mouse_action));
bd->cur_mouse_action = NULL;
}
else
{
if (!e_bindings_mouse_up_event_handle(E_BINDING_CONTEXT_WINDOW, E_OBJECT(bd), ev))
e_focus_event_mouse_up(bd);
}
}
if (ev->window != bd->event_win) return ECORE_CALLBACK_PASS_ON;
if ((ev->buttons >= 1) && (ev->buttons <= 3))
{
bd->mouse.last_up[ev->buttons - 1].mx = ev->root.x;
bd->mouse.last_up[ev->buttons - 1].my = ev->root.y;
bd->mouse.last_up[ev->buttons - 1].x = bd->x + bd->fx.x;
bd->mouse.last_up[ev->buttons - 1].y = bd->y + bd->fx.y;
}
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
bd->drag.start = 0;
evas_event_feed_mouse_up(bd->bg_evas, ev->buttons, EVAS_BUTTON_NONE, ev->timestamp, NULL);
return ECORE_CALLBACK_PASS_ON;
}
static void
_e_border_stay_within_container(E_Border *bd, int x, int y, int *new_x, int *new_y)
{
int new_x_max, new_y_max;
int zw, zh;
Eina_Bool lw, lh;
if (!bd->zone)
{
if (new_x) *new_x = x;
if (new_y) *new_y = y;
return;
}
_e_border_zones_layout_calc(bd, NULL, NULL, &zw, &zh);
new_x_max = zw - bd->w;
new_y_max = zh - bd->h;
lw = bd->w > zw ? EINA_TRUE : EINA_FALSE;
lh = bd->h > zh ? EINA_TRUE : EINA_FALSE;
if (lw)
{
if (x <= new_x_max)
*new_x = new_x_max;
else if (x >= 0)
*new_x = 0;
}
else
{
if (x >= new_x_max)
*new_x = new_x_max;
else if (x <= 0)
*new_x = 0;
}
if (lh)
{
if (y <= new_y_max)
*new_y = new_y_max;
else if (y >= 0)
*new_y = 0;
}
else
{
if (y >= new_y_max)
*new_y = new_y_max;
else if (y <= 0)
*new_y = 0;
}
}
static Eina_Bool
_e_border_cb_mouse_move(void *data,
int type __UNUSED__,
void *event)
{
Ecore_Event_Mouse_Move *ev;
E_Border *bd;
ev = event;
bd = data;
if ((ev->window != bd->event_win) &&
(ev->event_window != bd->win)) return ECORE_CALLBACK_PASS_ON;
bd->mouse.current.mx = ev->root.x;
bd->mouse.current.my = ev->root.y;
if (bd->moving)
{
int x, y, new_x, new_y;
int new_w, new_h;
Eina_List *skiplist = NULL;
#if 0
// FIXME: remove? sync what for when only moving?
if ((ecore_loop_time_get() - bd->client.netwm.sync.time) > 0.5)
bd->client.netwm.sync.wait = 0;
if ((bd->client.netwm.sync.request) &&
(bd->client.netwm.sync.alarm) &&
(bd->client.netwm.sync.wait > 1)) return ECORE_CALLBACK_PASS_ON;
#endif
if ((bd->moveinfo.down.button >= 1) && (bd->moveinfo.down.button <= 3))
{
x = bd->mouse.last_down[bd->moveinfo.down.button - 1].x +
(bd->mouse.current.mx - bd->moveinfo.down.mx);
y = bd->mouse.last_down[bd->moveinfo.down.button - 1].y +
(bd->mouse.current.my - bd->moveinfo.down.my);
}
else
{
x = bd->moveinfo.down.x +
(bd->mouse.current.mx - bd->moveinfo.down.mx);
y = bd->moveinfo.down.y +
(bd->mouse.current.my - bd->moveinfo.down.my);
}
new_x = x;
new_y = y;
skiplist = eina_list_append(skiplist, bd);
e_resist_container_border_position(bd->zone->container, skiplist,
bd->x, bd->y, bd->w, bd->h,
x, y, bd->w, bd->h,
&new_x, &new_y, &new_w, &new_h);
eina_list_free(skiplist);
if (e_config->screen_limits == E_SCREEN_LIMITS_WITHIN)
_e_border_stay_within_container(bd, x, y, &new_x, &new_y);
bd->shelf_fix.x = 0;
bd->shelf_fix.y = 0;
bd->shelf_fix.modified = 0;
e_border_move(bd, new_x, new_y);
e_zone_flip_coords_handle(bd->zone, ev->root.x, ev->root.y);
}
else if (bd->resize_mode != RESIZE_NONE)
{
if ((bd->client.netwm.sync.request) &&
(bd->client.netwm.sync.alarm))
{
if ((ecore_loop_time_get() - bd->client.netwm.sync.send_time) > 0.5)
{
E_Border_Pending_Move_Resize *pnd;
if (bd->pending_move_resize)
{
bd->changes.pos = 1;
bd->changes.size = 1;
bd->changed = 1;
_e_border_client_move_resize_send(bd);
}
EINA_LIST_FREE(bd->pending_move_resize, pnd)
E_FREE(pnd);
bd->client.netwm.sync.wait = 0;
}
/* sync.wait is incremented when resize_handle sends
* sync-request and decremented by sync-alarm cb. so
* we resize here either on initial resize, timeout or
* when no new resize-request was added by sync-alarm cb.
*/
if (!bd->client.netwm.sync.wait)
_e_border_resize_handle(bd);
}
else
_e_border_resize_handle(bd);
}
else
{
if (bd->drag.start)
{
if ((bd->drag.x == -1) && (bd->drag.y == -1))
{
bd->drag.x = ev->root.x;
bd->drag.y = ev->root.y;
}
else
{
int dx, dy;
dx = bd->drag.x - ev->root.x;
dy = bd->drag.y - ev->root.y;
if (((dx * dx) + (dy * dy)) >
(e_config->drag_resist * e_config->drag_resist))
{
/* start drag! */
if (bd->icon_object)
{
Evas_Object *o = NULL;
Evas_Coord x, y, w, h;
const char *drag_types[] = { "enlightenment/border" };
e_object_ref(E_OBJECT(bd));
evas_object_geometry_get(bd->icon_object,
&x, &y, &w, &h);
drag_border = e_drag_new(bd->zone->container,
bd->x + bd->fx.x + x,
bd->y + bd->fx.y + y,
drag_types, 1, bd, -1,
NULL,
_e_border_cb_drag_finished);
o = e_border_icon_add(bd, drag_border->evas);
if (!o)
{
/* FIXME: fallback icon for drag */
o = evas_object_rectangle_add(drag_border->evas);
evas_object_color_set(o, 255, 255, 255, 255);
}
e_drag_object_set(drag_border, o);
e_drag_resize(drag_border, w, h);
e_drag_start(drag_border, bd->drag.x, bd->drag.y);
}
bd->drag.start = 0;
}
}
}
evas_event_feed_mouse_move(bd->bg_evas, ev->x, ev->y, ev->timestamp, NULL);
}
return ECORE_CALLBACK_PASS_ON;
}
static Eina_Bool
_e_border_cb_grab_replay(void *data __UNUSED__,
int type,
void *event)
{
Ecore_Event_Mouse_Button *ev;
if (type != ECORE_EVENT_MOUSE_BUTTON_DOWN) return ECORE_CALLBACK_DONE;
ev = event;
if ((e_config->pass_click_on)
|| (e_config->always_click_to_raise) // this works even if not on click-to-focus
|| (e_config->always_click_to_focus) // this works even if not on click-to-focus
)
{
E_Border *bd;
bd = e_border_find_by_window(ev->event_window);
if (bd)
{
if (bd->cur_mouse_action)
return ECORE_CALLBACK_DONE;
if (ev->event_window == bd->win)
{
if (!e_bindings_mouse_down_find(E_BINDING_CONTEXT_WINDOW,
E_OBJECT(bd), ev, NULL))
return ECORE_CALLBACK_PASS_ON;
}
}
}
return ECORE_CALLBACK_DONE;
}
static void
_e_border_cb_drag_finished(E_Drag *drag,
int dropped __UNUSED__)
{
E_Border *bd;
bd = drag->data;
e_object_unref(E_OBJECT(bd));
drag_border = NULL;
}
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
static Eina_Bool
_e_border_cb_desk_window_profile_change(void *data __UNUSED__,
int ev_type __UNUSED__,
void *ev __UNUSED__)
{
// E_Event_Desk_Window_Profile_Change *e = ev;
Eina_List *l = NULL;
E_Border *bd;
EINA_LIST_FOREACH(borders, l, bd)
{
if (!e_object_is_del(E_OBJECT(bd)))
{
bd->client.e.fetch.profile = 1;
bd->changed = 1;
}
}
return ECORE_CALLBACK_PASS_ON;
}
#endif
static Eina_Bool
_e_border_post_move_resize_job(void *data)
{
E_Border *bd;
bd = (E_Border *)data;
if (bd->post_move)
{
E_Border *tmp;
Eina_List *l;
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
ecore_x_window_move(tmp->win,
bd->x +
bd->client_inset.l +
bd->fx.x +
tmp->client.e.state.video_position.x,
bd->y +
bd->client_inset.t +
bd->fx.y +
tmp->client.e.state.video_position.y);
}
if (bd->client.e.state.video)
{
E_Border *parent;
parent = bd->client.e.state.video_parent_border;
ecore_x_window_move(bd->win,
parent->x +
parent->client_inset.l +
parent->fx.x +
bd->client.e.state.video_position.x,
parent->y +
parent->client_inset.t +
parent->fx.y +
bd->client.e.state.video_position.y);
}
else if ((bd->post_move) && (bd->post_resize))
{
ecore_x_window_move_resize(bd->win,
bd->x + bd->fx.x,
bd->y + bd->fx.y,
bd->w, bd->h);
}
else if (bd->post_move)
{
ecore_x_window_move(bd->win, bd->x + bd->fx.x, bd->y + bd->fx.y);
}
else if (bd->post_resize)
{
ecore_x_window_resize(bd->win, bd->w, bd->h);
}
if (bd->client.e.state.video)
{
fprintf(stderr, "%x: [%i, %i] [%i, %i]\n",
bd->win,
bd->client.e.state.video_parent_border->x +
bd->client.e.state.video_parent_border->client_inset.l +
bd->client.e.state.video_parent_border->fx.x +
bd->client.e.state.video_position.x,
bd->client.e.state.video_parent_border->y +
bd->client.e.state.video_parent_border->client_inset.t +
bd->client.e.state.video_parent_border->fx.y +
bd->client.e.state.video_position.y,
bd->w, bd->h);
}
if (bd->post_show)
{
if (bd->visible)
{
bd->post_job = NULL;
_e_border_show(bd);
}
}
bd->post_show = 0;
bd->post_move = 0;
bd->post_resize = 0;
bd->post_job = NULL;
return ECORE_CALLBACK_CANCEL;
}
static void
_e_border_container_layout_hook(E_Container *con)
{
_e_border_hook_call(E_BORDER_HOOK_CONTAINER_LAYOUT, con);
}
static void
_e_border_eval0(E_Border *bd)
{
int change_urgent = 0;
int rem_change = 0;
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
Eina_Bool need_desk_set = EINA_FALSE;
#endif
if (e_object_is_del(E_OBJECT(bd)))
{
CRI("_e_border_eval(%p) with deleted border!\n", bd);
bd->changed = 0;
return;
}
_e_border_hook_call(E_BORDER_HOOK_EVAL_PRE_FETCH, bd);
bd->changes.border = 0;
/* fetch any info queued to be fetched */
if (bd->changes.prop || bd->client.netwm.fetch.state)
{
e_hints_window_state_get(bd);
bd->client.netwm.fetch.state = 0;
rem_change = 1;
}
if (bd->client.icccm.fetch.client_leader)
{
/* TODO: What do to if the client leader isn't mapped yet? */
E_Border *bd_leader = NULL;
bd->client.icccm.client_leader = ecore_x_icccm_client_leader_get(bd->client.win);
if (bd->client.icccm.client_leader)
bd_leader = e_border_find_by_client_window(bd->client.icccm.client_leader);
if (bd->leader)
{
if (bd->leader != bd_leader)
{
bd->leader->group = eina_list_remove(bd->leader->group, bd);
if (bd->leader->modal == bd) bd->leader->modal = NULL;
bd->leader = NULL;
}
else
bd_leader = NULL;
}
/* If this border is the leader of the group, don't register itself */
if ((bd_leader) && (bd_leader != bd))
{
bd_leader->group = eina_list_append(bd_leader->group, bd);
bd->leader = bd_leader;
/* Only set the window modal to the leader it there is no parent */
if ((e_config->modal_windows) && (bd->client.netwm.state.modal) &&
((!bd->parent) || (bd->parent->modal != bd)))
{
bd->leader->modal = bd;
if (bd->leader->focused)
e_border_focus_set(bd, 1, 1);
else
{
Eina_List *l;
E_Border *child;
EINA_LIST_FOREACH(bd->leader->group, l, child)
{
if ((child != bd) && (child->focused))
e_border_focus_set(bd, 1, 1);
}
}
}
}
bd->client.icccm.fetch.client_leader = 0;
rem_change = 1;
}
if (bd->client.icccm.fetch.title)
{
char *title = ecore_x_icccm_title_get(bd->client.win);
eina_stringshare_replace(&bd->client.icccm.title, title);
free(title);
if (bd->bg_object)
edje_object_part_text_set(bd->bg_object, "e.text.title",
bd->client.icccm.title);
bd->client.icccm.fetch.title = 0;
rem_change = 1;
}
if (bd->client.netwm.fetch.name)
{
char *name;
ecore_x_netwm_name_get(bd->client.win, &name);
eina_stringshare_replace(&bd->client.netwm.name, name);
free(name);
if (bd->bg_object)
edje_object_part_text_set(bd->bg_object, "e.text.title",
bd->client.netwm.name);
bd->client.netwm.fetch.name = 0;
rem_change = 1;
}
if (bd->client.icccm.fetch.name_class)
{
const char *pname, *pclass;
char *nname, *nclass;
ecore_x_icccm_name_class_get(bd->client.win, &nname, &nclass);
pname = bd->client.icccm.name;
pclass = bd->client.icccm.class;
bd->client.icccm.name = eina_stringshare_add(nname);
bd->client.icccm.class = eina_stringshare_add(nclass);
if ((!e_util_strcasecmp(bd->client.icccm.class, "vmplayer")) ||
(!e_util_strcasecmp(bd->client.icccm.class, "vmware")))
e_bindings_mapping_change_enable(EINA_FALSE);
free(nname);
free(nclass);
if (!((bd->client.icccm.name == pname) &&
(bd->client.icccm.class == pclass)))
bd->changes.icon = 1;
if (pname) eina_stringshare_del(pname);
if (pclass) eina_stringshare_del(pclass);
bd->client.icccm.fetch.name_class = 0;
bd->changes.icon = 1;
rem_change = 1;
}
if (bd->changes.prop || bd->client.icccm.fetch.state)
{
bd->client.icccm.state = ecore_x_icccm_state_get(bd->client.win);
bd->client.icccm.fetch.state = 0;
rem_change = 1;
}
if (bd->changes.prop || bd->client.e.fetch.state)
{
e_hints_window_e_state_get(bd);
bd->client.e.fetch.state = 0;
rem_change = 1;
}
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
if (bd->client.e.fetch.profile)
{
const char **list = NULL;
int n, i, res;
unsigned int use;
if (bd->client.e.state.profile.name)
{
eina_stringshare_del(bd->client.e.state.profile.name);
bd->client.e.state.profile.name = NULL;
}
if (bd->client.e.state.profile.available_list)
{
for (i = 0; i < bd->client.e.state.profile.num; i++)
{
if (bd->client.e.state.profile.available_list[i])
{
eina_stringshare_del(bd->client.e.state.profile.available_list[i]);
bd->client.e.state.profile.available_list[i] = NULL;
}
}
E_FREE(bd->client.e.state.profile.available_list);
bd->client.e.state.profile.available_list = NULL;
}
bd->client.e.state.profile.num = 0;
res = ecore_x_window_prop_card32_get(bd->client.win,
ECORE_X_ATOM_E_WINDOW_PROFILE_SUPPORTED,
&use,
1);
if ((res == 1) && (use == 1))
{
Ecore_X_Atom val;
res = ecore_x_window_prop_atom_get(bd->client.win,
ECORE_X_ATOM_E_WINDOW_PROFILE_CHANGE,
&val, 1);
if (res == 1)
{
char *name = ecore_x_atom_name_get(val);
if (name)
{
bd->client.e.state.profile.name = eina_stringshare_add(name);
free(name);
}
}
if (ecore_x_e_window_available_profiles_get(bd->client.win, &list, &n))
{
bd->client.e.state.profile.available_list = E_NEW(const char *, n);
for (i = 0; i < n; i++)
bd->client.e.state.profile.available_list[i] = eina_stringshare_add(list[i]);
bd->client.e.state.profile.num = n;
}
need_desk_set = EINA_TRUE;
bd->client.e.state.profile.use = 1;
free(list);
}
bd->client.e.fetch.profile = 0;
}
#endif
if (bd->changes.prop || bd->client.netwm.fetch.type)
{
e_hints_window_type_get(bd);
if ((!bd->lock_border) || (!bd->client.border.name))
bd->client.border.changed = 1;
if (bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DOCK)
{
if (!bd->client.netwm.state.skip_pager)
{
bd->client.netwm.state.skip_pager = 1;
bd->client.netwm.update.state = 1;
}
if (!bd->client.netwm.state.skip_taskbar)
{
bd->client.netwm.state.skip_taskbar = 1;
bd->client.netwm.update.state = 1;
}
}
else if (bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DESKTOP)
{
bd->focus_policy_override = E_FOCUS_CLICK;
e_focus_setup(bd);
if (!bd->client.netwm.state.skip_pager)
{
bd->client.netwm.state.skip_pager = 1;
bd->client.netwm.update.state = 1;
}
if (!bd->client.netwm.state.skip_taskbar)
{
bd->client.netwm.state.skip_taskbar = 1;
bd->client.netwm.update.state = 1;
}
}
bd->client.netwm.fetch.type = 0;
}
if (bd->client.icccm.fetch.machine)
{
char *machine = ecore_x_icccm_client_machine_get(bd->client.win);
if ((!machine) && (bd->client.icccm.client_leader))
machine = ecore_x_icccm_client_machine_get(bd->client.icccm.client_leader);
eina_stringshare_replace(&bd->client.icccm.machine, machine);
free(machine);
bd->client.icccm.fetch.machine = 0;
rem_change = 1;
}
if (bd->client.icccm.fetch.command)
{
if ((bd->client.icccm.command.argc > 0) && (bd->client.icccm.command.argv))
{
int i;
for (i = 0; i < bd->client.icccm.command.argc; i++)
free(bd->client.icccm.command.argv[i]);
free(bd->client.icccm.command.argv);
}
bd->client.icccm.command.argc = 0;
bd->client.icccm.command.argv = NULL;
ecore_x_icccm_command_get(bd->client.win,
&(bd->client.icccm.command.argc),
&(bd->client.icccm.command.argv));
if ((bd->client.icccm.client_leader) &&
(!bd->client.icccm.command.argv))
ecore_x_icccm_command_get(bd->client.icccm.client_leader,
&(bd->client.icccm.command.argc),
&(bd->client.icccm.command.argv));
bd->client.icccm.fetch.command = 0;
rem_change = 1;
}
if (bd->changes.prop || bd->client.icccm.fetch.hints)
{
Eina_Bool accepts_focus, is_urgent;
accepts_focus = EINA_TRUE;
is_urgent = EINA_FALSE;
bd->client.icccm.initial_state = ECORE_X_WINDOW_STATE_HINT_NORMAL;
if (ecore_x_icccm_hints_get(bd->client.win,
&accepts_focus,
&bd->client.icccm.initial_state,
&bd->client.icccm.icon_pixmap,
&bd->client.icccm.icon_mask,
&bd->client.icccm.icon_window,
&bd->client.icccm.window_group,
&is_urgent))
{
bd->client.icccm.accepts_focus = accepts_focus;
if ((bd->client.icccm.urgent != is_urgent) && ((!bd->focused) || (!is_urgent)))
change_urgent = 1;
bd->client.icccm.urgent = is_urgent;
/* If this is a new window, set the state as requested. */
if ((bd->new_client) &&
(bd->client.icccm.initial_state == ECORE_X_WINDOW_STATE_HINT_ICONIC))
{
e_border_iconify(bd);
e_border_hide(bd, 1);
}
}
bd->client.icccm.fetch.hints = 0;
rem_change = 1;
}
if (bd->changes.prop || bd->client.icccm.fetch.size_pos_hints)
{
Eina_Bool request_pos;
request_pos = EINA_FALSE;
if (ecore_x_icccm_size_pos_hints_get(bd->client.win,
&request_pos,
&bd->client.icccm.gravity,
&bd->client.icccm.min_w,
&bd->client.icccm.min_h,
&bd->client.icccm.max_w,
&bd->client.icccm.max_h,
&bd->client.icccm.base_w,
&bd->client.icccm.base_h,
&bd->client.icccm.step_w,
&bd->client.icccm.step_h,
&bd->client.icccm.min_aspect,
&bd->client.icccm.max_aspect))
{
bd->client.icccm.request_pos = request_pos;
}
else
{
}
if (bd->client.icccm.min_w > 32767) bd->client.icccm.min_w = 32767;
if (bd->client.icccm.min_h > 32767) bd->client.icccm.min_h = 32767;
if (bd->client.icccm.max_w > 32767) bd->client.icccm.max_w = 32767;
if (bd->client.icccm.max_h > 32767) bd->client.icccm.max_h = 32767;
if (bd->client.icccm.base_w > 32767) bd->client.icccm.base_w = 32767;
if (bd->client.icccm.base_h > 32767) bd->client.icccm.base_h = 32767;
// if (bd->client.icccm.step_w < 1) bd->client.icccm.step_w = 1;
// if (bd->client.icccm.step_h < 1) bd->client.icccm.step_h = 1;
// if doing a resize, fix it up
if (bd->resize_mode != RESIZE_NONE)
{
int x, y, w, h, new_w, new_h;
x = bd->x;
y = bd->y;
w = bd->w;
h = bd->h;
new_w = w;
new_h = h;
e_border_resize_limit(bd, &new_w, &new_h);
if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_L) ||
(bd->resize_mode == RESIZE_BL))
x += (w - new_w);
if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_T) ||
(bd->resize_mode == RESIZE_TR))
y += (h - new_h);
e_border_move_resize(bd, x, y, new_w, new_h);
}
bd->client.icccm.fetch.size_pos_hints = 0;
rem_change = 1;
}
if (bd->client.icccm.fetch.protocol)
{
int i, num;
Ecore_X_WM_Protocol *proto;
proto = ecore_x_window_prop_protocol_list_get(bd->client.win, &num);
if (proto)
{
for (i = 0; i < num; i++)
{
if (proto[i] == ECORE_X_WM_PROTOCOL_DELETE_REQUEST)
bd->client.icccm.delete_request = 1;
else if (proto[i] == ECORE_X_WM_PROTOCOL_TAKE_FOCUS)
bd->client.icccm.take_focus = 1;
else if (proto[i] == ECORE_X_NET_WM_PROTOCOL_PING)
bd->client.netwm.ping = 1;
else if (proto[i] == ECORE_X_NET_WM_PROTOCOL_SYNC_REQUEST)
{
bd->client.netwm.sync.request = 1;
if (!ecore_x_netwm_sync_counter_get(bd->client.win,
&bd->client.netwm.sync.counter))
bd->client.netwm.sync.request = 0;
}
}
free(proto);
}
if (bd->client.netwm.ping)
e_border_ping(bd);
else
{
if (bd->ping_poller) ecore_poller_del(bd->ping_poller);
bd->ping_poller = NULL;
}
bd->client.icccm.fetch.protocol = 0;
}
if (bd->client.icccm.fetch.transient_for)
{
/* TODO: What do to if the transient for isn't mapped yet? */
E_Border *bd_parent = NULL;
bd->client.icccm.transient_for = ecore_x_icccm_transient_for_get(bd->client.win);
if (bd->client.icccm.transient_for)
bd_parent = e_border_find_by_client_window(bd->client.icccm.transient_for);
/* If we already have a parent, remove it */
if (bd->parent)
{
if (bd_parent != bd->parent)
{
bd->parent->transients = eina_list_remove(bd->parent->transients, bd);
if (bd->parent->modal == bd) bd->parent->modal = NULL;
bd->parent = NULL;
}
else
bd_parent = NULL;
}
if ((bd_parent) && (bd_parent != bd) &&
(eina_list_data_find(bd->transients, bd_parent) != bd_parent))
{
bd_parent->transients = eina_list_append(bd_parent->transients, bd);
bd->parent = bd_parent;
}
if (bd->parent)
{
if (bd->parent->layer != bd->layer)
e_border_layer_set(bd, bd->parent->layer);
if ((e_config->modal_windows) && (bd->client.netwm.state.modal))
{
bd->parent->modal = bd;
bd->parent->lock_close = 1;
if (!bd->parent->client.lock_win)
{
bd->parent->client.lock_win = ecore_x_window_input_new(bd->parent->client.shell_win, 0, 0, bd->parent->client.w, bd->parent->client.h);
eina_hash_add(borders_hash, e_util_winid_str_get(bd->parent->client.lock_win), bd->parent);
ecore_x_window_show(bd->parent->client.lock_win);
}
}
if (e_config->focus_setting == E_FOCUS_NEW_DIALOG ||
(bd->parent->focused && (e_config->focus_setting == E_FOCUS_NEW_DIALOG_IF_OWNER_FOCUSED)))
bd->take_focus = 1;
}
bd->client.icccm.fetch.transient_for = 0;
rem_change = 1;
}
if (bd->client.icccm.fetch.window_role)
{
char *role = ecore_x_icccm_window_role_get(bd->client.win);
eina_stringshare_replace(&bd->client.icccm.window_role, role);
free(role);
bd->client.icccm.fetch.window_role = 0;
rem_change = 1;
}
if (bd->client.icccm.fetch.icon_name)
{
char *icon_name = ecore_x_icccm_icon_name_get(bd->client.win);
eina_stringshare_replace(&bd->client.icccm.icon_name, icon_name);
free(icon_name);
bd->client.icccm.fetch.icon_name = 0;
rem_change = 1;
}
if (bd->client.netwm.fetch.icon_name)
{
char *icon_name;
ecore_x_netwm_icon_name_get(bd->client.win, &icon_name);
eina_stringshare_replace(&bd->client.netwm.icon_name, icon_name);
free(icon_name);
bd->client.netwm.fetch.icon_name = 0;
rem_change = 1;
}
if (bd->client.netwm.fetch.icon)
{
int i;
if (bd->client.netwm.icons)
{
for (i = 0; i < bd->client.netwm.num_icons; i++)
{
free(bd->client.netwm.icons[i].data);
bd->client.netwm.icons[i].data = NULL;
}
free(bd->client.netwm.icons);
}
bd->client.netwm.icons = NULL;
bd->client.netwm.num_icons = 0;
if (ecore_x_netwm_icons_get(bd->client.win,
&bd->client.netwm.icons,
&bd->client.netwm.num_icons))
{
// unless the rest of e17 uses border icons OTHER than icon #0
// then free the rest that we don't need anymore.
for (i = 1; i < bd->client.netwm.num_icons; i++)
{
free(bd->client.netwm.icons[i].data);
bd->client.netwm.icons[i].data = NULL;
}
bd->client.netwm.num_icons = 1;
bd->changes.icon = 1;
}
bd->client.netwm.fetch.icon = 0;
}
if (bd->client.netwm.fetch.user_time)
{
ecore_x_netwm_user_time_get(bd->client.win, &bd->client.netwm.user_time);
bd->client.netwm.fetch.user_time = 0;
}
if (bd->client.netwm.fetch.strut)
{
if (!ecore_x_netwm_strut_partial_get(bd->client.win,
&bd->client.netwm.strut.left,
&bd->client.netwm.strut.right,
&bd->client.netwm.strut.top,
&bd->client.netwm.strut.bottom,
&bd->client.netwm.strut.left_start_y,
&bd->client.netwm.strut.left_end_y,
&bd->client.netwm.strut.right_start_y,
&bd->client.netwm.strut.right_end_y,
&bd->client.netwm.strut.top_start_x,
&bd->client.netwm.strut.top_end_x,
&bd->client.netwm.strut.bottom_start_x,
&bd->client.netwm.strut.bottom_end_x))
{
ecore_x_netwm_strut_get(bd->client.win,
&bd->client.netwm.strut.left, &bd->client.netwm.strut.right,
&bd->client.netwm.strut.top, &bd->client.netwm.strut.bottom);
bd->client.netwm.strut.left_start_y = 0;
bd->client.netwm.strut.left_end_y = 0;
bd->client.netwm.strut.right_start_y = 0;
bd->client.netwm.strut.right_end_y = 0;
bd->client.netwm.strut.top_start_x = 0;
bd->client.netwm.strut.top_end_x = 0;
bd->client.netwm.strut.bottom_start_x = 0;
bd->client.netwm.strut.bottom_end_x = 0;
}
bd->client.netwm.fetch.strut = 0;
}
if (bd->client.qtopia.fetch.soft_menu)
{
e_hints_window_qtopia_soft_menu_get(bd);
bd->client.qtopia.fetch.soft_menu = 0;
rem_change = 1;
}
if (bd->client.qtopia.fetch.soft_menus)
{
e_hints_window_qtopia_soft_menus_get(bd);
bd->client.qtopia.fetch.soft_menus = 0;
rem_change = 1;
}
if (bd->client.vkbd.fetch.state)
{
e_hints_window_virtual_keyboard_state_get(bd);
bd->client.vkbd.fetch.state = 0;
rem_change = 1;
}
if (bd->client.vkbd.fetch.vkbd)
{
e_hints_window_virtual_keyboard_get(bd);
bd->client.vkbd.fetch.vkbd = 0;
rem_change = 1;
}
if (bd->client.illume.conformant.fetch.conformant)
{
bd->client.illume.conformant.conformant =
ecore_x_e_illume_conformant_get(bd->client.win);
bd->client.illume.conformant.fetch.conformant = 0;
}
if (bd->client.illume.quickpanel.fetch.state)
{
bd->client.illume.quickpanel.state =
ecore_x_e_illume_quickpanel_state_get(bd->client.win);
bd->client.illume.quickpanel.fetch.state = 0;
}
if (bd->client.illume.quickpanel.fetch.quickpanel)
{
bd->client.illume.quickpanel.quickpanel =
ecore_x_e_illume_quickpanel_get(bd->client.win);
bd->client.illume.quickpanel.fetch.quickpanel = 0;
}
if (bd->client.illume.quickpanel.fetch.priority.major)
{
bd->client.illume.quickpanel.priority.major =
ecore_x_e_illume_quickpanel_priority_major_get(bd->client.win);
bd->client.illume.quickpanel.fetch.priority.major = 0;
}
if (bd->client.illume.quickpanel.fetch.priority.minor)
{
bd->client.illume.quickpanel.priority.minor =
ecore_x_e_illume_quickpanel_priority_minor_get(bd->client.win);
bd->client.illume.quickpanel.fetch.priority.minor = 0;
}
if (bd->client.illume.quickpanel.fetch.zone)
{
bd->client.illume.quickpanel.zone =
ecore_x_e_illume_quickpanel_zone_get(bd->client.win);
bd->client.illume.quickpanel.fetch.zone = 0;
}
if (bd->client.illume.drag.fetch.drag)
{
bd->client.illume.drag.drag =
ecore_x_e_illume_drag_get(bd->client.win);
bd->client.illume.drag.fetch.drag = 0;
}
if (bd->client.illume.drag.fetch.locked)
{
bd->client.illume.drag.locked =
ecore_x_e_illume_drag_locked_get(bd->client.win);
bd->client.illume.drag.fetch.locked = 0;
}
if (bd->client.illume.win_state.fetch.state)
{
bd->client.illume.win_state.state =
ecore_x_e_illume_window_state_get(bd->client.win);
bd->client.illume.win_state.fetch.state = 0;
}
if (bd->changes.shape)
{
Ecore_X_Rectangle *rects;
int num;
bd->changes.shape = 0;
rects = ecore_x_window_shape_rectangles_get(bd->client.win, &num);
if (rects)
{
int cw = 0, ch = 0;
/* This doesn't fix the race, but makes it smaller. we detect
* this and if cw and ch != client w/h then mark this as needing
* a shape change again to fixup next event loop.
*/
ecore_x_window_size_get(bd->client.win, &cw, &ch);
if ((cw != bd->client.w) || (ch != bd->client.h))
bd->changes.shape = 1;
if ((num == 1) &&
(rects[0].x == 0) &&
(rects[0].y == 0) &&
((int)rects[0].width == cw) &&
((int)rects[0].height == ch))
{
if (bd->client.shaped)
{
bd->client.shaped = 0;
if (!bd->bordername)
bd->client.border.changed = 1;
}
}
else
{
if (!bd->client.shaped)
{
bd->client.shaped = 1;
if (!bd->bordername)
bd->client.border.changed = 1;
}
}
free(rects);
}
else
{
// FIXME: no rects i think can mean... totally empty window
bd->client.shaped = 0;
if (!bd->bordername)
bd->client.border.changed = 1;
}
bd->need_shape_merge = 1;
}
if (bd->changes.shape_input)
{
Ecore_X_Rectangle *rects;
int num;
bd->changes.shape_input = 0;
rects = ecore_x_window_shape_input_rectangles_get(bd->client.win, &num);
if (rects)
{
int cw = 0, ch = 0;
/* This doesn't fix the race, but makes it smaller. we detect
* this and if cw and ch != client w/h then mark this as needing
* a shape change again to fixup next event loop.
*/
ecore_x_window_size_get(bd->client.win, &cw, &ch);
if ((cw != bd->client.w) || (ch != bd->client.h))
bd->changes.shape_input = 1;
if ((num == 1) &&
(rects[0].x == 0) &&
(rects[0].y == 0) &&
((int)rects[0].width == cw) &&
((int)rects[0].height == ch))
{
if (bd->shaped_input)
{
bd->shaped_input = 0;
if (!bd->bordername)
bd->client.border.changed = 1;
}
}
else
{
if (!bd->shaped_input)
{
bd->shaped_input = 1;
if (!bd->bordername)
bd->client.border.changed = 1;
}
}
free(rects);
}
else
{
bd->shaped_input = 1;
if (!bd->bordername)
bd->client.border.changed = 1;
}
bd->need_shape_merge = 1;
}
if (bd->changes.prop || bd->client.mwm.fetch.hints)
{
int pb;
bd->client.mwm.exists =
ecore_x_mwm_hints_get(bd->client.win,
&bd->client.mwm.func,
&bd->client.mwm.decor,
&bd->client.mwm.input);
pb = bd->client.mwm.borderless;
bd->client.mwm.borderless = 0;
if (bd->client.mwm.exists)
{
if ((!(bd->client.mwm.decor & ECORE_X_MWM_HINT_DECOR_ALL)) &&
(!(bd->client.mwm.decor & ECORE_X_MWM_HINT_DECOR_TITLE)) &&
(!(bd->client.mwm.decor & ECORE_X_MWM_HINT_DECOR_BORDER)))
bd->client.mwm.borderless = 1;
}
if (bd->client.mwm.borderless != pb)
{
if ((!bd->lock_border) || (!bd->client.border.name))
bd->client.border.changed = 1;
}
bd->client.mwm.fetch.hints = 0;
rem_change = 1;
}
if (bd->client.e.fetch.video_parent)
{
/* unlinking child/parent */
if (bd->client.e.state.video_parent_border != NULL)
{
bd->client.e.state.video_parent_border->client.e.state.video_child =
eina_list_remove
(bd->client.e.state.video_parent_border->client.e.state.video_child,
bd);
}
ecore_x_window_prop_card32_get(bd->client.win,
ECORE_X_ATOM_E_VIDEO_PARENT,
&bd->client.e.state.video_parent,
1);
/* linking child/parent */
if (bd->client.e.state.video_parent != 0)
{
E_Border *tmp;
Eina_List *l;
EINA_LIST_FOREACH(borders, l, tmp)
if (tmp->client.win == bd->client.e.state.video_parent)
{
/* fprintf(stderr, "child added to parent \\o/\n"); */
bd->client.e.state.video_parent_border = tmp;
tmp->client.e.state.video_child = eina_list_append(tmp->client.e.state.video_child,
bd);
if (bd->desk != tmp->desk)
e_border_desk_set(bd, tmp->desk);
break;
}
}
/* fprintf(stderr, "new parent %x => %p\n", bd->client.e.state.video_parent, bd->client.e.state.video_parent_border); */
if (bd->client.e.state.video_parent_border) bd->client.e.fetch.video_parent = 0;
rem_change = 1;
}
if (bd->client.e.fetch.video_position && bd->client.e.fetch.video_parent == 0)
{
unsigned int xy[2];
ecore_x_window_prop_card32_get(bd->client.win,
ECORE_X_ATOM_E_VIDEO_POSITION,
xy,
2);
bd->client.e.state.video_position.x = xy[0];
bd->client.e.state.video_position.y = xy[1];
bd->client.e.state.video_position.updated = 1;
bd->client.e.fetch.video_position = 0;
bd->x = bd->client.e.state.video_position.x;
bd->y = bd->client.e.state.video_position.y;
fprintf(stderr, "internal position has been updated [%i, %i]\n", bd->client.e.state.video_position.x, bd->client.e.state.video_position.y);
}
if (bd->changes.prop || bd->client.netwm.update.state)
{
e_hints_window_state_set(bd);
/* Some stats might change the border, like modal */
if (((!bd->lock_border) || (!bd->client.border.name)) &&
(!(((bd->maximized & E_MAXIMIZE_TYPE) == E_MAXIMIZE_FULLSCREEN))))
{
bd->client.border.changed = 1;
}
if (bd->parent)
{
if ((e_config->modal_windows) && (bd->client.netwm.state.modal))
{
bd->parent->modal = bd;
if (bd->parent->focused)
e_border_focus_set(bd, 1, 1);
}
}
else if (bd->leader)
{
if ((e_config->modal_windows) && (bd->client.netwm.state.modal))
{
bd->leader->modal = bd;
if (bd->leader->focused)
e_border_focus_set(bd, 1, 1);
else
{
Eina_List *l;
E_Border *child;
EINA_LIST_FOREACH(bd->leader->group, l, child)
{
if ((child != bd) && (child->focused))
e_border_focus_set(bd, 1, 1);
}
}
}
}
bd->client.netwm.update.state = 0;
}
#if (ECORE_VERSION_MAJOR > 1) || (ECORE_VERSION_MINOR >= 8)
if ((e_config->use_desktop_window_profile) && (need_desk_set))
{
if (!(bd->client.e.state.profile.name) &&
(bd->client.e.state.profile.num >= 1))
{
const char *p = NULL;
int i;
for (i = 0; i < bd->client.e.state.profile.num; i++)
{
if (!bd->client.e.state.profile.available_list[i])
continue;
p = bd->client.e.state.profile.available_list[i];
if (strcmp(bd->desk->window_profile, p) == 0)
{
bd->client.e.state.profile.name = eina_stringshare_add(bd->desk->window_profile);
break;
}
}
if (!bd->client.e.state.profile.name)
{
E_Container *con = bd->zone->container;
E_Desk *desk = NULL;
for (i = 0; i < bd->client.e.state.profile.num; i++)
{
if (!bd->client.e.state.profile.available_list[i])
continue;
p = bd->client.e.state.profile.available_list[i];
desk = e_container_desk_window_profile_get(con, p);
if ((desk) && (bd->desk != desk))
{
bd->client.e.state.profile.name = eina_stringshare_add(p);
break;
}
}
}
}
if (!bd->client.e.state.profile.name)
{
bd->client.e.state.profile.name = eina_stringshare_add(bd->desk->window_profile);
}
ecore_x_e_window_profile_change_request_send(bd->client.win,
bd->client.e.state.profile.name);
bd->client.e.state.profile.wait_for_done = 1;
}
#endif
if (bd->new_client)
{
E_Event_Border_Add *ev;
E_Exec_Instance *inst;
ev = E_NEW(E_Event_Border_Add, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_add_event");
ecore_event_add(E_EVENT_BORDER_ADD, ev, _e_border_event_border_add_free, NULL);
if ((!bd->lock_border) || (!bd->client.border.name))
bd->client.border.changed = 1;
{
char *str = NULL;
if ((ecore_x_netwm_startup_id_get(bd->client.win, &str) && (str)) ||
((bd->client.icccm.client_leader > 0) &&
ecore_x_netwm_startup_id_get(bd->client.icccm.client_leader, &str) && (str))
)
{
if (!strncmp(str, "E_START|", 8))
{
int id;
id = atoi(str + 8);
if (id > 0) bd->client.netwm.startup_id = id;
}
free(str);
}
}
/* It's ok not to have fetch flag, should only be set on startup
* * and not changed. */
if (!ecore_x_netwm_pid_get(bd->client.win, &bd->client.netwm.pid))
{
if (bd->client.icccm.client_leader)
{
if (!ecore_x_netwm_pid_get(bd->client.icccm.client_leader, &bd->client.netwm.pid))
bd->client.netwm.pid = -1;
}
else
bd->client.netwm.pid = -1;
}
if (!bd->re_manage)
{
inst = e_exec_startup_id_pid_instance_find(bd->client.netwm.startup_id,
bd->client.netwm.pid);
if ((inst) && (inst->used == 0))
{
E_Zone *zone;
E_Desk *desk;
inst->used++;
zone = e_container_zone_number_get(bd->zone->container,
inst->screen);
if (zone) e_border_zone_set(bd, zone);
desk = e_desk_at_xy_get(bd->zone, inst->desk_x,
inst->desk_y);
if (desk) e_border_desk_set(bd, desk);
e_exec_instance_found(inst);
}
if (e_config->window_grouping) // FIXME: We may want to make the border "urgent" so that the user knows it appeared.
{
E_Border *bdl = NULL;
bdl = bd->parent;
if (!bdl)
{
if (bd->leader) bdl = bd->leader;
}
if (!bdl)
{
E_Border *child;
E_Border_List *bl;
bl = e_container_border_list_first(bd->zone->container);
while ((child = e_container_border_list_next(bl)))
{
if (child == bd) continue;
if (e_object_is_del(E_OBJECT(child))) continue;
if ((bd->client.icccm.client_leader) &&
(child->client.icccm.client_leader ==
bd->client.icccm.client_leader))
{
bdl = child;
break;
}
}
e_container_border_list_free(bl);
}
if (bdl)
{
if (bdl->zone)
e_border_zone_set(bd, bdl->zone);
if (bdl->desk)
e_border_desk_set(bd, bdl->desk);
else
e_border_stick(bd);
}
}
}
}
/* PRE_POST_FETCH calls e_remember apply for new client */
_e_border_hook_call(E_BORDER_HOOK_EVAL_PRE_POST_FETCH, bd);
_e_border_hook_call(E_BORDER_HOOK_EVAL_POST_FETCH, bd);
_e_border_hook_call(E_BORDER_HOOK_EVAL_PRE_BORDER_ASSIGN, bd);
if (bd->need_reparent)
{
if (!bd->internal)
ecore_x_window_save_set_add(bd->client.win);
ecore_x_window_reparent(bd->client.win, bd->client.shell_win, 0, 0);
if (bd->visible)
{
if ((bd->new_client) && (bd->internal) &&
(bd->internal_ecore_evas))
ecore_evas_show(bd->internal_ecore_evas);
ecore_x_window_show(bd->client.win);
}
bd->need_reparent = 0;
}
if ((bd->client.border.changed) && (!bd->shaded) &&
(!(((bd->maximized & E_MAXIMIZE_TYPE) == E_MAXIMIZE_FULLSCREEN))))
{
const char *bordername;
if (bd->fullscreen)
bordername = "borderless";
else if (bd->bordername)
bordername = bd->bordername;
else if ((bd->client.mwm.borderless) || (bd->borderless))
bordername = "borderless";
else if (bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DESKTOP)
bordername = "borderless";
else if (((bd->client.icccm.transient_for != 0) ||
(bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DIALOG)) &&
(bd->client.icccm.min_w == bd->client.icccm.max_w) &&
(bd->client.icccm.min_h == bd->client.icccm.max_h))
bordername = "noresize_dialog";
else if ((bd->client.icccm.min_w == bd->client.icccm.max_w) &&
(bd->client.icccm.min_h == bd->client.icccm.max_h))
bordername = "noresize";
else if (bd->client.shaped)
bordername = "shaped";
else if ((!bd->client.icccm.accepts_focus) &&
(!bd->client.icccm.take_focus))
bordername = "nofocus";
else if (bd->client.icccm.urgent)
bordername = "urgent";
else if ((bd->client.icccm.transient_for != 0) ||
(bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DIALOG))
bordername = "dialog";
else if (bd->client.netwm.state.modal)
bordername = "modal";
else if ((bd->client.netwm.state.skip_taskbar) ||
(bd->client.netwm.state.skip_pager))
bordername = "skipped";
/*
else if ((bd->internal) && (bd->client.icccm.class) &&
(!strncmp(bd->client.icccm.class, "e_fwin", 6)))
bordername = "internal_fileman";
*/
else
bordername = e_config->theme_default_border_style;
if (!bordername) bordername = "default";
if ((!bd->client.border.name) || (strcmp(bd->client.border.name, bordername)))
{
Evas_Object *o;
char buf[4096];
int ok;
bd->changes.border = 1;
eina_stringshare_replace(&bd->client.border.name, bordername);
if (bd->bg_object)
{
bd->w -= (bd->client_inset.l + bd->client_inset.r);
bd->h -= (bd->client_inset.t + bd->client_inset.b);
bd->changes.size = 1;
evas_object_del(bd->bg_object);
}
o = edje_object_add(bd->bg_evas);
snprintf(buf, sizeof(buf), "e/widgets/border/%s/border", bd->client.border.name);
ok = e_theme_edje_object_set(o, "base/theme/borders", buf);
if ((!ok) && (strcmp(bd->client.border.name, "borderless")))
{
if (bd->client.border.name != e_config->theme_default_border_style)
{
snprintf(buf, sizeof(buf), "e/widgets/border/%s/border", e_config->theme_default_border_style);
ok = e_theme_edje_object_set(o, "base/theme/borders", buf);
}
if (!ok)
{
ok = e_theme_edje_object_set(o, "base/theme/borders",
"e/widgets/border/default/border");
if (ok)
{
/* Reset default border style to default */
eina_stringshare_replace(&e_config->theme_default_border_style, "default");
e_config_save_queue();
}
}
}
bd->shaped = 0;
if (ok)
{
const char *shape_option, *argb_option;
int use_argb = 0;
bd->bg_object = o;
if ((e_config->use_composite) && (!bd->client.argb))
{
argb_option = edje_object_data_get(o, "argb");
if ((argb_option) && (!strcmp(argb_option, "1")))
use_argb = 1;
o = bd->bg_object;
if (use_argb != bd->argb)
_e_border_frame_replace(bd, use_argb);
if (bd->icon_object != o)
{
if (bd->bg_object)
{
evas_object_show(bd->icon_object);
edje_object_part_swallow(bd->bg_object, "e.swallow.icon", bd->icon_object);
}
else
evas_object_hide(bd->icon_object);
}
o = bd->bg_object;
}
if (!bd->argb)
{
shape_option = edje_object_data_get(o, "shaped");
if ((shape_option) && (!strcmp(shape_option, "1")))
bd->shaped = 1;
}
if (bd->client.netwm.name)
edje_object_part_text_set(o, "e.text.title",
bd->client.netwm.name);
else if (bd->client.icccm.title)
edje_object_part_text_set(o, "e.text.title",
bd->client.icccm.title);
}
else
{
evas_object_del(o);
bd->bg_object = NULL;
}
_e_border_client_inset_calc(bd);
bd->w += (bd->client_inset.l + bd->client_inset.r);
bd->h += (bd->client_inset.t + bd->client_inset.b);
ecore_evas_shaped_set(bd->bg_ecore_evas, bd->shaped);
bd->changes.size = 1;
/* really needed ? */
ecore_x_window_move(bd->client.shell_win,
bd->client_inset.l,
bd->client_inset.t);
if (bd->maximized != E_MAXIMIZE_NONE)
{
E_Maximize maximized = bd->maximized;
/* to force possible resizes */
bd->maximized = E_MAXIMIZE_NONE;
_e_border_maximize(bd, maximized);
/* restore maximized state */
bd->maximized = maximized;
e_hints_window_maximized_set(bd, bd->maximized & E_MAXIMIZE_HORIZONTAL,
bd->maximized & E_MAXIMIZE_VERTICAL);
}
if (bd->bg_object)
{
edje_object_signal_callback_add(bd->bg_object, "*", "*",
_e_border_cb_signal_bind, bd);
if (bd->focused)
{
edje_object_signal_emit(bd->bg_object, "e,state,focused", "e");
if (bd->icon_object)
edje_object_signal_emit(bd->icon_object, "e,state,focused", "e");
}
if (bd->shaded)
edje_object_signal_emit(bd->bg_object, "e,state,shaded", "e");
if (bd->sticky)
edje_object_signal_emit(bd->bg_object, "e,state,sticky", "e");
if (bd->hung)
edje_object_signal_emit(bd->bg_object, "e,state,hung", "e");
// FIXME: in eval -do differently
// edje_object_message_signal_process(bd->bg_object);
// e_border_frame_recalc(bd);
evas_object_move(bd->bg_object, 0, 0);
evas_object_resize(bd->bg_object, bd->w, bd->h);
evas_object_show(bd->bg_object);
}
}
bd->client.border.changed = 0;
}
bd->changes.prop = 0;
if (rem_change) e_remember_update(bd);
if (change_urgent)
{
E_Event_Border_Urgent_Change *ev;
if (bd->client.icccm.urgent)
edje_object_signal_emit(bd->bg_object, "e,state,urgent", "e");
else
edje_object_signal_emit(bd->bg_object, "e,state,not_urgent", "e");
ev = E_NEW(E_Event_Border_Urgent_Change, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
ecore_event_add(E_EVENT_BORDER_URGENT_CHANGE, ev,
_e_border_event_border_urgent_change_free, NULL);
}
_e_border_hook_call(E_BORDER_HOOK_EVAL_POST_BORDER_ASSIGN, bd);
}
static void
_e_border_eval(E_Border *bd)
{
E_Event_Border_Property *event;
E_Border_Pending_Move_Resize *pnd;
int rem_change = 0;
int send_event = 1;
if (e_object_is_del(E_OBJECT(bd)))
{
CRI("_e_border_eval(%p) with deleted border! - %d\n", bd, bd->new_client);
bd->changed = 0;
return;
}
_e_border_hook_call(E_BORDER_HOOK_EVAL_PRE_NEW_BORDER, bd);
if (bd->new_client)
{
int zx = 0, zy = 0, zw = 0, zh = 0;
if (bd->zone)
e_zone_useful_geometry_get(bd->zone, &zx, &zy, &zw, &zh);
/*
* Limit maximum size of windows to useful geometry
*/
// TODO: temoporary limited maximize algorithm
// ->
/*if (bd->w > zw)
rw = zw;
else
rw = bd->w;
if (bd->h > zh)
rh = zh;
else
rh = bd->h;
if ((rw != bd->w) || (rh != bd->h))
{
bd->w = rw;
bd->h = rh;
e_border_resize (bd, bd->w, bd->h);
}*/
// <-
if (bd->re_manage)
{
bd->x -= bd->client_inset.l;
bd->y -= bd->client_inset.t;
bd->changes.pos = 1;
bd->placed = 1;
}
else if ((!bd->placed) && (bd->client.icccm.request_pos))
{
Ecore_X_Window_Attributes *att;
int bw;
att = &bd->client.initial_attributes;
bw = att->border * 2;
switch (bd->client.icccm.gravity)
{
case ECORE_X_GRAVITY_N:
bd->x = (att->x - (bw / 2)) - (bd->client_inset.l / 2);
bd->y = att->y;
break;
case ECORE_X_GRAVITY_NE:
bd->x = (att->x - (bw)) - (bd->client_inset.l);
bd->y = att->y;
break;
case ECORE_X_GRAVITY_E:
bd->x = (att->x - (bw)) - (bd->client_inset.l);
bd->y = (att->y - (bw / 2)) - (bd->client_inset.t / 2);
break;
case ECORE_X_GRAVITY_SE:
bd->x = (att->x - (bw)) - (bd->client_inset.l);
bd->y = (att->y - (bw)) - (bd->client_inset.t);
break;
case ECORE_X_GRAVITY_S:
bd->x = (att->x - (bw / 2)) - (bd->client_inset.l / 2);
bd->y = (att->y - (bw)) - (bd->client_inset.t);
break;
case ECORE_X_GRAVITY_SW:
bd->x = att->x;
bd->y = (att->y - (bw)) - (bd->client_inset.t);
break;
case ECORE_X_GRAVITY_W:
bd->x = att->x;
bd->y = (att->y - (bw)) - (bd->client_inset.t);
break;
case ECORE_X_GRAVITY_CENTER:
bd->x = (att->x - (bw / 2)) - (bd->client_inset.l / 2);
bd->y = (att->y - (bw / 2)) - (bd->client_inset.t / 2);
break;
case ECORE_X_GRAVITY_NW:
default:
bd->x = att->x;
bd->y = att->y;
}
/*
* This ensures that windows that like to open with a x/y
* position smaller than returned by e_zone_useful_geometry_get()
* are moved to useful positions.
*/
// ->
if (e_config->geometry_auto_move)
{
if (bd->x < zx)
bd->x = zx;
if (bd->y < zy)
bd->y = zy;
/* ensure we account for windows which already have client_inset;
* fixes lots of wine placement issues
*/
if (bd->x - bd->client_inset.l >= zx)
bd->x -= bd->client_inset.l;
if (bd->y - bd->client_inset.t >= zy)
bd->y -= bd->client_inset.t;
if (bd->x + bd->w > zx + zw)
bd->x = zx + zw - bd->w;
if (bd->y + bd->h > zy + zh)
bd->y = zy + zh - bd->h;
// <--
if (bd->zone && e_container_zone_at_point_get(bd->zone->container, bd->x, bd->y))
{
bd->changes.pos = 1;
bd->placed = 1;
}
}
else
{
bd->changes.pos = 1;
bd->placed = 1;
}
}
if (!bd->placed)
{
/* FIXME: special placement for dialogs etc. etc. etc goes
* here */
/* FIXME: what if parent is not on this desktop - or zone? */
if ((bd->parent) && (bd->parent->visible))
{
bd->x = bd->parent->x + ((bd->parent->w - bd->w) / 2);
bd->y = bd->parent->y + ((bd->parent->h - bd->h) / 2);
bd->changes.pos = 1;
bd->placed = 1;
}
#if 0
else if ((bd->leader) && (bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DIALOG))
{
/* TODO: Place in center of group */
}
#endif
else if (bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DIALOG)
{
bd->x = zx + ((zw - bd->w) / 2);
bd->y = zy + ((zh - bd->h) / 2);
bd->changes.pos = 1;
bd->placed = 1;
}
}
if (!bd->placed)
{
Eina_List *skiplist = NULL;
int new_x, new_y;
if (zw > bd->w)
new_x = zx + (rand() % (zw - bd->w));
else
new_x = zx;
if (zh > bd->h)
new_y = zy + (rand() % (zh - bd->h));
else
new_y = zy;
if ((e_config->window_placement_policy == E_WINDOW_PLACEMENT_SMART) || (e_config->window_placement_policy == E_WINDOW_PLACEMENT_ANTIGADGET))
{
skiplist = eina_list_append(skiplist, bd);
if (bd->desk)
e_place_desk_region_smart(bd->desk, skiplist,
bd->x, bd->y, bd->w, bd->h,
&new_x, &new_y);
else
e_place_zone_region_smart(bd->zone, skiplist,
bd->x, bd->y, bd->w, bd->h,
&new_x, &new_y);
eina_list_free(skiplist);
}
else if (e_config->window_placement_policy == E_WINDOW_PLACEMENT_MANUAL)
{
e_place_zone_manual(bd->zone, bd->w, bd->client_inset.t,
&new_x, &new_y);
}
else
{
e_place_zone_cursor(bd->zone, bd->x, bd->y, bd->w, bd->h,
bd->client_inset.t, &new_x, &new_y);
}
bd->x = new_x;
bd->y = new_y;
bd->changes.pos = 1;
}
EINA_LIST_FREE(bd->pending_move_resize, pnd)
{
if ((!bd->lock_client_location) && (pnd->move))
{
bd->x = pnd->x;
bd->y = pnd->y;
bd->changes.pos = 1;
bd->placed = 1;
if (pnd->without_border)
{
bd->x -= bd->client_inset.l;
bd->y -= bd->client_inset.t;
}
}
if ((!bd->lock_client_size) && (pnd->resize))
{
bd->w = pnd->w + (bd->client_inset.l + bd->client_inset.r);
bd->h = pnd->h + (bd->client_inset.t + bd->client_inset.b);
bd->client.w = pnd->w;
bd->client.h = pnd->h;
bd->changes.size = 1;
}
free(pnd);
}
/* Recreate state */
e_hints_window_init(bd);
if ((bd->client.e.state.centered) &&
((!bd->remember) ||
((bd->remember) && (!(bd->remember->apply & E_REMEMBER_APPLY_POS)))))
{
bd->x = zx + (zw - bd->w) / 2;
bd->y = zy + (zh - bd->h) / 2;
bd->changes.pos = 1;
bd->placed = 1;
}
_e_border_client_move_resize_send(bd);
/* if the explicit geometry request asks for the app to be
* in another zone - well move it there */
{
E_Zone *zone;
zone = e_container_zone_at_point_get(bd->zone->container,
bd->x + (bd->w / 2),
bd->y + (bd->h / 2));
if (!zone)
zone = e_container_zone_at_point_get(bd->zone->container,
bd->x,
bd->y);
if (!zone)
zone = e_container_zone_at_point_get(bd->zone->container,
bd->x + bd->w - 1,
bd->y);
if (!zone)
zone = e_container_zone_at_point_get(bd->zone->container,
bd->x + bd->w - 1,
bd->y + bd->h - 1);
if (!zone)
zone = e_container_zone_at_point_get(bd->zone->container,
bd->x,
bd->y + bd->h - 1);
if ((zone) && (zone != bd->zone))
e_border_zone_set(bd, zone);
}
}
_e_border_hook_call(E_BORDER_HOOK_EVAL_POST_NEW_BORDER, bd);
/* effect changes to the window border itself */
if ((bd->changes.shading))
{
/* show at start of unshade (but don't hide until end of shade) */
if (bd->shaded)
ecore_x_window_raise(bd->client.shell_win);
bd->changes.shading = 0;
rem_change = 1;
}
if ((bd->changes.shaded) && (bd->changes.pos) && (bd->changes.size))
{
if (bd->shaded)
ecore_x_window_lower(bd->client.shell_win);
else
ecore_x_window_raise(bd->client.shell_win);
bd->changes.shaded = 0;
rem_change = 1;
}
else if ((bd->changes.shaded) && (bd->changes.pos))
{
if (bd->shaded)
ecore_x_window_lower(bd->client.shell_win);
else
ecore_x_window_raise(bd->client.shell_win);
bd->changes.size = 1;
bd->changes.shaded = 0;
rem_change = 1;
}
else if ((bd->changes.shaded) && (bd->changes.size))
{
if (bd->shaded)
ecore_x_window_lower(bd->client.shell_win);
else
ecore_x_window_raise(bd->client.shell_win);
bd->changes.shaded = 0;
rem_change = 1;
}
else if (bd->changes.shaded)
{
if (bd->shaded)
ecore_x_window_lower(bd->client.shell_win);
else
ecore_x_window_raise(bd->client.shell_win);
bd->changes.size = 1;
bd->changes.shaded = 0;
rem_change = 1;
}
if (bd->changes.size)
{
int x = 0, y = 0, xx = 0, yy = 0;
if ((bd->shaded) && (!bd->shading))
{
evas_obscured_clear(bd->bg_evas);
}
else
{
xx = bd->w - (bd->client_inset.l + bd->client_inset.r);
yy = bd->h - (bd->client_inset.t + bd->client_inset.b);
evas_obscured_clear(bd->bg_evas);
evas_obscured_rectangle_add(bd->bg_evas,
bd->client_inset.l, bd->client_inset.t, xx, yy);
if (bd->shading)
{
if (bd->shade.dir == E_DIRECTION_UP)
{
y = yy - bd->client.h;
}
else if (bd->shade.dir == E_DIRECTION_LEFT)
{
x = xx - bd->client.w;
}
}
}
if (bd->client.e.state.video)
{
if (bd->client.e.state.video_position.updated)
{
ecore_x_window_move(bd->win,
bd->client.e.state.video_parent_border->x +
bd->client.e.state.video_parent_border->client_inset.l +
bd->client.e.state.video_parent_border->fx.x +
bd->client.e.state.video_position.x,
bd->client.e.state.video_parent_border->y +
bd->client.e.state.video_parent_border->client_inset.t +
bd->client.e.state.video_parent_border->fx.y +
bd->client.e.state.video_position.y);
bd->client.e.state.video_position.updated = 0;
}
}
else if (!bd->changes.pos)
{
if (bd->post_job) ecore_idle_enterer_del(bd->post_job);
bd->post_job = ecore_idle_enterer_add(_e_border_post_move_resize_job, bd);
bd->post_resize = 1;
}
else
{
E_Border *tmp;
Eina_List *l;
ecore_x_window_move_resize(bd->win,
bd->x + bd->fx.x,
bd->y + bd->fx.y,
bd->w, bd->h);
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
ecore_x_window_move(tmp->win,
bd->x + bd->fx.x + bd->client_inset.l + tmp->client.e.state.video_position.x,
bd->y + bd->fx.y + bd->client_inset.t + tmp->client.e.state.video_position.y);
}
ecore_x_window_move_resize(bd->event_win, 0, 0, bd->w, bd->h);
if ((!bd->shaded) || (bd->shading))
ecore_x_window_move_resize(bd->client.shell_win,
bd->client_inset.l, bd->client_inset.t, xx, yy);
if (bd->internal_ecore_evas)
ecore_evas_move_resize(bd->internal_ecore_evas, x, y, bd->client.w, bd->client.h);
else if (!bd->client.e.state.video)
{
ecore_x_window_move_resize(bd->client.win, x, y, bd->client.w, bd->client.h);
ecore_x_window_move_resize(bd->client.lock_win, x, y, bd->client.w, bd->client.h);
}
ecore_evas_move_resize(bd->bg_ecore_evas, 0, 0, bd->w, bd->h);
evas_object_resize(bd->bg_object, bd->w, bd->h);
e_container_shape_resize(bd->shape, bd->w, bd->h);
if (bd->changes.pos)
e_container_shape_move(bd->shape, bd->x + bd->fx.x, bd->y + bd->fx.y);
_e_border_client_move_resize_send(bd);
bd->changes.pos = 0;
bd->changes.size = 0;
rem_change = 1;
}
else if (bd->changes.pos)
{
if (bd->post_job) ecore_idle_enterer_del(bd->post_job);
bd->post_job = ecore_idle_enterer_add(_e_border_post_move_resize_job, bd);
bd->post_move = 1;
e_container_shape_move(bd->shape, bd->x + bd->fx.x, bd->y + bd->fx.y);
_e_border_client_move_resize_send(bd);
bd->changes.pos = 0;
rem_change = 1;
}
if (bd->changes.reset_gravity)
{
GRAV_SET(bd, ECORE_X_GRAVITY_NW);
bd->changes.reset_gravity = 0;
rem_change = 1;
}
if (bd->need_shape_merge)
{
_e_border_shape_input_rectangle_set(bd);
if ((bd->shaped) || (bd->client.shaped))
{
Ecore_X_Window twin, twin2;
int x, y;
twin = ecore_x_window_override_new
(bd->zone->container->scratch_win, 0, 0, bd->w, bd->h);
if (bd->shaped)
ecore_x_window_shape_window_set(twin, bd->bg_win);
else
{
Ecore_X_Rectangle rects[4];
rects[0].x = 0;
rects[0].y = 0;
rects[0].width = bd->w;
rects[0].height = bd->client_inset.t;
rects[1].x = 0;
rects[1].y = bd->client_inset.t;
rects[1].width = bd->client_inset.l;
rects[1].height = bd->h - bd->client_inset.t - bd->client_inset.b;
rects[2].x = bd->w - bd->client_inset.r;
rects[2].y = bd->client_inset.t;
rects[2].width = bd->client_inset.r;
rects[2].height = bd->h - bd->client_inset.t - bd->client_inset.b;
rects[3].x = 0;
rects[3].y = bd->h - bd->client_inset.b;
rects[3].width = bd->w;
rects[3].height = bd->client_inset.b;
ecore_x_window_shape_rectangles_set(twin, rects, 4);
}
twin2 = ecore_x_window_override_new
(bd->zone->container->scratch_win, 0, 0,
bd->w - bd->client_inset.l - bd->client_inset.r,
bd->h - bd->client_inset.t - bd->client_inset.b);
x = 0;
y = 0;
if ((bd->shading) || (bd->shaded))
{
if (bd->shade.dir == E_DIRECTION_UP)
y = bd->h - bd->client_inset.t - bd->client_inset.b - bd->client.h;
else if (bd->shade.dir == E_DIRECTION_LEFT)
x = bd->w - bd->client_inset.l - bd->client_inset.r - bd->client.w;
}
ecore_x_window_shape_window_set_xy(twin2, bd->client.win,
x, y);
ecore_x_window_shape_rectangle_clip(twin2, 0, 0,
bd->w - bd->client_inset.l - bd->client_inset.r,
bd->h - bd->client_inset.t - bd->client_inset.b);
ecore_x_window_shape_window_add_xy(twin, twin2,
bd->client_inset.l,
bd->client_inset.t);
ecore_x_window_free(twin2);
ecore_x_window_shape_window_set(bd->win, twin);
ecore_x_window_free(twin);
}
else
ecore_x_window_shape_mask_set(bd->win, 0);
// bd->need_shape_export = 1;
bd->need_shape_merge = 0;
}
if (bd->need_shape_export)
{
Ecore_X_Rectangle *rects, *orects;
int num;
rects = ecore_x_window_shape_rectangles_get(bd->win, &num);
if (rects)
{
int changed;
changed = 1;
if ((num == bd->shape_rects_num) && (bd->shape_rects))
{
int i;
orects = bd->shape_rects;
changed = 0;
for (i = 0; i < num; i++)
{
if (rects[i].x < 0)
{
rects[i].width -= rects[i].x;
rects[i].x = 0;
}
if ((rects[i].x + (int)rects[i].width) > bd->w)
rects[i].width = rects[i].width - rects[i].x;
if (rects[i].y < 0)
{
rects[i].height -= rects[i].y;
rects[i].y = 0;
}
if ((rects[i].y + (int)rects[i].height) > bd->h)
rects[i].height = rects[i].height - rects[i].y;
if ((orects[i].x != rects[i].x) ||
(orects[i].y != rects[i].y) ||
(orects[i].width != rects[i].width) ||
(orects[i].height != rects[i].height))
{
changed = 1;
break;
}
}
}
if (changed)
{
if (bd->client.shaped)
e_container_shape_solid_rect_set(bd->shape, 0, 0, 0, 0);
else
e_container_shape_solid_rect_set(bd->shape, bd->client_inset.l, bd->client_inset.t, bd->client.w, bd->client.h);
E_FREE(bd->shape_rects);
bd->shape_rects = rects;
bd->shape_rects_num = num;
e_container_shape_rects_set(bd->shape, rects, num);
}
else
free(rects);
}
else
{
E_FREE(bd->shape_rects);
bd->shape_rects = NULL;
bd->shape_rects_num = 0;
e_container_shape_rects_set(bd->shape, NULL, 0);
}
bd->need_shape_export = 0;
}
if ((bd->changes.visible) && (bd->visible) && (bd->new_client))
{
int x, y;
ecore_x_pointer_xy_get(bd->zone->container->win, &x, &y);
if ((!bd->placed) && (!bd->re_manage) &&
(e_config->window_placement_policy == E_WINDOW_PLACEMENT_MANUAL) &&
(!((bd->client.icccm.transient_for != 0) ||
(bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DIALOG))) &&
(!bdmove) && (!bdresize))
{
/* Set this window into moving state */
bd->cur_mouse_action = e_action_find("window_move");
if (bd->cur_mouse_action)
{
if ((!bd->cur_mouse_action->func.end_mouse) &&
(!bd->cur_mouse_action->func.end))
bd->cur_mouse_action = NULL;
if (bd->cur_mouse_action)
{
bd->x = x - (bd->w >> 1);
bd->y = y - (bd->client_inset.t >> 1);
bd->changed = 1;
bd->changes.pos = 1;
_e_border_client_move_resize_send(bd);
}
}
}
_e_border_show(bd);
if (bd->cur_mouse_action)
{
bd->moveinfo.down.x = bd->x + bd->fx.x;
bd->moveinfo.down.y = bd->y + bd->fx.y;
bd->moveinfo.down.w = bd->w;
bd->moveinfo.down.h = bd->h;
bd->mouse.current.mx = x;
bd->mouse.current.my = y;
bd->moveinfo.down.button = 0;
bd->moveinfo.down.mx = x;
bd->moveinfo.down.my = y;
grabbed = 1;
e_object_ref(E_OBJECT(bd->cur_mouse_action));
bd->cur_mouse_action->func.go(E_OBJECT(bd), NULL);
if (e_config->border_raise_on_mouse_action)
e_border_raise(bd);
e_border_focus_set(bd, 1, 1);
}
bd->changes.visible = 0;
rem_change = 1;
}
if (bd->changes.icon)
{
if (bd->desktop)
{
efreet_desktop_free(bd->desktop);
bd->desktop = NULL;
}
if (bd->icon_object)
{
evas_object_del(bd->icon_object);
bd->icon_object = NULL;
}
if (bd->remember && bd->remember->prop.desktop_file)
{
const char *desktop = bd->remember->prop.desktop_file;
bd->desktop = efreet_desktop_get(desktop);
if (!bd->desktop)
bd->desktop = efreet_util_desktop_name_find(desktop);
}
if (!bd->desktop)
{
if ((bd->client.icccm.name) && (bd->client.icccm.class))
bd->desktop = efreet_util_desktop_wm_class_find(bd->client.icccm.name,
bd->client.icccm.class);
}
if (!bd->desktop)
{
/* libreoffice and maybe others match window class
with .desktop file name */
if (bd->client.icccm.class)
{
char buf[128];
snprintf(buf, sizeof(buf), "%s.desktop", bd->client.icccm.class);
bd->desktop = efreet_util_desktop_file_id_find(buf);
}
}
if (!bd->desktop)
{
bd->desktop = e_exec_startup_id_pid_find(bd->client.netwm.startup_id,
bd->client.netwm.pid);
if (bd->desktop) efreet_desktop_ref(bd->desktop);
}
if (!bd->desktop && bd->client.icccm.name)
{
/* this works for most cases as fallback. useful when app is
run from a shell */
bd->desktop = efreet_util_desktop_exec_find(bd->client.icccm.name);
}
if (!bd->desktop && bd->client.icccm.transient_for)
{
E_Border *bd2 = e_border_find_by_client_window(bd->client.icccm.transient_for);
if (bd2 && bd2->desktop)
{
efreet_desktop_ref(bd2->desktop);
bd->desktop = bd2->desktop;
}
}
if (bd->desktop)
{
ecore_x_window_prop_string_set(bd->client.win, E_ATOM_DESKTOP_FILE,
bd->desktop->orig_path);
}
bd->icon_object = e_border_icon_add(bd, bd->bg_evas);
if ((bd->focused) && (bd->icon_object))
edje_object_signal_emit(bd->icon_object, "e,state,focused", "e");
if (bd->bg_object)
{
evas_object_show(bd->icon_object);
edje_object_part_swallow(bd->bg_object, "e.swallow.icon", bd->icon_object);
}
else
evas_object_hide(bd->icon_object);
{
E_Event_Border_Icon_Change *ev;
ev = E_NEW(E_Event_Border_Icon_Change, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_icon_change_event");
ecore_event_add(E_EVENT_BORDER_ICON_CHANGE, ev,
_e_border_event_border_icon_change_free, NULL);
}
bd->changes.icon = 0;
}
bd->new_client = 0;
bd->changed = 0;
bd->changes.stack = 0;
if ((bd->take_focus) || (bd->want_focus))
{
bd->take_focus = 0;
if ((e_config->focus_setting == E_FOCUS_NEW_WINDOW) || (bd->want_focus))
{
bd->want_focus = 0;
e_border_focus_set_with_pointer(bd);
}
else if ((bd->client.netwm.type == ECORE_X_WINDOW_TYPE_DIALOG) ||
(bd->parent && (bd->parent->modal == bd)))
{
if ((e_config->focus_setting == E_FOCUS_NEW_DIALOG) ||
((e_config->focus_setting == E_FOCUS_NEW_DIALOG_IF_OWNER_FOCUSED) &&
(e_border_find_by_client_window(bd->client.icccm.transient_for) ==
e_border_focused_get())))
{
e_border_focus_set_with_pointer(bd);
}
}
else
{
/* focus window by default when it is the only one on desk */
E_Border *bd2 = NULL;
Eina_List *l;
EINA_LIST_FOREACH(focus_stack, l, bd2)
{
if (bd == bd2) continue;
if ((!bd2->iconic) && (bd2->visible) &&
((bd->desk == bd2->desk) || bd2->sticky))
break;
}
if (!bd2)
{
e_border_focus_set_with_pointer(bd);
}
}
}
if (bd->need_maximize)
{
E_Maximize max;
max = bd->maximized;
bd->maximized = E_MAXIMIZE_NONE;
e_border_maximize(bd, max);
bd->need_maximize = 0;
}
if (bd->need_fullscreen)
{
e_border_fullscreen(bd, e_config->fullscreen_policy);
bd->need_fullscreen = 0;
}
if (rem_change)
e_remember_update(bd);
if (send_event) // FIXME: send only if a property changed - above need to
{ // check on that. for now - always send.
event = E_NEW(E_Event_Border_Property, 1);
event->border = bd;
e_object_ref(E_OBJECT(bd));
ecore_event_add(E_EVENT_BORDER_PROPERTY, event, _e_border_event_border_property_free, NULL);
}
_e_border_hook_call(E_BORDER_HOOK_EVAL_END, bd);
}
static void
_e_border_moveinfo_gather(E_Border *bd,
const char *source)
{
if (e_util_glob_match(source, "mouse,*,1")) bd->moveinfo.down.button = 1;
else if (e_util_glob_match(source, "mouse,*,2"))
bd->moveinfo.down.button = 2;
else if (e_util_glob_match(source, "mouse,*,3"))
bd->moveinfo.down.button = 3;
else bd->moveinfo.down.button = 0;
if ((bd->moveinfo.down.button >= 1) && (bd->moveinfo.down.button <= 3))
{
bd->moveinfo.down.mx = bd->mouse.last_down[bd->moveinfo.down.button - 1].mx;
bd->moveinfo.down.my = bd->mouse.last_down[bd->moveinfo.down.button - 1].my;
}
else
{
bd->moveinfo.down.mx = bd->mouse.current.mx;
bd->moveinfo.down.my = bd->mouse.current.my;
}
}
static void
_e_border_resize_handle(E_Border *bd)
{
int x, y, w, h;
int new_x, new_y, new_w, new_h;
int tw, th;
Eina_List *skiplist = NULL;
x = bd->x;
y = bd->y;
w = bd->w;
h = bd->h;
if ((bd->resize_mode == RESIZE_TR) ||
(bd->resize_mode == RESIZE_R) ||
(bd->resize_mode == RESIZE_BR))
{
if ((bd->moveinfo.down.button >= 1) &&
(bd->moveinfo.down.button <= 3))
w = bd->mouse.last_down[bd->moveinfo.down.button - 1].w +
(bd->mouse.current.mx - bd->moveinfo.down.mx);
else
w = bd->moveinfo.down.w + (bd->mouse.current.mx - bd->moveinfo.down.mx);
}
else if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_L) ||
(bd->resize_mode == RESIZE_BL))
{
if ((bd->moveinfo.down.button >= 1) &&
(bd->moveinfo.down.button <= 3))
w = bd->mouse.last_down[bd->moveinfo.down.button - 1].w -
(bd->mouse.current.mx - bd->moveinfo.down.mx);
else
w = bd->moveinfo.down.w - (bd->mouse.current.mx - bd->moveinfo.down.mx);
}
if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_T) ||
(bd->resize_mode == RESIZE_TR))
{
if ((bd->moveinfo.down.button >= 1) &&
(bd->moveinfo.down.button <= 3))
h = bd->mouse.last_down[bd->moveinfo.down.button - 1].h -
(bd->mouse.current.my - bd->moveinfo.down.my);
else
h = bd->moveinfo.down.h - (bd->mouse.current.my - bd->moveinfo.down.my);
}
else if ((bd->resize_mode == RESIZE_BL) ||
(bd->resize_mode == RESIZE_B) ||
(bd->resize_mode == RESIZE_BR))
{
if ((bd->moveinfo.down.button >= 1) &&
(bd->moveinfo.down.button <= 3))
h = bd->mouse.last_down[bd->moveinfo.down.button - 1].h +
(bd->mouse.current.my - bd->moveinfo.down.my);
else
h = bd->moveinfo.down.h + (bd->mouse.current.my - bd->moveinfo.down.my);
}
tw = bd->w;
th = bd->h;
if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_L) ||
(bd->resize_mode == RESIZE_BL))
x += (tw - w);
if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_T) ||
(bd->resize_mode == RESIZE_TR))
y += (th - h);
skiplist = eina_list_append(skiplist, bd);
e_resist_container_border_position(bd->zone->container, skiplist,
bd->x, bd->y, bd->w, bd->h,
x, y, w, h,
&new_x, &new_y, &new_w, &new_h);
eina_list_free(skiplist);
w = new_w;
h = new_h;
e_border_resize_limit(bd, &new_w, &new_h);
if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_L) ||
(bd->resize_mode == RESIZE_BL))
new_x += (w - new_w);
if ((bd->resize_mode == RESIZE_TL) ||
(bd->resize_mode == RESIZE_T) ||
(bd->resize_mode == RESIZE_TR))
new_y += (h - new_h);
e_border_move_resize(bd, new_x, new_y, new_w, new_h);
}
static Eina_Bool
_e_border_shade_animator(void *data)
{
E_Border *bd = data;
double dt, val;
double dur = bd->client.h / e_config->border_shade_speed;
dt = ecore_loop_time_get() - bd->shade.start;
val = dt / dur;
if (val < 0.0) val = 0.0;
else if (val > 1.0)
val = 1.0;
if (e_config->border_shade_transition == E_TRANSITION_SINUSOIDAL)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_SINUSOIDAL, 0.0, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_DECELERATE)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_DECELERATE, 0.0, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_ACCELERATE)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_ACCELERATE, 0.0, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_LINEAR)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_LINEAR, 0.0, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_ACCELERATE_LOTS)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_ACCELERATE_FACTOR, 1.7, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_DECELERATE_LOTS)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_DECELERATE_FACTOR, 1.7, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_SINUSOIDAL_LOTS)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_SINUSOIDAL_FACTOR, 1.7, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_BOUNCE)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_BOUNCE, 1.2, 3.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else if (e_config->border_shade_transition == E_TRANSITION_BOUNCE_LOTS)
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_BOUNCE, 1.2, 5.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
else
{
bd->shade.val =
ecore_animator_pos_map(val, ECORE_POS_MAP_LINEAR, 0.0, 0.0);
if (!bd->shaded) bd->shade.val = 1.0 - bd->shade.val;
}
/* due to M_PI's innacuracy, cos(M_PI/2) != 0.0, so we need this */
if (bd->shade.val < 0.001) bd->shade.val = 0.0;
else if (bd->shade.val > .999)
bd->shade.val = 1.0;
if (bd->shade.dir == E_DIRECTION_UP)
bd->h = bd->client_inset.t + bd->client_inset.b + bd->client.h * bd->shade.val;
else if (bd->shade.dir == E_DIRECTION_DOWN)
{
bd->h = bd->client_inset.t + bd->client_inset.b + bd->client.h * bd->shade.val;
bd->y = bd->shade.y + bd->client.h * (1 - bd->shade.val);
bd->changes.pos = 1;
}
else if (bd->shade.dir == E_DIRECTION_LEFT)
bd->w = bd->client_inset.l + bd->client_inset.r + bd->client.w * bd->shade.val;
else if (bd->shade.dir == E_DIRECTION_RIGHT)
{
bd->w = bd->client_inset.l + bd->client_inset.r + bd->client.w * bd->shade.val;
bd->x = bd->shade.x + bd->client.w * (1 - bd->shade.val);
bd->changes.pos = 1;
}
if ((bd->shaped) || (bd->client.shaped))
{
bd->need_shape_merge = 1;
bd->need_shape_export = 1;
}
if (bd->shaped_input)
{
bd->need_shape_merge = 1;
}
bd->changes.size = 1;
bd->changed = 1;
/* we're done */
if (val == 1)
{
E_Event_Border_Resize *ev;
bd->shading = 0;
bd->shaded = !(bd->shaded);
bd->changes.size = 1;
bd->changes.shaded = 1;
bd->changes.shading = 1;
bd->changed = 1;
bd->shade.anim = NULL;
if (bd->shaded)
edje_object_signal_emit(bd->bg_object, "e,state,shaded", "e");
else
edje_object_signal_emit(bd->bg_object, "e,state,unshaded", "e");
edje_object_message_signal_process(bd->bg_object);
e_border_frame_recalc(bd);
ecore_x_window_gravity_set(bd->client.win, ECORE_X_GRAVITY_NW);
if (bd->client.lock_win) ecore_x_window_gravity_set(bd->client.lock_win, ECORE_X_GRAVITY_NW);
ev = E_NEW(E_Event_Border_Resize, 1);
ev->border = bd;
e_object_ref(E_OBJECT(bd));
// e_object_breadcrumb_add(E_OBJECT(bd), "border_resize_event");
ecore_event_add(E_EVENT_BORDER_RESIZE, ev, _e_border_event_border_resize_free, NULL);
return ECORE_CALLBACK_CANCEL;
}
return ECORE_CALLBACK_RENEW;
}
static void
_e_border_event_border_resize_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Resize *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_resize_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_move_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Move *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_move_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_add_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Add *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_add_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_remove_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Remove *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_remove_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_show_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Show *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_show_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_hide_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Hide *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_hide_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_iconify_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Iconify *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_iconify_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_uniconify_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Uniconify *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_uniconify_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_stick_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Stick *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_stick_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_unstick_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Unstick *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_unstick_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_zone_set_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Zone_Set *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_zone_set_event");
e_object_unref(E_OBJECT(e->border));
e_object_unref(E_OBJECT(e->zone));
E_FREE(e);
}
static void
_e_border_event_border_desk_set_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Desk_Set *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_desk_set_event");
e_object_unref(E_OBJECT(e->border));
e_object_unref(E_OBJECT(e->desk));
E_FREE(e);
}
static void
_e_border_event_border_stack_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Stack *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_raise_event");
e_object_unref(E_OBJECT(e->border));
if (e->stack)
{
// e_object_breadcrumb_del(E_OBJECT(e->above), "border_raise_event.above");
e_object_unref(E_OBJECT(e->stack));
}
E_FREE(e);
}
static void
_e_border_event_border_icon_change_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Icon_Change *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_icon_change_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_urgent_change_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Urgent_Change *e;
e = ev;
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_focus_in_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Focus_In *e;
e = ev;
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_focus_out_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Focus_Out *e;
e = ev;
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_property_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Property *e;
e = ev;
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_fullscreen_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Fullscreen *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_fullscreen_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_event_border_unfullscreen_free(void *data __UNUSED__,
void *ev)
{
E_Event_Border_Unfullscreen *e;
e = ev;
// e_object_breadcrumb_del(E_OBJECT(e->border), "border_unfullscreen_event");
e_object_unref(E_OBJECT(e->border));
E_FREE(e);
}
static void
_e_border_zone_update(E_Border *bd)
{
E_Container *con;
Eina_List *l;
E_Zone *zone;
/* still within old zone - leave it there */
if (E_INTERSECTS(bd->x, bd->y, bd->w, bd->h,
bd->zone->x, bd->zone->y, bd->zone->w, bd->zone->h))
return;
/* find a new zone */
con = bd->zone->container;
EINA_LIST_FOREACH(con->zones, l, zone)
{
if (E_INTERSECTS(bd->x, bd->y, bd->w, bd->h,
zone->x, zone->y, zone->w, zone->h))
{
e_border_zone_set(bd, zone);
return;
}
}
}
static int
_e_border_resize_begin(E_Border *bd)
{
if (!bd->lock_user_stacking)
{
if (e_config->border_raise_on_mouse_action)
e_border_raise(bd);
}
if ((bd->shaded) || (bd->shading) ||
(bd->fullscreen) || (bd->lock_user_size))
return 0;
if (grabbed && !e_grabinput_get(bd->win, 0, bd->win))
{
grabbed = 0;
return 0;
}
if (bd->client.netwm.sync.request)
{
bd->client.netwm.sync.alarm = ecore_x_sync_alarm_new(bd->client.netwm.sync.counter);
bd->client.netwm.sync.serial = 1;
bd->client.netwm.sync.wait = 0;
bd->client.netwm.sync.send_time = ecore_loop_time_get();
}
_e_border_hook_call(E_BORDER_HOOK_RESIZE_BEGIN, bd);
bdresize = bd;
return 1;
}
static int
_e_border_resize_end(E_Border *bd)
{
if (grabbed)
{
e_grabinput_release(bd->win, bd->win);
grabbed = 0;
}
if (bd->client.netwm.sync.alarm)
{
E_Border_Pending_Move_Resize *pnd;
ecore_x_sync_alarm_free(bd->client.netwm.sync.alarm);
bd->client.netwm.sync.alarm = 0;
/* resize to last geometry if sync alarm for it was not yet handled */
if (bd->pending_move_resize)
{
bd->changed = 1;
bd->changes.pos = 1;
bd->changes.size = 1;
_e_border_client_move_resize_send(bd);
}
EINA_LIST_FREE(bd->pending_move_resize, pnd)
E_FREE(pnd);
}
_e_border_hook_call(E_BORDER_HOOK_RESIZE_END, bd);
bdresize = NULL;
/* If this border was maximized, we need to unset Maximized state or
* on restart, E still thinks it's maximized */
if (bd->maximized != E_MAXIMIZE_NONE)
e_hints_window_maximized_set(bd, bd->maximized & E_MAXIMIZE_NONE,
bd->maximized & E_MAXIMIZE_NONE);
return 1;
}
static void
_e_border_resize_update(E_Border *bd)
{
_e_border_hook_call(E_BORDER_HOOK_RESIZE_UPDATE, bd);
}
static int
_e_border_move_begin(E_Border *bd)
{
if (!bd->lock_user_stacking)
{
if (e_config->border_raise_on_mouse_action)
e_border_raise(bd);
}
if ((bd->fullscreen) || (bd->lock_user_location))
return 0;
if (grabbed && !e_grabinput_get(bd->win, 0, bd->win))
{
grabbed = 0;
return 0;
}
#if 0
if (bd->client.netwm.sync.request)
{
bd->client.netwm.sync.alarm = ecore_x_sync_alarm_new(bd->client.netwm.sync.counter);
bd->client.netwm.sync.serial = 0;
bd->client.netwm.sync.wait = 0;
bd->client.netwm.sync.time = ecore_loop_time_get();
}
#endif
_e_border_hook_call(E_BORDER_HOOK_MOVE_BEGIN, bd);
bdmove = bd;
return 1;
}
static int
_e_border_move_end(E_Border *bd)
{
if (grabbed)
{
e_grabinput_release(bd->win, bd->win);
grabbed = 0;
}
#if 0
if (bd->client.netwm.sync.alarm)
{
ecore_x_sync_alarm_free(bd->client.netwm.sync.alarm);
bd->client.netwm.sync.alarm = 0;
}
#endif
_e_border_hook_call(E_BORDER_HOOK_MOVE_END, bd);
bdmove = NULL;
return 1;
}
static void
_e_border_move_update(E_Border *bd)
{
_e_border_hook_call(E_BORDER_HOOK_MOVE_UPDATE, bd);
}
static Eina_Bool
_e_border_cb_ping_poller(void *data)
{
E_Border *bd;
bd = data;
if (bd->ping_ok)
{
if (bd->hung)
{
bd->hung = 0;
edje_object_signal_emit(bd->bg_object, "e,state,unhung", "e");
if (bd->kill_timer)
{
ecore_timer_del(bd->kill_timer);
bd->kill_timer = NULL;
}
}
}
else
{
/* if time between last ping and now is greater
* than half the ping interval... */
if ((ecore_loop_time_get() - bd->ping) >
((e_config->ping_clients_interval *
ecore_poller_poll_interval_get(ECORE_POLLER_CORE)) / 2.0))
{
if (!bd->hung)
{
bd->hung = 1;
edje_object_signal_emit(bd->bg_object, "e,state,hung", "e");
/* FIXME: if below dialog is up - hide it now */
}
if (bd->delete_requested)
{
/* FIXME: pop up dialog saying app is hung - kill client, or pid */
e_border_act_kill_begin(bd);
}
}
}
bd->ping_poller = NULL;
e_border_ping(bd);
return ECORE_CALLBACK_CANCEL;
}
static Eina_Bool
_e_border_cb_kill_timer(void *data)
{
E_Border *bd;
bd = data;
// dont wait until it's hung -
// if (bd->hung)
// {
if (bd->client.netwm.pid > 1)
kill(bd->client.netwm.pid, SIGKILL);
// }
bd->kill_timer = NULL;
return ECORE_CALLBACK_CANCEL;
}
static void
_e_border_pointer_resize_begin(E_Border *bd)
{
switch (bd->resize_mode)
{
case RESIZE_TL:
e_pointer_type_push(bd->pointer, bd, "resize_tl");
break;
case RESIZE_T:
e_pointer_type_push(bd->pointer, bd, "resize_t");
break;
case RESIZE_TR:
e_pointer_type_push(bd->pointer, bd, "resize_tr");
break;
case RESIZE_R:
e_pointer_type_push(bd->pointer, bd, "resize_r");
break;
case RESIZE_BR:
e_pointer_type_push(bd->pointer, bd, "resize_br");
break;
case RESIZE_B:
e_pointer_type_push(bd->pointer, bd, "resize_b");
break;
case RESIZE_BL:
e_pointer_type_push(bd->pointer, bd, "resize_bl");
break;
case RESIZE_L:
e_pointer_type_push(bd->pointer, bd, "resize_l");
break;
}
}
static void
_e_border_pointer_resize_end(E_Border *bd)
{
switch (bd->resize_mode)
{
case RESIZE_TL:
e_pointer_type_pop(bd->pointer, bd, "resize_tl");
break;
case RESIZE_T:
e_pointer_type_pop(bd->pointer, bd, "resize_t");
break;
case RESIZE_TR:
e_pointer_type_pop(bd->pointer, bd, "resize_tr");
break;
case RESIZE_R:
e_pointer_type_pop(bd->pointer, bd, "resize_r");
break;
case RESIZE_BR:
e_pointer_type_pop(bd->pointer, bd, "resize_br");
break;
case RESIZE_B:
e_pointer_type_pop(bd->pointer, bd, "resize_b");
break;
case RESIZE_BL:
e_pointer_type_pop(bd->pointer, bd, "resize_bl");
break;
case RESIZE_L:
e_pointer_type_pop(bd->pointer, bd, "resize_l");
break;
}
}
static void
_e_border_pointer_move_begin(E_Border *bd)
{
e_pointer_type_push(bd->pointer, bd, "move");
}
static void
_e_border_pointer_move_end(E_Border *bd)
{
e_pointer_type_pop(bd->pointer, bd, "move");
}
static Eina_List *_e_border_hooks = NULL;
static int _e_border_hooks_delete = 0;
static int _e_border_hooks_walking = 0;
static void
_e_border_hooks_clean(void)
{
Eina_List *l, *ln;
E_Border_Hook *bh;
EINA_LIST_FOREACH_SAFE(_e_border_hooks, l, ln, bh)
{
if (bh->delete_me)
{
_e_border_hooks = eina_list_remove_list(_e_border_hooks, l);
free(bh);
}
}
}
static void
_e_border_hook_call(E_Border_Hook_Point hookpoint,
void *bd)
{
Eina_List *l;
E_Border_Hook *bh;
_e_border_hooks_walking++;
EINA_LIST_FOREACH(_e_border_hooks, l, bh)
{
if (bh->delete_me) continue;
if (bh->hookpoint == hookpoint) bh->func(bh->data, bd);
}
_e_border_hooks_walking--;
if ((_e_border_hooks_walking == 0) && (_e_border_hooks_delete > 0))
_e_border_hooks_clean();
}
EAPI E_Border_Hook *
e_border_hook_add(E_Border_Hook_Point hookpoint,
void (*func)(void *data,
void *bd),
void *data)
{
E_Border_Hook *bh;
bh = E_NEW(E_Border_Hook, 1);
if (!bh) return NULL;
bh->hookpoint = hookpoint;
bh->func = func;
bh->data = data;
_e_border_hooks = eina_list_append(_e_border_hooks, bh);
return bh;
}
EAPI void
e_border_hook_del(E_Border_Hook *bh)
{
bh->delete_me = 1;
if (_e_border_hooks_walking == 0)
{
_e_border_hooks = eina_list_remove(_e_border_hooks, bh);
free(bh);
}
else
_e_border_hooks_delete++;
}
EAPI void
e_border_focus_track_freeze(void)
{
focus_track_frozen++;
}
EAPI void
e_border_focus_track_thaw(void)
{
focus_track_frozen--;
}
static E_Border *
_e_border_under_pointer_helper(E_Desk *desk, E_Border *exclude, int x, int y)
{
E_Border *bd = NULL, *cbd;
Eina_List *l;
EINA_LIST_FOREACH(e_border_raise_stack_get(), l, cbd)
{
if (!cbd) continue;
/* If a border was specified which should be excluded from the list
* (because it will be closed shortly for example), skip */
if ((exclude) && (cbd == exclude)) continue;
if ((desk) && (cbd->desk != desk)) continue;
if (!E_INSIDE(x, y, cbd->x, cbd->y, cbd->w, cbd->h))
continue;
/* If the layer is higher, the position of the window is higher
* (always on top vs always below) */
if (!bd || (cbd->layer > bd->layer))
bd = cbd;
}
return bd;
}
EAPI E_Border *
e_border_under_pointer_get(E_Desk *desk,
E_Border *exclude)
{
int x, y;
/* We need to ensure that we can get the container window for the
* zone of either the given desk or the desk of the excluded
* window, so return if neither is given */
if (desk)
ecore_x_pointer_xy_get(desk->zone->container->win, &x, &y);
else if (exclude)
ecore_x_pointer_xy_get(exclude->desk->zone->container->win, &x, &y);
else
return NULL;
return _e_border_under_pointer_helper(desk, exclude, x, y);
}
static Eina_Bool
_e_border_pointer_warp_to_center_timer(void *data __UNUSED__)
{
if (warp_to)
{
int x, y;
double spd;
ecore_x_pointer_xy_get(warp_to_win, &x, &y);
/* move hasn't happened yet */
if ((x == warp_x[1]) && (y == warp_y[1])) return EINA_TRUE;
if ((abs(x - warp_x[0]) > 5) || (abs(y - warp_y[0]) > 5))
{
/* User moved the mouse, so stop warping */
warp_to = 0;
goto cleanup;
}
/* We just use the same warp speed as configured
* for the windowlist */
spd = e_config->winlist_warp_speed;
warp_x[1] = x = warp_x[0];
warp_y[1] = y = warp_y[0];
warp_x[0] = (x * (1.0 - spd)) + (warp_to_x * spd);
warp_y[0] = (y * (1.0 - spd)) + (warp_to_y * spd);
if ((warp_x[0] == x) && (warp_y[0] == y))
{
warp_x[0] = warp_to_x;
warp_y[0] = warp_to_y;
warp_to = 0;
goto cleanup;
}
ecore_x_pointer_warp(warp_to_win, warp_x[0], warp_y[0]);
return ECORE_CALLBACK_RENEW;
}
cleanup:
ecore_timer_del(warp_timer);
warp_timer = NULL;
e_border_focus_lock_set(EINA_FALSE);
e_focus_event_mouse_in(warp_timer_border);
warp_timer_border = NULL;
return ECORE_CALLBACK_CANCEL;
}
EAPI int
e_border_pointer_warp_to_center(E_Border *bd)
{
int x, y;
E_Border *cbd = NULL;
/* Do not slide pointer when disabled (probably breaks focus
* on sloppy/mouse focus but requested by users). */
if (!e_config->pointer_slide) return 0;
/* Only warp the pointer if it is not already in the area of
* the given border */
ecore_x_pointer_xy_get(bd->zone->container->win, &x, &y);
if ((x >= bd->x) && (x <= (bd->x + bd->w)) &&
(y >= bd->y) && (y <= (bd->y + bd->h)))
{
cbd = _e_border_under_pointer_helper(bd->desk, bd, x, y);
if (cbd == bd) return 0;
}
warp_to_x = bd->x + (bd->w / 2);
if (warp_to_x < (bd->zone->x + 1))
warp_to_x = bd->zone->x + ((bd->x + bd->w - bd->zone->x) / 2);
else if (warp_to_x > (bd->zone->x + bd->zone->w))
warp_to_x = (bd->zone->x + bd->zone->w + bd->x) / 2;
warp_to_y = bd->y + (bd->h / 2);
if (warp_to_y < (bd->zone->y + 1))
warp_to_y = bd->zone->y + ((bd->y + bd->h - bd->zone->y) / 2);
else if (warp_to_y > (bd->zone->y + bd->zone->h))
warp_to_y = (bd->zone->y + bd->zone->h + bd->y) / 2;
/* TODO: handle case where another border is over the exact center,
* find a place where the requested border is not overlapped?
*
if (!cbd) cbd = _e_border_under_pointer_helper(bd->desk, bd, x, y);
if (cbd != bd)
{
}
*/
warp_to = 1;
warp_to_win = bd->zone->container->win;
ecore_x_pointer_xy_get(bd->zone->container->win, &warp_x[0], &warp_y[0]);
if (warp_timer) ecore_timer_del(warp_timer);
warp_timer = ecore_timer_add(0.01, _e_border_pointer_warp_to_center_timer, bd);
warp_timer_border = bd;
e_border_focus_lock_set(EINA_TRUE);
return 1;
}
EAPI void
e_border_comp_hidden_set(E_Border *bd,
Eina_Bool hidden)
{
E_Border *tmp;
Eina_List *l;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
{
if (hidden)
ecore_x_window_hide(tmp->win);
else
ecore_x_window_show(tmp->win);
}
if (bd->comp_hidden == hidden) return;
bd->comp_hidden = hidden;
if ((bd->comp_hidden) || (bd->tmp_input_hidden > 0))
{
ecore_x_composite_window_events_disable(bd->win);
ecore_x_window_ignore_set(bd->win, EINA_TRUE);
}
else
{
_e_border_shape_input_rectangle_set(bd);
ecore_x_window_ignore_set(bd->win, EINA_FALSE);
}
}
EAPI void
e_border_tmp_input_hidden_push(E_Border *bd)
{
E_Border *tmp;
Eina_List *l;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
e_border_tmp_input_hidden_push(tmp);
bd->tmp_input_hidden++;
if (bd->tmp_input_hidden != 1) return;
if ((bd->comp_hidden) || (bd->tmp_input_hidden > 0))
{
ecore_x_composite_window_events_disable(bd->win);
ecore_x_window_ignore_set(bd->win, EINA_TRUE);
}
else
{
_e_border_shape_input_rectangle_set(bd);
ecore_x_window_ignore_set(bd->win, EINA_FALSE);
}
}
EAPI void
e_border_tmp_input_hidden_pop(E_Border *bd)
{
E_Border *tmp;
Eina_List *l;
E_OBJECT_CHECK(bd);
E_OBJECT_TYPE_CHECK(bd, E_BORDER_TYPE);
EINA_LIST_FOREACH(bd->client.e.state.video_child, l, tmp)
e_border_tmp_input_hidden_pop(tmp);
bd->tmp_input_hidden--;
if (bd->tmp_input_hidden != 0) return;
if ((bd->comp_hidden) || (bd->tmp_input_hidden > 0))
{
ecore_x_composite_window_events_disable(bd->win);
ecore_x_window_ignore_set(bd->win, EINA_TRUE);
}
else
{
_e_border_shape_input_rectangle_set(bd);
ecore_x_window_ignore_set(bd->win, EINA_FALSE);
}
}
EAPI void
e_border_activate(E_Border *bd, Eina_Bool just_do_it)
{
if ((e_config->focus_setting == E_FOCUS_NEW_WINDOW) ||
((bd->parent) &&
((e_config->focus_setting == E_FOCUS_NEW_DIALOG) ||
((bd->parent->focused) &&
(e_config->focus_setting == E_FOCUS_NEW_DIALOG_IF_OWNER_FOCUSED)))) ||
(just_do_it))
{
if (bd->iconic)
{
if (e_config->clientlist_warp_to_iconified_desktop == 1)
e_desk_show(bd->desk);
if (!bd->lock_user_iconify)
e_border_uniconify(bd);
}
if ((!bd->iconic) && (!bd->sticky))
e_desk_show(bd->desk);
if (!bd->lock_user_stacking) e_border_raise(bd);
if (!bd->lock_focus_out)
{
/* XXX ooffice does send this request for
config dialogs when the main window gets focus.
causing the pointer to jump back and forth. */
if ((e_config->focus_policy != E_FOCUS_CLICK) && (!bd->new_client) &&
!(bd->client.icccm.name && !strcmp(bd->client.icccm.name, "VCLSalFrame")))
ecore_x_pointer_warp(bd->zone->container->win,
bd->x + (bd->w / 2), bd->y + (bd->h / 2));
e_border_focus_set(bd, 1, 1);
}
}
}
/*vim:ts=8 sw=3 sts=3 expandtab cino=>5n-3f0^-2{2(0W1st0*/
| 32.284331 | 158 | 0.52994 | [
"geometry",
"object",
"shape"
] |
4e0867654305f4996c763e3bcbabc0afb46a9933 | 9,694 | h | C | cpp/daal/src/algorithms/svm/oneapi/svm_train_result_oneapi.h | KulikovNikita/daal | 117adbffd9a86089a481b2664a89c687e654a795 | [
"Apache-2.0"
] | null | null | null | cpp/daal/src/algorithms/svm/oneapi/svm_train_result_oneapi.h | KulikovNikita/daal | 117adbffd9a86089a481b2664a89c687e654a795 | [
"Apache-2.0"
] | null | null | null | cpp/daal/src/algorithms/svm/oneapi/svm_train_result_oneapi.h | KulikovNikita/daal | 117adbffd9a86089a481b2664a89c687e654a795 | [
"Apache-2.0"
] | null | null | null | /* file: svm_train_result_oneapi.h */
/*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// SVM save result structure implementation
//--
*/
#ifndef __SVM_TRAIN_RESULT_ONEAPI_H__
#define __SVM_TRAIN_RESULT_ONEAPI_H__
#include "src/services/service_utils.h"
#include "src/algorithms/svm/oneapi/svm_helper_oneapi.h"
#include "src/sycl/reducer.h"
namespace daal
{
namespace algorithms
{
namespace svm
{
namespace training
{
namespace internal
{
using namespace daal::services::internal::sycl::math;
template <typename algorithmFPType>
class SaveResultModel
{
using Helper = utils::internal::HelperSVM<algorithmFPType>;
public:
SaveResultModel(services::internal::Buffer<algorithmFPType> & alphaBuff, const services::internal::Buffer<algorithmFPType> & fBuff,
const services::internal::Buffer<algorithmFPType> & yBuff, const algorithmFPType C, const size_t nVectors)
: _yBuff(yBuff), _coeffBuff(alphaBuff), _fBuff(fBuff), _C(C), _nVectors(nVectors)
{}
services::Status init()
{
services::Status status;
auto & context = services::internal::getDefaultContext();
_tmpValues = context.allocate(TypeIds::id<algorithmFPType>(), _nVectors, status);
DAAL_CHECK_STATUS_VAR(status);
_mask = context.allocate(TypeIds::id<uint32_t>(), _nVectors, status);
DAAL_CHECK_STATUS_VAR(status);
DAAL_CHECK_STATUS(status, Helper::computeDualCoeffs(_yBuff, _coeffBuff, _nVectors));
return status;
}
services::Status setResultsToModel(const NumericTablePtr & xTable, Model & model) const
{
DAAL_ITTNOTIFY_SCOPED_TASK(setResultsToModel);
services::Status status;
model.setNFeatures(xTable->getNumberOfColumns());
size_t nSV;
DAAL_CHECK_STATUS(status, setSVCoefficients(nSV, model));
DAAL_CHECK_STATUS(status, setSVIndices(nSV, model));
DAAL_CHECK_STATUS(status, setSVDense(model, xTable, nSV));
/* Calculate bias and write it into model */
algorithmFPType bias;
DAAL_CHECK_STATUS(status, calculateBias(_C, bias));
model.setBias(double(bias));
return status;
}
protected:
services::Status setSVCoefficients(size_t & nSV, Model & model) const
{
services::Status status;
auto & context = services::internal::getDefaultContext();
auto tmpValuesBuff = _tmpValues.get<algorithmFPType>();
auto maskBuff = _mask.get<uint32_t>();
DAAL_CHECK_STATUS(status, Helper::checkNonZeroBinary(_coeffBuff, maskBuff, _nVectors));
nSV = 0;
DAAL_CHECK_STATUS(status, Partition::flagged(maskBuff, _coeffBuff, tmpValuesBuff, _nVectors, nSV));
NumericTablePtr svCoeffTable = model.getClassificationCoefficients();
DAAL_CHECK_STATUS(status, svCoeffTable->resize(nSV));
if (nSV == 0) return status;
BlockDescriptor<algorithmFPType> svCoeffBlock;
DAAL_CHECK_STATUS(status, svCoeffTable->getBlockOfRows(0, nSV, ReadWriteMode::writeOnly, svCoeffBlock));
auto svCoeffBuff = svCoeffBlock.getBuffer();
context.copy(svCoeffBuff, 0, tmpValuesBuff, 0, nSV, status);
DAAL_CHECK_STATUS_VAR(status);
DAAL_CHECK_STATUS(status, svCoeffTable->releaseBlockOfRows(svCoeffBlock));
return status;
}
services::Status setSVIndices(size_t nSV, Model & model) const
{
auto & context = services::internal::getDefaultContext();
NumericTablePtr svIndicesTable = model.getSupportIndices();
services::Status status;
DAAL_CHECK_STATUS(status, svIndicesTable->resize(nSV));
if (nSV == 0) return status;
BlockDescriptor<int> svIndicesBlock;
DAAL_CHECK_STATUS(status, svIndicesTable->getBlockOfRows(0, nSV, ReadWriteMode::writeOnly, svIndicesBlock));
auto svIndices = svIndicesBlock.getBuffer();
auto buffIndex = context.allocate(TypeIds::id<int>(), nSV, status);
DAAL_CHECK_STATUS_VAR(status);
auto rangeIndex = context.allocate(TypeIds::id<int>(), _nVectors, status);
DAAL_CHECK_STATUS_VAR(status);
DAAL_CHECK_STATUS(status, Helper::makeRange(rangeIndex, _nVectors));
size_t nSVCheck = 0;
DAAL_CHECK_STATUS(status, Partition::flagged(_mask, rangeIndex, buffIndex, _nVectors, nSVCheck));
DAAL_ASSERT(nSVCheck == nSV);
context.copy(svIndices, 0, buffIndex, 0, nSV, status);
DAAL_CHECK_STATUS_VAR(status);
DAAL_CHECK_STATUS(status, svIndicesTable->releaseBlockOfRows(svIndicesBlock));
return status;
}
services::Status setSVDense(Model & model, const NumericTablePtr & xTable, size_t nSV) const
{
services::Status status;
const size_t nFeatures = xTable->getNumberOfColumns();
NumericTablePtr svTable = model.getSupportVectors();
DAAL_CHECK_STATUS(status, svTable->resize(nSV));
if (nSV == 0) return status;
BlockDescriptor<algorithmFPType> svBlock;
DAAL_CHECK_STATUS(status, svTable->getBlockOfRows(0, nSV, ReadWriteMode::writeOnly, svBlock));
auto svBuff = svBlock.getBuffer();
NumericTablePtr svIndicesTable = model.getSupportIndices();
BlockDescriptor<int> svIndicesBlock;
DAAL_CHECK_STATUS(status, svIndicesTable->getBlockOfRows(0, nSV, ReadWriteMode::readOnly, svIndicesBlock));
auto svIndicesBuff = svIndicesBlock.getBuffer();
BlockDescriptor<algorithmFPType> xBlock;
DAAL_CHECK_STATUS(status, xTable->getBlockOfRows(0, _nVectors, ReadWriteMode::readOnly, xBlock));
auto xBuff = xBlock.getBuffer();
DAAL_CHECK_STATUS(status, Helper::copyDataByIndices(xBuff, svIndicesBuff, svBuff, nSV, nFeatures));
DAAL_CHECK_STATUS(status, svTable->releaseBlockOfRows(svBlock));
DAAL_CHECK_STATUS(status, svIndicesTable->releaseBlockOfRows(svIndicesBlock));
return status;
}
services::Status calculateBias(const algorithmFPType C, algorithmFPType & bias) const
{
services::Status status;
auto tmpValuesBuff = _tmpValues.get<algorithmFPType>();
auto maskBuff = _mask.get<uint32_t>();
/* free SV: (0 < alpha < C)*/
DAAL_CHECK_STATUS(status, Helper::checkBorder(_coeffBuff, maskBuff, C, _nVectors));
size_t nFree = 0;
DAAL_CHECK_STATUS(status, Partition::flagged(maskBuff, _fBuff, tmpValuesBuff, _nVectors, nFree));
if (nFree > 0)
{
auto reduceRes = Reducer::reduce(Reducer::BinaryOp::SUM, Layout::RowMajor, tmpValuesBuff, 1, nFree, status);
DAAL_CHECK_STATUS_VAR(status);
UniversalBuffer sumU = reduceRes.reduceRes;
auto sumHost = sumU.get<algorithmFPType>().toHost(data_management::readOnly, status);
DAAL_CHECK_STATUS_VAR(status);
bias = -*sumHost / algorithmFPType(nFree);
}
else
{
algorithmFPType ub = -MaxVal<algorithmFPType>::get();
algorithmFPType lb = MaxVal<algorithmFPType>::get();
{
DAAL_CHECK_STATUS(status, Helper::checkUpper(_yBuff, _coeffBuff, maskBuff, C, _nVectors));
size_t nUpper = 0;
DAAL_CHECK_STATUS(status, Partition::flagged(maskBuff, _fBuff, tmpValuesBuff, _nVectors, nUpper));
auto resultOp = Reducer::reduce(Reducer::BinaryOp::MIN, Layout::RowMajor, tmpValuesBuff, 1, nUpper, status);
DAAL_CHECK_STATUS_VAR(status);
UniversalBuffer minBuff = resultOp.reduceRes;
auto minHost = minBuff.get<algorithmFPType>().toHost(data_management::readOnly, status);
DAAL_CHECK_STATUS_VAR(status);
ub = *minHost;
}
{
DAAL_CHECK_STATUS(status, Helper::checkLower(_yBuff, _coeffBuff, maskBuff, C, _nVectors));
size_t nLower = 0;
DAAL_CHECK_STATUS(status, Partition::flagged(maskBuff, _fBuff, tmpValuesBuff, _nVectors, nLower));
auto resultOp = Reducer::reduce(Reducer::BinaryOp::MAX, Layout::RowMajor, tmpValuesBuff, 1, nLower, status);
DAAL_CHECK_STATUS_VAR(status);
UniversalBuffer maxBuff = resultOp.reduceRes;
auto maxHost = maxBuff.get<algorithmFPType>().toHost(data_management::readOnly, status);
DAAL_CHECK_STATUS_VAR(status);
lb = *maxHost;
}
bias = -0.5 * (ub + lb);
}
return status;
}
private:
services::internal::Buffer<algorithmFPType> _yBuff;
services::internal::Buffer<algorithmFPType> _fBuff;
services::internal::Buffer<algorithmFPType> _coeffBuff;
UniversalBuffer _tmpValues;
UniversalBuffer _mask;
const algorithmFPType _C;
const size_t _nVectors;
};
} // namespace internal
} // namespace training
} // namespace svm
} // namespace algorithms
} // namespace daal
#endif
| 38.931727 | 135 | 0.665051 | [
"model"
] |
4e0951e3903a54f57ed20de991e9b320b225d3ad | 8,594 | c | C | syslibs/ksapi/source/getVar.c | fransvanderlek/acplt-rte | 8c664d247e4a0c9291b97aafc930c05341f3b048 | [
"Apache-2.0"
] | 18 | 2015-12-07T15:15:53.000Z | 2021-10-07T04:09:36.000Z | syslibs/ksapi/source/getVar.c | fransvanderlek/acplt-rte | 8c664d247e4a0c9291b97aafc930c05341f3b048 | [
"Apache-2.0"
] | 41 | 2015-12-08T13:31:41.000Z | 2022-01-31T16:32:14.000Z | syslibs/ksapi/source/getVar.c | fransvanderlek/acplt-rte | 8c664d247e4a0c9291b97aafc930c05341f3b048 | [
"Apache-2.0"
] | 12 | 2015-06-11T13:09:41.000Z | 2019-02-07T13:33:37.000Z |
/******************************************************************************
*
* FILE
* ----
* getVar.c
*
* History
* -------
* 2013-05-14 File created
*
*******************************************************************************
*
* This file is generated by the 'acplt_builder' command
*
******************************************************************************/
#ifndef OV_COMPILE_LIBRARY_ksapi
#define OV_COMPILE_LIBRARY_ksapi
#endif
#include "ksapi.h"
#include "ov_macros.h"
#include "ksapi_commonFuncs.h"
#include "ks_logfile.h"
#include "ksbase_helper.h"
void ksapi_getVar_callback(const OV_INSTPTR_ov_domain this, const OV_INSTPTR_ov_domain that);
OV_DLLFNCEXPORT OV_RESULT ksapi_getVar_constructor(
OV_INSTPTR_ov_object pobj
) {
/*
* local variables
*/
OV_RESULT result;
/* do what the base class does first */
result = ksapi_variableOperation_constructor(pobj);
if(Ov_Fail(result))
return result;
/* do what */
return OV_ERR_OK;
}
OV_DLLFNCEXPORT void ksapi_getVar_destructor(
OV_INSTPTR_ov_object pobj
) {
/* destroy object */
ksapi_variableOperation_destructor(pobj);
return;
}
OV_DLLFNCEXPORT void ksapi_getVar_startup(
OV_INSTPTR_ov_object pobj
) {
/* do what the base class does first */
ksapi_variableOperation_startup(pobj);
/* do what */
return;
}
OV_DLLFNCEXPORT void ksapi_getVar_shutdown(
OV_INSTPTR_ov_object pobj
) {
/* do what */
/* set the object's state to "shut down" */
ksapi_KSApiCommon_shutdown(pobj);
return;
}
OV_DLLFNCEXPORT void ksapi_getVar_submit(
OV_INSTPTR_ksapi_KSApiCommon pobj
) {
OV_INSTPTR_ksapi_getVar pthis = Ov_StaticPtrCast(ksapi_getVar, pobj);
OV_INSTPTR_ksbase_ClientBase pClient = NULL;
OV_VTBLPTR_ksbase_ClientBase pVtblClient = NULL;
OV_INSTPTR_ksapi_Variable pCurrVar = NULL;
OV_RESULT result;
OV_STRING* varPaths = NULL;
OV_UINT numberOfItems = 1;
result = ksapi_KSApiCommon_prepareSubmit(pobj, &pClient, &pVtblClient);
if(Ov_Fail(result))
return;
varPaths = Ov_HeapMalloc(numberOfItems * sizeof(OV_STRING));
if(!varPaths)
{
pthis->v_status = KSAPI_COMMON_INTERNALERROR;
pthis->v_result = OV_ERR_HEAPOUTOFMEMORY;
return;
}
if(pthis->v_path)
{
varPaths[0] = pthis->v_path; /* see comment below */
}
else
{
KS_logfile_error(("%s: submit: own Variable has empty path", pobj->v_identifier));
pthis->v_status = KSAPI_COMMON_INTERNALERROR;
pthis->v_result = result;
Ov_HeapFree(varPaths);
return;
}
/* iterate over variable objects in containment and linked ones and add them to the package */
Ov_ForEachChildEx(ov_containment, pthis, pCurrVar, ksapi_Variable)
{
if(!pCurrVar->v_order)
{ /* variable not processed yet */
numberOfItems++;
varPaths = Ov_HeapRealloc(varPaths, numberOfItems * sizeof(OV_STRING));
if(!varPaths)
{
pthis->v_status = KSAPI_COMMON_INTERNALERROR;
pthis->v_result = OV_ERR_HEAPOUTOFMEMORY;
return;
}
if(pCurrVar->v_path)
{
varPaths[numberOfItems-1] = pCurrVar->v_path; /* the string will not be changed, so we do not need to copy it */
pCurrVar->v_order = numberOfItems;
}
else
{
KS_logfile_error(("%s: submit: Variable %s has empty path", pobj->v_identifier, pCurrVar->v_identifier));
pthis->v_status = KSAPI_COMMON_INTERNALERROR;
pthis->v_result = result;
Ov_HeapFree(varPaths);
return;
}
}
}
Ov_ForEachChild(ksapi_operationToVariable, pthis, pCurrVar)
{
if(!pCurrVar->v_order)
{ /* variable not processed yet */
numberOfItems++;
varPaths = Ov_HeapRealloc(varPaths, numberOfItems * sizeof(OV_STRING));
if(!varPaths)
{
pthis->v_status = KSAPI_COMMON_INTERNALERROR;
pthis->v_result = OV_ERR_HEAPOUTOFMEMORY;
return;
}
if(pCurrVar->v_path)
{
varPaths[numberOfItems-1] = pCurrVar->v_path; /* the string will not be changed, so we do not need to copy it */
pCurrVar->v_order = numberOfItems;
}
else
{
KS_logfile_error(("%s: submit: Variable %s has empty path", pobj->v_identifier, pCurrVar->v_identifier));
pthis->v_status = KSAPI_COMMON_INTERNALERROR;
pthis->v_result = result;
Ov_HeapFree(varPaths);
return;
}
}
}
/* do the actual submit */
pVtblClient->m_requestGetVar(pClient, NULL, numberOfItems, varPaths, (OV_INSTPTR_ov_domain) pthis,
&ksapi_getVar_callback);
if(!(pClient->v_state & KSBASE_CLST_ERROR))
pthis->v_status = KSAPI_COMMON_WAITINGFORANSWER;
else
pthis->v_status = KSAPI_COMMON_INTERNALERROR;
Ov_HeapFree(varPaths);
return;
}
OV_DLLFNCEXPORT void ksapi_getVar_setandsubmit(
OV_INSTPTR_ksapi_getVar pobj,
OV_STRING serverHost,
OV_STRING serverName,
OV_STRING path
) {
OV_RESULT result;
result = ksapi_KSApiCommon_genSetForSubmit(Ov_StaticPtrCast(ksapi_KSApiCommon, pobj), serverHost, serverName, path);
if(Ov_Fail(result))
return;
ksapi_getVar_submit(Ov_StaticPtrCast(ksapi_KSApiCommon, pobj));
return;
}
void ksapi_getVar_callback(const OV_INSTPTR_ov_domain this, const OV_INSTPTR_ov_domain that)
{
OV_INSTPTR_ksapi_getVar thisGV = Ov_StaticPtrCast(ksapi_getVar, this);
OV_INSTPTR_ksbase_ClientBase pClient = Ov_StaticPtrCast(ksbase_ClientBase, that);
OV_INSTPTR_ksapi_Variable pCurrVar = NULL;
OV_VTBLPTR_ksbase_ClientBase pVtblClient = NULL;
OV_UINT itemsLength;
OV_GETVAR_ITEM* itemsVals = NULL;
OV_RESULT result;
if(!this || !that)
{
KS_logfile_error(("callback issued with NULL pointers. aborting."));
return;
}
Ov_GetVTablePtr(ksbase_ClientBase, pVtblClient, pClient);
if(!pVtblClient)
{
KS_logfile_error(("%s callback: could not determine Vtable of Client %s. aborting",
this->v_identifier, that->v_identifier));
thisGV->v_status = KSAPI_COMMON_INTERNALERROR;
thisGV->v_result = OV_ERR_BADOBJTYPE;
return;
}
ov_memstack_lock();
result = pVtblClient->m_processGetVar(pClient, NULL, (OV_RESULT*) &(thisGV->v_result), &itemsLength, &itemsVals);
if(Ov_Fail(result))
{
thisGV->v_status = KSAPI_COMMON_INTERNALERROR;
thisGV->v_result = result;
ov_memstack_unlock();
return;
}
if(Ov_Fail(thisGV->v_result))
{
thisGV->v_status = KSAPI_COMMON_EXTERNALERROR;
ov_memstack_unlock();
return;
}
thisGV->v_status = KSAPI_COMMON_REQUESTCOMPLETED;
thisGV->v_varRes = itemsVals[0].result;
if(Ov_OK(thisGV->v_varRes))
{
result = Ov_SetAnyValue(&(thisGV->v_varValue), &(itemsVals[0].var_current_props));
if(Ov_Fail(thisGV->v_result))
{
thisGV->v_status = KSAPI_COMMON_EXTERNALERROR;
ov_memstack_unlock();
return;
}
}
/* iterate over variable objects in containment and linked ones and fill in the results */
Ov_ForEachChildEx(ov_containment, thisGV, pCurrVar, ksapi_Variable)
{
if(pCurrVar->v_order)
{
if(pCurrVar->v_order <= itemsLength)
{
pCurrVar->v_varRes = itemsVals[(pCurrVar->v_order-1)].result;
if(Ov_OK(pCurrVar->v_varRes))
{
result = Ov_SetAnyValue(&(pCurrVar->v_varValue), &(itemsVals[(pCurrVar->v_order)-1].var_current_props));
pCurrVar->v_order = 0; /* reset order to be processed again next time */
if(Ov_Fail(result))
{
thisGV->v_status = KSAPI_COMMON_INTERNALERROR;
thisGV->v_result = result;
ov_memstack_unlock();
return;
}
}
pCurrVar->v_order = 0; /* reset order to be processed again next time */
}
else
{
pCurrVar->v_varRes = OV_ERR_BADPLACEMENT;
}
}
}
Ov_ForEachChild(ksapi_operationToVariable, thisGV, pCurrVar)
{
if(pCurrVar->v_order)
{
if(pCurrVar->v_order <= itemsLength)
{
pCurrVar->v_varRes = itemsVals[(pCurrVar->v_order)-1].result;
if(Ov_OK(pCurrVar->v_varRes))
{
result = Ov_SetAnyValue(&(pCurrVar->v_varValue), &(itemsVals[(pCurrVar->v_order)-1].var_current_props));
pCurrVar->v_order = 0; /* reset order to be processed again next time */
if(Ov_Fail(result))
{
thisGV->v_status = KSAPI_COMMON_INTERNALERROR;
thisGV->v_result = result;
ov_memstack_unlock();
return;
}
}
pCurrVar->v_order = 0; /* reset order to be processed again next time */
}
else
{
pCurrVar->v_varRes = OV_ERR_BADPLACEMENT;
}
}
}
ov_memstack_unlock();
return;
}
| 26.443077 | 118 | 0.662555 | [
"object"
] |
4e09638f708a7ebd8d57c25f15e5cc29c2ba47db | 13,984 | h | C | ns-allinone-3.22/ns-3.22/src/lte/model/lte-spectrum-phy.h | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | null | null | null | ns-allinone-3.22/ns-3.22/src/lte/model/lte-spectrum-phy.h | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | null | null | null | ns-allinone-3.22/ns-3.22/src/lte/model/lte-spectrum-phy.h | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | 2 | 2018-06-06T14:10:23.000Z | 2020-04-07T17:20:55.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 CTTC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Nicola Baldo <nbaldo@cttc.es>
* Giuseppe Piro <g.piro@poliba.it>
* Modified by: Marco Miozzo <mmiozzo@cttc.es> (introduce physical error model)
*/
#ifndef LTE_SPECTRUM_PHY_H
#define LTE_SPECTRUM_PHY_H
#include <ns3/event-id.h>
#include <ns3/spectrum-value.h>
#include <ns3/mobility-model.h>
#include <ns3/packet.h>
#include <ns3/nstime.h>
#include <ns3/net-device.h>
#include <ns3/spectrum-phy.h>
#include <ns3/spectrum-channel.h>
#include <ns3/spectrum-interference.h>
#include <ns3/data-rate.h>
#include <ns3/generic-phy.h>
#include <ns3/packet-burst.h>
#include <ns3/lte-interference.h>
#include "ns3/random-variable-stream.h"
#include <map>
#include <ns3/ff-mac-common.h>
#include <ns3/lte-harq-phy.h>
#include <ns3/lte-common.h>
namespace ns3 {
struct TbId_t
{
uint16_t m_rnti;
uint8_t m_layer;
public:
TbId_t ();
TbId_t (const uint16_t a, const uint8_t b);
friend bool operator == (const TbId_t &a, const TbId_t &b);
friend bool operator < (const TbId_t &a, const TbId_t &b);
};
struct tbInfo_t
{
uint8_t ndi;
uint16_t size;
uint8_t mcs;
std::vector<int> rbBitmap;
uint8_t harqProcessId;
uint8_t rv;
double mi;
bool downlink;
bool corrupt;
bool harqFeedbackSent;
};
typedef std::map<TbId_t, tbInfo_t> expectedTbs_t;
class LteNetDevice;
class AntennaModel;
class LteControlMessage;
struct LteSpectrumSignalParametersDataFrame;
struct LteSpectrumSignalParametersDlCtrlFrame;
struct LteSpectrumSignalParametersUlSrsFrame;
/**
* this method is invoked by the LteSpectrumPhy to notify the PHY that the
* transmission of a given packet has been completed.
*
* @param packet the Packet whose TX has been completed.
*/
typedef Callback< void, Ptr<const Packet> > LtePhyTxEndCallback;
/**
* This method is used by the LteSpectrumPhy to notify the PHY that a
* previously started RX attempt has terminated without success
*/
typedef Callback< void > LtePhyRxDataEndErrorCallback;
/**
* This method is used by the LteSpectrumPhy to notify the PHY that a
* previously started RX attempt has been successfully completed.
*
* @param packet the received Packet
*/
typedef Callback< void, Ptr<Packet> > LtePhyRxDataEndOkCallback;
/**
* This method is used by the LteSpectrumPhy to notify the PHY that a
* previously started RX of a control frame attempt has been
* successfully completed.
*
* @param packet the received Packet
*/
typedef Callback< void, std::list<Ptr<LteControlMessage> > > LtePhyRxCtrlEndOkCallback;
/**
* This method is used by the LteSpectrumPhy to notify the PHY that a
* previously started RX of a control frame attempt has terminated
* without success.
*/
typedef Callback< void > LtePhyRxCtrlEndErrorCallback;
/**
* This method is used by the LteSpectrumPhy to notify the UE PHY that a
* PSS has been received
*/
typedef Callback< void, uint16_t, Ptr<SpectrumValue> > LtePhyRxPssCallback;
/**
* This method is used by the LteSpectrumPhy to notify the PHY about
* the status of a certain DL HARQ process
*/
typedef Callback< void, DlInfoListElement_s > LtePhyDlHarqFeedbackCallback;
/**
* This method is used by the LteSpectrumPhy to notify the PHY about
* the status of a certain UL HARQ process
*/
typedef Callback< void, UlInfoListElement_s > LtePhyUlHarqFeedbackCallback;
/**
* \ingroup lte
*
* The LteSpectrumPhy models the physical layer of LTE
*
* It supports a single antenna model instance which is
* used for both transmission and reception.
*/
class LteSpectrumPhy : public SpectrumPhy
{
public:
LteSpectrumPhy ();
virtual ~LteSpectrumPhy ();
/**
* PHY states
*/
enum State
{
IDLE, TX, RX_DATA, RX_CTRL
};
// inherited from Object
static TypeId GetTypeId (void);
virtual void DoDispose ();
// inherited from SpectrumPhy
void SetChannel (Ptr<SpectrumChannel> c);
void SetMobility (Ptr<MobilityModel> m);
void SetDevice (Ptr<NetDevice> d);
Ptr<MobilityModel> GetMobility ();
Ptr<NetDevice> GetDevice ();
Ptr<const SpectrumModel> GetRxSpectrumModel () const;
Ptr<AntennaModel> GetRxAntenna ();
void StartRx (Ptr<SpectrumSignalParameters> params);
void StartRxData (Ptr<LteSpectrumSignalParametersDataFrame> params);
void StartRxCtrl (Ptr<SpectrumSignalParameters> params);
void SetHarqPhyModule (Ptr<LteHarqPhy> harq);
/**
* set the Power Spectral Density of outgoing signals in W/Hz.
*
* @param txPsd
*/
void SetTxPowerSpectralDensity (Ptr<SpectrumValue> txPsd);
/**
* \brief set the noise power spectral density
* @param noisePsd the Noise Power Spectral Density in power units
* (Watt, Pascal...) per Hz.
*/
void SetNoisePowerSpectralDensity (Ptr<const SpectrumValue> noisePsd);
/**
* reset the internal state
*
*/
void Reset ();
/**
* set the AntennaModel to be used
*
* \param a the Antenna Model
*/
void SetAntenna (Ptr<AntennaModel> a);
/**
* Start a transmission of data frame in DL and UL
*
*
* @param pb the burst of packets to be transmitted in PDSCH/PUSCH
* @param ctrlMsgList the list of LteControlMessage to send
* @param duration the duration of the data frame
*
* @return true if an error occurred and the transmission was not
* started, false otherwise.
*/
bool StartTxDataFrame (Ptr<PacketBurst> pb, std::list<Ptr<LteControlMessage> > ctrlMsgList, Time duration);
/**
* Start a transmission of control frame in DL
*
*
* @param ctrlMsgList the burst of control messages to be transmitted
* @param pss the flag for transmitting the primary synchronization signal
*
* @return true if an error occurred and the transmission was not
* started, false otherwise.
*/
bool StartTxDlCtrlFrame (std::list<Ptr<LteControlMessage> > ctrlMsgList, bool pss);
/**
* Start a transmission of control frame in UL
*
* @return true if an error occurred and the transmission was not
* started, false otherwise.
*/
bool StartTxUlSrsFrame ();
/**
* set the callback for the end of a TX, as part of the
* interconnections between the PHY and the MAC
*
* @param c the callback
*/
void SetLtePhyTxEndCallback (LtePhyTxEndCallback c);
/**
* set the callback for the end of a RX in error, as part of the
* interconnections between the PHY and the MAC
*
* @param c the callback
*/
void SetLtePhyRxDataEndErrorCallback (LtePhyRxDataEndErrorCallback c);
/**
* set the callback for the successful end of a RX, as part of the
* interconnections between the PHY and the MAC
*
* @param c the callback
*/
void SetLtePhyRxDataEndOkCallback (LtePhyRxDataEndOkCallback c);
/**
* set the callback for the successful end of a RX ctrl frame, as part
* of the interconnections between the LteSpectrumPhy and the PHY
*
* @param c the callback
*/
void SetLtePhyRxCtrlEndOkCallback (LtePhyRxCtrlEndOkCallback c);
/**
* set the callback for the erroneous end of a RX ctrl frame, as part
* of the interconnections between the LteSpectrumPhy and the PHY
*
* @param c the callback
*/
void SetLtePhyRxCtrlEndErrorCallback (LtePhyRxCtrlEndErrorCallback c);
/**
* set the callback for the reception of the PSS as part
* of the interconnections between the LteSpectrumPhy and the UE PHY
*
* @param c the callback
*/
void SetLtePhyRxPssCallback (LtePhyRxPssCallback c);
/**
* set the callback for the DL HARQ feedback as part of the
* interconnections between the LteSpectrumPhy and the PHY
*
* @param c the callback
*/
void SetLtePhyDlHarqFeedbackCallback (LtePhyDlHarqFeedbackCallback c);
/**
* set the callback for the UL HARQ feedback as part of the
* interconnections between the LteSpectrumPhy and the PHY
*
* @param c the callback
*/
void SetLtePhyUlHarqFeedbackCallback (LtePhyUlHarqFeedbackCallback c);
/**
* \brief Set the state of the phy layer
* \param newState the state
*/
void SetState (State newState);
/**
*
*
* \param cellId the Cell Identifier
*/
void SetCellId (uint16_t cellId);
/**
*
*
* \param p the new LteChunkProcessor to be added to the RS power
* processing chain
*/
void AddRsPowerChunkProcessor (Ptr<LteChunkProcessor> p);
/**
*
*
* \param p the new LteChunkProcessor to be added to the Data Channel power
* processing chain
*/
void AddDataPowerChunkProcessor (Ptr<LteChunkProcessor> p);
/**
*
*
* \param p the new LteChunkProcessor to be added to the data processing chain
*/
void AddDataSinrChunkProcessor (Ptr<LteChunkProcessor> p);
/**
* LteChunkProcessor devoted to evaluate interference + noise power
* in control symbols of the subframe
*
* \param p the new LteChunkProcessor to be added to the data processing chain
*/
void AddInterferenceCtrlChunkProcessor (Ptr<LteChunkProcessor> p);
/**
* LteChunkProcessor devoted to evaluate interference + noise power
* in data symbols of the subframe
*
* \param p the new LteChunkProcessor to be added to the data processing chain
*/
void AddInterferenceDataChunkProcessor (Ptr<LteChunkProcessor> p);
/**
*
*
* \param p the new LteChunkProcessor to be added to the ctrl processing chain
*/
void AddCtrlSinrChunkProcessor (Ptr<LteChunkProcessor> p);
/**
*
*
* \param rnti the rnti of the source of the TB
* \param ndi new data indicator flag
* \param size the size of the TB
* \param mcs the MCS of the TB
* \param map the map of RB(s) used
* \param layer the layer (in case of MIMO tx)
* \param harqId the id of the HARQ process (valid only for DL)
* \param downlink true when the TB is for DL
*/
void AddExpectedTb (uint16_t rnti, uint8_t ndi, uint16_t size, uint8_t mcs, std::vector<int> map, uint8_t layer, uint8_t harqId, uint8_t rv, bool downlink);
/**
*
*
* \param sinr vector of sinr perceived per each RB
*/
void UpdateSinrPerceived (const SpectrumValue& sinr);
/**
*
*
* \param txMode UE transmission mode (SISO, MIMO tx diversity, ...)
*/
void SetTransmissionMode (uint8_t txMode);
/**
*
* \return the previously set channel
*/
Ptr<SpectrumChannel> GetChannel ();
friend class LteUePhy;
/**
* Assign a fixed random variable stream number to the random variables
* used by this model. Return the number of streams (possibly zero) that
* have been assigned.
*
* \param stream first stream index to use
* \return the number of stream indices assigned by this model
*/
int64_t AssignStreams (int64_t stream);
private:
void ChangeState (State newState);
void EndTx ();
void EndRxData ();
void EndRxDlCtrl ();
void EndRxUlSrs ();
void SetTxModeGain (uint8_t txMode, double gain);
Ptr<MobilityModel> m_mobility;
Ptr<AntennaModel> m_antenna;
Ptr<NetDevice> m_device;
Ptr<SpectrumChannel> m_channel;
Ptr<const SpectrumModel> m_rxSpectrumModel;
Ptr<SpectrumValue> m_txPsd;
Ptr<PacketBurst> m_txPacketBurst;
std::list<Ptr<PacketBurst> > m_rxPacketBurstList;
std::list<Ptr<LteControlMessage> > m_txControlMessageList;
std::list<Ptr<LteControlMessage> > m_rxControlMessageList;
State m_state;
Time m_firstRxStart;
Time m_firstRxDuration;
TracedCallback<Ptr<const PacketBurst> > m_phyTxStartTrace;
TracedCallback<Ptr<const PacketBurst> > m_phyTxEndTrace;
TracedCallback<Ptr<const PacketBurst> > m_phyRxStartTrace;
TracedCallback<Ptr<const Packet> > m_phyRxEndOkTrace;
TracedCallback<Ptr<const Packet> > m_phyRxEndErrorTrace;
LtePhyTxEndCallback m_ltePhyTxEndCallback;
LtePhyRxDataEndErrorCallback m_ltePhyRxDataEndErrorCallback;
LtePhyRxDataEndOkCallback m_ltePhyRxDataEndOkCallback;
LtePhyRxCtrlEndOkCallback m_ltePhyRxCtrlEndOkCallback;
LtePhyRxCtrlEndErrorCallback m_ltePhyRxCtrlEndErrorCallback;
LtePhyRxPssCallback m_ltePhyRxPssCallback;
Ptr<LteInterference> m_interferenceData;
Ptr<LteInterference> m_interferenceCtrl;
uint16_t m_cellId;
expectedTbs_t m_expectedTbs;
SpectrumValue m_sinrPerceived;
/// Provides uniform random variables.
Ptr<UniformRandomVariable> m_random;
bool m_dataErrorModelEnabled; // when true (default) the phy error model is enabled
bool m_ctrlErrorModelEnabled; // when true (default) the phy error model is enabled for DL ctrl frame
uint8_t m_transmissionMode; // for UEs: store the transmission mode
uint8_t m_layersNum;
std::vector <double> m_txModeGain; // duplicate value of LteUePhy
Ptr<LteHarqPhy> m_harqPhyModule;
LtePhyDlHarqFeedbackCallback m_ltePhyDlHarqFeedbackCallback;
LtePhyUlHarqFeedbackCallback m_ltePhyUlHarqFeedbackCallback;
/**
* Trace information regarding PHY stats from DL Rx perspective
* PhyReceptionStatParameters (see lte-common.h)
*/
TracedCallback<PhyReceptionStatParameters> m_dlPhyReception;
/**
* Trace information regarding PHY stats from UL Rx perspective
* PhyReceptionStatParameters (see lte-common.h)
*/
TracedCallback<PhyReceptionStatParameters> m_ulPhyReception;
EventId m_endTxEvent;
EventId m_endRxDataEvent;
EventId m_endRxDlCtrlEvent;
EventId m_endRxUlSrsEvent;
};
}
#endif /* LTE_SPECTRUM_PHY_H */
| 27.153398 | 159 | 0.72633 | [
"object",
"vector",
"model"
] |
4e1a9b6d28ed0dc4f5b0a2e0a883b28d6333a79c | 5,540 | c | C | speech_recognition/cmusphinx-code/sphinxtrain/src/libs/libio/topo_read.c | Ohara124c41/TUB-MSc_Thesis | b1a2d5dc9c0c589a39019126cf7a5cc775baa288 | [
"MIT"
] | 1 | 2016-12-05T01:29:52.000Z | 2016-12-05T01:29:52.000Z | speech_recognition/cmusphinx-code/sphinxtrain/src/libs/libio/topo_read.c | Ohara124c41/TUB-MSc_Thesis | b1a2d5dc9c0c589a39019126cf7a5cc775baa288 | [
"MIT"
] | null | null | null | speech_recognition/cmusphinx-code/sphinxtrain/src/libs/libio/topo_read.c | Ohara124c41/TUB-MSc_Thesis | b1a2d5dc9c0c589a39019126cf7a5cc775baa288 | [
"MIT"
] | 1 | 2016-12-03T04:06:45.000Z | 2016-12-03T04:06:45.000Z | /* ====================================================================
* Copyright (c) 1995-2000 Carnegie Mellon University. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* This work was supported in part by funding from the Defense Advanced
* Research Projects Agency and the National Science Foundation of the
* United States of America, and the CMU Sphinx Speech Consortium.
*
* THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
* ANY EXPRESSED 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 CARNEGIE MELLON UNIVERSITY
* NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
*
*/
/*********************************************************************
*
* File: topo_read.c
*
* Description:
* Read an ASCII model topology file. This file contains
* an adjacency matrix with non-zero elements for all
* allowable transitions where a row represents a source state
* and a column represents a sink state.
*
* If the adjacency matrix contains values that are all equal,
* the matrix can be normalized to obtain a uniform transition
* probability matrix.
*
* Author:
* Eric H. Thayer (eht@cs.cmu.edu)
*********************************************************************/
/* try to put header files in local to global order to
try to flush out hidden dependencies */
#include <s3/topo_read.h>
#include <sphinxbase/pio.h>
#include <s3/common.h>
#include <s3/s3.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#define TOPO_FILE_VERSION "0.1"
/*********************************************************************
*
* Function:
* topo_read
*
* Description:
* This routine reads an ASCII transition matrix which may then be
* used to determine the topology of the models used in the system.
*
* Traceability:
*
* Function Inputs:
*
* Global Inputs:
* None
*
* Return Values:
* S3_SUCCESS is returned upon successful completion
* S3_ERROR is returned upon an error condition
*
* Global Outputs:
* None
*
* Errors:
*
* Pre-Conditions:
*
* Post-Conditions:
*
* Design:
*
* Notes:
*
*********************************************************************/
int32
topo_read(float32 ***tmat,
uint32 *n_state_pm,
const char *topo_file_name)
{
float32 **out;
FILE *fp;
lineiter_t *li = NULL;
uint32 n_state;
uint32 i, j;
float32 row_sum;
assert(topo_file_name != NULL);
fp = fopen(topo_file_name, "r");
if (fp == NULL) {
E_ERROR_SYSTEM("Unable to open %s for reading\n", topo_file_name);
goto error;
}
li = lineiter_start_clean(fp);
if (li == NULL) {
E_ERROR("EOF encounted while reading version number in %s!?\n", topo_file_name);
goto error;
}
if (strcmp(li->buf, TOPO_FILE_VERSION) != 0) {
E_ERROR("Topo file version in %s is %s. Expected %s\n",
topo_file_name, li->buf, TOPO_FILE_VERSION);
goto error;
}
li = lineiter_next(li);
if (li == NULL) {
E_ERROR("EOF encountered while reading n_state in %s!?\n", topo_file_name);
goto error;
}
sscanf(li->buf, "%d\n", &n_state);
/* Support Request 1504066: robust reading of topo file in
SphinxTrain
When user put
0.1
1.0 1.0 1.0 0.0
1.0 1.0 1.0 0.0
1.0 1.0 1.0 1.0
instead of
0.1
4
1.0 1.0 1.0 0.0
1.0 1.0 1.0 0.0
1.0 1.0 1.0 1.0
topo_read will misread 1.0 into n_state as 1. And the
generated transition matrix will corrupt bw as well. This
problem is now fixed.
*/
if(n_state==1) {
E_ERROR("n_state =1, if you are using a transition matrix with more than 1 state, this error might show that there is format issue in your input topology file. You are recommended to use perl/make_topology.pl to generate the topo file instead.\n");
goto error;
}
out = (float **)ckd_calloc_2d(n_state-1, n_state, sizeof(float32));
for (i = 0; i < n_state-1; i++) {
row_sum = 0.0;
for (j = 0; j < n_state; j++) {
fscanf(fp, "%f", &out[i][j]);
row_sum += out[i][j];
}
for (j = 0; j < n_state; j++) {
out[i][j] /= row_sum;
}
}
*tmat = out;
*n_state_pm = n_state;
fclose(fp);
lineiter_free(li);
return S3_SUCCESS;
error:
if (fp) fclose(fp);
lineiter_free(li);
return S3_ERROR;
}
| 27.839196 | 257 | 0.61083 | [
"model"
] |
4e26006f9501fc8843100ab060538480013fc586 | 177,970 | h | C | proto/fbe.h | backwardn/FastBinaryEncoding | ba66e57951f19047491d3befea9b580f247a694d | [
"MIT"
] | null | null | null | proto/fbe.h | backwardn/FastBinaryEncoding | ba66e57951f19047491d3befea9b580f247a694d | [
"MIT"
] | null | null | null | proto/fbe.h | backwardn/FastBinaryEncoding | ba66e57951f19047491d3befea9b580f247a694d | [
"MIT"
] | null | null | null | // Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: fbe
// Version: 1.3.0.0
#pragma once
#if defined(__clang__)
#pragma clang system_header
#elif defined(__GNUC__)
#pragma GCC system_header
#elif defined(_MSC_VER)
#pragma system_header
#endif
#include <array>
#include <bitset>
#include <cassert>
#include <cmath>
#include <cstring>
#include <cctype>
#include <future>
#include <iomanip>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <vector>
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include <time.h>
#include <uuid/uuid.h>
#undef HOST_NOT_FOUND
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#undef DELETE
#undef ERROR
#undef HOST_NOT_FOUND
#undef Yield
#undef min
#undef max
#undef uuid_t
#endif
#define RAPIDJSON_HAS_STDSTRING 1
#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
namespace FBE {
//! Bytes buffer type
/*!
Represents bytes buffer which is a lightweight wrapper around std::vector<uint8_t>
with similar interface.
*/
class buffer_t
{
public:
typedef std::vector<uint8_t>::iterator iterator;
typedef std::vector<uint8_t>::const_iterator const_iterator;
typedef std::vector<uint8_t>::reverse_iterator reverse_iterator;
typedef std::vector<uint8_t>::const_reverse_iterator const_reverse_iterator;
buffer_t() = default;
buffer_t(size_t capacity) { reserve(capacity); }
buffer_t(const std::string& str) { assign(str); }
buffer_t(size_t size, uint8_t value) { assign(size, value); }
buffer_t(const uint8_t* data, size_t size) { assign(data, size); }
buffer_t(const std::vector<uint8_t>& other) : _data(other) {}
buffer_t(std::vector<uint8_t>&& other) : _data(std::move(other)) {}
buffer_t(const buffer_t& other) = default;
buffer_t(buffer_t&& other) = default;
~buffer_t() = default;
buffer_t& operator=(const std::string& str) { assign(str); return *this; }
buffer_t& operator=(const std::vector<uint8_t>& other) { _data = other; return *this; }
buffer_t& operator=(std::vector<uint8_t>&& other) { _data = std::move(other); return *this; }
buffer_t& operator=(const buffer_t& other) = default;
buffer_t& operator=(buffer_t&& other) = default;
uint8_t& operator[](size_t index) { return _data[index]; }
const uint8_t& operator[](size_t index) const { return _data[index]; }
bool empty() const { return _data.empty(); }
size_t capacity() const { return _data.capacity(); }
size_t size() const { return _data.size(); }
size_t max_size() const { return _data.max_size(); }
std::vector<uint8_t>& buffer() noexcept { return _data; }
const std::vector<uint8_t>& buffer() const noexcept { return _data; }
uint8_t* data() noexcept { return _data.data(); }
const uint8_t* data() const noexcept { return _data.data(); }
uint8_t& at(size_t index) { return _data.at(index); }
const uint8_t& at(size_t index) const { return _data.at(index); }
uint8_t& front() { return _data.front(); }
const uint8_t& front() const { return _data.front(); }
uint8_t& back() { return _data.back(); }
const uint8_t& back() const { return _data.back(); }
void reserve(size_t capacity) { _data.reserve(capacity); }
void resize(size_t size, uint8_t value = 0) { _data.resize(size, value); }
void shrink_to_fit() { _data.shrink_to_fit(); }
void assign(const std::string& str) { assign((const uint8_t*)str.c_str(), str.size()); }
void assign(const std::vector<uint8_t>& vec) { assign(vec.begin(), vec.end()); }
void assign(size_t size, uint8_t value) { _data.assign(size, value); }
void assign(const uint8_t* data, size_t size) { _data.assign(data, data + size); }
template <class InputIterator>
void assign(InputIterator first, InputIterator last) { _data.assign(first, last); }
iterator insert(const_iterator position, uint8_t value) { return _data.insert(position, value); }
iterator insert(const_iterator position, const std::string& str) { return insert(position, (const uint8_t*)str.c_str(), str.size()); }
iterator insert(const_iterator position, const std::vector<uint8_t>& vec) { return insert(position, vec.begin(), vec.end()); }
iterator insert(const_iterator position, size_t size, uint8_t value) { return _data.insert(position, size, value); }
iterator insert(const_iterator position, const uint8_t* data, size_t size) { return _data.insert(position, data, data + size); }
template <class InputIterator>
iterator insert(const_iterator position, InputIterator first, InputIterator last) { return _data.insert(position, first, last); }
iterator erase(const_iterator position) { return _data.erase(position); }
iterator erase(const_iterator first, const_iterator last) { return _data.erase(first, last); }
void clear() noexcept { _data.clear(); }
void push_back(uint8_t value) { _data.push_back(value); }
void pop_back() { _data.pop_back(); }
template <class... Args>
iterator emplace(const_iterator position, Args&&... args) { return _data.emplace(position, args...); }
template <class... Args>
void emplace_back(Args&&... args) { _data.emplace_back(args...); }
iterator begin() noexcept { return _data.begin(); }
const_iterator begin() const noexcept { return _data.begin(); }
const_iterator cbegin() const noexcept { return _data.cbegin(); }
reverse_iterator rbegin() noexcept { return _data.rbegin(); }
const_reverse_iterator rbegin() const noexcept { return _data.rbegin(); }
const_reverse_iterator crbegin() const noexcept { return _data.crbegin(); }
iterator end() noexcept { return _data.end(); }
const_iterator end() const noexcept { return _data.end(); }
const_iterator cend() const noexcept { return _data.cend(); }
reverse_iterator rend() noexcept { return _data.rend(); }
const_reverse_iterator rend() const noexcept { return _data.rend(); }
const_reverse_iterator crend() const noexcept { return _data.crend(); }
//! Get the string equivalent from the bytes buffer
std::string string() const { return std::string(_data.begin(), _data.end()); }
//! Encode the Base64 string from the bytes buffer
std::string base64encode() const;
//! Decode the bytes buffer from the Base64 string
static buffer_t base64decode(const std::string& str);
//! Swap two instances
void swap(buffer_t& value) noexcept
{ using std::swap; swap(_data, value._data); }
friend void swap(buffer_t& value1, buffer_t& value2) noexcept
{ value1.swap(value2); }
private:
std::vector<uint8_t> _data;
};
inline std::string buffer_t::base64encode() const
{
const char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string result;
int val = 0;
int valb = -6;
for (auto c : _data)
{
val = (val << 8) + c;
valb += 8;
while (valb >= 0)
{
result.push_back(base64[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6)
result.push_back(base64[((val << 8) >> (valb + 8)) & 0x3F]);
while (result.size() % 4)
result.push_back('=');
return result;
}
inline buffer_t buffer_t::base64decode(const std::string& str)
{
const char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
buffer_t result;
std::vector<int> pattern(256, -1);
for (int i = 0; i < 64; ++i)
pattern[base64[i]] = i;
int val = 0;
int valb = -8;
for (auto c : str)
{
if (pattern[c] == -1)
break;
val = (val << 6) + pattern[c];
valb += 6;
if (valb >= 0)
{
result.push_back((uint8_t)((val >> valb) & 0xFF));
valb -= 8;
}
}
return result;
}
//! Decimal type
/*!
Represents decimal type using double and provides basic arithmetic operations.
*/
class decimal_t
{
public:
decimal_t() noexcept { _value = 0.0; }
decimal_t(int8_t value) noexcept { _value = (double)value; }
decimal_t(uint8_t value) noexcept { _value = (double)value; }
decimal_t(int16_t value) noexcept { _value = (double)value; }
decimal_t(uint16_t value) noexcept { _value = (double)value; }
decimal_t(int32_t value) noexcept { _value = (double)value; }
decimal_t(uint32_t value) noexcept { _value = (double)value; }
decimal_t(int64_t value) noexcept { _value = (double)value; }
decimal_t(uint64_t value) noexcept { _value = (double)value; }
decimal_t(float value) noexcept { _value = (double)value; }
decimal_t(double value) noexcept { _value = value; }
template <typename T>
explicit decimal_t(const T& value) noexcept { _value = (double)value; }
decimal_t(const decimal_t& value) noexcept = default;
decimal_t(decimal_t&& value) noexcept = default;
~decimal_t() noexcept = default;
template <typename T>
decimal_t& operator=(const T& value) noexcept { _value = (double)value; return *this; }
decimal_t& operator=(const decimal_t& value) noexcept = default;
decimal_t& operator=(decimal_t&& value) noexcept = default;
// Arithmetic operators
decimal_t operator+() const noexcept { return decimal_t(_value); }
decimal_t operator-() const noexcept { return decimal_t(-_value); }
decimal_t& operator++() noexcept { return *this += 1; }
decimal_t operator++(int) noexcept { decimal_t temp(*this); ++*this; return temp; }
decimal_t& operator--() noexcept { return *this -= 1; }
decimal_t operator--(int) noexcept { decimal_t temp(*this); --*this; return temp; }
decimal_t& operator+=(const decimal_t& value) noexcept { return *this = *this + value; }
decimal_t& operator-=(const decimal_t& value) noexcept { return *this = *this - value; }
decimal_t& operator*=(const decimal_t& value) noexcept { return *this = *this * value; }
decimal_t& operator/=(const decimal_t& value) { return *this = *this / value; }
template <typename T>
decimal_t& operator+=(const T& value) noexcept { return *this = *this + decimal_t(value); }
template <typename T>
decimal_t& operator-=(const T& value) noexcept { return *this = *this - decimal_t(value); }
template <typename T>
decimal_t& operator*=(const T& value) noexcept { return *this = *this * decimal_t(value); }
template <typename T>
decimal_t& operator/=(const T& value) { return *this = *this / decimal_t(value); }
template <typename T>
friend T& operator+=(T& value1, const decimal_t& value2) noexcept { return value1 = (T)(decimal_t(value1) + value2); }
template <typename T>
friend T& operator-=(T& value1, const decimal_t& value2) noexcept { return value1 = (T)(decimal_t(value1) - value2); }
template <typename T>
friend T& operator*=(T& value1, const decimal_t& value2) noexcept { return value1 = (T)(decimal_t(value1) * value2); }
template <typename T>
friend T& operator/=(T& value1, const decimal_t& value2) { return value1 = (T)(decimal_t(value1) / value2); }
template <typename T>
friend decimal_t operator+(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) + value2; }
template <typename T>
friend decimal_t operator+(const decimal_t& value1, const T& value2) noexcept { return value1 + decimal_t(value2); }
friend decimal_t operator+(const decimal_t& value1, const decimal_t& value2) noexcept { return decimal_t(value1._value + value2._value); }
template <typename T>
friend decimal_t operator-(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) - value2; }
template <typename T>
friend decimal_t operator-(const decimal_t& value1, const T& value2) noexcept { return value1 - decimal_t(value2); }
friend decimal_t operator-(const decimal_t& value1, const decimal_t& value2) noexcept { return decimal_t(value1._value - value2._value); }
template <typename T>
friend decimal_t operator*(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) * value2; }
template <typename T>
friend decimal_t operator*(const decimal_t& value1, const T& value2) noexcept { return value1 * decimal_t(value2); }
friend decimal_t operator*(const decimal_t& value1, const decimal_t& value2) noexcept { return decimal_t(value1._value * value2._value); }
template <typename T>
friend decimal_t operator/(const T& value1, const decimal_t& value2) { return decimal_t(value1) / value2; }
template <typename T>
friend decimal_t operator/(const decimal_t& value1, const T& value2) { return value1 / decimal_t(value2); }
friend decimal_t operator/(const decimal_t& value1, const decimal_t& value2) { return decimal_t(value1._value / value2._value); }
// Comparison operators
template <typename T>
friend bool operator==(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) == value2; }
template <typename T>
friend bool operator==(const decimal_t& value1, const T& value2) noexcept { return value1 == decimal_t(value2); }
friend bool operator==(const decimal_t& value1, const decimal_t& value2) noexcept { return value1._value == value2._value; }
template <typename T>
friend bool operator!=(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) != value2; }
template <typename T>
friend bool operator!=(const decimal_t& value1, const T& value2) noexcept { return value1 != decimal_t(value2); }
friend bool operator!=(const decimal_t& value1, const decimal_t& value2) noexcept { return value1._value != value2._value; }
template <typename T>
friend bool operator<(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) < value2; }
template <typename T>
friend bool operator<(const decimal_t& value1, const T& value2) noexcept { return value1 < decimal_t(value2); }
friend bool operator<(const decimal_t& value1, const decimal_t& value2) noexcept { return value1._value < value2._value; }
template <typename T>
friend bool operator>(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) > value2; }
template <typename T>
friend bool operator>(const decimal_t& value1, const T& value2) noexcept { return value1 > decimal_t(value2); }
friend bool operator>(const decimal_t& value1, const decimal_t& value2) noexcept { return value1._value > value2._value; }
template <typename T>
friend bool operator<=(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) <= value2; }
template <typename T>
friend bool operator<=(const decimal_t& value1, const T& value2) noexcept { return value1 <= decimal_t(value2); }
friend bool operator<=(const decimal_t& value1, const decimal_t& value2) noexcept { return value1._value <= value2._value; }
template <typename T>
friend bool operator>=(const T& value1, const decimal_t& value2) noexcept { return decimal_t(value1) >= value2; }
template <typename T>
friend bool operator>=(const decimal_t& value1, const T& value2) noexcept { return value1 >= decimal_t(value2); }
friend bool operator>=(const decimal_t& value1, const decimal_t& value2) noexcept { return value1._value >= value2._value; }
// Type cast
operator bool() const noexcept { return (_value != 0.0); }
operator uint8_t() const noexcept { return (uint8_t)_value; }
operator uint16_t() const noexcept { return (uint16_t)_value; }
operator uint32_t() const noexcept { return (uint32_t)_value; }
operator uint64_t() const noexcept { return (uint64_t)_value; }
operator float() const noexcept { return (float)_value; }
operator double() const noexcept { return (double)_value; }
//! Get string from the current decimal value
/*!
\return Result string
*/
std::string string() const { return std::to_string(_value); }
//! Input instance from the given input stream
friend std::istream& operator>>(std::istream& is, decimal_t& value)
{ is >> value._value; return is; }
//! Output instance into the given output stream
friend std::ostream& operator<<(std::ostream& os, const decimal_t& value)
{ os << value.string(); return os; }
#if defined(LOGGING_PROTOCOL)
//! Store logging format
friend CppLogging::Record& operator<<(CppLogging::Record& record, const decimal_t& value)
{ return record.StoreCustom(value._value); }
#endif
//! Swap two instances
void swap(decimal_t& value) noexcept
{ using std::swap; swap(_value, value._value); }
friend void swap(decimal_t& value1, decimal_t& value2) noexcept
{ value1.swap(value2); }
private:
double _value;
};
} // namespace FBE
namespace std {
template <>
struct hash<FBE::decimal_t>
{
typedef FBE::decimal_t argument_type;
typedef size_t result_type;
result_type operator () (const argument_type& value) const
{
result_type result = 17;
result = result * 31 + std::hash<double>()((double)value);
return result;
}
};
} // namespace std
namespace FBE {
// Register a new enum-based flags macro
#define FBE_ENUM_FLAGS(type)\
inline FBE::Flags<type> operator|(type f1, type f2) noexcept { return FBE::Flags<type>(f1) | FBE::Flags<type>(f2); }\
inline FBE::Flags<type> operator&(type f1, type f2) noexcept { return FBE::Flags<type>(f1) & FBE::Flags<type>(f2); }\
inline FBE::Flags<type> operator^(type f1, type f2) noexcept { return FBE::Flags<type>(f1) ^ FBE::Flags<type>(f2); }
// Enum-based flags
template <typename TEnum>
class Flags
{
// Enum underlying type
typedef typename std::make_unsigned<typename std::underlying_type<TEnum>::type>::type type;
public:
Flags() noexcept : _value(0) {}
explicit Flags(type value) noexcept : _value(value) {}
explicit Flags(TEnum value) noexcept : _value((type)value) {}
Flags(const Flags&) noexcept = default;
Flags(Flags&&) noexcept = default;
~Flags() noexcept = default;
Flags& operator=(type value) noexcept
{ _value = value; return *this; }
Flags& operator=(TEnum value) noexcept
{ _value = (type)value; return *this; }
Flags& operator=(const Flags&) noexcept = default;
Flags& operator=(Flags&&) noexcept = default;
// Is any flag set?
explicit operator bool() const noexcept { return isset(); }
// Is no flag set?
bool operator!() const noexcept { return !isset(); }
// Reverse all flags
Flags operator~() const noexcept { return Flags(~_value); }
// Flags logical assign operators
Flags& operator&=(const Flags& flags) noexcept
{ _value &= flags._value; return *this; }
Flags& operator|=(const Flags& flags) noexcept
{ _value |= flags._value; return *this; }
Flags& operator^=(const Flags& flags) noexcept
{ _value ^= flags._value; return *this; }
// Flags logical friend operators
friend Flags operator&(const Flags& flags1, const Flags& flags2) noexcept
{ return Flags(flags1._value & flags2._value); }
friend Flags operator|(const Flags& flags1, const Flags& flags2) noexcept
{ return Flags(flags1._value | flags2._value); }
friend Flags operator^(const Flags& flags1, const Flags& flags2) noexcept
{ return Flags(flags1._value ^ flags2._value); }
// Flags comparison
friend bool operator==(const Flags& flags1, const Flags& flags2) noexcept
{ return flags1._value == flags2._value; }
friend bool operator!=(const Flags& flags1, const Flags& flags2) noexcept
{ return flags1._value != flags2._value; }
// Convert to the enum value
operator TEnum() const noexcept { return (TEnum)_value; }
//! Is any flag set?
bool isset() const noexcept { return (_value != 0); }
//! Is the given flag set?
bool isset(type value) const noexcept { return (_value & value) != 0; }
//! Is the given flag set?
bool isset(TEnum value) const noexcept { return (_value & (type)value) != 0; }
// Get the enum value
TEnum value() const noexcept { return (TEnum)_value; }
// Get the underlying enum value
type underlying() const noexcept { return _value; }
// Get the bitset value
std::bitset<sizeof(type) * 8> bitset() const noexcept { return {_value}; }
// Swap two instances
void swap(Flags& flags) noexcept { using std::swap; swap(_value, flags._value); }
template <typename UEnum>
friend void swap(Flags<UEnum>& flags1, Flags<UEnum>& flags2) noexcept;
private:
type _value;
};
template <typename TEnum>
inline void swap(Flags<TEnum>& flags1, Flags<TEnum>& flags2) noexcept
{
flags1.swap(flags2);
}
inline uint64_t epoch() { return 0ull; }
inline uint64_t utc()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
struct timespec timestamp;
if (clock_gettime(CLOCK_REALTIME, ×tamp) != 0)
throw std::runtime_error("Cannot get value of CLOCK_REALTIME timer!");
return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
FILETIME ft;
GetSystemTimePreciseAsFileTime(&ft);
ULARGE_INTEGER result;
result.LowPart = ft.dwLowDateTime;
result.HighPart = ft.dwHighDateTime;
return (result.QuadPart - 116444736000000000ull) * 100;
#endif
}
//! Universally unique identifier (UUID)
/*!
A universally unique identifier (UUID) is an identifier standard used
in software construction. This implementation generates the following
UUID types:
- Nil UUID0 (all bits set to zero)
- Sequential UUID1 (time based version)
- Random UUID4 (randomly or pseudo-randomly generated version)
A UUID is simply a 128-bit value: "123e4567-e89b-12d3-a456-426655440000"
https://en.wikipedia.org/wiki/Universally_unique_identifier
https://www.ietf.org/rfc/rfc4122.txt
*/
class uuid_t
{
public:
//! Default constructor
uuid_t() : _data() { _data.fill(0); }
//! Initialize UUID with a given string
/*!
\param uuid - UUID string
*/
explicit uuid_t(const std::string& uuid)
{
char v1 = 0;
char v2 = 0;
bool pack = false;
size_t index = 0;
// Parse UUID string
for (auto ch : uuid)
{
if ((ch == '-') || (ch == '{') || (ch == '}'))
continue;
if (pack)
{
v2 = ch;
pack = false;
uint8_t ui1 = unhex(v1);
uint8_t ui2 = unhex(v2);
if ((ui1 > 15) || (ui2 > 15))
throw std::invalid_argument("Invalid UUID string: " + uuid);
_data[index++] = ui1 * 16 + ui2;
if (index >= 16)
break;
}
else
{
v1 = ch;
pack = true;
}
}
// Fill remaining data with zeros
for (; index < 16; ++index)
_data[index++] = 0;
}
//! Initialize UUID with a given 16 bytes data buffer
/*!
\param data - UUID 16 bytes data buffer
*/
explicit uuid_t(const std::array<uint8_t, 16>& data) : _data(data) {}
uuid_t(const uuid_t&) = default;
uuid_t(uuid_t&&) noexcept = default;
~uuid_t() = default;
uuid_t& operator=(const std::string& uuid)
{ _data = uuid_t(uuid).data(); return *this; }
uuid_t& operator=(const std::array<uint8_t, 16>& data)
{ _data = data; return *this; }
uuid_t& operator=(const uuid_t&) = default;
uuid_t& operator=(uuid_t&&) noexcept = default;
// UUID comparison
friend bool operator==(const uuid_t& uuid1, const uuid_t& uuid2)
{ return uuid1._data == uuid2._data; }
friend bool operator!=(const uuid_t& uuid1, const uuid_t& uuid2)
{ return uuid1._data != uuid2._data; }
friend bool operator<(const uuid_t& uuid1, const uuid_t& uuid2)
{ return uuid1._data < uuid2._data; }
friend bool operator>(const uuid_t& uuid1, const uuid_t& uuid2)
{ return uuid1._data > uuid2._data; }
friend bool operator<=(const uuid_t& uuid1, const uuid_t& uuid2)
{ return uuid1._data <= uuid2._data; }
friend bool operator>=(const uuid_t& uuid1, const uuid_t& uuid2)
{ return uuid1._data >= uuid2._data; }
//! Check if the UUID is nil UUID0 (all bits set to zero)
explicit operator bool() const noexcept { return *this != nil(); }
//! Get the UUID data buffer
std::array<uint8_t, 16>& data() noexcept { return _data; }
//! Get the UUID data buffer
const std::array<uint8_t, 16>& data() const noexcept { return _data; }
//! Get string from the current UUID in format "00000000-0000-0000-0000-000000000000"
std::string string() const
{
const char* digits = "0123456789abcdef";
std::string result(36, '0');
int index = 0;
for (auto value : _data)
{
result[index++] = digits[(value >> 4) & 0x0F];
result[index++] = digits[(value >> 0) & 0x0F];
if ((index == 8) || (index == 13) || (index == 18) || (index == 23))
result[index++] = '-';
}
return result;
}
//! Generate nil UUID0 (all bits set to zero)
static uuid_t nil() { return uuid_t(); }
//! Generate sequential UUID1 (time based version)
static uuid_t sequential()
{
uuid_t result;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
::uuid_t uuid;
uuid_generate_time(uuid);
result._data[0] = uuid[0];
result._data[1] = uuid[1];
result._data[2] = uuid[2];
result._data[3] = uuid[3];
result._data[4] = uuid[4];
result._data[5] = uuid[5];
result._data[6] = uuid[6];
result._data[7] = uuid[7];
result._data[8] = uuid[8];
result._data[9] = uuid[9];
result._data[10] = uuid[10];
result._data[11] = uuid[11];
result._data[12] = uuid[12];
result._data[13] = uuid[13];
result._data[14] = uuid[14];
result._data[15] = uuid[15];
#elif defined(_WIN32) || defined(_WIN64)
::UUID uuid;
if (UuidCreateSequential(&uuid) != RPC_S_OK)
throw std::runtime_error("Cannot generate sequential UUID!");
result._data[0] = (uuid.Data1 >> 24) & 0xFF;
result._data[1] = (uuid.Data1 >> 16) & 0xFF;
result._data[2] = (uuid.Data1 >> 8) & 0xFF;
result._data[3] = (uuid.Data1 >> 0) & 0xFF;
result._data[4] = (uuid.Data2 >> 8) & 0xFF;
result._data[5] = (uuid.Data2 >> 0) & 0xFF;
result._data[6] = (uuid.Data3 >> 8) & 0xFF;
result._data[7] = (uuid.Data3 >> 0) & 0xFF;
result._data[8] = uuid.Data4[0];
result._data[9] = uuid.Data4[1];
result._data[10] = uuid.Data4[2];
result._data[11] = uuid.Data4[3];
result._data[12] = uuid.Data4[4];
result._data[13] = uuid.Data4[5];
result._data[14] = uuid.Data4[6];
result._data[15] = uuid.Data4[7];
#endif
return result;
}
//! Generate random UUID4 (randomly or pseudo-randomly generated version)
static uuid_t random()
{
uuid_t result;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
::uuid_t uuid;
uuid_generate_random(uuid);
result._data[0] = uuid[0];
result._data[1] = uuid[1];
result._data[2] = uuid[2];
result._data[3] = uuid[3];
result._data[4] = uuid[4];
result._data[5] = uuid[5];
result._data[6] = uuid[6];
result._data[7] = uuid[7];
result._data[8] = uuid[8];
result._data[9] = uuid[9];
result._data[10] = uuid[10];
result._data[11] = uuid[11];
result._data[12] = uuid[12];
result._data[13] = uuid[13];
result._data[14] = uuid[14];
result._data[15] = uuid[15];
#elif defined(_WIN32) || defined(_WIN64)
::UUID uuid;
if (UuidCreate(&uuid) != RPC_S_OK)
throw std::runtime_error("Cannot generate random UUID!");
result._data[0] = (uuid.Data1 >> 24) & 0xFF;
result._data[1] = (uuid.Data1 >> 16) & 0xFF;
result._data[2] = (uuid.Data1 >> 8) & 0xFF;
result._data[3] = (uuid.Data1 >> 0) & 0xFF;
result._data[4] = (uuid.Data2 >> 8) & 0xFF;
result._data[5] = (uuid.Data2 >> 0) & 0xFF;
result._data[6] = (uuid.Data3 >> 8) & 0xFF;
result._data[7] = (uuid.Data3 >> 0) & 0xFF;
result._data[8] = uuid.Data4[0];
result._data[9] = uuid.Data4[1];
result._data[10] = uuid.Data4[2];
result._data[11] = uuid.Data4[3];
result._data[12] = uuid.Data4[4];
result._data[13] = uuid.Data4[5];
result._data[14] = uuid.Data4[6];
result._data[15] = uuid.Data4[7];
#endif
return result;
}
//! Output instance into the given output stream
friend std::ostream& operator<<(std::ostream& os, const uuid_t& uuid)
{ os << uuid.string(); return os; }
#if defined(LOGGING_PROTOCOL)
//! Store logging format
friend CppLogging::Record& operator<<(CppLogging::Record& record, const uuid_t& uuid)
{
const char* digits = "0123456789abcdef";
std::array<char, 36> result;
int index = 0;
for (auto value : uuid.data())
{
result[index++] = digits[(value >> 4) & 0x0F];
result[index++] = digits[(value >> 0) & 0x0F];
if ((index == 8) || (index == 13) || (index == 18) || (index == 23))
result[index++] = '-';
}
return record.StoreCustom(std::string_view(result.data(), result.size()));
}
#endif
//! Swap two instances
void swap(uuid_t& uuid) noexcept
{ using std::swap; swap(_data, uuid._data); }
friend void swap(uuid_t& uuid1, uuid_t& uuid2) noexcept
{ uuid1.swap(uuid2); }
private:
std::array<uint8_t, 16> _data;
static uint8_t unhex(char ch)
{
if ((ch >= '0') && (ch <= '9'))
return ch - '0';
else if ((ch >= 'a') && (ch <= 'f'))
return 10 + ch - 'a';
else if ((ch >= 'A') && (ch <= 'F'))
return 10 + ch - 'A';
else
return 255;
}
};
} // namespace FBE
namespace std {
template <>
struct hash<FBE::uuid_t>
{
typedef FBE::uuid_t argument_type;
typedef size_t result_type;
result_type operator () (const argument_type& value) const
{
result_type result = 17;
std::hash<uint8_t> hasher;
for (size_t i = 0; i < value.data().size(); ++i)
result = result * 31 + hasher(value.data()[i]);
return result;
}
};
} // namespace std
namespace FBE {
// Fast Binary Encoding write buffer based on the dynamic byte buffer
class WriteBuffer
{
public:
WriteBuffer() : _data(nullptr), _capacity(0), _size(0), _offset(0) {}
// Initialize the write buffer with the given capacity
explicit WriteBuffer(size_t capacity) : WriteBuffer() { reserve(capacity); }
WriteBuffer(const WriteBuffer&) = default;
WriteBuffer(WriteBuffer&&) noexcept = default;
~WriteBuffer() { std::free(_data); }
WriteBuffer& operator=(const WriteBuffer&) = default;
WriteBuffer& operator=(WriteBuffer&&) noexcept = default;
bool empty() const noexcept { return (_data == nullptr) || (_size == 0); }
const uint8_t* data() const noexcept { return _data; }
uint8_t* data() noexcept { return _data; }
size_t capacity() const noexcept { return _capacity; }
size_t size() const noexcept { return _size; }
size_t offset() const noexcept { return _offset; }
// Attach the given buffer with a given offset to the end of the current buffer
void attach(const void* data, size_t size, size_t offset = 0)
{
assert((offset <= size) && "Invalid offset!");
if (offset > size)
throw std::invalid_argument("Invalid offset!");
reserve(size);
std::memcpy(_data, data, size);
_capacity = size;
_size = size;
_offset = offset;
}
// Attach the given vector with a given offset to the end of the current buffer
void attach(const std::vector<uint8_t>& buffer, size_t offset = 0)
{
assert((offset <= buffer.size()) && "Invalid offset!");
if (offset > buffer.size())
throw std::invalid_argument("Invalid offset!");
size_t size = buffer.size();
reserve(size);
std::memcpy(_data, buffer.data(), size);
_capacity = size;
_size = size;
_offset = offset;
}
// Allocate memory in the current write buffer and return offset to the allocated memory block
size_t allocate(size_t size)
{
size_t offset = _size;
// Calculate a new buffer size
size_t total = _size + size;
if (total <= _capacity)
{
_size = total;
return offset;
}
_capacity = std::max(total, 2 * _capacity);
uint8_t* data = (uint8_t*)std::malloc(_capacity);
std::memcpy(data, _data, _size);
std::free(_data);
_data = data;
_size = total;
return offset;
}
// Remove some memory of the given size from the current write buffer
void remove(size_t offset, size_t size)
{
assert(((offset + size) <= _size) && "Invalid offset & size!");
if ((offset + size) > _size)
throw std::invalid_argument("Invalid offset & size!");
std::memcpy(_data + offset, _data + offset + size, _size - size - offset);
_size -= size;
if (_offset >= (offset + size))
_offset -= size;
else if (_offset >= offset)
{
_offset -= _offset - offset;
if (_offset > _size)
_offset = _size;
}
}
// Reserve memory of the given capacity in the current write buffer
void reserve(size_t capacity)
{
if (capacity > _capacity)
{
_capacity = std::max(capacity, 2 * _capacity);
uint8_t* data = (uint8_t*)std::malloc(_capacity);
std::memcpy(data, _data, _size);
std::free(_data);
_data = data;
}
}
// Resize the current write buffer
void resize(size_t size)
{
reserve(size);
_size = size;
if (_offset > _size)
_offset = _size;
}
// Reset the current write buffer and its offset
void reset()
{
_size = 0;
_offset = 0;
}
// Shift the current write buffer offset
void shift(size_t offset) { _offset += offset; }
// Unshift the current write buffer offset
void unshift(size_t offset) { _offset -= offset; }
private:
uint8_t* _data;
size_t _capacity;
size_t _size;
size_t _offset;
};
// Fast Binary Encoding read buffer based on the constant byte buffer
class ReadBuffer
{
public:
ReadBuffer() : _data(nullptr), _size(0), _offset(0) {}
// Initialize the read buffer with the given byte buffer and offset
explicit ReadBuffer(const void* data, size_t size, size_t offset = 0) { attach(data, size, offset); }
// Initialize the read buffer with the given byte vector and offset
explicit ReadBuffer(const std::vector<uint8_t>& buffer, size_t offset = 0) { attach(buffer, offset); }
// Initialize the read buffer with another read buffer and offset
explicit ReadBuffer(const ReadBuffer& buffer, size_t offset = 0) { attach(buffer.data(), buffer.size(), offset); }
// Initialize the read buffer with another write buffer and offset
explicit ReadBuffer(const WriteBuffer& buffer, size_t offset = 0) { attach(buffer.data(), buffer.size(), offset); }
ReadBuffer(ReadBuffer&&) noexcept = default;
~ReadBuffer() = default;
ReadBuffer& operator=(const ReadBuffer&) = default;
ReadBuffer& operator=(ReadBuffer&&) noexcept = default;
bool empty() const noexcept { return (_data == nullptr) || (_size == 0); }
const uint8_t* data() const noexcept { return _data; }
size_t capacity() const noexcept { return _size; }
size_t size() const noexcept { return _size; }
size_t offset() const noexcept { return _offset; }
// Attach the given buffer with a given offset to the current read buffer
void attach(const void* data, size_t size, size_t offset = 0)
{
assert((data != nullptr) && "Invalid buffer!");
if (data == nullptr)
throw std::invalid_argument("Invalid buffer!");
assert((size > 0) && "Invalid size!");
if (size == 0)
throw std::invalid_argument("Invalid size!");
assert((offset <= size) && "Invalid offset!");
if (offset > size)
throw std::invalid_argument("Invalid offset!");
_data = (const uint8_t*)data;
_size = size;
_offset = offset;
}
// Attach the given byte vector with a given offset to the current read buffer
void attach(const std::vector<uint8_t>& buffer, size_t offset = 0)
{
assert((buffer.data() != nullptr) && "Invalid buffer!");
if (buffer.data() == nullptr)
throw std::invalid_argument("Invalid buffer!");
assert((buffer.size() > 0) && "Invalid size!");
if (buffer.size() == 0)
throw std::invalid_argument("Invalid size!");
assert((offset <= buffer.size()) && "Invalid offset!");
if (offset > buffer.size())
throw std::invalid_argument("Invalid offset!");
_data = buffer.data();
_size = buffer.size();
_offset = offset;
}
// Allocate fake method
size_t allocate(size_t size)
{
assert(false && "Cannot allocate using the read buffer!");
throw std::logic_error("Cannot allocate using the read buffer!");
}
// Remove fake method
void remove(size_t offset, size_t size)
{
assert(false && "Cannot remove from the read buffer!");
throw std::logic_error("Cannot remove from the read buffer!");
}
// Reserve fake method
void reserve(size_t capacity)
{
assert(false && "Cannot reserve using the read buffer!");
throw std::logic_error("Cannot reserve using the read buffer!");
}
// Resize fake method
void resize(size_t size)
{
assert(false && "Cannot resize the read buffer!");
throw std::logic_error("Cannot resize the read buffer!");
}
// Reset the current read buffer and its offset
void reset()
{
_data = nullptr;
_size = 0;
_offset = 0;
}
// Shift the current read buffer offset
void shift(size_t size) { _offset += size; }
// Unshift the current read buffer offset
void unshift(size_t size) { _offset -= size; }
private:
const uint8_t* _data;
size_t _size;
size_t _offset;
};
// Fast Binary Encoding base model
template <class TBuffer>
class Model
{
public:
Model() : Model(nullptr) {}
Model(const std::shared_ptr<TBuffer>& buffer) { _buffer = buffer ? buffer : std::make_shared<TBuffer>(); }
Model(const Model&) = default;
Model(Model&&) noexcept = default;
~Model() = default;
Model& operator=(const Model&) = default;
Model& operator=(Model&&) noexcept = default;
// Get the model buffer
TBuffer& buffer() noexcept { return *_buffer; }
const TBuffer& buffer() const noexcept { return *_buffer; }
// Attach the model buffer
void attach(const void* data, size_t size, size_t offset = 0) { _buffer->attach(data, size, offset); }
void attach(const std::vector<uint8_t>& buffer, size_t offset = 0) { _buffer->attach(buffer, offset); }
void attach(const ReadBuffer& buffer, size_t offset = 0) { _buffer->attach(buffer.data(), buffer.size(), offset); }
void attach(const WriteBuffer& buffer, size_t offset = 0) { _buffer->attach(buffer.data(), buffer.size(), offset); }
// Model buffer operations
size_t allocate(size_t size) { return _buffer->allocate(size); }
void remove(size_t offset, size_t size) { _buffer->remove(offset, size); }
void reserve(size_t capacity) { _buffer->reserve(capacity); }
void resize(size_t size) { _buffer->resize(size); }
void reset() { _buffer->reset(); }
void shift(size_t offset) { _buffer->shift(offset); }
void unshift(size_t offset) { _buffer->unshift(offset); }
private:
std::shared_ptr<TBuffer> _buffer;
};
// Fast Binary Encoding base field model
template <class TBuffer, typename T, typename TBase = T>
class FieldModelBase
{
public:
FieldModelBase(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return sizeof(TBase); }
// Get the field extra size
size_t fbe_extra() const noexcept { return 0; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the value is valid
bool verify() const noexcept { return true; }
// Get the field value
void get(T& value, T defaults = (T)0) const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
{
value = defaults;
return;
}
value = (T)(*((const TBase*)(_buffer.data() + _buffer.offset() + fbe_offset())));
}
// Set the field value
void set(T value) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
*((TBase*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (TBase)value;
}
private:
TBuffer& _buffer;
size_t _offset;
};
// Fast Binary Encoding field model
template <class TBuffer, typename T>
class FieldModel : public FieldModelBase<TBuffer, T>
{
public:
using FieldModelBase<TBuffer, T>::FieldModelBase;
};
// Fast Binary Encoding field model bool specialization
template <class TBuffer>
class FieldModel<TBuffer, bool> : public FieldModelBase<TBuffer, bool, uint8_t>
{
public:
using FieldModelBase<TBuffer, bool, uint8_t>::FieldModelBase;
};
// Fast Binary Encoding field model char specialization
template <class TBuffer>
class FieldModel<TBuffer, char> : public FieldModelBase<TBuffer, char, uint8_t>
{
public:
using FieldModelBase<TBuffer, char, uint8_t>::FieldModelBase;
};
// Fast Binary Encoding field model wchar specialization
template <class TBuffer>
class FieldModel<TBuffer, wchar_t> : public FieldModelBase<TBuffer, wchar_t, uint32_t>
{
public:
using FieldModelBase<TBuffer, wchar_t, uint32_t>::FieldModelBase;
};
// Fast Binary Encoding field model decimal specialization
template <class TBuffer>
class FieldModel<TBuffer, decimal_t>
{
public:
FieldModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return 16; }
// Get the field extra size
size_t fbe_extra() const noexcept { return 0; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the decimal value is valid
bool verify() const noexcept { return true; }
// Get the decimal value
void get(decimal_t& value, decimal_t defaults = decimal_t()) const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
{
value = defaults;
return;
}
// Value taken via reverse engineering the double that corresponds to 2^64
const double ds2to64 = 1.8446744073709552e+019;
// Read decimal parts
uint64_t low = *((const uint64_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
uint32_t high = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8));
uint32_t flags = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 12));
// Calculate decimal value
double dValue = ((double)low + (double)high * ds2to64) / pow(10.0, (uint8_t)(flags >> 16));
if (flags & 0x80000000)
dValue = -dValue;
value = dValue;
}
// Set the decimal value
void set(decimal_t value) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
// The most we can scale by is 10^28, which is just slightly more
// than 2^93. So a float with an exponent of -94 could just
// barely reach 0.5, but smaller exponents will always round to zero.
const uint32_t DBLBIAS = 1022;
// Get exponent value
double dValue = (double)value;
int32_t iExp = (int32_t)(((uint32_t)((*(uint64_t*)&dValue) >> 52) & 0x7FFu) - DBLBIAS);
if ((iExp < -94) || (iExp > 96))
{
// Value too big for .NET Decimal (exponent is limited to [-94, 96])
memset((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), 0, 16);
return;
}
uint32_t flags = 0;
if (dValue < 0)
{
dValue = -dValue;
flags = 0x80000000;
}
// Round the input to a 15-digit integer. The R8 format has
// only 15 digits of precision, and we want to keep garbage digits
// out of the Decimal were making.
// Calculate max power of 10 input value could have by multiplying
// the exponent by log10(2). Using scaled integer multiplcation,
// log10(2) * 2 ^ 16 = .30103 * 65536 = 19728.3.
int32_t iPower = 14 - ((iExp * 19728) >> 16);
// iPower is between -14 and 43
if (iPower >= 0)
{
// We have less than 15 digits, scale input up.
if (iPower > 28)
iPower = 28;
dValue *= pow(10.0, iPower);
}
else
{
if ((iPower != -1) || (dValue >= 1E15))
dValue /= pow(10.0, -iPower);
else
iPower = 0; // didn't scale it
}
assert(dValue < 1E15);
if ((dValue < 1E14) && (iPower < 28))
{
dValue *= 10;
iPower++;
assert(dValue >= 1E14);
}
// Round to int64
uint64_t ulMant;
ulMant = (uint64_t)(int64_t)dValue;
dValue -= (int64_t)ulMant; // difference between input & integer
if ((dValue > 0.5) || ((dValue == 0.5) && ((ulMant & 1) != 0)))
ulMant++;
if (ulMant == 0)
{
// Mantissa is 0
memset((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), 0, 16);
return;
}
if (iPower < 0)
{
// Add -iPower factors of 10, -iPower <= (29 - 15) = 14
iPower = -iPower;
if (iPower < 10)
{
double pow10 = (double)powl(10.0, iPower);
uint64_t low64 = uint32x32((uint32_t)ulMant, (uint32_t)pow10);
uint64_t high64 = uint32x32((uint32_t)(ulMant >> 32), (uint32_t)pow10);
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (uint32_t)low64;
high64 += low64 >> 32;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4)) = (uint32_t)high64;
high64 >>= 32;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8)) = (uint32_t)high64;
}
else
{
// Have a big power of 10.
assert(iPower <= 14);
uint64_t low64;
uint32_t high32;
uint64x64(ulMant, (uint64_t)pow(10.0, iPower), low64, high32);
*((uint64_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = low64;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8)) = high32;
}
}
else
{
// Factor out powers of 10 to reduce the scale, if possible.
// The maximum number we could factor out would be 14. This
// comes from the fact we have a 15-digit number, and the
// MSD must be non-zero -- but the lower 14 digits could be
// zero. Note also the scale factor is never negative, so
// we can't scale by any more than the power we used to
// get the integer.
int lmax = iPower;
if (lmax > 14)
lmax = 14;
if ((((uint8_t)ulMant) == 0) && (lmax >= 8))
{
const uint32_t den = 100000000;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower -= 8;
lmax -= 8;
}
}
if ((((uint32_t)ulMant & 0xF) == 0) && (lmax >= 4))
{
const uint32_t den = 10000;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower -= 4;
lmax -= 4;
}
}
if ((((uint32_t)ulMant & 3) == 0) && (lmax >= 2))
{
const uint32_t den = 100;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower -= 2;
lmax -= 2;
}
}
if ((((uint32_t)ulMant & 1) == 0) && (lmax >= 1))
{
const uint32_t den = 10;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower--;
}
}
flags |= (uint32_t)iPower << 16;
*((uint64_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = ulMant;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8)) = 0;
}
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 12)) = flags;
}
private:
TBuffer& _buffer;
size_t _offset;
static uint64_t uint32x32(uint32_t a, uint32_t b) noexcept
{
return (uint64_t)a * (uint64_t)b;
}
static void uint64x64(uint64_t a, uint64_t b, uint64_t& low64, uint32_t& high32) noexcept
{
uint64_t low = uint32x32((uint32_t)a, (uint32_t)b);
uint64_t mid = uint32x32((uint32_t)a, (uint32_t)(b >> 32));
uint64_t high = uint32x32((uint32_t)(a >> 32), (uint32_t)(b >> 32));
high += (mid >> 32);
low += (mid <<= 32);
// Test for carry
if (low < mid)
high++;
mid = uint32x32((uint32_t)(a >> 32), (uint32_t)b);
high += (mid >> 32);
low += (mid <<= 32);
// Test for carry
if (low < mid)
high++;
if (high > 0xFFFFFFFFu)
{
low64 = 0;
high32 = 0;
}
low64 = low;
high32 = (uint32_t)high;
}
};
// Fast Binary Encoding field model UUID specialization
template <class TBuffer>
class FieldModel<TBuffer, uuid_t>
{
public:
FieldModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return 16; }
// Get the field extra size
size_t fbe_extra() const noexcept { return 0; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the UUID value is valid
bool verify() const noexcept { return true; }
// Get the UUID value
void get(uuid_t& value, uuid_t defaults = uuid_t::nil()) const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
{
value = defaults;
return;
}
std::memcpy(value.data().data(), (const uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), fbe_size());
}
// Set the UUID value
void set(uuid_t value) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
std::memcpy((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), value.data().data(), fbe_size());
}
private:
TBuffer& _buffer;
size_t _offset;
};
// Fast Binary Encoding field model bytes specialization
template <class TBuffer>
class FieldModel<TBuffer, buffer_t>
{
public:
FieldModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return 4; }
// Get the field extra size
size_t fbe_extra() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_bytes_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((fbe_bytes_offset == 0) || ((_buffer.offset() + fbe_bytes_offset + 4) > _buffer.size()))
return 0;
uint32_t fbe_bytes_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset));
return (size_t)(4 + fbe_bytes_size);
}
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the bytes value is valid
bool verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return true;
uint32_t fbe_bytes_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_bytes_offset == 0)
return true;
if ((_buffer.offset() + fbe_bytes_offset + 4) > _buffer.size())
return false;
uint32_t fbe_bytes_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset));
if ((_buffer.offset() + fbe_bytes_offset + 4 + fbe_bytes_size) > _buffer.size())
return false;
return true;
}
// Get the bytes value
size_t get(void* data, size_t size) const noexcept
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return 0;
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_bytes_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_bytes_offset == 0)
return 0;
assert(((_buffer.offset() + fbe_bytes_offset + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_bytes_offset + 4) > _buffer.size())
return 0;
uint32_t fbe_bytes_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset));
assert(((_buffer.offset() + fbe_bytes_offset + 4 + fbe_bytes_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_bytes_offset + 4 + fbe_bytes_size) > _buffer.size())
return 0;
size_t result = std::min(size, (size_t)fbe_bytes_size);
memcpy(data, (const char*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset + 4), result);
return result;
}
// Get the bytes value
template <size_t N>
size_t get(uint8_t (&data)[N]) const noexcept { return get(data, N); }
// Get the bytes value
template <size_t N>
size_t get(std::array<uint8_t, N>& data) const noexcept { return get(data.data(), data.size()); }
// Get the bytes value
void get(std::vector<uint8_t>& value) const noexcept
{
value.clear();
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
uint32_t fbe_bytes_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_bytes_offset == 0)
return;
assert(((_buffer.offset() + fbe_bytes_offset + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_bytes_offset + 4) > _buffer.size())
return;
uint32_t fbe_bytes_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset));
assert(((_buffer.offset() + fbe_bytes_offset + 4 + fbe_bytes_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_bytes_offset + 4 + fbe_bytes_size) > _buffer.size())
return;
const char* fbe_bytes = (const char*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset + 4);
value.assign(fbe_bytes, fbe_bytes + fbe_bytes_size);
}
// Get the bytes value
void get(buffer_t& value) const noexcept { get(value.buffer()); }
// Set the bytes value
void set(const void* data, size_t size)
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return;
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
uint32_t fbe_bytes_size = (uint32_t)size;
uint32_t fbe_bytes_offset = (uint32_t)(_buffer.allocate(4 + fbe_bytes_size) - _buffer.offset());
assert(((fbe_bytes_offset > 0) && ((_buffer.offset() + fbe_bytes_offset + 4 + fbe_bytes_size) <= _buffer.size())) && "Model is broken!");
if ((fbe_bytes_offset == 0) || ((_buffer.offset() + fbe_bytes_offset + 4 + fbe_bytes_size) > _buffer.size()))
return;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_bytes_offset;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset)) = fbe_bytes_size;
memcpy((char*)(_buffer.data() + _buffer.offset() + fbe_bytes_offset + 4), data, fbe_bytes_size);
}
// Set the bytes value
template <size_t N>
void set(const uint8_t (&data)[N]) { set(data, N); }
// Set the bytes value
template <size_t N>
void set(const std::array<uint8_t, N>& data) { set(data.data(), data.size()); }
// Set the bytes value
void set(const std::vector<uint8_t>& value) { set(value.data(), value.size()); }
// Set the bytes value
void set(const buffer_t& value) { set(value.buffer()); }
private:
TBuffer& _buffer;
size_t _offset;
};
// Fast Binary Encoding field model string specialization
template <class TBuffer>
class FieldModel<TBuffer, std::string>
{
public:
FieldModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return 4; }
// Get the field extra size
size_t fbe_extra() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_string_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((fbe_string_offset == 0) || ((_buffer.offset() + fbe_string_offset + 4) > _buffer.size()))
return 0;
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_string_offset));
return (size_t)(4 + fbe_string_size);
}
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the string value is valid
bool verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return true;
uint32_t fbe_string_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_string_offset == 0)
return true;
if ((_buffer.offset() + fbe_string_offset + 4) > _buffer.size())
return false;
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_string_offset));
if ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) > _buffer.size())
return false;
return true;
}
// Get the string value
size_t get(char* data, size_t size) const noexcept
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return 0;
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_string_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_string_offset == 0)
return 0;
assert(((_buffer.offset() + fbe_string_offset + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_string_offset + 4) > _buffer.size())
return 0;
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_string_offset));
assert(((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) > _buffer.size())
return 0;
size_t result = std::min(size, (size_t)fbe_string_size);
memcpy(data, (const char*)(_buffer.data() + _buffer.offset() + fbe_string_offset + 4), result);
return result;
}
// Get the string value
template <size_t N>
size_t get(char (&data)[N]) const noexcept { return get(data, N); }
// Get the string value
template <size_t N>
size_t get(std::array<char, N>& data) const noexcept { return get(data.data(), data.size()); }
// Get the string value
void get(std::string& value) const noexcept
{
value.clear();
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
uint32_t fbe_string_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + _offset));
if (fbe_string_offset == 0)
return;
assert(((_buffer.offset() + fbe_string_offset + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_string_offset + 4) > _buffer.size())
return;
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_string_offset));
assert(((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) > _buffer.size())
return;
value.assign((const char*)(_buffer.data() + _buffer.offset() + fbe_string_offset + 4), fbe_string_size);
}
// Get the string value
void get(std::string& value, const std::string& defaults) const noexcept
{
value = defaults;
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
uint32_t fbe_string_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + _offset));
if (fbe_string_offset == 0)
return;
assert(((_buffer.offset() + fbe_string_offset + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_string_offset + 4) > _buffer.size())
return;
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_string_offset));
assert(((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) > _buffer.size())
return;
value.assign((const char*)(_buffer.data() + _buffer.offset() + fbe_string_offset + 4), fbe_string_size);
}
// Set the string value
void set(const char* data, size_t size)
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return;
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
uint32_t fbe_string_size = (uint32_t)size;
uint32_t fbe_string_offset = (uint32_t)(_buffer.allocate(4 + fbe_string_size) - _buffer.offset());
assert(((fbe_string_offset > 0) && ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) <= _buffer.size())) && "Model is broken!");
if ((fbe_string_offset == 0) || ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) > _buffer.size()))
return;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_string_offset;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_string_offset)) = fbe_string_size;
memcpy((char*)(_buffer.data() + _buffer.offset() + fbe_string_offset + 4), data, fbe_string_size);
}
// Set the string value
template <size_t N>
void set(const char (&data)[N]) { set(data, N); }
// Set the string value
template <size_t N>
void set(const std::array<char, N>& data) { set(data.data(), data.size()); }
// Set the string value
void set(const std::string& value)
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
uint32_t fbe_string_size = (uint32_t)value.size();
uint32_t fbe_string_offset = (uint32_t)(_buffer.allocate(4 + fbe_string_size) - _buffer.offset());
assert(((fbe_string_offset > 0) && ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) <= _buffer.size())) && "Model is broken!");
if ((fbe_string_offset == 0) || ((_buffer.offset() + fbe_string_offset + 4 + fbe_string_size) > _buffer.size()))
return;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_string_offset;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_string_offset)) = fbe_string_size;
memcpy((char*)(_buffer.data() + _buffer.offset() + fbe_string_offset + 4), value.data(), fbe_string_size);
}
private:
TBuffer& _buffer;
size_t _offset;
};
// Fast Binary Encoding field model optional specialization
template <class TBuffer, typename T>
class FieldModel<TBuffer, std::optional<T>>
{
public:
FieldModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset), value(buffer, 0) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return 1 + 4; }
// Get the field extra size
size_t fbe_extra() const noexcept
{
if (!has_value())
return 0;
uint32_t fbe_optional_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 1));
if ((fbe_optional_offset == 0) || ((_buffer.offset() + fbe_optional_offset + 4) > _buffer.size()))
return 0;
_buffer.shift(fbe_optional_offset);
size_t fbe_result = value.fbe_size() + value.fbe_extra();
_buffer.unshift(fbe_optional_offset);
return fbe_result;
}
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
//! Is the value present?
explicit operator bool() const noexcept { return has_value(); }
// Checks if the object contains a value
bool has_value() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return false;
uint8_t fbe_has_value = *((const uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
return (fbe_has_value != 0);
}
// Check if the optional value is valid
bool verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return true;
uint8_t fbe_has_value = *((const uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_has_value == 0)
return true;
uint32_t fbe_optional_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 1));
if (fbe_optional_offset == 0)
return false;
_buffer.shift(fbe_optional_offset);
bool fbe_result = value.verify();
_buffer.unshift(fbe_optional_offset);
return fbe_result;
}
// Get the optional value (being phase)
size_t get_begin() const noexcept
{
if (!has_value())
return 0;
uint32_t fbe_optional_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 1));
assert((fbe_optional_offset > 0) && "Model is broken!");
if (fbe_optional_offset == 0)
return 0;
_buffer.shift(fbe_optional_offset);
return fbe_optional_offset;
}
// Get the optional value (end phase)
void get_end(size_t fbe_begin) const noexcept
{
_buffer.unshift(fbe_begin);
}
// Get the optional value
void get(std::optional<T>& opt, const std::optional<T>& defaults = std::nullopt) const noexcept
{
opt = defaults;
size_t fbe_begin = get_begin();
if (fbe_begin == 0)
return;
T temp = T();
value.get(temp);
opt.emplace(temp);
get_end(fbe_begin);
}
// Set the optional value (begin phase)
size_t set_begin(bool has_value)
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint8_t fbe_has_value = has_value ? 1 : 0;
*((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_has_value;
if (fbe_has_value == 0)
return 0;
uint32_t fbe_optional_size = (uint32_t)value.fbe_size();
uint32_t fbe_optional_offset = (uint32_t)(_buffer.allocate(fbe_optional_size) - _buffer.offset());
assert(((fbe_optional_offset > 0) && ((_buffer.offset() + fbe_optional_offset + fbe_optional_size) <= _buffer.size())) && "Model is broken!");
if ((fbe_optional_offset == 0) || ((_buffer.offset() + fbe_optional_offset + fbe_optional_size) > _buffer.size()))
return 0;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 1)) = fbe_optional_offset;
_buffer.shift(fbe_optional_offset);
return fbe_optional_offset;
}
// Set the optional value (end phase)
void set_end(size_t fbe_begin)
{
_buffer.unshift(fbe_begin);
}
// Set the optional value
void set(const std::optional<T>& opt)
{
size_t fbe_begin = set_begin(opt.has_value());
if (fbe_begin == 0)
return;
if (opt)
value.set(opt.value());
set_end(fbe_begin);
}
private:
TBuffer& _buffer;
size_t _offset;
public:
// Base field model value
FieldModel<TBuffer, T> value;
};
// Fast Binary Encoding field model array
template <class TBuffer, typename T, size_t N>
class FieldModelArray
{
public:
FieldModelArray(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset), _model(buffer, offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return N * _model.fbe_size(); }
// Get the field extra size
size_t fbe_extra() const noexcept { return 0; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Get the array
const uint8_t* data() const noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
return _buffer.data() + _buffer.offset() + fbe_offset();
}
// Get the array
uint8_t* data() noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
return _buffer.data() + _buffer.offset() + fbe_offset();
}
// Get the array offset
size_t offset() const noexcept { return 0; }
// Get the array size
size_t size() const noexcept { return N; }
// Array index operator
FieldModel<TBuffer, T> operator[](size_t index) const noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
assert((index < N) && "Index is out of bounds!");
FieldModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
fbe_model.fbe_shift(index * fbe_model.fbe_size());
return fbe_model;
}
// Check if the array is valid
bool verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return false;
FieldModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = N; i-- > 0;)
{
if (!fbe_model.verify())
return false;
fbe_model.fbe_shift(fbe_model.fbe_size());
}
return true;
}
// Get the array as C-array
template <size_t S>
void get(T (&values)[S]) const noexcept
{
auto fbe_model = (*this)[0];
for (size_t i = 0; (i < S) && (i < N); ++i)
{
fbe_model.get(values[i]);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Get the array as std::array
template <size_t S>
void get(std::array<T, S>& values) const noexcept
{
auto fbe_model = (*this)[0];
for (size_t i = 0; (i < S) && (i < N); ++i)
{
fbe_model.get(values[i]);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Get the array as std::vector
void get(std::vector<T>& values) const noexcept
{
values.clear();
values.reserve(N);
auto fbe_model = (*this)[0];
for (size_t i = N; i-- > 0;)
{
T value = T();
fbe_model.get(value);
values.emplace_back(value);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Set the array as C-array
template <size_t S>
void set(const T (&values)[S]) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = (*this)[0];
for (size_t i = 0; (i < S) && (i < N); ++i)
{
fbe_model.set(values[i]);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Set the array as std::array
template <size_t S>
void set(const std::array<T, S>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = (*this)[0];
for (size_t i = 0; (i < S) && (i < N); ++i)
{
fbe_model.set(values[i]);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Set the array as std::vector
void set(const std::vector<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = (*this)[0];
for (size_t i = 0; (i < values.size()) && (i < N); ++i)
{
fbe_model.set(values[i]);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
private:
TBuffer& _buffer;
size_t _offset;
FieldModel<TBuffer, T> _model;
};
// Fast Binary Encoding field model vector
template <class TBuffer, typename T>
class FieldModelVector
{
public:
FieldModelVector(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return 4; }
// Get the field extra size
size_t fbe_extra() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_vector_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((fbe_vector_offset == 0) || ((_buffer.offset() + fbe_vector_offset + 4) > _buffer.size()))
return 0;
uint32_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_vector_offset));
size_t fbe_result = 4;
FieldModel<TBuffer, T> fbe_model(_buffer, fbe_vector_offset + 4);
for (size_t i = fbe_vector_size; i-- > 0;)
{
fbe_result += fbe_model.fbe_size() + fbe_model.fbe_extra();
fbe_model.fbe_shift(fbe_model.fbe_size());
}
return fbe_result;
}
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Get the vector offset
size_t offset() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_vector_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
return fbe_vector_offset;
}
// Get the vector size
size_t size() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_vector_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((fbe_vector_offset == 0) || ((_buffer.offset() + fbe_vector_offset + 4) > _buffer.size()))
return 0;
uint32_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_vector_offset));
return fbe_vector_size;
}
// Vector index operator
FieldModel<TBuffer, T> operator[](size_t index) const noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
uint32_t fbe_vector_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
assert(((fbe_vector_offset > 0) && ((_buffer.offset() + fbe_vector_offset + 4) <= _buffer.size())) && "Model is broken!");
[[maybe_unused]] uint32_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_vector_offset));
assert((index < fbe_vector_size) && "Index is out of bounds!");
FieldModel<TBuffer, T> fbe_model(_buffer, fbe_vector_offset + 4);
fbe_model.fbe_shift(index * fbe_model.fbe_size());
return fbe_model;
}
// Resize the vector and get its first model
FieldModel<TBuffer, T> resize(size_t size)
{
FieldModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
uint32_t fbe_vector_size = (uint32_t)(size * fbe_model.fbe_size());
uint32_t fbe_vector_offset = (uint32_t)(_buffer.allocate(4 + fbe_vector_size) - _buffer.offset());
assert(((fbe_vector_offset > 0) && ((_buffer.offset() + fbe_vector_offset + 4) <= _buffer.size())) && "Model is broken!");
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_vector_offset;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_vector_offset)) = (uint32_t)size;
memset((char*)(_buffer.data() + _buffer.offset() + fbe_vector_offset + 4), 0, fbe_vector_size);
return FieldModel<TBuffer, T>(_buffer, fbe_vector_offset + 4);
}
// Check if the vector is valid
bool verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return true;
uint32_t fbe_vector_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_vector_offset == 0)
return true;
if ((_buffer.offset() + fbe_vector_offset + 4) > _buffer.size())
return false;
uint32_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_vector_offset));
FieldModel<TBuffer, T> fbe_model(_buffer, fbe_vector_offset + 4);
for (size_t i = fbe_vector_size; i-- > 0;)
{
if (!fbe_model.verify())
return false;
fbe_model.fbe_shift(fbe_model.fbe_size());
}
return true;
}
// Get the vector as std::vector
void get(std::vector<T>& values) const noexcept
{
values.clear();
size_t fbe_vector_size = size();
if (fbe_vector_size == 0)
return;
values.reserve(fbe_vector_size);
auto fbe_model = (*this)[0];
for (size_t i = fbe_vector_size; i-- > 0;)
{
T value = T();
fbe_model.get(value);
values.emplace_back(value);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Get the vector as std::list
void get(std::list<T>& values) const noexcept
{
values.clear();
size_t fbe_vector_size = size();
if (fbe_vector_size == 0)
return;
auto fbe_model = (*this)[0];
for (size_t i = fbe_vector_size; i-- > 0;)
{
T value = T();
fbe_model.get(value);
values.emplace_back(value);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Get the vector as std::set
void get(std::set<T>& values) const noexcept
{
values.clear();
size_t fbe_vector_size = size();
if (fbe_vector_size == 0)
return;
auto fbe_model = (*this)[0];
for (size_t i = fbe_vector_size; i-- > 0;)
{
T value = T();
fbe_model.get(value);
values.emplace(value);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Set the vector as std::vector
void set(const std::vector<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = resize(values.size());
for (const auto& value : values)
{
fbe_model.set(value);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Set the vector as std::list
void set(const std::list<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = resize(values.size());
for (const auto& value : values)
{
fbe_model.set(value);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
// Set the vector as std::set
void set(const std::set<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = resize(values.size());
for (const auto& value : values)
{
fbe_model.set(value);
fbe_model.fbe_shift(fbe_model.fbe_size());
}
}
private:
TBuffer& _buffer;
size_t _offset;
};
// Fast Binary Encoding field model map
template <class TBuffer, typename TKey, typename TValue>
class FieldModelMap
{
public:
FieldModelMap(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Get the field size
size_t fbe_size() const noexcept { return 4; }
// Get the field extra size
size_t fbe_extra() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_map_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((fbe_map_offset == 0) || ((_buffer.offset() + fbe_map_offset + 4) > _buffer.size()))
return 0;
uint32_t fbe_map_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_map_offset));
size_t fbe_result = 4;
FieldModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_map_offset + 4);
FieldModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_map_offset + 4 + fbe_model_key.fbe_size());
for (size_t i = fbe_map_size; i-- > 0;)
{
fbe_result += fbe_model_key.fbe_size() + fbe_model_key.fbe_extra();
fbe_model_key.fbe_shift(fbe_model_key.fbe_size() + fbe_model_value.fbe_size());
fbe_result += fbe_model_value.fbe_size() + fbe_model_value.fbe_extra();
fbe_model_value.fbe_shift(fbe_model_key.fbe_size() + fbe_model_value.fbe_size());
}
return fbe_result;
}
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Get the map offset
size_t offset() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_map_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
return fbe_map_offset;
}
// Get the map size
size_t size() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
uint32_t fbe_map_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((fbe_map_offset == 0) || ((_buffer.offset() + fbe_map_offset + 4) > _buffer.size()))
return 0;
uint32_t fbe_map_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_map_offset));
return fbe_map_size;
}
// Map index operator
std::pair<FieldModel<TBuffer, TKey>, FieldModel<TBuffer, TValue>> operator[](size_t index) const noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
uint32_t fbe_map_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
assert(((fbe_map_offset > 0) && ((_buffer.offset() + fbe_map_offset + 4) <= _buffer.size())) && "Model is broken!");
[[maybe_unused]] uint32_t fbe_map_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_map_offset));
assert((index < fbe_map_size) && "Index is out of bounds!");
FieldModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_map_offset + 4);
FieldModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_map_offset + 4 + fbe_model_key.fbe_size());
fbe_model_key.fbe_shift(index * (fbe_model_key.fbe_size() + fbe_model_value.fbe_size()));
fbe_model_value.fbe_shift(index * (fbe_model_key.fbe_size() + fbe_model_value.fbe_size()));
return std::make_pair(fbe_model_key, fbe_model_value);
}
// Resize the map and get its first model
std::pair<FieldModel<TBuffer, TKey>, FieldModel<TBuffer, TValue>> resize(size_t size)
{
FieldModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset());
FieldModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + fbe_model_key.fbe_size());
uint32_t fbe_map_size = (uint32_t)(size * (fbe_model_key.fbe_size() + fbe_model_value.fbe_size()));
uint32_t fbe_map_offset = (uint32_t)(_buffer.allocate(4 + fbe_map_size) - _buffer.offset());
assert(((fbe_map_offset > 0) && ((_buffer.offset() + fbe_map_offset + 4 + fbe_map_size) <= _buffer.size())) && "Model is broken!");
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_map_offset;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_map_offset)) = (uint32_t)size;
memset((char*)(_buffer.data() + _buffer.offset() + fbe_map_offset + 4), 0, fbe_map_size);
return std::make_pair(FieldModel<TBuffer, TKey>(_buffer, fbe_map_offset + 4), FieldModel<TBuffer, TValue>(_buffer, fbe_map_offset + 4 + fbe_model_key.fbe_size()));
}
// Check if the map is valid
bool verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return true;
uint32_t fbe_map_offset = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_map_offset == 0)
return true;
if ((_buffer.offset() + fbe_map_offset + 4) > _buffer.size())
return false;
uint32_t fbe_map_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_map_offset));
FieldModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_map_offset + 4);
FieldModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_map_offset + 4 + fbe_model_key.fbe_size());
for (size_t i = fbe_map_size; i-- > 0;)
{
if (!fbe_model_key.verify())
return false;
fbe_model_key.fbe_shift(fbe_model_key.fbe_size() + fbe_model_value.fbe_size());
if (!fbe_model_value.verify())
return false;
fbe_model_value.fbe_shift(fbe_model_key.fbe_size() + fbe_model_value.fbe_size());
}
return true;
}
// Get the map as std::map
void get(std::map<TKey, TValue>& values) const noexcept
{
values.clear();
size_t fbe_map_size = size();
if (fbe_map_size == 0)
return;
auto fbe_model = (*this)[0];
for (size_t i = fbe_map_size; i-- > 0;)
{
TKey key;
TValue value;
fbe_model.first.get(key);
fbe_model.second.get(value);
values.emplace(key, value);
fbe_model.first.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
fbe_model.second.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
}
}
// Get the map as std::unordered_map
void get(std::unordered_map<TKey, TValue>& values) const noexcept
{
values.clear();
size_t fbe_map_size = size();
if (fbe_map_size == 0)
return;
auto fbe_model = (*this)[0];
for (size_t i = fbe_map_size; i-- > 0;)
{
TKey key;
TValue value;
fbe_model.first.get(key);
fbe_model.second.get(value);
values.emplace(key, value);
fbe_model.first.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
fbe_model.second.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
}
}
// Set the map as std::map
void set(const std::map<TKey, TValue>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = resize(values.size());
for (const auto& value : values)
{
fbe_model.first.set(value.first);
fbe_model.first.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
fbe_model.second.set(value.second);
fbe_model.second.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
}
}
// Set the map as std::unordered_map
void set(const std::unordered_map<TKey, TValue>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return;
auto fbe_model = resize(values.size());
for (const auto& value : values)
{
fbe_model.first.set(value.first);
fbe_model.first.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
fbe_model.second.set(value.second);
fbe_model.second.fbe_shift(fbe_model.first.fbe_size() + fbe_model.second.fbe_size());
}
}
private:
TBuffer& _buffer;
size_t _offset;
};
// Fast Binary Encoding base final model
template <class TBuffer, typename T, typename TBase = T>
class FinalModelBase
{
public:
FinalModelBase(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
size_t fbe_allocation_size(T value) const noexcept { return fbe_size(); }
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Get the final size
size_t fbe_size() const noexcept { return sizeof(TBase); }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the value is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
return fbe_size();
}
// Get the field value
size_t get(T& value) const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
value = (T)(*((const TBase*)(_buffer.data() + _buffer.offset() + fbe_offset())));
return fbe_size();
}
// Set the field value
size_t set(T value) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
*((TBase*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (TBase)value;
return fbe_size();
}
private:
TBuffer& _buffer;
mutable size_t _offset;
};
// Fast Binary Encoding final model
template <class TBuffer, typename T>
class FinalModel : public FinalModelBase<TBuffer, T>
{
public:
using FinalModelBase<TBuffer, T>::FinalModelBase;
};
// Fast Binary Encoding final model bool specialization
template <class TBuffer>
class FinalModel<TBuffer, bool> : public FinalModelBase<TBuffer, bool, uint8_t>
{
public:
using FinalModelBase<TBuffer, bool, uint8_t>::FinalModelBase;
};
// Fast Binary Encoding final model char specialization
template <class TBuffer>
class FinalModel<TBuffer, char> : public FinalModelBase<TBuffer, char, uint8_t>
{
public:
using FinalModelBase<TBuffer, char, uint8_t>::FinalModelBase;
};
// Fast Binary Encoding final model wchar specialization
template <class TBuffer>
class FinalModel<TBuffer, wchar_t> : public FinalModelBase<TBuffer, wchar_t, uint32_t>
{
public:
using FinalModelBase<TBuffer, wchar_t, uint32_t>::FinalModelBase;
};
// Fast Binary Encoding final model decimal specialization
template <class TBuffer>
class FinalModel<TBuffer, decimal_t>
{
public:
FinalModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
size_t fbe_allocation_size(decimal_t value) const noexcept { return fbe_size(); }
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Get the final size
size_t fbe_size() const noexcept { return 16; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the decimal value is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
return fbe_size();
}
// Get the decimal value
size_t get(decimal_t& value) const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
// Value taken via reverse engineering the double that corresponds to 2^64
const double ds2to64 = 1.8446744073709552e+019;
// Read decimal parts
uint64_t low = *((const uint64_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
uint32_t high = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8));
uint32_t flags = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 12));
// Calculate decimal value
double dValue = ((double)low + (double)high * ds2to64) / pow(10.0, (uint8_t)(flags >> 16));
if (flags & 0x80000000)
dValue = -dValue;
value = dValue;
return fbe_size();
}
// Set the decimal value
size_t set(decimal_t value) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
// The most we can scale by is 10^28, which is just slightly more
// than 2^93. So a float with an exponent of -94 could just
// barely reach 0.5, but smaller exponents will always round to zero.
const uint32_t DBLBIAS = 1022;
// Get exponent value
double dValue = (double)value;
int32_t iExp = (int32_t)(((uint32_t)((*(uint64_t*)&dValue) >> 52) & 0x7FFu) - DBLBIAS);
if ((iExp < -94) || (iExp > 96))
{
// Value too big for .NET Decimal (exponent is limited to [-94, 96])
memset((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), 0, 16);
return fbe_size();
}
uint32_t flags = 0;
if (dValue < 0)
{
dValue = -dValue;
flags = 0x80000000;
}
// Round the input to a 15-digit integer. The R8 format has
// only 15 digits of precision, and we want to keep garbage digits
// out of the Decimal were making.
// Calculate max power of 10 input value could have by multiplying
// the exponent by log10(2). Using scaled integer multiplcation,
// log10(2) * 2 ^ 16 = .30103 * 65536 = 19728.3.
int32_t iPower = 14 - ((iExp * 19728) >> 16);
// iPower is between -14 and 43
if (iPower >= 0)
{
// We have less than 15 digits, scale input up.
if (iPower > 28)
iPower = 28;
dValue *= pow(10.0, iPower);
}
else
{
if ((iPower != -1) || (dValue >= 1E15))
dValue /= pow(10.0, -iPower);
else
iPower = 0; // didn't scale it
}
assert(dValue < 1E15);
if ((dValue < 1E14) && (iPower < 28))
{
dValue *= 10;
iPower++;
assert(dValue >= 1E14);
}
// Round to int64
uint64_t ulMant;
ulMant = (uint64_t)(int64_t)dValue;
dValue -= (int64_t)ulMant; // difference between input & integer
if ((dValue > 0.5) || ((dValue == 0.5) && ((ulMant & 1) != 0)))
ulMant++;
if (ulMant == 0)
{
// Mantissa is 0
memset((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), 0, 16);
return fbe_size();
}
if (iPower < 0)
{
// Add -iPower factors of 10, -iPower <= (29 - 15) = 14
iPower = -iPower;
if (iPower < 10)
{
double pow10 = (double)powl(10.0, iPower);
uint64_t low64 = uint32x32((uint32_t)ulMant, (uint32_t)pow10);
uint64_t high64 = uint32x32((uint32_t)(ulMant >> 32), (uint32_t)pow10);
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (uint32_t)low64;
high64 += low64 >> 32;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4)) = (uint32_t)high64;
high64 >>= 32;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8)) = (uint32_t)high64;
}
else
{
// Have a big power of 10.
assert(iPower <= 14);
uint64_t low64;
uint32_t high32;
uint64x64(ulMant, (uint64_t)pow(10.0, iPower), low64, high32);
*((uint64_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = low64;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8)) = high32;
}
}
else
{
// Factor out powers of 10 to reduce the scale, if possible.
// The maximum number we could factor out would be 14. This
// comes from the fact we have a 15-digit number, and the
// MSD must be non-zero -- but the lower 14 digits could be
// zero. Note also the scale factor is never negative, so
// we can't scale by any more than the power we used to
// get the integer.
int lmax = iPower;
if (lmax > 14)
lmax = 14;
if ((((uint8_t)ulMant) == 0) && (lmax >= 8))
{
const uint32_t den = 100000000;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower -= 8;
lmax -= 8;
}
}
if ((((uint32_t)ulMant & 0xF) == 0) && (lmax >= 4))
{
const uint32_t den = 10000;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower -= 4;
lmax -= 4;
}
}
if ((((uint32_t)ulMant & 3) == 0) && (lmax >= 2))
{
const uint32_t den = 100;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower -= 2;
lmax -= 2;
}
}
if ((((uint32_t)ulMant & 1) == 0) && (lmax >= 1))
{
const uint32_t den = 10;
uint64_t div = ulMant / den;
if ((uint32_t)ulMant == (uint32_t)(div * den))
{
ulMant = div;
iPower--;
}
}
flags |= (uint32_t)iPower << 16;
*((uint64_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = ulMant;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 8)) = 0;
}
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset() + 12)) = flags;
return fbe_size();
}
private:
TBuffer& _buffer;
mutable size_t _offset;
static uint64_t uint32x32(uint32_t a, uint32_t b) noexcept
{
return (uint64_t)a * (uint64_t)b;
}
static void uint64x64(uint64_t a, uint64_t b, uint64_t& low64, uint32_t& high32) noexcept
{
uint64_t low = uint32x32((uint32_t)a, (uint32_t)b);
uint64_t mid = uint32x32((uint32_t)a, (uint32_t)(b >> 32));
uint64_t high = uint32x32((uint32_t)(a >> 32), (uint32_t)(b >> 32));
high += (mid >> 32);
low += (mid <<= 32);
// Test for carry
if (low < mid)
high++;
mid = uint32x32((uint32_t)(a >> 32), (uint32_t)b);
high += (mid >> 32);
low += (mid <<= 32);
// Test for carry
if (low < mid)
high++;
if (high > 0xFFFFFFFFu)
{
low64 = 0;
high32 = 0;
}
low64 = low;
high32 = (uint32_t)high;
}
};
// Fast Binary Encoding final model UUID specialization
template <class TBuffer>
class FinalModel<TBuffer, uuid_t>
{
public:
FinalModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
size_t fbe_allocation_size(uuid_t value) const noexcept { return fbe_size(); }
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Get the final size
size_t fbe_size() const noexcept { return 16; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the UUID value is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
return fbe_size();
}
// Get the UUID value
size_t get(uuid_t& value) const noexcept
{
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
std::memcpy(value.data().data(), (const uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), fbe_size());
return fbe_size();
}
// Set the UUID value
size_t set(uuid_t value) noexcept
{
assert(((_buffer.offset() + fbe_offset() + fbe_size()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + fbe_size()) > _buffer.size())
return 0;
std::memcpy((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()), value.data().data(), fbe_size());
return fbe_size();
}
private:
TBuffer& _buffer;
mutable size_t _offset;
};
// Fast Binary Encoding final model bytes specialization
template <class TBuffer>
class FinalModel<TBuffer, buffer_t>
{
public:
FinalModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
size_t fbe_allocation_size(const void* data, size_t size) const noexcept { return 4 + size; }
template <size_t N>
size_t fbe_allocation_size(const uint8_t (&data)[N]) const noexcept { return 4 + N; }
template <size_t N>
size_t fbe_allocation_size(const std::array<uint8_t, N>& data) const noexcept { return 4 + N; }
size_t fbe_allocation_size(const std::vector<uint8_t>& value) const noexcept { return 4 + value.size(); }
size_t fbe_allocation_size(const buffer_t& value) const noexcept { return 4 + value.size(); }
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the bytes value is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
uint32_t fbe_bytes_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((_buffer.offset() + fbe_offset() + 4 + fbe_bytes_size) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
return 4 + fbe_bytes_size;
}
// Get the bytes value
size_t get(void* data, size_t size) const noexcept
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return 0;
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
uint32_t fbe_bytes_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
assert(((_buffer.offset() + fbe_offset() + 4 + fbe_bytes_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4 + fbe_bytes_size) > _buffer.size())
return 4;
size_t result = std::min(size, (size_t)fbe_bytes_size);
memcpy(data, (const char*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4), result);
return 4 + fbe_bytes_size;
}
// Get the bytes value
template <size_t N>
size_t get(uint8_t (&data)[N]) const noexcept { return get(data, N); }
// Get the bytes value
template <size_t N>
size_t get(std::array<uint8_t, N>& data) const noexcept { return get(data.data(), data.size()); }
// Get the bytes value
size_t get(std::vector<uint8_t>& value) const noexcept
{
value.clear();
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
uint32_t fbe_bytes_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
assert(((_buffer.offset() + fbe_offset() + 4 + fbe_bytes_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4 + fbe_bytes_size) > _buffer.size())
return 4;
const char* fbe_bytes = (const char*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4);
value.assign(fbe_bytes, fbe_bytes + fbe_bytes_size);
return 4 + fbe_bytes_size;
}
// Get the bytes value
size_t get(buffer_t& value) const noexcept { return get(value.buffer()); }
// Set the bytes value
size_t set(const void* data, size_t size)
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return 0;
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
uint32_t fbe_bytes_size = (uint32_t)size;
assert(((_buffer.offset() + fbe_offset() + 4 + fbe_bytes_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4 + fbe_bytes_size) > _buffer.size())
return 4;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_bytes_size;
memcpy((char*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4), data, fbe_bytes_size);
return 4 + fbe_bytes_size;
}
// Set the bytes value
template <size_t N>
size_t set(const uint8_t (&data)[N]) { return set(data, N); }
// Set the bytes value
template <size_t N>
size_t set(const std::array<uint8_t, N>& data) { return set(data.data(), data.size()); }
// Set the bytes value
size_t set(const std::vector<uint8_t>& value) { return set(value.data(), value.size()); }
// Set the bytes value
size_t set(const buffer_t& value) { return set(value.buffer()); }
private:
TBuffer& _buffer;
mutable size_t _offset;
};
// Fast Binary Encoding final model string specialization
template <class TBuffer>
class FinalModel<TBuffer, std::string>
{
public:
FinalModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
size_t fbe_allocation_size(const char* data, size_t size) const noexcept { return 4 + size; }
template <size_t N>
size_t fbe_allocation_size(const char (&data)[N]) const noexcept { return 4 + N; }
template <size_t N>
size_t fbe_allocation_size(const std::array<char, N>& data) const noexcept { return 4 + N; }
size_t fbe_allocation_size(const std::string& value) const noexcept { return 4 + value.size(); }
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the string value is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if ((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
return 4 + fbe_string_size;
}
// Get the string value
size_t get(char* data, size_t size) const noexcept
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return 0;
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
assert(((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) > _buffer.size())
return 4;
size_t result = std::min(size, (size_t)fbe_string_size);
memcpy(data, (const char*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4), result);
return 4 + fbe_string_size;
}
// Get the string value
template <size_t N>
size_t get(char (&data)[N]) const noexcept { return get(data, N); }
// Get the string value
template <size_t N>
size_t get(std::array<char, N>& data) const noexcept { return get(data.data(), data.size()); }
// Get the string value
size_t get(std::string& value) const noexcept
{
value.clear();
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
uint32_t fbe_string_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
assert(((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) > _buffer.size())
return 4;
value.assign((const char*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4), fbe_string_size);
return 4 + fbe_string_size;
}
// Set the string value
size_t set(const char* data, size_t size)
{
assert(((size == 0) || (data != nullptr)) && "Invalid buffer!");
if ((size > 0) && (data == nullptr))
return 0;
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
uint32_t fbe_string_size = (uint32_t)size;
assert(((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) > _buffer.size())
return 4;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_string_size;
memcpy((char*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4), data, fbe_string_size);
return 4 + fbe_string_size;
}
// Set the string value
template <size_t N>
size_t set(const char (&data)[N]) { return set(data, N); }
// Set the string value
template <size_t N>
size_t set(const std::array<char, N>& data) { return set(data.data(), data.size()); }
// Set the string value
size_t set(const std::string& value)
{
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
uint32_t fbe_string_size = (uint32_t)value.size();
assert(((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4 + fbe_string_size) > _buffer.size())
return 4;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_string_size;
memcpy((char*)(_buffer.data() + _buffer.offset() + fbe_offset() + 4), value.data(), fbe_string_size);
return 4 + fbe_string_size;
}
private:
TBuffer& _buffer;
mutable size_t _offset;
};
// Fast Binary Encoding final model optional specialization
template <class TBuffer, typename T>
class FinalModel<TBuffer, std::optional<T>>
{
public:
FinalModel(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset), value(buffer, 0) {}
// Get the allocation size
size_t fbe_allocation_size(const std::optional<T>& opt) const noexcept { return 1 + (opt ? value.fbe_allocation_size(opt.value()) : 0); }
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
//! Is the value present?
explicit operator bool() const noexcept { return has_value(); }
// Checks if the object contains a value
bool has_value() const noexcept
{
if ((_buffer.offset() + fbe_offset() + 1) > _buffer.size())
return false;
uint8_t fbe_has_value = *((const uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
return (fbe_has_value != 0);
}
// Check if the optional value is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + 1) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
uint8_t fbe_has_value = *((const uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_has_value == 0)
return 1;
_buffer.shift(fbe_offset() + 1);
size_t fbe_result = value.verify();
_buffer.unshift(fbe_offset() + 1);
return 1 + fbe_result;
}
// Get the optional value
size_t get(std::optional<T>& opt) const noexcept
{
opt = std::nullopt;
assert(((_buffer.offset() + fbe_offset() + 1) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 1) > _buffer.size())
return 0;
if (!has_value())
return 1;
_buffer.shift(fbe_offset() + 1);
T temp = T();
size_t size = value.get(temp);
opt.emplace(temp);
_buffer.unshift(fbe_offset() + 1);
return 1 + size;
}
// Set the optional value
size_t set(const std::optional<T>& opt)
{
assert(((_buffer.offset() + fbe_offset() + 1) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 1) > _buffer.size())
return 0;
uint8_t fbe_has_value = opt ? 1 : 0;
*((uint8_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = fbe_has_value;
if (fbe_has_value == 0)
return 1;
_buffer.shift(fbe_offset() + 1);
size_t size = 0;
if (opt)
size = value.set(opt.value());
_buffer.unshift(fbe_offset() + 1);
return 1 + size;
}
private:
TBuffer& _buffer;
mutable size_t _offset;
public:
// Base final model value
FinalModel<TBuffer, T> value;
};
// Fast Binary Encoding final model array
template <class TBuffer, typename T, size_t N>
class FinalModelArray
{
public:
FinalModelArray(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
template <size_t S>
size_t fbe_allocation_size(const T (&values)[S]) const noexcept
{
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < S) && (i < N); ++i)
size += fbe_model.fbe_allocation_size(values[i]);
return size;
}
template <size_t S>
size_t fbe_allocation_size(const std::array<T, S>& values) const noexcept
{
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < S) && (i < N); ++i)
size += fbe_model.fbe_allocation_size(values[i]);
return size;
}
size_t fbe_allocation_size(const std::vector<T>& values) const noexcept
{
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < values.size()) && (i < N); ++i)
size += fbe_model.fbe_allocation_size(values[i]);
return size;
}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the array is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset()) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = N; i-- > 0;)
{
size_t offset = fbe_model.verify();
if (offset == std::numeric_limits<std::size_t>::max())
return std::numeric_limits<std::size_t>::max();
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Get the array as C-array
template <size_t S>
size_t get(T (&values)[S]) const noexcept
{
assert(((_buffer.offset() + fbe_offset()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset()) > _buffer.size())
return 0;
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < S) && (i < N); ++i)
{
size_t offset = fbe_model.get(values[i]);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Get the array as std::array
template <size_t S>
size_t get(std::array<T, S>& values) const noexcept
{
assert(((_buffer.offset() + fbe_offset()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset()) > _buffer.size())
return 0;
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < S) && (i < N); ++i)
{
size_t offset = fbe_model.get(values[i]);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Get the array as std::vector
size_t get(std::vector<T>& values) const noexcept
{
values.clear();
assert(((_buffer.offset() + fbe_offset()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset()) > _buffer.size())
return 0;
values.reserve(N);
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = N; i-- > 0;)
{
T value = T();
size_t offset = fbe_model.get(value);
values.emplace_back(value);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Set the array as C-array
template <size_t S>
size_t set(const T (&values)[S]) noexcept
{
assert(((_buffer.offset() + fbe_offset()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset()) > _buffer.size())
return 0;
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < S) && (i < N); ++i)
{
size_t offset = fbe_model.set(values[i]);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Set the array as std::array
template <size_t S>
size_t set(const std::array<T, S>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset()) > _buffer.size())
return 0;
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < S) && (i < N); ++i)
{
size_t offset = fbe_model.set(values[i]);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Set the array as std::vector
size_t set(const std::vector<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset()) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset()) > _buffer.size())
return 0;
size_t size = 0;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset());
for (size_t i = 0; (i < values.size()) && (i < N); ++i)
{
size_t offset = fbe_model.set(values[i]);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
private:
TBuffer& _buffer;
mutable size_t _offset;
};
// Fast Binary Encoding final model vector
template <class TBuffer, typename T>
class FinalModelVector
{
public:
FinalModelVector(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
size_t fbe_allocation_size(const std::vector<T>& values) const noexcept
{
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (const auto& value : values)
size += fbe_model.fbe_allocation_size(value);
return size;
}
size_t fbe_allocation_size(const std::list<T>& values) const noexcept
{
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (const auto& value : values)
size += fbe_model.fbe_allocation_size(value);
return size;
}
size_t fbe_allocation_size(const std::set<T>& values) const noexcept
{
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (const auto& value : values)
size += fbe_model.fbe_allocation_size(value);
return size;
}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the vector is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
uint32_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (size_t i = fbe_vector_size; i-- > 0;)
{
size_t offset = fbe_model.verify();
if (offset == std::numeric_limits<std::size_t>::max())
return std::numeric_limits<std::size_t>::max();
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Get the vector as std::vector
size_t get(std::vector<T>& values) const noexcept
{
values.clear();
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
size_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_vector_size == 0)
return 4;
values.reserve(fbe_vector_size);
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (size_t i = fbe_vector_size; i-- > 0;)
{
T value = T();
size_t offset = fbe_model.get(value);
values.emplace_back(value);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Get the vector as std::list
size_t get(std::list<T>& values) const noexcept
{
values.clear();
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
size_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_vector_size == 0)
return 4;
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (size_t i = fbe_vector_size; i-- > 0;)
{
T value = T();
size_t offset = fbe_model.get(value);
values.emplace_back(value);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Get the vector as std::set
size_t get(std::set<T>& values) const noexcept
{
values.clear();
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
size_t fbe_vector_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_vector_size == 0)
return 4;
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (size_t i = fbe_vector_size; i-- > 0;)
{
T value = T();
size_t offset = fbe_model.get(value);
values.emplace(value);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Set the vector as std::vector
size_t set(const std::vector<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (uint32_t)values.size();
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (const auto& value : values)
{
size_t offset = fbe_model.set(value);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Set the vector as std::list
size_t set(const std::list<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (uint32_t)values.size();
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (const auto& value : values)
{
size_t offset = fbe_model.set(value);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
// Set the vector as std::set
size_t set(const std::set<T>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (uint32_t)values.size();
size_t size = 4;
FinalModel<TBuffer, T> fbe_model(_buffer, fbe_offset() + 4);
for (const auto& value : values)
{
size_t offset = fbe_model.set(value);
fbe_model.fbe_shift(offset);
size += offset;
}
return size;
}
private:
TBuffer& _buffer;
mutable size_t _offset;
};
// Fast Binary Encoding final model map
template <class TBuffer, typename TKey, typename TValue>
class FinalModelMap
{
public:
FinalModelMap(TBuffer& buffer, size_t offset) noexcept : _buffer(buffer), _offset(offset) {}
// Get the allocation size
size_t fbe_allocation_size(const std::map<TKey, TValue>& values) const noexcept
{
size_t size = 4;
FinalModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset() + 4);
FinalModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + 4);
for (const auto& value : values)
{
size += fbe_model_key.fbe_allocation_size(value.first);
size += fbe_model_value.fbe_allocation_size(value.second);
}
return size;
}
size_t fbe_allocation_size(const std::unordered_map<TKey, TValue>& values) const noexcept
{
size_t size = 4;
FinalModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset() + 4);
FinalModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + 4);
for (const auto& value : values)
{
size += fbe_model_key.fbe_allocation_size(value.first);
size += fbe_model_value.fbe_allocation_size(value.second);
}
return size;
}
// Get the field offset
size_t fbe_offset() const noexcept { return _offset; }
// Set the field offset
size_t fbe_offset(size_t offset) const noexcept { return _offset = offset; }
// Shift the current field offset
void fbe_shift(size_t size) noexcept { _offset += size; }
// Unshift the current field offset
void fbe_unshift(size_t size) noexcept { _offset -= size; }
// Check if the map is valid
size_t verify() const noexcept
{
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return std::numeric_limits<std::size_t>::max();
uint32_t fbe_map_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
size_t size = 4;
FinalModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset() + 4);
FinalModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + 4);
for (size_t i = fbe_map_size; i-- > 0;)
{
size_t offset_key = fbe_model_key.verify();
if (offset_key == std::numeric_limits<std::size_t>::max())
return std::numeric_limits<std::size_t>::max();
fbe_model_key.fbe_shift(offset_key);
fbe_model_value.fbe_shift(offset_key);
size += offset_key;
size_t offset_value = fbe_model_value.verify();
if (offset_value == std::numeric_limits<std::size_t>::max())
return std::numeric_limits<std::size_t>::max();
fbe_model_key.fbe_shift(offset_value);
fbe_model_value.fbe_shift(offset_value);
size += offset_value;
}
return size;
}
// Get the map as std::map
size_t get(std::map<TKey, TValue>& values) const noexcept
{
values.clear();
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
size_t fbe_map_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_map_size == 0)
return 4;
size_t size = 4;
FinalModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset() + 4);
FinalModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + 4);
for (size_t i = fbe_map_size; i-- > 0;)
{
TKey key;
TValue value;
size_t offset_key = fbe_model_key.get(key);
fbe_model_key.fbe_shift(offset_key);
fbe_model_value.fbe_shift(offset_key);
size_t offset_value = fbe_model_value.get(value);
fbe_model_key.fbe_shift(offset_value);
fbe_model_value.fbe_shift(offset_value);
values.emplace(key, value);
size += offset_key + offset_value;
}
return size;
}
// Get the map as std::unordered_map
size_t get(std::unordered_map<TKey, TValue>& values) const noexcept
{
values.clear();
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
size_t fbe_map_size = *((const uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset()));
if (fbe_map_size == 0)
return 4;
size_t size = 4;
FinalModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset() + 4);
FinalModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + 4);
for (size_t i = fbe_map_size; i-- > 0;)
{
TKey key;
TValue value;
size_t offset_key = fbe_model_key.get(key);
fbe_model_key.fbe_shift(offset_key);
fbe_model_value.fbe_shift(offset_key);
size_t offset_value = fbe_model_value.get(value);
fbe_model_key.fbe_shift(offset_value);
fbe_model_value.fbe_shift(offset_value);
values.emplace(key, value);
size += offset_key + offset_value;
}
return size;
}
// Set the map as std::map
size_t set(const std::map<TKey, TValue>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (uint32_t)values.size();
size_t size = 4;
FinalModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset() + 4);
FinalModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + 4);
for (const auto& value : values)
{
size_t offset_key = fbe_model_key.set(value.first);
fbe_model_key.fbe_shift(offset_key);
fbe_model_value.fbe_shift(offset_key);
size_t offset_value = fbe_model_value.set(value.second);
fbe_model_key.fbe_shift(offset_value);
fbe_model_value.fbe_shift(offset_value);
size += offset_key + offset_value;
}
return size;
}
// Set the map as std::unordered_map
size_t set(const std::unordered_map<TKey, TValue>& values) noexcept
{
assert(((_buffer.offset() + fbe_offset() + 4) <= _buffer.size()) && "Model is broken!");
if ((_buffer.offset() + fbe_offset() + 4) > _buffer.size())
return 0;
*((uint32_t*)(_buffer.data() + _buffer.offset() + fbe_offset())) = (uint32_t)values.size();
size_t size = 4;
FinalModel<TBuffer, TKey> fbe_model_key(_buffer, fbe_offset() + 4);
FinalModel<TBuffer, TValue> fbe_model_value(_buffer, fbe_offset() + 4);
for (const auto& value : values)
{
size_t offset_key = fbe_model_key.set(value.first);
fbe_model_key.fbe_shift(offset_key);
fbe_model_value.fbe_shift(offset_key);
size_t offset_value = fbe_model_value.set(value.second);
fbe_model_key.fbe_shift(offset_value);
fbe_model_value.fbe_shift(offset_value);
size += offset_key + offset_value;
}
return size;
}
private:
TBuffer& _buffer;
mutable size_t _offset;
};
// Fast Binary Encoding base sender
template <class TBuffer>
class Sender
{
public:
Sender(const Sender&) = default;
Sender(Sender&&) noexcept = default;
virtual ~Sender() = default;
Sender& operator=(const Sender&) = default;
Sender& operator=(Sender&&) noexcept = default;
// Get the sender buffer
TBuffer& buffer() noexcept { return *_buffer; }
const TBuffer& buffer() const noexcept { return *_buffer; }
// Get the final protocol flag
bool final() const noexcept { return _final; }
// Get the logging flag
bool logging() const noexcept { return _logging; }
// Enable/Disable logging
void logging(bool enable) noexcept { _logging = enable; }
// Reset the sender buffer
void reset() noexcept { _buffer->reset(); }
// Send serialized buffer.
// Direct call of the method requires knowledge about internals of FBE models serialization.
// Use it with care!
size_t send_serialized(size_t serialized)
{
assert((serialized > 0) && "Invalid size of the serialized buffer!");
if (serialized == 0)
return 0;
// Shift the send buffer
this->_buffer->shift(serialized);
// Send the value
size_t sent = onSend(this->_buffer->data(), this->_buffer->size());
this->_buffer->remove(0, sent);
return sent;
}
protected:
// Send message handler
virtual size_t onSend(const void* data, size_t size) = 0;
// Send log message handler
virtual void onSendLog(const std::string& message) const {}
protected:
std::shared_ptr<TBuffer> _buffer;
bool _logging;
bool _final;
Sender() : Sender(nullptr) {}
Sender(const std::shared_ptr<TBuffer>& buffer) : _logging(false), _final(false) { _buffer = buffer ? buffer : std::make_shared<TBuffer>(); }
// Enable/Disable final protocol
void final(bool enable) noexcept { _final = enable; }
};
// Fast Binary Encoding base receiver
template <class TBuffer>
class Receiver
{
public:
Receiver(const Receiver&) = default;
Receiver(Receiver&&) = default;
virtual ~Receiver() = default;
Receiver& operator=(const Receiver&) = default;
Receiver& operator=(Receiver&&) = default;
// Get the receiver buffer
TBuffer& buffer() noexcept { return *_buffer; }
const TBuffer& buffer() const noexcept { return *_buffer; }
// Get the final protocol flag
bool final() const noexcept { return _final; }
// Get the logging flag
bool logging() const noexcept { return _logging; }
// Enable/Disable logging
void logging(bool enable) noexcept { _logging = enable; }
// Reset the receiver buffer
void reset() noexcept { _buffer->reset(); }
// Receive data
void receive(const void* data, size_t size)
{
if (size == 0)
return;
assert((data != nullptr) && "Invalid buffer!");
if (data == nullptr)
return;
// Storage buffer
uint8_t* buffer1 = _buffer->data();
size_t offset0 = _buffer->offset();
size_t offset1 = _buffer->size();
size_t size1 = _buffer->size();
// Receive buffer
const uint8_t* buffer2 = (const uint8_t*)data;
size_t offset2 = 0;
size_t size2 = size;
// While receive buffer is available to handle...
while (offset2 < size2)
{
const uint8_t* message_buffer = nullptr;
size_t message_size = 0;
// Try to receive message size
bool message_size_copied = false;
bool message_size_found = false;
while (!message_size_found)
{
// Look into the storage buffer
if (offset0 < size1)
{
size_t count = std::min(size1 - offset0, (size_t)4);
if (count == 4)
{
message_size_copied = true;
message_size_found = true;
message_size = (size_t)(*((const uint32_t*)(buffer1 + offset0)));
offset0 += 4;
break;
}
else
{
// Fill remaining data from the receive buffer
if (offset2 < size2)
{
count = std::min(size2 - offset2, 4 - count);
// Allocate and refresh the storage buffer
_buffer->allocate(count);
buffer1 = _buffer->data();
size1 += count;
memcpy(buffer1 + offset1, buffer2 + offset2, count);
offset1 += count;
offset2 += count;
continue;
}
else
break;
}
}
// Look into the receive buffer
if (offset2 < size2)
{
size_t count = std::min(size2 - offset2, (size_t)4);
if (count == 4)
{
message_size_found = true;
message_size = (size_t)(*((const uint32_t*)(buffer2 + offset2)));
offset2 += 4;
break;
}
else
{
// Allocate and refresh the storage buffer
_buffer->allocate(count);
buffer1 = _buffer->data();
size1 += count;
memcpy(buffer1 + offset1, buffer2 + offset2, count);
offset1 += count;
offset2 += count;
continue;
}
}
else
break;
}
if (!message_size_found)
return;
// Check the message full size
size_t min_size = _final ? (4 + 4) : (4 + 4 + 4 + 4);
assert((message_size >= min_size) && "Invalid receive data!");
if (message_size < min_size)
return;
// Try to receive message body
bool message_found = false;
while (!message_found)
{
// Look into the storage buffer
if (offset0 < size1)
{
size_t count = std::min(size1 - offset0, message_size - 4);
if (count == (message_size - 4))
{
message_found = true;
message_buffer = buffer1 + offset0 - 4;
offset0 += message_size - 4;
break;
}
else
{
// Fill remaining data from the receive buffer
if (offset2 < size2)
{
// Copy message size into the storage buffer
if (!message_size_copied)
{
// Allocate and refresh the storage buffer
_buffer->allocate(4);
buffer1 = _buffer->data();
size1 += 4;
*((uint32_t*)(buffer1 + offset0)) = (uint32_t)message_size;
offset0 += 4;
offset1 += 4;
message_size_copied = true;
}
count = std::min(size2 - offset2, message_size - 4 - count);
// Allocate and refresh the storage buffer
_buffer->allocate(count);
buffer1 = _buffer->data();
size1 += count;
memcpy(buffer1 + offset1, buffer2 + offset2, count);
offset1 += count;
offset2 += count;
continue;
}
else
break;
}
}
// Look into the receive buffer
if (offset2 < size2)
{
size_t count = std::min(size2 - offset2, message_size - 4);
if (!message_size_copied && (count == (message_size - 4)))
{
message_found = true;
message_buffer = buffer2 + offset2 - 4;
offset2 += message_size - 4;
break;
}
else
{
// Copy message size into the storage buffer
if (!message_size_copied)
{
// Allocate and refresh the storage buffer
_buffer->allocate(4);
buffer1 = _buffer->data();
size1 += 4;
*((uint32_t*)(buffer1 + offset0)) = (uint32_t)message_size;
offset0 += 4;
offset1 += 4;
message_size_copied = true;
}
// Allocate and refresh the storage buffer
_buffer->allocate(count);
buffer1 = _buffer->data();
size1 += count;
memcpy(buffer1 + offset1, buffer2 + offset2, count);
offset1 += count;
offset2 += count;
continue;
}
}
else
break;
}
if (!message_found)
{
// Copy message size into the storage buffer
if (!message_size_copied)
{
// Allocate and refresh the storage buffer
_buffer->allocate(4);
buffer1 = _buffer->data();
size1 += 4;
*((uint32_t*)(buffer1 + offset0)) = (uint32_t)message_size;
offset0 += 4;
offset1 += 4;
message_size_copied = true;
}
return;
}
[[maybe_unused]] uint32_t fbe_struct_size;
uint32_t fbe_struct_type;
// Read the message parameters
if (_final)
{
fbe_struct_size = *((const uint32_t*)(message_buffer));
fbe_struct_type = *((const uint32_t*)(message_buffer + 4));
}
else
{
uint32_t fbe_struct_offset = *((const uint32_t*)(message_buffer + 4));
fbe_struct_size = *((const uint32_t*)(message_buffer + fbe_struct_offset));
fbe_struct_type = *((const uint32_t*)(message_buffer + fbe_struct_offset + 4));
}
// Handle the message
onReceive(fbe_struct_type, message_buffer, message_size);
// Reset the storage buffer
_buffer->reset();
// Refresh the storage buffer
buffer1 = _buffer->data();
offset0 = _buffer->offset();
offset1 = _buffer->size();
size1 = _buffer->size();
}
}
protected:
// Receive message handler
virtual bool onReceive(size_t type, const void* data, size_t size) = 0;
// Receive log message handler
virtual void onReceiveLog(const std::string& message) const {}
protected:
std::shared_ptr<TBuffer> _buffer;
bool _logging;
bool _final;
Receiver() : Receiver(nullptr) {}
Receiver(const std::shared_ptr<TBuffer>& buffer) : _logging(false), _final(false) { _buffer = buffer ? buffer : std::make_shared<TBuffer>(); }
// Enable/Disable final protocol
void final(bool enable) noexcept { _final = enable; }
};
namespace JSON {
template <class TWriter, typename T>
struct KeyWriter
{
static bool to_json_key(TWriter& writer, const T& key)
{
return writer.Key(std::to_string(key));
}
};
template <class TWriter, typename T>
bool to_json_key(TWriter& writer, const T& key)
{
return KeyWriter<TWriter, T>::to_json_key(writer, key);
}
template <class TWriter>
struct KeyWriter<TWriter, FBE::decimal_t>
{
static bool to_json_key(TWriter& writer, const FBE::decimal_t& key)
{
return writer.Key(key.string());
}
};
template <class TWriter>
struct KeyWriter<TWriter, FBE::uuid_t>
{
static bool to_json_key(TWriter& writer, const FBE::uuid_t& key)
{
return writer.Key(key.string());
}
};
template <class TWriter>
struct KeyWriter<TWriter, std::string>
{
static bool to_json_key(TWriter& writer, const std::string& key)
{
return writer.Key(key);
}
};
template <class TWriter, size_t N>
struct KeyWriter<TWriter, char[N]>
{
static bool to_json_key(TWriter& writer, const char (&key)[N])
{
return writer.Key(key, N - 1);
}
};
template <class TWriter, typename T>
struct ValueWriter
{
static bool to_json(TWriter& writer, const T& value, bool scope = true)
{
throw std::logic_error("Not implemented!");
}
};
template <class TWriter, typename T>
bool to_json(TWriter& writer, const T& value, bool scope = true)
{
return ValueWriter<TWriter, T>::to_json(writer, value, scope);
}
template <class TWriter>
struct ValueWriter<TWriter, bool>
{
static bool to_json(TWriter& writer, const bool& value, bool scope = true)
{
return writer.Bool(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, char>
{
static bool to_json(TWriter& writer, const char& value, bool scope = true)
{
return writer.Uint(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, wchar_t>
{
static bool to_json(TWriter& writer, const wchar_t& value, bool scope = true)
{
return writer.Uint(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, int8_t>
{
static bool to_json(TWriter& writer, const int8_t& value, bool scope = true)
{
return writer.Int(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, uint8_t>
{
static bool to_json(TWriter& writer, const uint8_t& value, bool scope = true)
{
return writer.Uint(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, int16_t>
{
static bool to_json(TWriter& writer, const int16_t& value, bool scope = true)
{
return writer.Int(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, uint16_t>
{
static bool to_json(TWriter& writer, const uint16_t& value, bool scope = true)
{
return writer.Uint(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, int32_t>
{
static bool to_json(TWriter& writer, const int32_t& value, bool scope = true)
{
return writer.Int(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, uint32_t>
{
static bool to_json(TWriter& writer, const uint32_t& value, bool scope = true)
{
return writer.Uint(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, int64_t>
{
static bool to_json(TWriter& writer, const int64_t& value, bool scope = true)
{
return writer.Int64(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, uint64_t>
{
static bool to_json(TWriter& writer, const uint64_t& value, bool scope = true)
{
return writer.Uint64(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, float>
{
static bool to_json(TWriter& writer, const float& value, bool scope = true)
{
return writer.Double(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, double>
{
static bool to_json(TWriter& writer, const double& value, bool scope = true)
{
return writer.Double(value);
}
};
template <class TWriter>
struct ValueWriter<TWriter, FBE::decimal_t>
{
static bool to_json(TWriter& writer, const FBE::decimal_t& value, bool scope = true)
{
return writer.String(value.string());
}
};
template <class TWriter>
struct ValueWriter<TWriter, FBE::uuid_t>
{
static bool to_json(TWriter& writer, const FBE::uuid_t& value, bool scope = true)
{
return writer.String(value.string());
}
};
template <class TWriter>
struct ValueWriter<TWriter, std::string>
{
static bool to_json(TWriter& writer, const std::string& value, bool scope = true)
{
return writer.String(value);
}
};
template <class TWriter, std::size_t N>
struct ValueWriter<TWriter, char[N]>
{
static bool to_json(TWriter& writer, const char (&value)[N], bool scope = true)
{
return writer.String(value, N);
}
};
template <class TWriter, typename T>
struct ValueWriter<TWriter, std::optional<T>>
{
static bool to_json(TWriter& writer, const std::optional<T>& value, bool scope = true)
{
if (value)
return ValueWriter<TWriter, T>::to_json(writer, value.value(), true);
else
return writer.Null();
}
};
template <class TWriter>
struct ValueWriter<TWriter, buffer_t>
{
static bool to_json(TWriter& writer, const buffer_t& values, bool scope = true)
{
return writer.String(values.base64encode());
}
};
template <class TWriter, typename T, size_t N>
struct ValueWriter<TWriter, std::array<T, N>>
{
static bool to_json(TWriter& writer, const std::array<T, N>& values, bool scope = true)
{
writer.StartArray();
for (const auto& value : values)
if (!ValueWriter<TWriter, T>::to_json(writer, value, true))
return false;
writer.EndArray();
return true;
}
};
template <class TWriter, typename T>
struct ValueWriter<TWriter, std::vector<T>>
{
static bool to_json(TWriter& writer, const std::vector<T>& values, bool scope = true)
{
writer.StartArray();
for (const auto& value : values)
if (!FBE::JSON::to_json(writer, value, true))
return false;
writer.EndArray();
return true;
}
};
template <class TWriter, typename T>
struct ValueWriter<TWriter, std::list<T>>
{
static bool to_json(TWriter& writer, const std::list<T>& values, bool scope = true)
{
writer.StartArray();
for (const auto& value : values)
if (!FBE::JSON::to_json(writer, value, true))
return false;
writer.EndArray();
return true;
}
};
template <class TWriter, typename T>
struct ValueWriter<TWriter, std::set<T>>
{
static bool to_json(TWriter& writer, const std::set<T>& values, bool scope = true)
{
writer.StartArray();
for (const auto& value : values)
if (!FBE::JSON::to_json(writer, value, true))
return false;
writer.EndArray();
return true;
}
};
template <class TWriter, typename TKey, typename TValue>
struct ValueWriter<TWriter, std::map<TKey, TValue>>
{
static bool to_json(TWriter& writer, const std::map<TKey, TValue>& values, bool scope = true)
{
writer.StartObject();
for (const auto& value : values)
{
if (!FBE::JSON::to_json_key(writer, value.first))
return false;
if (!FBE::JSON::to_json(writer, value.second, true))
return false;
}
writer.EndObject();
return true;
}
};
template <class TWriter, typename TKey, typename TValue>
struct ValueWriter<TWriter, std::unordered_map<TKey, TValue>>
{
static bool to_json(TWriter& writer, const std::unordered_map<TKey, TValue>& values, bool scope = true)
{
writer.StartObject();
for (const auto& value : values)
{
if (!FBE::JSON::to_json_key(writer, value.first))
return false;
if (!FBE::JSON::to_json(writer, value.second, true))
return false;
}
writer.EndObject();
return true;
}
};
template <class TJson, typename T>
struct ValueReader
{
static bool from_json(const TJson& json, T& value)
{
throw std::logic_error("Not implemented!");
}
};
template <class TJson, typename T>
bool from_json(const TJson& json, T& value)
{
return ValueReader<TJson, T>::from_json(json, value);
}
template <class TJson, typename T>
struct KeyReader
{
static bool from_json_key(const TJson& json, T& key)
{
std::string str;
if (!FBE::JSON::from_json(json, str))
return false;
std::istringstream(str) >> key;
return true;
}
};
template <class TJson, typename T>
bool from_json_key(const TJson& json, T& key)
{
return KeyReader<TJson, T>::from_json_key(json, key);
}
template <class TJson>
struct KeyReader<TJson, std::string>
{
static bool from_json_key(const TJson& json, std::string& key)
{
return FBE::JSON::from_json(json, key);
}
};
template <class TJson>
struct KeyReader<TJson, FBE::decimal_t>
{
static bool from_json_key(const TJson& json, FBE::decimal_t& key)
{
return FBE::JSON::from_json(json, key);
}
};
template <class TJson>
struct KeyReader<TJson, FBE::uuid_t>
{
static bool from_json_key(const TJson& json, FBE::uuid_t& key)
{
return FBE::JSON::from_json(json, key);
}
};
template <class TJson, size_t N>
struct KeyReader<TJson, char[N]>
{
static bool from_json_key(const TJson& json, char (&key)[N])
{
return FBE::JSON::from_json(json, key);
}
};
template <class TJson>
struct ValueReader<TJson, bool>
{
static bool from_json(const TJson& json, bool& value)
{
value = false;
// Schema validation
if (json.IsNull() || !json.IsBool())
return false;
// Save the value
value = json.GetBool();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, char>
{
static bool from_json(const TJson& json, char& value)
{
value = '\0';
// Schema validation
if (json.IsNull() || !json.IsUint())
return false;
// Save the value
value = (char)json.GetUint();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, wchar_t>
{
static bool from_json(const TJson& json, wchar_t& value)
{
value = L'\0';
// Schema validation
if (json.IsNull() || !json.IsUint())
return false;
// Save the value
value = (wchar_t)json.GetUint();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, int8_t>
{
static bool from_json(const TJson& json, int8_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsInt())
return false;
// Save the value
value = (int8_t)json.GetInt();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, uint8_t>
{
static bool from_json(const TJson& json, uint8_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsUint())
return false;
// Save the value
value = (uint8_t)json.GetUint();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, int16_t>
{
static bool from_json(const TJson& json, int16_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsInt())
return false;
// Save the value
value = (int16_t)json.GetInt();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, uint16_t>
{
static bool from_json(const TJson& json, uint16_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsUint())
return false;
// Save the value
value = (uint16_t)json.GetUint();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, int32_t>
{
static bool from_json(const TJson& json, int32_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsInt())
return false;
// Save the value
value = (int32_t)json.GetInt();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, uint32_t>
{
static bool from_json(const TJson& json, uint32_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsUint())
return false;
// Save the value
value = (uint32_t)json.GetUint();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, int64_t>
{
static bool from_json(const TJson& json, int64_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsInt64())
return false;
// Save the value
value = (int64_t)json.GetInt64();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, uint64_t>
{
static bool from_json(const TJson& json, uint64_t& value)
{
value = 0;
// Schema validation
if (json.IsNull() || !json.IsUint64())
return false;
// Save the value
value = (uint64_t)json.GetUint64();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, float>
{
static bool from_json(const TJson& json, float& value)
{
value = 0.0f;
// Schema validation
if (json.IsNull() || !(json.IsInt() || json.IsFloat()))
return false;
// Save the value
value = json.GetFloat();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, double>
{
static bool from_json(const TJson& json, double& value)
{
value = 0.0;
// Schema validation
if (json.IsNull() || !(json.IsInt() || json.IsDouble()))
return false;
// Save the value
value = json.GetDouble();
return true;
}
};
template <class TJson>
struct ValueReader<TJson, FBE::decimal_t>
{
static bool from_json(const TJson& json, FBE::decimal_t& value)
{
value = 0.0;
// Schema validation
if (json.IsNull() || !json.IsString())
return false;
// Save the value
try
{
std::string str(json.GetString(), (size_t)json.GetStringLength());
value = std::stod(str);
return true;
}
catch (...)
{
return false;
}
}
};
template <class TJson>
struct ValueReader<TJson, FBE::uuid_t>
{
static bool from_json(const TJson& json, FBE::uuid_t& value)
{
value = uuid_t::nil();
// Schema validation
if (json.IsNull() || !json.IsString())
return false;
// Save the value
try
{
std::string str(json.GetString(), (size_t)json.GetStringLength());
value = str;
return true;
}
catch (...)
{
return false;
}
}
};
template <class TJson>
struct ValueReader<TJson, std::string>
{
static bool from_json(const TJson& json, std::string& value)
{
value = "";
// Schema validation
if (json.IsNull() || !json.IsString())
return false;
// Save the value
value.assign(json.GetString(), (size_t)json.GetStringLength());
return true;
}
};
template <class TJson, size_t N>
struct ValueReader<TJson, char[N]>
{
static bool from_json(const TJson& json, char (&value)[N])
{
// Schema validation
if (json.IsNull() || !json.IsString())
return false;
// Save the value
size_t length = std::min((size_t)json.GetStringLength(), N);
std::memcpy(value, json.GetString(), length);
// Write the end of string character if possible
if (length < N)
value[length] = '\0';
return true;
}
};
template <class TJson, typename T>
struct ValueReader<TJson, std::optional<T>>
{
static bool from_json(const TJson& json, std::optional<T>& value)
{
value = std::nullopt;
// Empty optional value
if (json.IsNull())
return true;
// Try to get the value
T temp = T();
if (!FBE::JSON::from_json(json, temp))
return false;
// Save the value
value.emplace(temp);
return true;
}
};
template <class TJson>
struct ValueReader<TJson, buffer_t>
{
static bool from_json(const TJson& json, buffer_t& value)
{
// Schema validation
if (json.IsNull() || !json.IsString())
return false;
std::string str(json.GetString(), (size_t)json.GetStringLength());
value = buffer_t::base64decode(str);
return true;
}
};
template <class TJson, typename T, size_t N>
struct ValueReader<TJson, std::array<T, N>>
{
static bool from_json(const TJson& json, std::array<T, N>& values)
{
// Schema validation
if (json.IsNull() || !json.IsArray())
return false;
// Collect array items
size_t length = json.GetArray().Size();
for (size_t i = 0; (i < length) && (i < N); ++i)
if (!FBE::JSON::from_json(json.GetArray()[(rapidjson::SizeType)i], values[i]))
return false;
return true;
}
};
template <class TJson, typename T>
struct ValueReader<TJson, std::vector<T>>
{
static bool from_json(const TJson& json, std::vector<T>& values)
{
values.clear();
// Schema validation
if (json.IsNull() || !json.IsArray())
return false;
// Collect vector items
values.reserve(json.GetArray().Size());
for (const auto& item : json.GetArray())
{
T temp = T();
if (!FBE::JSON::from_json(item, temp))
return false;
values.emplace_back(temp);
}
return true;
}
};
template <class TJson, typename T>
struct ValueReader<TJson, std::list<T>>
{
static bool from_json(const TJson& json, std::list<T>& values)
{
values.clear();
// Schema validation
if (json.IsNull() || !json.IsArray())
return false;
// Collect list items
for (const auto& item : json.GetArray())
{
T temp = T();
if (!FBE::JSON::from_json(item, temp))
return false;
values.emplace_back(temp);
}
return true;
}
};
template <class TJson, typename T>
struct ValueReader<TJson, std::set<T>>
{
static bool from_json(const TJson& json, std::set<T>& values)
{
values.clear();
// Schema validation
if (json.IsNull() || !json.IsArray())
return false;
// Collect set items
for (const auto& item : json.GetArray())
{
T temp = T();
if (!FBE::JSON::from_json(item, temp))
return false;
values.emplace(temp);
}
return true;
}
};
template <class TJson, typename TKey, typename TValue>
struct ValueReader<TJson, std::map<TKey, TValue>>
{
static bool from_json(const TJson& json, std::map<TKey, TValue>& values)
{
values.clear();
// Schema validation
if (json.IsNull() || !json.IsObject())
return false;
// Collect map items
for (auto it = json.MemberBegin(); it != json.MemberEnd(); ++it)
{
TKey key;
TValue value;
if (!FBE::JSON::from_json_key(it->name, key))
return false;
if (!FBE::JSON::from_json(it->value, value))
return false;
values.emplace(key, value);
}
return true;
}
};
template <class TJson, typename TKey, typename TValue>
struct ValueReader<TJson, std::unordered_map<TKey, TValue>>
{
static bool from_json(const TJson& json, std::unordered_map<TKey, TValue>& values)
{
values.clear();
// Schema validation
if (json.IsNull() || !json.IsObject())
return false;
// Collect hash items
for (auto it = json.MemberBegin(); it != json.MemberEnd(); ++it)
{
TKey key;
TValue value;
if (!FBE::JSON::from_json_key(it->name, key))
return false;
if (!FBE::JSON::from_json(it->value, value))
return false;
values.emplace(key, value);
}
return true;
}
};
template <class TJson, typename T>
struct NodeReader
{
static bool from_json(const TJson& json, T& value, const char* key)
{
if (key == nullptr)
return false;
// Try to find a member with the given key
rapidjson::Value::ConstMemberIterator member = json.FindMember(key);
if (member == json.MemberEnd())
return false;
return FBE::JSON::from_json(member->value, value);
}
};
template <class TJson, typename T>
bool from_json(const TJson& json, T& value, const char* key)
{
return NodeReader<TJson, T>::from_json(json, value, key);
}
template <class TJson, typename T>
struct ChildNodeReader
{
static bool from_json_child(const TJson& json, T& value, const char* key)
{
if (key == nullptr)
return false;
// Try to find a member with the given key
rapidjson::Value::ConstMemberIterator member = json.FindMember(key);
if (member == json.MemberEnd())
return false;
// Schema validation
if (member->value.IsNull() || !member->value.IsObject())
return false;
// Deserialize the child object
return FBE::JSON::from_json(member->value.GetObject(), value);
}
};
template <class TJson, typename T>
bool from_json_child(const TJson& json, T& value, const char* key)
{
return ChildNodeReader<TJson, T>::from_json_child(json, value, key);
}
} // namespace JSON
} // namespace FBE
| 33.950782 | 171 | 0.585526 | [
"object",
"vector",
"model"
] |
4e2b172ec3543508cd697d02f5d5f17c430f51da | 997 | c | C | lib/guilds/spells/chaos/_dcs_cwe_lec.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/guilds/spells/chaos/_dcs_cwe_lec.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/guilds/spells/chaos/_dcs_cwe_lec.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | #define WARLOCK_D "/daemons/warlock_d"
//Chaos bludgeon
resolve(bonus, string target, caster_ob) {
object ob;
object who;
int souls;
if(!caster_ob)caster_ob=this_player();
who = this_player();
ob = present("warlock_weapon", caster_ob);
if(ob) {
tell_object(caster_ob, "You already have warlock weapon.\n");
return 1;
}
if(caster_ob->query_demon()) {
who = find_player(caster_ob->query_demon_master());
} else
souls = 100;
if(WARLOCK_D->query_souls(who->query_real_name()) < souls) {
tell_object(caster_ob, "You don't have enough souls sacrificed to cast this spell.\n");
return 1;
}
tell_object(caster_ob, "You call the void and receive a chaos bludgeon.\n");
tell_room(environment(caster_ob), caster_ob->query_name()+" calls the void and receives a chaos bludgeon.\n", ({ caster_ob }));
ob = clone_object("/guilds/warlock/obj/bludgeon");
move_object(ob, caster_ob);
ob->set_class(who->query_skills("knowledge of chaos")/10);
WARLOCK_D->reduce_souls(who->query_real_name(), souls);
return 1;
}
| 30.212121 | 127 | 0.744233 | [
"object"
] |
4e30ca1b379853a267410a90565ab4b9f872684c | 1,271 | h | C | src/Core/External/naoleague/featureextraction/img_processing.h | thaleshsp2/Mari | fd800261f3c9f7d207f35b82987ad31d9880dc1e | [
"MIT"
] | null | null | null | src/Core/External/naoleague/featureextraction/img_processing.h | thaleshsp2/Mari | fd800261f3c9f7d207f35b82987ad31d9880dc1e | [
"MIT"
] | null | null | null | src/Core/External/naoleague/featureextraction/img_processing.h | thaleshsp2/Mari | fd800261f3c9f7d207f35b82987ad31d9880dc1e | [
"MIT"
] | 1 | 2020-04-29T18:49:22.000Z | 2020-04-29T18:49:22.000Z | #ifndef IMG_PROCESSING_H
#define IMG_PROCESSING_H
#include <iostream>
#include <math.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <vector>
//#include <cv.h>
//#include <highgui.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define BACK_THRESHOLD 1
#define YEL_HUE_MIN 20
#define YEL_HUE_MAX 38
#define YEL_SAT_MIN 100
#define YEL_SAT_MAX 255
#define YEL_VAL_MIN 100
#define YEL_VAL_MAX 255
#define GR_HUE_MIN 38
#define GR_HUE_MAX 75
#define GR_SAT_MIN 50
#define GR_SAT_MAX 255
#define GR_VAL_MIN 50
#define GR_VAL_MAX 255
#define WH_HUE_MIN 0
#define WH_HUE_MAX 255
#define WH_SAT_MIN 0
#define WH_SAT_MAX 60
#define WH_VAL_MIN 200
#define WH_VAL_MAX 255
//using namespace cv;
using namespace std;
bool hsv_range(cv::Vec3b pixel, int h_min, int h_max, int s_min, int s_max, int v_min, int v_max);
void ass_val_pixel(cv::Vec3b &pixel, int h, int s, int v);
void ass_val_pixel2pixel(cv::Vec3b &src, cv::Vec3b &dst);
void remove_background(cv::Mat image, cv::Mat &lines, cv::Mat &posts, cv::Mat &ball, std::vector<cv::Point> &goalRoot, double* hor_hist, int* ver_hist);
double compute_white_ratio(cv::Mat image, cv::Point point1, cv::Point point2);
#endif
| 23.109091 | 152 | 0.75059 | [
"vector"
] |
4e312c646f2f4da2fcd492ac1eb5c17f68a2c396 | 2,370 | c | C | glibc/signal/tst-minsigstksz-2.c | chyidl/mirror-glibc | 3b17633afc85a9fb8cba0edc365d19403158c5a0 | [
"BSD-3-Clause"
] | null | null | null | glibc/signal/tst-minsigstksz-2.c | chyidl/mirror-glibc | 3b17633afc85a9fb8cba0edc365d19403158c5a0 | [
"BSD-3-Clause"
] | null | null | null | glibc/signal/tst-minsigstksz-2.c | chyidl/mirror-glibc | 3b17633afc85a9fb8cba0edc365d19403158c5a0 | [
"BSD-3-Clause"
] | null | null | null | /* Tests of signal delivery on an alternate stack (abort).
Copyright (C) 2019-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <support/xsignal.h>
#include <support/support.h>
#include <support/check.h>
#include <stdlib.h>
/* C2011 7.4.1.1p5 specifies that only the following operations are
guaranteed to be well-defined inside an asynchronous signal handler:
* any operation on a lock-free atomic object
* assigning a value to an object declared as volatile sig_atomic_t
* calling abort, _Exit, quick_exit, or signal
* signal may only be called with its first argument equal to the
number of the signal that caused the handler to be called
We use this list as a guideline for the set of operations that ought
also to be safe in a _synchronous_ signal delivered on an alternate
signal stack with only MINSIGSTKSZ bytes of space.
This test program tests calls to abort. Note that it does _not_
install a handler for SIGABRT, because that signal would also be
delivered on the alternate stack and MINSIGSTKSZ does not provide
enough space for delivery of nested signals. */
static void
handler (int unused)
{
abort ();
}
int
do_test (void)
{
void *sstk = xalloc_sigstack (0);
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_flags = SA_RESTART | SA_ONSTACK;
sigfillset (&sa.sa_mask);
if (sigaction (SIGUSR1, &sa, 0))
FAIL_RET ("sigaction (SIGUSR1, handler): %m\n");
raise (SIGUSR1);
xfree_sigstack (sstk);
FAIL_RET ("test process was not terminated by abort in signal handler");
}
#define EXPECTED_SIGNAL SIGABRT
#include <support/test-driver.c>
| 35.373134 | 74 | 0.735021 | [
"object"
] |
4e38c54fd2c53903627ef2311cb4653ae1d66086 | 1,859 | h | C | mindspore/ccsrc/minddata/mindrecord/include/shard_index.h | dongkcs/mindspore | cd7df6dbf463ff3128e9181e9d0c779cecb81320 | [
"Apache-2.0"
] | 2 | 2020-08-12T16:14:40.000Z | 2020-12-04T03:05:57.000Z | mindspore/ccsrc/minddata/mindrecord/include/shard_index.h | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | 1 | 2020-12-29T06:46:38.000Z | 2020-12-29T06:46:38.000Z | mindspore/ccsrc/minddata/mindrecord/include/shard_index.h | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | 1 | 2021-05-12T06:30:29.000Z | 2021-05-12T06:30:29.000Z | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINDSPORE_CCSRC_MINDDATA_MINDRECORD_INDEX_H
#define MINDSPORE_CCSRC_MINDDATA_MINDRECORD_INDEX_H
#pragma once
#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "minddata/mindrecord/include/common/shard_utils.h"
#include "minddata/mindrecord/include/shard_error.h"
#include "minddata/mindrecord/include/shard_schema.h"
#include "utils/log_adapter.h"
namespace mindspore {
namespace mindrecord {
using std::cin;
using std::endl;
using std::pair;
using std::string;
using std::vector;
class Index {
public:
Index();
~Index() {}
/// \brief Add field which from schema according to schemaId
/// \param[in] schemaId the id of schema to be added
/// \param[in] field the field need to be added
///
/// add the field to the fields_ vector
void AddIndexField(const int64_t &schemaId, const std::string &field);
/// \brief get stored fields
/// \return fields stored
std::vector<std::pair<uint64_t, std::string> > GetFields();
private:
std::vector<std::pair<uint64_t, std::string> > fields_;
string database_name_;
string table_name_;
};
} // namespace mindrecord
} // namespace mindspore
#endif // MINDSPORE_CCSRC_MINDDATA_MINDRECORD_INDEX_H
| 28.166667 | 75 | 0.741259 | [
"vector"
] |
4e3c3f5e898e07acf5251e867cf25b24c8f0a80c | 1,225 | h | C | src/Simulation_p.h | AronRubin/CxxSimulator_ | db9e50fbdafb47e697099234caac6504c42721fc | [
"MIT"
] | null | null | null | src/Simulation_p.h | AronRubin/CxxSimulator_ | db9e50fbdafb47e697099234caac6504c42721fc | [
"MIT"
] | null | null | null | src/Simulation_p.h | AronRubin/CxxSimulator_ | db9e50fbdafb47e697099234caac6504c42721fc | [
"MIT"
] | null | null | null | /**
* Simulation_p.h
* Simulation private interface with instances
*/
#ifndef SIMULATION_P_H_INCLUDED
#define SIMULATION_P_H_INCLUDED
#include <CxxSimulator/Simulator.h>
#include <CxxSimulator/Instance.h>
#include <CxxSimulator/Model.h>
#include <memory>
#include <functional>
#include <string>
#include <any>
#include <future>
namespace sim {
struct Simulation::Private {
static std::future<bool> insertResumeActivity(
std::shared_ptr<Simulation> simulation,
std::shared_ptr<Activity> activity,
const Clock::time_point &time );
static std::future<bool> activityWaitOn(
std::shared_ptr<Simulation> simulation,
std::shared_ptr<Activity> activity,
const std::string &signal_name,
const Clock::time_point &time = {} );
static std::future<bool> activityPadReceive(
std::shared_ptr<Simulation> simulation,
std::shared_ptr<Activity> activity,
const std::string &pad_name,
const Clock::time_point &time = {} );
static std::future<bool> padSend( std::shared_ptr<Simulation> simulation,
std::shared_ptr<Pad> pad,
const std::any &payload,
const Clock::time_point &time = {} );
};
} // namespace sim
#endif // SIMULATION_P_H_INCLUDED
| 27.222222 | 75 | 0.707755 | [
"model"
] |
4e3c72212c8515a76d7ce2b4eeec0cf1b542ebef | 2,681 | h | C | libs/DS4_SDK/include/dzbuttonbar.h | Red54/reality | 510d4f5fde2f4c5535482f1ea199f914102b8a2a | [
"BSD-3-Clause"
] | null | null | null | libs/DS4_SDK/include/dzbuttonbar.h | Red54/reality | 510d4f5fde2f4c5535482f1ea199f914102b8a2a | [
"BSD-3-Clause"
] | null | null | null | libs/DS4_SDK/include/dzbuttonbar.h | Red54/reality | 510d4f5fde2f4c5535482f1ea199f914102b8a2a | [
"BSD-3-Clause"
] | null | null | null | /**********************************************************************
Copyright (C) 2002-2012 DAZ 3D, Inc. All Rights Reserved.
This file is part of the DAZ Studio SDK.
This file may be used only in accordance with the DAZ Studio SDK
license provided with the DAZ Studio SDK.
The contents of this file may not be disclosed to third parties,
copied or duplicated in any form, in whole or in part, without the
prior written permission of DAZ 3D, Inc, except as explicitly
allowed in the DAZ Studio SDK license.
See http://www.daz3d.com to contact DAZ 3D or for more
information about the DAZ Studio SDK.
**********************************************************************/
/**
@sdk
@file
Defines the DzButtonBar class.
**/
#ifndef DAZ_BUTTON_BAR_H
#define DAZ_BUTTON_BAR_H
/*****************************
Include files
*****************************/
#include <QtGui/QAbstractButton>
#include "dzgeneraldefs.h"
/*****************************
Class definitions
*****************************/
class DZ_EXPORT DzButtonBar : public QWidget {
Q_OBJECT
public:
enum SeparatorType { Vertical, SlantRight, SlantLeft };
DzButtonBar( QWidget *parent = 0, const QString &name = QString::null );
virtual ~DzButtonBar();
void addWidget( QWidget *widget, int id = -1 );
void addSeparator( SeparatorType sep = Vertical, int id = -1 );
void hideItem( int id );
void showItem( int id );
virtual bool event( QEvent *e );
protected:
virtual void mousePressEvent( QMouseEvent *e );
virtual void mouseReleaseEvent( QMouseEvent *e );
virtual void paintEvent( QPaintEvent *e );
virtual void resizeEvent( QResizeEvent *e );
virtual void styleChange( QStyle &old );
private:
void updateMinSize();
void updateLayout();
void doLayout();
void createMask();
void activateButton( const QPoint &pos );
void activateButton( int which, const QPoint &pos );
struct Data;
Data *m_data;
};
class DZ_EXPORT DzBarButton : public QAbstractButton {
Q_OBJECT
public:
DzBarButton( QWidget *parent = 0, const QString &name = QString::null );
DzBarButton( const QPixmap &icon, QWidget *parent = 0, const QString &name = QString::null );
DzBarButton( const QIcon &icon, QWidget *parent = 0, const QString &name = QString::null );
virtual ~DzBarButton();
virtual void setIcon( const QPixmap &pix );
virtual void setIcon( const QIcon &icon );
protected:
virtual void paintEvent( QPaintEvent *e );
virtual void styleChange( QStyle &old );
private:
void updateMinSize();
struct Data;
Data *m_data;
};
#endif // DAZ_BUTTON_BAR_H
| 26.284314 | 95 | 0.627378 | [
"3d"
] |
4e42a2b43f8ded524e31be039050d069f0a6decb | 8,434 | h | C | simmotionpackage/include/simmotionpackage/Feedback_Control.h | TKUICLab-humanoid/gazebo_ws_submodule | 09881aace370b4a89f9c32d29ef2ba3ae1bf6344 | [
"MIT"
] | null | null | null | simmotionpackage/include/simmotionpackage/Feedback_Control.h | TKUICLab-humanoid/gazebo_ws_submodule | 09881aace370b4a89f9c32d29ef2ba3ae1bf6344 | [
"MIT"
] | null | null | null | simmotionpackage/include/simmotionpackage/Feedback_Control.h | TKUICLab-humanoid/gazebo_ws_submodule | 09881aace370b4a89f9c32d29ef2ba3ae1bf6344 | [
"MIT"
] | null | null | null | #ifndef FEEDBACK_CONTROL_H_
#define FEEDBACK_CONTROL_H_
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <fstream>
#include <vector>
#include <map>
#include <eigen3/Eigen/Dense>
#include "simmotionpackage/Inverse_kinematic.h"
#include "simmotionpackage/ZMPProcess.h"
#include "walkinggait/WalkingGaitByLIPM.hpp"
#include "tku_libs/TKU_tool.h"
class ZMPProcess;
using namespace std;
#define PI 3.1415926535897932384626433832795 //pi
#define PI_2 1.5707963267948966192313216916398 //pi/2
#define Angle_2_PI PI/180
#define PI_2_Angle 180/PI
#define DEGREE2RADIAN (M_PI / 180.0)
#define RADIAN2DEGREE (180.0/ M_PI)
/*******************Function Define******************************/
#define Auto_Gyro_offset
/********************************************************/
#define GRAVITATIONAL_ACCELERATION 9.8 //9.8(m/s^2)
#define ANKLE_HEIGHT 2.6 //2.6(cm)
#define COM_HEIGHT_TO_GROUND (COM_HEIGHT + ANKLE_HEIGHT)
// #define IMU_HEIGHT 7.462 //7.462(cm)
/////////////////////////Posture///////////////////////
#define Acc_offset_X 0
#define Acc_offset_Y 0
#define Acc_offset_Z 0
#define Gyro_manual_offset_X 0
#define Gyro_manual_offset_Y 0
#define Gyro_manual_offset_Z 0
#define kalman_manual_offset_Pitch 0
#define kalman_manual_offset_Roll 0
#define kalman_manual_offset_Yaw 0
#define Gyro_LSB_2_Angle 16.4
#define Acc_LSB_2_G 2048.0
#define index_Pitch 0
#define index_Roll 1
#define index_Yaw 2
#define Posture_Gain 0.3
////////////////////////////////////////////////////////
/////////////////////////Zmp Control///////////////////////
#define DOUBLE_FEET_WEIGHT_FAR_Y 10.5 //7.6 cm
#define DOUBLE_FEET_WEIGHT_NEAR_Y 3.0 //3.0 cm
#define DOUBLE_FEET_WEIGHT_X 7.15 //4.4 cm
#define DOUBLE_FEET_BALANCE_POINT_Y 4.5 //4.5 cm
#define SINGLE_FOOT_WEIGHT_FAR_Y 3.1 //3.1 cm
#define SINGLE_FOOT_WEIGHT_NEAR_Y 1.5 //1.5 cm
#define SINGLE_FOOT_WEIGHT_X 7.15 //4.4 cm
#define RIGHT_PRESS_SHIFT 4
#define SINGLE_FOOT_WEIGHT_EQUAL_Y 3.9
///////////////////////////////////////////////////////////
//////////////////////for Fall down & Get up/////////////////////////////
#define RPY_ROLL_LIMIT 1.133 //65 degree
#define RPY_PITCH_LIMIT 1.133 //65 degree
#define RPY_STAND_RANGE 0.52 //30 degree
enum class imu {roll = 0,pitch,yaw};
typedef enum {leftfoot = 0,rightfoot,doublefeet} etSupFoot;
class ButterWorthParam
{
public:
static ButterWorthParam set(float a1, float a2, float b1, float b2);
float a_[2];
float b_[2];
};
class ButterWorthFilter
{
public:
ButterWorthFilter();
~ButterWorthFilter();
void initialize(ButterWorthParam param);
float getValue(float present_value);
private:
ButterWorthParam param_;
float prev_output_;
float prev_value_;
};
class PID_Controller
{
public:
PID_Controller(float Kp, float Ki, float Kd);
PID_Controller();
~PID_Controller();
void initParam();
void setKpid(double Kp, double Ki, double Kd);
void setControlGoal(float x1c = 0, float x2c = 0, float x3c = 0);
void setValueLimit(float upper_limit, float lower_limit);
// void setDataValue(float value);
float calculateExpValue(float value);
float calculateExpValue_roll(float value);
float getError();
float getErrors();
float getErrord();
// void setErrorValue(float error);
// void setErrorsValue(float errors);
// void setErrordValue(float errord);
// float getFixValue();
private:
double Kp;
double Ki;
double Kd;
float error;
float pre_error;
float errors;
float errord;
float x1c;
float x2c;
float x3c;
float exp_value;
float value;
float pre_value;
float upper_limit;
float lower_limit;
};
typedef struct IMUParameter IMUParam;
struct IMUParameter
{
float pos;
float vel;
void initialize()
{
pos = 0;
vel = 0;
}
// float acc;
};
class SimIMUData
{
public:
double qx,qy,qz,qw,g_x,g_y,g_z,a_x,a_y,a_z;
double sensor_rpy[3];
float Roll = 0;
float Pitch = 0;
float Yaw = 0;
};
typedef struct BalanceParameter BalanceParam;
struct BalanceParameter
{
float control_value_total;
float control_value_once;
void initialize()
{
control_value_total = 0;
control_value_once = 0;
}
};
typedef struct ButterWorthIMUParameter ButterWorthIMUParam;
struct ButterWorthIMUParameter
{
ButterWorthFilter pos;
ButterWorthFilter vel;
void initialize()
{
pos.initialize(ButterWorthParam::set(1, -0.676819, 0.161590, 0.161590)); //fs = 33 , fc = 2, n = 1;
vel.initialize(ButterWorthParam::set(1, -0.676819, 0.161590, 0.161590)); //fs = 33 , fc = 2, n = 1;
}
};
class BalanceLowPassFilter
{
public:
BalanceLowPassFilter();
~BalanceLowPassFilter();
void initialize(double control_cycle_sec, double cut_off_frequency);
void set_cut_off_frequency(double cut_off_frequency);
double get_cut_off_frequency(void);
double get_filtered_output(double present_raw_value);
private:
double cut_off_freq_;
double control_cycle_sec_;
double alpha_;
double prev_output_;
};
class BalanceControl
{
public:
BalanceControl();
~BalanceControl();
struct timeval timer_start_, timer_end_;
double timer_dt_;
void initialize(const int control_cycle_msec);
void balance_control();
void get_sensor_value();
void control_after_ik_calculation();
//LIPM
void setSupportFoot();
void resetControlValue();
void endPointControl();
float calculateCOMPosbyLIPM(float pos_adj, float vel);
BalanceLowPassFilter roll_imu_lpf_;
BalanceLowPassFilter pitch_imu_lpf_;
double roll_imu_filtered_;
double pitch_imu_filtered_;
bool two_feet_grounded_;
bool roll_over_limit_;
bool pitch_over_limit_;
double cog_roll_offset_;
double cog_pitch_offset_;
double foot_cog_x_;
double foot_cog_y_;
etSupFoot sup_foot_, pre_sup_foot_;
IMUParam init_imu_value[3];
IMUParam pres_imu_value[3];
IMUParam prev_imu_value[3];
IMUParam ideal_imu_value[3];
IMUParam passfilter_pres_imu_value[3];
IMUParam passfilter_prev_imu_value[3];
ButterWorthIMUParam butterfilter_imu[3];
//hip
BalanceParam leftfoot_hip_roll_value;
BalanceParam leftfoot_hip_pitch_value;
BalanceParam rightfoot_hip_roll_value;
BalanceParam rightfoot_hip_pitch_value;
PID_Controller PIDleftfoot_hip_roll;
PID_Controller PIDleftfoot_hip_pitch;
PID_Controller PIDrightfoot_hip_roll;
PID_Controller PIDrightfoot_hip_pitch;
//ankle
BalanceParam leftfoot_ankle_roll_value;
BalanceParam leftfoot_ankle_pitch_value;
BalanceParam rightfoot_ankle_roll_value;
BalanceParam rightfoot_ankle_pitch_value;
PID_Controller PIDleftfoot_ankle_roll;
PID_Controller PIDleftfoot_ankle_pitch;
PID_Controller PIDrightfoot_ankle_roll;
PID_Controller PIDrightfoot_ankle_pitch;
BalanceParam leftfoot_EPx_value; //EP = End point
BalanceParam leftfoot_EPy_value;
BalanceParam rightfoot_EPx_value;
BalanceParam rightfoot_EPy_value;
PID_Controller PIDleftfoot_zmp_x;
PID_Controller PIDleftfoot_zmp_y;
PID_Controller PIDrightfoot_zmp_x;
PID_Controller PIDrightfoot_zmp_y;
BalanceParam CoM_EPx_value;
PID_Controller PIDCoM_x;
ZMPParam pres_ZMP;
ZMPParam prev_ZMP;
ZMPParam ideal_ZMP;
ZMPProcess *ZMP_process;
float leftfoot_hip_roll;
float leftfoot_hip_pitch;
float leftfoot_ankle_roll;
float leftfoot_ankle_pitch;
float rightfoot_hip_roll;
float rightfoot_hip_pitch;
float rightfoot_ankle_roll;
float rightfoot_ankle_pitch;
void saveData();
string DtoS(double value);
ToolInstance *tool;
double original_ik_point_rz_, original_ik_point_lz_;
std::map<std::string, float> map_param;
std::map<std::string, std::vector<float>> map_roll;
std::map<std::string, std::vector<float>> map_pitch;
std::map<std::string, std::vector<float>> map_ZMP;
std::map<std::string, std::vector<float>> map_CoM;
std::map<std::string, std::vector<float>> map_Accel;
int name_cont_;
};
#endif /*FEEDBACK_CONTROL_H_*/
| 27.206452 | 108 | 0.680934 | [
"vector"
] |
4e5127cf537e35697c9021266f4ce88c6a73b50d | 3,872 | h | C | pxr/usd/usd/typed.h | tsahee/USD | dc710925675f7f58f7a37f6c18d046a687b09271 | [
"Apache-2.0"
] | 1 | 2021-06-17T17:06:40.000Z | 2021-06-17T17:06:40.000Z | pxr/usd/usd/typed.h | tsahee/USD | dc710925675f7f58f7a37f6c18d046a687b09271 | [
"Apache-2.0"
] | null | null | null | pxr/usd/usd/typed.h | tsahee/USD | dc710925675f7f58f7a37f6c18d046a687b09271 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_USD_TYPED_H
#define PXR_USD_USD_TYPED_H
#include "pxr/pxr.h"
#include "pxr/usd/usd/api.h"
#include "pxr/usd/usd/schemaBase.h"
#include "pxr/usd/usd/prim.h"
#include "pxr/usd/usd/stage.h"
#include "pxr/base/tf/token.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class UsdTyped
///
/// The base class for all \em typed schemas (those that can impart a
/// typeName to a UsdPrim), and therefore the base class for all
/// instantiable and "IsA" schemas.
///
/// UsdTyped implements a typeName-based query for its override of
/// UsdSchemaBase::_IsCompatible(). It provides no other behavior.
///
class UsdTyped : public UsdSchemaBase
{
public:
/// Compile time constant representing what kind of schema this class is.
///
/// \sa UsdSchemaKind
static const UsdSchemaKind schemaKind = UsdSchemaKind::AbstractBase;
/// \deprecated
/// Same as schemaKind, provided to maintain temporary backward
/// compatibility with older generated schemas.
static const UsdSchemaKind schemaType = UsdSchemaKind::AbstractBase;
/// Construct a UsdTyped on UsdPrim \p prim .
/// Equivalent to UsdTyped::Get(prim.GetStage(), prim.GetPath())
/// for a \em valid \p prim, but will not immediately throw an error for
/// an invalid \p prim
explicit UsdTyped(const UsdPrim& prim=UsdPrim())
: UsdSchemaBase(prim)
{
}
/// Construct a UsdTyped on the prim wrapped by \p schemaObj .
/// Should be preferred over UsdTyped(schemaObj.GetPrim()),
/// as it preserves SchemaBase state.
explicit UsdTyped(const UsdSchemaBase& schemaObj)
: UsdSchemaBase(schemaObj)
{
}
USD_API
virtual ~UsdTyped();
/// Return a vector of names of all pre-declared attributes for this schema
/// class and all its ancestor classes. Does not include attributes that
/// may be authored by custom/extended methods of the schemas involved.
static const TfTokenVector &
GetSchemaAttributeNames(bool includeInherited=true) {
/* This only exists for consistency */
static TfTokenVector names;
return names;
}
/// Return a UsdTyped holding the prim adhering to this schema at \p path
/// on \p stage. If no prim exists at \p path on \p stage, or if the prim
/// at that path does not adhere to this schema, return an invalid schema
/// object. This is shorthand for the following:
///
/// \code
/// UsdTyped(stage->GetPrimAtPath(path));
/// \endcode
///
USD_API
static UsdTyped
Get(const UsdStagePtr &stage, const SdfPath &path);
protected:
USD_API
bool _IsCompatible() const override;
private:
USD_API
const TfType &_GetTfType() const override;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_USD_TYPED_H
| 33.37931 | 79 | 0.705579 | [
"object",
"vector"
] |
4e51a68f8fc4d0db2c8dafe326b32646436fb693 | 955 | h | C | src/pointer-analysis/object_numbering.h | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | null | null | null | src/pointer-analysis/object_numbering.h | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | 2 | 2018-02-14T16:11:37.000Z | 2018-02-23T18:12:27.000Z | src/pointer-analysis/object_numbering.h | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: Object Numbering
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
/// \file
/// Object Numbering
///
/// This is used to abbreviate identical expressions by number: for example,
/// an object_numberingt instance might maintain the map:
/// ```
/// 1 -> constant_exprt("Hello", string_typet())
/// 2 -> constant_exprt("World", string_typet())
/// ```
/// Then any users that agree to use the same object_numberingt instance as a
/// common reference source can use '1' and '2' as shorthands for "Hello" and
/// "World" respectively.
#ifndef CPROVER_POINTER_ANALYSIS_OBJECT_NUMBERING_H
#define CPROVER_POINTER_ANALYSIS_OBJECT_NUMBERING_H
#include <util/expr.h>
#include <util/numbering.h>
typedef hash_numbering<exprt, irep_hash> object_numberingt;
#endif // CPROVER_POINTER_ANALYSIS_OBJECT_NUMBERING_H
| 30.806452 | 77 | 0.646073 | [
"object"
] |
4e53c965d0abcabd21268c7e96360c26398f675e | 689 | h | C | Source/MassSample/Common/Traits/MSMoverMassTrait.h | Megafunk/MassSample | d4d2e343e8de87ed7fdff002700f8749acf0eb2f | [
"MIT"
] | 3 | 2022-03-23T04:34:49.000Z | 2022-03-26T15:05:36.000Z | Source/MassSample/Common/Traits/MSMoverMassTrait.h | Megafunk/MassSample | d4d2e343e8de87ed7fdff002700f8749acf0eb2f | [
"MIT"
] | 10 | 2022-03-19T15:25:52.000Z | 2022-03-28T07:59:27.000Z | Source/MassSample/Common/Traits/MSMoverMassTrait.h | Megafunk/MassSample | d4d2e343e8de87ed7fdff002700f8749acf0eb2f | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "MassEntityTraitBase.h"
#include "UObject/Object.h"
#include "MSMoverMassTrait.generated.h"
/**
* This trait uses 2 fragments. One to set the location of the entity, and another one to feed a constant force to add.
*/
UCLASS(meta = (DisplayName = "Sample Mover Trait"))
class MASSSAMPLE_API UMSMoverMassTrait : public UMassEntityTraitBase
{
GENERATED_BODY()
protected:
virtual void BuildTemplate(FMassEntityTemplateBuildContext& BuildContext, UWorld& World) const override;
UPROPERTY(EditAnywhere, Category = "Mass")
FVector Force = {0,0,100.0f};
};
| 27.56 | 119 | 0.767779 | [
"object"
] |
4e58cb882f2d81329e057e9dad9169e7f306b4ad | 470 | h | C | Remonttimies/Raytracing/Image.h | naavis/remonttimies | e155dfcb00a565bf0df666279ada8389ae852a0f | [
"Unlicense",
"MIT"
] | 1 | 2019-05-14T20:12:08.000Z | 2019-05-14T20:12:08.000Z | Remonttimies/Raytracing/Image.h | naavis/remonttimies | e155dfcb00a565bf0df666279ada8389ae852a0f | [
"Unlicense",
"MIT"
] | null | null | null | Remonttimies/Raytracing/Image.h | naavis/remonttimies | e155dfcb00a565bf0df666279ada8389ae852a0f | [
"Unlicense",
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <glm/glm.hpp>
class Image
{
public:
Image(unsigned int width, unsigned int height);
void SetPixel(unsigned int x, unsigned int y, glm::vec3 color);
glm::vec3 GetPixel(unsigned int x, unsigned int y) const;
unsigned int GetWidth() const;
unsigned int GetHeight() const;
float GetMaximumValue() const;
Image GetNormalized() const;
private:
unsigned int width;
unsigned int height;
std::vector<glm::vec3> imageContents;
}; | 24.736842 | 64 | 0.746809 | [
"vector"
] |
4e58d5949c3b978ed9464986c4e281b173b15844 | 5,175 | h | C | dev/bld/revision2018/contour/contour.h | gnilk/yapt | 1f1d7bad26fb477b545927774f323c367c0e1dad | [
"BSD-3-Clause"
] | null | null | null | dev/bld/revision2018/contour/contour.h | gnilk/yapt | 1f1d7bad26fb477b545927774f323c367c0e1dad | [
"BSD-3-Clause"
] | null | null | null | dev/bld/revision2018/contour/contour.h | gnilk/yapt | 1f1d7bad26fb477b545927774f323c367c0e1dad | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <math.h>
#include <map>
#include <vector>
#include "bitmap.h"
#include "vec2d.h"
#include "contour_internal.h"
namespace gnilk {
namespace contour {
class Block;
class BlockMap;
struct Config {
uint8_t GreyThresholdLevel;
float ClusterCutOffDistance;
float LineCutOffDistance;
float LineCutOffAngle;
float LongLineDistance;
float OptimizationCutOffAngle;
float ContrastFactor; // NOT USED
float ContrastScale; // NOT USED
int BlockSize;
float FilledBlockLevel;
int Width;
int Height;
bool Optimize;
bool Verbose;
};
class LineSegment {
private:
Point ptStart;
Point ptEnd;
int idxStart;
int idxEnd;
public:
LineSegment(Point _start, Point _end) {
ptStart = _start;
ptEnd = _end;
idxStart = -1;
idxEnd = -1;
}
LineSegment(Point _start, Point _end, int iStart, int iEnd) {
ptStart = _start;
ptEnd = _end;
idxStart = iStart;
idxEnd = iEnd;
}
Point Start() {
return ptStart;
}
Point End() {
return ptEnd;
}
Point *StartPtr() {
return &ptStart;
}
Point *EndPtr() {
return &ptEnd;
}
int IdxEnd() {
return idxEnd;
}
int IdxStart() {
return idxStart;
}
void SetStart(int x, int y) {
ptStart.Set(x,y);
}
void SetEnd(int x, int y) {
ptEnd.Set(x,y);
}
Vec2D *AsVector(Vec2D *dst) {
dst->x = (float)(ptEnd.x - ptStart.x);
dst->y = (float)(ptEnd.y - ptStart.y);
return dst;
}
float Len() {
Vec2D tmp;
return AsVector(&tmp)->Abs();
}
};
class ContourPoint {
private:
int pindex;
Point pt;
Block *block;
bool used;
public:
ContourPoint(int x, int y, Block *b);
int X() { return pt.x; }
int Y() { return pt.y; }
Point Pt() { return pt; }
bool IsUsed() { return used; }
void Use() { used = true; }
void ResetUsage() { used = false; }
int PIndex() { return pindex; }
void SetPIndex(int idx) { pindex = idx; }
Block *GetBlock() { return block; }
float Distance(ContourPoint *other);
};
class ContourCluster {
private:
std::vector<ContourPoint *> &points;
BlockMap *blockmap;
public:
ContourCluster(std::vector<ContourPoint *> &points, BlockMap *map);
std::vector<LineSegment *> ExtractVectors();
private:
LineSegment *NextSegment(int idxStart);
void CalcPointDistance(int pidx, std::vector<PointDistance *> &distances);
void LocalSearchPointDistance(int pidx, std::vector<PointDistance *> &distances);
void FullSearchPointDistance(int pidx, std::vector<PointDistance *> &distances);
LineSegment *NewLineSegment(int idxA, int idxB);
int Len() { return points.size(); }
ContourPoint *At(int idx) { return points[idx]; }
Vec2D *NewVector(int idxA, int idxB);
};
class Block {
private:
Bitmap *bitmap;
int x,y;
bool visited; // during scan
bool extracted; // during line extraction
public:
std::vector<ContourPoint *> points;
private:
int HashFunc(int x, int y);
uint8_t ReadGreyPixel(int x, int y);
float PixelAsFloat(int x, int y);
public:
Block(Bitmap *bitmap, int x, int y);
int Hash();
int Left();
int Right();
int Up();
int Down();
void Scan(std::vector<ContourPoint *> &pnts);
void CalcPointDistance(ContourPoint *cp, std::vector<PointDistance *> &distances);
bool IsVisited() { return visited; }
void Visit() { visited = true; }
bool IsExtracted() { return extracted; }
void SetExtracted() { extracted = true; }
int NumPoints() { return points.size(); }
};
class BlockMap {
private:
Bitmap *bitmap;
std::map<int, Block *> blocks;
void BuildBlocks();
public:
BlockMap(Bitmap *bitmap);
Block *GetBlock(int hashValue);
Block *Left(Block *block);
Block *Right(Block *block);
Block *Up(Block *block);
Block *Down(Block *block);
Block *GetBlockForExtraction(Block *previous = NULL);
void Scan(std::vector<ContourPoint *> &points, Block *b);
int NumBlocks() { return blocks.size(); }
std::vector<ContourPoint *> ExtractContourPoints();
private:
Block *GetBlockForExtractionRecursive(Block *previous);
};
class Trace {
private:
int intermediateWidth;
int intermediateHeight;
void SetDefaultConfig();
public:
Trace();
void ProcessImage(std::vector<Strip *> &optStrips, unsigned char *data, int width, int height);
void ProcessImageDebug(unsigned char *data, int width, int height);
private:
void OptimizeLineSegments(std::vector<LineSegment *> &newSegments, std::vector<LineSegment *> &lineSegments);
void RescaleLineSegments(std::vector<LineSegment *> &lineSegments, int w, int h);
int LineSegmentsToStrips(std::vector<Strip *> &strips, std::vector<LineSegment *> &lineSegments);
void DumpStrips(const char *title, std::vector<Strip *> &strips);
void WriteStrips(std::string filename, std::vector<Strip *> &strips);
Bitmap *DrawLineSegments(std::vector<LineSegment *> &lineSegments);
Bitmap *DrawCluster(std::vector<ContourPoint *> &points);
void DrawLine(Bitmap *dst, Point a, Point b, uint8_t cr, uint8_t cg, uint8_t cb);
};
}
} | 24.642857 | 112 | 0.652947 | [
"vector"
] |
4e590e2381954bb8d58add82a957e354d582567d | 1,960 | h | C | Morphs/Importers/Transcoders/Transcoders/Include/ExporterGLTF/ExporterGLTF.h | SergioRZMasson/BabylonPolymorph | 9def147959dc6292a36f9a2b055edf1d58cb2851 | [
"MIT"
] | 16 | 2020-01-09T13:36:46.000Z | 2021-11-16T10:09:54.000Z | Morphs/Importers/Transcoders/Transcoders/Include/ExporterGLTF/ExporterGLTF.h | SergioRZMasson/BabylonPolymorph | 9def147959dc6292a36f9a2b055edf1d58cb2851 | [
"MIT"
] | 30 | 2020-01-09T00:49:50.000Z | 2020-07-14T18:21:52.000Z | Morphs/Importers/Transcoders/Transcoders/Include/ExporterGLTF/ExporterGLTF.h | SergioRZMasson/BabylonPolymorph | 9def147959dc6292a36f9a2b055edf1d58cb2851 | [
"MIT"
] | 10 | 2020-04-09T14:10:29.000Z | 2022-03-18T09:18:40.000Z | /********************************************************
* *
* Copyright (C) Microsoft. All rights reserved. *
* *
********************************************************/
#pragma once
#include "Asset3D/Asset3D.h"
#include "PluginSDK/IOutputStreamFactory.h"
#include "GLTFSDK/IStreamWriter.h"
#include "ExporterGLTF/Asset3DToGLTFConverter.h"
namespace Babylon
{
namespace Transcoder
{
class GLTFExportOptions;
class ExporterGLTF
{
public:
static void ExportStatic(Asset3DPtr asset3D, std::string const& assetName, IOutputStreamFactory* streamFactory, FractionalProgressCallback progress = nullptr, Babylon::Framework::ICancellationTokenPtr cancellationToken = nullptr, const std::unordered_map<std::string, std::string>& options = {});
static void Export(const Asset3D& asset3d, std::unique_ptr<const Microsoft::glTF::IStreamWriter>&& streamWriter, const std::string& assetName, const GLTFExportOptions& options, Framework::ICancellationTokenPtr cancellationToken = nullptr);
};
class GLTFWriter : public IGLTFWriter
{
public:
GLTFWriter(const std::string& assetName, std::unique_ptr<const Microsoft::glTF::IStreamWriter>&& streamWriter);
void WriteImage(Microsoft::glTF::Document& document, const std::vector<uint8_t>& data,
const std::string& id, const std::string& mimeType, const std::string& extension) override;
void Finalize(Microsoft::glTF::Document& document, const Microsoft::glTF::ExtensionSerializer& extensionSerializer) override;
Microsoft::glTF::BufferBuilder& GetBufferBuilder() override { return m_bufferBuilder; }
private:
const std::string m_assetName;
Microsoft::glTF::BufferBuilder m_bufferBuilder;
};
}
}
| 42.608696 | 308 | 0.616327 | [
"vector"
] |
4e5a7f3cfd8491b65be676983c7bd6e2aa029ecf | 33,636 | c | C | src/zjs_ocf_client.c | jimmy-huang/zephyr.js | cef5c0dffaacf7d5aa3f8265626f68a1e2b32eb5 | [
"Apache-2.0"
] | null | null | null | src/zjs_ocf_client.c | jimmy-huang/zephyr.js | cef5c0dffaacf7d5aa3f8265626f68a1e2b32eb5 | [
"Apache-2.0"
] | null | null | null | src/zjs_ocf_client.c | jimmy-huang/zephyr.js | cef5c0dffaacf7d5aa3f8265626f68a1e2b32eb5 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2016-2018, Intel Corporation.
#ifdef BUILD_MODULE_OCF
// C includes
#ifdef ZJS_LINUX_BUILD
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#endif
// JerryScript includes
#include "jerryscript.h"
// OCF includes
#include "oc_api.h"
#include "port/oc_clock.h"
// ZJS includes
#include "zjs_common.h"
#include "zjs_event.h"
#include "zjs_ocf_client.h"
#include "zjs_ocf_common.h"
#include "zjs_ocf_encoder.h"
#include "zjs_util.h"
//#define USE_PROMISES
typedef enum {
RES_STATE_SEARCHING,
RES_STATE_FOUND
} resource_state;
#define FLAG_OBSERVE 1 << 0
#define FLAG_DISCOVERABLE 1 << 1
#define FLAG_SLOW 1 << 2
#define FLAG_SECURE 1 << 3
jerry_value_t ocf_client = 0;
struct client_resource {
char *device_id;
char *resource_path;
char *resource_type;
jerry_value_t types_array;
jerry_value_t iface_array;
oc_endpoint_t *endpoint;
resource_state state;
u32_t flags;
u32_t error_code;
struct client_resource *next;
};
struct ocf_handler {
jerry_value_t promise_obj;
struct client_resource *res;
};
static struct client_resource *resource_list = NULL;
static struct ocf_handler *new_ocf_handler(struct client_resource *res)
{
struct ocf_handler *h = zjs_malloc(sizeof(struct ocf_handler));
if (!h) {
ERR_PRINT("could not allocate OCF handle, out of memory\n");
return NULL;
}
memset(h, 0, sizeof(struct ocf_handler));
h->res = res;
return h;
}
static jerry_value_t make_ocf_error(const char *name, const char *msg,
struct client_resource *res)
{
if (res) {
ZVAL ret = zjs_create_object();
if (name) {
zjs_obj_add_string(ret, "name", name);
} else {
ERR_PRINT("error must have a name\n");
return ZJS_UNDEFINED;
}
if (msg) {
zjs_obj_add_string(ret, "message", msg);
} else {
ERR_PRINT("error must have a message\n");
return ZJS_UNDEFINED;
}
if (res->device_id) {
zjs_obj_add_string(ret, "deviceId", res->device_id);
}
if (res->resource_path) {
zjs_obj_add_string(ret, "resourcePath", res->resource_path);
}
zjs_obj_add_number(ret, "errorCode", (double)res->error_code);
return jerry_acquire_value(ret);
} else {
ERR_PRINT("client resource was NULL\n");
return ZJS_UNDEFINED;
}
}
/*
* Combine a UUID and path to form a URI
*/
static char *create_url(const char *uuid, const char *path)
{
// create URL of form oic://<uuid>/<path>
if (path[0] == '/') {
path++;
}
int url_len = strlen(uuid) + strlen(path) + 8;
char *url = zjs_malloc(url_len);
snprintf(url, url_len, "oic://%s/%s", uuid, path);
return url;
}
#ifdef DEBUG_BUILD
#define do_print \
do_prefix(p); \
ZJS_PRINT
static void do_prefix(int p)
{
int i;
for (i = 0; i < p; i++) {
ZJS_PRINT("\t");
}
}
static void print_props_data(int prefix, oc_rep_t *data)
{
int p = prefix;
int i;
oc_rep_t *rep = data;
while (rep != NULL) {
switch (rep->type) {
case BOOL:
do_print("%s: %d\n", oc_string(rep->name), rep->value.boolean);
break;
case INT:
do_print("%s: %d\n", oc_string(rep->name), rep->value.integer);
break;
case BYTE_STRING:
case STRING:
do_print("%s: %s\n", oc_string(rep->name),
oc_string(rep->value.string));
break;
case OBJECT:
do_print("%s: {\n", oc_string(rep->name));
print_props_data(p + 1, rep->value.object);
do_print("}\n");
break;
case STRING_ARRAY:
do_print("%s: [", oc_string(rep->name));
int sz = oc_string_array_get_allocated_size(rep->value.array);
for (i = 0; i < sz; i++) {
ZJS_PRINT("\"%s\",",
oc_string_array_get_item(rep->value.array, i));
}
ZJS_PRINT("]\n");
break;
case INT_ARRAY:
do_print("%s: [", oc_string(rep->name));
int *i_array = oc_int_array(rep->value.array);
for (i = 0; i < oc_int_array_size(rep->value.array); i++) {
ZJS_PRINT("%u,", i_array[i]);
}
ZJS_PRINT("]\n");
break;
case DOUBLE_ARRAY:
do_print("%s: [", oc_string(rep->name));
double *d_array = oc_double_array(rep->value.array);
for (i = 0; i < oc_double_array_size(rep->value.array); i++) {
ZJS_PRINT("%lf,", d_array[i]);
}
ZJS_PRINT("]\n");
break;
case BOOL_ARRAY:
do_print("%s: [", oc_string(rep->name));
bool *b_array = oc_bool_array(rep->value.array);
for (i = 0; i < oc_bool_array_size(rep->value.array); i++) {
ZJS_PRINT("%d,", b_array[i]);
}
ZJS_PRINT("]\n");
break;
case OBJECT_ARRAY: {
oc_rep_t *iter = rep->value.object_array;
do_print("%s: [", oc_string(rep->name));
p++;
while (iter) {
ZJS_PRINT("{\n");
print_props_data(p + 1, iter->value.object);
iter = iter->next;
do_print("}");
ZJS_PRINT(",");
}
ZJS_PRINT("\n");
p--;
do_print("]\n");
} break;
default:
break;
}
rep = rep->next;
}
}
#else
#define print_props_data(p, d) do {} while(0)
#endif
/*
* Find a client_resource by searching with a device ID
*/
static struct client_resource *find_resource_by_id(const char *device_id)
{
if (device_id) {
struct client_resource *cur = resource_list;
while (cur) {
if (cur->state != RES_STATE_SEARCHING) {
if (strequal(cur->device_id, device_id)) {
return cur;
}
}
cur = cur->next;
}
}
return NULL;
}
/*
* Create a new resource object
*/
static jerry_value_t create_resource(struct client_resource *client)
{
jerry_value_t resource = zjs_create_object();
if (client->device_id) {
zjs_obj_add_string(resource, "deviceId", client->device_id);
}
if (client->resource_path) {
zjs_obj_add_string(resource, "resourcePath", client->resource_path);
}
ZVAL props = zjs_create_object();
zjs_set_property(resource, "properties", props);
zjs_set_property(resource, "resourceTypes", client->types_array);
zjs_set_property(resource, "interfaces", client->iface_array);
DBG_PRINT("id=%s, path=%s, obj number=%x\n", client->device_id,
client->resource_path, resource);
return resource;
}
// a zjs_event_free callback
static void client_free_cb(void *native)
{
struct client_resource *cur = resource_list;
while (cur) {
if (cur->device_id) {
zjs_free(cur->device_id);
}
if (cur->resource_type) {
zjs_free(cur->resource_type);
}
if (cur->resource_path) {
zjs_free(cur->resource_path);
}
jerry_release_value(cur->types_array);
jerry_release_value(cur->iface_array);
resource_list = resource_list->next;
zjs_free(cur);
cur = resource_list;
}
}
/*
* Add a discovered resource to the list of resource_list
*/
static void add_resource(char *id, char *type, char *path,
jerry_value_t listener)
{
struct client_resource *new = zjs_malloc(sizeof(struct client_resource));
memset(new, 0, sizeof(struct client_resource));
new->state = RES_STATE_SEARCHING;
if (id) {
new->device_id = zjs_alloc_from_string(id, NULL);
}
if (type) {
new->resource_type = zjs_alloc_from_string(type, NULL);
}
if (path) {
new->resource_path = zjs_alloc_from_string(path, NULL);
}
if (jerry_value_is_function(listener)) {
zjs_add_event_listener(ocf_client, "resourcefound", listener);
}
new->next = resource_list;
resource_list = new;
}
/*
* Callback to observe
*/
static void observe_callback(oc_client_response_t *data)
{
if (data && data->user_data) {
struct client_resource *resource =
(struct client_resource *)data->user_data;
jerry_value_t resource_val = create_resource(resource);
ZVAL properties_val = zjs_ocf_decode_value(data->payload);
zjs_set_property(resource_val, "properties", properties_val);
zjs_defer_emit_event(ocf_client, "update", &resource_val,
sizeof(resource_val), zjs_copy_arg,
zjs_release_args);
#ifdef DEBUG_BUILD
print_props_data(0, data->payload);
#endif
}
}
/*
* Callback for resource discovery
*/
static oc_discovery_flags_t discovery(const char *di,
const char *uri,
oc_string_array_t types,
oc_interface_mask_t interfaces,
oc_endpoint_t *endpoint,
void *user_handle)
{
struct ocf_handler *h = (struct ocf_handler *)user_handle;
int i;
for (i = 0; i < oc_string_array_get_allocated_size(types); i++) {
char *t = oc_string_array_get_item(types, i);
struct client_resource *cur = resource_list;
while (cur) {
if (cur->state == RES_STATE_SEARCHING) {
// check if resource has any filter constraints
if (cur->device_id) {
if (strequal(cur->device_id, di)) {
goto Found;
} else {
goto NotFound;
}
}
if (cur->resource_type) {
if (strequal(cur->resource_type, t)) {
goto Found;
} else {
goto NotFound;
}
}
if (cur->resource_path) {
if (strequal(cur->resource_path, uri)) {
goto Found;
} else {
goto NotFound;
}
}
// TODO: If there are no filters what is supposed to happen?
goto NotFound;
} else {
NotFound:
cur = cur->next;
continue;
}
Found:
cur->state = RES_STATE_FOUND;
cur->endpoint = endpoint;
if (!cur->device_id) {
cur->device_id = zjs_alloc_from_string(di, NULL);
}
if (!cur->resource_path) {
// TODO: before this code was pretending to limit things to a
// MAX_URI_LENGTH of 30, but it wasn't working right anyway;
// not sure if there was a point to that
cur->resource_path = zjs_alloc_from_string(uri, NULL);
}
/*
* Add the array of resource types to newly discovered resource
*/
u32_t sz = oc_string_array_get_allocated_size(types);
cur->types_array = jerry_create_array(sz);
for (i = 0; i < sz; i++) {
char *t = oc_string_array_get_item(types, i);
ZVAL val = jerry_create_string(t);
jerry_set_property_by_index(cur->types_array, i, val);
}
/*
* Add array of interfaces
*/
sz = 0;
// count up set ifaces
for (i = 1; i < 8; ++i) {
if ((1 << i) & interfaces) {
sz++;
}
}
cur->iface_array = jerry_create_array(sz);
if (interfaces & OC_IF_BASELINE) {
ZVAL val = jerry_create_string("oic.if.baseline");
jerry_set_property_by_index(cur->iface_array, --sz, val);
}
if (interfaces & OC_IF_LL) {
ZVAL val = jerry_create_string("oic.if.ll");
jerry_set_property_by_index(cur->iface_array, --sz, val);
}
if (interfaces & OC_IF_B) {
ZVAL val = jerry_create_string("oic.if.b");
jerry_set_property_by_index(cur->iface_array, --sz, val);
}
if (interfaces & OC_IF_R) {
ZVAL val = jerry_create_string("oic.if.r");
jerry_set_property_by_index(cur->iface_array, --sz, val);
}
if (interfaces & OC_IF_RW) {
ZVAL val = jerry_create_string("oic.if.rw");
jerry_set_property_by_index(cur->iface_array, --sz, val);
}
if (interfaces & OC_IF_A) {
ZVAL val = jerry_create_string("oic.if.a");
jerry_set_property_by_index(cur->iface_array, --sz, val);
}
if (interfaces & OC_IF_S) {
ZVAL val = jerry_create_string("oic.if.s");
jerry_set_property_by_index(cur->iface_array, --sz, val);
}
// Work-around for #1332
// Pass duplicate resource to trigger event and promise
jerry_value_t res = create_resource(cur);
ZVAL res2 = create_resource(cur);
// FIXME: see if we can do without the second one now with the
// emit_event implementation
zjs_defer_emit_event(ocf_client, "resourcefound", &res,
sizeof(res), zjs_copy_arg, zjs_release_args);
jerry_resolve_or_reject_promise(h->promise_obj, res2, true);
jerry_release_value(h->promise_obj);
DBG_PRINT("resource found, id=%s, path=%s\n", cur->device_id,
cur->resource_path);
return OC_STOP_DISCOVERY;
}
}
oc_free_server_endpoints(endpoint);
return OC_CONTINUE_DISCOVERY;
}
static ZJS_DECL_FUNC(ocf_find_resources)
{
// args: options object
ZJS_VALIDATE_ARGS(Z_OPTIONAL Z_OBJECT, Z_OPTIONAL Z_FUNCTION);
char *resource_type = NULL;
char *device_id = NULL;
char *resource_path = NULL;
jerry_value_t listener = ZJS_UNDEFINED;
if (argc > 0 && !jerry_value_is_function(argv[0])) {
// has options parameter
ZVAL device_id_val = zjs_get_property(argv[0], "deviceId");
ZVAL res_type_val = zjs_get_property(argv[0], "resourceType");
ZVAL res_path_val = zjs_get_property(argv[0], "resourcePath");
if (jerry_value_is_string(device_id_val)) {
jerry_size_t size = OCF_MAX_DEVICE_ID_LEN;
device_id = zjs_alloc_from_jstring(device_id_val, &size);
if (device_id)
DBG_PRINT("deviceId: %s\n", device_id);
}
if (jerry_value_is_string(res_type_val)) {
jerry_size_t size = OCF_MAX_RES_TYPE_LEN;
resource_type = zjs_alloc_from_jstring(res_type_val, &size);
if (resource_type)
DBG_PRINT("resourceType: %s\n", resource_type);
}
if (jerry_value_is_string(res_path_val)) {
jerry_size_t size = OCF_MAX_RES_PATH_LEN;
resource_path = zjs_alloc_from_jstring(res_path_val, &size);
if (resource_path)
DBG_PRINT("resourcePath: %s\n", resource_path);
}
}
if (jerry_value_is_function(argv[0])) {
listener = argv[0];
} else if (argc >= 2 && jerry_value_is_function(argv[1])) {
listener = argv[1];
}
add_resource(device_id, resource_type, resource_path, listener);
if (device_id) {
zjs_free(device_id);
}
if (resource_path) {
zjs_free(resource_path);
}
jerry_value_t promise = jerry_create_promise();
struct ocf_handler *h = new_ocf_handler(NULL);
h->promise_obj = jerry_acquire_value(promise);
oc_do_ip_discovery(resource_type, discovery, h);
if (resource_type) {
zjs_free(resource_type);
}
return promise;
}
static void ocf_get_handler(oc_client_response_t *data)
{
if (data && data->user_data) {
struct ocf_handler *h = (struct ocf_handler *)data->user_data;
if (h && h->res) {
struct client_resource *resource = h->res;
if (data->code == OC_STATUS_OK) {
print_props_data(0, data->payload);
ZVAL resource_val = create_resource(resource);
ZVAL properties_val = zjs_ocf_decode_value(data->payload);
zjs_set_property(resource_val, "properties", properties_val);
jerry_resolve_or_reject_promise(h->promise_obj, resource_val,
true);
jerry_release_value(h->promise_obj);
DBG_PRINT("GET response OK, device_id=%s\n",
resource->device_id);
} else {
// Reject promise
/*
* TODO: change to use real errors
*/
ZVAL err = make_ocf_error("NetworkError", "Error code from GET",
resource);
jerry_resolve_or_reject_promise(h->promise_obj, err, false);
jerry_release_value(h->promise_obj);
ERR_PRINT("GET response code %d\n", data->code);
}
}
}
}
static ZJS_DECL_FUNC(ocf_retrieve)
{
// args: device id[, options][, listener]
ZJS_VALIDATE_ARGS(Z_STRING, Z_OPTIONAL Z_OBJECT, Z_OPTIONAL Z_FUNCTION);
jerry_value_t options = 0;
jerry_value_t listener = 0;
struct ocf_handler *h;
ZJS_GET_STRING(argv[0], device_id, OCF_MAX_DEVICE_ID_LEN + 1);
struct client_resource *resource = find_resource_by_id(device_id);
if (!resource) {
ERR_PRINT("could not find resource %s\n", device_id);
REJECT("NotFoundError", "resource was not found");
}
if (argc > 1) {
if (jerry_value_is_function(argv[1])) {
listener = argv[1];
} else {
options = argv[1];
if (argc > 2) {
listener = argv[2];
}
}
if (listener) {
zjs_add_event_listener(this, "update", listener);
}
}
if (options) {
ZVAL observe_flag = zjs_get_property(options, "observable");
if (jerry_value_is_boolean(observe_flag)) {
bool val = jerry_get_boolean_value(observe_flag);
if (val) {
resource->flags |= FLAG_OBSERVE;
}
}
ZVAL discover_flag = zjs_get_property(options, "discoverable");
if (jerry_value_is_boolean(discover_flag)) {
bool val = jerry_get_boolean_value(discover_flag);
if (val) {
resource->flags |= FLAG_DISCOVERABLE;
}
}
ZVAL secure_flag = zjs_get_property(options, "secure");
if (jerry_value_is_boolean(secure_flag)) {
bool val = jerry_get_boolean_value(secure_flag);
if (val) {
resource->flags |= FLAG_SECURE;
}
}
ZVAL slow_flag = zjs_get_property(options, "slow");
if (jerry_value_is_boolean(slow_flag)) {
bool val = jerry_get_boolean_value(slow_flag);
if (val) {
resource->flags |= FLAG_SLOW;
}
}
}
if (resource->flags & FLAG_OBSERVE) {
oc_do_observe(resource->resource_path, resource->endpoint, NULL,
&observe_callback, LOW_QOS, resource);
}
DBG_PRINT("resource found in lookup: path=%s, id=%s\n",
resource->resource_path, resource->device_id);
jerry_value_t promise = jerry_create_promise();
h = new_ocf_handler(resource);
h->res = resource;
h->promise_obj = jerry_acquire_value(promise);
if (!oc_do_get(resource->resource_path, resource->endpoint, NULL,
ocf_get_handler, LOW_QOS, h)) {
ZVAL err = make_ocf_error("NetworkError", "GET call failed", resource);
jerry_resolve_or_reject_promise(promise, err, false);
jerry_release_value(h->promise_obj);
}
return promise;
}
static void put_finished(oc_client_response_t *data)
{
if (data) {
struct ocf_handler *h = (struct ocf_handler *)data->user_data;
if (h->res) {
struct client_resource *resource = h->res;
h->res->error_code = data->code;
if (data->code == OC_STATUS_CHANGED) {
DBG_PRINT("PUT response OK, device_id=%s\n",
resource->device_id);
ZVAL resource_val = create_resource(resource);
jerry_resolve_or_reject_promise(h->promise_obj, resource_val,
true);
jerry_release_value(h->promise_obj);
} else {
ERR_PRINT("PUT response code %d\n", data->code);
ZVAL err = make_ocf_error("NetworkError",
"PUT response error code", resource);
jerry_resolve_or_reject_promise(h->promise_obj, err, false);
jerry_release_value(h->promise_obj);
}
}
}
}
static ZJS_DECL_FUNC(ocf_update)
{
// args: resource object
ZJS_VALIDATE_ARGS(Z_OBJECT);
struct ocf_handler *h;
// Get device ID property from resource
ZVAL device_id_val = zjs_get_property(argv[0], "deviceId");
ZJS_GET_STRING(device_id_val, device_id, OCF_MAX_DEVICE_ID_LEN + 1);
struct client_resource *resource = find_resource_by_id(device_id);
if (!resource) {
ERR_PRINT("could not find resource %s\n", device_id);
REJECT("NotFoundError", "resource was not found");
}
DBG_PRINT("update resource '%s'\n", resource->device_id);
jerry_value_t promise = jerry_create_promise();
h = new_ocf_handler(resource);
h->res = resource;
h->promise_obj = jerry_acquire_value(promise);
if (oc_init_put(resource->resource_path, resource->endpoint, NULL,
put_finished, LOW_QOS, h)) {
ZVAL props = zjs_get_property(argv[0], "properties");
zjs_ocf_encode_value(props);
if (!oc_do_put()) {
ERR_PRINT("error sending PUT request\n");
ZVAL err = make_ocf_error("NetworkError", "PUT call failed",
resource);
jerry_resolve_or_reject_promise(promise, err, false);
jerry_release_value(promise);
}
} else {
ERR_PRINT("error initializing PUT\n");
ZVAL err = make_ocf_error("NetworkError", "PUT init failed", resource);
jerry_resolve_or_reject_promise(promise, err, false);
jerry_release_value(promise);
}
return promise;
}
static void ocf_get_platform_info_handler(oc_client_response_t *data)
{
if (data && data->user_data) {
struct ocf_handler *h = (struct ocf_handler *)data->user_data;
jerry_value_t platform_info = zjs_create_object();
/*
* TODO: This while loop is repeated in several functions. It would be
* nice to have a universal way to do it but the properties that go
* OTA don't have the same names as the ones exposed in JavaScript.
* Perhaps changing this to be a function that takes a C callback
* which is called for each property.
*/
int i;
oc_rep_t *rep = data->payload;
while (rep != NULL) {
DBG_PRINT("Key: %s, Value: ", oc_string(rep->name));
switch (rep->type) {
case BOOL:
DBG_PRINT("%d\n", rep->value.boolean);
break;
case INT:
DBG_PRINT("%d\n", rep->value.integer);
break;
case BYTE_STRING:
case STRING:
if (strequal(oc_string(rep->name), "mnmn")) {
zjs_obj_add_readonly_string(platform_info,
"manufacturerName",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "pi")) {
zjs_obj_add_readonly_string(platform_info, "id",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "mnmo")) {
zjs_obj_add_readonly_string(platform_info, "model",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "mndt")) {
zjs_obj_add_readonly_string(platform_info,
"manufacturerDate",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "mnpv")) {
zjs_obj_add_readonly_string(platform_info,
"platformVersion",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "mnos")) {
zjs_obj_add_readonly_string(platform_info, "osVersion",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "mnfv")) {
zjs_obj_add_readonly_string(platform_info,
"firmwareVersion",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "mnml")) {
zjs_obj_add_readonly_string(platform_info,
"manufacturerURL",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "mnsl")) {
zjs_obj_add_readonly_string(platform_info, "supportURL",
oc_string(rep->value.string));
}
DBG_PRINT("%s\n", oc_string(rep->value.string));
break;
case STRING_ARRAY:
DBG_PRINT("[ ");
for (i = 0;
i < oc_string_array_get_allocated_size(rep->value.array);
i++) {
DBG_PRINT("%s ", oc_string_array_get_item(rep->value.array,
i));
}
DBG_PRINT("]\n");
break;
default:
break;
}
rep = rep->next;
}
zjs_defer_emit_event(ocf_client, "platformfound", &platform_info,
sizeof(platform_info), zjs_copy_arg,
zjs_release_args);
jerry_resolve_or_reject_promise(h->promise_obj, platform_info, true);
jerry_release_value(h->promise_obj);
}
}
static ZJS_DECL_FUNC(ocf_get_platform_info)
{
// args: device ide
ZJS_VALIDATE_ARGS(Z_STRING);
struct ocf_handler *h;
ZJS_GET_STRING(argv[0], device_id, OCF_MAX_DEVICE_ID_LEN + 1);
struct client_resource *resource = find_resource_by_id(device_id);
if (!resource) {
ERR_PRINT("%s: %s\n", "resource was not found", device_id);
REJECT("NotFoundError", "resource was not found");
}
jerry_value_t promise = jerry_create_promise();
h = new_ocf_handler(resource);
h->promise_obj = jerry_acquire_value(promise);
DBG_PRINT("sending GET to /oic/p\n");
if (!oc_do_get("/oic/p", resource->endpoint, NULL,
ocf_get_platform_info_handler, LOW_QOS, h)) {
jerry_value_t err = make_ocf_error("NetworkError", "GET call failed",
resource);
jerry_resolve_or_reject_promise(promise, err, false);
jerry_release_value(promise);
}
return promise;
}
static void ocf_get_device_info_handler(oc_client_response_t *data)
{
if (data && data->user_data) {
struct ocf_handler *h = (struct ocf_handler *)data->user_data;
struct client_resource *resource = h->res;
jerry_value_t device_info = zjs_create_object();
/*
* TODO: This while loop is repeated in several functions. It would be
* nice to have a universal way to do it but the properties that go
* OTA don't have the same names as the ones exposed in JavaScript.
* Perhaps changing this to be a function that takes a C callback
* which is called for each property.
*/
int i;
oc_rep_t *rep = data->payload;
while (rep != NULL) {
DBG_PRINT("Key: %s, Value: ", oc_string(rep->name));
switch (rep->type) {
case BOOL:
DBG_PRINT("%d\n", rep->value.boolean);
break;
case INT:
DBG_PRINT("%d\n", rep->value.integer);
break;
case BYTE_STRING:
case STRING:
if (strequal(oc_string(rep->name), "di")) {
zjs_obj_add_string(device_info, "uuid",
oc_string(rep->value.string));
/*
* TODO: Where do we get the devices path to construct the
* URL. For now, the existing resources path will be used,
* but this is incorrect, because there could be devices
* found that are not already in our list of resources.
*/
zjs_obj_add_string(device_info, "url",
create_url(oc_string(rep->value.string),
resource->resource_path));
} else if (strequal(oc_string(rep->name), "n")) {
zjs_obj_add_string(device_info, "name",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "icv")) {
zjs_obj_add_string(device_info, "coreSpecVersion",
oc_string(rep->value.string));
} else if (strequal(oc_string(rep->name), "dmv")) {
zjs_obj_add_string(device_info, "dataModels",
oc_string(rep->value.string));
}
DBG_PRINT("%s\n", oc_string(rep->value.string));
break;
case STRING_ARRAY:
DBG_PRINT("[ ");
for (i = 0;
i < oc_string_array_get_allocated_size(rep->value.array);
i++) {
DBG_PRINT("%s ", oc_string_array_get_item(rep->value.array,
i));
}
DBG_PRINT("]\n");
break;
default:
break;
}
rep = rep->next;
}
zjs_defer_emit_event(ocf_client, "devicefound", &device_info,
sizeof(device_info), zjs_copy_arg,
zjs_release_args);
jerry_resolve_or_reject_promise(h->promise_obj, device_info, true);
jerry_release_value(h->promise_obj);
}
}
static ZJS_DECL_FUNC(ocf_get_device_info)
{
// args: device id
ZJS_VALIDATE_ARGS(Z_STRING);
struct ocf_handler *h;
ZJS_GET_STRING(argv[0], device_id, OCF_MAX_DEVICE_ID_LEN + 1);
struct client_resource *resource = find_resource_by_id(device_id);
if (!resource) {
ERR_PRINT("%s: %s\n", "resource was not found", device_id);
REJECT("NotFoundError", "resource was not found");
}
jerry_value_t promise = jerry_create_promise();
h = new_ocf_handler(resource);
h->promise_obj = jerry_acquire_value(promise);
DBG_PRINT("sending GET to /oic/d\n");
if (!oc_do_get("/oic/d", resource->endpoint, NULL,
&ocf_get_device_info_handler, LOW_QOS, h)) {
ZVAL err = make_ocf_error("NetworkError", "GET call failed", resource);
jerry_resolve_or_reject_promise(promise, err, false);
jerry_release_value(promise);
}
return promise;
}
jerry_value_t zjs_ocf_client_init()
{
// create Client API object
if (ocf_client) {
return jerry_acquire_value(ocf_client);
}
ocf_client = zjs_create_object();
zjs_obj_add_function(ocf_client, "findResources", ocf_find_resources);
zjs_obj_add_function(ocf_client, "retrieve", ocf_retrieve);
zjs_obj_add_function(ocf_client, "update", ocf_update);
zjs_obj_add_function(ocf_client, "getPlatformInfo", ocf_get_platform_info);
zjs_obj_add_function(ocf_client, "getDeviceInfo", ocf_get_device_info);
zjs_make_emitter(ocf_client, ZJS_UNDEFINED, NULL, client_free_cb);
return jerry_acquire_value(ocf_client);
}
void zjs_ocf_client_cleanup()
{
// the ocf client object going out of scope will clean up everything
jerry_release_value(ocf_client);
ocf_client = 0;
}
#endif // BUILD_MODULE_OCF
| 34.392638 | 80 | 0.548876 | [
"object",
"model"
] |
4e5d0a72594b67f2e36fed04e9d50331157b6d26 | 801 | h | C | src/postProcessManager.h | FaramosCZ/SeriousProton | 6ac1245d787a3937ffc7d552a764123026ae3b1f | [
"MIT"
] | null | null | null | src/postProcessManager.h | FaramosCZ/SeriousProton | 6ac1245d787a3937ffc7d552a764123026ae3b1f | [
"MIT"
] | null | null | null | src/postProcessManager.h | FaramosCZ/SeriousProton | 6ac1245d787a3937ffc7d552a764123026ae3b1f | [
"MIT"
] | null | null | null | #ifndef POST_PROCESS_MANAGER_H
#define POST_PROCESS_MANAGER_H
#include <SFML/Graphics.hpp>
#include "stringImproved.h"
#include "Updatable.h"
#include "Renderable.h"
class PostProcessor : public RenderChain
{
private:
sf::Shader shader;
sf::RenderTexture renderTexture;
sf::Vector2u size;
RenderChain* chain;
static bool global_post_processor_enabled;
public:
bool enabled;
PostProcessor(string name, RenderChain* chain);
virtual ~PostProcessor() {}
virtual void render(sf::RenderTarget& window);
void setUniform(string name, float value);
static void setEnable(bool enable) { global_post_processor_enabled = enable; }
static bool isEnabled() { return global_post_processor_enabled; }
};
#endif//POST_PROCESS_MANAGER_H
| 22.885714 | 82 | 0.724095 | [
"render"
] |
bdaa1658d1f94366770262f40a4a5ac159e5096f | 5,530 | h | C | mat.h | orangeduck/Joint-Limits | 1e48238f656bd8fe24a58dabe040c5a3ce122215 | [
"MIT"
] | 61 | 2021-11-11T17:57:46.000Z | 2022-03-17T11:00:20.000Z | mat.h | orangeduck/Joint-Limits | 1e48238f656bd8fe24a58dabe040c5a3ce122215 | [
"MIT"
] | 3 | 2021-12-01T03:29:53.000Z | 2022-01-10T21:40:50.000Z | mat.h | orangeduck/Joint-Limits | 1e48238f656bd8fe24a58dabe040c5a3ce122215 | [
"MIT"
] | 7 | 2021-11-12T10:47:18.000Z | 2021-12-29T05:48:38.000Z | #pragma once
#include "vec.h"
struct mat3
{
mat3() :
xx(1.0f), xy(0.0f), xz(0.0f),
yx(0.0f), yy(1.0f), yz(0.0f),
zx(0.0f), zy(0.0f), zz(1.0f) {}
mat3(
float _xx, float _xy, float _xz,
float _yx, float _yy, float _yz,
float _zx, float _zy, float _zz) :
xx(_xx), xy(_xy), xz(_xz),
yx(_yx), yy(_yy), yz(_yz),
zx(_zx), zy(_zy), zz(_zz) {}
mat3(vec3 r0, vec3 r1, vec3 r2) :
xx(r0.x), xy(r0.y), xz(r0.z),
yx(r1.x), yy(r1.y), yz(r1.z),
zx(r2.x), zy(r2.y), zz(r2.z) {}
vec3 r0() const { return vec3(xx, xy, xz); }
vec3 r1() const { return vec3(yx, yy, yz); }
vec3 r2() const { return vec3(zx, zy, zz); }
vec3 c0() const { return vec3(xx, yx, zx); }
vec3 c1() const { return vec3(xy, yy, zy); }
vec3 c2() const { return vec3(xz, yz, zz); }
float xx, xy, xz,
yx, yy, yz,
zx, zy, zz;
};
static inline mat3 operator+(mat3 m, mat3 n)
{
return mat3(
m.xx + n.xx, m.xy + n.xy, m.xz + n.xz,
m.yx + n.yx, m.yy + n.yy, m.yz + n.yz,
m.zx + n.zx, m.zy + n.zy, m.zz + n.zz);
}
static inline mat3 operator-(mat3 m, mat3 n)
{
return mat3(
m.xx - n.xx, m.xy - n.xy, m.xz - n.xz,
m.yx - n.yx, m.yy - n.yy, m.yz - n.yz,
m.zx - n.zx, m.zy - n.zy, m.zz - n.zz);
}
static inline mat3 operator/(mat3 m, float v)
{
return mat3(
m.xx / v, m.xy / v, m.xz / v,
m.yx / v, m.yy / v, m.yz / v,
m.zx / v, m.zy / v, m.zz / v);
}
static inline mat3 operator*(float v, mat3 m)
{
return mat3(
v * m.xx, v * m.xy, v * m.xz,
v * m.yx, v * m.yy, v * m.yz,
v * m.zx, v * m.zy, v * m.zz);
}
static inline mat3 mat3_zero()
{
return mat3(
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f);
}
static inline mat3 mat3_transpose(mat3 m)
{
return mat3(
m.xx, m.yx, m.zx,
m.xy, m.yy, m.zy,
m.xz, m.yz, m.zz);
}
static inline mat3 mat3_mul(mat3 m, mat3 n)
{
return mat3(
dot(m.r0(), n.c0()), dot(m.r0(), n.c1()), dot(m.r0(), n.c2()),
dot(m.r1(), n.c0()), dot(m.r1(), n.c1()), dot(m.r1(), n.c2()),
dot(m.r2(), n.c0()), dot(m.r2(), n.c1()), dot(m.r2(), n.c2()));
}
static inline mat3 mat3_transpose_mul(mat3 m, mat3 n)
{
return mat3(
dot(m.c0(), n.c0()), dot(m.c0(), n.c1()), dot(m.c0(), n.c2()),
dot(m.c1(), n.c0()), dot(m.c1(), n.c1()), dot(m.c1(), n.c2()),
dot(m.c2(), n.c0()), dot(m.c2(), n.c1()), dot(m.c2(), n.c2()));
}
static inline vec3 mat3_mul_vec3(mat3 m, vec3 v)
{
return vec3(
dot(m.r0(), v),
dot(m.r1(), v),
dot(m.r2(), v));
}
static inline vec3 mat3_transpose_mul_vec3(mat3 m, vec3 v)
{
return vec3(
dot(m.c0(), v),
dot(m.c1(), v),
dot(m.c2(), v));
}
static inline mat3 mat3_from_angle_axis(float angle, vec3 axis)
{
float a0 = axis.x, a1 = axis.y, a2 = axis.z;
float c = cosf(angle), s = sinf(angle), t = 1.0f - cosf(angle);
return mat3(
c+a0*a0*t, a0*a1*t-a2*s, a0*a2*t+a1*s,
a0*a1*t+a2*s, c+a1*a1*t, a1*a2*t-a0*s,
a0*a2*t-a1*s, a1*a2*t+a0*s, c+a2*a2*t);
}
static inline mat3 mat3_outer(vec3 v, vec3 w)
{
return mat3(
v.x * w.x, v.x * w.y, v.x * w.z,
v.y * w.x, v.y * w.y, v.y * w.z,
v.z * w.x, v.z * w.y, v.z * w.z);
}
static inline vec3 mat3_svd_dominant_eigen(
const mat3 A,
const vec3 v0,
const int iterations,
const float eps)
{
// Initial Guess at Eigen Vector & Value
vec3 v = v0;
float ev = (mat3_mul_vec3(A, v) / v).x;
for (int i = 0; i < iterations; i++)
{
// Power Iteration
vec3 Av = mat3_mul_vec3(A, v);
// Next Guess at Eigen Vector & Value
vec3 v_new = normalize(Av);
float ev_new = (mat3_mul_vec3(A, v_new) / v_new).x;
// Break if converged
if (fabs(ev - ev_new) < eps)
{
break;
}
// Update best guess
v = v_new;
ev = ev_new;
}
return v;
}
static inline void mat3_svd_piter(
mat3& U,
vec3& s,
mat3& V,
const mat3 A,
const int iterations = 64,
const float eps = 1e-5f)
{
// First Eigen Vector
vec3 g0 = vec3(1, 0, 0);
mat3 B0 = A;
vec3 u0 = mat3_svd_dominant_eigen(B0, g0, iterations, eps);
vec3 v0_unnormalized = mat3_transpose_mul_vec3(A, u0);
float s0 = length(v0_unnormalized);
vec3 v0 = s0 < eps ? g0 : normalize(v0_unnormalized);
// Second Eigen Vector
mat3 B1 = A;
vec3 g1 = normalize(cross(vec3(0, 0, 1), v0));
B1 = B1 - s0 * mat3_outer(u0, v0);
vec3 u1 = mat3_svd_dominant_eigen(B1, g1, iterations, eps);
vec3 v1_unnormalized = mat3_transpose_mul_vec3(A, u1);
float s1 = length(v1_unnormalized);
vec3 v1 = s1 < eps ? g1 : normalize(v1_unnormalized);
// Third Eigen Vector
mat3 B2 = A;
vec3 v2 = normalize(cross(v0, v1));
B2 = B2 - s0 * mat3_outer(u0, v0);
B2 = B2 - s1 * mat3_outer(u1, v1);
vec3 u2 = mat3_svd_dominant_eigen(B2, v2, iterations, eps);
float s2 = length(mat3_transpose_mul_vec3(A, u2));
// Done
U = mat3(u0, u1, u2);
s = vec3(s0, s1, s2);
V = mat3(v0, v1, v2);
}
| 26.714976 | 70 | 0.49132 | [
"vector"
] |
bdbc95e14d66b36a08e485ec4f0f768ba25e0d73 | 2,015 | h | C | open_spiel/algorithms/expected_returns.h | findmyway/open_spiel | aa9bf4ae5a5f97234b73de9bf4ccb61b33005d78 | [
"Apache-2.0"
] | null | null | null | open_spiel/algorithms/expected_returns.h | findmyway/open_spiel | aa9bf4ae5a5f97234b73de9bf4ccb61b33005d78 | [
"Apache-2.0"
] | null | null | null | open_spiel/algorithms/expected_returns.h | findmyway/open_spiel | aa9bf4ae5a5f97234b73de9bf4ccb61b33005d78 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 DeepMind Technologies Ltd. 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 OPEN_SPIEL_ALGORITHMS_EXPECTED_RETURNS_H_
#define OPEN_SPIEL_ALGORITHMS_EXPECTED_RETURNS_H_
#include <string>
#include "open_spiel/policy.h"
#include "open_spiel/spiel.h"
namespace open_spiel {
namespace algorithms {
// Computes the (undiscounted) expected returns from a depth-limited search
// starting at the state and following each player's policy. Using a negative
// depth will do a full tree traversal (from the specified state).
//
// The second overloaded function acts the same way, except assumes that all of
// the players' policies are encapsulated in one joint policy.
// `provides_infostate` should be set to true if the Policy* objects passed in
// have implemented the GetStatePolicy(const std::string&) method, as this
// allows for additional optimizations. Otherwise, GetStatePolicy(const State&)
// will be called.
std::vector<double> ExpectedReturns(const State& state,
const std::vector<const Policy*>& policies,
int depth_limit,
bool provides_infostate = true);
std::vector<double> ExpectedReturns(const State& state,
const Policy& joint_policy,
int depth_limit);
} // namespace algorithms
} // namespace open_spiel
#endif // OPEN_SPIEL_ALGORITHMS_EXPECTED_RETURNS_H_
| 41.979167 | 79 | 0.707196 | [
"vector"
] |
bddaa9f46e715cd55213e14dba43c4dbb7261f1a | 8,564 | h | C | Include/10.0.18362.0/cppwinrt/winrt/impl/Windows.Graphics.Display.2.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-29T06:22:17.000Z | 2021-11-28T08:21:38.000Z | Include/10.0.18362.0/cppwinrt/winrt/impl/Windows.Graphics.Display.2.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | null | null | null | Include/10.0.18362.0/cppwinrt/winrt/impl/Windows.Graphics.Display.2.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-30T04:15:11.000Z | 2021-11-28T08:48:56.000Z | // C++/WinRT v1.0.190111.3
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "winrt/impl/Windows.Storage.Streams.1.h"
#include "winrt/impl/Windows.Graphics.Display.1.h"
WINRT_EXPORT namespace winrt::Windows::Graphics::Display {
struct DisplayPropertiesEventHandler : Windows::Foundation::IUnknown
{
DisplayPropertiesEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> DisplayPropertiesEventHandler(L lambda);
template <typename F> DisplayPropertiesEventHandler(F* function);
template <typename O, typename M> DisplayPropertiesEventHandler(O* object, M method);
template <typename O, typename M> DisplayPropertiesEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> DisplayPropertiesEventHandler(weak_ref<O>&& object, M method);
void operator()(Windows::Foundation::IInspectable const& sender) const;
};
struct NitRange
{
float MinNits;
float MaxNits;
float StepSizeNits;
};
inline bool operator==(NitRange const& left, NitRange const& right) noexcept
{
return left.MinNits == right.MinNits && left.MaxNits == right.MaxNits && left.StepSizeNits == right.StepSizeNits;
}
inline bool operator!=(NitRange const& left, NitRange const& right) noexcept
{
return !(left == right);
}
}
namespace winrt::impl {
}
WINRT_EXPORT namespace winrt::Windows::Graphics::Display {
struct WINRT_EBO AdvancedColorInfo :
Windows::Graphics::Display::IAdvancedColorInfo
{
AdvancedColorInfo(std::nullptr_t) noexcept {}
};
struct WINRT_EBO BrightnessOverride :
Windows::Graphics::Display::IBrightnessOverride
{
BrightnessOverride(std::nullptr_t) noexcept {}
static Windows::Graphics::Display::BrightnessOverride GetDefaultForSystem();
static Windows::Graphics::Display::BrightnessOverride GetForCurrentView();
static Windows::Foundation::IAsyncOperation<bool> SaveForSystemAsync(Windows::Graphics::Display::BrightnessOverride const& value);
};
struct WINRT_EBO BrightnessOverrideSettings :
Windows::Graphics::Display::IBrightnessOverrideSettings
{
BrightnessOverrideSettings(std::nullptr_t) noexcept {}
static Windows::Graphics::Display::BrightnessOverrideSettings CreateFromLevel(double level);
static Windows::Graphics::Display::BrightnessOverrideSettings CreateFromNits(float nits);
static Windows::Graphics::Display::BrightnessOverrideSettings CreateFromDisplayBrightnessOverrideScenario(Windows::Graphics::Display::DisplayBrightnessOverrideScenario const& overrideScenario);
};
struct WINRT_EBO ColorOverrideSettings :
Windows::Graphics::Display::IColorOverrideSettings
{
ColorOverrideSettings(std::nullptr_t) noexcept {}
static Windows::Graphics::Display::ColorOverrideSettings CreateFromDisplayColorOverrideScenario(Windows::Graphics::Display::DisplayColorOverrideScenario const& overrideScenario);
};
struct WINRT_EBO DisplayEnhancementOverride :
Windows::Graphics::Display::IDisplayEnhancementOverride
{
DisplayEnhancementOverride(std::nullptr_t) noexcept {}
static Windows::Graphics::Display::DisplayEnhancementOverride GetForCurrentView();
};
struct WINRT_EBO DisplayEnhancementOverrideCapabilities :
Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities
{
DisplayEnhancementOverrideCapabilities(std::nullptr_t) noexcept {}
};
struct WINRT_EBO DisplayEnhancementOverrideCapabilitiesChangedEventArgs :
Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilitiesChangedEventArgs
{
DisplayEnhancementOverrideCapabilitiesChangedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO DisplayInformation :
Windows::Graphics::Display::IDisplayInformation,
impl::require<DisplayInformation, Windows::Graphics::Display::IDisplayInformation2, Windows::Graphics::Display::IDisplayInformation3, Windows::Graphics::Display::IDisplayInformation4, Windows::Graphics::Display::IDisplayInformation5>
{
DisplayInformation(std::nullptr_t) noexcept {}
static Windows::Graphics::Display::DisplayInformation GetForCurrentView();
static Windows::Graphics::Display::DisplayOrientations AutoRotationPreferences();
static void AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations const& value);
static winrt::event_token DisplayContentsInvalidated(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler);
using DisplayContentsInvalidated_revoker = impl::factory_event_revoker<Windows::Graphics::Display::IDisplayInformationStatics, &impl::abi_t<Windows::Graphics::Display::IDisplayInformationStatics>::remove_DisplayContentsInvalidated>;
static DisplayContentsInvalidated_revoker DisplayContentsInvalidated(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler);
static void DisplayContentsInvalidated(winrt::event_token const& token);
};
struct DisplayProperties
{
DisplayProperties() = delete;
static Windows::Graphics::Display::DisplayOrientations CurrentOrientation();
static Windows::Graphics::Display::DisplayOrientations NativeOrientation();
static Windows::Graphics::Display::DisplayOrientations AutoRotationPreferences();
static void AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations const& value);
static winrt::event_token OrientationChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
using OrientationChanged_revoker = impl::factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_OrientationChanged>;
static OrientationChanged_revoker OrientationChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
static void OrientationChanged(winrt::event_token const& token);
static Windows::Graphics::Display::ResolutionScale ResolutionScale();
static float LogicalDpi();
static winrt::event_token LogicalDpiChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
using LogicalDpiChanged_revoker = impl::factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_LogicalDpiChanged>;
static LogicalDpiChanged_revoker LogicalDpiChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
static void LogicalDpiChanged(winrt::event_token const& token);
static bool StereoEnabled();
static winrt::event_token StereoEnabledChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
using StereoEnabledChanged_revoker = impl::factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_StereoEnabledChanged>;
static StereoEnabledChanged_revoker StereoEnabledChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
static void StereoEnabledChanged(winrt::event_token const& token);
static Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream> GetColorProfileAsync();
static winrt::event_token ColorProfileChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
using ColorProfileChanged_revoker = impl::factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_ColorProfileChanged>;
static ColorProfileChanged_revoker ColorProfileChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
static void ColorProfileChanged(winrt::event_token const& token);
static winrt::event_token DisplayContentsInvalidated(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
using DisplayContentsInvalidated_revoker = impl::factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_DisplayContentsInvalidated>;
static DisplayContentsInvalidated_revoker DisplayContentsInvalidated(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler);
static void DisplayContentsInvalidated(winrt::event_token const& token);
};
}
| 58.657534 | 237 | 0.81107 | [
"object"
] |
bddd6fc18eea97a872caf27ad379c3d5b70de858 | 803 | h | C | library.collision/ContactResolver.h | S1lv10Fr4gn4n1/physics-simulation-tool-ios | 6d32bfcbe0b90a9b0112c56faa971ea4be278e93 | [
"MIT"
] | null | null | null | library.collision/ContactResolver.h | S1lv10Fr4gn4n1/physics-simulation-tool-ios | 6d32bfcbe0b90a9b0112c56faa971ea4be278e93 | [
"MIT"
] | null | null | null | library.collision/ContactResolver.h | S1lv10Fr4gn4n1/physics-simulation-tool-ios | 6d32bfcbe0b90a9b0112c56faa971ea4be278e93 | [
"MIT"
] | null | null | null | //
// ContactResolver.h
// Physical.Simulation.Tool
//
// Created by Silvio Fragnani on 09/09/12.
#ifndef CONTACTRESOLVER_H
#define CONTACTRESOLVER_H
#include "CommonStructures.h"
#include "Contact.h"
class ContactResolver {
private:
// avoid instability velocities smaller
real velocityEpsilon;
// avoid instability penetrations smaller
real positionEpsilon;
void prepareContacts(std::vector<Contact *> * _contacts, real _duration);
void solverPositions(std::vector<Contact *> * _contacts, real _duration);
void solverVelocities(std::vector<Contact *> * _contacts, real _duration);
public:
ContactResolver(real _positionEpsilon=0.001f, real _velocityEpsilon=0.01f);
void solverContacts(std::vector<Contact *> * _contacts, real _duration);
};
#endif
| 26.766667 | 79 | 0.734745 | [
"vector"
] |
bddf3f61dabecd4c0db399f8df8eae8e18b23ec4 | 591 | h | C | ShopTest/NewApp/Home/View/JiesuanTableViewCell.h | DYS12345/xiaoLingShou | 01b826a102fbdd60d6d71a241634722942e7512e | [
"Apache-2.0"
] | null | null | null | ShopTest/NewApp/Home/View/JiesuanTableViewCell.h | DYS12345/xiaoLingShou | 01b826a102fbdd60d6d71a241634722942e7512e | [
"Apache-2.0"
] | null | null | null | ShopTest/NewApp/Home/View/JiesuanTableViewCell.h | DYS12345/xiaoLingShou | 01b826a102fbdd60d6d71a241634722942e7512e | [
"Apache-2.0"
] | null | null | null | //
// JiesuanTableViewCell.h
// Shop
//
// Created by 董永胜 on 2018/4/17.
// Copyright © 2018年 董永胜. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ProductSkuModel.h"
@interface JiesuanTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *goodsImageView;
@property (weak, nonatomic) IBOutlet UILabel *goodsNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *skuLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@property (nonatomic, strong) ProductSkuModel *model;
@end
| 26.863636 | 65 | 0.759729 | [
"model"
] |
bddf803704aa757cddddc2c7ab95ba8073fe513e | 1,630 | h | C | atom/browser/web_view/web_view_renderer_state.h | rprichard/atom-shell | 73ee24bd98ff40a0bbde1fe1bbbf74ff9a91a5d5 | [
"MIT"
] | 1 | 2015-03-18T16:05:33.000Z | 2015-03-18T16:05:33.000Z | atom/browser/web_view/web_view_renderer_state.h | rprichard/atom-shell | 73ee24bd98ff40a0bbde1fe1bbbf74ff9a91a5d5 | [
"MIT"
] | null | null | null | atom/browser/web_view/web_view_renderer_state.h | rprichard/atom-shell | 73ee24bd98ff40a0bbde1fe1bbbf74ff9a91a5d5 | [
"MIT"
] | null | null | null | // Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_WEB_VIEW_WEB_VIEW_RENDERER_STATE_H_
#define ATOM_BROWSER_WEB_VIEW_WEB_VIEW_RENDERER_STATE_H_
#include <map>
#include <string>
#include <utility>
#include "base/files/file_path.h"
#include "base/memory/singleton.h"
namespace atom {
class WebViewManager;
// This class keeps track of <webview> renderer state for use on the IO thread.
// All methods should be called on the IO thread.
class WebViewRendererState {
public:
struct WebViewInfo {
int guest_instance_id;
bool node_integration;
bool plugins;
base::FilePath preload_script;
};
static WebViewRendererState* GetInstance();
// Looks up the information for the embedder <webview> for a given render
// view, if one exists. Called on the IO thread.
bool GetInfo(int guest_process_id, WebViewInfo* webview_info);
// Returns true if the given renderer is used by webviews.
bool IsGuest(int render_process_id);
private:
friend class WebViewManager;
friend struct DefaultSingletonTraits<WebViewRendererState>;
typedef std::map<int, WebViewInfo> WebViewInfoMap;
WebViewRendererState();
~WebViewRendererState();
// Adds or removes a <webview> guest render process from the set.
void AddGuest(int render_process_id, const WebViewInfo& webview_info);
void RemoveGuest(int render_process_id);
WebViewInfoMap webview_info_map_;
DISALLOW_COPY_AND_ASSIGN(WebViewRendererState);
};
} // namespace atom
#endif // ATOM_BROWSER_WEB_VIEW_WEB_VIEW_RENDERER_STATE_H_
| 27.166667 | 79 | 0.771779 | [
"render"
] |
bde68297dd09cc62702388c2b2fed40ce6699163 | 1,009 | h | C | engine/Engine.Core/src/core/window/WindowClass.h | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 66 | 2018-12-16T21:03:36.000Z | 2022-03-26T12:23:57.000Z | engine/Engine.Core/src/core/window/WindowClass.h | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 57 | 2018-04-24T20:53:01.000Z | 2021-02-21T12:14:20.000Z | engine/Engine.Core/src/core/window/WindowClass.h | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 7 | 2019-07-16T08:25:25.000Z | 2022-03-21T08:29:46.000Z | #pragma once
#include "core/Enum.h"
#include "core/Event.h"
#include "core/NamedObject.h"
#include "core/Object.h"
#include "core/string/String.h"
namespace Ghurund::Core {
class Window;
enum class WindowClassEnum {
WINDOWED, FULLSCREEN, POPUP
};
class WindowClass:public Enum<WindowClassEnum, WindowClass> {
private:
String className;
WNDCLASSEX windowClass;
HINSTANCE hInst;
DWORD exStyle, dwStyle;
public:
static const WindowClass WINDOWED, FULLSCREEN, POPUP;
static const EnumValues<WindowClassEnum, WindowClass> VALUES;
WindowClass(WindowClassEnum value, const AString& name, DWORD exStyle, DWORD dwStyle, UINT style);
~WindowClass(){
UnregisterClass(windowClass.lpszClassName, windowClass.hInstance);
}
HWND create() const;
inline DWORD getStyle() const {
return dwStyle;
}
__declspec(property(get = getStyle)) DWORD Style;
};
} | 24.02381 | 106 | 0.653122 | [
"object"
] |
bdf08f4c4e4a1f3f9a65ebbc68e9409672691fce | 6,146 | h | C | dtpc/library/dtpcP.h | amontilla24/AndroidFixMe | 0e4c7599beaf87e62be441fd30ba6b57500ca1b0 | [
"Unlicense"
] | 2 | 2018-10-20T12:41:45.000Z | 2018-10-20T14:48:21.000Z | dtpc/library/dtpcP.h | amontilla24/AndroidFixMe | 0e4c7599beaf87e62be441fd30ba6b57500ca1b0 | [
"Unlicense"
] | null | null | null | dtpc/library/dtpcP.h | amontilla24/AndroidFixMe | 0e4c7599beaf87e62be441fd30ba6b57500ca1b0 | [
"Unlicense"
] | 2 | 2018-10-20T14:16:39.000Z | 2020-10-21T16:27:52.000Z | /*
dtpcP.h: Private definitions supporting the implementation
of DTPC nodes in the ION (Interplanetary Overlay
Network) stack.
Authors: Giorgos Papastergiou, SPICE
Ioannis Alexiadis, SPICE
Copyright (c) 2011, Space Internetworking Center,
Democritus University of Thrace. ALL RIGHTS RESERVED.
*/
#include "dtpc.h"
#define DTPC_SEND_SVC_NBR (128)
#define DTPC_RECV_SVC_NBR (129)
#define DTPC_MAX_SEQ_NBR 999999999
#define EPOCH_2000_SEC 946684800
#define BUFMAXSIZE (65536)
/* "Watch" switches for DTPC protocol operation. */
#define WATCH_o (1)
#define WATCH_newItem (2)
#define WATCH_r (4)
#define WATCH_complete (8)
#define WATCH_send (16)
#define WATCH_l (32)
#define WATCH_m (64)
#define WATCH_n (128)
#define WATCH_i (256)
#define WATCH_u (512)
#define WATCH_v (1024)
#define WATCH_discard (2048)
#define WATCH_expire (4096)
#define WATCH_reset (8192)
typedef enum
{
ResendAdu = 0,
DeleteAdu,
DeleteGap
} DtpcEventType;
typedef struct
{
Object text; /* Not NULL-terminated. */
unsigned int textLength;
} BpString;
typedef struct
{
Object dstEid; /* SDR string */
unsigned int profileID;
Scalar aduCounter;
Object outAdus; /* SDR list of outAdus */
Object queuedAdus; /* SDR list of queued bundles */
Object inProgressAduElt; /* 0 if no outADU
* aggregation
* in progress */
} OutAggregator;
typedef struct
{
Scalar seqNum;
int ageOfAdu;
int rtxCount;
time_t expirationTime;
/* Database navigation stuff */
Object aggregatedZCO; /* ZCO Ref. */
Object bundleObj; /* Bundle object */
Object outAggrElt; /* Ref. to OutboundAggregator */
Object topics; /* SDR list of Topics */
Object rtxEventElt; /* Ref. to retransmission event */
Object delEventElt; /* Ref. to deletion event */
} OutAdu;
typedef struct
{
unsigned int topicID;
Object payloadRecords; /* SDR list of PayloadRecords */
Object outAduElt; /* Ref. to OutAdu - not used */
} Topic;
typedef struct
{
DtpcEventType type;
time_t scheduledTime;
Object aduElt;
} DtpcEvent;
typedef struct
{
Object srcEid; /* SDR string */
unsigned int profileID;
Scalar nextExpected; /* Next expected seqNum */
Scalar resetSeqNum; /* Last received seqNum in
reset range. */
time_t resetTimestamp; /* Expiration time of
resetSeqNum */
Object inAdus; /* SDR list of InAdus */
} InAggregator;
typedef struct
{
Scalar seqNum;
Object aggregatedZCO; /* ZCO Ref. */
Object inAggrElt; /* Ref. to InboundAggretor */
Object gapEventElt; /* Ref. to gap deletion event */
} InAdu;
typedef struct
{
unsigned int topicID;
int appPid;
sm_SemId semaphore;
Object dlvQueue; /* SDR list of PayloadRecords */
} VSap;
typedef struct dtpcsap_st
{
VSap *vsap;
DtpcElisionFn elisionFn;
sm_SemId semaphore;
} Sap;
typedef struct
{
Object outAggregators; /* SDR list OutboundAggregators */
Object inAggregators; /* SDR list InboundAggregators */
Object events; /* SDR list dtpcEvents */
Object profiles; /* SDR list Profiles */
Object queues; /* SDR list topic delivery queues
* identified by list USER DATA */
Object outboundAdus; /* SDR list: OutAdus */
} DtpcDB;
typedef struct
{
unsigned int profileID;
unsigned int maxRtx;
unsigned int lifespan;
unsigned int aggrSizeLimit;
unsigned int aggrTimeLimit;
BpAncillaryData ancillaryData;
int srrFlags;
BpCustodySwitch custodySwitch;
Object reportToEid; /* SDR String */
int classOfService;
} Profile;
typedef struct
{
int dtpcdPid; /* For stopping dtpc daemon. */
int clockPid; /* For stopping dtpcclock. */
int watching; /* Activity watch. */
/* The aduSemaphore of the DTPC protocol is given whenever
* a new outAdu is inserted in the outbounAdus list. */
sm_SemId aduSemaphore;
PsmAddress vsaps; /* SM list: VSaps */
PsmAddress profiles; /* SM List: Profiles */
} DtpcVdb;
typedef struct
{
Object srcEid; /* SDR string */
unsigned int length;
Object content;
} DlvPayload;
extern int dtpcInit();
#define dtpcStart() _dtpcStart()
extern int _dtpcStart();
#define dtpcStop() _dtpcStop();
extern void dtpcStop();
extern int dtpcAttach();
extern unsigned int dtpcGetProfile(unsigned int maxRtx,
unsigned int aggrSizeLimit,
unsigned int aggrTimeLimit,
unsigned int lifespan,
BpAncillaryData *ancillaryData,
unsigned char srrFlags,
BpCustodySwitch custodySwitch,
char *reportToEid,
int classOfService);
extern int raiseProfile(Sdr sdr, Object sdrElt, DtpcVdb *vdb);
extern int raiseVSap(Sdr sdr, Object elt, DtpcVdb *vdb,
unsigned int topicID);
extern int initOutAdu(Profile *profile, Object outAggrAddr,
Object outAggrElt, Object *outAduObj,
Object *outAduElt);
extern int insertRecord (DtpcSAP sap, char *dstEid,
unsigned int profileID, unsigned int topicID,
Object adu, int length);
extern int createAdu(Profile *profile, Object outAduObj,
Object outAduElt);
extern int sendAdu(BpSAP sap);
extern void deleteAdu(Sdr sdr, Object aduElt);
extern int resendAdu(Sdr sdr, Object aduElt, time_t currentTime);
extern int addProfile(unsigned int profileID, unsigned int maxRtx,
unsigned int lifespan,
unsigned int aggrSizeLimit,
unsigned int aggrTimeLimit,
char *svcClass, char *flags,
char* reportToEid);
extern int removeProfile(unsigned int profileID);
extern Object getDtpcDbObject();
extern DtpcDB *getDtpcConstants();
extern DtpcVdb *getDtpcVdb();
extern int handleInAdu(Sdr sdr, BpSAP txSap, BpDelivery *dlv,
unsigned int profNum, Scalar seqNum);
extern int handleAck(Sdr sdr, BpDelivery *dlv,
unsigned int profNum, Scalar seqNum);
extern void deletePlaceholder(Sdr sdr, Object aduElt);
extern int parseInAdus(Sdr sdr);
extern int sendAck(BpSAP sap, unsigned int profileID,
Scalar seqNum, BpDelivery *dlv);
extern void scalarToSdnv(Sdnv *sdnv, Scalar *scalar);
extern int sdnvToScalar(Scalar *scalar, unsigned char *sdnvText);
extern int compareScalars(Scalar *scalar1, Scalar *scalar2);
| 27.19469 | 74 | 0.70973 | [
"object"
] |
bdf328f6e400de8813c562ced4c4381b1faa97a5 | 656 | h | C | project/camera.h | isikmustafa/shapenet-renderer | 66cf800fb1807b85517d582e493e3e09c69bc1d9 | [
"BSD-2-Clause"
] | null | null | null | project/camera.h | isikmustafa/shapenet-renderer | 66cf800fb1807b85517d582e493e3e09c69bc1d9 | [
"BSD-2-Clause"
] | null | null | null | project/camera.h | isikmustafa/shapenet-renderer | 66cf800fb1807b85517d582e493e3e09c69bc1d9 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include <string>
#include <cuda_runtime.h>
struct Camera
{
Camera(const glm::vec3& p_look_at, const glm::vec3& p_position, const glm::mat3& p_intrinsics);
#ifdef __NVCC__
__device__ glm::vec3 pointEyeToWorld(const glm::vec3& point) const
{
return rotation * point + position;
}
__device__ glm::vec3 vectorEyeToWorld(const glm::vec3& vector) const
{
return rotation * vector;
}
#endif
void dumpPoseToFile(const std::string& filename) const;
void dumpIntrinsicsToFile(const std::string& filename) const;
glm::vec3 position;
glm::mat3 rotation;
glm::mat3 intrinsics;
glm::mat3 inverse_intrinsics;
}; | 21.866667 | 96 | 0.742378 | [
"vector"
] |
bdf8bffe0fa7d01942f6a957ea4d475f3accbb2b | 2,541 | h | C | third_lib/include/mrsid/lti_metadataWriter.h | FlyAlCode/FlightSim | 800b46ebf87449408cc908c59cb5e18bea5863c3 | [
"Apache-2.0"
] | null | null | null | third_lib/include/mrsid/lti_metadataWriter.h | FlyAlCode/FlightSim | 800b46ebf87449408cc908c59cb5e18bea5863c3 | [
"Apache-2.0"
] | null | null | null | third_lib/include/mrsid/lti_metadataWriter.h | FlyAlCode/FlightSim | 800b46ebf87449408cc908c59cb5e18bea5863c3 | [
"Apache-2.0"
] | null | null | null | /* $Id$ */
/* //////////////////////////////////////////////////////////////////////////
// //
// This code is Copyright (c) 2004 LizardTech, Inc, 1008 Western Avenue, //
// Suite 200, Seattle, WA 98104. Unauthorized use or distribution //
// prohibited. Access to and use of this code is permitted only under //
// license from LizardTech, Inc. Portions of the code are protected by //
// US and foreign patents and other filings. All Rights Reserved. //
// //
////////////////////////////////////////////////////////////////////////// */
/* PUBLIC */
#ifndef LTI_METADATA_WRITER_H
#define LTI_METADATA_WRITER_H
// lt_lib_base
#include "lt_base.h"
LT_BEGIN_NAMESPACE(LizardTech)
#if defined(LT_COMPILER_MS)
#pragma warning(push,4)
#endif
class LTIMetadataDatabase;
/**
* abstract class for exporting a metadata database
*
* This abstract class provides an interface for exporting metadata records
* from an LTIMetadataDatabase to a foreign source.
*
* This is used, for example, to provide a mechanism for writing the
* format-neutral, in-memory database into binary TIFF tag format. it
* is also used to dump the database to plain-text format (for debugging).
*/
class LTIMetadataWriter
{
public:
/**
* destructor
*/
virtual ~LTIMetadataWriter();
/**
* write records out from database
*
* This function must be implemented in the derived class. It should
* write each of the LTIMetadataRecord objects in the database out to
* the foreign format.
*
* @return status code indicating success or failure
*/
virtual LT_STATUS write() const = 0;
protected:
/**
* default constructor
*
* This base constructor creates a writer object which can export
* records from a database to some foreign format.
*
* @param database the database to be read into
*/
LTIMetadataWriter(const LTIMetadataDatabase& database);
/**
* the database to be written from
*
* This is the database to be written out from. Derived classes may access
* it directly.
*/
const LTIMetadataDatabase& m_database;
private:
// nope
LTIMetadataWriter(const LTIMetadataWriter&);
LTIMetadataWriter& operator=(const LTIMetadataWriter&);
};
LT_END_NAMESPACE(LizardTech)
#if defined(LT_COMPILER_MS)
#pragma warning(pop)
#endif
#endif // LTI_METADATA_WRITER_H
| 27.923077 | 78 | 0.61708 | [
"object"
] |
da00a0440095a47353e1437a70d961607d5e112c | 144,216 | c | C | source/blender/blenkernel/intern/particle.c | gcandal/RIPE-Blender | c3ef1f8db3c420612aecf40359533cb043615208 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/blenkernel/intern/particle.c | gcandal/RIPE-Blender | c3ef1f8db3c420612aecf40359533cb043615208 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/blenkernel/intern/particle.c | gcandal/RIPE-Blender | c3ef1f8db3c420612aecf40359533cb043615208 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2019-09-13T15:29:14.000Z | 2019-09-13T15:29:14.000Z | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2007 by Janne Karhu.
* All rights reserved.
*/
/** \file
* \ingroup bke
*/
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "MEM_guardedalloc.h"
#include "DNA_collection_types.h"
#include "DNA_curve_types.h"
#include "DNA_key_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_particle_types.h"
#include "DNA_smoke_types.h"
#include "DNA_scene_types.h"
#include "DNA_dynamicpaint_types.h"
#include "BLI_blenlib.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "BLI_kdopbvh.h"
#include "BLI_kdtree.h"
#include "BLI_rand.h"
#include "BLI_task.h"
#include "BLI_threads.h"
#include "BLI_linklist.h"
#include "BLT_translation.h"
#include "BKE_anim.h"
#include "BKE_animsys.h"
#include "BKE_boids.h"
#include "BKE_cloth.h"
#include "BKE_collection.h"
#include "BKE_colortools.h"
#include "BKE_effect.h"
#include "BKE_main.h"
#include "BKE_lattice.h"
#include "BKE_displist.h"
#include "BKE_particle.h"
#include "BKE_material.h"
#include "BKE_key.h"
#include "BKE_library.h"
#include "BKE_modifier.h"
#include "BKE_mesh.h"
#include "BKE_cdderivedmesh.h" /* for weight_to_rgb() */
#include "BKE_pointcache.h"
#include "BKE_scene.h"
#include "BKE_deform.h"
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"
#include "DEG_depsgraph_query.h"
#include "RE_render_ext.h"
#include "particle_private.h"
unsigned int PSYS_FRAND_SEED_OFFSET[PSYS_FRAND_COUNT];
unsigned int PSYS_FRAND_SEED_MULTIPLIER[PSYS_FRAND_COUNT];
float PSYS_FRAND_BASE[PSYS_FRAND_COUNT];
void psys_init_rng(void)
{
RNG *rng = BLI_rng_new_srandom(5831); /* arbitrary */
for (int i = 0; i < PSYS_FRAND_COUNT; ++i) {
PSYS_FRAND_BASE[i] = BLI_rng_get_float(rng);
PSYS_FRAND_SEED_OFFSET[i] = (unsigned int)BLI_rng_get_int(rng);
PSYS_FRAND_SEED_MULTIPLIER[i] = (unsigned int)BLI_rng_get_int(rng);
}
BLI_rng_free(rng);
}
static void get_child_modifier_parameters(ParticleSettings *part,
ParticleThreadContext *ctx,
ChildParticle *cpa,
short cpa_from,
int cpa_num,
float *cpa_fuv,
float *orco,
ParticleTexture *ptex);
static void get_cpa_texture(Mesh *mesh,
ParticleSystem *psys,
ParticleSettings *part,
ParticleData *par,
int child_index,
int face_index,
const float fw[4],
float *orco,
ParticleTexture *ptex,
int event,
float cfra);
/* few helpers for countall etc. */
int count_particles(ParticleSystem *psys)
{
ParticleSettings *part = psys->part;
PARTICLE_P;
int tot = 0;
LOOP_SHOWN_PARTICLES
{
if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {
}
else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {
}
else {
tot++;
}
}
return tot;
}
int count_particles_mod(ParticleSystem *psys, int totgr, int cur)
{
ParticleSettings *part = psys->part;
PARTICLE_P;
int tot = 0;
LOOP_SHOWN_PARTICLES
{
if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {
}
else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {
}
else if (p % totgr == cur) {
tot++;
}
}
return tot;
}
/* we allocate path cache memory in chunks instead of a big contiguous
* chunk, windows' memory allocater fails to find big blocks of memory often */
#define PATH_CACHE_BUF_SIZE 1024
static ParticleCacheKey *pcache_key_segment_endpoint_safe(ParticleCacheKey *key)
{
return (key->segments > 0) ? (key + (key->segments - 1)) : key;
}
static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int totkeys)
{
LinkData *buf;
ParticleCacheKey **cache;
int i, totkey, totbufkey;
tot = MAX2(tot, 1);
totkey = 0;
cache = MEM_callocN(tot * sizeof(void *), "PathCacheArray");
while (totkey < tot) {
totbufkey = MIN2(tot - totkey, PATH_CACHE_BUF_SIZE);
buf = MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
buf->data = MEM_callocN(sizeof(ParticleCacheKey) * totbufkey * totkeys, "ParticleCacheKey");
for (i = 0; i < totbufkey; i++) {
cache[totkey + i] = ((ParticleCacheKey *)buf->data) + i * totkeys;
}
totkey += totbufkey;
BLI_addtail(bufs, buf);
}
return cache;
}
static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
{
LinkData *buf;
if (cache) {
MEM_freeN(cache);
}
for (buf = bufs->first; buf; buf = buf->next) {
MEM_freeN(buf->data);
}
BLI_freelistN(bufs);
}
/************************************************/
/* Getting stuff */
/************************************************/
/* get object's active particle system safely */
ParticleSystem *psys_get_current(Object *ob)
{
ParticleSystem *psys;
if (ob == NULL) {
return NULL;
}
for (psys = ob->particlesystem.first; psys; psys = psys->next) {
if (psys->flag & PSYS_CURRENT) {
return psys;
}
}
return NULL;
}
short psys_get_current_num(Object *ob)
{
ParticleSystem *psys;
short i;
if (ob == NULL) {
return 0;
}
for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) {
if (psys->flag & PSYS_CURRENT) {
return i;
}
}
return i;
}
void psys_set_current_num(Object *ob, int index)
{
ParticleSystem *psys;
short i;
if (ob == NULL) {
return;
}
for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) {
if (i == index) {
psys->flag |= PSYS_CURRENT;
}
else {
psys->flag &= ~PSYS_CURRENT;
}
}
}
struct LatticeDeformData *psys_create_lattice_deform_data(ParticleSimulationData *sim)
{
struct LatticeDeformData *lattice_deform_data = NULL;
if (psys_in_edit_mode(sim->depsgraph, sim->psys) == 0) {
Object *lattice = NULL;
ModifierData *md = (ModifierData *)psys_get_modifier(sim->ob, sim->psys);
bool for_render = DEG_get_mode(sim->depsgraph) == DAG_EVAL_RENDER;
int mode = for_render ? eModifierMode_Render : eModifierMode_Realtime;
for (; md; md = md->next) {
if (md->type == eModifierType_Lattice) {
if (md->mode & mode) {
LatticeModifierData *lmd = (LatticeModifierData *)md;
lattice = lmd->object;
sim->psys->lattice_strength = lmd->strength;
}
break;
}
}
if (lattice) {
lattice_deform_data = init_latt_deform(lattice, NULL);
}
}
return lattice_deform_data;
}
void psys_disable_all(Object *ob)
{
ParticleSystem *psys = ob->particlesystem.first;
for (; psys; psys = psys->next) {
psys->flag |= PSYS_DISABLED;
}
}
void psys_enable_all(Object *ob)
{
ParticleSystem *psys = ob->particlesystem.first;
for (; psys; psys = psys->next) {
psys->flag &= ~PSYS_DISABLED;
}
}
ParticleSystem *psys_orig_get(ParticleSystem *psys)
{
if (psys->orig_psys == NULL) {
return psys;
}
return psys->orig_psys;
}
struct ParticleSystem *psys_eval_get(Depsgraph *depsgraph, Object *object, ParticleSystem *psys)
{
Object *object_eval = DEG_get_evaluated_object(depsgraph, object);
if (object_eval == object) {
return psys;
}
ParticleSystem *psys_eval = object_eval->particlesystem.first;
while (psys_eval != NULL) {
if (psys_eval->orig_psys == psys) {
return psys_eval;
}
psys_eval = psys_eval->next;
}
return psys_eval;
}
static PTCacheEdit *psys_orig_edit_get(ParticleSystem *psys)
{
if (psys->orig_psys == NULL) {
return psys->edit;
}
return psys->orig_psys->edit;
}
bool psys_in_edit_mode(Depsgraph *depsgraph, const ParticleSystem *psys)
{
const ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph);
if (view_layer->basact == NULL) {
/* TODO(sergey): Needs double-check with multi-object edit. */
return false;
}
const bool use_render_params = (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER);
const Object *object = view_layer->basact->object;
if (object->mode != OB_MODE_PARTICLE_EDIT) {
return false;
}
const ParticleSystem *psys_orig = psys_orig_get((ParticleSystem *)psys);
return (psys_orig->edit || psys->pointcache->edit) && (use_render_params == false);
}
bool psys_check_enabled(Object *ob, ParticleSystem *psys, const bool use_render_params)
{
ParticleSystemModifierData *psmd;
if (psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE || !psys->part) {
return 0;
}
psmd = psys_get_modifier(ob, psys);
if (use_render_params) {
if (!(psmd->modifier.mode & eModifierMode_Render)) {
return 0;
}
}
else if (!(psmd->modifier.mode & eModifierMode_Realtime)) {
return 0;
}
return 1;
}
bool psys_check_edited(ParticleSystem *psys)
{
if (psys->part && psys->part->type == PART_HAIR) {
return (psys->flag & PSYS_EDITED || (psys->edit && psys->edit->edited));
}
else {
return (psys->pointcache->edit && psys->pointcache->edit->edited);
}
}
void psys_find_group_weights(ParticleSettings *part)
{
/* Find object pointers based on index. If the collection is linked from
* another library linking may not have the object pointers available on
* file load, so we have to retrieve them later. See T49273. */
ListBase instance_collection_objects = {NULL, NULL};
if (part->instance_collection) {
instance_collection_objects = BKE_collection_object_cache_get(part->instance_collection);
}
for (ParticleDupliWeight *dw = part->instance_weights.first; dw; dw = dw->next) {
if (dw->ob == NULL) {
Base *base = BLI_findlink(&instance_collection_objects, dw->index);
if (base != NULL) {
dw->ob = base->object;
}
}
}
}
void psys_check_group_weights(ParticleSettings *part)
{
ParticleDupliWeight *dw, *tdw;
if (part->ren_as != PART_DRAW_GR || !part->instance_collection) {
BLI_freelistN(&part->instance_weights);
return;
}
/* Find object pointers. */
psys_find_group_weights(part);
/* Remove NULL objects, that were removed from the collection. */
dw = part->instance_weights.first;
while (dw) {
if (dw->ob == NULL ||
!BKE_collection_has_object_recursive(part->instance_collection, dw->ob)) {
tdw = dw->next;
BLI_freelinkN(&part->instance_weights, dw);
dw = tdw;
}
else {
dw = dw->next;
}
}
/* Add new objects in the collection. */
int index = 0;
FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (part->instance_collection, object) {
dw = part->instance_weights.first;
while (dw && dw->ob != object) {
dw = dw->next;
}
if (!dw) {
dw = MEM_callocN(sizeof(ParticleDupliWeight), "ParticleDupliWeight");
dw->ob = object;
dw->count = 1;
BLI_addtail(&part->instance_weights, dw);
}
dw->index = index++;
}
FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
/* Ensure there is an element marked as current. */
int current = 0;
for (dw = part->instance_weights.first; dw; dw = dw->next) {
if (dw->flag & PART_DUPLIW_CURRENT) {
current = 1;
break;
}
}
if (!current) {
dw = part->instance_weights.first;
if (dw) {
dw->flag |= PART_DUPLIW_CURRENT;
}
}
}
int psys_uses_gravity(ParticleSimulationData *sim)
{
return sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY && sim->psys->part &&
sim->psys->part->effector_weights->global_gravity != 0.0f;
}
/************************************************/
/* Freeing stuff */
/************************************************/
static void fluid_free_settings(SPHFluidSettings *fluid)
{
if (fluid) {
MEM_freeN(fluid);
}
}
/**
* Free (or release) any data used by this particle settings (does not free the partsett itself).
*/
void BKE_particlesettings_free(ParticleSettings *part)
{
int a;
BKE_animdata_free((ID *)part, false);
for (a = 0; a < MAX_MTEX; a++) {
MEM_SAFE_FREE(part->mtex[a]);
}
if (part->clumpcurve) {
BKE_curvemapping_free(part->clumpcurve);
}
if (part->roughcurve) {
BKE_curvemapping_free(part->roughcurve);
}
if (part->twistcurve) {
BKE_curvemapping_free(part->twistcurve);
}
BKE_partdeflect_free(part->pd);
BKE_partdeflect_free(part->pd2);
MEM_SAFE_FREE(part->effector_weights);
BLI_freelistN(&part->instance_weights);
boid_free_settings(part->boids);
fluid_free_settings(part->fluid);
}
void free_hair(Object *object, ParticleSystem *psys, int dynamics)
{
PARTICLE_P;
LOOP_PARTICLES
{
if (pa->hair) {
MEM_freeN(pa->hair);
}
pa->hair = NULL;
pa->totkey = 0;
}
psys->flag &= ~PSYS_HAIR_DONE;
if (psys->clmd) {
if (dynamics) {
modifier_free((ModifierData *)psys->clmd);
psys->clmd = NULL;
PTCacheID pid;
BKE_ptcache_id_from_particles(&pid, object, psys);
BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_ALL, 0);
}
else {
cloth_free_modifier(psys->clmd);
}
}
if (psys->hair_in_mesh) {
BKE_id_free(NULL, psys->hair_in_mesh);
}
psys->hair_in_mesh = NULL;
if (psys->hair_out_mesh) {
BKE_id_free(NULL, psys->hair_out_mesh);
}
psys->hair_out_mesh = NULL;
}
void free_keyed_keys(ParticleSystem *psys)
{
PARTICLE_P;
if (psys->part->type == PART_HAIR) {
return;
}
if (psys->particles && psys->particles->keys) {
MEM_freeN(psys->particles->keys);
LOOP_PARTICLES
{
if (pa->keys) {
pa->keys = NULL;
pa->totkey = 0;
}
}
}
}
static void free_child_path_cache(ParticleSystem *psys)
{
psys_free_path_cache_buffers(psys->childcache, &psys->childcachebufs);
psys->childcache = NULL;
psys->totchildcache = 0;
}
void psys_free_path_cache(ParticleSystem *psys, PTCacheEdit *edit)
{
if (edit) {
psys_free_path_cache_buffers(edit->pathcache, &edit->pathcachebufs);
edit->pathcache = NULL;
edit->totcached = 0;
}
if (psys) {
psys_free_path_cache_buffers(psys->pathcache, &psys->pathcachebufs);
psys->pathcache = NULL;
psys->totcached = 0;
free_child_path_cache(psys);
}
}
void psys_free_children(ParticleSystem *psys)
{
if (psys->child) {
MEM_freeN(psys->child);
psys->child = NULL;
psys->totchild = 0;
}
free_child_path_cache(psys);
}
void psys_free_particles(ParticleSystem *psys)
{
PARTICLE_P;
if (psys->particles) {
/* Even though psys->part should never be NULL,
* this can happen as an exception during deletion.
* See ID_REMAP_SKIP/FORCE/FLAG_NEVER_NULL_USAGE in BKE_library_remap. */
if (psys->part && psys->part->type == PART_HAIR) {
LOOP_PARTICLES
{
if (pa->hair) {
MEM_freeN(pa->hair);
}
}
}
if (psys->particles->keys) {
MEM_freeN(psys->particles->keys);
}
if (psys->particles->boid) {
MEM_freeN(psys->particles->boid);
}
MEM_freeN(psys->particles);
psys->particles = NULL;
psys->totpart = 0;
}
}
void psys_free_pdd(ParticleSystem *psys)
{
if (psys->pdd) {
if (psys->pdd->cdata) {
MEM_freeN(psys->pdd->cdata);
}
psys->pdd->cdata = NULL;
if (psys->pdd->vdata) {
MEM_freeN(psys->pdd->vdata);
}
psys->pdd->vdata = NULL;
if (psys->pdd->ndata) {
MEM_freeN(psys->pdd->ndata);
}
psys->pdd->ndata = NULL;
if (psys->pdd->vedata) {
MEM_freeN(psys->pdd->vedata);
}
psys->pdd->vedata = NULL;
psys->pdd->totpoint = 0;
psys->pdd->totpart = 0;
psys->pdd->partsize = 0;
}
}
/* free everything */
void psys_free(Object *ob, ParticleSystem *psys)
{
if (psys) {
int nr = 0;
ParticleSystem *tpsys;
psys_free_path_cache(psys, NULL);
/* NOTE: We pass dynamics=0 to free_hair() to prevent it from doing an
* unneeded clear of the cache. But for historical reason that code path
* was only clearing cloth part of modifier data.
*
* Part of the story there is that particle evaluation is trying to not
* re-allocate thew ModifierData itself, and limits all allocations to
* the cloth part of it.
*
* Why evaluation is relying on hair_free() and in some specific code
* paths there is beyond me.
*/
free_hair(ob, psys, 0);
if (psys->clmd != NULL) {
modifier_free((ModifierData *)psys->clmd);
}
psys_free_particles(psys);
if (psys->edit && psys->free_edit) {
psys->free_edit(psys->edit);
}
if (psys->child) {
MEM_freeN(psys->child);
psys->child = NULL;
psys->totchild = 0;
}
/* check if we are last non-visible particle system */
for (tpsys = ob->particlesystem.first; tpsys; tpsys = tpsys->next) {
if (tpsys->part) {
if (ELEM(tpsys->part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
nr++;
break;
}
}
}
/* clear do-not-draw-flag */
if (!nr) {
ob->transflag &= ~OB_DUPLIPARTS;
}
psys->part = NULL;
if ((psys->flag & PSYS_SHARED_CACHES) == 0) {
BKE_ptcache_free_list(&psys->ptcaches);
}
psys->pointcache = NULL;
BLI_freelistN(&psys->targets);
BLI_bvhtree_free(psys->bvhtree);
BLI_kdtree_3d_free(psys->tree);
if (psys->fluid_springs) {
MEM_freeN(psys->fluid_springs);
}
BKE_effectors_free(psys->effectors);
if (psys->pdd) {
psys_free_pdd(psys);
MEM_freeN(psys->pdd);
}
BKE_particle_batch_cache_free(psys);
MEM_freeN(psys);
}
}
void psys_copy_particles(ParticleSystem *psys_dst, ParticleSystem *psys_src)
{
/* Free existing particles. */
if (psys_dst->particles != psys_src->particles) {
psys_free_particles(psys_dst);
}
if (psys_dst->child != psys_src->child) {
psys_free_children(psys_dst);
}
/* Restore counters. */
psys_dst->totpart = psys_src->totpart;
psys_dst->totchild = psys_src->totchild;
/* Copy particles and children. */
psys_dst->particles = MEM_dupallocN(psys_src->particles);
psys_dst->child = MEM_dupallocN(psys_src->child);
if (psys_dst->part->type == PART_HAIR) {
ParticleData *pa;
int p;
for (p = 0, pa = psys_dst->particles; p < psys_dst->totpart; p++, pa++) {
pa->hair = MEM_dupallocN(pa->hair);
}
}
if (psys_dst->particles && (psys_dst->particles->keys || psys_dst->particles->boid)) {
ParticleKey *key = psys_dst->particles->keys;
BoidParticle *boid = psys_dst->particles->boid;
ParticleData *pa;
int p;
if (key != NULL) {
key = MEM_dupallocN(key);
}
if (boid != NULL) {
boid = MEM_dupallocN(boid);
}
for (p = 0, pa = psys_dst->particles; p < psys_dst->totpart; p++, pa++) {
if (boid != NULL) {
pa->boid = boid++;
}
if (key != NULL) {
pa->keys = key;
key += pa->totkey;
}
}
}
}
/************************************************/
/* Interpolation */
/************************************************/
static float interpolate_particle_value(
float v1, float v2, float v3, float v4, const float w[4], int four)
{
float value;
value = w[0] * v1 + w[1] * v2 + w[2] * v3;
if (four) {
value += w[3] * v4;
}
CLAMP(value, 0.f, 1.f);
return value;
}
void psys_interpolate_particle(
short type, ParticleKey keys[4], float dt, ParticleKey *result, bool velocity)
{
float t[4];
if (type < 0) {
interp_cubic_v3(result->co, result->vel, keys[1].co, keys[1].vel, keys[2].co, keys[2].vel, dt);
}
else {
key_curve_position_weights(dt, t, type);
interp_v3_v3v3v3v3(result->co, keys[0].co, keys[1].co, keys[2].co, keys[3].co, t);
if (velocity) {
float temp[3];
if (dt > 0.999f) {
key_curve_position_weights(dt - 0.001f, t, type);
interp_v3_v3v3v3v3(temp, keys[0].co, keys[1].co, keys[2].co, keys[3].co, t);
sub_v3_v3v3(result->vel, result->co, temp);
}
else {
key_curve_position_weights(dt + 0.001f, t, type);
interp_v3_v3v3v3v3(temp, keys[0].co, keys[1].co, keys[2].co, keys[3].co, t);
sub_v3_v3v3(result->vel, temp, result->co);
}
}
}
}
typedef struct ParticleInterpolationData {
HairKey *hkey[2];
Mesh *mesh;
MVert *mvert[2];
int keyed;
ParticleKey *kkey[2];
PointCache *cache;
PTCacheMem *pm;
PTCacheEditPoint *epoint;
PTCacheEditKey *ekey[2];
float birthtime, dietime;
int bspline;
} ParticleInterpolationData;
/**
* Assumes pointcache->mem_cache exists, so for disk cached particles
* call #psys_make_temp_pointcache() before use.
* It uses #ParticleInterpolationData.pm to store the current memory cache frame
* so it's thread safe.
*/
static void get_pointcache_keys_for_time(Object *UNUSED(ob),
PointCache *cache,
PTCacheMem **cur,
int index,
float t,
ParticleKey *key1,
ParticleKey *key2)
{
static PTCacheMem *pm = NULL;
int index1, index2;
if (index < 0) { /* initialize */
*cur = cache->mem_cache.first;
if (*cur) {
*cur = (*cur)->next;
}
}
else {
if (*cur) {
while (*cur && (*cur)->next && (float)(*cur)->frame < t) {
*cur = (*cur)->next;
}
pm = *cur;
index2 = BKE_ptcache_mem_index_find(pm, index);
index1 = BKE_ptcache_mem_index_find(pm->prev, index);
if (index2 < 0) {
return;
}
BKE_ptcache_make_particle_key(key2, index2, pm->data, (float)pm->frame);
if (index1 < 0) {
copy_particle_key(key1, key2, 1);
}
else {
BKE_ptcache_make_particle_key(key1, index1, pm->prev->data, (float)pm->prev->frame);
}
}
else if (cache->mem_cache.first) {
pm = cache->mem_cache.first;
index2 = BKE_ptcache_mem_index_find(pm, index);
if (index2 < 0) {
return;
}
BKE_ptcache_make_particle_key(key2, index2, pm->data, (float)pm->frame);
copy_particle_key(key1, key2, 1);
}
}
}
static int get_pointcache_times_for_particle(PointCache *cache,
int index,
float *start,
float *end)
{
PTCacheMem *pm;
int ret = 0;
for (pm = cache->mem_cache.first; pm; pm = pm->next) {
if (BKE_ptcache_mem_index_find(pm, index) >= 0) {
*start = pm->frame;
ret++;
break;
}
}
for (pm = cache->mem_cache.last; pm; pm = pm->prev) {
if (BKE_ptcache_mem_index_find(pm, index) >= 0) {
*end = pm->frame;
ret++;
break;
}
}
return ret == 2;
}
float psys_get_dietime_from_cache(PointCache *cache, int index)
{
PTCacheMem *pm;
int dietime = 10000000; /* some max value so that we can default to pa->time+lifetime */
for (pm = cache->mem_cache.last; pm; pm = pm->prev) {
if (BKE_ptcache_mem_index_find(pm, index) >= 0) {
return (float)pm->frame;
}
}
return (float)dietime;
}
static void init_particle_interpolation(Object *ob,
ParticleSystem *psys,
ParticleData *pa,
ParticleInterpolationData *pind)
{
if (pind->epoint) {
PTCacheEditPoint *point = pind->epoint;
pind->ekey[0] = point->keys;
pind->ekey[1] = point->totkey > 1 ? point->keys + 1 : NULL;
pind->birthtime = *(point->keys->time);
pind->dietime = *((point->keys + point->totkey - 1)->time);
}
else if (pind->keyed) {
ParticleKey *key = pa->keys;
pind->kkey[0] = key;
pind->kkey[1] = pa->totkey > 1 ? key + 1 : NULL;
pind->birthtime = key->time;
pind->dietime = (key + pa->totkey - 1)->time;
}
else if (pind->cache) {
float start = 0.0f, end = 0.0f;
get_pointcache_keys_for_time(ob, pind->cache, &pind->pm, -1, 0.0f, NULL, NULL);
pind->birthtime = pa ? pa->time : pind->cache->startframe;
pind->dietime = pa ? pa->dietime : pind->cache->endframe;
if (get_pointcache_times_for_particle(pind->cache, pa - psys->particles, &start, &end)) {
pind->birthtime = MAX2(pind->birthtime, start);
pind->dietime = MIN2(pind->dietime, end);
}
}
else {
HairKey *key = pa->hair;
pind->hkey[0] = key;
pind->hkey[1] = key + 1;
pind->birthtime = key->time;
pind->dietime = (key + pa->totkey - 1)->time;
if (pind->mesh) {
pind->mvert[0] = &pind->mesh->mvert[pa->hair_index];
pind->mvert[1] = pind->mvert[0] + 1;
}
}
}
static void edit_to_particle(ParticleKey *key, PTCacheEditKey *ekey)
{
copy_v3_v3(key->co, ekey->co);
if (ekey->vel) {
copy_v3_v3(key->vel, ekey->vel);
}
key->time = *(ekey->time);
}
static void hair_to_particle(ParticleKey *key, HairKey *hkey)
{
copy_v3_v3(key->co, hkey->co);
key->time = hkey->time;
}
static void mvert_to_particle(ParticleKey *key, MVert *mvert, HairKey *hkey)
{
copy_v3_v3(key->co, mvert->co);
key->time = hkey->time;
}
static void do_particle_interpolation(ParticleSystem *psys,
int p,
ParticleData *pa,
float t,
ParticleInterpolationData *pind,
ParticleKey *result)
{
PTCacheEditPoint *point = pind->epoint;
ParticleKey keys[4];
int point_vel = (point && point->keys->vel);
float real_t, dfra, keytime, invdt = 1.f;
/* billboards wont fill in all of these, so start cleared */
memset(keys, 0, sizeof(keys));
/* interpret timing and find keys */
if (point) {
if (result->time < 0.0f) {
real_t = -result->time;
}
else {
real_t = *(pind->ekey[0]->time) +
t * (*(pind->ekey[0][point->totkey - 1].time) - *(pind->ekey[0]->time));
}
while (*(pind->ekey[1]->time) < real_t) {
pind->ekey[1]++;
}
pind->ekey[0] = pind->ekey[1] - 1;
}
else if (pind->keyed) {
/* we have only one key, so let's use that */
if (pind->kkey[1] == NULL) {
copy_particle_key(result, pind->kkey[0], 1);
return;
}
if (result->time < 0.0f) {
real_t = -result->time;
}
else {
real_t = pind->kkey[0]->time +
t * (pind->kkey[0][pa->totkey - 1].time - pind->kkey[0]->time);
}
if (psys->part->phystype == PART_PHYS_KEYED && psys->flag & PSYS_KEYED_TIMING) {
ParticleTarget *pt = psys->targets.first;
pt = pt->next;
while (pt && pa->time + pt->time < real_t) {
pt = pt->next;
}
if (pt) {
pt = pt->prev;
if (pa->time + pt->time + pt->duration > real_t) {
real_t = pa->time + pt->time;
}
}
else {
real_t = pa->time + ((ParticleTarget *)psys->targets.last)->time;
}
}
CLAMP(real_t, pa->time, pa->dietime);
while (pind->kkey[1]->time < real_t) {
pind->kkey[1]++;
}
pind->kkey[0] = pind->kkey[1] - 1;
}
else if (pind->cache) {
if (result->time < 0.0f) { /* flag for time in frames */
real_t = -result->time;
}
else {
real_t = pa->time + t * (pa->dietime - pa->time);
}
}
else {
if (result->time < 0.0f) {
real_t = -result->time;
}
else {
real_t = pind->hkey[0]->time +
t * (pind->hkey[0][pa->totkey - 1].time - pind->hkey[0]->time);
}
while (pind->hkey[1]->time < real_t) {
pind->hkey[1]++;
pind->mvert[1]++;
}
pind->hkey[0] = pind->hkey[1] - 1;
}
/* set actual interpolation keys */
if (point) {
edit_to_particle(keys + 1, pind->ekey[0]);
edit_to_particle(keys + 2, pind->ekey[1]);
}
else if (pind->mesh) {
pind->mvert[0] = pind->mvert[1] - 1;
mvert_to_particle(keys + 1, pind->mvert[0], pind->hkey[0]);
mvert_to_particle(keys + 2, pind->mvert[1], pind->hkey[1]);
}
else if (pind->keyed) {
memcpy(keys + 1, pind->kkey[0], sizeof(ParticleKey));
memcpy(keys + 2, pind->kkey[1], sizeof(ParticleKey));
}
else if (pind->cache) {
get_pointcache_keys_for_time(NULL, pind->cache, &pind->pm, p, real_t, keys + 1, keys + 2);
}
else {
hair_to_particle(keys + 1, pind->hkey[0]);
hair_to_particle(keys + 2, pind->hkey[1]);
}
/* set secondary interpolation keys for hair */
if (!pind->keyed && !pind->cache && !point_vel) {
if (point) {
if (pind->ekey[0] != point->keys) {
edit_to_particle(keys, pind->ekey[0] - 1);
}
else {
edit_to_particle(keys, pind->ekey[0]);
}
}
else if (pind->mesh) {
if (pind->hkey[0] != pa->hair) {
mvert_to_particle(keys, pind->mvert[0] - 1, pind->hkey[0] - 1);
}
else {
mvert_to_particle(keys, pind->mvert[0], pind->hkey[0]);
}
}
else {
if (pind->hkey[0] != pa->hair) {
hair_to_particle(keys, pind->hkey[0] - 1);
}
else {
hair_to_particle(keys, pind->hkey[0]);
}
}
if (point) {
if (pind->ekey[1] != point->keys + point->totkey - 1) {
edit_to_particle(keys + 3, pind->ekey[1] + 1);
}
else {
edit_to_particle(keys + 3, pind->ekey[1]);
}
}
else if (pind->mesh) {
if (pind->hkey[1] != pa->hair + pa->totkey - 1) {
mvert_to_particle(keys + 3, pind->mvert[1] + 1, pind->hkey[1] + 1);
}
else {
mvert_to_particle(keys + 3, pind->mvert[1], pind->hkey[1]);
}
}
else {
if (pind->hkey[1] != pa->hair + pa->totkey - 1) {
hair_to_particle(keys + 3, pind->hkey[1] + 1);
}
else {
hair_to_particle(keys + 3, pind->hkey[1]);
}
}
}
dfra = keys[2].time - keys[1].time;
keytime = (real_t - keys[1].time) / dfra;
/* convert velocity to timestep size */
if (pind->keyed || pind->cache || point_vel) {
invdt = dfra * 0.04f * (psys ? psys->part->timetweak : 1.f);
mul_v3_fl(keys[1].vel, invdt);
mul_v3_fl(keys[2].vel, invdt);
interp_qt_qtqt(result->rot, keys[1].rot, keys[2].rot, keytime);
}
/* Now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between
* [0, 1]->[k2, k3] (k1 & k4 used for cardinal & bspline interpolation). */
psys_interpolate_particle((pind->keyed || pind->cache || point_vel) ?
-1 /* signal for cubic interpolation */
:
(pind->bspline ? KEY_BSPLINE : KEY_CARDINAL),
keys,
keytime,
result,
1);
/* the velocity needs to be converted back from cubic interpolation */
if (pind->keyed || pind->cache || point_vel) {
mul_v3_fl(result->vel, 1.f / invdt);
}
}
static void interpolate_pathcache(ParticleCacheKey *first, float t, ParticleCacheKey *result)
{
int i = 0;
ParticleCacheKey *cur = first;
/* scale the requested time to fit the entire path even if the path is cut early */
t *= (first + first->segments)->time;
while (i < first->segments && cur->time < t) {
cur++;
}
if (cur->time == t) {
*result = *cur;
}
else {
float dt = (t - (cur - 1)->time) / (cur->time - (cur - 1)->time);
interp_v3_v3v3(result->co, (cur - 1)->co, cur->co, dt);
interp_v3_v3v3(result->vel, (cur - 1)->vel, cur->vel, dt);
interp_qt_qtqt(result->rot, (cur - 1)->rot, cur->rot, dt);
result->time = t;
}
/* first is actual base rotation, others are incremental from first */
if (cur == first || cur - 1 == first) {
copy_qt_qt(result->rot, first->rot);
}
else {
mul_qt_qtqt(result->rot, first->rot, result->rot);
}
}
/************************************************/
/* Particles on a dm */
/************************************************/
/* interpolate a location on a face based on face coordinates */
void psys_interpolate_face(MVert *mvert,
MFace *mface,
MTFace *tface,
float (*orcodata)[3],
float w[4],
float vec[3],
float nor[3],
float utan[3],
float vtan[3],
float orco[3])
{
float *v1 = 0, *v2 = 0, *v3 = 0, *v4 = 0;
float e1[3], e2[3], s1, s2, t1, t2;
float *uv1, *uv2, *uv3, *uv4;
float n1[3], n2[3], n3[3], n4[3];
float tuv[4][2];
float *o1, *o2, *o3, *o4;
v1 = mvert[mface->v1].co;
v2 = mvert[mface->v2].co;
v3 = mvert[mface->v3].co;
normal_short_to_float_v3(n1, mvert[mface->v1].no);
normal_short_to_float_v3(n2, mvert[mface->v2].no);
normal_short_to_float_v3(n3, mvert[mface->v3].no);
if (mface->v4) {
v4 = mvert[mface->v4].co;
normal_short_to_float_v3(n4, mvert[mface->v4].no);
interp_v3_v3v3v3v3(vec, v1, v2, v3, v4, w);
if (nor) {
if (mface->flag & ME_SMOOTH) {
interp_v3_v3v3v3v3(nor, n1, n2, n3, n4, w);
}
else {
normal_quad_v3(nor, v1, v2, v3, v4);
}
}
}
else {
interp_v3_v3v3v3(vec, v1, v2, v3, w);
if (nor) {
if (mface->flag & ME_SMOOTH) {
interp_v3_v3v3v3(nor, n1, n2, n3, w);
}
else {
normal_tri_v3(nor, v1, v2, v3);
}
}
}
/* calculate tangent vectors */
if (utan && vtan) {
if (tface) {
uv1 = tface->uv[0];
uv2 = tface->uv[1];
uv3 = tface->uv[2];
uv4 = tface->uv[3];
}
else {
uv1 = tuv[0];
uv2 = tuv[1];
uv3 = tuv[2];
uv4 = tuv[3];
map_to_sphere(uv1, uv1 + 1, v1[0], v1[1], v1[2]);
map_to_sphere(uv2, uv2 + 1, v2[0], v2[1], v2[2]);
map_to_sphere(uv3, uv3 + 1, v3[0], v3[1], v3[2]);
if (v4) {
map_to_sphere(uv4, uv4 + 1, v4[0], v4[1], v4[2]);
}
}
if (v4) {
s1 = uv3[0] - uv1[0];
s2 = uv4[0] - uv1[0];
t1 = uv3[1] - uv1[1];
t2 = uv4[1] - uv1[1];
sub_v3_v3v3(e1, v3, v1);
sub_v3_v3v3(e2, v4, v1);
}
else {
s1 = uv2[0] - uv1[0];
s2 = uv3[0] - uv1[0];
t1 = uv2[1] - uv1[1];
t2 = uv3[1] - uv1[1];
sub_v3_v3v3(e1, v2, v1);
sub_v3_v3v3(e2, v3, v1);
}
vtan[0] = (s1 * e2[0] - s2 * e1[0]);
vtan[1] = (s1 * e2[1] - s2 * e1[1]);
vtan[2] = (s1 * e2[2] - s2 * e1[2]);
utan[0] = (t1 * e2[0] - t2 * e1[0]);
utan[1] = (t1 * e2[1] - t2 * e1[1]);
utan[2] = (t1 * e2[2] - t2 * e1[2]);
}
if (orco) {
if (orcodata) {
o1 = orcodata[mface->v1];
o2 = orcodata[mface->v2];
o3 = orcodata[mface->v3];
if (mface->v4) {
o4 = orcodata[mface->v4];
interp_v3_v3v3v3v3(orco, o1, o2, o3, o4, w);
}
else {
interp_v3_v3v3v3(orco, o1, o2, o3, w);
}
}
else {
copy_v3_v3(orco, vec);
}
}
}
void psys_interpolate_uvs(const MTFace *tface, int quad, const float w[4], float uvco[2])
{
float v10 = tface->uv[0][0];
float v11 = tface->uv[0][1];
float v20 = tface->uv[1][0];
float v21 = tface->uv[1][1];
float v30 = tface->uv[2][0];
float v31 = tface->uv[2][1];
float v40, v41;
if (quad) {
v40 = tface->uv[3][0];
v41 = tface->uv[3][1];
uvco[0] = w[0] * v10 + w[1] * v20 + w[2] * v30 + w[3] * v40;
uvco[1] = w[0] * v11 + w[1] * v21 + w[2] * v31 + w[3] * v41;
}
else {
uvco[0] = w[0] * v10 + w[1] * v20 + w[2] * v30;
uvco[1] = w[0] * v11 + w[1] * v21 + w[2] * v31;
}
}
void psys_interpolate_mcol(const MCol *mcol, int quad, const float w[4], MCol *mc)
{
const char *cp1, *cp2, *cp3, *cp4;
char *cp;
cp = (char *)mc;
cp1 = (const char *)&mcol[0];
cp2 = (const char *)&mcol[1];
cp3 = (const char *)&mcol[2];
if (quad) {
cp4 = (char *)&mcol[3];
cp[0] = (int)(w[0] * cp1[0] + w[1] * cp2[0] + w[2] * cp3[0] + w[3] * cp4[0]);
cp[1] = (int)(w[0] * cp1[1] + w[1] * cp2[1] + w[2] * cp3[1] + w[3] * cp4[1]);
cp[2] = (int)(w[0] * cp1[2] + w[1] * cp2[2] + w[2] * cp3[2] + w[3] * cp4[2]);
cp[3] = (int)(w[0] * cp1[3] + w[1] * cp2[3] + w[2] * cp3[3] + w[3] * cp4[3]);
}
else {
cp[0] = (int)(w[0] * cp1[0] + w[1] * cp2[0] + w[2] * cp3[0]);
cp[1] = (int)(w[0] * cp1[1] + w[1] * cp2[1] + w[2] * cp3[1]);
cp[2] = (int)(w[0] * cp1[2] + w[1] * cp2[2] + w[2] * cp3[2]);
cp[3] = (int)(w[0] * cp1[3] + w[1] * cp2[3] + w[2] * cp3[3]);
}
}
static float psys_interpolate_value_from_verts(
Mesh *mesh, short from, int index, const float fw[4], const float *values)
{
if (values == 0 || index == -1) {
return 0.0;
}
switch (from) {
case PART_FROM_VERT:
return values[index];
case PART_FROM_FACE:
case PART_FROM_VOLUME: {
MFace *mf = &mesh->mface[index];
return interpolate_particle_value(
values[mf->v1], values[mf->v2], values[mf->v3], values[mf->v4], fw, mf->v4);
}
}
return 0.0f;
}
/* conversion of pa->fw to origspace layer coordinates */
static void psys_w_to_origspace(const float w[4], float uv[2])
{
uv[0] = w[1] + w[2];
uv[1] = w[2] + w[3];
}
/* conversion of pa->fw to weights in face from origspace */
static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, const float w[4], float neww[4])
{
float v[4][3], co[3];
v[0][0] = osface->uv[0][0];
v[0][1] = osface->uv[0][1];
v[0][2] = 0.0f;
v[1][0] = osface->uv[1][0];
v[1][1] = osface->uv[1][1];
v[1][2] = 0.0f;
v[2][0] = osface->uv[2][0];
v[2][1] = osface->uv[2][1];
v[2][2] = 0.0f;
psys_w_to_origspace(w, co);
co[2] = 0.0f;
if (quad) {
v[3][0] = osface->uv[3][0];
v[3][1] = osface->uv[3][1];
v[3][2] = 0.0f;
interp_weights_poly_v3(neww, v, 4, co);
}
else {
interp_weights_poly_v3(neww, v, 3, co);
neww[3] = 0.0f;
}
}
/**
* Find the final derived mesh tessface for a particle, from its original tessface index.
* This is slow and can be optimized but only for many lookups.
*
* \param mesh_final: Final mesh, it may not have the same topology as original mesh.
* \param mesh_original: Original mesh, use for accessing #MPoly to #MFace mapping.
* \param findex_orig: The input tessface index.
* \param fw: Face weights (position of the particle inside the \a findex_orig tessface).
* \param poly_nodes: May be NULL, otherwise an array of linked list,
* one for each final \a mesh_final polygon, containing all its tessfaces indices.
* \return The \a mesh_final tessface index.
*/
int psys_particle_dm_face_lookup(Mesh *mesh_final,
Mesh *mesh_original,
int findex_orig,
const float fw[4],
struct LinkNode **poly_nodes)
{
MFace *mtessface_final;
OrigSpaceFace *osface_final;
int pindex_orig;
float uv[2], (*faceuv)[2];
const int *index_mf_to_mpoly_deformed = NULL;
const int *index_mf_to_mpoly = NULL;
const int *index_mp_to_orig = NULL;
const int totface_final = mesh_final->totface;
const int totface_deformed = mesh_original ? mesh_original->totface : totface_final;
if (ELEM(0, totface_final, totface_deformed)) {
return DMCACHE_NOTFOUND;
}
index_mf_to_mpoly = CustomData_get_layer(&mesh_final->fdata, CD_ORIGINDEX);
index_mp_to_orig = CustomData_get_layer(&mesh_final->pdata, CD_ORIGINDEX);
BLI_assert(index_mf_to_mpoly);
if (mesh_original) {
index_mf_to_mpoly_deformed = CustomData_get_layer(&mesh_original->fdata, CD_ORIGINDEX);
}
else {
BLI_assert(mesh_final->runtime.deformed_only);
index_mf_to_mpoly_deformed = index_mf_to_mpoly;
}
BLI_assert(index_mf_to_mpoly_deformed);
pindex_orig = index_mf_to_mpoly_deformed[findex_orig];
if (mesh_original == NULL) {
mesh_original = mesh_final;
}
index_mf_to_mpoly_deformed = NULL;
mtessface_final = mesh_final->mface;
osface_final = CustomData_get_layer(&mesh_final->fdata, CD_ORIGSPACE);
if (osface_final == NULL) {
/* Assume we don't need osface_final data, and we get a direct 1-1 mapping... */
if (findex_orig < totface_final) {
// printf("\tNO CD_ORIGSPACE, assuming not needed\n");
return findex_orig;
}
else {
printf("\tNO CD_ORIGSPACE, error out of range\n");
return DMCACHE_NOTFOUND;
}
}
else if (findex_orig >= mesh_original->totface) {
return DMCACHE_NOTFOUND; /* index not in the original mesh */
}
psys_w_to_origspace(fw, uv);
if (poly_nodes) {
/* we can have a restricted linked list of faces to check, faster! */
LinkNode *tessface_node = poly_nodes[pindex_orig];
for (; tessface_node; tessface_node = tessface_node->next) {
int findex_dst = POINTER_AS_INT(tessface_node->link);
faceuv = osface_final[findex_dst].uv;
/* check that this intersects - Its possible this misses :/ -
* could also check its not between */
if (mtessface_final[findex_dst].v4) {
if (isect_point_quad_v2(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3])) {
return findex_dst;
}
}
else if (isect_point_tri_v2(uv, faceuv[0], faceuv[1], faceuv[2])) {
return findex_dst;
}
}
}
else { /* if we have no node, try every face */
for (int findex_dst = 0; findex_dst < totface_final; findex_dst++) {
/* If current tessface from 'final' DM and orig tessface (given by index)
* map to the same orig poly. */
if (BKE_mesh_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, findex_dst) ==
pindex_orig) {
faceuv = osface_final[findex_dst].uv;
/* check that this intersects - Its possible this misses :/ -
* could also check its not between */
if (mtessface_final[findex_dst].v4) {
if (isect_point_quad_v2(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3])) {
return findex_dst;
}
}
else if (isect_point_tri_v2(uv, faceuv[0], faceuv[1], faceuv[2])) {
return findex_dst;
}
}
}
}
return DMCACHE_NOTFOUND;
}
static int psys_map_index_on_dm(Mesh *mesh,
int from,
int index,
int index_dmcache,
const float fw[4],
float UNUSED(foffset),
int *mapindex,
float mapfw[4])
{
if (index < 0) {
return 0;
}
if (mesh->runtime.deformed_only || index_dmcache == DMCACHE_ISCHILD) {
/* for meshes that are either only deformed or for child particles, the
* index and fw do not require any mapping, so we can directly use it */
if (from == PART_FROM_VERT) {
if (index >= mesh->totvert) {
return 0;
}
*mapindex = index;
}
else { /* FROM_FACE/FROM_VOLUME */
if (index >= mesh->totface) {
return 0;
}
*mapindex = index;
copy_v4_v4(mapfw, fw);
}
}
else {
/* for other meshes that have been modified, we try to map the particle
* to their new location, which means a different index, and for faces
* also a new face interpolation weights */
if (from == PART_FROM_VERT) {
if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache >= mesh->totvert) {
return 0;
}
*mapindex = index_dmcache;
}
else { /* FROM_FACE/FROM_VOLUME */
/* find a face on the derived mesh that uses this face */
MFace *mface;
OrigSpaceFace *osface;
int i;
i = index_dmcache;
if (i == DMCACHE_NOTFOUND || i >= mesh->totface) {
return 0;
}
*mapindex = i;
/* modify the original weights to become
* weights for the derived mesh face */
osface = CustomData_get_layer(&mesh->fdata, CD_ORIGSPACE);
mface = &mesh->mface[i];
if (osface == NULL) {
mapfw[0] = mapfw[1] = mapfw[2] = mapfw[3] = 0.0f;
}
else {
psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw);
}
}
}
return 1;
}
/* interprets particle data to get a point on a mesh in object space */
void psys_particle_on_dm(Mesh *mesh_final,
int from,
int index,
int index_dmcache,
const float fw[4],
float foffset,
float vec[3],
float nor[3],
float utan[3],
float vtan[3],
float orco[3])
{
float tmpnor[3], mapfw[4];
float(*orcodata)[3];
int mapindex;
if (!psys_map_index_on_dm(
mesh_final, from, index, index_dmcache, fw, foffset, &mapindex, mapfw)) {
if (vec) {
vec[0] = vec[1] = vec[2] = 0.0;
}
if (nor) {
nor[0] = nor[1] = 0.0;
nor[2] = 1.0;
}
if (orco) {
orco[0] = orco[1] = orco[2] = 0.0;
}
if (utan) {
utan[0] = utan[1] = utan[2] = 0.0;
}
if (vtan) {
vtan[0] = vtan[1] = vtan[2] = 0.0;
}
return;
}
orcodata = CustomData_get_layer(&mesh_final->vdata, CD_ORCO);
if (from == PART_FROM_VERT) {
copy_v3_v3(vec, mesh_final->mvert[mapindex].co);
if (nor) {
normal_short_to_float_v3(nor, mesh_final->mvert[mapindex].no);
normalize_v3(nor);
}
if (orco) {
if (orcodata) {
copy_v3_v3(orco, orcodata[mapindex]);
}
else {
copy_v3_v3(orco, vec);
}
}
if (utan && vtan) {
utan[0] = utan[1] = utan[2] = 0.0f;
vtan[0] = vtan[1] = vtan[2] = 0.0f;
}
}
else { /* PART_FROM_FACE / PART_FROM_VOLUME */
MFace *mface;
MTFace *mtface;
MVert *mvert;
mface = &mesh_final->mface[mapindex];
mvert = mesh_final->mvert;
mtface = mesh_final->mtface;
if (mtface) {
mtface += mapindex;
}
if (from == PART_FROM_VOLUME) {
psys_interpolate_face(mvert, mface, mtface, orcodata, mapfw, vec, tmpnor, utan, vtan, orco);
if (nor) {
copy_v3_v3(nor, tmpnor);
}
normalize_v3(
tmpnor); /* XXX Why not normalize tmpnor before copying it into nor??? -- mont29 */
mul_v3_fl(tmpnor, -foffset);
add_v3_v3(vec, tmpnor);
}
else {
psys_interpolate_face(mvert, mface, mtface, orcodata, mapfw, vec, nor, utan, vtan, orco);
}
}
}
float psys_particle_value_from_verts(Mesh *mesh, short from, ParticleData *pa, float *values)
{
float mapfw[4];
int mapindex;
if (!psys_map_index_on_dm(
mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw)) {
return 0.0f;
}
return psys_interpolate_value_from_verts(mesh, from, mapindex, mapfw, values);
}
ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
{
ModifierData *md;
ParticleSystemModifierData *psmd;
for (md = ob->modifiers.first; md; md = md->next) {
if (md->type == eModifierType_ParticleSystem) {
psmd = (ParticleSystemModifierData *)md;
if (psmd->psys == psys) {
return psmd;
}
}
}
return NULL;
}
/************************************************/
/* Particles on a shape */
/************************************************/
/* ready for future use */
static void psys_particle_on_shape(int UNUSED(distr),
int UNUSED(index),
float *UNUSED(fuv),
float vec[3],
float nor[3],
float utan[3],
float vtan[3],
float orco[3])
{
/* TODO */
float zerovec[3] = {0.0f, 0.0f, 0.0f};
if (vec) {
copy_v3_v3(vec, zerovec);
}
if (nor) {
copy_v3_v3(nor, zerovec);
}
if (utan) {
copy_v3_v3(utan, zerovec);
}
if (vtan) {
copy_v3_v3(vtan, zerovec);
}
if (orco) {
copy_v3_v3(orco, zerovec);
}
}
/************************************************/
/* Particles on emitter */
/************************************************/
void psys_emitter_customdata_mask(ParticleSystem *psys, CustomData_MeshMasks *r_cddata_masks)
{
MTex *mtex;
int i;
if (!psys->part) {
return;
}
for (i = 0; i < MAX_MTEX; i++) {
mtex = psys->part->mtex[i];
if (mtex && mtex->mapto && (mtex->texco & TEXCO_UV)) {
r_cddata_masks->fmask |= CD_MASK_MTFACE;
}
}
if (psys->part->tanfac != 0.0f) {
r_cddata_masks->fmask |= CD_MASK_MTFACE;
}
/* ask for vertexgroups if we need them */
for (i = 0; i < PSYS_TOT_VG; i++) {
if (psys->vgroup[i]) {
r_cddata_masks->vmask |= CD_MASK_MDEFORMVERT;
break;
}
}
/* particles only need this if they are after a non deform modifier, and
* the modifier stack will only create them in that case. */
r_cddata_masks->lmask |= CD_MASK_ORIGSPACE_MLOOP;
/* XXX Check we do need all those? */
r_cddata_masks->vmask |= CD_MASK_ORIGINDEX;
r_cddata_masks->emask |= CD_MASK_ORIGINDEX;
r_cddata_masks->pmask |= CD_MASK_ORIGINDEX;
r_cddata_masks->vmask |= CD_MASK_ORCO;
}
void psys_particle_on_emitter(ParticleSystemModifierData *psmd,
int from,
int index,
int index_dmcache,
float fuv[4],
float foffset,
float vec[3],
float nor[3],
float utan[3],
float vtan[3],
float orco[3])
{
if (psmd && psmd->mesh_final) {
if (psmd->psys->part->distr == PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT) {
if (vec) {
copy_v3_v3(vec, fuv);
}
if (orco) {
copy_v3_v3(orco, fuv);
}
return;
}
/* we cant use the num_dmcache */
psys_particle_on_dm(
psmd->mesh_final, from, index, index_dmcache, fuv, foffset, vec, nor, utan, vtan, orco);
}
else {
psys_particle_on_shape(from, index, fuv, vec, nor, utan, vtan, orco);
}
}
/************************************************/
/* Path Cache */
/************************************************/
void precalc_guides(ParticleSimulationData *sim, ListBase *effectors)
{
EffectedPoint point;
ParticleKey state;
EffectorData efd;
EffectorCache *eff;
ParticleSystem *psys = sim->psys;
EffectorWeights *weights = sim->psys->part->effector_weights;
GuideEffectorData *data;
PARTICLE_P;
if (!effectors) {
return;
}
LOOP_PARTICLES
{
psys_particle_on_emitter(sim->psmd,
sim->psys->part->from,
pa->num,
pa->num_dmcache,
pa->fuv,
pa->foffset,
state.co,
0,
0,
0,
0);
mul_m4_v3(sim->ob->obmat, state.co);
mul_mat3_m4_v3(sim->ob->obmat, state.vel);
pd_point_from_particle(sim, pa, &state, &point);
for (eff = effectors->first; eff; eff = eff->next) {
if (eff->pd->forcefield != PFIELD_GUIDE) {
continue;
}
if (!eff->guide_data) {
eff->guide_data = MEM_callocN(sizeof(GuideEffectorData) * psys->totpart,
"GuideEffectorData");
}
data = eff->guide_data + p;
sub_v3_v3v3(efd.vec_to_point, state.co, eff->guide_loc);
copy_v3_v3(efd.nor, eff->guide_dir);
efd.distance = len_v3(efd.vec_to_point);
copy_v3_v3(data->vec_to_point, efd.vec_to_point);
data->strength = effector_falloff(eff, &efd, &point, weights);
}
}
}
int do_guides(Depsgraph *depsgraph,
ParticleSettings *part,
ListBase *effectors,
ParticleKey *state,
int index,
float time)
{
CurveMapping *clumpcurve = (part->child_flag & PART_CHILD_USE_CLUMP_CURVE) ? part->clumpcurve :
NULL;
CurveMapping *roughcurve = (part->child_flag & PART_CHILD_USE_ROUGH_CURVE) ? part->roughcurve :
NULL;
EffectorCache *eff;
PartDeflect *pd;
Curve *cu;
GuideEffectorData *data;
float effect[3] = {0.0f, 0.0f, 0.0f}, veffect[3] = {0.0f, 0.0f, 0.0f};
float guidevec[4], guidedir[3], rot2[4], temp[3];
float guidetime, radius, weight, angle, totstrength = 0.0f;
float vec_to_point[3];
if (effectors) {
for (eff = effectors->first; eff; eff = eff->next) {
pd = eff->pd;
if (pd->forcefield != PFIELD_GUIDE) {
continue;
}
data = eff->guide_data + index;
if (data->strength <= 0.0f) {
continue;
}
guidetime = time / (1.0f - pd->free_end);
if (guidetime > 1.0f) {
continue;
}
cu = (Curve *)eff->ob->data;
if (pd->flag & PFIELD_GUIDE_PATH_ADD) {
if (where_on_path(
eff->ob, data->strength * guidetime, guidevec, guidedir, NULL, &radius, &weight) ==
0) {
return 0;
}
}
else {
if (where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0) {
return 0;
}
}
mul_m4_v3(eff->ob->obmat, guidevec);
mul_mat3_m4_v3(eff->ob->obmat, guidedir);
normalize_v3(guidedir);
copy_v3_v3(vec_to_point, data->vec_to_point);
if (guidetime != 0.0f) {
/* curve direction */
cross_v3_v3v3(temp, eff->guide_dir, guidedir);
angle = dot_v3v3(eff->guide_dir, guidedir) / (len_v3(eff->guide_dir));
angle = saacos(angle);
axis_angle_to_quat(rot2, temp, angle);
mul_qt_v3(rot2, vec_to_point);
/* curve tilt */
axis_angle_to_quat(rot2, guidedir, guidevec[3] - eff->guide_loc[3]);
mul_qt_v3(rot2, vec_to_point);
}
/* curve taper */
if (cu->taperobj) {
mul_v3_fl(vec_to_point,
BKE_displist_calc_taper(depsgraph,
eff->scene,
cu->taperobj,
(int)(data->strength * guidetime * 100.0f),
100));
}
else { /* curve size*/
if (cu->flag & CU_PATH_RADIUS) {
mul_v3_fl(vec_to_point, radius);
}
}
if (clumpcurve) {
BKE_curvemapping_changed_all(clumpcurve);
}
if (roughcurve) {
BKE_curvemapping_changed_all(roughcurve);
}
{
ParticleKey key;
float par_co[3] = {0.0f, 0.0f, 0.0f};
float par_vel[3] = {0.0f, 0.0f, 0.0f};
float par_rot[4] = {1.0f, 0.0f, 0.0f, 0.0f};
float orco_offset[3] = {0.0f, 0.0f, 0.0f};
copy_v3_v3(key.co, vec_to_point);
do_kink(&key,
par_co,
par_vel,
par_rot,
guidetime,
pd->kink_freq,
pd->kink_shape,
pd->kink_amp,
0.f,
pd->kink,
pd->kink_axis,
0,
0);
do_clump(&key,
par_co,
guidetime,
orco_offset,
pd->clump_fac,
pd->clump_pow,
1.0f,
part->child_flag & PART_CHILD_USE_CLUMP_NOISE,
part->clump_noise_size,
clumpcurve);
copy_v3_v3(vec_to_point, key.co);
}
add_v3_v3(vec_to_point, guidevec);
// sub_v3_v3v3(pa_loc, pa_loc, pa_zero);
madd_v3_v3fl(effect, vec_to_point, data->strength);
madd_v3_v3fl(veffect, guidedir, data->strength);
totstrength += data->strength;
if (pd->flag & PFIELD_GUIDE_PATH_WEIGHT) {
totstrength *= weight;
}
}
}
if (totstrength != 0.0f) {
if (totstrength > 1.0f) {
mul_v3_fl(effect, 1.0f / totstrength);
}
CLAMP(totstrength, 0.0f, 1.0f);
// add_v3_v3(effect, pa_zero);
interp_v3_v3v3(state->co, state->co, effect, totstrength);
normalize_v3(veffect);
mul_v3_fl(veffect, len_v3(state->vel));
copy_v3_v3(state->vel, veffect);
return 1;
}
return 0;
}
static void do_path_effectors(ParticleSimulationData *sim,
int i,
ParticleCacheKey *ca,
int k,
int steps,
float *UNUSED(rootco),
float effector,
float UNUSED(dfra),
float UNUSED(cfra),
float *length,
float *vec)
{
float force[3] = {0.0f, 0.0f, 0.0f};
ParticleKey eff_key;
EffectedPoint epoint;
/* Don't apply effectors for dynamic hair, otherwise the effectors don't get applied twice. */
if (sim->psys->flag & PSYS_HAIR_DYNAMICS) {
return;
}
copy_v3_v3(eff_key.co, (ca - 1)->co);
copy_v3_v3(eff_key.vel, (ca - 1)->vel);
copy_qt_qt(eff_key.rot, (ca - 1)->rot);
pd_point_from_particle(sim, sim->psys->particles + i, &eff_key, &epoint);
BKE_effectors_apply(sim->psys->effectors,
sim->colliders,
sim->psys->part->effector_weights,
&epoint,
force,
NULL);
mul_v3_fl(force,
effector * powf((float)k / (float)steps, 100.0f * sim->psys->part->eff_hair) /
(float)steps);
add_v3_v3(force, vec);
normalize_v3(force);
if (k < steps) {
sub_v3_v3v3(vec, (ca + 1)->co, ca->co);
}
madd_v3_v3v3fl(ca->co, (ca - 1)->co, force, *length);
if (k < steps) {
*length = len_v3(vec);
}
}
static void offset_child(ChildParticle *cpa,
ParticleKey *par,
float *par_rot,
ParticleKey *child,
float flat,
float radius)
{
copy_v3_v3(child->co, cpa->fuv);
mul_v3_fl(child->co, radius);
child->co[0] *= flat;
copy_v3_v3(child->vel, par->vel);
if (par_rot) {
mul_qt_v3(par_rot, child->co);
copy_qt_qt(child->rot, par_rot);
}
else {
unit_qt(child->rot);
}
add_v3_v3(child->co, par->co);
}
float *psys_cache_vgroup(Mesh *mesh, ParticleSystem *psys, int vgroup)
{
float *vg = 0;
if (vgroup < 0) {
/* hair dynamics pinning vgroup */
}
else if (psys->vgroup[vgroup]) {
MDeformVert *dvert = mesh->dvert;
if (dvert) {
int totvert = mesh->totvert, i;
vg = MEM_callocN(sizeof(float) * totvert, "vg_cache");
if (psys->vg_neg & (1 << vgroup)) {
for (i = 0; i < totvert; i++) {
vg[i] = 1.0f - defvert_find_weight(&dvert[i], psys->vgroup[vgroup] - 1);
}
}
else {
for (i = 0; i < totvert; i++) {
vg[i] = defvert_find_weight(&dvert[i], psys->vgroup[vgroup] - 1);
}
}
}
}
return vg;
}
void psys_find_parents(ParticleSimulationData *sim, const bool use_render_params)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = sim->psys->part;
KDTree_3d *tree;
ChildParticle *cpa;
ParticleTexture ptex;
int p, totparent, totchild = sim->psys->totchild;
float co[3], orco[3];
int from = PART_FROM_FACE;
totparent = (int)(totchild * part->parents * 0.3f);
if (use_render_params && part->child_nbr && part->ren_child_nbr) {
totparent *= (float)part->child_nbr / (float)part->ren_child_nbr;
}
/* hard limit, workaround for it being ignored above */
if (sim->psys->totpart < totparent) {
totparent = sim->psys->totpart;
}
tree = BLI_kdtree_3d_new(totparent);
for (p = 0, cpa = sim->psys->child; p < totparent; p++, cpa++) {
psys_particle_on_emitter(
sim->psmd, from, cpa->num, DMCACHE_ISCHILD, cpa->fuv, cpa->foffset, co, 0, 0, 0, orco);
/* Check if particle doesn't exist because of texture influence.
* Insert only existing particles into kdtree. */
get_cpa_texture(sim->psmd->mesh_final,
psys,
part,
psys->particles + cpa->pa[0],
p,
cpa->num,
cpa->fuv,
orco,
&ptex,
PAMAP_DENS | PAMAP_CHILD,
psys->cfra);
if (ptex.exist >= psys_frand(psys, p + 24)) {
BLI_kdtree_3d_insert(tree, p, orco);
}
}
BLI_kdtree_3d_balance(tree);
for (; p < totchild; p++, cpa++) {
psys_particle_on_emitter(
sim->psmd, from, cpa->num, DMCACHE_ISCHILD, cpa->fuv, cpa->foffset, co, 0, 0, 0, orco);
cpa->parent = BLI_kdtree_3d_find_nearest(tree, orco, NULL);
}
BLI_kdtree_3d_free(tree);
}
static bool psys_thread_context_init_path(ParticleThreadContext *ctx,
ParticleSimulationData *sim,
Scene *scene,
float cfra,
const bool editupdate,
const bool use_render_params)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
int totparent = 0, between = 0;
int segments = 1 << part->draw_step;
int totchild = psys->totchild;
psys_thread_context_init(ctx, sim);
/*---start figuring out what is actually wanted---*/
if (psys_in_edit_mode(sim->depsgraph, psys)) {
ParticleEditSettings *pset = &scene->toolsettings->particle;
if ((use_render_params == 0) &&
(psys_orig_edit_get(psys) == NULL || pset->flag & PE_DRAW_PART) == 0) {
totchild = 0;
}
segments = 1 << pset->draw_step;
}
if (totchild && part->childtype == PART_CHILD_FACES) {
totparent = (int)(totchild * part->parents * 0.3f);
if (use_render_params && part->child_nbr && part->ren_child_nbr) {
totparent *= (float)part->child_nbr / (float)part->ren_child_nbr;
}
/* part->parents could still be 0 so we can't test with totparent */
between = 1;
}
if (use_render_params) {
segments = 1 << part->ren_step;
}
else {
totchild = (int)((float)totchild * (float)part->disp / 100.0f);
totparent = MIN2(totparent, totchild);
}
if (totchild == 0) {
return false;
}
/* fill context values */
ctx->between = between;
ctx->segments = segments;
if (ELEM(part->kink, PART_KINK_SPIRAL)) {
ctx->extra_segments = max_ii(part->kink_extra_steps, 1);
}
else {
ctx->extra_segments = 0;
}
ctx->totchild = totchild;
ctx->totparent = totparent;
ctx->parent_pass = 0;
ctx->cfra = cfra;
ctx->editupdate = editupdate;
psys->lattice_deform_data = psys_create_lattice_deform_data(&ctx->sim);
/* cache all relevant vertex groups if they exist */
ctx->vg_length = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_LENGTH);
ctx->vg_clump = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_CLUMP);
ctx->vg_kink = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_KINK);
ctx->vg_rough1 = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_ROUGH1);
ctx->vg_rough2 = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_ROUGH2);
ctx->vg_roughe = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_ROUGHE);
ctx->vg_twist = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_TWIST);
if (psys->part->flag & PART_CHILD_EFFECT) {
ctx->vg_effector = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_EFFECTOR);
}
/* prepare curvemapping tables */
if ((part->child_flag & PART_CHILD_USE_CLUMP_CURVE) && part->clumpcurve) {
ctx->clumpcurve = BKE_curvemapping_copy(part->clumpcurve);
BKE_curvemapping_changed_all(ctx->clumpcurve);
}
else {
ctx->clumpcurve = NULL;
}
if ((part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && part->roughcurve) {
ctx->roughcurve = BKE_curvemapping_copy(part->roughcurve);
BKE_curvemapping_changed_all(ctx->roughcurve);
}
else {
ctx->roughcurve = NULL;
}
if ((part->child_flag & PART_CHILD_USE_TWIST_CURVE) && part->twistcurve) {
ctx->twistcurve = BKE_curvemapping_copy(part->twistcurve);
BKE_curvemapping_changed_all(ctx->twistcurve);
}
else {
ctx->twistcurve = NULL;
}
return true;
}
static void psys_task_init_path(ParticleTask *task, ParticleSimulationData *sim)
{
/* init random number generator */
int seed = 31415926 + sim->psys->seed;
task->rng_path = BLI_rng_new(seed);
}
/* note: this function must be thread safe, except for branching! */
static void psys_thread_create_path(ParticleTask *task,
struct ChildParticle *cpa,
ParticleCacheKey *child_keys,
int i)
{
ParticleThreadContext *ctx = task->ctx;
Object *ob = ctx->sim.ob;
ParticleSystem *psys = ctx->sim.psys;
ParticleSettings *part = psys->part;
ParticleCacheKey **cache = psys->childcache;
PTCacheEdit *edit = psys_orig_edit_get(psys);
ParticleCacheKey **pcache = psys_in_edit_mode(ctx->sim.depsgraph, psys) && edit ?
edit->pathcache :
psys->pathcache;
ParticleCacheKey *child, *key[4];
ParticleTexture ptex;
float *cpa_fuv = 0, *par_rot = 0, rot[4];
float orco[3], hairmat[4][4], dvec[3], off1[4][3], off2[4][3];
float eff_length, eff_vec[3], weight[4];
int k, cpa_num;
short cpa_from;
if (!pcache) {
return;
}
if (ctx->between) {
ParticleData *pa = psys->particles + cpa->pa[0];
int w, needupdate;
float foffset, wsum = 0.f;
float co[3];
float p_min = part->parting_min;
float p_max = part->parting_max;
/* Virtual parents don't work nicely with parting. */
float p_fac = part->parents > 0.f ? 0.f : part->parting_fac;
if (ctx->editupdate) {
needupdate = 0;
w = 0;
while (w < 4 && cpa->pa[w] >= 0) {
if (edit->points[cpa->pa[w]].flag & PEP_EDIT_RECALC) {
needupdate = 1;
break;
}
w++;
}
if (!needupdate) {
return;
}
else {
memset(child_keys, 0, sizeof(*child_keys) * (ctx->segments + 1));
}
}
/* get parent paths */
for (w = 0; w < 4; w++) {
if (cpa->pa[w] >= 0) {
key[w] = pcache[cpa->pa[w]];
weight[w] = cpa->w[w];
}
else {
key[w] = pcache[0];
weight[w] = 0.f;
}
}
/* modify weights to create parting */
if (p_fac > 0.f) {
const ParticleCacheKey *key_0_last = pcache_key_segment_endpoint_safe(key[0]);
for (w = 0; w < 4; w++) {
if (w && (weight[w] > 0.f)) {
const ParticleCacheKey *key_w_last = pcache_key_segment_endpoint_safe(key[w]);
float d;
if (part->flag & PART_CHILD_LONG_HAIR) {
/* For long hair use tip distance/root distance as parting
* factor instead of root to tip angle. */
float d1 = len_v3v3(key[0]->co, key[w]->co);
float d2 = len_v3v3(key_0_last->co, key_w_last->co);
d = d1 > 0.f ? d2 / d1 - 1.f : 10000.f;
}
else {
float v1[3], v2[3];
sub_v3_v3v3(v1, key_0_last->co, key[0]->co);
sub_v3_v3v3(v2, key_w_last->co, key[w]->co);
normalize_v3(v1);
normalize_v3(v2);
d = RAD2DEGF(saacos(dot_v3v3(v1, v2)));
}
if (p_max > p_min) {
d = (d - p_min) / (p_max - p_min);
}
else {
d = (d - p_min) <= 0.f ? 0.f : 1.f;
}
CLAMP(d, 0.f, 1.f);
if (d > 0.f) {
weight[w] *= (1.f - d);
}
}
wsum += weight[w];
}
for (w = 0; w < 4; w++) {
weight[w] /= wsum;
}
interp_v4_v4v4(weight, cpa->w, weight, p_fac);
}
/* get the original coordinates (orco) for texture usage */
cpa_num = cpa->num;
foffset = cpa->foffset;
cpa_fuv = cpa->fuv;
cpa_from = PART_FROM_FACE;
psys_particle_on_emitter(
ctx->sim.psmd, cpa_from, cpa_num, DMCACHE_ISCHILD, cpa->fuv, foffset, co, 0, 0, 0, orco);
mul_m4_v3(ob->obmat, co);
for (w = 0; w < 4; w++) {
sub_v3_v3v3(off1[w], co, key[w]->co);
}
psys_mat_hair_to_global(ob, ctx->sim.psmd->mesh_final, psys->part->from, pa, hairmat);
}
else {
ParticleData *pa = psys->particles + cpa->parent;
float co[3];
if (ctx->editupdate) {
if (!(edit->points[cpa->parent].flag & PEP_EDIT_RECALC)) {
return;
}
memset(child_keys, 0, sizeof(*child_keys) * (ctx->segments + 1));
}
/* get the parent path */
key[0] = pcache[cpa->parent];
/* get the original coordinates (orco) for texture usage */
cpa_from = part->from;
/*
* NOTE: Should in theory be the same as:
* cpa_num = psys_particle_dm_face_lookup(
* ctx->sim.psmd->dm_final,
* ctx->sim.psmd->dm_deformed,
* pa->num, pa->fuv,
* NULL);
*/
cpa_num = (ELEM(pa->num_dmcache, DMCACHE_ISCHILD, DMCACHE_NOTFOUND)) ? pa->num :
pa->num_dmcache;
/* XXX hack to avoid messed up particle num and subsequent crash (#40733) */
if (cpa_num > ctx->sim.psmd->mesh_final->totface) {
cpa_num = 0;
}
cpa_fuv = pa->fuv;
psys_particle_on_emitter(ctx->sim.psmd,
cpa_from,
cpa_num,
DMCACHE_ISCHILD,
cpa_fuv,
pa->foffset,
co,
0,
0,
0,
orco);
psys_mat_hair_to_global(ob, ctx->sim.psmd->mesh_final, psys->part->from, pa, hairmat);
}
child_keys->segments = ctx->segments;
/* get different child parameters from textures & vgroups */
get_child_modifier_parameters(part, ctx, cpa, cpa_from, cpa_num, cpa_fuv, orco, &ptex);
if (ptex.exist < psys_frand(psys, i + 24)) {
child_keys->segments = -1;
return;
}
/* create the child path */
for (k = 0, child = child_keys; k <= ctx->segments; k++, child++) {
if (ctx->between) {
int w = 0;
zero_v3(child->co);
zero_v3(child->vel);
unit_qt(child->rot);
for (w = 0; w < 4; w++) {
copy_v3_v3(off2[w], off1[w]);
if (part->flag & PART_CHILD_LONG_HAIR) {
/* Use parent rotation (in addition to emission location) to determine child offset. */
if (k) {
mul_qt_v3((key[w] + k)->rot, off2[w]);
}
/* Fade the effect of rotation for even lengths in the end */
project_v3_v3v3(dvec, off2[w], (key[w] + k)->vel);
madd_v3_v3fl(off2[w], dvec, -(float)k / (float)ctx->segments);
}
add_v3_v3(off2[w], (key[w] + k)->co);
}
/* child position is the weighted sum of parent positions */
interp_v3_v3v3v3v3(child->co, off2[0], off2[1], off2[2], off2[3], weight);
interp_v3_v3v3v3v3(child->vel,
(key[0] + k)->vel,
(key[1] + k)->vel,
(key[2] + k)->vel,
(key[3] + k)->vel,
weight);
copy_qt_qt(child->rot, (key[0] + k)->rot);
}
else {
if (k) {
mul_qt_qtqt(rot, (key[0] + k)->rot, key[0]->rot);
par_rot = rot;
}
else {
par_rot = key[0]->rot;
}
/* offset the child from the parent position */
offset_child(cpa,
(ParticleKey *)(key[0] + k),
par_rot,
(ParticleKey *)child,
part->childflat,
part->childrad);
}
child->time = (float)k / (float)ctx->segments;
}
/* apply effectors */
if (part->flag & PART_CHILD_EFFECT) {
for (k = 0, child = child_keys; k <= ctx->segments; k++, child++) {
if (k) {
do_path_effectors(&ctx->sim,
cpa->pa[0],
child,
k,
ctx->segments,
child_keys->co,
ptex.effector,
0.0f,
ctx->cfra,
&eff_length,
eff_vec);
}
else {
sub_v3_v3v3(eff_vec, (child + 1)->co, child->co);
eff_length = len_v3(eff_vec);
}
}
}
{
ParticleData *pa = NULL;
ParticleCacheKey *par = NULL;
float par_co[3];
float par_orco[3];
if (ctx->totparent) {
if (i >= ctx->totparent) {
pa = &psys->particles[cpa->parent];
/* this is now threadsafe, virtual parents are calculated before rest of children */
BLI_assert(cpa->parent < psys->totchildcache);
par = cache[cpa->parent];
}
}
else if (cpa->parent >= 0) {
pa = &psys->particles[cpa->parent];
par = pcache[cpa->parent];
/* If particle is unexisting, try to pick a viable parent from particles
* used for interpolation. */
for (k = 0; k < 4 && pa && (pa->flag & PARS_UNEXIST); k++) {
if (cpa->pa[k] >= 0) {
pa = &psys->particles[cpa->pa[k]];
par = pcache[cpa->pa[k]];
}
}
if (pa->flag & PARS_UNEXIST) {
pa = NULL;
}
}
if (pa) {
ListBase modifiers;
BLI_listbase_clear(&modifiers);
psys_particle_on_emitter(ctx->sim.psmd,
part->from,
pa->num,
pa->num_dmcache,
pa->fuv,
pa->foffset,
par_co,
NULL,
NULL,
NULL,
par_orco);
psys_apply_child_modifiers(
ctx, &modifiers, cpa, &ptex, orco, hairmat, child_keys, par, par_orco);
}
else {
zero_v3(par_orco);
}
}
/* Hide virtual parents */
if (i < ctx->totparent) {
child_keys->segments = -1;
}
}
static void exec_child_path_cache(TaskPool *__restrict UNUSED(pool),
void *taskdata,
int UNUSED(threadid))
{
ParticleTask *task = taskdata;
ParticleThreadContext *ctx = task->ctx;
ParticleSystem *psys = ctx->sim.psys;
ParticleCacheKey **cache = psys->childcache;
ChildParticle *cpa;
int i;
cpa = psys->child + task->begin;
for (i = task->begin; i < task->end; ++i, ++cpa) {
BLI_assert(i < psys->totchildcache);
psys_thread_create_path(task, cpa, cache[i], i);
}
}
void psys_cache_child_paths(ParticleSimulationData *sim,
float cfra,
const bool editupdate,
const bool use_render_params)
{
TaskScheduler *task_scheduler;
TaskPool *task_pool;
ParticleThreadContext ctx;
ParticleTask *tasks_parent, *tasks_child;
int numtasks_parent, numtasks_child;
int i, totchild, totparent;
if (sim->psys->flag & PSYS_GLOBAL_HAIR) {
return;
}
/* create a task pool for child path tasks */
if (!psys_thread_context_init_path(&ctx, sim, sim->scene, cfra, editupdate, use_render_params)) {
return;
}
task_scheduler = BLI_task_scheduler_get();
task_pool = BLI_task_pool_create(task_scheduler, &ctx);
totchild = ctx.totchild;
totparent = ctx.totparent;
if (editupdate && sim->psys->childcache && totchild == sim->psys->totchildcache) {
/* just overwrite the existing cache */
}
else {
/* clear out old and create new empty path cache */
free_child_path_cache(sim->psys);
sim->psys->childcache = psys_alloc_path_cache_buffers(
&sim->psys->childcachebufs, totchild, ctx.segments + ctx.extra_segments + 1);
sim->psys->totchildcache = totchild;
}
/* cache parent paths */
ctx.parent_pass = 1;
psys_tasks_create(&ctx, 0, totparent, &tasks_parent, &numtasks_parent);
for (i = 0; i < numtasks_parent; ++i) {
ParticleTask *task = &tasks_parent[i];
psys_task_init_path(task, sim);
BLI_task_pool_push(task_pool, exec_child_path_cache, task, false, TASK_PRIORITY_LOW);
}
BLI_task_pool_work_and_wait(task_pool);
/* cache child paths */
ctx.parent_pass = 0;
psys_tasks_create(&ctx, totparent, totchild, &tasks_child, &numtasks_child);
for (i = 0; i < numtasks_child; ++i) {
ParticleTask *task = &tasks_child[i];
psys_task_init_path(task, sim);
BLI_task_pool_push(task_pool, exec_child_path_cache, task, false, TASK_PRIORITY_LOW);
}
BLI_task_pool_work_and_wait(task_pool);
BLI_task_pool_free(task_pool);
psys_tasks_free(tasks_parent, numtasks_parent);
psys_tasks_free(tasks_child, numtasks_child);
psys_thread_context_free(&ctx);
}
/* figure out incremental rotations along path starting from unit quat */
static void cache_key_incremental_rotation(ParticleCacheKey *key0,
ParticleCacheKey *key1,
ParticleCacheKey *key2,
float *prev_tangent,
int i)
{
float cosangle, angle, tangent[3], normal[3], q[4];
switch (i) {
case 0:
/* start from second key */
break;
case 1:
/* calculate initial tangent for incremental rotations */
sub_v3_v3v3(prev_tangent, key0->co, key1->co);
normalize_v3(prev_tangent);
unit_qt(key1->rot);
break;
default:
sub_v3_v3v3(tangent, key0->co, key1->co);
normalize_v3(tangent);
cosangle = dot_v3v3(tangent, prev_tangent);
/* note we do the comparison on cosangle instead of
* angle, since floating point accuracy makes it give
* different results across platforms */
if (cosangle > 0.999999f) {
copy_v4_v4(key1->rot, key2->rot);
}
else {
angle = saacos(cosangle);
cross_v3_v3v3(normal, prev_tangent, tangent);
axis_angle_to_quat(q, normal, angle);
mul_qt_qtqt(key1->rot, q, key2->rot);
}
copy_v3_v3(prev_tangent, tangent);
}
}
/**
* Calculates paths ready for drawing/rendering
* - Useful for making use of opengl vertex arrays for super fast strand drawing.
* - Makes child strands possible and creates them too into the cache.
* - Cached path data is also used to determine cut position for the editmode tool. */
void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_render_params)
{
PARTICLE_PSMD;
ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
ParticleCacheKey *ca, **cache;
Mesh *hair_mesh = (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS) ?
psys->hair_out_mesh :
NULL;
ParticleKey result;
Material *ma;
ParticleInterpolationData pind;
ParticleTexture ptex;
PARTICLE_P;
float birthtime = 0.0, dietime = 0.0;
float t, time = 0.0, dfra = 1.0 /* , frs_sec = sim->scene->r.frs_sec*/ /*UNUSED*/;
float col[4] = {0.5f, 0.5f, 0.5f, 1.0f};
float prev_tangent[3] = {0.0f, 0.0f, 0.0f}, hairmat[4][4];
float rotmat[3][3];
int k;
int segments = (int)pow(2.0, (double)((use_render_params) ? part->ren_step : part->draw_step));
int totpart = psys->totpart;
float length, vec[3];
float *vg_effector = NULL;
float *vg_length = NULL, pa_length = 1.0f;
int keyed, baked;
/* we don't have anything valid to create paths from so let's quit here */
if ((psys->flag & PSYS_HAIR_DONE || psys->flag & PSYS_KEYED || psys->pointcache) == 0) {
return;
}
if (psys_in_edit_mode(sim->depsgraph, psys)) {
if ((psys->edit == NULL || pset->flag & PE_DRAW_PART) == 0) {
return;
}
}
keyed = psys->flag & PSYS_KEYED;
baked = psys->pointcache->mem_cache.first && psys->part->type != PART_HAIR;
/* clear out old and create new empty path cache */
psys_free_path_cache(psys, psys->edit);
cache = psys->pathcache = psys_alloc_path_cache_buffers(
&psys->pathcachebufs, totpart, segments + 1);
psys->lattice_deform_data = psys_create_lattice_deform_data(sim);
ma = give_current_material(sim->ob, psys->part->omat);
if (ma && (psys->part->draw_col == PART_DRAW_COL_MAT)) {
copy_v3_v3(col, &ma->r);
}
if ((psys->flag & PSYS_GLOBAL_HAIR) == 0) {
if ((psys->part->flag & PART_CHILD_EFFECT) == 0) {
vg_effector = psys_cache_vgroup(psmd->mesh_final, psys, PSYS_VG_EFFECTOR);
}
if (!psys->totchild) {
vg_length = psys_cache_vgroup(psmd->mesh_final, psys, PSYS_VG_LENGTH);
}
}
/* ensure we have tessfaces to be used for mapping */
if (part->from != PART_FROM_VERT) {
BKE_mesh_tessface_ensure(psmd->mesh_final);
}
/*---first main loop: create all actual particles' paths---*/
LOOP_PARTICLES
{
if (!psys->totchild) {
psys_get_texture(sim, pa, &ptex, PAMAP_LENGTH, 0.f);
pa_length = ptex.length * (1.0f - part->randlength * psys_frand(psys, psys->seed + p));
if (vg_length) {
pa_length *= psys_particle_value_from_verts(psmd->mesh_final, part->from, pa, vg_length);
}
}
pind.keyed = keyed;
pind.cache = baked ? psys->pointcache : NULL;
pind.epoint = NULL;
pind.bspline = (psys->part->flag & PART_HAIR_BSPLINE);
pind.mesh = hair_mesh;
memset(cache[p], 0, sizeof(*cache[p]) * (segments + 1));
cache[p]->segments = segments;
/*--get the first data points--*/
init_particle_interpolation(sim->ob, sim->psys, pa, &pind);
/* hairmat is needed for for non-hair particle too so we get proper rotations */
psys_mat_hair_to_global(sim->ob, psmd->mesh_final, psys->part->from, pa, hairmat);
copy_v3_v3(rotmat[0], hairmat[2]);
copy_v3_v3(rotmat[1], hairmat[1]);
copy_v3_v3(rotmat[2], hairmat[0]);
if (part->draw & PART_ABS_PATH_TIME) {
birthtime = MAX2(pind.birthtime, part->path_start);
dietime = MIN2(pind.dietime, part->path_end);
}
else {
float tb = pind.birthtime;
birthtime = tb + part->path_start * (pind.dietime - tb);
dietime = tb + part->path_end * (pind.dietime - tb);
}
if (birthtime >= dietime) {
cache[p]->segments = -1;
continue;
}
dietime = birthtime + pa_length * (dietime - birthtime);
/*--interpolate actual path from data points--*/
for (k = 0, ca = cache[p]; k <= segments; k++, ca++) {
time = (float)k / (float)segments;
t = birthtime + time * (dietime - birthtime);
result.time = -t;
do_particle_interpolation(psys, p, pa, t, &pind, &result);
copy_v3_v3(ca->co, result.co);
/* dynamic hair is in object space */
/* keyed and baked are already in global space */
if (hair_mesh) {
mul_m4_v3(sim->ob->obmat, ca->co);
}
else if (!keyed && !baked && !(psys->flag & PSYS_GLOBAL_HAIR)) {
mul_m4_v3(hairmat, ca->co);
}
copy_v3_v3(ca->col, col);
}
if (part->type == PART_HAIR) {
HairKey *hkey;
for (k = 0, hkey = pa->hair; k < pa->totkey; ++k, ++hkey) {
mul_v3_m4v3(hkey->world_co, hairmat, hkey->co);
}
}
/*--modify paths and calculate rotation & velocity--*/
if (!(psys->flag & PSYS_GLOBAL_HAIR)) {
/* apply effectors */
if ((psys->part->flag & PART_CHILD_EFFECT) == 0) {
float effector = 1.0f;
if (vg_effector) {
effector *= psys_particle_value_from_verts(
psmd->mesh_final, psys->part->from, pa, vg_effector);
}
sub_v3_v3v3(vec, (cache[p] + 1)->co, cache[p]->co);
length = len_v3(vec);
for (k = 1, ca = cache[p] + 1; k <= segments; k++, ca++) {
do_path_effectors(
sim, p, ca, k, segments, cache[p]->co, effector, dfra, cfra, &length, vec);
}
}
/* apply guide curves to path data */
if (sim->psys->effectors && (psys->part->flag & PART_CHILD_EFFECT) == 0) {
for (k = 0, ca = cache[p]; k <= segments; k++, ca++) {
/* ca is safe to cast, since only co and vel are used */
do_guides(sim->depsgraph,
sim->psys->part,
sim->psys->effectors,
(ParticleKey *)ca,
p,
(float)k / (float)segments);
}
}
/* lattices have to be calculated separately to avoid mixups between effector calculations */
if (psys->lattice_deform_data) {
for (k = 0, ca = cache[p]; k <= segments; k++, ca++) {
calc_latt_deform(psys->lattice_deform_data, ca->co, psys->lattice_strength);
}
}
}
/* finally do rotation & velocity */
for (k = 1, ca = cache[p] + 1; k <= segments; k++, ca++) {
cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k);
if (k == segments) {
copy_qt_qt(ca->rot, (ca - 1)->rot);
}
/* set velocity */
sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co);
if (k == 1) {
copy_v3_v3((ca - 1)->vel, ca->vel);
}
ca->time = (float)k / (float)segments;
}
/* First rotation is based on emitting face orientation.
* This is way better than having flipping rotations resulting
* from using a global axis as a rotation pole (vec_to_quat()).
* It's not an ideal solution though since it disregards the
* initial tangent, but taking that in to account will allow
* the possibility of flipping again. -jahka
*/
mat3_to_quat_is_ok(cache[p]->rot, rotmat);
}
psys->totcached = totpart;
if (psys->lattice_deform_data) {
end_latt_deform(psys->lattice_deform_data);
psys->lattice_deform_data = NULL;
}
if (vg_effector) {
MEM_freeN(vg_effector);
}
if (vg_length) {
MEM_freeN(vg_length);
}
}
typedef struct CacheEditrPathsIterData {
Object *object;
PTCacheEdit *edit;
ParticleSystemModifierData *psmd;
ParticleData *pa;
int segments;
bool use_weight;
float sel_col[3];
float nosel_col[3];
} CacheEditrPathsIterData;
static void psys_cache_edit_paths_iter(void *__restrict iter_data_v,
const int iter,
const TaskParallelTLS *__restrict UNUSED(tls))
{
CacheEditrPathsIterData *iter_data = (CacheEditrPathsIterData *)iter_data_v;
PTCacheEdit *edit = iter_data->edit;
PTCacheEditPoint *point = &edit->points[iter];
if (edit->totcached && !(point->flag & PEP_EDIT_RECALC)) {
return;
}
if (point->totkey == 0) {
return;
}
Object *ob = iter_data->object;
ParticleSystem *psys = edit->psys;
ParticleCacheKey **cache = edit->pathcache;
ParticleSystemModifierData *psmd = iter_data->psmd;
ParticleData *pa = iter_data->pa ? iter_data->pa + iter : NULL;
PTCacheEditKey *ekey = point->keys;
const int segments = iter_data->segments;
const bool use_weight = iter_data->use_weight;
float birthtime = 0.0f, dietime = 0.0f;
float hairmat[4][4], rotmat[3][3], prev_tangent[3] = {0.0f, 0.0f, 0.0f};
ParticleInterpolationData pind;
pind.keyed = 0;
pind.cache = NULL;
pind.epoint = point;
pind.bspline = psys ? (psys->part->flag & PART_HAIR_BSPLINE) : 0;
pind.mesh = NULL;
/* should init_particle_interpolation set this ? */
if (use_weight) {
pind.hkey[0] = NULL;
/* pa != NULL since the weight brush is only available for hair */
pind.hkey[0] = pa->hair;
pind.hkey[1] = pa->hair + 1;
}
memset(cache[iter], 0, sizeof(*cache[iter]) * (segments + 1));
cache[iter]->segments = segments;
/*--get the first data points--*/
init_particle_interpolation(ob, psys, pa, &pind);
if (psys) {
psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, pa, hairmat);
copy_v3_v3(rotmat[0], hairmat[2]);
copy_v3_v3(rotmat[1], hairmat[1]);
copy_v3_v3(rotmat[2], hairmat[0]);
}
birthtime = pind.birthtime;
dietime = pind.dietime;
if (birthtime >= dietime) {
cache[iter]->segments = -1;
return;
}
/*--interpolate actual path from data points--*/
ParticleCacheKey *ca;
int k;
float t, time = 0.0f, keytime = 0.0f;
for (k = 0, ca = cache[iter]; k <= segments; k++, ca++) {
time = (float)k / (float)segments;
t = birthtime + time * (dietime - birthtime);
ParticleKey result;
result.time = -t;
do_particle_interpolation(psys, iter, pa, t, &pind, &result);
copy_v3_v3(ca->co, result.co);
/* non-hair points are already in global space */
if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
mul_m4_v3(hairmat, ca->co);
if (k) {
cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k);
if (k == segments) {
copy_qt_qt(ca->rot, (ca - 1)->rot);
}
/* set velocity */
sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co);
if (k == 1) {
copy_v3_v3((ca - 1)->vel, ca->vel);
}
}
}
else {
ca->vel[0] = ca->vel[1] = 0.0f;
ca->vel[2] = 1.0f;
}
/* selection coloring in edit mode */
if (use_weight) {
if (k == 0) {
BKE_defvert_weight_to_rgb(ca->col, pind.hkey[1]->weight);
}
else {
/* warning: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */
float real_t;
if (result.time < 0.0f) {
real_t = -result.time;
}
else {
real_t = pind.hkey[0]->time +
t * (pind.hkey[0][pa->totkey - 1].time - pind.hkey[0]->time);
}
while (pind.hkey[1]->time < real_t) {
pind.hkey[1]++;
}
pind.hkey[0] = pind.hkey[1] - 1;
/* end copy */
float w1[3], w2[3];
keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time));
BKE_defvert_weight_to_rgb(w1, pind.hkey[0]->weight);
BKE_defvert_weight_to_rgb(w2, pind.hkey[1]->weight);
interp_v3_v3v3(ca->col, w1, w2, keytime);
}
}
else {
if ((ekey + (pind.ekey[0] - point->keys))->flag & PEK_SELECT) {
if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) {
copy_v3_v3(ca->col, iter_data->sel_col);
}
else {
keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time));
interp_v3_v3v3(ca->col, iter_data->sel_col, iter_data->nosel_col, keytime);
}
}
else {
if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) {
keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time));
interp_v3_v3v3(ca->col, iter_data->nosel_col, iter_data->sel_col, keytime);
}
else {
copy_v3_v3(ca->col, iter_data->nosel_col);
}
}
}
ca->time = t;
}
if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
/* First rotation is based on emitting face orientation.
* This is way better than having flipping rotations resulting
* from using a global axis as a rotation pole (vec_to_quat()).
* It's not an ideal solution though since it disregards the
* initial tangent, but taking that in to account will allow
* the possibility of flipping again. -jahka
*/
mat3_to_quat_is_ok(cache[iter]->rot, rotmat);
}
}
void psys_cache_edit_paths(Depsgraph *depsgraph,
Scene *scene,
Object *ob,
PTCacheEdit *edit,
float cfra,
const bool use_render_params)
{
ParticleCacheKey **cache = edit->pathcache;
ParticleEditSettings *pset = &scene->toolsettings->particle;
ParticleSystem *psys = edit->psys;
ParticleData *pa = psys ? psys->particles : NULL;
int segments = 1 << pset->draw_step;
int totpart = edit->totpoint, recalc_set = 0;
if (edit->psmd_eval == NULL) {
return;
}
segments = MAX2(segments, 4);
if (!cache || edit->totpoint != edit->totcached) {
/* Clear out old and create new empty path cache. */
psys_free_path_cache(edit->psys, edit);
cache = edit->pathcache = psys_alloc_path_cache_buffers(
&edit->pathcachebufs, totpart, segments + 1);
/* Set flag for update (child particles check this too). */
int i;
PTCacheEditPoint *point;
for (i = 0, point = edit->points; i < totpart; i++, point++) {
point->flag |= PEP_EDIT_RECALC;
}
recalc_set = 1;
}
const bool use_weight = (pset->brushtype == PE_BRUSH_WEIGHT) && (psys != NULL) &&
(psys->particles != NULL);
CacheEditrPathsIterData iter_data;
iter_data.object = ob;
iter_data.edit = edit;
iter_data.psmd = edit->psmd_eval;
iter_data.pa = pa;
iter_data.segments = segments;
iter_data.use_weight = use_weight;
if (use_weight) {
/* use weight painting colors now... */
}
else {
iter_data.sel_col[0] = (float)edit->sel_col[0] / 255.0f;
iter_data.sel_col[1] = (float)edit->sel_col[1] / 255.0f;
iter_data.sel_col[2] = (float)edit->sel_col[2] / 255.0f;
iter_data.nosel_col[0] = (float)edit->nosel_col[0] / 255.0f;
iter_data.nosel_col[1] = (float)edit->nosel_col[1] / 255.0f;
iter_data.nosel_col[2] = (float)edit->nosel_col[2] / 255.0f;
}
TaskParallelSettings settings;
BLI_parallel_range_settings_defaults(&settings);
settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
BLI_task_parallel_range(0, edit->totpoint, &iter_data, psys_cache_edit_paths_iter, &settings);
edit->totcached = totpart;
if (psys) {
ParticleSimulationData sim = {0};
sim.depsgraph = depsgraph;
sim.scene = scene;
sim.ob = ob;
sim.psys = psys;
sim.psmd = edit->psmd_eval;
psys_cache_child_paths(&sim, cfra, true, use_render_params);
}
/* clear recalc flag if set here */
if (recalc_set) {
PTCacheEditPoint *point;
int i;
for (i = 0, point = edit->points; i < totpart; i++, point++) {
point->flag &= ~PEP_EDIT_RECALC;
}
}
}
/************************************************/
/* Particle Key handling */
/************************************************/
void copy_particle_key(ParticleKey *to, ParticleKey *from, int time)
{
if (time) {
memcpy(to, from, sizeof(ParticleKey));
}
else {
float to_time = to->time;
memcpy(to, from, sizeof(ParticleKey));
to->time = to_time;
}
}
void psys_get_from_key(ParticleKey *key, float loc[3], float vel[3], float rot[4], float *time)
{
if (loc) {
copy_v3_v3(loc, key->co);
}
if (vel) {
copy_v3_v3(vel, key->vel);
}
if (rot) {
copy_qt_qt(rot, key->rot);
}
if (time) {
*time = key->time;
}
}
static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat[4][4])
{
float det, w1, w2, d1[2], d2[2];
memset(mat, 0, sizeof(float) * 4 * 4);
mat[3][3] = 1.0f;
/* first axis is the normal */
normal_tri_v3(mat[2], v1, v2, v3);
/* second axis along (1, 0) in uv space */
if (uv) {
d1[0] = uv[1][0] - uv[0][0];
d1[1] = uv[1][1] - uv[0][1];
d2[0] = uv[2][0] - uv[0][0];
d2[1] = uv[2][1] - uv[0][1];
det = d2[0] * d1[1] - d2[1] * d1[0];
if (det != 0.0f) {
det = 1.0f / det;
w1 = -d2[1] * det;
w2 = d1[1] * det;
mat[1][0] = w1 * (v2[0] - v1[0]) + w2 * (v3[0] - v1[0]);
mat[1][1] = w1 * (v2[1] - v1[1]) + w2 * (v3[1] - v1[1]);
mat[1][2] = w1 * (v2[2] - v1[2]) + w2 * (v3[2] - v1[2]);
normalize_v3(mat[1]);
}
else {
mat[1][0] = mat[1][1] = mat[1][2] = 0.0f;
}
}
else {
sub_v3_v3v3(mat[1], v2, v1);
normalize_v3(mat[1]);
}
/* third as a cross product */
cross_v3_v3v3(mat[0], mat[1], mat[2]);
}
static void psys_face_mat(Object *ob, Mesh *mesh, ParticleData *pa, float mat[4][4], int orco)
{
float v[3][3];
MFace *mface;
OrigSpaceFace *osface;
float(*orcodata)[3];
int i = (ELEM(pa->num_dmcache, DMCACHE_ISCHILD, DMCACHE_NOTFOUND)) ? pa->num : pa->num_dmcache;
if (i == -1 || i >= mesh->totface) {
unit_m4(mat);
return;
}
mface = &mesh->mface[i];
osface = CustomData_get(&mesh->fdata, i, CD_ORIGSPACE);
if (orco && (orcodata = CustomData_get_layer(&mesh->vdata, CD_ORCO))) {
copy_v3_v3(v[0], orcodata[mface->v1]);
copy_v3_v3(v[1], orcodata[mface->v2]);
copy_v3_v3(v[2], orcodata[mface->v3]);
/* ugly hack to use non-transformed orcos, since only those
* give symmetric results for mirroring in particle mode */
if (CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX)) {
BKE_mesh_orco_verts_transform(ob->data, v, 3, 1);
}
}
else {
copy_v3_v3(v[0], mesh->mvert[mface->v1].co);
copy_v3_v3(v[1], mesh->mvert[mface->v2].co);
copy_v3_v3(v[2], mesh->mvert[mface->v3].co);
}
triatomat(v[0], v[1], v[2], (osface) ? osface->uv : NULL, mat);
}
void psys_mat_hair_to_object(
Object *UNUSED(ob), Mesh *mesh, short from, ParticleData *pa, float hairmat[4][4])
{
float vec[3];
/* can happen when called from a different object's modifier */
if (!mesh) {
unit_m4(hairmat);
return;
}
psys_face_mat(0, mesh, pa, hairmat, 0);
psys_particle_on_dm(mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0);
copy_v3_v3(hairmat[3], vec);
}
void psys_mat_hair_to_orco(
Object *ob, Mesh *mesh, short from, ParticleData *pa, float hairmat[4][4])
{
float vec[3], orco[3];
psys_face_mat(ob, mesh, pa, hairmat, 1);
psys_particle_on_dm(
mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco);
/* see psys_face_mat for why this function is called */
if (CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX)) {
BKE_mesh_orco_verts_transform(ob->data, &orco, 1, 1);
}
copy_v3_v3(hairmat[3], orco);
}
void psys_vec_rot_to_face(Mesh *mesh, ParticleData *pa, float vec[3])
{
float mat[4][4];
psys_face_mat(0, mesh, pa, mat, 0);
transpose_m4(mat); /* cheap inverse for rotation matrix */
mul_mat3_m4_v3(mat, vec);
}
void psys_mat_hair_to_global(
Object *ob, Mesh *mesh, short from, ParticleData *pa, float hairmat[4][4])
{
float facemat[4][4];
psys_mat_hair_to_object(ob, mesh, from, pa, facemat);
mul_m4_m4m4(hairmat, ob->obmat, facemat);
}
/************************************************/
/* ParticleSettings handling */
/************************************************/
ModifierData *object_add_particle_system(Main *bmain, Scene *scene, Object *ob, const char *name)
{
ParticleSystem *psys;
ModifierData *md;
ParticleSystemModifierData *psmd;
if (!ob || ob->type != OB_MESH) {
return NULL;
}
if (name == NULL) {
name = DATA_("ParticleSettings");
}
psys = ob->particlesystem.first;
for (; psys; psys = psys->next) {
psys->flag &= ~PSYS_CURRENT;
}
psys = MEM_callocN(sizeof(ParticleSystem), "particle_system");
psys->pointcache = BKE_ptcache_add(&psys->ptcaches);
BLI_addtail(&ob->particlesystem, psys);
psys_unique_name(ob, psys, name);
psys->part = BKE_particlesettings_add(bmain, psys->name);
md = modifier_new(eModifierType_ParticleSystem);
BLI_strncpy(md->name, psys->name, sizeof(md->name));
modifier_unique_name(&ob->modifiers, md);
psmd = (ParticleSystemModifierData *)md;
psmd->psys = psys;
BLI_addtail(&ob->modifiers, md);
psys->totpart = 0;
psys->flag = PSYS_CURRENT;
psys->cfra = BKE_scene_frame_to_ctime(scene, CFRA + 1);
DEG_relations_tag_update(bmain);
DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
return md;
}
void object_remove_particle_system(Main *bmain, Scene *UNUSED(scene), Object *ob)
{
ParticleSystem *psys = psys_get_current(ob);
ParticleSystemModifierData *psmd;
ModifierData *md;
if (!psys) {
return;
}
/* clear all other appearances of this pointer (like on smoke flow modifier) */
if ((md = modifiers_findByType(ob, eModifierType_Smoke))) {
SmokeModifierData *smd = (SmokeModifierData *)md;
if ((smd->type == MOD_SMOKE_TYPE_FLOW) && smd->flow && smd->flow->psys) {
if (smd->flow->psys == psys) {
smd->flow->psys = NULL;
}
}
}
if ((md = modifiers_findByType(ob, eModifierType_DynamicPaint))) {
DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
if (pmd->brush && pmd->brush->psys) {
if (pmd->brush->psys == psys) {
pmd->brush->psys = NULL;
}
}
}
/* clear modifier */
psmd = psys_get_modifier(ob, psys);
BLI_remlink(&ob->modifiers, psmd);
modifier_free((ModifierData *)psmd);
/* clear particle system */
BLI_remlink(&ob->particlesystem, psys);
if (psys->part) {
id_us_min(&psys->part->id);
}
psys_free(ob, psys);
if (ob->particlesystem.first) {
((ParticleSystem *)ob->particlesystem.first)->flag |= PSYS_CURRENT;
}
else {
ob->mode &= ~OB_MODE_PARTICLE_EDIT;
}
DEG_relations_tag_update(bmain);
DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
/* Flush object mode. */
DEG_id_tag_update(&ob->id, ID_RECALC_COPY_ON_WRITE);
}
static void default_particle_settings(ParticleSettings *part)
{
part->type = PART_EMITTER;
part->distr = PART_DISTR_JIT;
part->draw_as = PART_DRAW_REND;
part->ren_as = PART_DRAW_HALO;
part->bb_uv_split = 1;
part->flag = PART_EDISTR | PART_TRAND | PART_HIDE_ADVANCED_HAIR;
part->sta = 1.0;
part->end = 200.0;
part->lifetime = 50.0;
part->jitfac = 1.0;
part->totpart = 1000;
part->grid_res = 10;
part->timetweak = 1.0;
part->courant_target = 0.2;
part->integrator = PART_INT_MIDPOINT;
part->phystype = PART_PHYS_NEWTON;
part->hair_step = 5;
part->keys_step = 5;
part->draw_step = 2;
part->ren_step = 3;
part->adapt_angle = 5;
part->adapt_pix = 3;
part->kink_axis = 2;
part->kink_amp_clump = 1.f;
part->kink_extra_steps = 4;
part->clump_noise_size = 1.0f;
part->reactevent = PART_EVENT_DEATH;
part->disp = 100;
part->from = PART_FROM_FACE;
part->normfac = 1.0f;
part->mass = 1.0;
part->size = 0.05;
part->childsize = 1.0;
part->rotmode = PART_ROT_VEL;
part->avemode = PART_AVE_VELOCITY;
part->child_nbr = 10;
part->ren_child_nbr = 100;
part->childrad = 0.2f;
part->childflat = 0.0f;
part->clumppow = 0.0f;
part->kink_amp = 0.2f;
part->kink_freq = 2.0;
part->rough1_size = 1.0;
part->rough2_size = 1.0;
part->rough_end_shape = 1.0;
part->clength = 1.0f;
part->clength_thres = 0.0f;
part->draw = 0;
part->draw_line[0] = 0.5;
part->path_start = 0.0f;
part->path_end = 1.0f;
part->bb_size[0] = part->bb_size[1] = 1.0f;
part->keyed_loops = 1;
part->color_vec_max = 1.f;
part->draw_col = PART_DRAW_COL_MAT;
if (!part->effector_weights) {
part->effector_weights = BKE_effector_add_weights(NULL);
}
part->omat = 1;
part->use_modifier_stack = false;
part->draw_size = 0.1f;
part->shape_flag = PART_SHAPE_CLOSE_TIP;
part->shape = 0.0f;
part->rad_root = 1.0f;
part->rad_tip = 0.0f;
part->rad_scale = 0.01f;
}
ParticleSettings *BKE_particlesettings_add(Main *bmain, const char *name)
{
ParticleSettings *part;
part = BKE_libblock_alloc(bmain, ID_PA, name, 0);
default_particle_settings(part);
return part;
}
void BKE_particlesettings_clump_curve_init(ParticleSettings *part)
{
CurveMapping *cumap = BKE_curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
cumap->cm[0].curve[0].x = 0.0f;
cumap->cm[0].curve[0].y = 1.0f;
cumap->cm[0].curve[1].x = 1.0f;
cumap->cm[0].curve[1].y = 1.0f;
BKE_curvemapping_initialize(cumap);
part->clumpcurve = cumap;
}
void BKE_particlesettings_rough_curve_init(ParticleSettings *part)
{
CurveMapping *cumap = BKE_curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
cumap->cm[0].curve[0].x = 0.0f;
cumap->cm[0].curve[0].y = 1.0f;
cumap->cm[0].curve[1].x = 1.0f;
cumap->cm[0].curve[1].y = 1.0f;
BKE_curvemapping_initialize(cumap);
part->roughcurve = cumap;
}
void BKE_particlesettings_twist_curve_init(ParticleSettings *part)
{
CurveMapping *cumap = BKE_curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
cumap->cm[0].curve[0].x = 0.0f;
cumap->cm[0].curve[0].y = 1.0f;
cumap->cm[0].curve[1].x = 1.0f;
cumap->cm[0].curve[1].y = 1.0f;
BKE_curvemapping_initialize(cumap);
part->twistcurve = cumap;
}
/**
* Only copy internal data of ParticleSettings ID from source
* to already allocated/initialized destination.
* You probably never want to use that directly,
* use #BKE_id_copy or #BKE_id_copy_ex for typical needs.
*
* WARNING! This function will not handle ID user count!
*
* \param flag: Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
*/
void BKE_particlesettings_copy_data(Main *UNUSED(bmain),
ParticleSettings *part_dst,
const ParticleSettings *part_src,
const int UNUSED(flag))
{
part_dst->pd = BKE_partdeflect_copy(part_src->pd);
part_dst->pd2 = BKE_partdeflect_copy(part_src->pd2);
part_dst->effector_weights = MEM_dupallocN(part_src->effector_weights);
part_dst->fluid = MEM_dupallocN(part_src->fluid);
if (part_src->clumpcurve) {
part_dst->clumpcurve = BKE_curvemapping_copy(part_src->clumpcurve);
}
if (part_src->roughcurve) {
part_dst->roughcurve = BKE_curvemapping_copy(part_src->roughcurve);
}
if (part_src->twistcurve) {
part_dst->twistcurve = BKE_curvemapping_copy(part_src->twistcurve);
}
part_dst->boids = boid_copy_settings(part_src->boids);
for (int a = 0; a < MAX_MTEX; a++) {
if (part_src->mtex[a]) {
part_dst->mtex[a] = MEM_dupallocN(part_src->mtex[a]);
}
}
BLI_duplicatelist(&part_dst->instance_weights, &part_src->instance_weights);
}
ParticleSettings *BKE_particlesettings_copy(Main *bmain, const ParticleSettings *part)
{
ParticleSettings *part_copy;
BKE_id_copy(bmain, &part->id, (ID **)&part_copy);
return part_copy;
}
void BKE_particlesettings_make_local(Main *bmain, ParticleSettings *part, const bool lib_local)
{
BKE_id_make_local_generic(bmain, &part->id, true, lib_local);
}
/************************************************/
/* Textures */
/************************************************/
static int get_particle_uv(Mesh *mesh,
ParticleData *pa,
int index,
const float fuv[4],
char *name,
float *texco,
bool from_vert)
{
MFace *mf;
MTFace *tf;
int i;
tf = CustomData_get_layer_named(&mesh->fdata, CD_MTFACE, name);
if (tf == NULL) {
tf = mesh->mtface;
}
if (tf == NULL) {
return 0;
}
if (pa) {
i = ELEM(pa->num_dmcache, DMCACHE_NOTFOUND, DMCACHE_ISCHILD) ? pa->num : pa->num_dmcache;
if ((!from_vert && i >= mesh->totface) || (from_vert && i >= mesh->totvert)) {
i = -1;
}
}
else {
i = index;
}
if (i == -1) {
texco[0] = 0.0f;
texco[1] = 0.0f;
texco[2] = 0.0f;
}
else {
if (from_vert) {
mf = mesh->mface;
/* This finds the first face to contain the emitting vertex,
* this is not ideal, but is mostly fine as UV seams generally
* map to equal-colored parts of a texture */
for (int j = 0; j < mesh->totface; j++, mf++) {
if (ELEM(i, mf->v1, mf->v2, mf->v3, mf->v4)) {
i = j;
break;
}
}
}
else {
mf = &mesh->mface[i];
}
psys_interpolate_uvs(&tf[i], mf->v4, fuv, texco);
texco[0] = texco[0] * 2.0f - 1.0f;
texco[1] = texco[1] * 2.0f - 1.0f;
texco[2] = 0.0f;
}
return 1;
}
#define SET_PARTICLE_TEXTURE(type, pvalue, texfac) \
if ((event & mtex->mapto) & type) { \
pvalue = texture_value_blend(def, pvalue, value, texfac, blend); \
} \
(void)0
#define CLAMP_PARTICLE_TEXTURE_POS(type, pvalue) \
if (event & type) { \
CLAMP(pvalue, 0.0f, 1.0f); \
} \
(void)0
#define CLAMP_WARP_PARTICLE_TEXTURE_POS(type, pvalue) \
if (event & type) { \
if (pvalue < 0.0f) \
pvalue = 1.0f + pvalue; \
CLAMP(pvalue, 0.0f, 1.0f); \
} \
(void)0
#define CLAMP_PARTICLE_TEXTURE_POSNEG(type, pvalue) \
if (event & type) { \
CLAMP(pvalue, -1.0f, 1.0f); \
} \
(void)0
static void get_cpa_texture(Mesh *mesh,
ParticleSystem *psys,
ParticleSettings *part,
ParticleData *par,
int child_index,
int face_index,
const float fw[4],
float *orco,
ParticleTexture *ptex,
int event,
float cfra)
{
MTex *mtex, **mtexp = part->mtex;
int m;
float value, rgba[4], texvec[3];
ptex->ivel = ptex->life = ptex->exist = ptex->size = ptex->damp = ptex->gravity = ptex->field =
ptex->time = ptex->clump = ptex->kink_freq = ptex->kink_amp = ptex->effector = ptex->rough1 =
ptex->rough2 = ptex->roughe = 1.0f;
ptex->twist = 1.0f;
ptex->length = 1.0f - part->randlength * psys_frand(psys, child_index + 26);
ptex->length *= part->clength_thres < psys_frand(psys, child_index + 27) ? part->clength : 1.0f;
for (m = 0; m < MAX_MTEX; m++, mtexp++) {
mtex = *mtexp;
if (mtex && mtex->tex && mtex->mapto) {
float def = mtex->def_var;
short blend = mtex->blendtype;
short texco = mtex->texco;
if (ELEM(texco, TEXCO_UV, TEXCO_ORCO) &&
(ELEM(part->from, PART_FROM_FACE, PART_FROM_VOLUME) == 0 ||
part->distr == PART_DISTR_GRID)) {
texco = TEXCO_GLOB;
}
switch (texco) {
case TEXCO_GLOB:
copy_v3_v3(texvec, par->state.co);
break;
case TEXCO_OBJECT:
copy_v3_v3(texvec, par->state.co);
if (mtex->object) {
mul_m4_v3(mtex->object->imat, texvec);
}
break;
case TEXCO_UV:
if (fw && get_particle_uv(mesh,
NULL,
face_index,
fw,
mtex->uvname,
texvec,
(part->from == PART_FROM_VERT))) {
break;
}
/* no break, failed to get uv's, so let's try orco's */
ATTR_FALLTHROUGH;
case TEXCO_ORCO:
copy_v3_v3(texvec, orco);
break;
case TEXCO_PARTICLE:
/* texture coordinates in range [-1, 1] */
texvec[0] = 2.f * (cfra - par->time) / (par->dietime - par->time) - 1.f;
texvec[1] = 0.f;
texvec[2] = 0.f;
break;
}
externtex(mtex, texvec, &value, rgba, rgba + 1, rgba + 2, rgba + 3, 0, NULL, false, false);
if ((event & mtex->mapto) & PAMAP_ROUGH) {
ptex->rough1 = ptex->rough2 = ptex->roughe = texture_value_blend(
def, ptex->rough1, value, mtex->roughfac, blend);
}
SET_PARTICLE_TEXTURE(PAMAP_LENGTH, ptex->length, mtex->lengthfac);
SET_PARTICLE_TEXTURE(PAMAP_CLUMP, ptex->clump, mtex->clumpfac);
SET_PARTICLE_TEXTURE(PAMAP_KINK_AMP, ptex->kink_amp, mtex->kinkampfac);
SET_PARTICLE_TEXTURE(PAMAP_KINK_FREQ, ptex->kink_freq, mtex->kinkfac);
SET_PARTICLE_TEXTURE(PAMAP_DENS, ptex->exist, mtex->padensfac);
SET_PARTICLE_TEXTURE(PAMAP_TWIST, ptex->twist, mtex->twistfac);
}
}
CLAMP_PARTICLE_TEXTURE_POS(PAMAP_LENGTH, ptex->length);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_CLUMP, ptex->clump);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_KINK_AMP, ptex->kink_amp);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_KINK_FREQ, ptex->kink_freq);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_ROUGH, ptex->rough1);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_DENS, ptex->exist);
}
void psys_get_texture(
ParticleSimulationData *sim, ParticleData *pa, ParticleTexture *ptex, int event, float cfra)
{
Object *ob = sim->ob;
Mesh *me = (Mesh *)ob->data;
ParticleSettings *part = sim->psys->part;
MTex **mtexp = part->mtex;
MTex *mtex;
int m;
float value, rgba[4], co[3], texvec[3];
int setvars = 0;
/* initialize ptex */
ptex->ivel = ptex->life = ptex->exist = ptex->size = ptex->damp = ptex->gravity = ptex->field =
ptex->length = ptex->clump = ptex->kink_freq = ptex->kink_amp = ptex->effector =
ptex->rough1 = ptex->rough2 = ptex->roughe = 1.0f;
ptex->twist = 1.0f;
ptex->time = (float)(pa - sim->psys->particles) / (float)sim->psys->totpart;
for (m = 0; m < MAX_MTEX; m++, mtexp++) {
mtex = *mtexp;
if (mtex && mtex->tex && mtex->mapto) {
float def = mtex->def_var;
short blend = mtex->blendtype;
short texco = mtex->texco;
if (texco == TEXCO_UV && (ELEM(part->from, PART_FROM_FACE, PART_FROM_VOLUME) == 0 ||
part->distr == PART_DISTR_GRID)) {
texco = TEXCO_GLOB;
}
switch (texco) {
case TEXCO_GLOB:
copy_v3_v3(texvec, pa->state.co);
break;
case TEXCO_OBJECT:
copy_v3_v3(texvec, pa->state.co);
if (mtex->object) {
mul_m4_v3(mtex->object->imat, texvec);
}
break;
case TEXCO_UV:
if (get_particle_uv(sim->psmd->mesh_final,
pa,
0,
pa->fuv,
mtex->uvname,
texvec,
(part->from == PART_FROM_VERT))) {
break;
}
/* no break, failed to get uv's, so let's try orco's */
ATTR_FALLTHROUGH;
case TEXCO_ORCO:
psys_particle_on_emitter(sim->psmd,
sim->psys->part->from,
pa->num,
pa->num_dmcache,
pa->fuv,
pa->foffset,
co,
0,
0,
0,
texvec);
if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) {
BKE_mesh_texspace_calc(me);
}
sub_v3_v3(texvec, me->loc);
if (me->size[0] != 0.0f) {
texvec[0] /= me->size[0];
}
if (me->size[1] != 0.0f) {
texvec[1] /= me->size[1];
}
if (me->size[2] != 0.0f) {
texvec[2] /= me->size[2];
}
break;
case TEXCO_PARTICLE:
/* texture coordinates in range [-1, 1] */
texvec[0] = 2.f * (cfra - pa->time) / (pa->dietime - pa->time) - 1.f;
if (sim->psys->totpart > 0) {
texvec[1] = 2.f * (float)(pa - sim->psys->particles) / (float)sim->psys->totpart - 1.f;
}
else {
texvec[1] = 0.0f;
}
texvec[2] = 0.f;
break;
}
externtex(mtex, texvec, &value, rgba, rgba + 1, rgba + 2, rgba + 3, 0, NULL, false, false);
if ((event & mtex->mapto) & PAMAP_TIME) {
/* the first time has to set the base value for time regardless of blend mode */
if ((setvars & MAP_PA_TIME) == 0) {
int flip = (mtex->timefac < 0.0f);
float timefac = fabsf(mtex->timefac);
ptex->time *= 1.0f - timefac;
ptex->time += timefac * ((flip) ? 1.0f - value : value);
setvars |= MAP_PA_TIME;
}
else {
ptex->time = texture_value_blend(def, ptex->time, value, mtex->timefac, blend);
}
}
SET_PARTICLE_TEXTURE(PAMAP_LIFE, ptex->life, mtex->lifefac);
SET_PARTICLE_TEXTURE(PAMAP_DENS, ptex->exist, mtex->padensfac);
SET_PARTICLE_TEXTURE(PAMAP_SIZE, ptex->size, mtex->sizefac);
SET_PARTICLE_TEXTURE(PAMAP_IVEL, ptex->ivel, mtex->ivelfac);
SET_PARTICLE_TEXTURE(PAMAP_FIELD, ptex->field, mtex->fieldfac);
SET_PARTICLE_TEXTURE(PAMAP_GRAVITY, ptex->gravity, mtex->gravityfac);
SET_PARTICLE_TEXTURE(PAMAP_DAMP, ptex->damp, mtex->dampfac);
SET_PARTICLE_TEXTURE(PAMAP_LENGTH, ptex->length, mtex->lengthfac);
SET_PARTICLE_TEXTURE(PAMAP_TWIST, ptex->twist, mtex->twistfac);
}
}
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_TIME, ptex->time);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_LIFE, ptex->life);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_DENS, ptex->exist);
CLAMP_PARTICLE_TEXTURE_POS(PAMAP_SIZE, ptex->size);
CLAMP_PARTICLE_TEXTURE_POSNEG(PAMAP_IVEL, ptex->ivel);
CLAMP_PARTICLE_TEXTURE_POSNEG(PAMAP_FIELD, ptex->field);
CLAMP_PARTICLE_TEXTURE_POSNEG(PAMAP_GRAVITY, ptex->gravity);
CLAMP_WARP_PARTICLE_TEXTURE_POS(PAMAP_DAMP, ptex->damp);
CLAMP_PARTICLE_TEXTURE_POS(PAMAP_LENGTH, ptex->length);
}
/************************************************/
/* Particle State */
/************************************************/
float psys_get_timestep(ParticleSimulationData *sim)
{
return 0.04f * sim->psys->part->timetweak;
}
float psys_get_child_time(
ParticleSystem *psys, ChildParticle *cpa, float cfra, float *birthtime, float *dietime)
{
ParticleSettings *part = psys->part;
float time, life;
if (part->childtype == PART_CHILD_FACES) {
int w = 0;
time = 0.0;
while (w < 4 && cpa->pa[w] >= 0) {
time += cpa->w[w] * (psys->particles + cpa->pa[w])->time;
w++;
}
life = part->lifetime * (1.0f - part->randlife * psys_frand(psys, cpa - psys->child + 25));
}
else {
ParticleData *pa = psys->particles + cpa->parent;
time = pa->time;
life = pa->lifetime;
}
if (birthtime) {
*birthtime = time;
}
if (dietime) {
*dietime = time + life;
}
return (cfra - time) / life;
}
float psys_get_child_size(ParticleSystem *psys,
ChildParticle *cpa,
float UNUSED(cfra),
float *UNUSED(pa_time))
{
ParticleSettings *part = psys->part;
float size; // time XXX
if (part->childtype == PART_CHILD_FACES) {
int w = 0;
size = 0.0;
while (w < 4 && cpa->pa[w] >= 0) {
size += cpa->w[w] * (psys->particles + cpa->pa[w])->size;
w++;
}
}
else {
size = psys->particles[cpa->parent].size;
}
size *= part->childsize;
if (part->childrandsize != 0.0f) {
size *= 1.0f - part->childrandsize * psys_frand(psys, cpa - psys->child + 26);
}
return size;
}
static void get_child_modifier_parameters(ParticleSettings *part,
ParticleThreadContext *ctx,
ChildParticle *cpa,
short cpa_from,
int cpa_num,
float *cpa_fuv,
float *orco,
ParticleTexture *ptex)
{
ParticleSystem *psys = ctx->sim.psys;
int i = cpa - psys->child;
get_cpa_texture(ctx->mesh,
psys,
part,
psys->particles + cpa->pa[0],
i,
cpa_num,
cpa_fuv,
orco,
ptex,
PAMAP_DENS | PAMAP_CHILD,
psys->cfra);
if (ptex->exist < psys_frand(psys, i + 24)) {
return;
}
if (ctx->vg_length) {
ptex->length *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_length);
}
if (ctx->vg_clump) {
ptex->clump *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_clump);
}
if (ctx->vg_kink) {
ptex->kink_freq *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_kink);
}
if (ctx->vg_rough1) {
ptex->rough1 *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_rough1);
}
if (ctx->vg_rough2) {
ptex->rough2 *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_rough2);
}
if (ctx->vg_roughe) {
ptex->roughe *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_roughe);
}
if (ctx->vg_effector) {
ptex->effector *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_effector);
}
if (ctx->vg_twist) {
ptex->twist *= psys_interpolate_value_from_verts(
ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_twist);
}
}
/* gets hair (or keyed) particles state at the "path time" specified in state->time */
void psys_get_particle_on_path(ParticleSimulationData *sim,
int p,
ParticleKey *state,
const bool vel)
{
PARTICLE_PSMD;
ParticleSystem *psys = sim->psys;
ParticleSettings *part = sim->psys->part;
Material *ma = give_current_material(sim->ob, part->omat);
ParticleData *pa;
ChildParticle *cpa;
ParticleTexture ptex;
ParticleKey *par = 0, keys[4], tstate;
ParticleThreadContext ctx; /* fake thread context for child modifiers */
ParticleInterpolationData pind;
float t;
float co[3], orco[3];
float hairmat[4][4];
int totpart = psys->totpart;
int totchild = psys->totchild;
short between = 0, edit = 0;
int keyed = part->phystype & PART_PHYS_KEYED && psys->flag & PSYS_KEYED;
int cached = !keyed && part->type != PART_HAIR;
float *cpa_fuv;
int cpa_num;
short cpa_from;
/* initialize keys to zero */
memset(keys, 0, 4 * sizeof(ParticleKey));
t = state->time;
CLAMP(t, 0.0f, 1.0f);
if (p < totpart) {
/* interpolate pathcache directly if it exist */
if (psys->pathcache) {
ParticleCacheKey result;
interpolate_pathcache(psys->pathcache[p], t, &result);
copy_v3_v3(state->co, result.co);
copy_v3_v3(state->vel, result.vel);
copy_qt_qt(state->rot, result.rot);
}
/* otherwise interpolate with other means */
else {
pa = psys->particles + p;
pind.keyed = keyed;
pind.cache = cached ? psys->pointcache : NULL;
pind.epoint = NULL;
pind.bspline = (psys->part->flag & PART_HAIR_BSPLINE);
/* pind.dm disabled in editmode means we don't get effectors taken into
* account when subdividing for instance */
pind.mesh = psys_in_edit_mode(sim->depsgraph, psys) ?
NULL :
psys->hair_out_mesh; /* XXX Sybren EEK */
init_particle_interpolation(sim->ob, psys, pa, &pind);
do_particle_interpolation(psys, p, pa, t, &pind, state);
if (pind.mesh) {
mul_m4_v3(sim->ob->obmat, state->co);
mul_mat3_m4_v3(sim->ob->obmat, state->vel);
}
else if (!keyed && !cached && !(psys->flag & PSYS_GLOBAL_HAIR)) {
if ((pa->flag & PARS_REKEY) == 0) {
psys_mat_hair_to_global(sim->ob, sim->psmd->mesh_final, part->from, pa, hairmat);
mul_m4_v3(hairmat, state->co);
mul_mat3_m4_v3(hairmat, state->vel);
if (sim->psys->effectors && (part->flag & PART_CHILD_GUIDE) == 0) {
do_guides(
sim->depsgraph, sim->psys->part, sim->psys->effectors, state, p, state->time);
/* TODO: proper velocity handling */
}
if (psys->lattice_deform_data && edit == 0) {
calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength);
}
}
}
}
}
else if (totchild) {
// invert_m4_m4(imat, ob->obmat);
/* interpolate childcache directly if it exists */
if (psys->childcache) {
ParticleCacheKey result;
interpolate_pathcache(psys->childcache[p - totpart], t, &result);
copy_v3_v3(state->co, result.co);
copy_v3_v3(state->vel, result.vel);
copy_qt_qt(state->rot, result.rot);
}
else {
float par_co[3], par_orco[3];
cpa = psys->child + p - totpart;
if (state->time < 0.0f) {
t = psys_get_child_time(psys, cpa, -state->time, NULL, NULL);
}
if (totchild && part->childtype == PART_CHILD_FACES) {
/* part->parents could still be 0 so we can't test with totparent */
between = 1;
}
if (between) {
int w = 0;
float foffset;
/* get parent states */
while (w < 4 && cpa->pa[w] >= 0) {
keys[w].time = state->time;
psys_get_particle_on_path(sim, cpa->pa[w], keys + w, 1);
w++;
}
/* get the original coordinates (orco) for texture usage */
cpa_num = cpa->num;
foffset = cpa->foffset;
cpa_fuv = cpa->fuv;
cpa_from = PART_FROM_FACE;
psys_particle_on_emitter(
psmd, cpa_from, cpa_num, DMCACHE_ISCHILD, cpa->fuv, foffset, co, 0, 0, 0, orco);
/* We need to save the actual root position of the child for
* positioning it accurately to the surface of the emitter. */
// copy_v3_v3(cpa_1st, co);
// mul_m4_v3(ob->obmat, cpa_1st);
pa = psys->particles + cpa->parent;
psys_particle_on_emitter(psmd,
part->from,
pa->num,
pa->num_dmcache,
pa->fuv,
pa->foffset,
par_co,
0,
0,
0,
par_orco);
if (part->type == PART_HAIR) {
psys_mat_hair_to_global(sim->ob, sim->psmd->mesh_final, psys->part->from, pa, hairmat);
}
else {
unit_m4(hairmat);
}
pa = 0;
}
else {
/* get the parent state */
keys->time = state->time;
psys_get_particle_on_path(sim, cpa->parent, keys, 1);
/* get the original coordinates (orco) for texture usage */
pa = psys->particles + cpa->parent;
cpa_from = part->from;
cpa_num = pa->num;
cpa_fuv = pa->fuv;
psys_particle_on_emitter(psmd,
part->from,
pa->num,
pa->num_dmcache,
pa->fuv,
pa->foffset,
par_co,
0,
0,
0,
par_orco);
if (part->type == PART_HAIR) {
psys_particle_on_emitter(
psmd, cpa_from, cpa_num, DMCACHE_ISCHILD, cpa_fuv, pa->foffset, co, 0, 0, 0, orco);
psys_mat_hair_to_global(sim->ob, sim->psmd->mesh_final, psys->part->from, pa, hairmat);
}
else {
copy_v3_v3(orco, cpa->fuv);
unit_m4(hairmat);
}
}
/* get different child parameters from textures & vgroups */
memset(&ctx, 0, sizeof(ParticleThreadContext));
ctx.sim = *sim;
ctx.mesh = psmd->mesh_final;
ctx.ma = ma;
/* TODO: assign vertex groups */
get_child_modifier_parameters(part, &ctx, cpa, cpa_from, cpa_num, cpa_fuv, orco, &ptex);
if (between) {
int w = 0;
state->co[0] = state->co[1] = state->co[2] = 0.0f;
state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
/* child position is the weighted sum of parent positions */
while (w < 4 && cpa->pa[w] >= 0) {
state->co[0] += cpa->w[w] * keys[w].co[0];
state->co[1] += cpa->w[w] * keys[w].co[1];
state->co[2] += cpa->w[w] * keys[w].co[2];
state->vel[0] += cpa->w[w] * keys[w].vel[0];
state->vel[1] += cpa->w[w] * keys[w].vel[1];
state->vel[2] += cpa->w[w] * keys[w].vel[2];
w++;
}
/* apply offset for correct positioning */
// add_v3_v3(state->co, cpa_1st);
}
else {
/* offset the child from the parent position */
offset_child(cpa, keys, keys->rot, state, part->childflat, part->childrad);
}
par = keys;
if (vel) {
copy_particle_key(&tstate, state, 1);
}
/* apply different deformations to the child path */
ParticleChildModifierContext modifier_ctx = {NULL};
modifier_ctx.thread_ctx = NULL;
modifier_ctx.sim = sim;
modifier_ctx.ptex = &ptex;
modifier_ctx.cpa = cpa;
modifier_ctx.orco = orco;
modifier_ctx.par_co = par->co;
modifier_ctx.par_vel = par->vel;
modifier_ctx.par_rot = par->rot;
modifier_ctx.par_orco = par_orco;
modifier_ctx.parent_keys = psys->childcache ? psys->childcache[p - totpart] : NULL;
do_child_modifiers(&modifier_ctx, hairmat, state, t);
/* try to estimate correct velocity */
if (vel) {
ParticleKey tstate_tmp;
float length = len_v3(state->vel);
if (t >= 0.001f) {
tstate_tmp.time = t - 0.001f;
psys_get_particle_on_path(sim, p, &tstate_tmp, 0);
sub_v3_v3v3(state->vel, state->co, tstate_tmp.co);
normalize_v3(state->vel);
}
else {
tstate_tmp.time = t + 0.001f;
psys_get_particle_on_path(sim, p, &tstate_tmp, 0);
sub_v3_v3v3(state->vel, tstate_tmp.co, state->co);
normalize_v3(state->vel);
}
mul_v3_fl(state->vel, length);
}
}
}
}
/* gets particle's state at a time, returns 1 if particle exists and can be seen and 0 if not */
int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *state, int always)
{
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
ParticleData *pa = NULL;
ChildParticle *cpa = NULL;
float cfra;
int totpart = psys->totpart;
float timestep = psys_get_timestep(sim);
/* negative time means "use current time" */
cfra = state->time > 0 ? state->time : DEG_get_ctime(sim->depsgraph);
if (p >= totpart) {
if (!psys->totchild) {
return 0;
}
if (part->childtype == PART_CHILD_FACES) {
if (!(psys->flag & PSYS_KEYED)) {
return 0;
}
cpa = psys->child + p - totpart;
state->time = psys_get_child_time(psys, cpa, cfra, NULL, NULL);
if (!always) {
if ((state->time < 0.0f && !(part->flag & PART_UNBORN)) ||
(state->time > 1.0f && !(part->flag & PART_DIED))) {
return 0;
}
}
state->time = (cfra - (part->sta + (part->end - part->sta) * psys_frand(psys, p + 23))) /
(part->lifetime * psys_frand(psys, p + 24));
psys_get_particle_on_path(sim, p, state, 1);
return 1;
}
else {
cpa = sim->psys->child + p - totpart;
pa = sim->psys->particles + cpa->parent;
}
}
else {
pa = sim->psys->particles + p;
}
if (pa) {
if (!always) {
if ((cfra < pa->time && (part->flag & PART_UNBORN) == 0) ||
(cfra >= pa->dietime && (part->flag & PART_DIED) == 0)) {
return 0;
}
}
cfra = MIN2(cfra, pa->dietime);
}
if (sim->psys->flag & PSYS_KEYED) {
state->time = -cfra;
psys_get_particle_on_path(sim, p, state, 1);
return 1;
}
else {
if (cpa) {
float mat[4][4];
ParticleKey *key1;
float t = (cfra - pa->time) / pa->lifetime;
float par_orco[3] = {0.0f, 0.0f, 0.0f};
key1 = &pa->state;
offset_child(cpa, key1, key1->rot, state, part->childflat, part->childrad);
CLAMP(t, 0.0f, 1.0f);
unit_m4(mat);
ParticleChildModifierContext modifier_ctx = {NULL};
modifier_ctx.thread_ctx = NULL;
modifier_ctx.sim = sim;
modifier_ctx.ptex = NULL;
modifier_ctx.cpa = cpa;
modifier_ctx.orco = cpa->fuv;
modifier_ctx.par_co = key1->co;
modifier_ctx.par_vel = key1->vel;
modifier_ctx.par_rot = key1->rot;
modifier_ctx.par_orco = par_orco;
modifier_ctx.parent_keys = psys->childcache ? psys->childcache[p - totpart] : NULL;
do_child_modifiers(&modifier_ctx, mat, state, t);
if (psys->lattice_deform_data) {
calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength);
}
}
else {
if (pa->state.time == cfra || ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)) {
copy_particle_key(state, &pa->state, 1);
}
else if (pa->prev_state.time == cfra) {
copy_particle_key(state, &pa->prev_state, 1);
}
else {
float dfra, frs_sec = sim->scene->r.frs_sec;
/* let's interpolate to try to be as accurate as possible */
if (pa->state.time + 2.f >= state->time && pa->prev_state.time - 2.f <= state->time) {
if (pa->prev_state.time >= pa->state.time || pa->prev_state.time < 0.f) {
/* prev_state is wrong so let's not use it,
* this can happen at frames 1, 0 or particle birth. */
dfra = state->time - pa->state.time;
copy_particle_key(state, &pa->state, 1);
madd_v3_v3v3fl(state->co, state->co, state->vel, dfra / frs_sec);
}
else {
ParticleKey keys[4];
float keytime;
copy_particle_key(keys + 1, &pa->prev_state, 1);
copy_particle_key(keys + 2, &pa->state, 1);
dfra = keys[2].time - keys[1].time;
keytime = (state->time - keys[1].time) / dfra;
/* convert velocity to timestep size */
mul_v3_fl(keys[1].vel, dfra * timestep);
mul_v3_fl(keys[2].vel, dfra * timestep);
psys_interpolate_particle(-1, keys, keytime, state, 1);
/* convert back to real velocity */
mul_v3_fl(state->vel, 1.f / (dfra * timestep));
interp_v3_v3v3(state->ave, keys[1].ave, keys[2].ave, keytime);
interp_qt_qtqt(state->rot, keys[1].rot, keys[2].rot, keytime);
}
}
else if (pa->state.time + 1.f >= state->time && pa->state.time - 1.f <= state->time) {
/* linear interpolation using only pa->state */
dfra = state->time - pa->state.time;
copy_particle_key(state, &pa->state, 1);
madd_v3_v3v3fl(state->co, state->co, state->vel, dfra / frs_sec);
}
else {
/* Extrapolating over big ranges is not accurate
* so let's just give something close to reasonable back. */
copy_particle_key(state, &pa->state, 0);
}
}
if (sim->psys->lattice_deform_data) {
calc_latt_deform(sim->psys->lattice_deform_data, state->co, psys->lattice_strength);
}
}
return 1;
}
}
void psys_get_dupli_texture(ParticleSystem *psys,
ParticleSettings *part,
ParticleSystemModifierData *psmd,
ParticleData *pa,
ChildParticle *cpa,
float uv[2],
float orco[3])
{
MFace *mface;
MTFace *mtface;
float loc[3];
int num;
/* XXX: on checking '(psmd->dm != NULL)'
* This is incorrect but needed for metaball evaluation.
* Ideally this would be calculated via the depsgraph, however with metaballs,
* the entire scenes dupli's are scanned, which also looks into uncalculated data.
*
* For now just include this workaround as an alternative to crashing,
* but longer term metaballs should behave in a more manageable way, see: T46622. */
uv[0] = uv[1] = 0.f;
/* Grid distribution doesn't support UV or emit from vertex mode */
bool is_grid = (part->distr == PART_DISTR_GRID && part->from != PART_FROM_VERT);
if (cpa) {
if ((part->childtype == PART_CHILD_FACES) && (psmd->mesh_final != NULL)) {
CustomData *mtf_data = &psmd->mesh_final->fdata;
const int uv_idx = CustomData_get_render_layer(mtf_data, CD_MTFACE);
mtface = CustomData_get_layer_n(mtf_data, CD_MTFACE, uv_idx);
if (mtface && !is_grid) {
mface = CustomData_get(&psmd->mesh_final->fdata, cpa->num, CD_MFACE);
mtface += cpa->num;
psys_interpolate_uvs(mtface, mface->v4, cpa->fuv, uv);
}
psys_particle_on_emitter(psmd,
PART_FROM_FACE,
cpa->num,
DMCACHE_ISCHILD,
cpa->fuv,
cpa->foffset,
loc,
0,
0,
0,
orco);
return;
}
else {
pa = psys->particles + cpa->pa[0];
}
}
if ((part->from == PART_FROM_FACE) && (psmd->mesh_final != NULL) && !is_grid) {
CustomData *mtf_data = &psmd->mesh_final->fdata;
const int uv_idx = CustomData_get_render_layer(mtf_data, CD_MTFACE);
mtface = CustomData_get_layer_n(mtf_data, CD_MTFACE, uv_idx);
num = pa->num_dmcache;
if (num == DMCACHE_NOTFOUND) {
num = pa->num;
}
if (num >= psmd->mesh_final->totface) {
/* happens when simplify is enabled
* gives invalid coords but would crash otherwise */
num = DMCACHE_NOTFOUND;
}
if (mtface && !ELEM(num, DMCACHE_NOTFOUND, DMCACHE_ISCHILD)) {
mface = CustomData_get(&psmd->mesh_final->fdata, num, CD_MFACE);
mtface += num;
psys_interpolate_uvs(mtface, mface->v4, pa->fuv, uv);
}
}
psys_particle_on_emitter(
psmd, part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, loc, 0, 0, 0, orco);
}
void psys_get_dupli_path_transform(ParticleSimulationData *sim,
ParticleData *pa,
ChildParticle *cpa,
ParticleCacheKey *cache,
float mat[4][4],
float *scale)
{
Object *ob = sim->ob;
ParticleSystem *psys = sim->psys;
ParticleSystemModifierData *psmd = sim->psmd;
float loc[3], nor[3], vec[3], side[3], len;
float xvec[3] = {-1.0, 0.0, 0.0}, nmat[3][3];
sub_v3_v3v3(vec, (cache + cache->segments)->co, cache->co);
len = normalize_v3(vec);
if (pa == NULL && psys->part->childflat != PART_CHILD_FACES) {
pa = psys->particles + cpa->pa[0];
}
if (pa) {
psys_particle_on_emitter(psmd,
sim->psys->part->from,
pa->num,
pa->num_dmcache,
pa->fuv,
pa->foffset,
loc,
nor,
0,
0,
0);
}
else {
psys_particle_on_emitter(psmd,
PART_FROM_FACE,
cpa->num,
DMCACHE_ISCHILD,
cpa->fuv,
cpa->foffset,
loc,
nor,
0,
0,
0);
}
if (psys->part->rotmode == PART_ROT_VEL) {
transpose_m3_m4(nmat, ob->imat);
mul_m3_v3(nmat, nor);
normalize_v3(nor);
/* make sure that we get a proper side vector */
if (fabsf(dot_v3v3(nor, vec)) > 0.999999f) {
if (fabsf(dot_v3v3(nor, xvec)) > 0.999999f) {
nor[0] = 0.0f;
nor[1] = 1.0f;
nor[2] = 0.0f;
}
else {
nor[0] = 1.0f;
nor[1] = 0.0f;
nor[2] = 0.0f;
}
}
cross_v3_v3v3(side, nor, vec);
normalize_v3(side);
/* rotate side vector around vec */
if (psys->part->phasefac != 0) {
float q_phase[4];
float phasefac = psys->part->phasefac;
if (psys->part->randphasefac != 0.0f) {
phasefac += psys->part->randphasefac * psys_frand(psys, (pa - psys->particles) + 20);
}
axis_angle_to_quat(q_phase, vec, phasefac * (float)M_PI);
mul_qt_v3(q_phase, side);
}
cross_v3_v3v3(nor, vec, side);
unit_m4(mat);
copy_v3_v3(mat[0], vec);
copy_v3_v3(mat[1], side);
copy_v3_v3(mat[2], nor);
}
else {
quat_to_mat4(mat, pa->state.rot);
}
*scale = len;
}
void psys_apply_hair_lattice(Depsgraph *depsgraph, Scene *scene, Object *ob, ParticleSystem *psys)
{
ParticleSimulationData sim = {0};
sim.depsgraph = depsgraph;
sim.scene = scene;
sim.ob = ob;
sim.psys = psys;
sim.psmd = psys_get_modifier(ob, psys);
psys->lattice_deform_data = psys_create_lattice_deform_data(&sim);
if (psys->lattice_deform_data) {
ParticleData *pa = psys->particles;
HairKey *hkey;
int p, h;
float hairmat[4][4], imat[4][4];
for (p = 0; p < psys->totpart; p++, pa++) {
psys_mat_hair_to_global(sim.ob, sim.psmd->mesh_final, psys->part->from, pa, hairmat);
invert_m4_m4(imat, hairmat);
hkey = pa->hair;
for (h = 0; h < pa->totkey; h++, hkey++) {
mul_m4_v3(hairmat, hkey->co);
calc_latt_deform(psys->lattice_deform_data, hkey->co, psys->lattice_strength);
mul_m4_v3(imat, hkey->co);
}
}
end_latt_deform(psys->lattice_deform_data);
psys->lattice_deform_data = NULL;
/* protect the applied shape */
psys->flag |= PSYS_EDITED;
}
}
/* Draw Engine */
void (*BKE_particle_batch_cache_dirty_tag_cb)(ParticleSystem *psys, int mode) = NULL;
void (*BKE_particle_batch_cache_free_cb)(ParticleSystem *psys) = NULL;
void BKE_particle_batch_cache_dirty_tag(ParticleSystem *psys, int mode)
{
if (psys->batch_cache) {
BKE_particle_batch_cache_dirty_tag_cb(psys, mode);
}
}
void BKE_particle_batch_cache_free(ParticleSystem *psys)
{
if (psys->batch_cache) {
BKE_particle_batch_cache_free_cb(psys);
}
}
| 29.27055 | 99 | 0.562275 | [
"mesh",
"object",
"shape",
"vector"
] |
da01baaba7c7902408d3af155701a0541117369c | 14,464 | c | C | src/nautilus/loader.c | abu-bakar-nu/nautilus | 9c5046d714e2ff2a00f757ba42dc887024365be6 | [
"MIT"
] | 2 | 2020-01-04T02:21:10.000Z | 2020-08-13T02:42:43.000Z | src/nautilus/loader.c | abu-bakar-nu/nautilus | 9c5046d714e2ff2a00f757ba42dc887024365be6 | [
"MIT"
] | null | null | null | src/nautilus/loader.c | abu-bakar-nu/nautilus | 9c5046d714e2ff2a00f757ba42dc887024365be6 | [
"MIT"
] | 3 | 2019-04-24T15:10:45.000Z | 2020-03-08T00:00:00.000Z | /*
* This file is part of the Nautilus AeroKernel developed
* by the Hobbes and V3VEE Projects with funding from the
* United States National Science Foundation and the Department of Energy.
*
* The V3VEE Project is a joint project between Northwestern University
* and the University of New Mexico. The Hobbes Project is a collaboration
* led by Sandia National Laboratories that includes several national
* laboratories and universities. You can find out more at:
* http://www.v3vee.org and
* http://xstack.sandia.gov/hobbes
*
* Copyright (c) 2017, Peter Dinda <pdinda@northwestern.edu>
* Copyright (c) 2017, The V3VEE Project <http://www.v3vee.org>
* The Hobbes Project <http://xstack.sandia.gov/hobbes>
* All rights reserved.
*
* Author: Peter Dinda <pdinda@northwestern.edu>
*
* This is free software. You are permitted to use,
* redistribute, and modify it as specified in the file "LICENSE.txt".
*/
#include <nautilus/nautilus.h>
#include <nautilus/nautilus_exe.h>
#include <nautilus/loader.h>
#include <nautilus/fs.h>
#include <nautilus/shell.h>
#ifndef NAUT_CONFIG_DEBUG_LOADER
#undef DEBUG_PRINT
#define DEBUG_PRINT(fmt, args...)
#endif
#define ERROR(fmt, args...) ERROR_PRINT("loader: " fmt, ##args)
#define DEBUG(fmt, args...) DEBUG_PRINT("loader: " fmt, ##args)
#define INFO(fmt, args...) INFO_PRINT("loader: " fmt, ##args)
struct nk_exec {
void *blob; // where we loaded it
uint64_t blob_size; // extent in memory
uint64_t entry_offset; // where to start executing in it
};
/******************************************************************
Data contained in the ELF file we will attempt to load
******************************************************************/
#define ELF_MAGIC 0x464c457f
#define MB2_MAGIC 0xe85250d6
// EXE has one of these headers for sure
typedef struct mb_header {
uint32_t magic;
uint32_t arch;
#define ARCH_X86 0
uint32_t headerlen;
uint32_t checksum;
} __attribute__((packed)) mb_header_t;
// generic tagged type
typedef struct mb_tag {
uint16_t type;
uint16_t flags;
uint32_t size;
} __attribute__((packed)) mb_tag_t;
#define MB_TAG_INFO 1
typedef struct mb_info_req {
mb_tag_t tag;
uint32_t types[0];
} __attribute__((packed)) mb_info_t;
typedef uint32_t u_virt, u_phys;
#define MB_TAG_ADDRESS 2
typedef struct mb_addr {
mb_tag_t tag;
u_virt header_addr;
u_virt load_addr;
u_virt load_end_addr;
u_virt bss_end_addr;
} __attribute__((packed)) mb_addr_t;
#define MB_TAG_ENTRY 3
typedef struct mb_entry {
mb_tag_t tag;
u_virt entry_addr;
} __attribute__((packed)) mb_entry_t;
#define MB_TAG_FLAGS 4
typedef struct mb_flags {
mb_tag_t tag;
uint32_t console_flags;
} __attribute__((packed)) mb_flags_t;
#define MB_TAG_FRAMEBUF 5
typedef struct mb_framebuf {
mb_tag_t tag;
uint32_t width;
uint32_t height;
uint32_t depth;
} __attribute__((packed)) mb_framebuf_t;
#define MB_TAG_MODALIGN 6
typedef struct mb_modalign {
mb_tag_t tag;
uint32_t size;
} __attribute__((packed)) mb_modalign_t;
// For HVM, which can use a pure 64 bit variant
// version of multiboot. The existence of
// this tag indicates that this special mode is
// requested
#define MB_TAG_MB64_HRT 0xf00d
typedef struct mb_mb64_hrt {
mb_tag_t tag;
uint64_t hrt_flags;
// whether this kernel is relocable
#define MB_TAG_MB64_HRT_FLAG_RELOC 0x1
// whether this is an executable
#define MB_TAG_MB64_HRT_FLAG_EXE 0x2
// How to map the memory in the initial PTs
// highest set bit wins
#define MB_TAG_MB64_HRT_FLAG_MAP_4KB 0x100
#define MB_TAG_MB64_HRT_FLAG_MAP_2MB 0x200
#define MB_TAG_MB64_HRT_FLAG_MAP_1GB 0x400
#define MB_TAG_MB64_HRT_FLAG_MAP_512GB 0x800
// How much physical address space to map in the
// initial page tables (bytes)
//
uint64_t max_mem_to_map;
// offset of the GVA->GPA mappings (GVA of GPA 0)
uint64_t gva_offset;
// 64 bit entry address (=0 to use entry tag (which will be offset by gva_offset))
uint64_t gva_entry;
// desired address of the page the VMM, HRT, and ROS share
// for communication. "page" here a 4 KB quantity
uint64_t comm_page_gpa;
// desired interrupt vector that should be used for upcalls
// the default for this is 255
uint8_t hrt_int_vector;
uint8_t reserved[7];
} __attribute__((packed)) mb_mb64_hrt_t;
typedef struct mb_data {
mb_header_t *header;
mb_info_t *info;
mb_addr_t *addr;
mb_entry_t *entry;
mb_flags_t *flags;
mb_framebuf_t *framebuf;
mb_modalign_t *modalign;
mb_mb64_hrt_t *mb64_hrt;
} mb_data_t;
static int
is_elf (uint8_t *data, uint64_t size)
{
if (*((uint32_t*)data)==ELF_MAGIC) {
return 1;
} else {
return 0;
}
}
static mb_header_t *
find_mb_header (uint8_t *data, uint64_t size)
{
uint64_t limit = size > 32768 ? 32768 : size;
uint64_t i;
DEBUG("scanning for mb header at %p (%lu bytes)\n",data,size);
// Scan for the .boot magic cookie
// must be in first 32K, assume 4 byte aligned
for (i=0;i<limit;i+=4) {
if (*((uint32_t*)&data[i])==MB2_MAGIC) {
DEBUG("Found multiboot header at offset 0x%llx\n",i);
return (mb_header_t *) &data[i];
}
}
return 0;
}
static int
checksum4_ok (uint32_t *data, uint64_t size)
{
int i;
uint32_t sum=0;
for (i=0;i<size;i++) {
sum+=data[i];
}
return sum==0;
}
static int
parse_multiboot_header (void *data, uint64_t size, mb_data_t *mb)
{
uint64_t i;
mb_header_t *mb_header=0;
mb_tag_t *mb_tag=0;
mb_info_t *mb_inf=0;
mb_addr_t *mb_addr=0;
mb_entry_t *mb_entry=0;
mb_flags_t *mb_flags=0;
mb_framebuf_t *mb_framebuf=0;
mb_modalign_t *mb_modalign=0;
mb_mb64_hrt_t *mb_mb64_hrt=0;
if (!is_elf(data,size)) {
ERROR("HRT is not an ELF\n");
return -1;
}
mb_header = find_mb_header(data,size);
if (!mb_header) {
ERROR("No multiboot header found\n");
return -1;
}
// Checksum applies only to the header itself, not to
// the subsequent tags...
if (!checksum4_ok((uint32_t*)mb_header,4)) {
ERROR("Multiboot header has bad checksum\n");
return -1;
}
DEBUG("Multiboot header: arch=0x%x, headerlen=0x%x\n", mb_header->arch, mb_header->headerlen);
mb_tag = (mb_tag_t*)((void*)mb_header+16);
while (!(mb_tag->type==0 && mb_tag->size==8)) {
DEBUG("tag: type 0x%x flags=0x%x size=0x%x\n",mb_tag->type, mb_tag->flags,mb_tag->size);
switch (mb_tag->type) {
case MB_TAG_INFO: {
if (mb_inf) {
ERROR("Multiple info tags found!\n");
return -1;
}
mb_inf = (mb_info_t*)mb_tag;
DEBUG(" info request - types follow\n");
for (i=0;(mb_tag->size-8)/4;i++) {
DEBUG(" %llu: type 0x%x\n", i, mb_inf->types[i]);
}
}
break;
case MB_TAG_ADDRESS: {
if (mb_addr) {
ERROR("Multiple address tags found!\n");
return -1;
}
mb_addr = (mb_addr_t*)mb_tag;
DEBUG(" address\n");
DEBUG(" header_addr = 0x%x\n", mb_addr->header_addr);
DEBUG(" load_addr = 0x%x\n", mb_addr->load_addr);
DEBUG(" load_end_addr = 0x%x\n", mb_addr->load_end_addr);
DEBUG(" bss_end_addr = 0x%x\n", mb_addr->bss_end_addr);
}
break;
case MB_TAG_ENTRY: {
if (mb_entry) {
ERROR("Multiple entry tags found!\n");
return -1;
}
mb_entry=(mb_entry_t*)mb_tag;
DEBUG(" entry\n");
DEBUG(" entry_addr = 0x%x\n", mb_entry->entry_addr);
}
break;
case MB_TAG_FLAGS: {
if (mb_flags) {
ERROR("Multiple flags tags found!\n");
return -1;
}
mb_flags = (mb_flags_t*)mb_tag;
DEBUG(" flags\n");
DEBUG(" console_flags = 0x%x\n", mb_flags->console_flags);
}
break;
case MB_TAG_FRAMEBUF: {
if (mb_framebuf) {
ERROR("Multiple framebuf tags found!\n");
return -1;
}
mb_framebuf = (mb_framebuf_t*)mb_tag;
DEBUG(" framebuf\n");
DEBUG(" width = 0x%x\n", mb_framebuf->width);
DEBUG(" height = 0x%x\n", mb_framebuf->height);
DEBUG(" depth = 0x%x\n", mb_framebuf->depth);
}
break;
case MB_TAG_MODALIGN: {
if (mb_modalign) {
ERROR("Multiple modalign tags found!\n");
return -1;
}
mb_modalign = (mb_modalign_t*)mb_tag;
DEBUG(" modalign\n");
DEBUG(" size = 0x%x\n", mb_modalign->size);
}
break;
case MB_TAG_MB64_HRT: {
if (mb_mb64_hrt) {
ERROR("Multiple mb64_hrt tags found!\n");
return -1;
}
mb_mb64_hrt = (mb_mb64_hrt_t*)mb_tag;
DEBUG(" mb64_hrt\n");
}
break;
default:
DEBUG("Unknown tag... Skipping...\n");
break;
}
mb_tag = (mb_tag_t *)(((void*)mb_tag) + mb_tag->size);
}
// copy out to caller
mb->header=mb_header;
mb->info=mb_inf;
mb->addr=mb_addr;
mb->entry=mb_entry;
mb->flags=mb_flags;
mb->framebuf=mb_framebuf;
mb->modalign=mb_modalign;
mb->mb64_hrt=mb_mb64_hrt;
return 0;
}
#define MB_LOAD (2*PAGE_SIZE_4KB)
// load executable from file, do not run
struct nk_exec *nk_load_exec(char *path)
{
nk_fs_fd_t fd=FS_BAD_FD;
void *page = 0;
struct nk_exec *e = 0;
DEBUG("Loading executable at path %s\n", path);
if (!(page = malloc(MB_LOAD))) {
ERROR("Failed to allocate temporary space for loading file %s\n",path);
goto out_bad;
}
memset(page,0,MB_LOAD);
if (FS_FD_ERR(fd = nk_fs_open(path,O_RDONLY,0666))) {
ERROR("Executable file %s could not be opened\n", path);
goto out_bad;
}
if (nk_fs_read(fd,page,MB_LOAD)!=MB_LOAD) {
ERROR("Could not read first page of file %s\n", path);
goto out_bad;
}
// the MB header should be in the first 2 pages by construction
mb_data_t m;
if (parse_multiboot_header(page, MB_LOAD, &m)) {
ERROR("Cannot parse multiboot kernel header from first page of %s\n", path);
goto out_bad;
}
DEBUG("Parsed MB header from %s\n", path);
if (!m.mb64_hrt) {
ERROR("%s is not a MB64 image\n", path);
goto out_bad;
}
#define REQUIRED_FLAGS (MB_TAG_MB64_HRT_FLAG_RELOC | MB_TAG_MB64_HRT_FLAG_EXE)
if ((m.mb64_hrt->hrt_flags & REQUIRED_FLAGS)!=REQUIRED_FLAGS) {
ERROR("%s's flags (%lx) do not include %lx\n", path, m.mb64_hrt->hrt_flags, REQUIRED_FLAGS);
goto out_bad;
}
uint64_t load_start, load_end, bss_end;
uint64_t blob_size;
// although these are target addresses, we assume
// we can use them as offsets as well. The next page we load
// will be the "real" start of the text segment
load_start = m.addr->load_addr;
load_end = m.addr->load_end_addr;
bss_end = m.addr->bss_end_addr;
#define ALIGN_UP(x) (((x) % PAGE_SIZE_4KB) ? PAGE_SIZE_4KB*(1 + (x)/PAGE_SIZE_4KB) : (x))
blob_size = ALIGN_UP(bss_end - load_start + 1);
DEBUG("Load continuing... start=0x%lx, end=0x%lx, bss_end=0x%lx, blob_size=0x%lx\n",
load_start, load_end, bss_end, blob_size);
e = malloc(sizeof(struct nk_exec));
if (!e) {
ERROR("Cannot allocate executable exec for %s\n", path);
goto out_bad;
}
memset(e,0,sizeof(*e));
e->blob = malloc(blob_size);
if (!e->blob) {
ERROR("Cannot allocate executable blob for %s\n",path);
goto out_bad;
}
e->blob_size = blob_size;
e->entry_offset = m.entry->entry_addr - PAGE_SIZE_4KB;
// now copy it to memory
ssize_t n;
if ((n = nk_fs_read(fd,e->blob,e->blob_size))<0) {
ERROR("Unable to read blob from %s\n", path);
goto out_bad;
}
DEBUG("Tried to read 0x%lx byte blob, got 0x%lx bytes\n", e->blob_size, n);
DEBUG("Successfully loaded executable %s\n",path);
memset(e->blob+(load_end-load_start),0,bss_end-load_end);
DEBUG("Cleared BSS\n");
nk_fs_close(fd);
DEBUG("file closed\n");
free(page);
return e;
out_bad:
if (!FS_FD_ERR(fd)) { nk_fs_close(fd); }
if (page) { free(page); }
if (e && e->blob) { free(e->blob); }
if (e) { free(e); }
return 0;
}
// run executable's entry point - this is a blocking call on the current thread
// user I/O is via the current VC
static void * (*__nk_func_table[])() = {
[NK_VC_PRINTF] = (void * (*)()) nk_vc_printf,
};
int
nk_start_exec (struct nk_exec *exec, void *in, void **out)
{
int (*start)(void *, void **,void * (**)());
if (!exec) {
ERROR("Exec of null\n");
return -1;
}
if (!exec->blob) {
ERROR("Exec of null blob\n");
return -1;
}
if (exec->entry_offset > exec->blob_size) {
ERROR("Exec attempt beyond end of blob\n");
return -1;
}
start = exec->blob + exec->entry_offset;
DEBUG("Starting executable %p loaded at address %p with entry address %p and arguments %p and %p\n", exec, exec->blob, start, in, out);
int rc = start(in, out, __nk_func_table);
DEBUG("Executable %p has returned with rc=%d and *out=%p\n", exec, rc, out ? *out : 0);
return rc;
}
int
nk_unload_exec (struct nk_exec *exec)
{
if (exec && exec->blob) {
free(exec->blob);
}
if (exec) {
free(exec);
}
return 0;
}
// these don't do much now
int
nk_loader_init( )
{
DEBUG("init\n");
return 0;
}
void
nk_loader_deinit ()
{
DEBUG("deinit\n");
}
static int
handle_run (char * buf, void * priv)
{
char path[80];
if (sscanf(buf,"run %s", path)!=1) {
nk_vc_printf("Can't determine what to run\n");
return 0;
}
struct nk_exec *e = nk_load_exec(path);
if (!e) {
nk_vc_printf("Can't load %s\n", path);
return 0;
}
nk_vc_printf("Loaded executable, now running\n");
if (nk_start_exec(e,0,0)) {
nk_vc_printf("Failed to run %s\n", path);
}
nk_vc_printf("Unloading executable\n");
if (nk_unload_exec(e)) {
nk_vc_printf("Failed to unload %s\n",path);
}
return 0;
}
static struct shell_cmd_impl run_impl = {
.cmd = "run",
.help_str = "run path",
.handler = handle_run,
};
nk_register_shell_cmd(run_impl);
| 24.937931 | 139 | 0.619884 | [
"vector"
] |
da0332a17a5676ee5ef942a348b846fbd3d007c8 | 1,942 | c | C | libc/libgloss/sparc_leon/catch_interrupt_mvt.c | The0x539/wasp | 5f83aab7bf0c0915b1d3491034d35b091c7aebdf | [
"MIT"
] | 453 | 2016-07-29T23:26:30.000Z | 2022-02-21T01:09:13.000Z | libc/libgloss/sparc_leon/catch_interrupt_mvt.c | The0x539/wasp | 5f83aab7bf0c0915b1d3491034d35b091c7aebdf | [
"MIT"
] | 175 | 2018-05-30T03:06:15.000Z | 2019-02-06T23:54:24.000Z | libc/libgloss/sparc_leon/catch_interrupt_mvt.c | The0x539/wasp | 5f83aab7bf0c0915b1d3491034d35b091c7aebdf | [
"MIT"
] | 57 | 2016-07-29T23:34:09.000Z | 2021-07-13T18:17:02.000Z | /*
* Copyright (c) 2011 Aeroflex Gaisler
*
* BSD license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <asm-leon/leonstack.h>
#include <asm-leon/irq.h>
#define NULL 0
/* multi vector trapping version of trap handler installs */
int
mvtlolevelirqinstall (int irqnr, void (*handler) ())
{
unsigned long h = (unsigned long) handler;
unsigned long *addr =
(unsigned long *) ((locore_readtbr () & ~0xFFF) + 0x100 + (16 * irqnr));
if (irqnr == 0 || irqnr >= 15)
{
return 0;
}
addr[0] = ((h >> 10) & 0x3fffff) | 0x29000000; /* 29000000: sethi %hi(handler), %l4 */
addr[1] = ((h) & 0x3ff) | 0x81c52000; /* 81c52000: jmpl %l4 + %lo(handler), %g0 */
addr[2] = 0x01000000; /* 01000000: nop */
addr[3] = 0x01000000; /* 01000000: nop */
return 1;
}
int
lolevelirqinstall (int irqnr, void (*handler) ())
{
return mvtlolevelirqinstall (irqnr, handler);
}
| 34.678571 | 96 | 0.696189 | [
"vector"
] |
fffc0ce45216945c4474ee7a87a2e66791cd97a9 | 47,007 | h | C | src/wasm-stack.h | kumpera/binaryen | f831369f8586f86cafe10ee4f34c9b1f239abbfc | [
"Apache-2.0"
] | 1 | 2019-01-15T02:08:04.000Z | 2019-01-15T02:08:04.000Z | src/wasm-stack.h | kumpera/binaryen | f831369f8586f86cafe10ee4f34c9b1f239abbfc | [
"Apache-2.0"
] | null | null | null | src/wasm-stack.h | kumpera/binaryen | f831369f8586f86cafe10ee4f34c9b1f239abbfc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 WebAssembly Community Group participants
*
* 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 wasm_stack_h
#define wasm_stack_h
#include "wasm.h"
#include "wasm-binary.h"
#include "wasm-traversal.h"
#include "ir/branch-utils.h"
#include "pass.h"
namespace wasm {
// Stack IR: an IR that represents code at the wasm binary format level,
// that is, a stack machine. Binaryen IR is *almost* identical to this,
// but as documented in README.md, there are a few differences, intended
// to make Binaryen IR fast and flexible for maximal optimization. Stack
// IR, on the other hand, is designed to optimize a few final things that
// can only really be done when modeling the stack machine format precisely.
// Currently the benefits of Stack IR are minor, less than 1% reduction in
// code size. For that reason it is just a secondary IR, run optionally
// after the main IR has been optimized. However, if we improve Stack IR
// optimizations to a point where they have a significant impact, it's
// possible that could motivate investigating replacing the main IR with Stack
// IR (so that we have just a single IR).
// A StackIR instance (see wasm.h) contains a linear sequence of
// stack instructions. This representation is very simple: just a single vector of
// all instructions, in order.
// * nullptr is allowed in the vector, representing something to skip.
// This is useful as a common thing optimizations do is remove instructions,
// so this way we can do so without compacting the vector all the time.
// A Stack IR instruction. Most just directly reflect a Binaryen IR node,
// but we need extra ones for certain things.
class StackInst {
public:
StackInst(MixedArena&) {}
enum Op {
Basic, // an instruction directly corresponding to a non-control-flow
// Binaryen IR node
BlockBegin, // the beginning of a block
BlockEnd, // the ending of a block
IfBegin, // the beginning of a if
IfElse, // the else of a if
IfEnd, // the ending of a if
LoopBegin, // the beginning of a loop
LoopEnd, // the ending of a loop
} op;
Expression* origin; // the expression this originates from
Type type; // the type - usually identical to the origin type, but
// e.g. wasm has no unreachable blocks, they must be none
};
//
// StackWriter: Writes out binary format stack machine code for a Binaryen IR expression
//
// A stack writer has one of three modes:
// * Binaryen2Binary: directly writes the expression to wasm binary
// * Binaryen2Stack: queues the expressions linearly, in Stack IR (SIR)
// * Stack2Binary: emits SIR to wasm binary
//
// Direct writing, in Binaryen2Binary, is fast. Otherwise, Binaryen2Stack
// lets you optimize the Stack IR before running Stack2Binary (but the cost
// is that the extra IR in the middle makes things 20% slower than direct
// Binaryen2Binary).
//
// To reduce the amount of boilerplate code here, we implement all 3 in
// a single class, templated on the mode. This allows compilers to trivially
// optimize out irrelevant code paths, and there should be no runtime
// downside.
//
enum class StackWriterMode {
Binaryen2Binary, Binaryen2Stack, Stack2Binary
};
template<StackWriterMode Mode, typename Parent>
class StackWriter : public Visitor<StackWriter<Mode, Parent>> {
public:
StackWriter(Parent& parent, BufferWithRandomAccess& o, bool sourceMap=false, bool debug=false)
: parent(parent), o(o), sourceMap(sourceMap), debug(debug), allocator(parent.getModule()->allocator) {}
StackIR stackIR; // filled in Binaryen2Stack, read in Stack2Binary
std::map<Type, size_t> numLocalsByType; // type => number of locals of that type in the compact form
// visits a node, emitting the proper code for it
void visit(Expression* curr);
// emits a node, but if it is a block with no name, emit a list of its contents
void visitPossibleBlockContents(Expression* curr);
// visits a child node. (in some modes we may not want to visit children,
// that logic is handled here)
void visitChild(Expression* curr);
void visitBlock(Block* curr);
void visitBlockEnd(Block* curr);
void visitIf(If* curr);
void visitIfElse(If* curr);
void visitIfEnd(If* curr);
void visitLoop(Loop* curr);
void visitLoopEnd(Loop* curr);
void visitBreak(Break* curr);
void visitSwitch(Switch* curr);
void visitCall(Call* curr);
void visitCallImport(CallImport* curr);
void visitCallIndirect(CallIndirect* curr);
void visitGetLocal(GetLocal* curr);
void visitSetLocal(SetLocal* curr);
void visitGetGlobal(GetGlobal* curr);
void visitSetGlobal(SetGlobal* curr);
void visitLoad(Load* curr);
void visitStore(Store* curr);
void visitAtomicRMW(AtomicRMW* curr);
void visitAtomicCmpxchg(AtomicCmpxchg* curr);
void visitAtomicWait(AtomicWait* curr);
void visitAtomicWake(AtomicWake* curr);
void visitConst(Const* curr);
void visitUnary(Unary* curr);
void visitBinary(Binary* curr);
void visitSelect(Select* curr);
void visitReturn(Return* curr);
void visitHost(Host* curr);
void visitNop(Nop* curr);
void visitUnreachable(Unreachable* curr);
void visitDrop(Drop* curr);
// We need to emit extra unreachable opcodes in some cases
void emitExtraUnreachable();
// If we are in Binaryen2Stack, then this adds the item to the
// stack IR and returns true, which is all we need to do for
// non-control flow expressions.
bool justAddToStack(Expression* curr);
void setFunction(Function* funcInit) {
func = funcInit;
}
void mapLocalsAndEmitHeader();
protected:
Parent& parent;
BufferWithRandomAccess& o;
bool sourceMap;
bool debug;
MixedArena& allocator;
Function* func;
std::map<Index, size_t> mappedLocals; // local index => index in compact form of [all int32s][all int64s]etc
std::vector<Name> breakStack;
int32_t getBreakIndex(Name name);
void emitMemoryAccess(size_t alignment, size_t bytes, uint32_t offset);
void finishFunctionBody();
StackInst* makeStackInst(StackInst::Op op, Expression* origin);
StackInst* makeStackInst(Expression* origin) {
return makeStackInst(StackInst::Basic, origin);
}
};
// Write out a single expression, such as an offset for a global segment.
template<typename Parent>
class ExpressionStackWriter : StackWriter<StackWriterMode::Binaryen2Binary, Parent> {
public:
ExpressionStackWriter(Expression* curr, Parent& parent, BufferWithRandomAccess& o, bool debug=false) :
StackWriter<StackWriterMode::Binaryen2Binary, Parent>(parent, o, /* sourceMap= */ false, debug) {
this->visit(curr);
}
};
// Write out a function body, including the local header info.
template<typename Parent>
class FunctionStackWriter : StackWriter<StackWriterMode::Binaryen2Binary, Parent> {
public:
FunctionStackWriter(Function* funcInit, Parent& parent, BufferWithRandomAccess& o, bool sourceMap=false, bool debug=false) :
StackWriter<StackWriterMode::Binaryen2Binary, Parent>(parent, o, sourceMap, debug) {
this->setFunction(funcInit);
this->mapLocalsAndEmitHeader();
this->visitPossibleBlockContents(this->func->body);
this->finishFunctionBody();
}
};
// Use Stack IR to write the function body
template<typename Parent>
class StackIRFunctionStackWriter : StackWriter<StackWriterMode::Stack2Binary, Parent> {
public:
StackIRFunctionStackWriter(Function* funcInit, Parent& parent, BufferWithRandomAccess& o, bool debug=false) :
StackWriter<StackWriterMode::Stack2Binary, Parent>(parent, o, false, debug) {
this->setFunction(funcInit);
this->mapLocalsAndEmitHeader();
for (auto* inst : *funcInit->stackIR) {
if (!inst) continue; // a nullptr is just something we can skip
switch (inst->op) {
case StackInst::Basic:
case StackInst::BlockBegin:
case StackInst::IfBegin:
case StackInst::LoopBegin: {
this->visit(inst->origin);
break;
}
case StackInst::BlockEnd: {
this->visitBlockEnd(inst->origin->template cast<Block>());
break;
}
case StackInst::IfElse: {
this->visitIfElse(inst->origin->template cast<If>());
break;
}
case StackInst::IfEnd: {
this->visitIfEnd(inst->origin->template cast<If>());
break;
}
case StackInst::LoopEnd: {
this->visitLoopEnd(inst->origin->template cast<Loop>());
break;
}
default: WASM_UNREACHABLE();
}
}
this->finishFunctionBody();
}
};
//
// Implementations
//
// StackWriter
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::mapLocalsAndEmitHeader() {
// Map them
for (Index i = 0; i < func->getNumParams(); i++) {
size_t curr = mappedLocals.size();
mappedLocals[i] = curr;
}
for (auto type : func->vars) {
numLocalsByType[type]++;
}
std::map<Type, size_t> currLocalsByType;
for (Index i = func->getVarIndexBase(); i < func->getNumLocals(); i++) {
size_t index = func->getVarIndexBase();
Type type = func->getLocalType(i);
currLocalsByType[type]++; // increment now for simplicity, must decrement it in returns
if (type == i32) {
mappedLocals[i] = index + currLocalsByType[i32] - 1;
continue;
}
index += numLocalsByType[i32];
if (type == i64) {
mappedLocals[i] = index + currLocalsByType[i64] - 1;
continue;
}
index += numLocalsByType[i64];
if (type == f32) {
mappedLocals[i] = index + currLocalsByType[f32] - 1;
continue;
}
index += numLocalsByType[f32];
if (type == f64) {
mappedLocals[i] = index + currLocalsByType[f64] - 1;
continue;
}
WASM_UNREACHABLE();
}
// Emit them.
o << U32LEB(
(numLocalsByType[i32] ? 1 : 0) +
(numLocalsByType[i64] ? 1 : 0) +
(numLocalsByType[f32] ? 1 : 0) +
(numLocalsByType[f64] ? 1 : 0)
);
if (numLocalsByType[i32]) o << U32LEB(numLocalsByType[i32]) << binaryType(i32);
if (numLocalsByType[i64]) o << U32LEB(numLocalsByType[i64]) << binaryType(i64);
if (numLocalsByType[f32]) o << U32LEB(numLocalsByType[f32]) << binaryType(f32);
if (numLocalsByType[f64]) o << U32LEB(numLocalsByType[f64]) << binaryType(f64);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visit(Expression* curr) {
if (Mode == StackWriterMode::Binaryen2Binary && sourceMap) {
parent.writeDebugLocation(curr, func);
}
Visitor<StackWriter>::visit(curr);
}
// emits a node, but if it is a block with no name, emit a list of its contents
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitPossibleBlockContents(Expression* curr) {
auto* block = curr->dynCast<Block>();
if (!block || BranchUtils::BranchSeeker::hasNamed(block, block->name)) {
visitChild(curr);
return;
}
for (auto* child : block->list) {
visitChild(child);
}
if (block->type == unreachable && block->list.back()->type != unreachable) {
// similar to in visitBlock, here we could skip emitting the block itself,
// but must still end the 'block' (the contents, really) with an unreachable
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitChild(Expression* curr) {
// In stack => binary, we don't need to visit child nodes, everything
// is already in the linear stream.
if (Mode != StackWriterMode::Stack2Binary) {
visit(curr);
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBlock(Block* curr) {
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::BlockBegin, curr));
} else {
if (debug) std::cerr << "zz node: Block" << std::endl;
o << int8_t(BinaryConsts::Block);
o << binaryType(curr->type != unreachable ? curr->type : none);
}
breakStack.push_back(curr->name); // TODO: we don't need to do this in Binaryen2Stack
Index i = 0;
for (auto* child : curr->list) {
if (debug) std::cerr << " " << size_t(curr) << "\n zz Block element " << i++ << std::endl;
visitChild(child);
}
// in Stack2Binary the block ending is in the stream later on
if (Mode == StackWriterMode::Stack2Binary) {
return;
}
visitBlockEnd(curr);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBlockEnd(Block* curr) {
if (curr->type == unreachable) {
// an unreachable block is one that cannot be exited. We cannot encode this directly
// in wasm, where blocks must be none,i32,i64,f32,f64. Since the block cannot be
// exited, we can emit an unreachable at the end, and that will always be valid,
// and then the block is ok as a none
emitExtraUnreachable();
}
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::BlockEnd, curr));
} else {
o << int8_t(BinaryConsts::End);
}
assert(!breakStack.empty());
breakStack.pop_back();
if (curr->type == unreachable) {
// and emit an unreachable *outside* the block too, so later things can pop anything
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitIf(If* curr) {
if (debug) std::cerr << "zz node: If" << std::endl;
if (curr->condition->type == unreachable) {
// this if-else is unreachable because of the condition, i.e., the condition
// does not exit. So don't emit the if, but do consume the condition
visitChild(curr->condition);
emitExtraUnreachable();
return;
}
visitChild(curr->condition);
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::IfBegin, curr));
} else {
o << int8_t(BinaryConsts::If);
o << binaryType(curr->type != unreachable ? curr->type : none);
}
breakStack.push_back(IMPOSSIBLE_CONTINUE); // the binary format requires this; we have a block if we need one
// TODO: optimize this in Stack IR (if child is a block, we
// may break to this instead)
visitPossibleBlockContents(curr->ifTrue); // TODO: emit block contents directly, if possible
if (Mode == StackWriterMode::Stack2Binary) {
return;
}
if (curr->ifFalse) {
visitIfElse(curr);
}
visitIfEnd(curr);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitIfElse(If* curr) {
assert(!breakStack.empty());
breakStack.pop_back();
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::IfElse, curr));
} else {
o << int8_t(BinaryConsts::Else);
}
breakStack.push_back(IMPOSSIBLE_CONTINUE); // TODO ditto
visitPossibleBlockContents(curr->ifFalse);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitIfEnd(If* curr) {
assert(!breakStack.empty());
breakStack.pop_back();
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::IfEnd, curr));
} else {
o << int8_t(BinaryConsts::End);
}
if (curr->type == unreachable) {
// we already handled the case of the condition being unreachable. otherwise,
// we may still be unreachable, if we are an if-else with both sides unreachable.
// wasm does not allow this to be emitted directly, so we must do something more. we could do
// better, but for now we emit an extra unreachable instruction after the if, so it is not consumed itself,
assert(curr->ifFalse);
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitLoop(Loop* curr) {
if (debug) std::cerr << "zz node: Loop" << std::endl;
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::LoopBegin, curr));
} else {
o << int8_t(BinaryConsts::Loop);
o << binaryType(curr->type != unreachable ? curr->type : none);
}
breakStack.push_back(curr->name);
visitPossibleBlockContents(curr->body);
if (Mode == StackWriterMode::Stack2Binary) {
return;
}
visitLoopEnd(curr);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitLoopEnd(Loop* curr) {
assert(!breakStack.empty());
breakStack.pop_back();
if (curr->type == unreachable) {
// we emitted a loop without a return type, and the body might be
// block contents, so ensure it is not consumed
emitExtraUnreachable();
}
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(StackInst::LoopEnd, curr));
} else {
o << int8_t(BinaryConsts::End);
}
if (curr->type == unreachable) {
// we emitted a loop without a return type, so it must not be consumed
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBreak(Break* curr) {
if (debug) std::cerr << "zz node: Break" << std::endl;
if (curr->value) {
visitChild(curr->value);
}
if (curr->condition) visitChild(curr->condition);
if (!justAddToStack(curr)) {
o << int8_t(curr->condition ? BinaryConsts::BrIf : BinaryConsts::Br)
<< U32LEB(getBreakIndex(curr->name));
}
if (curr->condition && curr->type == unreachable) {
// a br_if is normally none or emits a value. if it is unreachable,
// then either the condition or the value is unreachable, which is
// extremely rare, and may require us to make the stack polymorphic
// (if the block we branch to has a value, we may lack one as we
// are not a reachable branch; the wasm spec on the other hand does
// presume the br_if emits a value of the right type, even if it
// popped unreachable)
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSwitch(Switch* curr) {
if (debug) std::cerr << "zz node: Switch" << std::endl;
if (curr->value) {
visitChild(curr->value);
}
visitChild(curr->condition);
if (!BranchUtils::isBranchReachable(curr)) {
// if the branch is not reachable, then it's dangerous to emit it, as
// wasm type checking rules are different, especially in unreachable
// code. so just don't emit that unreachable code.
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::TableSwitch) << U32LEB(curr->targets.size());
for (auto target : curr->targets) {
o << U32LEB(getBreakIndex(target));
}
o << U32LEB(getBreakIndex(curr->default_));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitCall(Call* curr) {
if (debug) std::cerr << "zz node: Call" << std::endl;
for (auto* operand : curr->operands) {
visitChild(operand);
}
if (!justAddToStack(curr)) {
o << int8_t(BinaryConsts::CallFunction) << U32LEB(parent.getFunctionIndex(curr->target));
}
if (curr->type == unreachable) { // TODO FIXME: this and similar can be removed
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitCallImport(CallImport* curr) {
if (debug) std::cerr << "zz node: CallImport" << std::endl;
for (auto* operand : curr->operands) {
visitChild(operand);
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::CallFunction) << U32LEB(parent.getFunctionIndex(curr->target));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitCallIndirect(CallIndirect* curr) {
if (debug) std::cerr << "zz node: CallIndirect" << std::endl;
for (auto* operand : curr->operands) {
visitChild(operand);
}
visitChild(curr->target);
if (!justAddToStack(curr)) {
o << int8_t(BinaryConsts::CallIndirect)
<< U32LEB(parent.getFunctionTypeIndex(curr->fullType))
<< U32LEB(0); // Reserved flags field
}
if (curr->type == unreachable) {
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitGetLocal(GetLocal* curr) {
if (debug) std::cerr << "zz node: GetLocal " << (o.size() + 1) << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::GetLocal) << U32LEB(mappedLocals[curr->index]);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSetLocal(SetLocal* curr) {
if (debug) std::cerr << "zz node: Set|TeeLocal" << std::endl;
visitChild(curr->value);
if (!justAddToStack(curr)) {
o << int8_t(curr->isTee() ? BinaryConsts::TeeLocal : BinaryConsts::SetLocal) << U32LEB(mappedLocals[curr->index]);
}
if (curr->type == unreachable) {
emitExtraUnreachable();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitGetGlobal(GetGlobal* curr) {
if (debug) std::cerr << "zz node: GetGlobal " << (o.size() + 1) << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::GetGlobal) << U32LEB(parent.getGlobalIndex(curr->name));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSetGlobal(SetGlobal* curr) {
if (debug) std::cerr << "zz node: SetGlobal" << std::endl;
visitChild(curr->value);
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::SetGlobal) << U32LEB(parent.getGlobalIndex(curr->name));
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitLoad(Load* curr) {
if (debug) std::cerr << "zz node: Load" << std::endl;
visitChild(curr->ptr);
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
if (!curr->isAtomic) {
switch (curr->type) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(curr->signed_ ? BinaryConsts::I32LoadMem8S : BinaryConsts::I32LoadMem8U); break;
case 2: o << int8_t(curr->signed_ ? BinaryConsts::I32LoadMem16S : BinaryConsts::I32LoadMem16U); break;
case 4: o << int8_t(BinaryConsts::I32LoadMem); break;
default: abort();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(curr->signed_ ? BinaryConsts::I64LoadMem8S : BinaryConsts::I64LoadMem8U); break;
case 2: o << int8_t(curr->signed_ ? BinaryConsts::I64LoadMem16S : BinaryConsts::I64LoadMem16U); break;
case 4: o << int8_t(curr->signed_ ? BinaryConsts::I64LoadMem32S : BinaryConsts::I64LoadMem32U); break;
case 8: o << int8_t(BinaryConsts::I64LoadMem); break;
default: abort();
}
break;
}
case f32: o << int8_t(BinaryConsts::F32LoadMem); break;
case f64: o << int8_t(BinaryConsts::F64LoadMem); break;
case unreachable: return; // the pointer is unreachable, so we are never reached; just don't emit a load
default: WASM_UNREACHABLE();
}
} else {
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->type) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32AtomicLoad8U); break;
case 2: o << int8_t(BinaryConsts::I32AtomicLoad16U); break;
case 4: o << int8_t(BinaryConsts::I32AtomicLoad); break;
default: WASM_UNREACHABLE();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64AtomicLoad8U); break;
case 2: o << int8_t(BinaryConsts::I64AtomicLoad16U); break;
case 4: o << int8_t(BinaryConsts::I64AtomicLoad32U); break;
case 8: o << int8_t(BinaryConsts::I64AtomicLoad); break;
default: WASM_UNREACHABLE();
}
break;
}
case unreachable: return;
default: WASM_UNREACHABLE();
}
}
emitMemoryAccess(curr->align, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitStore(Store* curr) {
if (debug) std::cerr << "zz node: Store" << std::endl;
visitChild(curr->ptr);
visitChild(curr->value);
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
if (!curr->isAtomic) {
switch (curr->valueType) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32StoreMem8); break;
case 2: o << int8_t(BinaryConsts::I32StoreMem16); break;
case 4: o << int8_t(BinaryConsts::I32StoreMem); break;
default: abort();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64StoreMem8); break;
case 2: o << int8_t(BinaryConsts::I64StoreMem16); break;
case 4: o << int8_t(BinaryConsts::I64StoreMem32); break;
case 8: o << int8_t(BinaryConsts::I64StoreMem); break;
default: abort();
}
break;
}
case f32: o << int8_t(BinaryConsts::F32StoreMem); break;
case f64: o << int8_t(BinaryConsts::F64StoreMem); break;
default: abort();
}
} else {
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->valueType) {
case i32: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32AtomicStore8); break;
case 2: o << int8_t(BinaryConsts::I32AtomicStore16); break;
case 4: o << int8_t(BinaryConsts::I32AtomicStore); break;
default: WASM_UNREACHABLE();
}
break;
}
case i64: {
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64AtomicStore8); break;
case 2: o << int8_t(BinaryConsts::I64AtomicStore16); break;
case 4: o << int8_t(BinaryConsts::I64AtomicStore32); break;
case 8: o << int8_t(BinaryConsts::I64AtomicStore); break;
default: WASM_UNREACHABLE();
}
break;
}
default: WASM_UNREACHABLE();
}
}
emitMemoryAccess(curr->align, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicRMW(AtomicRMW* curr) {
if (debug) std::cerr << "zz node: AtomicRMW" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->value);
if (curr->value->type == unreachable) return;
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix);
#define CASE_FOR_OP(Op) \
case Op: \
switch (curr->type) { \
case i32: \
switch (curr->bytes) { \
case 1: o << int8_t(BinaryConsts::I32AtomicRMW##Op##8U); break; \
case 2: o << int8_t(BinaryConsts::I32AtomicRMW##Op##16U); break; \
case 4: o << int8_t(BinaryConsts::I32AtomicRMW##Op); break; \
default: WASM_UNREACHABLE(); \
} \
break; \
case i64: \
switch (curr->bytes) { \
case 1: o << int8_t(BinaryConsts::I64AtomicRMW##Op##8U); break; \
case 2: o << int8_t(BinaryConsts::I64AtomicRMW##Op##16U); break; \
case 4: o << int8_t(BinaryConsts::I64AtomicRMW##Op##32U); break; \
case 8: o << int8_t(BinaryConsts::I64AtomicRMW##Op); break; \
default: WASM_UNREACHABLE(); \
} \
break; \
default: WASM_UNREACHABLE(); \
} \
break
switch(curr->op) {
CASE_FOR_OP(Add);
CASE_FOR_OP(Sub);
CASE_FOR_OP(And);
CASE_FOR_OP(Or);
CASE_FOR_OP(Xor);
CASE_FOR_OP(Xchg);
default: WASM_UNREACHABLE();
}
#undef CASE_FOR_OP
emitMemoryAccess(curr->bytes, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicCmpxchg(AtomicCmpxchg* curr) {
if (debug) std::cerr << "zz node: AtomicCmpxchg" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->expected);
if (curr->expected->type == unreachable) return;
visitChild(curr->replacement);
if (curr->replacement->type == unreachable) return;
if (curr->type == unreachable) {
// don't even emit it; we don't know the right type
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->type) {
case i32:
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I32AtomicCmpxchg8U); break;
case 2: o << int8_t(BinaryConsts::I32AtomicCmpxchg16U); break;
case 4: o << int8_t(BinaryConsts::I32AtomicCmpxchg); break;
default: WASM_UNREACHABLE();
}
break;
case i64:
switch (curr->bytes) {
case 1: o << int8_t(BinaryConsts::I64AtomicCmpxchg8U); break;
case 2: o << int8_t(BinaryConsts::I64AtomicCmpxchg16U); break;
case 4: o << int8_t(BinaryConsts::I64AtomicCmpxchg32U); break;
case 8: o << int8_t(BinaryConsts::I64AtomicCmpxchg); break;
default: WASM_UNREACHABLE();
}
break;
default: WASM_UNREACHABLE();
}
emitMemoryAccess(curr->bytes, curr->bytes, curr->offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicWait(AtomicWait* curr) {
if (debug) std::cerr << "zz node: AtomicWait" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->expected);
if (curr->expected->type == unreachable) return;
visitChild(curr->timeout);
if (curr->timeout->type == unreachable) return;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix);
switch (curr->expectedType) {
case i32: {
o << int8_t(BinaryConsts::I32AtomicWait);
emitMemoryAccess(4, 4, 0);
break;
}
case i64: {
o << int8_t(BinaryConsts::I64AtomicWait);
emitMemoryAccess(8, 8, 0);
break;
}
default: WASM_UNREACHABLE();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitAtomicWake(AtomicWake* curr) {
if (debug) std::cerr << "zz node: AtomicWake" << std::endl;
visitChild(curr->ptr);
// stop if the rest isn't reachable anyhow
if (curr->ptr->type == unreachable) return;
visitChild(curr->wakeCount);
if (curr->wakeCount->type == unreachable) return;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::AtomicPrefix) << int8_t(BinaryConsts::AtomicWake);
emitMemoryAccess(4, 4, 0);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitConst(Const* curr) {
if (debug) std::cerr << "zz node: Const" << curr << " : " << curr->type << std::endl;
if (justAddToStack(curr)) return;
switch (curr->type) {
case i32: {
o << int8_t(BinaryConsts::I32Const) << S32LEB(curr->value.geti32());
break;
}
case i64: {
o << int8_t(BinaryConsts::I64Const) << S64LEB(curr->value.geti64());
break;
}
case f32: {
o << int8_t(BinaryConsts::F32Const) << curr->value.reinterpreti32();
break;
}
case f64: {
o << int8_t(BinaryConsts::F64Const) << curr->value.reinterpreti64();
break;
}
default: abort();
}
if (debug) std::cerr << "zz const node done.\n";
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitUnary(Unary* curr) {
if (debug) std::cerr << "zz node: Unary" << std::endl;
visitChild(curr->value);
if (curr->type == unreachable) {
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
switch (curr->op) {
case ClzInt32: o << int8_t(BinaryConsts::I32Clz); break;
case CtzInt32: o << int8_t(BinaryConsts::I32Ctz); break;
case PopcntInt32: o << int8_t(BinaryConsts::I32Popcnt); break;
case EqZInt32: o << int8_t(BinaryConsts::I32EqZ); break;
case ClzInt64: o << int8_t(BinaryConsts::I64Clz); break;
case CtzInt64: o << int8_t(BinaryConsts::I64Ctz); break;
case PopcntInt64: o << int8_t(BinaryConsts::I64Popcnt); break;
case EqZInt64: o << int8_t(BinaryConsts::I64EqZ); break;
case NegFloat32: o << int8_t(BinaryConsts::F32Neg); break;
case AbsFloat32: o << int8_t(BinaryConsts::F32Abs); break;
case CeilFloat32: o << int8_t(BinaryConsts::F32Ceil); break;
case FloorFloat32: o << int8_t(BinaryConsts::F32Floor); break;
case TruncFloat32: o << int8_t(BinaryConsts::F32Trunc); break;
case NearestFloat32: o << int8_t(BinaryConsts::F32NearestInt); break;
case SqrtFloat32: o << int8_t(BinaryConsts::F32Sqrt); break;
case NegFloat64: o << int8_t(BinaryConsts::F64Neg); break;
case AbsFloat64: o << int8_t(BinaryConsts::F64Abs); break;
case CeilFloat64: o << int8_t(BinaryConsts::F64Ceil); break;
case FloorFloat64: o << int8_t(BinaryConsts::F64Floor); break;
case TruncFloat64: o << int8_t(BinaryConsts::F64Trunc); break;
case NearestFloat64: o << int8_t(BinaryConsts::F64NearestInt); break;
case SqrtFloat64: o << int8_t(BinaryConsts::F64Sqrt); break;
case ExtendSInt32: o << int8_t(BinaryConsts::I64STruncI32); break;
case ExtendUInt32: o << int8_t(BinaryConsts::I64UTruncI32); break;
case WrapInt64: o << int8_t(BinaryConsts::I32ConvertI64); break;
case TruncUFloat32ToInt32: o << int8_t(BinaryConsts::I32UTruncF32); break;
case TruncUFloat32ToInt64: o << int8_t(BinaryConsts::I64UTruncF32); break;
case TruncSFloat32ToInt32: o << int8_t(BinaryConsts::I32STruncF32); break;
case TruncSFloat32ToInt64: o << int8_t(BinaryConsts::I64STruncF32); break;
case TruncUFloat64ToInt32: o << int8_t(BinaryConsts::I32UTruncF64); break;
case TruncUFloat64ToInt64: o << int8_t(BinaryConsts::I64UTruncF64); break;
case TruncSFloat64ToInt32: o << int8_t(BinaryConsts::I32STruncF64); break;
case TruncSFloat64ToInt64: o << int8_t(BinaryConsts::I64STruncF64); break;
case ConvertUInt32ToFloat32: o << int8_t(BinaryConsts::F32UConvertI32); break;
case ConvertUInt32ToFloat64: o << int8_t(BinaryConsts::F64UConvertI32); break;
case ConvertSInt32ToFloat32: o << int8_t(BinaryConsts::F32SConvertI32); break;
case ConvertSInt32ToFloat64: o << int8_t(BinaryConsts::F64SConvertI32); break;
case ConvertUInt64ToFloat32: o << int8_t(BinaryConsts::F32UConvertI64); break;
case ConvertUInt64ToFloat64: o << int8_t(BinaryConsts::F64UConvertI64); break;
case ConvertSInt64ToFloat32: o << int8_t(BinaryConsts::F32SConvertI64); break;
case ConvertSInt64ToFloat64: o << int8_t(BinaryConsts::F64SConvertI64); break;
case DemoteFloat64: o << int8_t(BinaryConsts::F32ConvertF64); break;
case PromoteFloat32: o << int8_t(BinaryConsts::F64ConvertF32); break;
case ReinterpretFloat32: o << int8_t(BinaryConsts::I32ReinterpretF32); break;
case ReinterpretFloat64: o << int8_t(BinaryConsts::I64ReinterpretF64); break;
case ReinterpretInt32: o << int8_t(BinaryConsts::F32ReinterpretI32); break;
case ReinterpretInt64: o << int8_t(BinaryConsts::F64ReinterpretI64); break;
case ExtendS8Int32: o << int8_t(BinaryConsts::I32ExtendS8); break;
case ExtendS16Int32: o << int8_t(BinaryConsts::I32ExtendS16); break;
case ExtendS8Int64: o << int8_t(BinaryConsts::I64ExtendS8); break;
case ExtendS16Int64: o << int8_t(BinaryConsts::I64ExtendS16); break;
case ExtendS32Int64: o << int8_t(BinaryConsts::I64ExtendS32); break;
default: abort();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitBinary(Binary* curr) {
if (debug) std::cerr << "zz node: Binary" << std::endl;
visitChild(curr->left);
visitChild(curr->right);
if (curr->type == unreachable) {
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
switch (curr->op) {
case AddInt32: o << int8_t(BinaryConsts::I32Add); break;
case SubInt32: o << int8_t(BinaryConsts::I32Sub); break;
case MulInt32: o << int8_t(BinaryConsts::I32Mul); break;
case DivSInt32: o << int8_t(BinaryConsts::I32DivS); break;
case DivUInt32: o << int8_t(BinaryConsts::I32DivU); break;
case RemSInt32: o << int8_t(BinaryConsts::I32RemS); break;
case RemUInt32: o << int8_t(BinaryConsts::I32RemU); break;
case AndInt32: o << int8_t(BinaryConsts::I32And); break;
case OrInt32: o << int8_t(BinaryConsts::I32Or); break;
case XorInt32: o << int8_t(BinaryConsts::I32Xor); break;
case ShlInt32: o << int8_t(BinaryConsts::I32Shl); break;
case ShrUInt32: o << int8_t(BinaryConsts::I32ShrU); break;
case ShrSInt32: o << int8_t(BinaryConsts::I32ShrS); break;
case RotLInt32: o << int8_t(BinaryConsts::I32RotL); break;
case RotRInt32: o << int8_t(BinaryConsts::I32RotR); break;
case EqInt32: o << int8_t(BinaryConsts::I32Eq); break;
case NeInt32: o << int8_t(BinaryConsts::I32Ne); break;
case LtSInt32: o << int8_t(BinaryConsts::I32LtS); break;
case LtUInt32: o << int8_t(BinaryConsts::I32LtU); break;
case LeSInt32: o << int8_t(BinaryConsts::I32LeS); break;
case LeUInt32: o << int8_t(BinaryConsts::I32LeU); break;
case GtSInt32: o << int8_t(BinaryConsts::I32GtS); break;
case GtUInt32: o << int8_t(BinaryConsts::I32GtU); break;
case GeSInt32: o << int8_t(BinaryConsts::I32GeS); break;
case GeUInt32: o << int8_t(BinaryConsts::I32GeU); break;
case AddInt64: o << int8_t(BinaryConsts::I64Add); break;
case SubInt64: o << int8_t(BinaryConsts::I64Sub); break;
case MulInt64: o << int8_t(BinaryConsts::I64Mul); break;
case DivSInt64: o << int8_t(BinaryConsts::I64DivS); break;
case DivUInt64: o << int8_t(BinaryConsts::I64DivU); break;
case RemSInt64: o << int8_t(BinaryConsts::I64RemS); break;
case RemUInt64: o << int8_t(BinaryConsts::I64RemU); break;
case AndInt64: o << int8_t(BinaryConsts::I64And); break;
case OrInt64: o << int8_t(BinaryConsts::I64Or); break;
case XorInt64: o << int8_t(BinaryConsts::I64Xor); break;
case ShlInt64: o << int8_t(BinaryConsts::I64Shl); break;
case ShrUInt64: o << int8_t(BinaryConsts::I64ShrU); break;
case ShrSInt64: o << int8_t(BinaryConsts::I64ShrS); break;
case RotLInt64: o << int8_t(BinaryConsts::I64RotL); break;
case RotRInt64: o << int8_t(BinaryConsts::I64RotR); break;
case EqInt64: o << int8_t(BinaryConsts::I64Eq); break;
case NeInt64: o << int8_t(BinaryConsts::I64Ne); break;
case LtSInt64: o << int8_t(BinaryConsts::I64LtS); break;
case LtUInt64: o << int8_t(BinaryConsts::I64LtU); break;
case LeSInt64: o << int8_t(BinaryConsts::I64LeS); break;
case LeUInt64: o << int8_t(BinaryConsts::I64LeU); break;
case GtSInt64: o << int8_t(BinaryConsts::I64GtS); break;
case GtUInt64: o << int8_t(BinaryConsts::I64GtU); break;
case GeSInt64: o << int8_t(BinaryConsts::I64GeS); break;
case GeUInt64: o << int8_t(BinaryConsts::I64GeU); break;
case AddFloat32: o << int8_t(BinaryConsts::F32Add); break;
case SubFloat32: o << int8_t(BinaryConsts::F32Sub); break;
case MulFloat32: o << int8_t(BinaryConsts::F32Mul); break;
case DivFloat32: o << int8_t(BinaryConsts::F32Div); break;
case CopySignFloat32: o << int8_t(BinaryConsts::F32CopySign);break;
case MinFloat32: o << int8_t(BinaryConsts::F32Min); break;
case MaxFloat32: o << int8_t(BinaryConsts::F32Max); break;
case EqFloat32: o << int8_t(BinaryConsts::F32Eq); break;
case NeFloat32: o << int8_t(BinaryConsts::F32Ne); break;
case LtFloat32: o << int8_t(BinaryConsts::F32Lt); break;
case LeFloat32: o << int8_t(BinaryConsts::F32Le); break;
case GtFloat32: o << int8_t(BinaryConsts::F32Gt); break;
case GeFloat32: o << int8_t(BinaryConsts::F32Ge); break;
case AddFloat64: o << int8_t(BinaryConsts::F64Add); break;
case SubFloat64: o << int8_t(BinaryConsts::F64Sub); break;
case MulFloat64: o << int8_t(BinaryConsts::F64Mul); break;
case DivFloat64: o << int8_t(BinaryConsts::F64Div); break;
case CopySignFloat64: o << int8_t(BinaryConsts::F64CopySign);break;
case MinFloat64: o << int8_t(BinaryConsts::F64Min); break;
case MaxFloat64: o << int8_t(BinaryConsts::F64Max); break;
case EqFloat64: o << int8_t(BinaryConsts::F64Eq); break;
case NeFloat64: o << int8_t(BinaryConsts::F64Ne); break;
case LtFloat64: o << int8_t(BinaryConsts::F64Lt); break;
case LeFloat64: o << int8_t(BinaryConsts::F64Le); break;
case GtFloat64: o << int8_t(BinaryConsts::F64Gt); break;
case GeFloat64: o << int8_t(BinaryConsts::F64Ge); break;
default: abort();
}
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitSelect(Select* curr) {
if (debug) std::cerr << "zz node: Select" << std::endl;
visitChild(curr->ifTrue);
visitChild(curr->ifFalse);
visitChild(curr->condition);
if (curr->type == unreachable) {
emitExtraUnreachable();
return;
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Select);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitReturn(Return* curr) {
if (debug) std::cerr << "zz node: Return" << std::endl;
if (curr->value) {
visitChild(curr->value);
}
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Return);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitHost(Host* curr) {
if (debug) std::cerr << "zz node: Host" << std::endl;
switch (curr->op) {
case CurrentMemory: {
break;
}
case GrowMemory: {
visitChild(curr->operands[0]);
break;
}
default: WASM_UNREACHABLE();
}
if (justAddToStack(curr)) return;
switch (curr->op) {
case CurrentMemory: {
o << int8_t(BinaryConsts::CurrentMemory);
break;
}
case GrowMemory: {
o << int8_t(BinaryConsts::GrowMemory);
break;
}
default: WASM_UNREACHABLE();
}
o << U32LEB(0); // Reserved flags field
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitNop(Nop* curr) {
if (debug) std::cerr << "zz node: Nop" << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Nop);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitUnreachable(Unreachable* curr) {
if (debug) std::cerr << "zz node: Unreachable" << std::endl;
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Unreachable);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::visitDrop(Drop* curr) {
if (debug) std::cerr << "zz node: Drop" << std::endl;
visitChild(curr->value);
if (justAddToStack(curr)) return;
o << int8_t(BinaryConsts::Drop);
}
template<StackWriterMode Mode, typename Parent>
int32_t StackWriter<Mode, Parent>::getBreakIndex(Name name) { // -1 if not found
for (int i = breakStack.size() - 1; i >= 0; i--) {
if (breakStack[i] == name) {
return breakStack.size() - 1 - i;
}
}
WASM_UNREACHABLE();
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::emitMemoryAccess(size_t alignment, size_t bytes, uint32_t offset) {
o << U32LEB(Log2(alignment ? alignment : bytes));
o << U32LEB(offset);
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::emitExtraUnreachable() {
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(Builder(allocator).makeUnreachable()));
} else if (Mode == StackWriterMode::Binaryen2Binary) {
o << int8_t(BinaryConsts::Unreachable);
}
}
template<StackWriterMode Mode, typename Parent>
bool StackWriter<Mode, Parent>::justAddToStack(Expression* curr) {
if (Mode == StackWriterMode::Binaryen2Stack) {
stackIR.push_back(makeStackInst(curr));
return true;
}
return false;
}
template<StackWriterMode Mode, typename Parent>
void StackWriter<Mode, Parent>::finishFunctionBody() {
o << int8_t(BinaryConsts::End);
}
template<StackWriterMode Mode, typename Parent>
StackInst* StackWriter<Mode, Parent>::makeStackInst(StackInst::Op op, Expression* origin) {
auto* ret = allocator.alloc<StackInst>();
ret->op = op;
ret->origin = origin;
auto stackType = origin->type;
if (origin->is<Block>() || origin->is<Loop>() || origin->is<If>()) {
if (stackType == unreachable) {
// There are no unreachable blocks, loops, or ifs. we emit extra unreachables
// to fix that up, so that they are valid as having none type.
stackType = none;
} else if (op != StackInst::BlockEnd &&
op != StackInst::IfEnd &&
op != StackInst::LoopEnd) {
// If a concrete type is returned, we mark the end of the construct has
// having that type (as it is pushed to the value stack at that point),
// other parts are marked as none).
stackType = none;
}
}
ret->type = stackType;
return ret;
}
} // namespace wasm
#endif // wasm_stack_h
| 39.1725 | 126 | 0.657221 | [
"vector"
] |
ffffd12f76abb005a0c99cb9dfdce98d246541f9 | 120,215 | h | C | src/cpp/SPL/Runtime/Function/BuiltinCollectionFunctions.h | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 10 | 2021-02-19T20:19:24.000Z | 2021-09-16T05:11:50.000Z | src/cpp/SPL/Runtime/Function/BuiltinCollectionFunctions.h | xguerin/openstreams | 7000370b81a7f8778db283b2ba9f9ead984b7439 | [
"Apache-2.0"
] | 7 | 2021-02-20T01:17:12.000Z | 2021-06-08T14:56:34.000Z | src/cpp/SPL/Runtime/Function/BuiltinCollectionFunctions.h | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 4 | 2021-02-19T18:43:10.000Z | 2022-02-23T14:18:16.000Z | /*
* Copyright 2021 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SPL_RUNTIME_FUNCTION_BUILTIN_COLLECTION_FUNCTIONS_H
#define SPL_RUNTIME_FUNCTION_BUILTIN_COLLECTION_FUNCTIONS_H
/*!
* \file CollectionFunctions.h \brief Definitions of C++ counterparts of %SPL native functions for
* operations on collection types.
*/
#ifndef DOXYGEN_SKIP_FOR_USERS
#include <SPL/Runtime/Common/ApplicationRuntimeMessage.h>
#endif /* DOXYGEN_SKIP_FOR_USERS */
#include <SPL/Runtime/Type/SPLType.h>
#ifndef DOXYGEN_SKIP_FOR_USERS
#include <SPL/Runtime/Utility/LogTraceMessage.h>
#include <functional>
#endif /* DOXYGEN_SKIP_FOR_USERS */
/*
* Builtin SPL Collection functions
*/
/// @splcppns SPL::Functions::Collections
/// @spldir collection
/// @splname SPL-Collection-Functions
/*!
* \namespace SPL::Functions::Collections \brief C++ counterparts of %SPL native
* functions that deal with operations on collection types
*/
namespace SPL {
namespace Functions {
namespace Collections {
#ifndef DOXYGEN_SKIP_FOR_USERS
template<class T = const SPL::list<SPL::int32>, class E = SPL::int32>
struct _cachedMembership
{
static const size_t BSIZE = 16;
inline _cachedMembership(T& idxs)
: map()
, raw(idxs)
{
if (idxs.size() > BSIZE) {
typedef typename T::const_iterator itrT;
for (itrT it = idxs.begin(); it != idxs.end(); ++it) {
map.insert(*it);
}
}
}
boolean has(E idx)
{
if (raw.size() > BSIZE) {
return (map.count(idx) > 0);
} else {
for (size_t i = 0, iu = raw.size(); i < iu; ++i) {
if (raw[i] == idx) {
return true;
}
}
return false;
}
}
std::tr1::unordered_set<E> map;
T& raw;
};
#endif /* DOXYGEN_SKIP_FOR_USERS */
/// Get the size of a list.
/// @param values Input list.
/// @return Number of items in the list.
/// @splnative <collection T> public int32 size (T values)
/// @spleval $name = "size"; $ret = "uint32"; $numArgs = 1; $arg[0] = 'listSet<@primitive@>'
/// @splnative public int32 size (blob values)
inline SPL::int32 size(const SPL::List& values)
{
return values.getSize();
}
/// Get the size of a map.
/// @param values Input map.
/// @return Number of items in the map.
inline SPL::int32 size(const SPL::Map& values)
{
return values.getSize();
}
/// Get the size of a set.
/// @param values Input set.
/// @return Number of items in the set.
inline SPL::int32 size(const SPL::Set& values)
{
return values.getSize();
}
/// Get the size of a blob.
/// @param values Input blob.
/// @return Number of bytes in the blob.
inline SPL::int32 size(const SPL::blob& values)
{
return values.getSize();
}
/// Get the size of a blob.
/// @param b Input blob.
/// @return Number of bytes in the blob.
/// @splnative public uint64 blobSize (blob b)
inline SPL::uint64 blobSize(const SPL::blob& b)
{
return b.getSize();
}
/// Clear (empty) a list.
/// @param values Input list.
/// @splnative <collection T> public void clearM (mutable T values)
/// @splnative public void clearM (mutable blob values)
inline void clearM(SPL::List& values)
{
values.removeAllElements();
}
/// Clear (empty) a map.
/// @param values Input map.
inline void clearM(SPL::Map& values)
{
values.removeAllElements();
}
/// Clear (empty) a set.
/// @param values Input set.
inline void clearM(SPL::Set& values)
{
values.removeAllElements();
}
/// Clear (empty) a blob.
/// @param values Input blob.
inline void clearM(SPL::blob& values)
{
values.clear();
}
/// Compute the distinct count of a list.
/// @param values List of input values.
/// @return Number of distinct values in the list.
/// @splnative <any T> public int32 countDistinct (list<T> values)
/// @spleval $name = "countDistinct"; $ret = "int32"; $numArgs = 1; $arg[0] = 'list<@primitive@>'
/// @splnative <any T>[N] public int32 countDistinct (list<T>[N] values)
template<class T>
inline SPL::int32 countDistinct(const SPL::list<T>& values)
{
std::tr1::unordered_set<T> vmap;
for (size_t i = 0, ui = values.size(); i < ui; ++i) {
vmap.insert(values[i]);
}
return vmap.size();
}
/// Compute the distinct count of a list.
/// @param values List of input values.
/// @return Number of distinct values in the list.
template<class T, int32_t N>
inline SPL::int32 countDistinct(const SPL::blist<T, N>& values)
{
std::tr1::unordered_set<T> vmap;
for (size_t i = 0, ui = values.size(); i < ui; ++i) {
vmap.insert(values[i]);
}
return vmap.size();
}
/// Compute the union of two sets.
/// @param a First set (of type SPL::set or SPL::bset).
/// @param b Second set (of type SPL::set or SPL::bset).
/// @return A new set containing the elements in either a and b.
/// @splnative <set T> public T setUnion (T a, T b)
/// @spleval $name = "setUnion"; $ret = 'set<@primitive@>'; $numArgs = 2; $arg[0] = 'set<@primitive@>'; $arg[1] = 'set<@primitive@>'
/// works on sets & bsets of any type
template<class T>
inline T setUnion(const T& a, const T& b)
{
T res = a;
typename T::const_iterator it;
for (it = b.begin(); it != b.end(); it++) {
res.insert(*it);
}
return res;
}
/// Compute the intersection of two sets.
/// @param a First set (of type SPL::set or SPL::bset).
/// @param b Second set (of type SPL::set or SPL::bset).
/// @return A new set containing the elements in both a and b.
/// @splnative <set T> public T setIntersection (T a, T b)
/// @spleval $name = "setIntersection"; $ret = 'set<@primitive@>'; $numArgs = 2; $arg[0] = 'set<@primitive@>'; $arg[1] = 'set<@primitive@>'
/// works on sets & bsets of any type
template<class T>
inline T setIntersection(const T& a, const T& b)
{
T res;
typename T::const_iterator it;
for (it = a.begin(); it != a.end(); it++) {
if (b.count(*it) != 0) {
res.insert(*it);
}
}
return res;
}
/// Compute the difference of two sets.
/// @param a First set (of type SPL::set or SPL::bset).
/// @param b Second set (of type SPL::set or SPL::bset).
/// @return A new set containing the elements in a that are not in b.
/// @splnative <set T> public T setDifference (T a, T b)
/// @spleval $name = "setDifference"; $ret = 'set<@primitive@>'; $numArgs = 2; $arg[0] = 'set<@primitive@>'; $arg[1] = 'set<@primitive@>'
/// works on sets & bsets of any type
template<class T>
inline T setDifference(const T& a, const T& b)
{
T res;
typename T::const_iterator it;
for (it = a.begin(); it != a.end(); it++) {
if (b.count(*it) == 0) {
res.insert(*it);
}
}
return res;
}
// Sequences
/// Make a sequence.
/// @param val Input value.
/// @param cnt Sequence length.
/// @return A list of values that start with the input value and
/// increase by one at each step.
/// @splnative <numeric T> public list<T> makeSequence (T val, int32 cnt)
template<class T>
inline SPL::list<T> makeSequence(const T& val, const SPL::int32 cnt)
{
SPL::list<T> res;
res.reserve(cnt);
for (int32_t i = 0; i < cnt; ++i) {
res.push_back(val + static_cast<T>(i));
}
return res;
}
/// Make a sequence.
/// @param val Input value.
/// @param cnt Sequence length.
/// @param step Step increase.
/// @return A list of values that start with the input value val and
/// increase by a given step.
/// @splnative <numeric T> public list<T> makeSequence (T val, int32 cnt, T step)
template<class T>
inline SPL::list<T> makeSequence(const T& val, const SPL::int32 cnt, const T& step)
{
SPL::list<T> res;
T mval = val;
res.reserve(cnt);
for (int32_t i = 0; i < cnt; ++i) {
res.push_back(mval);
mval = mval + step;
}
return res;
}
/// Make a sequence.
/// @param val Input value.
/// @param cnt Sequence length.
/// @return A sequence of strings, where each string starts with the input value
/// and has an index value appended at the end (index starts from 0).
/// @splnative <string T> public list<T> makeSequence (T val, int32 cnt)
template<>
inline SPL::list<SPL::rstring> makeSequence<SPL::rstring>(const SPL::rstring& val,
const SPL::int32 cnt)
{
SPL::list<SPL::rstring> res;
res.reserve(cnt);
for (int32_t i = 0; i < cnt; ++i) {
std::stringstream s;
s.imbue(std::locale::classic());
s << i;
res.push_back(val + SPL::rstring(s.str()));
}
return res;
}
/// Make a sequence.
/// @param val Input value.
/// @param cnt Sequence length.
/// @return A sequence of strings, where each string starts with the input value
/// and has an index value appended at the end (index starts from 0).
template<>
inline SPL::list<SPL::ustring> makeSequence<SPL::ustring>(const SPL::ustring& val,
const SPL::int32 cnt)
{
SPL::list<SPL::ustring> res;
res.reserve(cnt);
for (int32_t i = 0; i < cnt; ++i) {
std::stringstream s;
s.imbue(std::locale::classic());
s << i;
res.push_back(val + SPL::ustring::fromUTF8(s.str()));
}
return res;
}
/// Make a sequence.
/// @param val Input value.
/// @param cnt Sequence length.
/// @return A sequence of strings, where each string starts with the input value
/// and has an index value appended at the end (index starts from 0).
template<int32_t msize>
inline SPL::list<SPL::bstring<msize> > makeSequence(const SPL::bstring<msize>& val,
const SPL::int32 cnt)
{
SPL::list<SPL::ustring> res;
res.reserve(cnt);
for (int32_t i = 0; i < cnt; ++i) {
std::stringstream s;
s.imbue(std::locale::classic());
s << i;
res.push_back(val + s.str());
}
return res;
}
// Ranges
/// Return a list of values in the range from 0 to limit-1
/// @param limit Upper bound of range to be returned, exclusive.
/// @return A list of int32 values from 0 to limit-1.
/// @note An empty list is returned if limit <= 0.
/// @splnote This is optimized by the SPL compiler to avoid creating the list in: `for (int32 i in range(u))`.
/// @splnative public list<int32> range (int32 limit)
inline SPL::list<SPL::int32> range(SPL::int32 limit)
{
SPL::list<SPL::int32> res;
if (limit > 0) {
res.reserve(limit);
for (int32_t i = 0; i < limit; i++) {
res.push_back(i);
}
}
return res;
}
/// Return a list of values in the range from start to limit-1
/// @param start Lower bound of range to be returned.
/// @param limit Upper bound of range to be returned, exclusive.
/// @return A list of int32 values from start to limit-1.
/// @note An empty list is returned if limit <= start.
/// @splnote This is optimized by the SPL compiler to avoid creating the list in: `for (int32 i in range(l,u))`.
/// @splnative public list<int32> range (int32 start, int32 limit)
inline SPL::list<SPL::int32> range(SPL::int32 start, SPL::int32 limit)
{
SPL::list<SPL::int32> res;
if (start < limit) {
res.reserve(limit - start);
for (int32_t i = start; i < limit; i++) {
res.push_back(i);
}
}
return res;
}
/// Return a list of values in the range from start to limit-1, with an increment of step
/// @pre step != 0
/// @param start Lower bound of range to be returned.
/// @param limit Upper bound of range to be returned, exclusive.
/// @param step Increment from start to limit.
/// @return A list of int32 values from start to limit-1 incrementing by step.
/// @note An empty list is returned if limit <= start for positive step or limit >= start for negative step.
/// @splnote This is optimized by the SPL compiler to avoid creating the list in: `for (int32 i in range(l,u,s))`.
/// @throws SPLRuntimeInvalidArgumentException If step is zero.
/// @splnative public list<int32> range (int32 start, int32 limit, int32 step)
inline SPL::list<SPL::int32> range(SPL::int32 start, SPL::int32 limit, SPL::int32 step)
{
if (step == 0) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_RANGE_STEP_ZERO, SPL_FUNC_DBG);
}
SPL::list<SPL::int32> res;
if (step > 0) {
if (start < limit) {
res.reserve((limit - start) / step + 1);
for (int32_t i = start; i < limit; i += step) {
res.push_back(i);
}
}
} else {
if (start > limit) {
res.reserve((start - limit) / -step + 1);
for (int32_t i = start; i > limit; i += step) {
res.push_back(i);
}
}
}
return res;
}
/// Return a list of values in the range from 0 to size(l)-1
/// @param l List to be used for index generation.
/// @return A list of int32 values from 0 to size(l)-1.
/// @splnote This is optimized by the SPL compiler to avoid creating the list in: `for (int32 i in range(myList))`.
/// @splnative <list T> public list<int32> range (T l)
template<class T>
inline SPL::list<SPL::int32> range(SPL::list<T> l)
{
SPL::list<SPL::int32> res;
int limit = l.size();
if (limit > 0) {
res.reserve(limit);
for (int32_t i = 0; i < limit; i++) {
res.push_back(i);
}
}
return res;
}
/// Return a list of values in the range from 0 to size(l)-1
/// @param l List to be used for index generation.
/// @return A list of int32 values from 0 to size(l)-1.
template<class T, int32_t N>
inline SPL::list<SPL::int32> range(SPL::blist<T, N> l)
{
SPL::list<SPL::int32> res;
int limit = l.size();
if (limit > 0) {
res.reserve(limit);
for (int32_t i = 0; i < limit; i++) {
res.push_back(i);
}
}
return res;
}
// Map Functions
/// Insert an element into a map.
/// @param values Input map.
/// @param key New key value.
/// @param value New value.
/// @return New map with an element mapping the key to the value inserted.
/// @splnative <any K, any V> public map<K,V> insert (map<K,V> values, K key, V value)
/// @splnative <any K, any V>[N] public map<K,V>[N] insert (map<K,V>[N] values, K key, V value)
template<class K, class V>
inline SPL::map<K, V> insert(const SPL::map<K, V>& values, const K& key, const V& value)
{
SPL::map<K, V> res(values);
std::pair<typename SPL::map<K, V>::iterator, bool> r = res.insert(std::make_pair(key, value));
if (!r.second) {
r.first->second = value;
}
return res;
}
/// Insert an element into a map.
/// @param values Input map.
/// @param key New key value.
/// @param value New value.
/// @return New map with an element mapping the key to the value inserted.
template<class K, class V, int32_t N>
inline SPL::bmap<K, V, N> insert(const SPL::bmap<K, V, N>& values, const K& key, const V& value)
{
SPL::bmap<K, V, N> res(values);
std::pair<typename SPL::bmap<K, V, N>::iterator, bool> r =
res.insert(std::make_pair(key, value));
if (!r.second) {
r.first->second = value;
}
return res;
}
/// Insert an element into a map (mutating version).
/// @param values Input map.
/// @param key New key value.
/// @param value New value.
/// @splnative <any K, any V> public void insertM (mutable map<K,V> values, K key, V value)
/// @splnative <any K, any V>[N] public void insertM (mutable map<K,V>[N] values, K key, V value)
template<class K, class V>
inline void insertM(SPL::map<K, V>& values, const K& key, const V& value)
{
std::pair<typename SPL::map<K, V>::iterator, bool> r =
values.insert(std::make_pair(key, value));
if (!r.second) {
r.first->second = value;
}
}
/// Insert an element into a map (mutating version).
/// @param values Input map.
/// @param key New key value.
/// @param value New value.
template<class K, class V, int32_t N>
inline void insertM(SPL::bmap<K, V, N>& values, const K& key, const V& value)
{
std::pair<typename SPL::bmap<K, V, N>::iterator, bool> r =
values.insert(std::make_pair(key, value));
if (!r.second) {
r.first->second = value;
}
}
/// Remove an element from a map.
/// @param values Input map.
/// @param key Key of value to be removed.
/// @return A copy of the map with the key removed.
/// @splnative <any K, any V> public map<K,V> remove (map<K,V> values, K key)
/// @splnative <any K, any V>[N] public map<K,V>[N] remove (map<K,V>[N] values, K key)
template<class K, class V>
inline SPL::map<K, V> remove(const SPL::map<K, V>& values, const K& key)
{
SPL::map<K, V> res(values);
typename SPL::map<K, V>::iterator it = res.find(key);
if (it != res.end()) {
res.erase(it);
}
return res;
}
/// Remove an element from a map.
/// @param values Input map.
/// @param key Key of value to be removed.
/// @return A copy of the map with the key removed.
template<class K, class V, int32_t N>
inline SPL::bmap<K, V, N> remove(const SPL::bmap<K, V, N>& values, const K& key)
{
SPL::bmap<K, V, N> res(values);
typename SPL::bmap<K, V, N>::iterator it = res.find(key);
if (it != res.end()) {
res.erase(it);
}
return res;
}
/// Remove an element from a map (mutating version).
/// @param values Input map.
/// @param key Key of value to be removed.
/// @splnative <any K, any V> public void removeM (mutable map<K,V> values, K key)
/// @splnative <any K, any V>[N] public void removeM (mutable map<K,V>[N] values, K key)
template<class K, class V>
inline void removeM(SPL::map<K, V>& values, const K& key)
{
typename SPL::map<K, V>::iterator it = values.find(key);
if (it != values.end()) {
values.erase(it);
}
}
/// Remove an element from a map (mutating version).
/// @param values Input map.
/// @param key Key of value to be removed.
template<class K, class V, int32_t N>
inline void removeM(SPL::bmap<K, V, N>& values, const K& key)
{
typename SPL::bmap<K, V, N>::iterator it = values.find(key);
if (it != values.end()) {
values.erase(it);
}
}
// List Functions
/// Find the matching values in a list, given a value to search for.
/// @param values List of values.
/// @param item Value to be found.
/// @return List of indexes at each of which the input list has a matching item.
/// @splnative <any T> public list<int32> find (list<T> values, T item)
/// @spleval $name = "find"; $ret = 'list<int32>'; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = '@primitive@'
/// @splnative <any T>[N] public list<int32> find (list<T>[N] values, T item)
template<class T>
inline SPL::list<SPL::int32> find(const SPL::list<T>& values, const T& item)
{
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (values[i] == item) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the matching values in a list, given a value to search for.
/// @param values List of values.
/// @param item Value to be found.
/// @return List of indexes at each of which the input list has a matching item.
template<class T, int32_t N>
inline SPL::list<SPL::int32> find(const SPL::blist<T, N>& values, const T& item)
{
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (values[i] == item) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a matching item.
/// @splnative <any T> public list<int32> findOf (list<T> values, list<T> items)
/// @spleval $name = "findOf"; $ret = 'list<int32>'; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'
/// @splnative <any T>[N] public list<int32> findOf (list<T> values, list<T>[N] items)
/// @splnative <any T>[N] public list<int32> findOf (list<T>[N] values, list<T> items)
/// @splnative <any T>[N,M] public list<int32> findOf (list<T>[N] values, list<T>[M] items)
template<class T>
inline SPL::list<SPL::int32> findOf(const SPL::list<T>& values, const SPL::list<T>& items)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a matching item.
template<class T, int32_t N>
inline SPL::list<SPL::int32> findOf(const SPL::list<T>& values, const SPL::blist<T, N>& items)
{
_cachedMembership<const SPL::blist<T, N>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a matching item.
template<class T, int32_t N>
inline SPL::list<SPL::int32> findOf(const SPL::blist<T, N>& values, const SPL::list<T>& items)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a matching item.
template<class T, int32_t N, int32_t M>
inline SPL::list<SPL::int32> findOf(const SPL::blist<T, N>& values, const SPL::blist<T, M>& items)
{
_cachedMembership<const SPL::blist<T, M>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the non-matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a non-matching item.
/// @splnative <any T> public list<int32> findNotOf (list<T> values, list<T> items)
/// @spleval $name = "findNotOf"; $ret = 'list<int32>'; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'
/// @splnative <any T>[N] public list<int32> findNotOf (list<T> values, list<T>[N] items)
/// @splnative <any T>[N] public list<int32> findNotOf (list<T>[N] values, list<T> items)
/// @splnative <any T>[N,M] public list<int32> findNotOf (list<T>[N] values, list<T>[M] items)
template<class T>
inline SPL::list<SPL::int32> findNotOf(const SPL::list<T>& values, const SPL::list<T>& items)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the non-matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a non-matching item.
template<class T, int32_t N>
inline SPL::list<SPL::int32> findNotOf(const SPL::list<T>& values, const SPL::blist<T, N>& items)
{
_cachedMembership<const SPL::blist<T, N>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the non-matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a non-matching item.
template<class T, int32_t N>
inline SPL::list<SPL::int32> findNotOf(const SPL::blist<T, N>& values, const SPL::list<T>& items)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the non-matching values in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @return List of indexes at each of which the input list has a non-matching item.
template<class T, int32_t N, int32_t M>
inline SPL::list<SPL::int32> findNotOf(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& items)
{
_cachedMembership<const SPL::blist<T, M>, T> cache(items);
SPL::list<SPL::int32> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
res.push_back(static_cast<SPL::int32>(i));
}
}
return res;
}
/// Find the first occurrence of a matching value in a list, given a value to search for.
/// @param values List of input values.
/// @param item Search value.
/// @param sidx Start index of the search.
/// @return Index of the first match (-1, if no match).
/// @splnative <any T> public int32 findFirst (list<T> values, T item, int32 sidx)
/// @spleval $name = "findFirst"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = '@primitive@'; $arg[2] = "int32"
/// @splnative <any T>[N] public int32 findFirst (list<T>[N] values, T item, int32 sidx)
template<class T>
inline SPL::int32 findFirst(const SPL::list<T>& values, const T& item, const SPL::int32 sidx = 0)
{
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (values[i] == item) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// @spldesc Find the first occurrence of a matching value in a list, given a value to search for, starting at index 0.
/// @splparam values List of input values.
/// @splparam item Search value.
/// @splreturn Index of the first match (-1, if no match).
/// @spleval $name = "findFirst"; $ret = "int32"; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = '@primitive@';
/// @splnative <any T> public int32 findFirst (list<T> values, T item)
/// Find the first occurrence of a matching value in a list, given a value to search for.
/// @param values List of input values.
/// @param item Search value.
/// @param sidx Start index of the search.
/// @return Index of the first match (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findFirst(const SPL::blist<T, N>& values,
const T& item,
const SPL::int32 sidx = 0)
{
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (values[i] == item) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// @spldesc Find the first occurrence of a matching value in a list, given a value to search for, starting at index 0.
/// @splparam values List of input values.
/// @splparam item Search value.
/// @splreturn Index of the first match (-1, if no match).
/// @splnative <any T>[N] public int32 findFirst (list<T>[N] values, T item)
/// Compare two lists in lexicographical order.
///
/// A list is less if a value at the same index in both lists is less,
/// or if the list has matching values, but is shorter than the other list.
/// @param values1 First list of input values.
/// @param values2 Second list of input values.
/// @return -1 if the first list is less that the second, 0 if they are equal,
/// and 1 if the first list is greater than the second.
/// @splnative <ordered T> public int32 lexicographicalCompare(list<T> values1, list<T> values2)
/// @spleval $name = "lexicographicalCompare"; $ret = "int32"; $numArgs = 2; $arg[0] = 'list<@ordered@>'; $arg[1] = 'list<@ordered@>'
/// @splnative <ordered T>[N,M] public int32 lexicographicalCompare(list<T>[N] values1, list<T>[M] values2)
template<class T>
inline SPL::int32 lexicographicalCompare(const SPL::list<T>& values1, const SPL::list<T>& values2)
{
typename SPL::list<T>::const_iterator first1 = values1.begin(), last1 = values1.end(),
first2 = values2.begin(), last2 = values2.end();
for (; first1 != last1 && first2 != last2; ++first1, ++first2) {
if (*first1 < *first2) {
return -1;
}
if (*first2 < *first1) {
return 1;
}
}
if (first1 == last1) {
if (first2 != last2) {
return -1;
} else {
return 0;
}
} else {
return 1;
}
}
/// Compare two lists in lexicographical order.
///
/// A list is less if a value at the same index in both lists is less,
/// or if the list has matching values, but is shorter than the other list.
/// @param values1 First list of input values.
/// @param values2 Second list of input values.
/// @return -1 if the first list is less that the second, 0 if they are equal,
/// and 1 if the first list is greater than the second.
template<class T, int32_t N, int32_t M>
inline SPL::int32 lexicographicalCompare(const SPL::blist<T, N>& values1,
const SPL::blist<T, M>& values2)
{
typename SPL::blist<T, N>::const_iterator first1 = values1.begin(), last1 = values1.end();
typename SPL::blist<T, M>::const_iterator first2 = values2.begin(), last2 = values2.end();
for (; first1 != last1 && first2 != last2; ++first1, ++first2) {
if (*first1 < *first2) {
return -1;
}
if (*first2 < *first1) {
return 1;
}
}
if (first1 == last1) {
if (first2 != last2) {
return -1;
} else {
return 0;
}
} else {
return 1;
}
}
/// Find the first occurrence of a matching sequence of values in a list.
/// @param values List of input values to be searched.
/// @param items List containing a sequence of values to be matched as a sequence.
/// @param sidx Index of the first item to be considered in the list to be searched.
/// @return Index of the first item of the first match in the list to be searched (-1, if no match).
/// @splnative <any T> public int32 findFirst(list<T> values, list<T> items, int32 sidx)
/// @spleval $name = "findFirst"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'; $arg[2] = "int32"
/// @splnative <any T>[N,M] public int32 findFirst (list<T>[N] values, list<T>[M] items, int32 sidx)
template<class T>
inline SPL::int32 findFirst(const SPL::list<T>& values,
const SPL::list<T>& items,
const SPL::int32 sidx = 0)
{
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
if (sidx >= (int)values.size()) {
return -1;
}
typename SPL::list<T>::const_iterator it =
std::search(values.begin() + start, values.end(), items.begin(), items.end());
if (it != values.end()) {
return std::distance(values.begin(), it);
}
return -1;
}
/// @spldesc Find the first occurrence of a matching sequence of values in a list, starting at index 0.
/// @splparam values List of input values to be searched.
/// @splparam items List containing a sequence of values to be matched as a sequence.
/// @splreturn Index of the first item of the first match in the list to be searched (-1, if no match).
/// @splnative <any T> public int32 findFirst(list<T> values, list<T> items)
/// @spleval $name = "findFirst"; $ret = "int32"; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>';
/// @splnative <any T>[N,M] public int32 findFirst (list<T>[N] values, list<T>[M] items)
/// Find the first occurrence of a matching sequence of values in a list.
/// @param values List of input values to be searched.
/// @param items List containing a sequence of values to be matched as a sequence.
/// @param sidx Index of the first item to be considered in the list to be searched.
/// @return Index of the first item of the first match in the list to be searched (-1, if no match).
template<class T, int32_t N, int32_t M>
inline SPL::int32 findFirst(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& items,
const SPL::int32 sidx = 0)
{
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
if (sidx >= values.size()) {
return -1;
}
typename SPL::blist<T, N>::const_iterator it =
std::search(values.begin() + start, values.end(), items.begin(), items.end());
if (it != values.end()) {
return std::distance(values.begin(), it);
}
return -1;
}
/// Find the last occurrence of a matching sequence of values in a list.
/// @param values List of input values to be searched.
/// @param items List containing a sequence of values to be matched as a sequence.
/// @param lidx Index of the last item to be considered in the list to be searched.
/// @return Index of the first item of the last match in the list to be searched (-1, if no match).
/// @splnative <any T> public int32 findLast (list<T> values, list<T> items, int32 lidx)
/// @spleval $name = "findLast"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'; $arg[2] = "int32"
/// @splnative <any T>[N,M] public int32 findLast (list<T>[N] values, list<T>[M] items, int32 lidx)
template<class T>
inline SPL::int32 findLast(const SPL::list<T>& values,
const SPL::list<T>& items,
const SPL::int32 lidx)
{
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
typename SPL::list<T>::const_iterator it =
std::find_end(values.begin(), values.begin() + last + 1, items.begin(), items.end());
if (it != (values.begin() + last + 1)) {
return std::distance(values.begin(), it);
}
return -1;
}
/// Find the last occurrence of a matching sequence of values in a list.
/// @param values List of input values to be searched.
/// @param items List containing a sequence of values to be matched as a sequence.
/// @param lidx Index of the last item to be considered in the list to be searched.
/// @return Index of the first item of the last match in the list to be searched (-1, if no match).
template<class T, int32_t N, int32_t M>
inline SPL::int32 findLast(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& items,
const SPL::int32 lidx)
{
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
typename SPL::blist<T, N>::const_iterator it =
std::find_end(values.begin(), values.begin() + last + 1, items.begin(), items.end());
if (it != (values.begin() + last + 1)) {
return std::distance(values.begin(), it);
}
return -1;
}
/// Find the last occurrence of a matching value in a list, given a value to search for.
/// @param values List of input values.
/// @param item Search value.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last match (-1, if no match).
/// @splnative <any T> public int32 findLast (list<T> values, T item, int32 lidx)
/// @spleval $name = "findLast"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = '@primitive@'; $arg[2] = "int32"
/// @splnative <any T>[N] public int32 findLast (list<T>[N] values, T item, int32 lidx)
template<class T>
inline SPL::int32 findLast(const SPL::list<T>& values, const T& item, const SPL::int32 lidx)
{
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (values[i] == item) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the last occurrence of a matching value in a list, given a value to search for.
/// @param values List of input values.
/// @param item Search value.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last match (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findLast(const SPL::blist<T, N>& values, const T& item, const SPL::int32 lidx)
{
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (values[i] == item) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the first occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that matches one of the values in the search list (-1, if no match).
/// @splnative <any T> public int32 findFirstOf (list<T> values, list<T> items, int32 sidx)
/// @spleval $name = "findFirstOf"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'; $arg[2] = "int32"
/// @splnative <any T>[N] public int32 findFirstOf (list<T>[N] values, list<T> items, int32 sidx)
/// @splnative <any T>[N] public int32 findFirstOf (list<T> values, list<T>[N] items, int32 sidx)
/// @splnative <any T>[N,M] public int32 findFirstOf (list<T>[N] values, list<T>[M] items, int32 sidx)
template<class T>
inline SPL::int32 findFirstOf(const SPL::list<T>& values,
const SPL::list<T>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// @spldesc Find the first occurrence of a matching value in a list, given a list of values to search for, starting at index 0.
/// @splparam values List of input values.
/// @splparam items List of search values.
/// @splreturn Index of the first value that matches one of the values in the search list (-1, if no match).
/// @splnative <any T> public int32 findFirstOf (list<T> values, list<T> items)
/// @spleval $name = "findFirstOf"; $ret = "int32"; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>';
/// @splnative <any T>[N] public int32 findFirstOf (list<T>[N] values, list<T> items)
/// @splnative <any T>[N] public int32 findFirstOf (list<T> values, list<T>[N] items)
/// @splnative <any T>[N,M] public int32 findFirstOf (list<T>[N] values, list<T>[M] items)
/// Find the first occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that matches one of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findFirstOf(const SPL::blist<T, N>& values,
const SPL::list<T>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// Find the first occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that matches one of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findFirstOf(const SPL::list<T>& values,
const SPL::blist<T, N>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::blist<T, N>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// Find the first occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that matches one of the values in the search list (-1, if no match).
template<class T, int32_t N, int32_t M>
inline SPL::int32 findFirstOf(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::blist<T, M>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// Find the last occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that matches one of the values in the search list (-1, if no match).
/// @splnative <any T> public int32 findLastOf (list<T> values, list<T> items, int32 lidx)
/// @spleval $name = "findLastOf"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'; $arg[2] = "int32"
/// @splnative <any T>[N] public int32 findLastOf (list<T>[N] values, list<T> items, int32 lidx)
/// @splnative <any T>[N] public int32 findLastOf (list<T> values, list<T>[N] items, int32 lidx)
/// @splnative <any T>[N,M] public int32 findLastOf (list<T>[N] values, list<T>[M] items, int32 lidx)
template<class T>
inline SPL::int32 findLastOf(const SPL::list<T>& values,
const SPL::list<T>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the last occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that matches one of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findLastOf(const SPL::blist<T, N>& values,
const SPL::list<T>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the last occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that matches one of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findLastOf(const SPL::list<T>& values,
const SPL::blist<T, N>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::blist<T, N>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the last occurrence of a matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that matches one of the values in the search list (-1, if no match).
template<class T, int32_t N, int32_t M>
inline SPL::int32 findLastOf(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::blist<T, M>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the first occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that does not match any of the values in the search list (-1, if no match).
/// @splnative <any T> public int32 findFirstNotOf (list<T> values, list<T> items, int32 sidx)
/// @spleval $name = "findFirstNotOf"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'; $arg[2] = "int32"
/// @splnative <any T>[N] public int32 findFirstNotOf (list<T>[N] values, list<T> items, int32 sidx)
/// @splnative <any T>[N] public int32 findFirstNotOf (list<T> values, list<T>[N] items, int32 sidx)
/// @splnative <any T>[N,M] public int32 findFirstNotOf (list<T>[N] values, list<T>[M] items, int32 sidx)
template<class T>
inline SPL::int32 findFirstNotOf(const SPL::list<T>& values,
const SPL::list<T>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// @spldesc Find the first occurrence of a non-matching value in a list, given a list of values to search for, starting at index 0.
/// @splparam values List of input values.
/// @splparam items List of search values.
/// @splreturn Index of the first value that does not match any of the values in the search list (-1, if no match).
/// @splnative <any T> public int32 findFirstNotOf (list<T> values, list<T> items)
/// @spleval $name = "findFirstNotOf"; $ret = "int32"; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>';
/// @splnative <any T>[N] public int32 findFirstNotOf (list<T>[N] values, list<T> items)
/// @splnative <any T>[N] public int32 findFirstNotOf (list<T> values, list<T>[N] items)
/// @splnative <any T>[N,M] public int32 findFirstNotOf (list<T>[N] values, list<T>[M] items)
/// Find the first occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that does not match any of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findFirstNotOf(const SPL::blist<T, N>& values,
const SPL::list<T>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// Find the first occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that does not match any of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findFirstNotOf(const SPL::list<T>& values,
const SPL::blist<T, N>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::blist<T, N>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// Find the first occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param sidx Start index of the search.
/// @return Index of the first value that does not match any of the values in the search list (-1, if no match).
template<class T, int32_t N, int32_t M>
inline SPL::int32 findFirstNotOf(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& items,
const SPL::int32 sidx = 0)
{
_cachedMembership<const SPL::blist<T, M>, T> cache(items);
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
for (size_t i = start, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
}
return -1;
}
/// Find the last occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that does not match any of the values in the search list (-1, if no match).
/// @splnative <any T> public int32 findLastNotOf (list<T> values, list<T> items, int32 lidx)
/// @spleval $name = "findLastNotOf"; $ret = "int32"; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'; $arg[2] = "int32"
/// @splnative <any T>[N] public int32 findLastNotOf (list<T>[N] values, list<T> items, int32 lidx)
/// @splnative <any T>[N] public int32 findLastNotOf (list<T> values, list<T>[N] items, int32 lidx)
/// @splnative <any T>[N,M] public int32 findLastNotOf (list<T>[N] values, list<T>[M] items, int32 lidx)
template<class T>
inline SPL::int32 findLastNotOf(const SPL::list<T>& values,
const SPL::list<T>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the last occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that does not match any of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findLastNotOf(const SPL::blist<T, N>& values,
const SPL::list<T>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::list<T>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the last occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that does not match any of the values in the search list (-1, if no match).
template<class T, int32_t N>
inline SPL::int32 findLastNotOf(const SPL::list<T>& values,
const SPL::blist<T, N>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::blist<T, N>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find the last occurrence of a non-matching value in a list, given a list of values to search for.
/// @param values List of input values.
/// @param items List of search values.
/// @param lidx Index of the last item to be considered.
/// @return Index of the last value that does not match any of the values in the search list (-1, if no match).
template<class T, int32_t N, int32_t M>
inline SPL::int32 findLastNotOf(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& items,
const SPL::int32 lidx)
{
_cachedMembership<const SPL::blist<T, M>, T> cache(items);
if (lidx < 0) {
return -1;
}
size_t last = static_cast<size_t>(lidx);
if (last >= values.size()) {
last = values.size() - 1;
}
for (size_t i = last; i >= 0; --i) {
if (!cache.has(static_cast<T>(values[i]))) {
return static_cast<SPL::int32>(i);
}
if (i == 0) {
break;
}
}
return -1;
}
/// Find whether a given value exists in a list.
/// @param values List of input values.
/// @param item Value to be found.
/// @return The result 'true' if the list contains the searched value, 'false' otherwise.
/// @splnative <any T> public boolean has (list<T> values, T item)
/// @spleval $name = "has"; $ret = "boolean"; $numArgs = 2; $arg[0] = 'listSet<@primitive@>'; $arg[1] = '@primitive@'
/// @splnative <any T>[N] public boolean has (list<T>[N] values, T item)
template<class T>
inline SPL::boolean has(const SPL::list<T>& values, const T& item)
{
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (values[i] == item) {
return true;
}
}
return false;
}
/// Find whether a given value exists in a list.
/// @param values List of input values.
/// @param item Value to be found.
/// @return The result 'true' if the list contains the searched value, 'false' otherwise.
template<class T, int32_t N>
inline SPL::boolean has(const SPL::blist<T, N>& values, const T& item)
{
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (values[i] == item) {
return true;
}
}
return false;
}
/// Find whether a given key exists in a map.
/// @param values Map of key-value pairs.
/// @param item Key to be found.
/// @return The result 'true' if the map contains the searched key, 'false' otherwise.
/// @splnative <any K, any V> public boolean has (map<K,V> values, K item)
template<class K, class V>
inline SPL::boolean has(const SPL::map<K, V>& values, const K& item)
{
return values.find(item) != values.end();
}
/// Find whether a given key exists in a map.
/// @param values Map of key-value pairs.
/// @param item Key to be found.
/// @return The result 'true' if the map contains the searched key, 'false' otherwise.
/// @splnative <any K, any V>[N] public boolean has (map<K,V>[N] values, K item)
template<class K, class V, int32_t size>
inline SPL::boolean has(const SPL::bmap<K, V, size>& values, const K& item)
{
return values.find(item) != values.end();
}
/// Find whether a given value exists in a set.
/// @param values Set of input values.
/// @param item Value to be found.
/// @return The result 'true' if the set contains the searched value, 'false' otherwise.
/// @splnative <any T> public boolean has (set<T> values, T item)
template<class K>
inline SPL::boolean has(const SPL::set<K>& values, const K& item)
{
return values.find(item) != values.end();
}
/// Find whether a given value exists in a set.
/// @param values Set of input values.
/// @param item Value to be found.
/// @return The result 'true' if the set contains the searched value, 'false' otherwise.
/// @splnative <any T>[N] public boolean has (set<T>[N] values, T item)
template<class K, int32_t size>
inline SPL::boolean has(const SPL::bset<K, size>& values, const K& item)
{
return values.find(item) != values.end();
}
/// Insert a value into a list.
/// @param values List of input values.
/// @param ival Value to be inserted.
/// @param idx Index of the insert position.
/// @return A new list of values with the new value inserted.
/// @splnative <any T> public list<T> insert (list<T> values, T ival, int32 idx)
/// @spleval $name = "insert"; $ret = 'list<@primitive@>'; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = '@primitive@'; $arg[2] = "int32"
/// @splnative <any T>[N] public list<T>[N] insert (list<T>[N] values, T ival, int32 idx)
template<class T>
inline SPL::list<T> insert(const SPL::list<T>& values, const T& ival, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
SPL::list<T> res(values);
res.insert(res.begin() + index, ival);
return res;
}
/// Insert a value into a list.
/// @param values List of input values.
/// @param ival Value to be inserted.
/// @param idx Index of the insert position.
/// @return A new list of values with the new value inserted.
template<class T, int32_t N>
inline SPL::blist<T, N> insert(const SPL::blist<T, N>& values, const T& ival, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
SPL::blist<T, N> res(values);
res.insert(res.begin() + index, ival);
return res;
}
/// Insert a value into a list (mutating version).
/// @param values List of input values.
/// @param ival Value to be inserted.
/// @param idx Index of the insert position.
/// @splnative <any T> public void insertM (mutable list<T> values, T ival, int32 idx)
/// @splnative <any T>[N] public void insertM (mutable list<T>[N] values, T ival, int32 idx)
template<class T>
inline void insertM(SPL::list<T>& values, const T& ival, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
values.insert(values.begin() + index, ival);
}
/// Insert a value into a list (mutating version).
/// @param values List of input values.
/// @param ival Value to be inserted.
/// @param idx Index of the insert position.
template<class T, int32_t N>
inline void insertM(SPL::blist<T, N>& values, const T& ival, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
values.insert(values.begin() + index, ival);
}
/// Insert a list of values into a list.
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
/// @return A new list of values with the new values inserted.
/// @splnative <any T> public list<T> insert (list<T> values, list<T> ivls, int32 idx)
/// @spleval $name = "insert"; $ret = 'list<@primitive@>'; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'; $arg[2] = "int32"
/// @splnative <any T>[N] public list<T> insert (list<T> values, list<T>[N] ivls, int32 idx)
/// @splnative <any T>[N] public list<T>[N] insert (list<T>[N] values, list<T> ivls, int32 idx)
/// @splnative <any T>[N,M] public list<T>[N] insert (list<T>[N] values, list<T>[M] ivls, int32 idx)
template<class T>
inline SPL::list<T> insert(const SPL::list<T>& values,
const SPL::list<T>& ivls,
const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
SPL::list<T> res(values);
res.insert(res.begin() + index, ivls.begin(), ivls.end());
return res;
}
/// Insert a list of values into a list.
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
/// @return A new list of values with the new values inserted.
template<class T, int32_t N>
inline SPL::list<T> insert(const SPL::list<T>& values,
const SPL::blist<T, N>& ivls,
const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
SPL::list<T> res(values);
res.insert(res.begin() + index, ivls.begin(), ivls.end());
return res;
}
/// Insert a list of values into a list.
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
/// @return A new list of values with the new values inserted.
template<class T, int32_t N>
inline SPL::blist<T, N> insert(const SPL::blist<T, N>& values,
const SPL::list<T>& ivls,
const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
SPL::blist<T, N> res(values);
res.insert(res.begin() + index, ivls.begin(), ivls.end());
return res;
}
/// Insert a list of values into a list.
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
/// @return A new list of values with the new values inserted.
template<class T, int32_t N, int32_t M>
inline SPL::blist<T, N> insert(const SPL::blist<T, N>& values,
const SPL::blist<T, M>& ivls,
const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
SPL::blist<T, N> res(values);
res.insert(res.begin() + index, ivls.begin(), ivls.end());
return res;
}
/// Insert values into a list (mutating version).
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
/// @splnative <any T> public void insertM (mutable list<T> values, list<T> ivls, int32 idx)
/// @splnative <any T>[N] public void insertM (mutable list<T> values, list<T>[N] ivls, int32 idx)
/// @splnative <any T>[N] public void insertM (mutable list<T>[N] values, list<T> ivls, int32 idx)
/// @splnative <any T>[N,M] public void insertM (mutable list<T>[N] values, list<T>[M] ivls, int32 idx)
template<class T>
inline void insertM(SPL::list<T>& values, const SPL::list<T>& ivls, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
values.insert(values.begin() + index, ivls.begin(), ivls.end());
}
/// Insert values into a list (mutating version).
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
template<class T, int32_t N>
inline void insertM(SPL::list<T>& values, const SPL::blist<T, N>& ivls, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
values.insert(values.begin() + index, ivls.begin(), ivls.end());
}
/// Insert values into a list (mutating version).
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
template<class T, int32_t N>
inline void insertM(SPL::blist<T, N>& values, const SPL::list<T>& ivls, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
values.insert(values.begin() + index, ivls.begin(), ivls.end());
}
/// Insert values into a list (mutating version).
/// @param values List of input values.
/// @param ivls List of values to be inserted.
/// @param idx Index of the insert position.
template<class T, int32_t N, int32_t M>
inline void insertM(SPL::blist<T, N>& values, const SPL::blist<T, M>& ivls, const SPL::int32 idx)
{
size_t index = static_cast<size_t>(idx);
if (idx < 0) {
index = 0;
}
if (index > values.size()) {
index = values.size();
}
values.insert(values.begin() + index, ivls.begin(), ivls.end());
}
/// Remove a value from a list.
/// @param values List of input values.
/// @param idx Index of the item to be removed.
/// @return A copy of the list of values after the removal.
/// @splnative <list T> public T remove (T values, int32 idx)
/// @spleval $name = "remove"; $ret = 'list<@primitive@>'; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = "int32"
template<class T>
inline SPL::list<T> remove(const SPL::list<T>& values, const SPL::int32 idx)
{
if (idx < 0) {
return values;
}
size_t index = static_cast<size_t>(idx);
SPL::list<T> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (i != index) {
res.push_back(values[i]);
}
}
return res;
}
/// Remove a value from a list.
/// @param values List of input values.
/// @param idx Index of the item to be removed.
/// @return A copy of the list of values after the removal.
template<class T, int32_t N>
inline SPL::blist<T, N> remove(const SPL::blist<T, N>& values, const SPL::int32 idx)
{
if (idx < 0) {
return values;
}
size_t index = static_cast<size_t>(idx);
SPL::blist<T, N> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (i != index) {
res.push_back(values[i]);
}
}
return res;
}
/// Remove a value from a list (mutating version).
/// @param values List of input values.
/// @param idx Index of the item to be removed.
/// @splnative <list T> public void removeM (mutable T values, int32 idx)
template<class T>
inline void removeM(SPL::list<T>& values, const SPL::int32 idx)
{
if (idx < 0) {
return;
}
values.erase(values.begin() + static_cast<size_t>(idx));
}
/// Remove a value from a list (mutating version).
/// @param values List of input values.
/// @param idx Index of the item to be removed.
template<class T, int32_t N>
inline void removeM(SPL::blist<T, N>& values, const SPL::int32 idx)
{
if (idx < 0) {
return;
}
values.erase(values.begin() + static_cast<size_t>(idx));
}
/// Remove values from a list using a range.
/// @param values List of input values.
/// @param sidx Start index of the removal range.
/// @param eidx End index of the removal range (inclusive).
/// @return A copy of the list of values with the range of values removed.
/// @splnative <list T> public T remove (T values, int32 sidx, int32 eidx)
/// @spleval $name = "remove"; $ret = 'list<@primitive@>'; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = "int32"; $arg[2] = "int32"
template<class T>
inline SPL::list<T> remove(const SPL::list<T>& values, const SPL::int32 sidx, const SPL::int32 eidx)
{
if (eidx < sidx || eidx < 0) {
return values;
}
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
size_t end = static_cast<size_t>(eidx);
SPL::list<T> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (i < start || i > end) {
res.push_back(values[i]);
}
}
return res;
}
/// Remove values from a list using a range.
/// @param values List of input values.
/// @param sidx Start index of the removal range.
/// @param eidx End index of the removal range (inclusive).
/// @return A copy of the list of values with the range of values removed.
template<class T, int32_t N>
inline SPL::blist<T, N> remove(const SPL::blist<T, N>& values,
const SPL::int32 sidx,
const SPL::int32 eidx)
{
if (eidx < sidx || eidx < 0) {
return values;
}
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
size_t end = static_cast<size_t>(eidx);
SPL::blist<T, N> res;
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (i < start || i > end) {
res.push_back(values[i]);
}
}
return res;
}
/// Remove values from a list using a range (mutating version).
/// @param values List of input values.
/// @param sidx Start index of the removal range.
/// @param eidx End index of the removal range (inclusive).
/// @splnative <list T> public void removeM (mutable T values, int32 sidx, int32 eidx)
template<class T>
inline void removeM(SPL::list<T>& values, const SPL::int32 sidx, const SPL::int32 eidx)
{
if (eidx < sidx || eidx < 0) {
return;
}
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
size_t end = static_cast<size_t>(eidx);
values.erase(values.begin() + start, values.begin() + end + 1);
}
/// Remove values from a list using a range (mutating version).
/// @param values List of input values.
/// @param sidx Start index of the removal range.
/// @param eidx End index of the removal range (inclusive).
template<class T, int32_t N>
inline void removeM(SPL::blist<T, N>& values, const SPL::int32 sidx, const SPL::int32 eidx)
{
if (eidx < sidx || eidx < 0) {
return;
}
size_t start = static_cast<size_t>(sidx);
if (sidx < 0) {
start = 0;
}
size_t end = static_cast<size_t>(eidx);
SPL::blist<T, N> res;
values.erase(values.begin() + start, values.begin() + end + 1);
}
/// Remove values from a list using an index list.
/// @param values List of input values.
/// @param idxs List of removal indexes.
/// @return A copy of the list of values with the specified values removed.
/// @splnative <list T> public T remove (T values, list<int32> idxs)
/// @spleval $name = "remove"; $ret = 'list<@primitive@>'; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<int32>'
template<class T>
inline SPL::list<T> remove(const SPL::list<T>& values, const SPL::list<SPL::int32>& idxs)
{
SPL::list<T> res;
_cachedMembership<const SPL::list<SPL::int32> > cache(idxs);
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<SPL::int32>(i))) {
res.push_back(values[i]);
}
}
return res;
}
/// Remove values from a list using an index list.
/// @param values List of input values.
/// @param idxs List of removal indexes.
/// @return A copy of the list of values with the specified values removed.
template<class T, int32_t N>
inline SPL::blist<T, N> remove(const SPL::blist<T, N>& values, const SPL::list<SPL::int32>& idxs)
{
SPL::blist<T, N> res;
_cachedMembership<const SPL::list<SPL::int32> > cache(idxs);
for (size_t i = 0, iu = values.size(); i < iu; ++i) {
if (!cache.has(static_cast<SPL::int32>(i))) {
res.push_back(values[i]);
}
}
return res;
}
/// Sort a list of values.
/// @param values List of values.
/// @return A copy of the list with values sorted in increasing order.
/// @splnative <ordered T> public list<T> sort (list<T> values)
/// @spleval $name = "sort"; $ret = 'list<@ordered@>'; $numArgs = 1; $arg[0] = 'list<@ordered@>'
/// @splnative <ordered T>[N] public list<T>[N] sort (list<T>[N] values)
template<class T>
inline SPL::list<T> sort(const SPL::list<T>& values)
{
SPL::list<T> res = values;
std::sort(res.begin(), res.end());
return res;
}
/// Sort a list of values.
/// @param values List of input values.
/// @return A copy of the list with values sorted in increasing order.
template<class T, int32_t N>
inline SPL::blist<T, N> sort(const SPL::blist<T, N>& values)
{
SPL::blist<T, N> res = values;
std::sort(res.begin(), res.end());
return res;
}
/// Sort a list of values (mutating version).
/// @param values List of values to be sorted.
/// @splnative <ordered T> public void sortM (mutable list<T> values)
/// @splnative <ordered T>[N] public void sortM (mutable list<T>[N] values)
template<class T>
inline void sortM(SPL::list<T>& values)
{
std::sort(values.begin(), values.end());
}
/// Sort a list of values (mutating version).
/// @param values List of values to be sorted.
template<class T, int32_t N>
inline void sortM(SPL::blist<T, N>& values)
{
std::sort(values.begin(), values.end());
}
#ifndef DOXYGEN_SKIP_FOR_USERS
/// function object used for indexed sort
template<class T>
class ListIndexSorter : public std::binary_function<int32_t, int32_t, bool>
{
public:
ListIndexSorter(const SPL::list<T>& vec)
: _vec(vec)
{}
bool operator()(int32_t lhs, int32_t rhs) { return _vec[lhs] < _vec[rhs]; }
private:
const SPL::list<T>& _vec;
};
// function object used for indexed sort
template<class T, int32_t N>
class BListIndexSorter : public std::binary_function<int32_t, int32_t, bool>
{
public:
BListIndexSorter(const SPL::blist<T, N>& vec)
: _vec(vec)
{}
bool operator()(int32_t lhs, int32_t rhs) { return _vec[lhs] < _vec[rhs]; }
private:
const SPL::blist<T, N>& _vec;
};
#endif /* DOXYGEN_SKIP_FOR_USERS */
/// Sort a list of values and return a list of indexes that specify the values in sorted order.
/// @param values List of input values.
/// @return A new list containing indexes to the items that specify the items in sorted order.
/// @splnative <ordered T> public list<uint32> sortIndices (list<T> values)
/// @spleval $name = "sortIndices"; $ret = 'list<uint32>'; $numArgs = 1; $arg[0] = 'list<@ordered@>'
/// @splnative <ordered T>[N] public list<uint32> sortIndices (list<T>[N] values)
template<class T>
inline SPL::list<SPL::uint32> sortIndices(const SPL::list<T>& values)
{
SPL::list<SPL::uint32> res;
size_t sz = values.size();
res.reserve(sz);
for (SPL::uint32 i = 0; i < sz; ++i) {
res.push_back(i);
}
std::sort(res.begin(), res.end(), ListIndexSorter<T>(values));
return res;
}
/// Sort a list of values and return a list of indexes that specify the values in sorted order.
/// @param values List of input values.
/// @return A new list containing indexes to the items that specify the items in sorted order.
template<class T, int32_t N>
inline SPL::blist<SPL::uint32, N> sortIndices(const SPL::blist<T, N>& values)
{
SPL::blist<SPL::uint32, N> res;
size_t sz = values.size();
for (SPL::uint32 i = 0; i < sz; ++i) {
res.push_back(i);
}
std::sort(res.begin(), res.end(), BListIndexSorter<T, N>(values));
return res;
}
/// Reverse a list of values.
/// @param values List of input values.
/// @return A copy of the list with the values in reverse order.
/// @splnative <list T> public T reverse (T values)
/// @spleval $name = "reverse"; $ret = 'list<@primitive@>'; $numArgs = 1; $arg[0] = 'list<@primitive@>'
template<class T>
inline SPL::list<T> reverse(const SPL::list<T>& values)
{
SPL::list<T> res;
res.reserve(values.size());
for (size_t i = values.size() - 1; i >= 0; --i) {
res.push_back(values[i]);
if (i == 0) {
break;
}
}
return res;
}
/// Reverse a list of values.
/// @param values List of input values.
/// @return A copy of the list with the values in reverse order.
template<class T, int32_t N>
inline SPL::blist<T, N> reverse(const SPL::blist<T, N>& values)
{
SPL::blist<T, N> res;
for (size_t i = values.size() - 1; i >= 0; --i) {
res.push_back(values[i]);
if (i == 0) {
break;
}
}
return res;
}
/// Reverse a list of values (mutating version).
/// @param values List to be reversed.
/// @splnative <list T> public void reverseM (mutable T values)
template<class T>
inline void reverseM(SPL::list<T>& values)
{
std::reverse(values.begin(), values.end());
}
/// Reverse a list of values (mutating version).
/// @param values List to be reversed.
template<class T, int32_t N>
inline void reverseM(SPL::blist<T, N>& values)
{
std::reverse(values.begin(), values.end());
}
/// Access multiple elements of a list.
/// @param values List of input values.
/// @param idxs List of selector indexes.
/// @return A new list of values at the indexes specified by the selectors.
/// @splnative <any T> public list<T> at (list<T> values, list<uint32> idxs)
/// @spleval $name = "at"; $ret = 'list<@primitive@>'; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<uint32>'
/// @splnative <any T>[N] public list<T> at (list<T>[N] values, list<uint32> idxs)
template<class T>
inline SPL::list<T> at(const SPL::list<T>& values, const SPL::list<SPL::uint32>& idxs)
{
SPL::list<T> res;
size_t vcnt = values.size();
for (size_t i = 0, iu = idxs.size(); i < iu; ++i) {
if (idxs[i] >= vcnt) {
continue;
}
res.push_back(values[idxs[i]]);
}
return res;
}
/// Access multiple elements of a list.
/// @param values List of input values.
/// @param idxs List of selector indexes.
/// @return A new list of values at the indexes specified by the selectors.
template<class T, int32_t N>
inline SPL::list<T> at(const SPL::blist<T, N>& values, const SPL::list<SPL::uint32>& idxs)
{
SPL::blist<T, N> res;
size_t vcnt = values.size();
for (size_t i = 0, iu = idxs.size(); i < iu; ++i) {
if (idxs[i] >= vcnt) {
continue;
}
res.push_back(values[idxs[i]]);
}
return res;
}
/// Select element-wise from two lists.
/// @param selector List of booleans where 'true' means select from the first list, and 'false' means select from the second list.
/// @param a First list.
/// @param b Second list.
/// @return A new list of values, each selected from either the first or the second list.
/// @throws SPLRuntimeInvalidArgumentException If the sizes of the two lists are not the same.
/// @splnative <list T> public T selectFromList (list<boolean> selector, T a, T b)
/// @spleval $name = "selectFromList"; $selector = 1; $ret = 'list<@primitive@>'; $numArgs = 3; $arg[0] = 'list<boolean>'; $arg[1] = 'list<@primitive@>'; $arg[2] = 'list<@primitive@>'
template<class T>
inline SPL::list<T> selectFromList(const SPL::list<SPL::boolean>& selector,
const SPL::list<T>& a,
const SPL::list<T>& b)
{
SPL::list<T> res;
size_t sSize = selector.size();
if (sSize != a.size()) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_MISMATCH_SELECTFROM(sSize, a.size()),
SPL_FUNC_DBG);
}
if (sSize != b.size()) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_MISMATCH_SELECTFROM(sSize, b.size()),
SPL_FUNC_DBG);
}
res.reserve(sSize);
for (size_t i = 0; i < sSize; ++i) {
res.push_back(selector[i] ? a[i] : b[i]);
}
return res;
}
/// Select element-wise from two lists.
/// @param selector List of booleans where 'true' means select from the first list, and 'false' means select from the second list.
/// @param a First list.
/// @param b Second list.
/// @return A new list of values, each selected from either the first or the second list.
/// @throws SPLRuntimeInvalidArgumentException If the sizes of the two lists are not the same.
template<class T, int32_t N>
inline SPL::blist<T, N> selectFromList(const SPL::list<SPL::boolean>& selector,
const SPL::blist<T, N>& a,
const SPL::blist<T, N>& b)
{
SPL::blist<T, N> res;
size_t sSize = selector.size();
if (sSize != a.size()) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_MISMATCH_SELECTFROM(sSize, a.size()),
SPL_FUNC_DBG);
}
if (sSize != b.size()) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_MISMATCH_SELECTFROM(sSize, b.size()),
SPL_FUNC_DBG);
}
for (size_t i = 0; i < sSize; ++i) {
res.push_back(selector[i] ? a[i] : b[i]);
}
return res;
}
/// Concatenate two lists.
/// @param values1 First list of input values.
/// @param values2 Second list of input values.
/// @return A new, combined list of values containing, in order, values in the first list,
/// followed by the values in the second list.
/// @splnative <any T> public list<T> concat (list<T> values1, list<T> values2)
/// @spleval $name = "concat"; $ret = 'list<@primitive@>'; $numArgs = 2; $arg[0] = 'list<@primitive@>'; $arg[1] = 'list<@primitive@>'
/// @splnative <any T>[N] public list<T> concat (list<T> values1, list<T>[N] values2)
/// @splnative <any T>[N] public list<T> concat (list<T>[N] values1, list<T> values2)
/// @splnative <any T>[N,M] public list<T> concat (list<T>[N] values1, list<T>[M] values2)
template<class T>
inline SPL::list<T> concat(const SPL::list<T>& values1, const SPL::list<T>& values2)
{
SPL::list<T> res = values1;
res.reserve(values1.size() + values2.size());
for (size_t i = 0, iu = values2.size(); i < iu; ++i) {
res.push_back(values2[i]);
}
return res;
}
/// Concatenate two lists.
/// @param values1 First list of input values.
/// @param values2 Second list of input values.
/// @return A new, combined list of values containing, in order, values in the first list,
/// followed by the values in the second list.
template<class T, int32_t N>
inline SPL::list<T> concat(const SPL::list<T>& values1, const SPL::blist<T, N>& values2)
{
SPL::list<T> res = values1;
res.reserve(values1.size() + values2.size());
for (size_t i = 0, iu = values2.size(); i < iu; ++i) {
res.push_back(values2[i]);
}
return res;
}
/// Concatenate two lists.
/// @param values1 First list of input values.
/// @param values2 Second list of input values.
/// @return A new, combined list of values containing, in order, values in the first list,
/// followed by the values in the second list.
template<class T, int32_t N>
inline SPL::list<T> concat(const SPL::blist<T, N>& values1, const SPL::list<T>& values2)
{
SPL::list<T> res;
res.reserve(values1.size() + values2.size());
for (size_t i = 0, iu = values1.size(); i < iu; ++i) {
res.push_back(values1[i]);
}
for (size_t i = 0, iu = values2.size(); i < iu; ++i) {
res.push_back(values2[i]);
}
return res;
}
/// Concatenate two lists.
/// @param values1 First list of input values.
/// @param values2 Second list of input values.
/// @return A new, combined list of values containing, in order, values in the first list,
/// followed by the values in the second list.
template<class T, int32_t N>
inline SPL::blist<T, N> concat(const SPL::blist<T, N>& values1, const SPL::blist<T, N>& values2)
{
SPL::blist<T, N> res = values1;
for (size_t i = 0, iu = values2.size(); i < iu; ++i) {
res.push_back(values2[i]);
}
return res;
}
/// Concatenate two lists.
/// @param values1 First list of input values.
/// @param values2 Second list of input values.
/// @return A new, combined list of values containing, in order, values in the first list,
/// followed by the values in the second list.
template<class T, int32_t N, int32_t M>
inline SPL::list<T> concat(const SPL::blist<T, N>& values1, const SPL::blist<T, M>& values2)
{
SPL::list<T> res;
res.reserve(values1.size() + values2.size());
for (size_t i = 0, iu = values1.size(); i < iu; ++i) {
res.push_back(values1[i]);
}
for (size_t i = 0, iu = values2.size(); i < iu; ++i) {
res.push_back(values2[i]);
}
return res;
}
/// Concatenate two lists (mutating version).
/// Append the list values2 to the list values1.
/// @param values1 List to be appended to.
/// @param values2 List to be appended.
/// @splnative <any T> public void concatM (mutable list<T> values1, list<T> values2)
/// @splnative <any T>[N] public void concatM (mutable list<T> values1, list<T>[N] values2)
/// @splnative <any T>[N] public void concatM (mutable list<T>[N] values1, list<T> values2)
/// @splnative <any T>[N,M] public void concatM (mutable list<T>[N] values1, list<T>[M] values2)
template<class T>
inline void concatM(SPL::list<T>& values1, const SPL::list<T>& values2)
{
values1.insert(values1.end(), values2.begin(), values2.end());
}
/// Concatenate two lists (mutating version).
/// Append the list values2 to the list values1.
/// @param values1 List to be appended to.
/// @param values2 List to be appended.
template<class T, int32_t N>
inline void concatM(SPL::list<T>& values1, const SPL::blist<T, N>& values2)
{
values1.insert(values1.end(), values2.begin(), values2.end());
}
/// Concatenate two lists (mutating version).
/// Append the list values2 to the list values1.
/// @param values1 List to be appended to.
/// @param values2 List to be appended.
template<class T, int32_t N>
inline void concatM(SPL::blist<T, N>& values1, const SPL::list<T>& values2)
{
values1.insert(values1.end(), values2.begin(), values2.end());
}
/// Concatenate two lists (mutating version).
/// Append the list values2 to the list values1.
/// @param values1 List to be appended to.
/// @param values2 List to be appended.
template<class T, int32_t N, int32_t M>
inline void concatM(SPL::blist<T, N>& values1, const SPL::blist<T, M>& values2)
{
values1.insert(values1.end(), values2.begin(), values2.end());
}
/// Append to a list (mutating version).
/// @param values List to be appended to.
/// @param value Value to be appended.
/// @splnative <any T> public void appendM (mutable list<T> values, T value)
template<class T>
inline void appendM(SPL::list<T>& values, const T& value)
{
values.push_back(value);
}
/// Append to a bounded list (mutating version).
/// If the list is already at its maximum size, it will not be changed.
/// @param values List to be appended to.
/// @param value Value to be appended.
/// @splnative <any T>[N] public void appendM (mutable list<T>[N] values, T value)
template<class T, int32_t N>
inline void appendM(SPL::blist<T, N>& values, const T& value)
{
values.push_back(value);
}
/// Slice a list: extract items from a list.
/// @param values List of input values.
/// @param from Start index of the extraction.
/// @param cnt Number of slices to be extracted.
/// @param skip Number of values to be skipped after each slice (should be >=0).
/// @param tape Number of values to be extracted after the first item in a
/// slice, i.e., slice size - 1 (should be >=0).
/// @return List of extracted input values.
/// @throws SPLRuntimeInvalidArgumentException If skip or tape is negative.
/// @splnative <list T> public T slice (T values, int32 from, int32 cnt, int32 skip, int32 tape)
/// @spleval $name = "slice"; $ret = 'list<@primitive@>'; $numArgs = 5; $arg[0] = 'list<@primitive@>'; $arg[1] = "int32"; $arg[2] = "int32"; $arg[3] = "int32"; $arg[4] = "int32"
template<class T>
inline SPL::list<T> slice(const SPL::list<T>& values,
const SPL::int32 from,
const SPL::int32 cnt,
const SPL::int32 skip,
const SPL::int32 tape)
{
SPL::list<T> res;
int32_t mcnt = cnt;
int32_t mfrm = from;
if (mcnt < 0) {
return res;
}
if (skip < 0) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_SLICE_NEGATIVE_ARG("skip"), SPL_FUNC_DBG);
}
if (tape < 0) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_SLICE_NEGATIVE_ARG("tape"), SPL_FUNC_DBG);
}
int32_t vcnt = static_cast<int32_t>(values.size());
if (mfrm < 0) {
mcnt -= ((-mfrm) / (1 + skip + tape));
if (mcnt < 0) {
return res;
}
mfrm = -((-mfrm) % (1 + skip + tape));
} else if (mfrm >= vcnt) {
return res;
}
for (int32_t i = mfrm, iu = mfrm + (1 + tape + skip) * mcnt; i < iu && i < vcnt; i += skip) {
if (i < 0) {
i += (1 + tape);
continue;
}
res.push_back(values[i++]);
for (int32_t j = 0; j < tape && i < vcnt; ++j) {
res.push_back(values[i++]);
}
}
return res;
}
/// Slice a list: extract items from a list.
/// @param values List of input values.
/// @param from Start index of the extraction.
/// @param cnt Number of slices to be extracted.
/// @param skip Number of values to be skipped after each slice (should be >=0).
/// @param tape Number of values to be extracted after the first item in a
/// slice, i.e., slice size - 1 (should be >=0).
/// @return List of extracted input values.
/// @throws SPLRuntimeInvalidArgumentException If skip or tape is negative.
template<class T, int32_t N>
inline SPL::blist<T, N> slice(const SPL::blist<T, N>& values,
const SPL::int32 from,
const SPL::int32 cnt,
const SPL::int32 skip,
const SPL::int32 tape)
{
SPL::blist<T, N> res;
int32_t mcnt = cnt;
int32_t mfrm = from;
if (mcnt < 0) {
return res;
}
if (skip < 0) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_SLICE_NEGATIVE_ARG("skip"), SPL_FUNC_DBG);
}
if (tape < 0) {
SPLTRACEMSGANDTHROW(SPL::SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_SIZE_SLICE_NEGATIVE_ARG("tape"), SPL_FUNC_DBG);
}
int32_t vcnt = static_cast<int32_t>(values.size());
if (mfrm < 0) {
mcnt -= ((-mfrm) / (1 + skip + tape));
if (mcnt < 0) {
return res;
}
mfrm = -((-mfrm) % (1 + skip + tape));
} else if (mfrm >= vcnt) {
return res;
}
for (int32_t i = mfrm, iu = mfrm + (1 + tape + skip) * mcnt; i < iu && i < vcnt; i += skip) {
if (i < 0) {
i += (1 + tape);
continue;
}
res.push_back(values[i++]);
for (int32_t j = 0; j < tape && i < vcnt; ++j) {
res.push_back(values[i++]);
}
}
return res;
}
/// Slice a list: extract items from a list.
/// @param values List of input values.
/// @param from Start index of the extraction.
/// @param cnt Number of values to be extracted.
/// @return List of extracted input values.
/// @splnative <list T> public T slice (T values, int32 from, int32 cnt)
/// @spleval $name = "slice"; $ret = 'list<@primitive@>'; $numArgs = 3; $arg[0] = 'list<@primitive@>'; $arg[1] = "int32"; $arg[2] = "int32"
template<class T>
inline SPL::list<T> slice(const SPL::list<T>& values, const SPL::int32 from, const SPL::int32 cnt)
{
return slice(values, from, cnt, 0, 0);
}
/// Slice a list: extract items from a list.
/// @param values List of input values.
/// @param from Start index of the extraction.
/// @param cnt Number of values to be extracted.
/// @return List of extracted input values.
template<class T, int32_t N>
inline SPL::blist<T, N> slice(const SPL::blist<T, N>& values,
const SPL::int32 from,
const SPL::int32 cnt)
{
return slice(values, from, cnt, 0, 0);
}
/// Slice a list: extract items from a list.
/// @param values List of input values.
/// @param from Start index of the extraction.
/// @param cnt Number of values to be extracted.
/// @param skip Number of values to be skipped after each extraction (should be >=0).
/// @return List of extracted input values.
/// @throws SPLRuntimeInvalidArgumentException If skip is negative.
/// @splnative <list T> public T slice (T values, int32 from, int32 cnt, int32 skip)
/// @spleval $name = "slice"; $ret = 'list<@primitive@>'; $numArgs = 4; $arg[0] = 'list<@primitive@>'; $arg[1] = "int32"; $arg[2] = "int32"; $arg[3] = "int32"
template<class T>
inline SPL::list<T> slice(const SPL::list<T>& values,
const SPL::int32 from,
const SPL::int32 cnt,
const SPL::int32 skip)
{
return slice(values, from, cnt, skip, 0);
}
/// Slice a list: extract items from a list.
/// @param values List of input values.
/// @param from Start index of the extraction.
/// @param cnt Number of values to be extracted.
/// @param skip Number of values to be skipped after each extraction (should be >=0).
/// @return List of extracted input values.
/// @throws SPLRuntimeInvalidArgumentException If skip is negative.
template<class T, int32_t N>
inline SPL::blist<T, N> slice(const SPL::blist<T, N>& values,
const SPL::int32 from,
const SPL::int32 cnt,
const SPL::int32 skip)
{
return slice(values, from, cnt, skip, 0);
}
/// Convert a list to a set.
/// @param values List of input values.
/// @return A new set containing the values from the list.
/// @splnative <any T> public set<T> toSet (list<T> values)
/// @spleval $name = "toSet"; $ret = 'set<@primitive@>'; $numArgs = 1; $arg[0] = 'list<@primitive@>'
/// @splnative <any T>[N] public set<T>[N] toSet (list<T>[N] values)
template<class T>
inline SPL::set<T> toSet(const SPL::list<T>& values)
{
SPL::set<T> res;
for (size_t i = 0, ui = values.size(); i < ui; ++i) {
res.insert(values[i]);
}
return res;
}
/// Convert a list to a set.
/// @param values List of input values.
/// @return A new set containing the values from the list.
template<class T, int32_t N>
inline SPL::bset<T, N> toSet(const SPL::blist<T, N>& values)
{
SPL::bset<T, N> res;
for (size_t i = 0, ui = values.size(); i < ui; ++i) {
res.insert(values[i]);
}
return res;
}
/// Insert a value into a set.
/// @param values Input set.
/// @param value Value to be inserted.
/// @return A copy of the set with the value inserted.
/// @splnative <any V> public set<V> insert (set<V> values, V value)
/// @spleval $name = "insert"; $ret = 'set<@primitive@>'; $numArgs = 2; $arg[0] = 'set<@primitive@>'; $arg[1] = '@primitive@'
/// @splnative <any V>[N] public set<V>[N] insert (set<V>[N] values, V value)
template<class V>
inline SPL::set<V> insert(const SPL::set<V>& values, const V& value)
{
SPL::set<V> res(values);
res.insert(value);
return res;
}
/// Insert a value into a set.
/// @param values Input set.
/// @param value Value to be inserted.
/// @return A copy of the set with the value inserted.
template<class V, int32_t N>
inline SPL::bset<V, N> insert(const SPL::bset<V, N>& values, const V& value)
{
SPL::bset<V, N> res(values);
res.insert(value);
return res;
}
/// Insert a value into a set (mutating version).
/// @param values Input set.
/// @param value Value to be inserted into the input set.
/// @splnative <any V> public void insertM (mutable set<V> values, V value)
/// @splnative <any V>[N] public void insertM (mutable set<V>[N] values, V value)
template<class V>
inline void insertM(SPL::set<V>& values, const V& value)
{
values.insert(value);
}
/// Insert a value into a set (mutating version).
/// @param values Input set.
/// @param value Value to be inserted into the input set.
template<class V, int32_t N>
inline void insertM(SPL::bset<V, N>& values, const V& value)
{
values.insert(value);
}
/// Return a set with a value removed.
/// @param values Input set.
/// @param key Value to be removed.
/// @return A copy of the set with the value removed.
/// @splnative <any K> public set<K> remove (set<K> values, K key)
/// @spleval $name = "remove"; $ret = 'set<@primitive@>'; $numArgs = 2; $arg[0] = 'set<@primitive@>'; $arg[1] = '@primitive@'
/// @splnative <any K>[N] public set<K>[N] remove (set<K>[N] values, K key)
template<class K>
inline SPL::set<K> remove(const SPL::set<K>& values, const K& key)
{
SPL::set<K> res(values);
typename SPL::set<K>::iterator it = res.find(key);
if (it != res.end()) {
res.erase(it);
}
return res;
}
/// Return a set with a value removed.
/// @param values Input set.
/// @param key Value to be removed.
/// @return A copy of the set with the value removed.
template<class K, int32_t N>
inline SPL::bset<K, N> remove(const SPL::bset<K, N>& values, const K& key)
{
SPL::bset<K, N> res(values);
typename SPL::bset<K, N>::iterator it = res.find(key);
if (it != res.end()) {
res.erase(it);
}
return res;
}
/// Remove a value from a set (mutating version).
/// @param values Input set.
/// @param key Value to be removed.
/// @splnative <any K> public void removeM (mutable set<K> values, K key)
/// @splnative <any K>[N] public void removeM (mutable set<K>[N] values, K key)
template<class K>
inline void removeM(SPL::set<K>& values, const K& key)
{
typename SPL::set<K>::iterator it = values.find(key);
if (it != values.end()) {
values.erase(it);
}
}
/// Remove a value from a set (mutating version).
/// @param values Input set.
/// @param key Value to be removed.
template<class K, int32_t N>
inline void removeM(SPL::bset<K, N>& values, const K& key)
{
typename SPL::bset<K, N>::iterator it = values.find(key);
if (it != values.end()) {
values.erase(it);
}
}
/// Concatenate two sets (mutating version).
/// @param values1 Set to be appended to.
/// @param values2 Set to be appended.
/// @splnative <any T> public void concatM (mutable set<T> values1, set<T> values2)
/// @splnative <any T>[N] public void concatM (mutable set<T> values1, set<T>[N] values2)
/// @splnative <any T>[N] public void concatM (mutable set<T>[N] values1, set<T> values2)
/// @splnative <any T>[N,M] public void concatM (mutable set<T>[N] values1, set<T>[M] values2)
template<class T>
inline void concatM(SPL::set<T>& values1, const SPL::set<T>& values2)
{
values1.insert(values2.begin(), values2.end());
}
/// Concatenate two sets (mutating version).
/// @param values1 Set to be appended to.
/// @param values2 Set to be appended.
template<class T, int32_t N>
inline void concatM(SPL::set<T>& values1, const SPL::bset<T, N>& values2)
{
typename bset<T, N>::const_iterator bit = values2.begin();
typename bset<T, N>::const_iterator eit = values2.end();
for (typename bset<T, N>::const_iterator it = bit; it != eit; ++it) {
values1.insert(*it);
}
}
/// Concatenate two sets (mutating version).
/// @param values1 Set to be appended to.
/// @param values2 Set to be appended.
template<class T, int32_t N>
inline void concatM(SPL::bset<T, N>& values1, const SPL::set<T>& values2)
{
values1.insert(values2.begin(), values2.end());
}
/// Concatenate two sets (mutating version).
/// @param values1 Set to be appended to.
/// @param values2 Set to be appended.
template<class T, int32_t N, int32_t M>
inline void concatM(SPL::bset<T, N>& values1, const SPL::bset<T, M>& values2)
{
typename bset<T, M>::const_iterator bit = values2.begin();
typename bset<T, M>::const_iterator eit = values2.end();
for (typename bset<T, M>::const_iterator it = bit; it != eit; ++it) {
values1.insert(*it);
}
}
/// Append a byte to a blob.
/// @param b Blob to be appended to.
/// @param byte Byte to be appended.
/// @splnative public void appendM (mutable blob b, uint8 byte)
inline void appendM(SPL::blob& b, const SPL::uint8 byte)
{
b += byte;
}
/// Append a list of bytes to a blob.
/// @param b Blob to be appended to.
/// @param bytes List of bytes to be appended.
/// @splnative public void appendM (mutable blob b, list<uint8> bytes)
inline void appendM(SPL::blob& b, const SPL::list<SPL::uint8>& bytes)
{
b += bytes;
}
// Helper functions for subscript slices
/// Return a slice from a blob [lower..upper-1].
/// @param b Input blob.
/// @param lower First index to be included.
/// @param upper Last index (not included in the result).
/// @return The slice b[lower..upper-1].
/// @throws SPLRuntimeInvalidArgumentException If lower > b.size().
SPL::blob subSlice(const SPL::blob& b, uint32_t lower, uint32_t upper);
/// Return a slice from a blob [0..upper-1].
/// @param b Input blob.
/// @param upper Last index (not included in the result).
/// @return The slice b[0..upper-1].
SPL::blob subSliceL(const SPL::blob& b, uint32_t upper);
/// Return a slice from a blob [lower..\<end of blob\>].
/// @param b Input blob.
/// @param lower First index to be included.
/// @return The slice b[lower..\<end of blob\>].
/// @throws SPLRuntimeInvalidArgumentException If lower > b.size().
SPL::blob subSliceU(const SPL::blob& b, uint32_t lower);
/// Return a slice from a list [lower..upper-1].
/// @param l Input list.
/// @param lower First index to be included.
/// @param upper Last index (not included in the result).
/// @return The slice l[lower..upper-1].
/// @throws SPLRuntimeInvalidArgumentException If lower > l.size().
template<class T>
inline SPL::list<T> subSlice(const SPL::list<T>& l, uint32_t lower, uint32_t upper)
{
if (lower > l.size()) {
SPLTRACEMSGANDTHROW(SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_INVALID_LIST_SLICE(lower, l.size()),
SPL_FUNC_DBG);
}
SPL::list<T> res;
for (uint32_t i = lower; i < upper; i++) {
res.push_back(l[i]);
}
return res;
}
/// Return a slice from a list [0..upper-1].
/// @param l Input list.
/// @param upper Last index (not included in the result).
/// @return The slice l[0..upper-1].
template<class T>
inline SPL::list<T> subSliceL(const SPL::list<T>& l, uint32_t upper)
{
SPL::list<T> res;
if (upper > l.size()) {
upper = l.size();
}
for (uint32_t i = 0; i < upper; i++) {
res.push_back(l[i]);
}
return res;
}
/// Return a slice from a list [lower..\<end of list\>].
/// @param l Input list.
/// @param lower First index to be included.
/// @return The slice l[lower..\<end of list\>].
/// @throws SPLRuntimeInvalidArgumentException If lower > l.size().
template<class T>
inline SPL::list<T> subSliceU(const SPL::list<T>& l, uint32_t lower)
{
uint32_t s = l.size();
if (lower > s) {
SPLTRACEMSGANDTHROW(SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_INVALID_LIST_SLICE(lower, s), SPL_FUNC_DBG);
}
SPL::list<T> res;
for (uint32_t i = lower; i < s; i++) {
res.push_back(l[i]);
}
return res;
}
/// Return a slice from a list [lower..upper-1].
/// @param l Input list.
/// @param lower First index to be included.
/// @param upper Last index (not included in the result).
/// @return The slice l[lower..upper-1].
/// @throws SPLRuntimeInvalidArgumentException If lower > l.size().
template<class T, int32_t msize>
inline SPL::blist<T, msize> subSlice(const SPL::blist<T, msize>& l, uint32_t lower, uint32_t upper)
{
if (lower > l.getUsedSize()) {
SPLTRACEMSGANDTHROW(SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_INVALID_LIST_SLICE(lower, l.getUsedSize()),
SPL_FUNC_DBG);
}
SPL::blist<T, msize> res;
for (uint32_t i = lower; i < upper; i++) {
res.push_back(l[i]);
}
return res;
}
/// Return a slice from a list [0..upper-1].
/// @param l Input list.
/// @param upper Last index (not included in the result).
/// @return The slice l[0..upper-1].
template<class T, int32_t msize>
inline SPL::blist<T, msize> subSliceL(const SPL::blist<T, msize>& l, uint32_t upper)
{
SPL::blist<T, msize> res;
if (upper > l.getUsedSize()) {
upper = l.getUsedSize();
}
for (uint32_t i = 0; i < upper; i++) {
res.push_back(l[i]);
}
return res;
}
/// Return a slice from a list [lower..\<end of list\>].
/// @param l Input list.
/// @param lower First index to be included.
/// @return The slice l[lower..\<end of list\>].
/// @throws SPLRuntimeInvalidArgumentException If lower > l.size().
template<class T, int32_t msize>
inline SPL::blist<T, msize> subSliceU(const SPL::blist<T, msize>& l, uint32_t lower)
{
uint32_t s = l.getUsedSize();
if (lower > s) {
SPLTRACEMSGANDTHROW(SPLRuntimeInvalidArgument, L_ERROR,
SPL_APPLICATION_RUNTIME_INVALID_LIST_SLICE(lower, s), SPL_FUNC_DBG);
}
SPL::blist<T, msize> res;
for (uint32_t i = lower; i < s; i++) {
res.push_back(l[i]);
}
return res;
}
/// Compare a list, element-wise, with a scalar value.
/// @param a List of values.
/// @param b Value to compare against.
/// @return List of comparison results, -1 if the element from the list is smaller,
/// 0 if they are equal, and 1 if the element from the list is larger.
/// @spleval $name = "pairwiseCompare"; $ret = 'list<int32>'; $numArgs = 2; $arg[0] = 'list<@ordered@>'; $arg[1] = '@ordered@'
/// @splnative <ordered T> public list<int32> pairwiseCompare (list<T> a, T b)
template<class T>
inline SPL::list<SPL::int32> pairwiseCompare(const SPL::list<T>& a, const T& b)
{
SPL::list<SPL::int32> res;
res.reserve(a.size());
for (uint32_t i = 0, u = a.size(); i < u; i++) {
const T& l = a[i];
if (l < b) {
res.push_back(-1);
} else if (l == b) {
res.push_back(0);
} else {
res.push_back(1);
}
}
return res;
}
/// Compare a list, element-wise, with a scalar value.
/// @param a List of values.
/// @param b Value to compare against.
/// @return List of comparison results, -1 if the element from the list is smaller,
/// 0 if they are equal, and 1 if the element from the list is larger.
/// @splnative <ordered T>[N] public list<int32>[N] pairwiseCompare (list<T>[N] a, T b)
template<class T, int32_t msize>
inline SPL::blist<SPL::int32, msize> pairwiseCompare(const SPL::blist<T, msize>& a, const T& b)
{
SPL::blist<SPL::int32, msize> res;
for (uint32_t i = 0, u = a.size(); i < u; i++) {
const T& l = a[i];
if (l < b) {
res.push_back(-1);
} else if (l == b) {
res.push_back(0);
} else {
res.push_back(1);
}
}
return res;
}
/// Compare a list, element-wise, with a scalar value.
/// @param a Value to compare against.
/// @param b List of values.
/// @return List of comparison results, 1 if the element from the list is smaller,
/// 0 if they are equal, and -1 if the element from the list is larger.
/// @spleval $name = "pairwiseCompare"; $ret = 'list<int32>'; $numArgs = 2; $arg[0] = '@ordered@'; $arg[1] = 'list<@ordered@>'
/// @splnative <ordered T> public list<int32> pairwiseCompare (T a, list<T> b)
template<class T>
inline SPL::list<SPL::int32> pairwiseCompare(const T& a, const SPL::list<T>& b)
{
SPL::list<SPL::int32> res;
res.reserve(b.size());
for (uint32_t i = 0, u = b.size(); i < u; i++) {
const T& r = b[i];
if (a > r) {
res.push_back(1);
} else if (a == r) {
res.push_back(0);
} else {
res.push_back(-1);
}
}
return res;
}
/// Compare a list, element-wise, with a scalar value.
/// @param a Value to compare against.
/// @param b List of values.
/// @return List of comparison results, 1 if the element from the list is smaller,
/// 0 if they are equal, and -1 if the element from the list is larger.
/// @splnative <ordered T>[N] public list<int32>[N] pairwiseCompare (T a, list<T>[N] b)
template<class T, int32_t msize>
inline SPL::blist<SPL::int32, msize> pairwiseCompare(const T& a, const SPL::blist<T, msize>& b)
{
SPL::list<SPL::int32> res;
res.reserve(b.size());
for (uint32_t i = 0, u = b.size(); i < u; i++) {
const T& r = b[i];
if (a > r) {
res.push_back(1);
} else if (a == r) {
res.push_back(0);
} else {
res.push_back(-1);
}
}
return res;
}
/// Compare two lists, element-wise, up to the end of the shorter list, or of both lists if they are of equal length.
/// @param a First list of values.
/// @param b List of values to compare against.
/// @return List of comparison results, -1 if the element from the first list is smaller,
/// 0 if they are equal, and 1 if the element from the first list is larger.
/// @spleval $name = "pairwiseCompare"; $ret = 'list<int32>'; $numArgs = 2; $arg[0] = 'list<@ordered@>'; $arg[1] = 'list<@ordered@>'
/// @splnative <ordered T> public list<int32> pairwiseCompare (list<T> a, list<T> b)
template<class T>
inline SPL::list<SPL::int32> pairwiseCompare(const SPL::list<T>& a, const SPL::list<T>& b)
{
SPL::list<SPL::int32> res;
uint32_t cnt = std::min(a.size(), b.size());
res.reserve(cnt);
for (uint32_t i = 0; i < cnt; i++) {
const T& l = a[i];
const T& r = b[i];
if (l < r) {
res.push_back(-1);
} else if (l == r) {
res.push_back(0);
} else {
res.push_back(1);
}
}
return res;
}
/// Compare two lists, element-wise, up to the end of the shorter list, or of both lists if they are of equal length.
/// @param a First list of values.
/// @param b List of values to compare against.
/// @return List of comparison results, -1 if the element from the first list is smaller,
/// 0 if they are equal, and 1 if the element from the first list is larger.
/// @splnative <ordered T>[N] public list<int32>[N] pairwiseCompare (list<T>[N] a, list<T>[N] b)
template<class T, int msize>
inline SPL::blist<SPL::int32, msize> pairwiseCompare(const SPL::blist<T, msize>& a,
const SPL::blist<T, msize>& b)
{
SPL::list<SPL::int32> res;
uint32_t cnt = std::min(a.size(), b.size());
for (uint32_t i = 0; i < cnt; i++) {
const T& l = a[i];
const T& r = b[i];
if (l < r) {
res.push_back(-1);
} else if (l == r) {
res.push_back(0);
} else {
res.push_back(1);
}
}
return res;
}
/// Compare two lists, element-wise, and fetch the smaller or equal value,
/// up to the end of the shorter list, or of both lists if they are of equal length.
/// @param a First list.
/// @param b Second list.
/// @return List of the smaller or equal of the two values from the corresponding locations.
/// @spleval $name = "pairwiseMin"; $ret = 'list<@ordered@>'; $numArgs = 2; $arg[0] = 'list<@ordered@>'; $arg[1] = 'list<@ordered@>'
/// @splnative <ordered T> public list<T> pairwiseMin (list<T> a, list<T> b)
template<class T>
inline SPL::list<T> pairwiseMin(const SPL::list<T>& a, const SPL::list<T>& b)
{
const SPL::list<T>& slst = (a.size() < b.size()) ? a : b;
const SPL::list<T>& llst = (&slst == &a) ? b : a;
SPL::list<T> res = slst;
for (uint32_t i = 0, iu = slst.size(); i < iu; ++i) {
if (llst[i] < res[i]) {
res[i] = llst[i];
}
}
return res;
}
/// Compare two lists, element-wise, and fetch the smaller or equal value,
/// up to the end of the shorter list, or of both lists if they are of equal length.
/// @param a First list.
/// @param b Second list.
/// @return List of the smaller or equal of the two values from the corresponding locations.
/// @splnative <ordered T>[N] public list<T>[N] pairwiseMin (list<T>[N] a, list<T>[N] b)
template<class T, int32_t msize>
inline SPL::blist<T, msize> pairwiseMin(const SPL::blist<T, msize>& a,
const SPL::blist<T, msize>& b)
{
const SPL::blist<T, msize>& slst = (a.size() < b.size()) ? a : b;
const SPL::blist<T, msize>& llst = (&slst == &a) ? b : a;
SPL::blist<T, msize> res = slst;
for (uint32_t i = 0, iu = slst.size(); i < iu; ++i) {
if (llst[i] < res[i]) {
res[i] = llst[i];
}
}
return res;
}
/// Compare two lists, element-wise, and fetch the larger or equal value,
/// up to the end of the shorter list, or of both lists if they are of equal length.
/// @param a First list.
/// @param b Second list.
/// @return List of the larger or equal of the two values from the corresponding locations.
/// @spleval $name = "pairwiseMax"; $ret = 'list<@ordered@>'; $numArgs = 2; $arg[0] = 'list<@ordered@>'; $arg[1] = 'list<@ordered@>'
/// @splnative <ordered T> public list<T> pairwiseMax (list<T> a, list<T> b)
template<class T>
inline SPL::list<T> pairwiseMax(const SPL::list<T>& a, const SPL::list<T>& b)
{
const SPL::list<T>& slst = (a.size() < b.size()) ? a : b;
const SPL::list<T>& llst = (&slst == &a) ? b : a;
SPL::list<T> res = slst;
for (uint32_t i = 0, iu = slst.size(); i < iu; ++i) {
if (llst[i] > res[i]) {
res[i] = llst[i];
}
}
return res;
}
/// Compare two lists, element-wise, and fetch the larger or equal value,
/// up to the end of the shorter list, or of both lists if they are of equal length.
/// @param a First list.
/// @param b Second list.
/// @return List of the larger or equal of the two values from the corresponding locations.
/// @splnative <ordered T>[N] public list<T>[N] pairwiseMax (list<T>[N] a, list<T>[N] b)
template<class T, int32_t msize>
SPL::blist<T, msize> pairwiseMax(const SPL::blist<T, msize>& a, const SPL::blist<T, msize>& b)
{
const SPL::blist<T, msize>& slst = (a.size() < b.size()) ? a : b;
const SPL::blist<T, msize>& llst = (&slst == &a) ? b : a;
SPL::blist<T, msize> res = slst;
for (uint32_t i = 0, iu = slst.size(); i < iu; ++i) {
if (llst[i] > res[i]) {
res[i] = llst[i];
}
}
return res;
}
/// Return a list of the keys in the given map. The order of the keys
/// in the returned list is undefined.
/// @note When used in a for loop
/// to iterate over the map, the keys function is optimized to iterate
/// over the map. No elements should be added or removed from the map within
/// the body of the for loop when using this function as the iterator.
/// @param m Input map.
/// @return A list of the keys from the map.
/// @splnative <any K, any V> public list<K> keys (map<K,V> m)
template<class K, class V>
inline SPL::list<K> keys(const SPL::map<K, V>& m)
{
SPL::list<K> ks;
for (typename SPL::map<K, V>::const_iterator it = m.begin(), itEnd = m.end(); it != itEnd;
++it) {
ks.push_back(it->first);
}
return ks;
}
/// Return a list of the keys in the given map. The order of the keys
/// in the returned list is undefined.
/// @note When used in a for loop
/// to iterate over the map, the keys function is optimized to iterate
/// over the map. No elements should be added or removed from the map within
/// the body of the for loop when using this function as the iterator.
/// @param m Input map.
/// @return A list of the keys from the map.
/// @splnative <any K, any V>[N] public list<K> keys (map<K,V>[N] m)
template<class K, class V, int32_t N>
inline SPL::list<K> keys(const SPL::bmap<K, V, N>& m)
{
SPL::list<K> ks;
for (typename SPL::bmap<K, V, N>::const_iterator it = m.begin(), itEnd = m.end(); it != itEnd;
++it) {
ks.push_back(it->first);
}
return ks;
}
}
}
}
#ifndef DOXYGEN_SKIP_FOR_USERS
#endif
#endif /* SPL_RUNTIME_FUNCTION_BUILTIN_COLLECTION_FUNCTIONS_H */
| 37.091947 | 183 | 0.611929 | [
"object"
] |
08001fbd579675ff31399b9e1b4ef500aa4f3678 | 3,616 | h | C | src/util/nondet.h | mina1604/cbmc | bd1d87a2cd93e9fe1b1791b5fbc38d4505cb78b7 | [
"BSD-4-Clause"
] | null | null | null | src/util/nondet.h | mina1604/cbmc | bd1d87a2cd93e9fe1b1791b5fbc38d4505cb78b7 | [
"BSD-4-Clause"
] | 8 | 2017-05-04T10:31:06.000Z | 2019-02-15T10:34:48.000Z | src/util/nondet.h | mina1604/cbmc | bd1d87a2cd93e9fe1b1791b5fbc38d4505cb78b7 | [
"BSD-4-Clause"
] | 4 | 2017-04-25T11:47:41.000Z | 2017-05-16T08:22:25.000Z | /*******************************************************************\
Module: Non-deterministic object init and choice for JBMC
Author: Diffblue Ltd.
\*******************************************************************/
#ifndef CPROVER_JAVA_BYTECODE_NONDET_H
#define CPROVER_JAVA_BYTECODE_NONDET_H
#include "std_code.h"
#include "std_expr.h"
class allocate_objectst;
class symbol_table_baset;
using allocate_local_symbolt =
std::function<symbol_exprt(const typet &type, std::string)>;
/// Same as \ref generate_nondet_int(
/// const mp_integer &min_value,
/// const mp_integer &max_value,
/// const std::string &name_prefix,
/// const typet &int_type,
/// const irep_idt &mode,
/// const source_locationt &source_location,
/// symbol_table_baset &symbol_table,
/// code_blockt &instructions)
/// except the minimum and maximum values are represented as exprts.
symbol_exprt generate_nondet_int(
const exprt &min_value_expr,
const exprt &max_value_expr,
const std::string &basename_prefix,
const source_locationt &source_location,
allocate_objectst &allocate_objects,
code_blockt &instructions);
symbol_exprt generate_nondet_int(
const exprt &min_value_expr,
const exprt &max_value_expr,
const std::string &basename_prefix,
const source_locationt &source_location,
const allocate_local_symbolt &alocate_local_symbol,
code_blockt &instructions);
/// Gets a fresh nondet choice in range (min_value, max_value). GOTO generated
/// resembles:
/// ```
/// int_type name_prefix::nondet_int = NONDET(int_type)
/// ASSUME(name_prefix::nondet_int >= min_value)
/// ASSUME(name_prefix::nondet_int <= max_value)
/// ```
/// \param min_value: Minimum value (inclusive) of returned int.
/// \param max_value: Maximum value (inclusive) of returned int.
/// \param basename_prefix: Basename prefix for the fresh symbol name generated.
/// \param int_type: The type of the int used to non-deterministically choose
/// one of the switch cases.
/// \param allocate_objects: Handles allocation of new objects.
/// \param source_location: The location to mark the generated int with.
/// \param [out] instructions: Output instructions are written to
/// 'instructions'. These declare, nondet-initialise and range-constrain (with
/// assume statements) a fresh integer.
/// \return Returns a symbol expression for the resulting integer.
symbol_exprt generate_nondet_int(
const mp_integer &min_value,
const mp_integer &max_value,
const std::string &basename_prefix,
const typet &int_type,
const source_locationt &source_location,
allocate_objectst &allocate_objects,
code_blockt &instructions);
typedef std::vector<codet> alternate_casest;
/// Pick nondeterministically between imperative actions 'switch_cases'.
/// \param name_prefix: Name prefix for fresh symbols (should be function id)
/// \param switch_cases: List of codet objects to execute in each switch case.
/// \param int_type: The type of the int used to non-deterministically choose
/// one of the switch cases.
/// \param mode: Mode (language) of the symbol to be generated.
/// \param source_location: The location to mark the generated int with.
/// \param symbol_table: The global symbol table.
/// \return Returns a nondet-switch choosing between switch_cases. The resulting
/// switch block has no default case.
code_blockt generate_nondet_switch(
const irep_idt &name_prefix,
const alternate_casest &switch_cases,
const typet &int_type,
const irep_idt &mode,
const source_locationt &source_location,
symbol_table_baset &symbol_table);
#endif // CPROVER_JAVA_BYTECODE_NONDET_H
| 38.063158 | 80 | 0.738385 | [
"object",
"vector"
] |
0801a0b3db1ab501356152af255aec306203aae8 | 1,572 | h | C | src/BerTlv.h | huckor/BER_TLV | e7ccc1981368ac5f1f5bdcd6fa6f04e5c6ff049f | [
"MIT"
] | 2 | 2017-03-15T18:05:18.000Z | 2021-05-14T05:16:46.000Z | src/BerTlv.h | huckor/BER_TLV | e7ccc1981368ac5f1f5bdcd6fa6f04e5c6ff049f | [
"MIT"
] | 1 | 2017-03-15T18:37:26.000Z | 2017-03-20T14:19:08.000Z | src/BerTlv.h | huckor/BER_TLV | e7ccc1981368ac5f1f5bdcd6fa6f04e5c6ff049f | [
"MIT"
] | null | null | null | #ifndef BerTlv_h
#define BerTlv_h
#include <vector>
#include <string>
class BerTlv
{
public:
BerTlv() { _TlvStruct = std::vector<unsigned char>(0); }
~BerTlv() { _TlvStruct.clear(); }
std::vector<unsigned char> GetTlv() { return _TlvStruct; }
void SetTlv(std::vector<unsigned char> TlvStruct) { _TlvStruct = TlvStruct; }
short Add(std::string Tag, std::vector<unsigned char> Value);
short GetValue(std::string Tag, std::vector<unsigned char> *ValueOfTag, bool CheckNestedTags);
void SetTwoBytesTags(std::vector<std::string> Tags);
void SetThreeBytesTags(std::vector<std::string> Tags);
void SetFourBytesTags(std::vector<std::string> Tags);
void SetNestedTags(std::vector<std::string> Tags) { _NestedTags = Tags; }
short DumpAllTagsAndValues(std::string *Output, bool ParseNestedTags);
private:
std::vector<unsigned char> _TlvStruct;
std::vector<unsigned char> _TwoBytesTags;
std::vector<unsigned char> _ThreeBytesTags;
std::vector<unsigned char> _FourBytesTags;
std::vector<std::string> _NestedTags;
std::vector<unsigned char> CalcSizeOfValue(std::vector<unsigned char> Value);
short GetSizeOfValue(size_t StartPosition, int *SizeOfValue);
short GetTagLength(size_t StartPosition);
short DumpTlvInsideTag(size_t StartPosition, int Length, std::string *Output);
bool IsTagNested(size_t StartPosition, short TagSize);
short GetValueFromTlv(size_t StartPosition, int Length, std::vector<unsigned char> Tag, std::vector<unsigned char> *Output);
};
#endif /* BerTlv_h */
| 40.307692 | 128 | 0.722646 | [
"vector"
] |
0803c0713888b8af6908249a991acae4d78a96d5 | 85,496 | h | C | TemplePlus/temple_enums.h | anatoliy-savchak/TemplePlus | 50922bb14cc2d7dcf8fceeccf45c3b905c1b512f | [
"MIT"
] | 2 | 2019-02-25T21:06:18.000Z | 2019-02-25T21:06:18.000Z | TemplePlus/temple_enums.h | anatoliy-savchak/TemplePlus | 50922bb14cc2d7dcf8fceeccf45c3b905c1b512f | [
"MIT"
] | null | null | null | TemplePlus/temple_enums.h | anatoliy-savchak/TemplePlus | 50922bb14cc2d7dcf8fceeccf45c3b905c1b512f | [
"MIT"
] | null | null | null | #pragma once
#pragma region feats
enum feat_enums : uint32_t {
FEAT_ACROBATIC = 0x0,
FEAT_AGILE = 0x1,
FEAT_ALERTNESS = 0x2,
FEAT_ANIMAL_AFFINITY = 0x3,
FEAT_ARMOR_PROFICIENCY_LIGHT = 0x4,
FEAT_ARMOR_PROFICIENCY_MEDIUM = 0x5,
FEAT_ARMOR_PROFICIENCY_HEAVY = 0x6,
FEAT_ATHLETIC = 0x7,
FEAT_AUGMENT_SUMMONING = 0x8,
FEAT_BLIND_FIGHT = 0x9,
FEAT_BREW_POTION = 0xA,
FEAT_CLEAVE = 0xB,
FEAT_COMBAT_CASTING = 0xC,
FEAT_COMBAT_EXPERTISE = 0xD,
FEAT_CRAFT_MAGIC_ARMS_AND_ARMOR = 0xE,
FEAT_CRAFT_ROD = 0xF,
FEAT_CRAFT_STAFF = 0x10,
FEAT_CRAFT_WAND = 0x11,
FEAT_CRAFT_WONDROUS_ITEM = 0x12,
FEAT_DECEITFUL = 0x13,
FEAT_DEFT_HANDS = 0x14,
FEAT_DIEHARD = 0x15,
FEAT_DILIGENT = 0x16,
FEAT_DEFLECT_ARROWS = 0x17,
FEAT_DODGE = 0x18,
FEAT_EMPOWER_SPELL = 0x19,
FEAT_ENDURANCE = 0x1A,
FEAT_ENLARGE_SPELL = 0x1B,
FEAT_ESCHEW_MATERIALS = 0x1C,
FEAT_EXOTIC_WEAPON_PROFICIENCY_HALFLING_KAMA = 0x1D,
FEAT_EXOTIC_WEAPON_PROFICIENCY_KUKRI = 0x1E,
FEAT_EXOTIC_WEAPON_PROFICIENCY_HALFLING_NUNCHAKU = 0x1F,
FEAT_EXOTIC_WEAPON_PROFICIENCY_HALFLING_SIANGHAM = 0x20,
FEAT_EXOTIC_WEAPON_PROFICIENCY_KAMA = 0x21,
FEAT_EXOTIC_WEAPON_PROFICIENCY_NUNCHAKU = 0x22,
FEAT_EXOTIC_WEAPON_PROFICIENCY_SIANGHAM = 0x23,
FEAT_EXOTIC_WEAPON_PROFICIENCY_BASTARD_SWORD = 0x24,
FEAT_EXOTIC_WEAPON_PROFICIENCY_DWARVEN_WARAXE = 0x25,
FEAT_EXOTIC_WEAPON_PROFICIENCY_GNOME_HOOKED_HAMMER = 0x26,
FEAT_EXOTIC_WEAPON_PROFICIENCY_ORC_DOUBLE_AXE = 0x27,
FEAT_EXOTIC_WEAPON_PROFICIENCY_SPIKE_CHAIN = 0x28,
FEAT_EXOTIC_WEAPON_PROFICIENCY_DIRE_FLAIL = 0x29,
FEAT_EXOTIC_WEAPON_PROFICIENCY_TWO_BLADED_SWORD = 0x2A,
FEAT_EXOTIC_WEAPON_PROFICIENCY_DWARVEN_URGROSH = 0x2B,
FEAT_EXOTIC_WEAPON_PROFICIENCY_HAND_CROSSBOW = 0x2C,
FEAT_EXOTIC_WEAPON_PROFICIENCY_SHURIKEN = 0x2D,
FEAT_EXOTIC_WEAPON_PROFICIENCY_WHIP = 0x2E,
FEAT_EXOTIC_WEAPON_PROFICIENCY_REPEATING_CROSSBOW = 0x2F,
FEAT_EXOTIC_WEAPON_PROFICIENCY_NET = 0x30,
FEAT_EXTEND_SPELL = 0x31,
FEAT_EXTRA_TURNING = 0x32,
FEAT_FAR_SHOT = 0x33,
FEAT_FORGE_RING = 0x34,
FEAT_GREAT_CLEAVE = 0x35,
FEAT_GREAT_FORTITUDE = 0x36,
FEAT_GREATER_SPELL_FOCUS_ABJURATION = 0x37,
FEAT_GREATER_SPELL_FOCUS_CONJURATION = 0x38,
FEAT_GREATER_SPELL_FOCUS_DIVINATION = 0x39,
FEAT_GREATER_SPELL_FOCUS_ENCHANTMENT = 0x3A,
FEAT_GREATER_SPELL_FOCUS_EVOCATION = 0x3B,
FEAT_GREATER_SPELL_FOCUS_ILLUSION = 0x3C,
FEAT_GREATER_SPELL_FOCUS_NECROMANCY = 0x3D,
FEAT_GREATER_SPELL_FOCUS_TRANSMUTATION = 0x3E,
FEAT_GREATER_SPELL_PENETRATION = 0x3F,
FEAT_GREATER_TWO_WEAPON_FIGHTING = 0x40,
FEAT_GREATER_WEAPON_FOCUS_GAUNTLET = 65,
FEAT_GREATER_WEAPON_FOCUS_UNARMED_STRIKE_MEDIUM_SIZED_BEING = 0x42,
FEAT_GREATER_WEAPON_FOCUS_UNARMED_STRIKE_SMALL_BEING = 0x43,
FEAT_GREATER_WEAPON_FOCUS_DAGGER = 0x44,
FEAT_GREATER_WEAPON_FOCUS_PUNCHING_DAGGER = 0x45,
FEAT_GREATER_WEAPON_FOCUS_SPIKED_GAUNTLET = 0x46,
FEAT_GREATER_WEAPON_FOCUS_LIGHT_MACE = 0x47,
FEAT_GREATER_WEAPON_FOCUS_SICKLE = 0x48,
FEAT_GREATER_WEAPON_FOCUS_CLUB = 0x49,
FEAT_GREATER_WEAPON_FOCUS_HALFSPEAR = 0x4A,
FEAT_GREATER_WEAPON_FOCUS_HEAVY_MACE = 0x4B,
FEAT_GREATER_WEAPON_FOCUS_MORNINGSTAR = 0x4C,
FEAT_GREATER_WEAPON_FOCUS_QUARTERSTAFF = 0x4D,
FEAT_GREATER_WEAPON_FOCUS_SHORTSPEAR = 0x4E,
FEAT_GREATER_WEAPON_FOCUS_LIGHT_CROSSBOW = 0x4F,
FEAT_GREATER_WEAPON_FOCUS_DART = 0x50,
FEAT_GREATER_WEAPON_FOCUS_SLING = 0x51,
FEAT_GREATER_WEAPON_FOCUS_HEAVY_CROSSBOW = 0x52,
FEAT_GREATER_WEAPON_FOCUS_JAVELIN = 0x53,
FEAT_GREATER_WEAPON_FOCUS_THROWING_AXE = 0x54,
FEAT_GREATER_WEAPON_FOCUS_LIGHT_HAMMER = 0x55,
FEAT_GREATER_WEAPON_FOCUS_HANDAXE = 0x56,
FEAT_GREATER_WEAPON_FOCUS_LIGHT_LANCE = 0x57,
FEAT_GREATER_WEAPON_FOCUS_LIGHT_PICK = 0x58,
FEAT_GREATER_WEAPON_FOCUS_SAP = 0x59,
FEAT_GREATER_WEAPON_FOCUS_SHORT_SWORD = 0x5A,
FEAT_GREATER_WEAPON_FOCUS_BATTLEAXE = 0x5B,
FEAT_GREATER_WEAPON_FOCUS_LIGHT_FLAIL = 0x5C,
FEAT_GREATER_WEAPON_FOCUS_HEAVY_LANCE = 0x5D,
FEAT_GREATER_WEAPON_FOCUS_LONGSWORD = 0x5E,
FEAT_GREATER_WEAPON_FOCUS_HEAVY_PICK = 0x5F,
FEAT_GREATER_WEAPON_FOCUS_RAPIER = 0x60,
FEAT_GREATER_WEAPON_FOCUS_SCIMITAR = 0x61,
FEAT_GREATER_WEAPON_FOCUS_TRIDENT = 0x62,
FEAT_GREATER_WEAPON_FOCUS_WARHAMMER = 0x63,
FEAT_GREATER_WEAPON_FOCUS_FALCHION = 0x64,
FEAT_GREATER_WEAPON_FOCUS_HEAVY_FLAIL = 0x65,
FEAT_GREATER_WEAPON_FOCUS_GLAIVE = 0x66,
FEAT_GREATER_WEAPON_FOCUS_GREATAXE = 0x67,
FEAT_GREATER_WEAPON_FOCUS_GREATCLUB = 0x68,
FEAT_GREATER_WEAPON_FOCUS_GREATSWORD = 0x69,
FEAT_GREATER_WEAPON_FOCUS_GUISARME = 0x6A,
FEAT_GREATER_WEAPON_FOCUS_HALBERD = 0x6B,
FEAT_GREATER_WEAPON_FOCUS_LONGSPEAR = 0x6C,
FEAT_GREATER_WEAPON_FOCUS_RANSEUR = 0x6D,
FEAT_GREATER_WEAPON_FOCUS_SCYTHE = 0x6E,
FEAT_GREATER_WEAPON_FOCUS_SHORTBOW = 0x6F,
FEAT_GREATER_WEAPON_FOCUS_COMPOSITE_SHORTBOW = 0x70,
FEAT_GREATER_WEAPON_FOCUS_LONGBOW = 0x71,
FEAT_GREATER_WEAPON_FOCUS_COMPOSITE_LONGBOW = 0x72,
FEAT_GREATER_WEAPON_FOCUS_HALFLING_KAMA = 0x73,
FEAT_GREATER_WEAPON_FOCUS_KUKRI = 0x74,
FEAT_GREATER_WEAPON_FOCUS_HALFLING_NUNCHAKU = 0x75,
FEAT_GREATER_WEAPON_FOCUS_HALFLING_SIANGHAM = 0x76,
FEAT_GREATER_WEAPON_FOCUS_KAMA = 0x77,
FEAT_GREATER_WEAPON_FOCUS_NUNCHAKU = 0x78,
FEAT_GREATER_WEAPON_FOCUS_SIANGHAM = 0x79,
FEAT_GREATER_WEAPON_FOCUS_BASTARD_SWORD = 0x7A,
FEAT_GREATER_WEAPON_FOCUS_DWARVEN_WARAXE = 0x7B,
FEAT_GREATER_WEAPON_FOCUS_GNOME_HOOKED_HAMMER = 0x7C,
FEAT_GREATER_WEAPON_FOCUS_ORC_DOUBLE_AXE = 0x7D,
FEAT_GREATER_WEAPON_FOCUS_SPIKE_CHAIN = 0x7E,
FEAT_GREATER_WEAPON_FOCUS_DIRE_FLAIL = 0x7F,
FEAT_GREATER_WEAPON_FOCUS_TWO_BLADED_SWORD = 0x80,
FEAT_GREATER_WEAPON_FOCUS_DWARVEN_URGROSH = 0x81,
FEAT_GREATER_WEAPON_FOCUS_HAND_CROSSBOW = 0x82,
FEAT_GREATER_WEAPON_FOCUS_SHURIKEN = 0x83,
FEAT_GREATER_WEAPON_FOCUS_WHIP = 0x84,
FEAT_GREATER_WEAPON_FOCUS_REPEATING_CROSSBOW = 0x85,
FEAT_GREATER_WEAPON_FOCUS_NET = 0x86,
FEAT_GREATER_WEAPON_FOCUS_GRAPPLE = 0x87,
FEAT_GREATER_WEAPON_FOCUS_RAY = 0x88,
FEAT_GREATER_WEAPON_SPECIALIZATION = 0x89,
FEAT_HEIGHTEN_SPELL = 0x8A,
FEAT_IMPROVED_BULL_RUSH = 0x8B,
FEAT_IMPROVED_COUNTERSPELL = 0x8C,
FEAT_IMPROVED_CRITICAL_GAUNTLET = 141,
FEAT_IMPROVED_CRITICAL_UNARMED_STRIKE_MEDIUM_SIZED_BEING = 0x8E,
FEAT_IMPROVED_CRITICAL_UNARMED_STRIKE_SMALL_BEING = 0x8F,
FEAT_IMPROVED_CRITICAL_DAGGER = 0x90,
FEAT_IMPROVED_CRITICAL_PUNCHING_DAGGER = 0x91,
FEAT_IMPROVED_CRITICAL_SPIKED_GAUNTLET = 0x92,
FEAT_IMPROVED_CRITICAL_LIGHT_MACE = 0x93,
FEAT_IMPROVED_CRITICAL_SICKLE = 0x94,
FEAT_IMPROVED_CRITICAL_CLUB = 0x95,
FEAT_IMPROVED_CRITICAL_HALFSPEAR = 0x96,
FEAT_IMPROVED_CRITICAL_HEAVY_MACE = 0x97,
FEAT_IMPROVED_CRITICAL_MORNINGSTAR = 0x98,
FEAT_IMPROVED_CRITICAL_QUARTERSTAFF = 0x99,
FEAT_IMPROVED_CRITICAL_SHORTSPEAR = 0x9A,
FEAT_IMPROVED_CRITICAL_LIGHT_CROSSBOW = 0x9B,
FEAT_IMPROVED_CRITICAL_DART = 0x9C,
FEAT_IMPROVED_CRITICAL_SLING = 0x9D,
FEAT_IMPROVED_CRITICAL_HEAVY_CROSSBOW = 0x9E,
FEAT_IMPROVED_CRITICAL_JAVELIN = 0x9F,
FEAT_IMPROVED_CRITICAL_THROWING_AXE = 0xA0,
FEAT_IMPROVED_CRITICAL_LIGHT_HAMMER = 0xA1,
FEAT_IMPROVED_CRITICAL_HANDAXE = 0xA2,
FEAT_IMPROVED_CRITICAL_LIGHT_LANCE = 0xA3,
FEAT_IMPROVED_CRITICAL_LIGHT_PICK = 0xA4,
FEAT_IMPROVED_CRITICAL_SAP = 0xA5,
FEAT_IMPROVED_CRITICAL_SHORT_SWORD = 0xA6,
FEAT_IMPROVED_CRITICAL_BATTLEAXE = 0xA7,
FEAT_IMPROVED_CRITICAL_LIGHT_FLAIL = 0xA8,
FEAT_IMPROVED_CRITICAL_HEAVY_LANCE = 0xA9,
FEAT_IMPROVED_CRITICAL_LONGSWORD = 0xAA,
FEAT_IMPROVED_CRITICAL_HEAVY_PICK = 0xAB,
FEAT_IMPROVED_CRITICAL_RAPIER = 0xAC,
FEAT_IMPROVED_CRITICAL_SCIMITAR = 0xAD,
FEAT_IMPROVED_CRITICAL_TRIDENT = 0xAE,
FEAT_IMPROVED_CRITICAL_WARHAMMER = 0xAF,
FEAT_IMPROVED_CRITICAL_FALCHION = 0xB0,
FEAT_IMPROVED_CRITICAL_HEAVY_FLAIL = 0xB1,
FEAT_IMPROVED_CRITICAL_GLAIVE = 0xB2,
FEAT_IMPROVED_CRITICAL_GREATAXE = 0xB3,
FEAT_IMPROVED_CRITICAL_GREATCLUB = 0xB4,
FEAT_IMPROVED_CRITICAL_GREATSWORD = 0xB5,
FEAT_IMPROVED_CRITICAL_GUISARME = 0xB6,
FEAT_IMPROVED_CRITICAL_HALBERD = 0xB7,
FEAT_IMPROVED_CRITICAL_LONGSPEAR = 0xB8,
FEAT_IMPROVED_CRITICAL_RANSEUR = 0xB9,
FEAT_IMPROVED_CRITICAL_SCYTHE = 0xBA,
FEAT_IMPROVED_CRITICAL_SHORTBOW = 0xBB,
FEAT_IMPROVED_CRITICAL_COMPOSITE_SHORTBOW = 0xBC,
FEAT_IMPROVED_CRITICAL_LONGBOW = 0xBD,
FEAT_IMPROVED_CRITICAL_COMPOSITE_LONGBOW = 0xBE,
FEAT_IMPROVED_CRITICAL_HALFLING_KAMA = 0xBF,
FEAT_IMPROVED_CRITICAL_KUKRI = 0xC0,
FEAT_IMPROVED_CRITICAL_HALFLING_NUNCHAKU = 0xC1,
FEAT_IMPROVED_CRITICAL_HALFLING_SIANGHAM = 0xC2,
FEAT_IMPROVED_CRITICAL_KAMA = 0xC3,
FEAT_IMPROVED_CRITICAL_NUNCHAKU = 0xC4,
FEAT_IMPROVED_CRITICAL_SIANGHAM = 0xC5,
FEAT_IMPROVED_CRITICAL_BASTARD_SWORD = 0xC6,
FEAT_IMPROVED_CRITICAL_DWARVEN_WARAXE = 0xC7,
FEAT_IMPROVED_CRITICAL_GNOME_HOOKED_HAMMER = 0xC8,
FEAT_IMPROVED_CRITICAL_ORC_DOUBLE_AXE = 0xC9,
FEAT_IMPROVED_CRITICAL_SPIKE_CHAIN = 0xCA,
FEAT_IMPROVED_CRITICAL_DIRE_FLAIL = 0xCB,
FEAT_IMPROVED_CRITICAL_TWO_BLADED_SWORD = 0xCC,
FEAT_IMPROVED_CRITICAL_DWARVEN_URGROSH = 0xCD,
FEAT_IMPROVED_CRITICAL_HAND_CROSSBOW = 0xCE,
FEAT_IMPROVED_CRITICAL_SHURIKEN = 0xCF,
FEAT_IMPROVED_CRITICAL_WHIP = 0xD0,
FEAT_IMPROVED_CRITICAL_REPEATING_CROSSBOW = 0xD1,
FEAT_IMPROVED_CRITICAL_NET = 0xD2,
FEAT_IMPROVED_DISARM = 0xD3,
FEAT_IMPROVED_FEINT = 0xD4,
FEAT_IMPROVED_GRAPPLE = 0xD5,
FEAT_IMPROVED_INITIATIVE = 0xD6,
FEAT_IMPROVED_OVERRUN = 0xD7,
FEAT_IMPROVED_SHIELD_BASH = 0xD8,
FEAT_IMPROVED_TRIP = 0xD9,
FEAT_IMPROVED_TWO_WEAPON_FIGHTING = 0xDA,
FEAT_IMPROVED_TURNING = 0xDB,
FEAT_IMPROVED_UNARMED_STRIKE = 0xDC,
FEAT_IMPROVED_UNCANNY_DODGE = 0xDD,
FEAT_INVESTIGATOR = 0xDE,
FEAT_IRON_WILL = 0xDF,
FEAT_LEADERSHIP = 0xE0,
FEAT_LIGHTNING_REFLEXES = 0xE1,
FEAT_MAGICAL_AFFINITY = 0xE2,
FEAT_MANYSHOT = 0xE3,
FEAT_MARTIAL_WEAPON_PROFICIENCY_THROWING_AXE = 0xE4,
FEAT_MARTIAL_WEAPON_PROFICIENCY_LIGHT_HAMMER = 0xE5,
FEAT_MARTIAL_WEAPON_PROFICIENCY_HANDAXE = 0xE6,
FEAT_MARTIAL_WEAPON_PROFICIENCY_LIGHT_LANCE = 0xE7,
FEAT_MARTIAL_WEAPON_PROFICIENCY_LIGHT_PICK = 0xE8,
FEAT_MARTIAL_WEAPON_PROFICIENCY_SAP = 0xE9,
FEAT_MARTIAL_WEAPON_PROFICIENCY_SHORT_SWORD = 0xEA,
FEAT_MARTIAL_WEAPON_PROFICIENCY_BATTLEAXE = 0xEB,
FEAT_MARTIAL_WEAPON_PROFICIENCY_LIGHT_FLAIL = 0xEC,
FEAT_MARTIAL_WEAPON_PROFICIENCY_HEAVY_LANCE = 0xED,
FEAT_MARTIAL_WEAPON_PROFICIENCY_LONGSWORD = 0xEE,
FEAT_MARTIAL_WEAPON_PROFICIENCY_HEAVY_PICK = 0xEF,
FEAT_MARTIAL_WEAPON_PROFICIENCY_RAPIER = 0xF0,
FEAT_MARTIAL_WEAPON_PROFICIENCY_SCIMITAR = 0xF1,
FEAT_MARTIAL_WEAPON_PROFICIENCY_TRIDENT = 0xF2,
FEAT_MARTIAL_WEAPON_PROFICIENCY_WARHAMMER = 0xF3,
FEAT_MARTIAL_WEAPON_PROFICIENCY_FALCHION = 0xF4,
FEAT_MARTIAL_WEAPON_PROFICIENCY_HEAVY_FLAIL = 0xF5,
FEAT_MARTIAL_WEAPON_PROFICIENCY_GLAIVE = 0xF6,
FEAT_MARTIAL_WEAPON_PROFICIENCY_GREATAXE = 0xF7,
FEAT_MARTIAL_WEAPON_PROFICIENCY_GREATCLUB = 0xF8,
FEAT_MARTIAL_WEAPON_PROFICIENCY_GREATSWORD = 0xF9,
FEAT_MARTIAL_WEAPON_PROFICIENCY_GUISARME = 0xFA,
FEAT_MARTIAL_WEAPON_PROFICIENCY_HALBERD = 0xFB,
FEAT_MARTIAL_WEAPON_PROFICIENCY_LONGSPEAR = 0xFC,
FEAT_MARTIAL_WEAPON_PROFICIENCY_RANSEUR = 0xFD,
FEAT_MARTIAL_WEAPON_PROFICIENCY_SCYTHE = 0xFE,
FEAT_MARTIAL_WEAPON_PROFICIENCY_SHORTBOW = 0xFF,
FEAT_MARTIAL_WEAPON_PROFICIENCY_COMPOSITE_SHORTBOW = 0x100,
FEAT_MARTIAL_WEAPON_PROFICIENCY_LONGBOW = 0x101,
FEAT_MARTIAL_WEAPON_PROFICIENCY_COMPOSITE_LONGBOW = 0x102,
FEAT_MAXIMIZE_SPELL = 0x103,
FEAT_MOBILITY = 0x104,
FEAT_MOUNTED_ARCHERY = 0x105,
FEAT_MOUNTED_COMBAT = 0x106,
FEAT_NATURAL_SPELL = 0x107,
FEAT_NEGOTIATOR = 0x108,
FEAT_NIMBLE_FINGERS = 0x109,
FEAT_PERSUASIVE = 0x10A,
FEAT_POINT_BLANK_SHOT = 0x10B,
FEAT_POWER_ATTACK = 0x10C,
FEAT_PRECISE_SHOT = 0x10D,
FEAT_QUICK_DRAW = 0x10E,
FEAT_QUICKEN_SPELL = 0x10F,
FEAT_RAPID_SHOT = 0x110,
FEAT_RAPID_RELOAD = 0x111,
FEAT_RIDE_BY_ATTACK = 0x112,
FEAT_RUN = 0x113,
FEAT_SCRIBE_SCROLL = 0x114,
FEAT_SELF_SUFFICIENT = 0x115,
FEAT_SHIELD_PROFICIENCY = 0x116,
FEAT_SHOT_ON_THE_RUN = 0x117,
FEAT_SILENT_SPELL = 0x118,
FEAT_SIMPLE_WEAPON_PROFICIENCY = 281,
FEAT_SKILL_FOCUS_ALCHEMY = 282,
FEAT_SKILL_FOCUS_ANIMAL_EMPATHY = 0x11B,
FEAT_SKILL_FOCUS_APPRAISE = 0x11C,
FEAT_SKILL_FOCUS_BALANCE = 0x11D,
FEAT_SKILL_FOCUS_BLUFF = 0x11E,
FEAT_SKILL_FOCUS_CLIMB = 0x11F,
FEAT_SKILL_FOCUS_CONCENTRATION = 0x120,
FEAT_SKILL_FOCUS_CRAFT = 0x121,
FEAT_SKILL_FOCUS_DECIPHER_SCRIPT = 0x122,
FEAT_SKILL_FOCUS_DIPLOMACY = 0x123,
FEAT_SKILL_FOCUS_DISABLE_DEVICE = 0x124,
FEAT_SKILL_FOCUS_DISGUISE = 0x125,
FEAT_SKILL_FOCUS_ESCAPE_ARTIST = 0x126,
FEAT_SKILL_FOCUS_FORGERY = 0x127,
FEAT_SKILL_FOCUS_GATHER_INFORMATION = 0x128,
FEAT_SKILL_FOCUS_HANDLE_ANIMAL = 0x129,
FEAT_SKILL_FOCUS_HEAL = 0x12A,
FEAT_SKILL_FOCUS_HIDE = 0x12B,
FEAT_SKILL_FOCUS_INNUENDO = 0x12C,
FEAT_SKILL_FOCUS_INTIMIDATE = 0x12D,
FEAT_SKILL_FOCUS_INTUIT_DIRECTION = 0x12E,
FEAT_SKILL_FOCUS_JUMP = 0x12F,
FEAT_SKILL_FOCUS_KNOWLEDGE = 0x130,
FEAT_SKILL_FOCUS_LISTEN = 0x131,
FEAT_SKILL_FOCUS_MOVE_SILENTLY = 0x132,
FEAT_SKILL_FOCUS_OPEN_LOCK = 0x133,
FEAT_SKILL_FOCUS_PERFORMANCE = 0x134,
FEAT_SKILL_FOCUS_SLIGHT_OF_HAND = 0x135,
FEAT_SKILL_FOCUS_PROFESSION = 0x136,
FEAT_SKILL_FOCUS_READ_LIPS = 0x137,
FEAT_SKILL_FOCUS_RIDE = 0x138,
FEAT_SKILL_FOCUS_SCRY = 0x139,
FEAT_SKILL_FOCUS_SEARCH = 0x13A,
FEAT_SKILL_FOCUS_SENSE_MOTIVE = 0x13B,
FEAT_SKILL_FOCUS_SPEAK_LANGUAGE = 0x13C,
FEAT_SKILL_FOCUS_SPELLCRAFT = 0x13D,
FEAT_SKILL_FOCUS_SPOT = 0x13E,
FEAT_SKILL_FOCUS_SWIM = 0x13F,
FEAT_SKILL_FOCUS_TUMBLE = 0x140,
FEAT_SKILL_FOCUS_USE_MAGIC_DEVICE = 0x141,
FEAT_SKILL_FOCUS_USE_ROPE = 0x142,
FEAT_SKILL_FOCUS_SURVIVAL = 323,
FEAT_SNATCH_ARROWS = 0x144,
FEAT_SPELL_FOCUS_ABJURATION = 0x145,
FEAT_SPELL_FOCUS_CONJURATION = 0x146,
FEAT_SPELL_FOCUS_DIVINATION = 0x147,
FEAT_SPELL_FOCUS_ENCHANTMENT = 0x148,
FEAT_SPELL_FOCUS_EVOCATION = 0x149,
FEAT_SPELL_FOCUS_ILLUSION = 0x14A,
FEAT_SPELL_FOCUS_NECROMANCY = 0x14B,
FEAT_SPELL_FOCUS_TRANSMUTATION = 0x14C,
FEAT_SPELL_MASTERY = 0x14D,
FEAT_SPELL_PENETRATION = 0x14E,
FEAT_SPIRITED_CHARGE = 0x14F,
FEAT_SPRING_ATTACK = 0x150,
FEAT_STEALTHY = 0x151,
FEAT_STILL_SPELL = 0x152,
FEAT_STUNNING_FIST = 0x153,
FEAT_IMPROVED_SUNDER = 340,
FEAT_TOUGHNESS = 0x155,
FEAT_TOWER_SHIELD_PROFICIENCY = 0x156,
FEAT_TRACK = 0x157,
FEAT_TRAMPLE = 0x158,
FEAT_TWO_WEAPON_FIGHTING = 0x159,
FEAT_TWO_WEAPON_DEFENSE = 0x15A,
FEAT_WEAPON_FINESSE_GAUNTLET = 0x15B,
FEAT_WEAPON_FINESSE_UNARMED_STRIKE_MEDIUM_SIZED_BEING = 0x15C,
FEAT_WEAPON_FINESSE_UNARMED_STRIKE_SMALL_BEING = 0x15D,
FEAT_WEAPON_FINESSE_DAGGER = 0x15E,
FEAT_WEAPON_FINESSE_PUNCHING_DAGGER = 0x15F,
FEAT_WEAPON_FINESSE_SPIKED_GAUNTLET = 0x160,
FEAT_WEAPON_FINESSE_LIGHT_MACE = 0x161,
FEAT_WEAPON_FINESSE_SICKLE = 0x162,
FEAT_WEAPON_FINESSE_CLUB = 0x163,
FEAT_WEAPON_FINESSE_HALFSPEAR = 0x164,
FEAT_WEAPON_FINESSE_HEAVY_MACE = 0x165,
FEAT_WEAPON_FINESSE_MORNINGSTAR = 0x166,
FEAT_WEAPON_FINESSE_QUARTERSTAFF = 0x167,
FEAT_WEAPON_FINESSE_SHORTSPEAR = 0x168,
FEAT_WEAPON_FINESSE_LIGHT_CROSSBOW = 0x169,
FEAT_WEAPON_FINESSE_DART = 0x16A,
FEAT_WEAPON_FINESSE_SLING = 0x16B,
FEAT_WEAPON_FINESSE_HEAVY_CROSSBOW = 0x16C,
FEAT_WEAPON_FINESSE_JAVELIN = 0x16D,
FEAT_WEAPON_FINESSE_THROWING_AXE = 0x16E,
FEAT_WEAPON_FINESSE_LIGHT_HAMMER = 0x16F,
FEAT_WEAPON_FINESSE_HANDAXE = 0x170,
FEAT_WEAPON_FINESSE_LIGHT_LANCE = 0x171,
FEAT_WEAPON_FINESSE_LIGHT_PICK = 0x172,
FEAT_WEAPON_FINESSE_SAP = 0x173,
FEAT_WEAPON_FINESSE_SHORT_SWORD = 0x174,
FEAT_WEAPON_FINESSE_BATTLEAXE = 0x175,
FEAT_WEAPON_FINESSE_LIGHT_FLAIL = 0x176,
FEAT_WEAPON_FINESSE_HEAVY_LANCE = 0x177,
FEAT_WEAPON_FINESSE_LONGSWORD = 0x178,
FEAT_WEAPON_FINESSE_HEAVY_PICK = 0x179,
FEAT_WEAPON_FINESSE_RAPIER = 0x17A,
FEAT_WEAPON_FINESSE_SCIMITAR = 0x17B,
FEAT_WEAPON_FINESSE_TRIDENT = 0x17C,
FEAT_WEAPON_FINESSE_WARHAMMER = 0x17D,
FEAT_WEAPON_FINESSE_FALCHION = 0x17E,
FEAT_WEAPON_FINESSE_HEAVY_FLAIL = 0x17F,
FEAT_WEAPON_FINESSE_GLAIVE = 0x180,
FEAT_WEAPON_FINESSE_GREATAXE = 0x181,
FEAT_WEAPON_FINESSE_GREATCLUB = 0x182,
FEAT_WEAPON_FINESSE_GREATSWORD = 0x183,
FEAT_WEAPON_FINESSE_GUISARME = 0x184,
FEAT_WEAPON_FINESSE_HALBERD = 0x185,
FEAT_WEAPON_FINESSE_LONGSPEAR = 0x186,
FEAT_WEAPON_FINESSE_RANSEUR = 0x187,
FEAT_WEAPON_FINESSE_SCYTHE = 0x188,
FEAT_WEAPON_FINESSE_SHORTBOW = 0x189,
FEAT_WEAPON_FINESSE_COMPOSITE_SHORTBOW = 0x18A,
FEAT_WEAPON_FINESSE_LONGBOW = 0x18B,
FEAT_WEAPON_FINESSE_COMPOSITE_LONGBOW = 0x18C,
FEAT_WEAPON_FINESSE_HALFLING_KAMA = 0x18D,
FEAT_WEAPON_FINESSE_KUKRI = 0x18E,
FEAT_WEAPON_FINESSE_HALFLING_NUNCHAKU = 0x18F,
FEAT_WEAPON_FINESSE_HALFLING_SIANGHAM = 0x190,
FEAT_WEAPON_FINESSE_KAMA = 0x191,
FEAT_WEAPON_FINESSE_NUNCHAKU = 0x192,
FEAT_WEAPON_FINESSE_SIANGHAM = 0x193,
FEAT_WEAPON_FINESSE_BASTARD_SWORD = 0x194,
FEAT_WEAPON_FINESSE_DWARVEN_WARAXE = 0x195,
FEAT_WEAPON_FINESSE_GNOME_HOOKED_HAMMER = 0x196,
FEAT_WEAPON_FINESSE_ORC_DOUBLE_AXE = 0x197,
FEAT_WEAPON_FINESSE_SPIKE_CHAIN = 0x198,
FEAT_WEAPON_FINESSE_DIRE_FLAIL = 0x199,
FEAT_WEAPON_FINESSE_TWO_BLADED_SWORD = 0x19A,
FEAT_WEAPON_FINESSE_DWARVEN_URGROSH = 0x19B,
FEAT_WEAPON_FINESSE_HAND_CROSSBOW = 0x19C,
FEAT_WEAPON_FINESSE_SHURIKEN = 0x19D,
FEAT_WEAPON_FINESSE_WHIP = 0x19E,
FEAT_WEAPON_FINESSE_REPEATING_CROSSBOW = 0x19F,
FEAT_WEAPON_FINESSE_NET = 0x1A0,
FEAT_WEAPON_FOCUS_GAUNTLET = 417,
FEAT_WEAPON_FOCUS_UNARMED_STRIKE_MEDIUM_SIZED_BEING = 0x1A2,
FEAT_WEAPON_FOCUS_UNARMED_STRIKE_SMALL_BEING = 0x1A3,
FEAT_WEAPON_FOCUS_DAGGER = 0x1A4,
FEAT_WEAPON_FOCUS_PUNCHING_DAGGER = 0x1A5,
FEAT_WEAPON_FOCUS_SPIKED_GAUNTLET = 0x1A6,
FEAT_WEAPON_FOCUS_LIGHT_MACE = 0x1A7,
FEAT_WEAPON_FOCUS_SICKLE = 0x1A8,
FEAT_WEAPON_FOCUS_CLUB = 0x1A9,
FEAT_WEAPON_FOCUS_HALFSPEAR = 0x1AA,
FEAT_WEAPON_FOCUS_HEAVY_MACE = 0x1AB,
FEAT_WEAPON_FOCUS_MORNINGSTAR = 0x1AC,
FEAT_WEAPON_FOCUS_QUARTERSTAFF = 0x1AD,
FEAT_WEAPON_FOCUS_SHORTSPEAR = 0x1AE,
FEAT_WEAPON_FOCUS_LIGHT_CROSSBOW = 0x1AF,
FEAT_WEAPON_FOCUS_DART = 0x1B0,
FEAT_WEAPON_FOCUS_SLING = 0x1B1,
FEAT_WEAPON_FOCUS_HEAVY_CROSSBOW = 0x1B2,
FEAT_WEAPON_FOCUS_JAVELIN = 0x1B3,
FEAT_WEAPON_FOCUS_THROWING_AXE = 0x1B4,
FEAT_WEAPON_FOCUS_LIGHT_HAMMER = 0x1B5,
FEAT_WEAPON_FOCUS_HANDAXE = 0x1B6,
FEAT_WEAPON_FOCUS_LIGHT_LANCE = 0x1B7,
FEAT_WEAPON_FOCUS_LIGHT_PICK = 0x1B8,
FEAT_WEAPON_FOCUS_SAP = 0x1B9,
FEAT_WEAPON_FOCUS_SHORT_SWORD = 0x1BA,
FEAT_WEAPON_FOCUS_BATTLEAXE = 0x1BB,
FEAT_WEAPON_FOCUS_LIGHT_FLAIL = 0x1BC,
FEAT_WEAPON_FOCUS_HEAVY_LANCE = 0x1BD,
FEAT_WEAPON_FOCUS_LONGSWORD = 0x1BE,
FEAT_WEAPON_FOCUS_HEAVY_PICK = 0x1BF,
FEAT_WEAPON_FOCUS_RAPIER = 0x1C0,
FEAT_WEAPON_FOCUS_SCIMITAR = 0x1C1,
FEAT_WEAPON_FOCUS_TRIDENT = 0x1C2,
FEAT_WEAPON_FOCUS_WARHAMMER = 0x1C3,
FEAT_WEAPON_FOCUS_FALCHION = 0x1C4,
FEAT_WEAPON_FOCUS_HEAVY_FLAIL = 0x1C5,
FEAT_WEAPON_FOCUS_GLAIVE = 0x1C6,
FEAT_WEAPON_FOCUS_GREATAXE = 0x1C7,
FEAT_WEAPON_FOCUS_GREATCLUB = 0x1C8,
FEAT_WEAPON_FOCUS_GREATSWORD = 0x1C9,
FEAT_WEAPON_FOCUS_GUISARME = 0x1CA,
FEAT_WEAPON_FOCUS_HALBERD = 0x1CB,
FEAT_WEAPON_FOCUS_LONGSPEAR = 0x1CC,
FEAT_WEAPON_FOCUS_RANSEUR = 0x1CD,
FEAT_WEAPON_FOCUS_SCYTHE = 0x1CE,
FEAT_WEAPON_FOCUS_SHORTBOW = 0x1CF,
FEAT_WEAPON_FOCUS_COMPOSITE_SHORTBOW = 0x1D0,
FEAT_WEAPON_FOCUS_LONGBOW = 0x1D1,
FEAT_WEAPON_FOCUS_COMPOSITE_LONGBOW = 0x1D2,
FEAT_WEAPON_FOCUS_HALFLING_KAMA = 0x1D3,
FEAT_WEAPON_FOCUS_KUKRI = 0x1D4,
FEAT_WEAPON_FOCUS_HALFLING_NUNCHAKU = 0x1D5,
FEAT_WEAPON_FOCUS_HALFLING_SIANGHAM = 0x1D6,
FEAT_WEAPON_FOCUS_KAMA = 0x1D7,
FEAT_WEAPON_FOCUS_NUNCHAKU = 0x1D8,
FEAT_WEAPON_FOCUS_SIANGHAM = 0x1D9,
FEAT_WEAPON_FOCUS_BASTARD_SWORD = 0x1DA,
FEAT_WEAPON_FOCUS_DWARVEN_WARAXE = 0x1DB,
FEAT_WEAPON_FOCUS_GNOME_HOOKED_HAMMER = 0x1DC,
FEAT_WEAPON_FOCUS_ORC_DOUBLE_AXE = 0x1DD,
FEAT_WEAPON_FOCUS_SPIKE_CHAIN = 0x1DE,
FEAT_WEAPON_FOCUS_DIRE_FLAIL = 0x1DF,
FEAT_WEAPON_FOCUS_TWO_BLADED_SWORD = 0x1E0,
FEAT_WEAPON_FOCUS_DWARVEN_URGROSH = 0x1E1,
FEAT_WEAPON_FOCUS_HAND_CROSSBOW = 0x1E2,
FEAT_WEAPON_FOCUS_SHURIKEN = 0x1E3,
FEAT_WEAPON_FOCUS_WHIP = 0x1E4,
FEAT_WEAPON_FOCUS_REPEATING_CROSSBOW = 0x1E5,
FEAT_WEAPON_FOCUS_NET = 0x1E6,
FEAT_WEAPON_FOCUS_GRAPPLE = 0x1E7,
FEAT_WEAPON_FOCUS_RAY = 0x1E8,
FEAT_WEAPON_SPECIALIZATION_GAUNTLET = 489,
FEAT_WEAPON_SPECIALIZATION_UNARMED_STRIKE_MEDIUM_SIZED_BEING = 0x1EA,
FEAT_WEAPON_SPECIALIZATION_UNARMED_STRIKE_SMALL_BEING = 0x1EB,
FEAT_WEAPON_SPECIALIZATION_DAGGER = 0x1EC,
FEAT_WEAPON_SPECIALIZATION_PUNCHING_DAGGER = 0x1ED,
FEAT_WEAPON_SPECIALIZATION_SPIKED_GAUNTLET = 0x1EE,
FEAT_WEAPON_SPECIALIZATION_LIGHT_MACE = 0x1EF,
FEAT_WEAPON_SPECIALIZATION_SICKLE = 0x1F0,
FEAT_WEAPON_SPECIALIZATION_CLUB = 0x1F1,
FEAT_WEAPON_SPECIALIZATION_HALFSPEAR = 0x1F2,
FEAT_WEAPON_SPECIALIZATION_HEAVY_MACE = 0x1F3,
FEAT_WEAPON_SPECIALIZATION_MORNINGSTAR = 0x1F4,
FEAT_WEAPON_SPECIALIZATION_QUARTERSTAFF = 0x1F5,
FEAT_WEAPON_SPECIALIZATION_SHORTSPEAR = 0x1F6,
FEAT_WEAPON_SPECIALIZATION_LIGHT_CROSSBOW = 0x1F7,
FEAT_WEAPON_SPECIALIZATION_DART = 0x1F8,
FEAT_WEAPON_SPECIALIZATION_SLING = 0x1F9,
FEAT_WEAPON_SPECIALIZATION_HEAVY_CROSSBOW = 0x1FA,
FEAT_WEAPON_SPECIALIZATION_JAVELIN = 0x1FB,
FEAT_WEAPON_SPECIALIZATION_THROWING_AXE = 0x1FC,
FEAT_WEAPON_SPECIALIZATION_LIGHT_HAMMER = 0x1FD,
FEAT_WEAPON_SPECIALIZATION_HANDAXE = 0x1FE,
FEAT_WEAPON_SPECIALIZATION_LIGHT_LANCE = 0x1FF,
FEAT_WEAPON_SPECIALIZATION_LIGHT_PICK = 0x200,
FEAT_WEAPON_SPECIALIZATION_SAP = 0x201,
FEAT_WEAPON_SPECIALIZATION_SHORT_SWORD = 0x202,
FEAT_WEAPON_SPECIALIZATION_BATTLEAXE = 0x203,
FEAT_WEAPON_SPECIALIZATION_LIGHT_FLAIL = 0x204,
FEAT_WEAPON_SPECIALIZATION_HEAVY_LANCE = 0x205,
FEAT_WEAPON_SPECIALIZATION_LONGSWORD = 0x206,
FEAT_WEAPON_SPECIALIZATION_HEAVY_PICK = 0x207,
FEAT_WEAPON_SPECIALIZATION_RAPIER = 0x208,
FEAT_WEAPON_SPECIALIZATION_SCIMITAR = 0x209,
FEAT_WEAPON_SPECIALIZATION_TRIDENT = 0x20A,
FEAT_WEAPON_SPECIALIZATION_WARHAMMER = 0x20B,
FEAT_WEAPON_SPECIALIZATION_FALCHION = 0x20C,
FEAT_WEAPON_SPECIALIZATION_HEAVY_FLAIL = 0x20D,
FEAT_WEAPON_SPECIALIZATION_GLAIVE = 0x20E,
FEAT_WEAPON_SPECIALIZATION_GREATAXE = 0x20F,
FEAT_WEAPON_SPECIALIZATION_GREATCLUB = 0x210,
FEAT_WEAPON_SPECIALIZATION_GREATSWORD = 0x211,
FEAT_WEAPON_SPECIALIZATION_GUISARME = 0x212,
FEAT_WEAPON_SPECIALIZATION_HALBERD = 0x213,
FEAT_WEAPON_SPECIALIZATION_LONGSPEAR = 0x214,
FEAT_WEAPON_SPECIALIZATION_RANSEUR = 0x215,
FEAT_WEAPON_SPECIALIZATION_SCYTHE = 0x216,
FEAT_WEAPON_SPECIALIZATION_SHORTBOW = 0x217,
FEAT_WEAPON_SPECIALIZATION_COMPOSITE_SHORTBOW = 0x218,
FEAT_WEAPON_SPECIALIZATION_LONGBOW = 0x219,
FEAT_WEAPON_SPECIALIZATION_COMPOSITE_LONGBOW = 0x21A,
FEAT_WEAPON_SPECIALIZATION_HALFLING_KAMA = 0x21B,
FEAT_WEAPON_SPECIALIZATION_KUKRI = 0x21C,
FEAT_WEAPON_SPECIALIZATION_HALFLING_NUNCHAKU = 0x21D,
FEAT_WEAPON_SPECIALIZATION_HALFLING_SIANGHAM = 0x21E,
FEAT_WEAPON_SPECIALIZATION_KAMA = 0x21F,
FEAT_WEAPON_SPECIALIZATION_NUNCHAKU = 0x220,
FEAT_WEAPON_SPECIALIZATION_SIANGHAM = 0x221,
FEAT_WEAPON_SPECIALIZATION_BASTARD_SWORD = 0x222,
FEAT_WEAPON_SPECIALIZATION_DWARVEN_WARAXE = 0x223,
FEAT_WEAPON_SPECIALIZATION_GNOME_HOOKED_HAMMER = 0x224,
FEAT_WEAPON_SPECIALIZATION_ORC_DOUBLE_AXE = 0x225,
FEAT_WEAPON_SPECIALIZATION_SPIKE_CHAIN = 0x226,
FEAT_WEAPON_SPECIALIZATION_DIRE_FLAIL = 0x227,
FEAT_WEAPON_SPECIALIZATION_TWO_BLADED_SWORD = 0x228,
FEAT_WEAPON_SPECIALIZATION_DWARVEN_URGROSH = 0x229,
FEAT_WEAPON_SPECIALIZATION_HAND_CROSSBOW = 0x22A,
FEAT_WEAPON_SPECIALIZATION_SHURIKEN = 0x22B,
FEAT_WEAPON_SPECIALIZATION_WHIP = 0x22C,
FEAT_WEAPON_SPECIALIZATION_REPEATING_CROSSBOW = 0x22D,
FEAT_WEAPON_SPECIALIZATION_NET = 0x22E,
FEAT_WEAPON_SPECIALIZATION_GRAPPLE = 0x22F,
FEAT_WHIRLWIND_ATTACK = 0x230,
FEAT_BARBARIAN_RAGE = 0x231,
FEAT_STUNNING_ATTACKS = 0x232,
FEAT_WHOLENESS_OF_BODY = 0x233,
FEAT_LAY_ON_HANDS = 0x234,
FEAT_SMITE_EVIL = 0x235,
FEAT_REMOVE_DISEASE = 0x236,
FEAT_DETECT_EVIL = 0x237,
FEAT_AURA_OF_COURAGE = 0x238,
FEAT_DIVINE_HEALTH = 0x239,
FEAT_DIVINE_GRACE = 0x23A,
FEAT_SPECIAL_MOUNT = 0x23B,
FEAT_CODE_OF_CONDUCT = 0x23C,
FEAT_ASSOCIATES = 0x23D,
FEAT_DEFENSIVE_ROLL = 0x23E,
FEAT_TURN_UNDEAD = 0x23F,
FEAT_REBUKE_UNDEAD = 0x240,
FEAT_DOMAIN_POWER = 0x241,
FEAT_SPONTANEOUS_CASTING_CURE = 0x242,
FEAT_SPONTANEOUS_CASTING_INFLICT = 0x243,
FEAT_COMBAT_REFLEXES = 0x244,
FEAT_MARTIAL_WEAPON_PROFICIENCY_ALL = 0x245,
FEAT_SIMPLE_WEAPON_PROFICIENCY_DRUID = 0x246,
FEAT_SIMPLE_WEAPON_PROFICIENCY_MONK = 0x247,
FEAT_SIMPLE_WEAPON_PROFICIENCY_ROGUE = 0x248,
FEAT_SIMPLE_WEAPON_PROFICIENCY_WIZARD = 0x249,
FEAT_SIMPLE_WEAPON_PROFICIENCY_ELF = 0x24A,
FEAT_UNCANNY_DODGE = 0x24B,
FEAT_FAST_MOVEMENT = 0x24C,
FEAT_BARDIC_MUSIC = 0x24D,
FEAT_BARDIC_KNOWLEDGE = 0x24E,
FEAT_NATURE_SENSE = 0x24F,
FEAT_WOODLAND_STRIDE = 0x250,
FEAT_TRACKLESS_STEP = 0x251,
FEAT_RESIST_NATURES_LURE = 0x252,
FEAT_WILD_SHAPE = 0x253,
FEAT_VENOM_IMMUNITY = 0x254,
FEAT_ARMOR_PROFICIENCY_DRUID = 0x255,
FEAT_FLURRY_OF_BLOWS = 0x256,
FEAT_EVASION = 0x257,
FEAT_STILL_MIND = 0x258,
FEAT_PURITY_OF_BODY = 0x259,
FEAT_IMPROVED_EVASION = 0x25A,
FEAT_KI_STRIKE = 0x25B,
FEAT_SNEAK_ATTACK = 0x25C,
FEAT_TRAPS = 0x25D,
FEAT_CRIPPLING_STRIKE = 0x25E,
FEAT_OPPORTUNIST = 0x25F,
FEAT_SKILL_MASTERY = 0x260,
FEAT_SLIPPERY_MIND = 0x261,
FEAT_CALL_FAMILIAR = 0x262,
FEAT_FAVORED_ENEMY_ABERRATION = 0x263,
FEAT_FAVORED_ENEMY_ANIMAL = 0x264,
FEAT_FAVORED_ENEMY_BEAST = 0x265,
FEAT_FAVORED_ENEMY_CONSTRUCT = 0x266,
FEAT_FAVORED_ENEMY_DRAGON = 0x267,
FEAT_FAVORED_ENEMY_ELEMENTAL = 0x268,
FEAT_FAVORED_ENEMY_FEY = 0x269,
FEAT_FAVORED_ENEMY_GIANT = 0x26A,
FEAT_FAVORED_ENEMY_MAGICAL_BEAST = 0x26B,
FEAT_FAVORED_ENEMY_MONSTROUS_HUMANOID = 0x26C,
FEAT_FAVORED_ENEMY_OOZE = 0x26D,
FEAT_FAVORED_ENEMY_PLANT = 0x26E,
FEAT_FAVORED_ENEMY_SHAPECHANGER = 0x26F,
FEAT_FAVORED_ENEMY_UNDEAD = 0x270,
FEAT_FAVORED_ENEMY_VERMIN = 0x271,
FEAT_FAVORED_ENEMY_OUTSIDER_EVIL = 0x272,
FEAT_FAVORED_ENEMY_OUTSIDER_GOOD = 0x273,
FEAT_FAVORED_ENEMY_OUTSIDER_LAWFUL = 0x274,
FEAT_FAVORED_ENEMY_OUTSIDER_CHAOTIC = 0x275,
FEAT_FAVORED_ENEMY_HUMANOID_GOBLINOID = 0x276,
FEAT_FAVORED_ENEMY_HUMANOID_REPTILIAN = 0x277,
FEAT_FAVORED_ENEMY_HUMANOID_DWARF = 0x278,
FEAT_FAVORED_ENEMY_HUMANOID_ELF = 0x279,
FEAT_FAVORED_ENEMY_HUMANOID_GNOLL = 0x27A,
FEAT_FAVORED_ENEMY_HUMANOID_GNOME = 0x27B,
FEAT_FAVORED_ENEMY_HUMANOID_HALFLING = 0x27C,
FEAT_FAVORED_ENEMY_HUMANOID_ORC = 0x27D,
FEAT_FAVORED_ENEMY_HUMANOID_HUMAN = 0x27E,
FEAT_AMBIDEXTERITY_RANGER = 0x27F,
FEAT_TWO_WEAPON_FIGHTING_RANGER = 0x280,
FEAT_IMPROVED_TWO_WEAPON_FIGHTING_RANGER = 0x281,
FEAT_ANIMAL_COMPANION = 0x282,
FEAT_RANGER_TWO_WEAPON_STYLE = 0x283,
FEAT_RANGER_ARCHERY_STYLE = 0x284,
FEAT_WIDEN_SPELL = 0x285,
FEAT_RANGER_RAPID_SHOT = 0x286,
FEAT_RANGER_MANYSHOT = 647,
FEAT_SIMPLE_WEAPON_PROFICIENCY_BARD = 648,
FEAT_NONE = 649,
FEAT_EXOTIC_WEAPON_PROFICIENCY, // these are just used for display in the feat selection ui
FEAT_IMPROVED_CRITICAL,
FEAT_MARTIAL_WEAPON_PROFICIENCY,
FEAT_SKILL_FOCUS,
FEAT_WEAPON_FINESSE,
FEAT_WEAPON_FOCUS,
FEAT_GREATER_WEAPON_FOCUS,
FEAT_WEAPON_SPECIALIZATION,
FEAT_MONK_DIAMOND_BODY = 658, // Moebius hacks
FEAT_MONK_ABUNDANT_STEP = 659,
FEAT_MONK_DIAMOND_SOUL = 660,
FEAT_MONK_QUIVERING_PALM = 661,
FEAT_MONK_EMPTY_BODY = 662,
FEAT_MONK_PERFECT_SELF = 663,
FEAT_GREATER_TWO_WEAPON_FIGHTING_RANGER = 664,
FEAT_IMPROVED_PRECISE_SHOT = 665,
FEAT_IMPROVED_PRECISE_SHOT_RANGER = 666,
FEAT_SHARP_SHOOTING = 667,
FEAT_DIVINE_MIGHT = 668,
FEAT_RECKLESS_OFFENSE = 669,
FEAT_KNOCK_DOWN = 670,
FEAT_SUPERIOR_EXPERTISE = 671,
FEAT_DEADLY_PRECISION = 672,
FEAT_PERSISTENT_SPELL = 673,
FEAT_POWER_CRITICAL = 674,
FEAT_GREATER_RAGE = 675,
FEAT_GREATER_WEAPON_SPECIALIZATION_GAUNTLET = 676,
FEAT_GREATER_WEAPON_SPECIALIZATION_UNARMED_STRIKE_MEDIUM_SIZED_BEING = 677,
FEAT_GREATER_WEAPON_SPECIALIZATION_BASTARD_SWORD = 733,
/// ... rest of Greater Weapon Specializations ...
FEAT_GREATER_WEAPON_SPECIALIZATION_GRAPPLE = 746,
FEAT_TIRELESS_RAGE = 747,
FEAT_MIGHTY_RAGE = 748,
FEAT_INDOMITABLE_WILL = 749,
FEAT_INVALID = 0xffFFffFF
};
enum feat_requirement_codes : int32_t {
featReqCodeTerminator = -1,
featReqCodeMinCasterLevel = -2,
featReqCodeTurnUndeadRelated = -3,
featReqCodeWeaponFeat = -4,
featReqCodeEvasionRelated = -5,
featReqCodeFastMovement = -6,
featReqCodeUncannyDodgeRelated = -7,
featReqCodeMinArcaneCasterLevel = -8,
featReqCodeAnimalCompanion = -9,
featReqCodeCrossbowFeat = -10
};
enum featPropertyEnums : uint32_t {
featPropDisabled = 0x00000002,
featPropRogueFeat = 0x00040000
};
#pragma endregion
#pragma region General Object stuff
enum ObjectType : uint32_t {
obj_t_portal = 0,
obj_t_container = 1,
obj_t_scenery = 2,
obj_t_projectile = 3,
obj_t_weapon = 4,
obj_t_ammo = 5,
obj_t_armor = 6,
obj_t_money = 7,
obj_t_food = 8,
obj_t_scroll = 9,
obj_t_key = 10,
obj_t_written = 11,
obj_t_generic = 12,
obj_t_pc = 13,
obj_t_npc = 14,
obj_t_trap = 15,
obj_t_bag = 16
};
static constexpr auto ObjectTypeCount = 17; // Number of literals in ObjectType
const char *GetObjectTypeName(ObjectType type);
enum obj_f : uint32_t {
obj_f_begin = 0,
obj_f_location = 1, // note: in the DLL this is labeled obj_f_current_aid but there appears to be an offset here. Maybe they removed "obj_f_current_aid" and forgot to update the strings?
obj_f_offset_x = 2,
obj_f_offset_y = 3,
obj_f_2D_shadow_art = 4, // was "offset_y" in the DLL, is probably obj_f_shadow but I'm not sure so leaving it as UNKOWN
obj_f_blit_flags = 5,
obj_f_blit_color = 6,
obj_f_transparency = 7,
obj_f_model_scale = 8,
obj_f_light_flags = 9,
obj_f_light_material = 10,
obj_f_light_color = 11,
obj_f_light_radius = 12,
obj_f_light_angle_start = 13,
obj_f_light_angle_end = 14,
obj_f_light_type = 15,
obj_f_light_facing_X = 16,
obj_f_light_facing_Y = 17,
obj_f_light_facing_Z = 18,
obj_f_light_offset_X = 19,
obj_f_light_offset_Y = 20,
obj_f_light_offset_Z = 21,
obj_f_flags = 22, // was "obj_f_name" in the DLL but is used as obj_f_flags so it must be another mis-named one
obj_f_spell_flags = 23, // looks more like animation system flags...
obj_f_name = 24,
obj_f_description = 25,
obj_f_size = 26,
obj_f_hp_pts = 27, // at least from here onwards the names are correct
obj_f_hp_adj = 28,
obj_f_hp_damage = 29,
obj_f_material = 30,
obj_f_scripts_idx = 31,
obj_f_sound_effect = 32,
obj_f_category = 33,
obj_f_rotation = 34,
obj_f_speed_walk = 35,
obj_f_speed_run = 36,
obj_f_base_mesh = 37,
obj_f_base_anim = 38,
obj_f_radius = 39,
obj_f_3d_render_height = 40,
obj_f_conditions = 41,
obj_f_condition_arg0 = 42,
obj_f_permanent_mods = 43,
obj_f_initiative = 44,
obj_f_dispatcher = 45,
obj_f_subinitiative = 46,
obj_f_secretdoor_flags = 47,
obj_f_secretdoor_effectname = 48,
obj_f_secretdoor_dc = 49,
obj_f_pad_i_7 = 50,
obj_f_pad_i_8 = 51,
obj_f_pad_i_9 = 52,
obj_f_pad_i_0 = 53,
obj_f_offset_z = 54,
obj_f_rotation_pitch = 55,
obj_f_pad_f_3 = 56,
obj_f_pad_f_4 = 57,
obj_f_pad_f_5 = 58,
obj_f_pad_f_6 = 59,
obj_f_pad_f_7 = 60,
obj_f_pad_f_8 = 61,
obj_f_pad_f_9 = 62,
obj_f_pad_f_0 = 63,
obj_f_pad_i64_0 = 64,
obj_f_pad_i64_1 = 65,
obj_f_pad_i64_2 = 66,
obj_f_pad_i64_3 = 67,
obj_f_pad_i64_4 = 68,
obj_f_last_hit_by = 69,
obj_f_pad_obj_1 = 70,
obj_f_pad_obj_2 = 71,
obj_f_pad_obj_3 = 72,
obj_f_pad_obj_4 = 73,
obj_f_permanent_mod_data = 74,
obj_f_attack_types_idx = 75,
obj_f_attack_bonus_idx = 76,
obj_f_strategy_state = 77,
obj_f_pad_ias_4 = 78,
obj_f_pad_i64as_0 = 79,
obj_f_pad_i64as_1 = 80,
obj_f_pad_i64as_2 = 81,
obj_f_pad_i64as_3 = 82,
obj_f_pad_i64as_4 = 83,
obj_f_pad_objas_0 = 84,
obj_f_pad_objas_1 = 85,
obj_f_pad_objas_2 = 86,
obj_f_end = 87,
obj_f_portal_begin = 88,
obj_f_portal_flags = 89,
obj_f_portal_lock_dc = 90,
obj_f_portal_key_id = 91,
obj_f_portal_notify_npc = 92,
obj_f_portal_pad_i_1 = 93,
obj_f_portal_pad_i_2 = 94,
obj_f_portal_pad_i_3 = 95,
obj_f_portal_pad_i_4 = 96,
obj_f_portal_pad_i_5 = 97,
obj_f_portal_pad_obj_1 = 98,
obj_f_portal_pad_ias_1 = 99,
obj_f_portal_pad_i64as_1 = 100,
obj_f_portal_end = 101,
obj_f_container_begin = 102,
obj_f_container_flags = 103,
obj_f_container_lock_dc = 104,
obj_f_container_key_id = 105,
obj_f_container_inventory_num = 106,
obj_f_container_inventory_list_idx = 107,
obj_f_container_inventory_source = 108,
obj_f_container_notify_npc = 109,
obj_f_container_pad_i_1 = 110,
obj_f_container_pad_i_2 = 111,
obj_f_container_pad_i_3 = 112,
obj_f_container_pad_i_4 = 113,
obj_f_container_pad_i_5 = 114,
obj_f_container_pad_obj_1 = 115,
obj_f_container_pad_obj_2 = 116,
obj_f_container_pad_ias_1 = 117,
obj_f_container_pad_i64as_1 = 118,
obj_f_container_pad_objas_1 = 119,
obj_f_container_end = 120,
obj_f_scenery_begin = 121,
obj_f_scenery_flags = 122,
obj_f_scenery_pad_obj_0 = 123,
obj_f_scenery_respawn_delay = 124,
obj_f_scenery_pad_i_0 = 125,
obj_f_scenery_pad_i_1 = 126,
obj_f_scenery_teleport_to = 127,
obj_f_scenery_pad_i_4 = 128,
obj_f_scenery_pad_i_5 = 129,
obj_f_scenery_pad_obj_1 = 130,
obj_f_scenery_pad_ias_1 = 131,
obj_f_scenery_pad_i64as_1 = 132,
obj_f_scenery_end = 133,
obj_f_projectile_begin = 134,
obj_f_projectile_flags_combat = 135,
obj_f_projectile_flags_combat_damage = 136,
obj_f_projectile_parent_weapon = 137,
obj_f_projectile_parent_ammo = 138,
obj_f_projectile_part_sys_id = 139,
obj_f_projectile_acceleration_x = 140,
obj_f_projectile_acceleration_y = 141,
obj_f_projectile_acceleration_z = 142,
obj_f_projectile_pad_i_4 = 143,
obj_f_projectile_pad_obj_1 = 144,
obj_f_projectile_pad_obj_2 = 145,
obj_f_projectile_pad_obj_3 = 146,
obj_f_projectile_pad_ias_1 = 147,
obj_f_projectile_pad_i64as_1 = 148,
obj_f_projectile_pad_objas_1 = 149,
obj_f_projectile_end = 150,
obj_f_item_begin = 151,
obj_f_item_flags = 152,
obj_f_item_parent = 153,
obj_f_item_weight = 154,
obj_f_item_worth = 155,
obj_f_item_inv_aid = 156,
obj_f_item_inv_location = 157,
obj_f_item_ground_mesh = 158,
obj_f_item_ground_anim = 159,
obj_f_item_description_unknown = 160,
obj_f_item_description_effects = 161,
obj_f_item_spell_idx = 162,
obj_f_item_spell_idx_flags = 163,
obj_f_item_spell_charges_idx = 164,
obj_f_item_ai_action = 165,
obj_f_item_wear_flags = 166,
obj_f_item_material_slot = 167,
obj_f_item_quantity = 168,
obj_f_item_pad_i_1 = 169,
obj_f_item_pad_i_2 = 170,
obj_f_item_pad_i_3 = 171,
obj_f_item_pad_i_4 = 172,
obj_f_item_pad_i_5 = 173,
obj_f_item_pad_i_6 = 174,
obj_f_item_pad_obj_1 = 175,
obj_f_item_pad_obj_2 = 176,
obj_f_item_pad_obj_3 = 177,
obj_f_item_pad_obj_4 = 178,
obj_f_item_pad_obj_5 = 179,
obj_f_item_pad_wielder_condition_array = 180,
obj_f_item_pad_wielder_argument_array = 181,
obj_f_item_pad_i64as_1 = 182,
obj_f_item_pad_i64as_2 = 183,
obj_f_item_pad_objas_1 = 184,
obj_f_item_pad_objas_2 = 185,
obj_f_item_end = 186,
obj_f_weapon_begin = 187,
obj_f_weapon_flags = 188,
obj_f_weapon_range = 189,
obj_f_weapon_ammo_type = 190,
obj_f_weapon_ammo_consumption = 191,
obj_f_weapon_missile_aid = 192,
obj_f_weapon_crit_hit_chart = 193,
obj_f_weapon_attacktype = 194,
obj_f_weapon_damage_dice = 195,
obj_f_weapon_animtype = 196,
obj_f_weapon_type = 197,
obj_f_weapon_crit_range = 198,
obj_f_weapon_pad_i_1 = 199,
obj_f_weapon_pad_i_2 = 200,
obj_f_weapon_pad_obj_1 = 201,
obj_f_weapon_pad_obj_2 = 202,
obj_f_weapon_pad_obj_3 = 203,
obj_f_weapon_pad_obj_4 = 204,
obj_f_weapon_pad_obj_5 = 205,
obj_f_weapon_pad_ias_1 = 206,
obj_f_weapon_pad_i64as_1 = 207,
obj_f_weapon_end = 208,
obj_f_ammo_begin = 209,
obj_f_ammo_flags = 210,
obj_f_ammo_quantity = 211,
obj_f_ammo_type = 212,
obj_f_ammo_pad_i_1 = 213,
obj_f_ammo_pad_i_2 = 214,
obj_f_ammo_pad_obj_1 = 215,
obj_f_ammo_pad_ias_1 = 216,
obj_f_ammo_pad_i64as_1 = 217,
obj_f_ammo_end = 218,
obj_f_armor_begin = 219,
obj_f_armor_flags = 220,
obj_f_armor_ac_adj = 221,
obj_f_armor_max_dex_bonus = 222,
obj_f_armor_arcane_spell_failure = 223,
obj_f_armor_armor_check_penalty = 224,
obj_f_armor_pad_i_1 = 225,
obj_f_armor_pad_ias_1 = 226,
obj_f_armor_pad_i64as_1 = 227,
obj_f_armor_end = 228,
obj_f_money_begin = 229,
obj_f_money_flags = 230,
obj_f_money_quantity = 231,
obj_f_money_type = 232,
obj_f_money_pad_i_1 = 233,
obj_f_money_pad_i_2 = 234,
obj_f_money_pad_i_3 = 235,
obj_f_money_pad_i_4 = 236,
obj_f_money_pad_i_5 = 237,
obj_f_money_pad_ias_1 = 238,
obj_f_money_pad_i64as_1 = 239,
obj_f_money_end = 240,
obj_f_food_begin = 241,
obj_f_food_flags = 242,
obj_f_food_pad_i_1 = 243,
obj_f_food_pad_i_2 = 244,
obj_f_food_pad_ias_1 = 245,
obj_f_food_pad_i64as_1 = 246,
obj_f_food_end = 247,
obj_f_scroll_begin = 248,
obj_f_scroll_flags = 249,
obj_f_scroll_pad_i_1 = 250,
obj_f_scroll_pad_i_2 = 251,
obj_f_scroll_pad_ias_1 = 252,
obj_f_scroll_pad_i64as_1 = 253,
obj_f_scroll_end = 254,
obj_f_key_begin = 255,
obj_f_key_key_id = 256,
obj_f_key_pad_i_1 = 257,
obj_f_key_pad_i_2 = 258,
obj_f_key_pad_ias_1 = 259,
obj_f_key_pad_i64as_1 = 260,
obj_f_key_end = 261,
obj_f_written_begin = 262,
obj_f_written_flags = 263,
obj_f_written_subtype = 264,
obj_f_written_text_start_line = 265,
obj_f_written_text_end_line = 266,
obj_f_written_pad_i_1 = 267,
obj_f_written_pad_i_2 = 268,
obj_f_written_pad_ias_1 = 269,
obj_f_written_pad_i64as_1 = 270,
obj_f_written_end = 271,
obj_f_bag_begin = 272,
obj_f_bag_flags = 273,
obj_f_bag_size = 274,
obj_f_bag_end = 275,
obj_f_generic_begin = 276,
obj_f_generic_flags = 277,
obj_f_generic_usage_bonus = 278,
obj_f_generic_usage_count_remaining = 279,
obj_f_generic_pad_ias_1 = 280,
obj_f_generic_pad_i64as_1 = 281,
obj_f_generic_end = 282,
obj_f_critter_begin = 283,
obj_f_critter_flags = 284,
obj_f_critter_flags2 = 285,
obj_f_critter_abilities_idx = 286,
obj_f_critter_level_idx = 287,
obj_f_critter_race = 288,
obj_f_critter_gender = 289,
obj_f_critter_age = 290,
obj_f_critter_height = 291,
obj_f_critter_weight = 292,
obj_f_critter_experience = 293,
obj_f_critter_pad_i_1 = 294,
obj_f_critter_alignment = 295,
obj_f_critter_deity = 296,
obj_f_critter_domain_1 = 297,
obj_f_critter_domain_2 = 298,
obj_f_critter_alignment_choice = 299,
obj_f_critter_school_specialization = 300,
obj_f_critter_spells_known_idx = 301,
obj_f_critter_spells_memorized_idx = 302,
obj_f_critter_spells_cast_idx = 303,
obj_f_critter_feat_idx = 304,
obj_f_critter_feat_count_idx = 305,
obj_f_critter_fleeing_from = 306,
obj_f_critter_portrait = 307,
obj_f_critter_money_idx = 308,
obj_f_critter_inventory_num = 309,
obj_f_critter_inventory_list_idx = 310,
obj_f_critter_inventory_source = 311,
obj_f_critter_description_unknown = 312,
obj_f_critter_follower_idx = 313,
obj_f_critter_teleport_dest = 314,
obj_f_critter_teleport_map = 315,
obj_f_critter_death_time = 316,
obj_f_critter_skill_idx = 317,
obj_f_critter_reach = 318,
obj_f_critter_subdual_damage = 319,
obj_f_critter_pad_i_4 = 320,
obj_f_critter_pad_i_5 = 321,
obj_f_critter_sequence = 322,
obj_f_critter_hair_style = 323,
obj_f_critter_strategy = 324,
obj_f_critter_pad_i_3 = 325,
obj_f_critter_monster_category = 326,
obj_f_critter_pad_i64_2 = 327,
obj_f_critter_pad_i64_3 = 328,
obj_f_critter_pad_i64_4 = 329,
obj_f_critter_pad_i64_5 = 330,
obj_f_critter_damage_idx = 331,
obj_f_critter_attacks_idx = 332,
obj_f_critter_seen_maplist = 333,
obj_f_critter_pad_i64as_2 = 334,
obj_f_critter_pad_i64as_3 = 335,
obj_f_critter_pad_i64as_4 = 336,
obj_f_critter_pad_i64as_5 = 337,
obj_f_critter_end = 338,
obj_f_pc_begin = 339,
obj_f_pc_flags = 340,
obj_f_pc_pad_ias_0 = 341,
obj_f_pc_pad_i64as_0 = 342,
obj_f_pc_player_name = 343,
obj_f_pc_global_flags = 344,
obj_f_pc_global_variables = 345,
obj_f_pc_voice_idx = 346,
obj_f_pc_roll_count = 347,
obj_f_pc_pad_i_2 = 348,
obj_f_pc_weaponslots_idx = 349,
obj_f_pc_pad_ias_2 = 350,
obj_f_pc_pad_i64as_1 = 351,
obj_f_pc_end = 352,
obj_f_npc_begin = 353,
obj_f_npc_flags = 354,
obj_f_npc_leader = 355,
obj_f_npc_ai_data = 356,
obj_f_npc_combat_focus = 357,
obj_f_npc_who_hit_me_last = 358,
obj_f_npc_waypoints_idx = 359,
obj_f_npc_waypoint_current = 360,
obj_f_npc_standpoint_day_INTERNAL_DO_NOT_USE = 361,
obj_f_npc_standpoint_night_INTERNAL_DO_NOT_USE = 362,
obj_f_npc_faction = 363,
obj_f_npc_retail_price_multiplier = 364,
obj_f_npc_substitute_inventory = 365,
obj_f_npc_reaction_base = 366,
obj_f_npc_challenge_rating = 367,
obj_f_npc_reaction_pc_idx = 368,
obj_f_npc_reaction_level_idx = 369,
obj_f_npc_reaction_time_idx = 370,
obj_f_npc_generator_data = 371,
obj_f_npc_ai_list_idx = 372,
obj_f_npc_save_reflexes_bonus = 373,
obj_f_npc_save_fortitude_bonus = 374,
obj_f_npc_save_willpower_bonus = 375,
obj_f_npc_ac_bonus = 376,
obj_f_npc_add_mesh = 377,
obj_f_npc_waypoint_anim = 378,
obj_f_npc_pad_i_3 = 379,
obj_f_npc_pad_i_4 = 380,
obj_f_npc_pad_i_5 = 381,
obj_f_npc_ai_flags64 = 382,
obj_f_npc_pad_i64_2 = 383,
obj_f_npc_pad_i64_3 = 384,
obj_f_npc_pad_i64_4 = 385,
obj_f_npc_pad_i64_5 = 386,
obj_f_npc_hitdice_idx = 387,
obj_f_npc_ai_list_type_idx = 388,
obj_f_npc_pad_ias_3 = 389,
obj_f_npc_pad_ias_4 = 390,
obj_f_npc_pad_ias_5 = 391,
obj_f_npc_standpoints = 392,
obj_f_npc_pad_i64as_2 = 393,
obj_f_npc_pad_i64as_3 = 394,
obj_f_npc_pad_i64as_4 = 395,
obj_f_npc_pad_i64as_5 = 396,
obj_f_npc_end = 397,
obj_f_trap_begin = 398,
obj_f_trap_flags = 399,
obj_f_trap_difficulty = 400,
obj_f_trap_pad_i_2 = 401,
obj_f_trap_pad_ias_1 = 402,
obj_f_trap_pad_i64as_1 = 403,
obj_f_trap_end = 404,
obj_f_total_normal = 405,
obj_f_transient_begin = 406,
obj_f_render_color = 407,
obj_f_render_colors = 408,
obj_f_render_palette = 409,
obj_f_render_scale = 410,
obj_f_render_alpha = 411,
obj_f_render_x = 412,
obj_f_render_y = 413,
obj_f_render_width = 414,
obj_f_render_height = 415,
obj_f_palette = 416,
obj_f_color = 417,
obj_f_colors = 418,
obj_f_render_flags = 419,
obj_f_temp_id = 420,
obj_f_light_handle = 421,
obj_f_overlay_light_handles = 422,
obj_f_internal_flags = 423,
obj_f_find_node = 424,
obj_f_animation_handle = 425,
obj_f_grapple_state = 426,
obj_f_transient_end = 427,
obj_f_type = 428,
obj_f_prototype_handle = 429
};
const char *GetObjectFieldName(obj_f field);
/*
Flags supported by all object types.
Query with objects.GetFlags
*/
enum ObjectFlag : uint32_t {
OF_DESTROYED = 1,
OF_OFF = 2,
OF_FLAT = 4,
OF_TEXT = 8,
OF_SEE_THROUGH = 0x10,
OF_SHOOT_THROUGH = 0x20,
OF_TRANSLUCENT = 0x40,
OF_SHRUNK = 0x80,
OF_DONTDRAW = 0x100,
OF_INVISIBLE = 0x200,
OF_NO_BLOCK = 0x400,
OF_CLICK_THROUGH = 0x800,
OF_INVENTORY = 0x1000,
OF_DYNAMIC = 0x2000,
OF_PROVIDES_COVER = 0x4000,
OF_RANDOM_SIZE = 0x8000,
OF_NOHEIGHT = 0x10000,
OF_WADING = 0x20000,
OF_UNUSED_40000 = 0x40000,
OF_STONED = 0x80000,
OF_DONTLIGHT = 0x100000,
OF_TEXT_FLOATER = 0x200000,
OF_INVULNERABLE = 0x400000,
OF_EXTINCT = 0x800000,
OF_TRAP_PC = 0x1000000,
OF_TRAP_SPOTTED = 0x2000000,
OF_DISALLOW_WADING = 0x4000000,
OF_UNUSED_08000000 = 0x8000000,
OF_HEIGHT_SET = 0x10000000,
OF_ANIMATED_DEAD = 0x20000000,
OF_TELEPORTED = 0x40000000,
OF_RADIUS_SET= 0x80000000
};
enum MaterialType : uint32_t {
mat_stone = 0,
mat_brick = 1,
mat_wood = 2,
mat_plant = 3,
mat_flesh = 4,
mat_metal = 5,
mat_glass = 6,
mat_cloth = 7,
mat_liquid = 8,
mat_paper = 9,
mat_gas = 10,
mat_force = 11,
mat_fire = 12,
mat_powder = 13,
};
#pragma endregion
#pragma region D20
enum D20Query : uint32_t {
Q_Helpless = 0x0,
Q_SneakAttack = 0x1,
Q_OpponentSneakAttack = 0x2,
Q_CoupDeGrace = 0x3,
Q_Mute = 0x4,
Q_CannotCast = 0x5,
Q_CannotUseIntSkill = 0x6,
Q_CannotUseChaSkill = 0x7,
Q_RapidShot = 0x8,
Q_Critter_Is_Concentrating = 0x9,
Q_Critter_Is_On_Consecrate_Ground = 0xA,
Q_Critter_Is_On_Desecrate_Ground = 0xB,
Q_Critter_Is_Held = 0xC,
Q_Critter_Is_Invisible = 0xD,
Q_Critter_Is_Afraid = 0xE,
Q_Critter_Is_Blinded = 0xF,
Q_Critter_Is_Charmed = 0x10,
Q_Critter_Is_Confused = 0x11,
Q_Critter_Is_AIControlled = 0x12,
Q_Critter_Is_Cursed = 0x13,
Q_Critter_Is_Deafened = 0x14,
Q_Critter_Is_Diseased = 0x15,
Q_Critter_Is_Poisoned = 0x16,
Q_Critter_Is_Stunned = 0x17,
Q_Critter_Is_Immune_Critical_Hits = 0x18,
Q_Critter_Is_Immune_Poison = 0x19,
Q_Critter_Has_Spell_Resistance = 0x1A,
Q_Critter_Has_Condition = 0x1B,
Q_Critter_Has_Freedom_of_Movement = 0x1C,
Q_Critter_Has_Endure_Elements = 0x1D,
Q_Critter_Has_Protection_From_Elements = 0x1E,
Q_Critter_Has_Resist_Elements = 0x1F,
Q_Critter_Has_True_Seeing = 0x20,
Q_Critter_Has_Spell_Active = 0x21,
Q_Critter_Can_Call_Lightning = 0x22,
Q_Critter_Can_See_Invisible = 0x23,
Q_Critter_Can_See_Darkvision = 0x24,
Q_Critter_Can_See_Ethereal = 0x25,
Q_Critter_Can_Discern_Lies = 0x26,
Q_Critter_Can_Detect_Chaos = 0x27,
Q_Critter_Can_Detect_Evil = 0x28,
Q_Critter_Can_Detect_Good = 0x29,
Q_Critter_Can_Detect_Law = 0x2A,
Q_Critter_Can_Detect_Magic = 0x2B,
Q_Critter_Can_Detect_Undead = 0x2C,
Q_Critter_Can_Find_Traps = 0x2D,
Q_Critter_Can_Dismiss_Spells = 0x2E,
Q_Obj_Is_Blessed = 0x2F,
Q_Unconscious = 0x30,
Q_Dying = 0x31,
Q_Dead = 0x32,
Q_AOOPossible = 0x33,
Q_AOOIncurs = 0x34,
Q_HoldingCharge = 0x35,
Q_Has_Temporary_Hit_Points = 0x36,
Q_SpellInterrupted = 0x37,
Q_ActionTriggersAOO = 0x38,
Q_ActionAllowed = 0x39,
Q_Prone = 0x3A,
Q_RerollSavingThrow = 0x3B,
Q_RerollAttack = 0x3C,
Q_RerollCritical = 0x3D,
Q_Commanded = 0x3E,
Q_Turned = 0x3F,
Q_Rebuked = 0x40,
Q_CanBeFlanked = 0x41,
Q_Critter_Is_Grappling = 0x42,
Q_Barbarian_Raged = 0x43,
Q_Barbarian_Fatigued = 0x44,
Q_NewRound_This_Turn = 0x45,
Q_Flatfooted = 0x46,
Q_Masterwork = 0x47,
Q_FailedDecipherToday = 0x48,
Q_Polymorphed = 0x49,
Q_IsActionInvalid_CheckAction = 0x4A,
Q_CanBeAffected_PerformAction = 0x4B,
Q_CanBeAffected_ActionFrame = 0x4C,
Q_AOOWillTake = 0x4D,
Q_Weapon_Is_Mighty_Cleaving = 0x4E,
Q_Autoend_Turn = 0x4F,
Q_ExperienceExempt = 0x50,
Q_FavoredClass = 0x51,
Q_IsFallenPaladin = 0x52,
Q_WieldedTwoHanded = 0x53,
Q_Critter_Is_Immune_Energy_Drain = 0x54,
Q_Critter_Is_Immune_Death_Touch = 0x55,
Q_Failed_Copy_Scroll = 0x56,
Q_Armor_Get_AC_Bonus = 0x57,
Q_Armor_Get_Max_DEX_Bonus = 0x58,
Q_Armor_Get_Max_Speed = 0x59,
Q_FightingDefensively = 0x5A,
Q_Elemental_Gem_State = 0x5B,
Q_Untripable = 0x5C,
Q_Has_Thieves_Tools = 0x5D,
Q_Critter_Is_Encumbered_Light = 0x5E,
Q_Critter_Is_Encumbered_Medium = 0x5F,
Q_Critter_Is_Encumbered_Heavy = 0x60,
Q_Critter_Is_Encumbered_Overburdened = 0x61,
Q_Has_Aura_Of_Courage = 0x62,
Q_BardicInstrument = 0x63,
Q_EnterCombat = 0x64,
Q_AI_Fireball_OK = 0x65,
Q_Critter_Cannot_Loot = 0x66,
Q_Critter_Cannot_Wield_Items = 0x67,
Q_Critter_Is_Spell_An_Ability = 0x68,
Q_Play_Critical_Hit_Anim = 0x69,
Q_Is_BreakFree_Possible = 0x6A,
Q_Critter_Has_Mirror_Image = 0x6B,
Q_Wearing_Ring_of_Change = 0x6C,
Q_Critter_Has_No_Con_Score = 0x6D,
Q_Item_Has_Enhancement_Bonus = 0x6E,
Q_Item_Has_Keen_Bonus = 0x6F,
Q_AI_Has_Spell_Override = 0x70,
Q_Weapon_Get_Keen_Bonus = 0x71,
};
enum D20Signal : uint32_t {
S_HP_Changed = 0x0,
S_HealSkill = 0x1,
S_Sequence = 0x2,
S_Pre_Action_Sequence = 0x3,
S_Action_Recipient = 0x4,
S_BeginTurn = 0x5,
S_EndTurn = 0x6,
S_Dropped_Enemy = 0x7,
S_Concentration_Broken = 0x8,
S_Remove_Concentration = 0x9,
S_BreakFree = 0xA,
S_Spell_Cast = 0xB,
S_Spell_End = 0xC,
S_Spell_Grapple_Removed = 0xD,
S_Killed = 0xE,
S_AOOPerformed = 0xF,
S_Aid_Another = 0x10,
S_TouchAttackAdded = 0x11,
S_TouchAttack = 0x12,
S_Temporary_Hit_Points_Removed = 0x13,
S_Standing_Up = 0x14,
S_Bardic_Music_Completed = 0x15,
S_Combat_End = 0x16,
S_Initiative_Update = 0x17,
S_RadialMenu_Clear_Checkbox_Group = 0x18,
S_Combat_Critter_Moved = 0x19,
S_Hide = 0x1A,
S_Show = 0x1B,
S_Feat_Remove_Slippery_Mind = 0x1C,
S_Broadcast_Action = 0x1D,
S_Remove_Disease = 0x1E,
S_Rogue_Skill_Mastery_Init = 0x1F,
S_Spell_Call_Lightning = 0x20,
S_Magical_Item_Deactivate = 0x21,
S_Spell_Mirror_Image_Struck = 0x22,
S_Spell_Sanctuary_Attempt_Save = 0x23,
S_Experience_Awarded = 0x24,
S_Pack = 0x25,
S_Unpack = 0x26,
S_Teleport_Prepare = 0x27,
S_Teleport_Reconnect = 0x28,
S_Atone_Fallen_Paladin = 0x29,
S_Summon_Creature = 0x2A,
S_Attack_Made = 0x2B,
S_Golden_Skull_Combine = 0x2C,
S_Inventory_Update = 0x2D,
S_Critter_Killed = 0x2E,
S_SetPowerAttack = 0x2F,
S_SetExpertise = 0x30,
S_SetCastDefensively = 0x31,
S_Resurrection = 0x32,
S_Dismiss_Spells = 0x33,
S_DealNormalDamage = 0x34,
S_Update_Encumbrance = 0x35,
S_Remove_AI_Controlled = 0x36,
S_Verify_Obj_Conditions = 0x37,
S_Web_Burning = 0x38,
S_Anim_CastConjureEnd = 0x39,
S_Item_Remove_Enhancement = 0x3A,
};
enum D20DispatcherKey : uint32_t {
DK_NONE = 0x0,
DK_STAT_STRENGTH = 1,
DK_STAT_DEXTERITY = 2,
DK_STAT_CONSTITUTION = 3,
DK_STAT_INTELLIGENCE = 4,
DK_STAT_WISDOM = 5,
DK_STAT_CHARISMA = 6,
DK_SAVE_FORTITUDE = 7,
DK_SAVE_REFLEX = 8,
DK_SAVE_WILL = 9,
DK_IMMUNITY_SPELL = 10,
DK_IMMUNITY_11 = 11,
DK_IMMUNITY_12 = 12, // used in AI Controlled, Blindness, and Dominate. Might be a bug, but it doesn't seem to be handled in the immunity handler anyway
DK_IMMUNITY_COURAGE = 13, // used in Aura of Courage
DK_IMMUNITY_RACIAL = 14, // actually just Undead and Ooze use this
DK_IMMUNITY_15 = 15,
DK_IMMUNITY_SPECIAL = 16,
DK_OnEnterAoE = 18,
DK_OnLeaveAoE = 19,
DK_SKILL_APPRAISE = 20,
DK_SKILL_BLUFF = 21,
DK_SKILL_CONCENTRATION = 22,
DK_SKILL_RIDE = 59,
DK_SKILL_SWIM = 60,
DK_SKILL_USE_ROPE = 61,
DK_CL_Level = 63, // used for queries that regard negative levels
DK_CL_Barbarian = 64,
DK_CL_Bard = 65,
DK_CL_Cleric = 66,
DK_CL_Druid = 67,
DK_CL_Fighter = 68,
DK_CL_Monk = 69,
DK_CL_Paladin = 70,
DK_CL_Ranger = 71,
DK_CL_Rogue = 72,
DK_CL_Sorcerer = 73,
DK_CL_Wizard = 74,
DK_D20A_UNSPECIFIED_MOVE =75,
DK_D20A_UNSPECIFIED_ATTACK,
DK_D20A_STANDARD_ATTACK,
DK_D20A_FULL_ATTACK,
DK_D20A_STANDARD_RANGED_ATTACK,
DK_D20A_RELOAD,
DK_D20A_5FOOTSTEP,
DK_D20A_MOVE,
DK_D20A_DOUBLE_MOVE,
DK_D20A_RUN,
DK_D20A_CAST_SPELL,
DK_D20A_HEAL,
DK_D20A_CLEAVE,
DK_D20A_ATTACK_OF_OPPORTUNITY,
DK_D20A_WHIRLWIND_ATTACK,
DK_D20A_TOUCH_ATTACK,
DK_D20A_TOTAL_DEFENSE,
DK_D20A_CHARGE,
DK_D20A_FALL_TO_PRONE,
DK_D20A_STAND_UP,
DK_D20A_TURN_UNDEAD,
DK_D20A_DEATH_TOUCH,
DK_D20A_PROTECTIVE_WARD,
DK_D20A_FEAT_OF_STRENGTH,
DK_D20A_BARDIC_MUSIC,
DK_D20A_PICKUP_OBJECT,
DK_D20A_COUP_DE_GRACE,
DK_D20A_USE_ITEM,
DK_D20A_BARBARIAN_RAGE,
DK_D20A_STUNNING_FIST,
DK_D20A_SMITE_EVIL,
DK_D20A_LAY_ON_HANDS_SET,
DK_D20A_DETECT_EVIL,
DK_D20A_STOP_CONCENTRATION,
DK_D20A_BREAK_FREE,
DK_D20A_TRIP,
DK_D20A_REMOVE_DISEASE,
DK_D20A_ITEM_CREATION,
DK_D20A_WHOLENESS_OF_BODY_SET,
DK_D20A_USE_MAGIC_DEVICE_DECIPHER_WRITTEN_SPELL,
DK_D20A_TRACK,
DK_D20A_ACTIVATE_DEVICE_STANDARD,
DK_D20A_SPELL_CALL_LIGHTNING,
DK_D20A_AOO_MOVEMENT,
DK_D20A_CLASS_ABILITY_SA,
DK_D20A_ACTIVATE_DEVICE_FREE,
DK_D20A_OPEN_INVENTORY,
DK_D20A_ACTIVATE_DEVICE_SPELL,
DK_D20A_DISABLE_DEVICE,
DK_D20A_SEARCH,
DK_D20A_SNEAK,
DK_D20A_TALK,
DK_D20A_OPEN_LOCK,
DK_D20A_SLEIGHT_OF_HAND,
DK_D20A_OPEN_CONTAINER,
DK_D20A_THROW,
DK_D20A_THROW_GRENADE,
DK_D20A_FEINT,
DK_D20A_READY_SPELL,
DK_D20A_READY_COUNTERSPELL,
DK_D20A_READY_ENTER,
DK_D20A_READY_EXIT,
DK_D20A_COPY_SCROLL,
DK_D20A_READIED_INTERRUPT,
DK_D20A_LAY_ON_HANDS_USE,
DK_D20A_WHOLENESS_OF_BODY_USE,
DK_D20A_DISMISS_SPELLS,
DK_D20A_FLEE_COMBAT,
DK_D20A_USE_POTION,
DK_D20A_DIVINE_MIGHT = 144,
DK_D20A_EMPTY_BODY = 145,
DK_D20A_QUIVERING_PALM = 146,
DK_NEWDAY_REST = 145, // for successfully resting (is also triggered for an 8 hour uninterrupted rest period)
DK_NEWDAY_CALENDARICAL = 146, // for starting a new calendarical day (or artificially adding a days period); I think it's only used for disease timers
DK_SIG_HP_Changed = 147,
DK_SIG_HealSkill = 0x94,
DK_SIG_Sequence = 0x95,
DK_SIG_Pre_Action_Sequence = 0x96,
DK_SIG_Action_Recipient = 0x97,
DK_SIG_BeginTurn = 0x98,
DK_SIG_EndTurn = 0x99,
DK_SIG_Dropped_Enemy = 0x9A,
DK_SIG_Concentration_Broken = 0x9B,
DK_SIG_Remove_Concentration = 0x9C,
DK_SIG_BreakFree = 0x9D,
DK_SIG_Spell_Cast = 0x9E,
DK_SIG_Spell_End = 0x9F,
DK_SIG_Spell_Grapple_Removed = 0xA0,
DK_SIG_Killed = 0xA1,
DK_SIG_AOOPerformed = 0xA2,
DK_SIG_Aid_Another = 0xA3,
DK_SIG_TouchAttackAdded = 0xA4,
DK_SIG_TouchAttack = 0xA5,
DK_SIG_Temporary_Hit_Points_Removed = 0xA6,
DK_SIG_Standing_Up = 0xA7,
DK_SIG_Bardic_Music_Completed = 0xA8,
DK_SIG_Combat_End = 0xA9,
DK_SIG_Initiative_Update = 0xAA,
DK_SIG_RadialMenu_Clear_Checkbox_Group = 0xAB,
DK_SIG_Combat_Critter_Moved = 0xAC,
DK_SIG_Hide = 0xAD,
DK_SIG_Show = 0xAE,
DK_SIG_Feat_Remove_Slippery_Mind = 0xAF,
DK_SIG_Broadcast_Action = 0xB0,
DK_SIG_Remove_Disease = 0xB1,
DK_SIG_Rogue_Skill_Mastery_Init = 0xB2,
DK_SIG_Spell_Call_Lightning = 0xB3,
DK_SIG_Magical_Item_Deactivate = 0xB4,
DK_SIG_Spell_Mirror_Image_Struck = 0xB5,
DK_SIG_Spell_Sanctuary_Attempt_Save = 0xB6,
DK_SIG_Experience_Awarded = 0xB7,
DK_SIG_Pack = 0xB8,
DK_SIG_Unpack = 0xB9,
DK_SIG_Teleport_Prepare = 0xBA,
DK_SIG_Teleport_Reconnect = 0xBB,
DK_SIG_Atone_Fallen_Paladin = 0xBC,
DK_SIG_Summon_Creature = 0xBD,
DK_SIG_Attack_Made = 0xBE,
DK_SIG_Golden_Skull_Combine = 0xBF,
DK_SIG_Inventory_Update = 0xC0,
DK_SIG_Critter_Killed = 0xC1,
DK_SIG_SetPowerAttack = 0xC2,
DK_SIG_SetExpertise = 0xC3,
DK_SIG_SetCastDefensively = 0xC4,
DK_SIG_Resurrection = 0xC5,
DK_SIG_Dismiss_Spells = 0xC6,
DK_SIG_DealNormalDamage = 0xC7,
DK_SIG_Update_Encumbrance = 0xC8,
DK_SIG_Remove_AI_Controlled = 0xC9,
DK_SIG_Verify_Obj_Conditions = 0xCA,
DK_SIG_Web_Burning = 0xCB,
DK_SIG_Anim_CastConjureEnd = 0xCC,
DK_SIG_Item_Remove_Enhancement = 0xCD,
DK_SIG_Disarmed_Weapon_Retrieve = 0xCE, // NEW
DK_SIG_Disarm = 0xCF, // NEW; resets the "took damage -> abort" flag
DK_SIG_AID_ANOTHER_WAKE_UP = 0xD0,
DK_QUE_Helpless = 0xCF,
DK_QUE_SneakAttack = 0xD0,
DK_QUE_OpponentSneakAttack = 0xD1,
DK_QUE_CoupDeGrace = 0xD2,
DK_QUE_Mute = 0xD3,
DK_QUE_CannotCast = 0xD4,
DK_QUE_CannotUseIntSkill = 0xD5,
DK_QUE_CannotUseChaSkill = 0xD6,
DK_QUE_RapidShot = 0xD7,
DK_QUE_Critter_Is_Concentrating = 0xD8,
DK_QUE_Critter_Is_On_Consecrate_Ground = 0xD9,
DK_QUE_Critter_Is_On_Desecrate_Ground = 0xDA,
DK_QUE_Critter_Is_Held = 0xDB,
DK_QUE_Critter_Is_Invisible = 0xDC,
DK_QUE_Critter_Is_Afraid = 0xDD,
DK_QUE_Critter_Is_Blinded = 0xDE,
DK_QUE_Critter_Is_Charmed = 0xDF,
DK_QUE_Critter_Is_Confused = 0xE0,
DK_QUE_Critter_Is_AIControlled = 0xE1,
DK_QUE_Critter_Is_Cursed = 0xE2,
DK_QUE_Critter_Is_Deafened = 0xE3,
DK_QUE_Critter_Is_Diseased = 0xE4,
DK_QUE_Critter_Is_Poisoned = 0xE5,
DK_QUE_Critter_Is_Stunned = 0xE6,
DK_QUE_Critter_Is_Immune_Critical_Hits = 0xE7,
DK_QUE_Critter_Is_Immune_Poison = 0xE8,
DK_QUE_Critter_Has_Spell_Resistance = 0xE9,
DK_QUE_Critter_Has_Condition = 0xEA,
DK_QUE_Critter_Has_Freedom_of_Movement = 0xEB,
DK_QUE_Critter_Has_Endure_Elements = 0xEC,
DK_QUE_Critter_Has_Protection_From_Elements = 0xED,
DK_QUE_Critter_Has_Resist_Elements = 0xEE,
DK_QUE_Critter_Has_True_Seeing = 0xEF,
DK_QUE_Critter_Has_Spell_Active = 0xF0,
DK_QUE_Critter_Can_Call_Lightning = 0xF1,
DK_QUE_Critter_Can_See_Invisible = 0xF2,
DK_QUE_Critter_Can_See_Darkvision = 0xF3,
DK_QUE_Critter_Can_See_Ethereal = 0xF4,
DK_QUE_Critter_Can_Discern_Lies = 0xF5,
DK_QUE_Critter_Can_Detect_Chaos = 0xF6,
DK_QUE_Critter_Can_Detect_Evil = 0xF7,
DK_QUE_Critter_Can_Detect_Good = 0xF8,
DK_QUE_Critter_Can_Detect_Law = 0xF9,
DK_QUE_Critter_Can_Detect_Magic = 0xFA,
DK_QUE_Critter_Can_Detect_Undead = 0xFB,
DK_QUE_Critter_Can_Find_Traps = 0xFC,
DK_QUE_Critter_Can_Dismiss_Spells = 0xFD,
DK_QUE_Obj_Is_Blessed = 0xFE,
DK_QUE_Unconscious = 0xFF,
DK_QUE_Dying = 0x100,
DK_QUE_Dead = 0x101,
DK_QUE_AOOPossible = 0x102,
DK_QUE_AOOIncurs = 0x103,
DK_QUE_HoldingCharge = 0x104,
DK_QUE_Has_Temporary_Hit_Points = 0x105,
DK_QUE_SpellInterrupted = 0x106,
DK_QUE_ActionTriggersAOO = 0x107,
DK_QUE_ActionAllowed = 0x108,
DK_QUE_Prone = 0x109,
DK_QUE_RerollSavingThrow = 0x10A,
DK_QUE_RerollAttack = 0x10B,
DK_QUE_RerollCritical = 0x10C,
DK_QUE_Commanded = 0x10D,
DK_QUE_Turned = 0x10E,
DK_QUE_Rebuked = 0x10F,
DK_QUE_CanBeFlanked = 0x110,
DK_QUE_Critter_Is_Grappling = 0x111,
DK_QUE_Barbarian_Raged = 0x112,
DK_QUE_Barbarian_Fatigued = 0x113,
DK_QUE_NewRound_This_Turn = 0x114,
DK_QUE_Flatfooted = 0x115,
DK_QUE_Masterwork = 0x116,
DK_QUE_FailedDecipherToday = 0x117,
DK_QUE_Polymorphed = 0x118,
DK_QUE_IsActionInvalid_CheckAction = 0x119,
DK_QUE_CanBeAffected_PerformAction = 0x11A,
DK_QUE_CanBeAffected_ActionFrame = 0x11B,
DK_QUE_AOOWillTake = 0x11C,
DK_QUE_Weapon_Is_Mighty_Cleaving = 0x11D,
DK_QUE_Autoend_Turn = 0x11E,
DK_QUE_ExperienceExempt = 0x11F,
DK_QUE_FavoredClass = 0x120,
DK_QUE_IsFallenPaladin = 0x121,
DK_QUE_WieldedTwoHanded = 0x122,
DK_QUE_Critter_Is_Immune_Energy_Drain = 0x123,
DK_QUE_Critter_Is_Immune_Death_Touch = 0x124,
DK_QUE_Failed_Copy_Scroll = 0x125,
DK_QUE_Armor_Get_AC_Bonus = 0x126,
DK_QUE_Armor_Get_Max_DEX_Bonus = 0x127,
DK_QUE_Armor_Get_Max_Speed = 0x128,
DK_QUE_FightingDefensively = 0x129,
DK_QUE_Elemental_Gem_State = 0x12A,
DK_QUE_Untripable = 0x12B,
DK_QUE_Has_Thieves_Tools = 0x12C,
DK_QUE_Critter_Is_Encumbered_Light = 0x12D,
DK_QUE_Critter_Is_Encumbered_Medium = 0x12E,
DK_QUE_Critter_Is_Encumbered_Heavy = 0x12F,
DK_QUE_Critter_Is_Encumbered_Overburdened = 0x130,
DK_QUE_Has_Aura_Of_Courage = 0x131,
DK_QUE_BardicInstrument = 0x132,
DK_QUE_EnterCombat = 0x133,
DK_QUE_AI_Fireball_OK = 0x134,
DK_QUE_Critter_Cannot_Loot = 0x135,
DK_QUE_Critter_Cannot_Wield_Items = 0x136,
DK_QUE_Critter_Is_Spell_An_Ability = 0x137,
DK_QUE_Play_Critical_Hit_Anim = 0x138,
DK_QUE_Is_BreakFree_Possible = 0x139,
DK_QUE_Critter_Has_Mirror_Image = 0x13A,
DK_QUE_Wearing_Ring_of_Change = 0x13B,
DK_QUE_Critter_Has_No_Con_Score = 0x13C,
DK_QUE_Item_Has_Enhancement_Bonus = 0x13D,
DK_QUE_Item_Has_Keen_Bonus = 0x13E,
DK_QUE_AI_Has_Spell_Override = 0x13F,
DK_QUE_Weapon_Get_Keen_Bonus = 0x140,
DK_QUE_Disarmed = 0x141,
DK_SIG_Destruction_Domain_Smite = 0x142,
DK_QUE_Can_Perform_Disarm = 0x143,
DK_QUE_Craft_Wand_Spell_Level = 0x144,
DK_QUE_Is_Ethereal = 0x145,
DK_QUE_Empty_Body_Num_Rounds = 0x146, // returns number of rounds set for Monk's Empty Body
DK_QUE_Quivering_Palm_Can_Perform = 0x147,
DK_QUE_Trip_AOO = 0x148,
DK_QUE_Get_Arcane_Spell_Failure = 0x149, // returns additive spell failure chance
DK_QUE_Is_Preferring_One_Handed_Wield = 0x14A, // e.g. a character with a Buckler can opt to wield a sword one handed so as to not take the -1 to hit penalty
DK_QUE_Scribe_Scroll_Spell_Level = 0x14B,
DK_QUE_Critter_Is_Immune_Paralysis = 0x14C,
DK_LVL_Stats_Activate = 100,
DK_LVL_Stats_Check_Complete = 101,
DK_LVL_Stats_Finalize = 102,
DK_LVL_Features_Activate = 200,
DK_LVL_Features_Check_Complete = 201,
DK_LVL_Features_Finalize = 202,
DK_LVL_Skills_Activate = 300,
DK_LVL_Skills_Check_Complete = 301,
DK_LVL_Skills_Finalize = 302,
DK_LVL_Feats_Activate = 400,
DK_LVL_Feats_Check_Complete = 401,
DK_LVL_Feats_Finalize = 402,
DK_LVL_Spells_Activate = 500,
DK_LVL_Spells_Check_Complete = 501,
DK_LVL_Spells_Finalize = 502,
DK_SPELL_Base_Caster_Level = 1000,
DK_SPELL_Base_Caster_Level_2 = 1001
};
enum enum_dispIO_type : uint32_t {
dispIoTypeNull= 0, // not in actual use (other than init), first real type is the next one
dispIoTypeCondStruct,
dispIOTypeBonusList,
dispIOTypeSavingThrow,
dispIOTypeDamage,
dispIOTypeAttackBonus, // AC
dispIoTypeSendSignal, // Usages detected: dispTypeD20AdvanceTime (6), dispTypeBeginRound (48), and of course also dispTypeD20Signal (28)
dispIOTypeQuery,
dispIOTypeTurnBasedStatus,
dispIoTypeTooltip,
dispIoTypeObjBonus, // used for skill level, initiative level, and attacker concealment chance
dispIOTypeDispelCheck, // goes with dispTypeDispelCheck
dispIOTypeD20ActionTurnBased,
dispIOTypeMoveSpeed,
dispIoTypeBonusListAndSpellEntry,
dispIOTypeReflexThrow,
dispIOType16,
dispIoTypeObjEvent,
dispIOType18,
dispIOType19,
dispIOType20,
dispIOType21ImmunityTrigger,
dispIOType22,
dispIOTypeImmunityHandler,
dispIOTypeEffectTooltip,
dispIOType25,
dispIOType26,
dispIOType27,
dispIOType28,
dispIOType29,
dispIOType30,
dispIOType31,
dispIOType32,
dispIOType33,
evtObjTypeSpellCaster, // new! used for querying spell caster specs (caster level, learnable spells, etc.)
evtObjTypeActionCost, // new! used for modifying action cost
evtObjTypeAddMesh,
};
// Note: if you add new stuff here, it must be on top! Otherwise python sync is ruined
enum enum_disp_type : uint32_t {
dispType0 = 0,
dispTypeConditionAdd,
dispTypeConditionRemove,
dispTypeConditionAddPre,
dispTypeConditionRemove2,
dispTypeConditionAddFromD20StatusInit,
dispTypeD20AdvanceTime,
dispTypeTurnBasedStatusInit,
dispTypeInitiative,
dispTypeNewDay, // refers both to an uninterrupted 8 hour rest period (key 0x91), or a 1 day rest period (key 0x91), or a new calendarical day (with key 0x92)
dispTypeAbilityScoreLevel,
dispTypeGetAC,
dispTypeAcModifyByAttacker, // modifies defender's Armor Class by attacker conditions (e.g. if the attacker is Invisible, they will have a hook that nullifies the defender's dexterity bonus using this event type)
dispTypeSaveThrowLevel, // goes with keys DK_SAVE_X
dispTypeSaveThrowSpellResistanceBonus, // only used for Inward Magic Circle
dispTypeToHitBonusBase,
dispTypeToHitBonus2,
dispTypeToHitBonusFromDefenderCondition, // e.g. if the defender has Blindness, the attacker will get a bonus for his To Hit
dispTypeDealingDamage,
dispTypeTakingDamage,
dispTypeDealingDamage2,
dispTypeTakingDamage2,
dispTypeReceiveHealing, // Healing
dispTypeGetCriticalHitRange, // first hit roll that is a critical hit
dispTypeGetCriticalHitExtraDice, // runs for the attacker's dispatcher
dispTypeCurrentHP,
dispTypeMaxHP,
dispTypeInitiativeMod,
dispTypeD20Signal = 28,
dispTypeD20Query = 29,
dispTypeSkillLevel,
dispTypeRadialMenuEntry,
dispTypeTooltip,
dispTypeDispelCheck,
dispTypeGetDefenderConcealmentMissChance, // defender bonus (e.g. if defender is invisible)
dispTypeBaseCasterLevelMod,
dispTypeD20ActionCheck,
dispTypeD20ActionPerform,
dispTypeD20ActionOnActionFrame,
dispTypeDestructionDomain,
dispTypeGetMoveSpeedBase,
dispTypeGetMoveSpeed,
dispTypeAbilityCheckModifier, // only used in Trip as far as I can tell for stuff like Sickened condition
dispTypeGetAttackerConcealmentMissChance, // attacker penalty (e.g. if attacker is blind). Also applies to stuff like Blink spell
dispTypeCountersongSaveThrow,
dispTypeSpellResistanceMod,
dispTypeSpellDcBase, // haven't seen this actually used, just the mod dispatch (for Spell Focus and the Gnome bonus for Illusion spells)
dispTypeSpellDcMod,
dispTypeBeginRound, // immediately followed by the OnBeginRound spell trigger. Commonly used for spell countdown / removal when finished. Note: normally this is reserved for critters, but some spells will explicitly add items/objects to the d20 object registry (via d20_status_init), whose member get BeginRound events.
dispTypeReflexThrow,
dispTypeDeflectArrows,
dispTypeGetNumAttacksBase,
dispTypeGetBonusAttacks,
dispTypeGetCritterNaturalAttacksNum,
dispTypeObjectEvent, // Enter or leaving the area of effect of an object event
dispTypeProjectileCreated, // Used to create the particle effects for arrows and such
dispTypeProjectileDestroyed, // Used to stop the particle effects for arrows
dispType57, // Unused
dispType58, // Unused
dispTypeGetAbilityLoss = 59,
dispTypeGetAttackDice,
dispTypeGetLevel, // Class or Character Level (using stat enum)
dispTypeImmunityTrigger = 62,
dispType63,
dispTypeSpellImmunityCheck,
dispTypeEffectTooltip, // for those little bonus flags on top of portraits
dispTypeStatBaseGet, // this is actually stat_base + permanent modifiers (basically race)
dispTypeWeaponGlowType, // Returns the ID of the weapon glow to use (0 = no glow, 1-10 are specific glow types, check mapobjrenderer)
dispTypeItemForceRemove, // has a single function associated with this - 10104410 int __cdecl ItemForceRemoveCallback_SetItemPadWielderArgs(Dispatcher_Callback_Args args);
dispTypeArmorToHitPenalty = 69, // none exist apparently
dispTypeMaxDexAcBonus,
dispTypeGetSizeCategory,
dispTypeBucklerAcPenalty,
dispTypeGetModelScale = 73, // NEW! used for modifying the model scale with messing with internal fields
dispTypePythonQuery = 74, // NEW! for handling python dispatcher queries
dispTypePythonSignal = 75,
dispTypePythonActionCheck = 76,
dispTypePythonActionPerform,
dispTypePythonActionFrame,
dispTypePythonActionAdd, // add to sequence
dispTypePythonAdf, // for expansion
dispTypePythonUnused3, // for expansion
dispTypePythonUnused4, // for expansion
dispTypePythonUnused5, // for expansion
dispTypePythonUnused6, // for expansion
dispTypePythonUnused7, // for expansion
dispTypePythonUnused8, // for expansion
dispTypePythonUnused9, // for expansion
dispTypeSpellListExtension = 88, // NEW! used for extending spell-casting classes by other classes (as with Prestige Classes)
dispTypeGetBaseCasterLevel,
dispTypeLevelupSystemEvent,
dispTypeDealingDamageWeaponlikeSpell,
dispTypeActionCostMod,
dispTypeMetaMagicMod,
dispTypeSpecialAttack,
dispConfirmCriticalBonus,
dispRangeIncrementBonus,
dispTypeDealingDamageSpell,
dispTypeSpellResistanceCasterLevelCheck = 98,
dispTypeTargetSpellDCBonus = 99,
dispTypeIgnoreDruidOathCheck = 100,
dispTypeSpellCasterGeneral = 101, // Uses EvtObjSpellCaster, to be used with specific keys only!
dispTypeAddMesh = 102, // used to fetch additional addmeshes
dispTypeCount // used just for size definition purposes
};
enum Domain
{
Domain_None = 0,
Domain_Air = 1,
Domain_Animal = 2,
Domain_Chaos = 3,
Domain_Death = 4,
Domain_Destruction = 5,
Domain_Earth = 6,
Domain_Evil = 7,
Domain_Fire = 8,
Domain_Good = 9,
Domain_Healing = 10,
Domain_Knowledge = 11,
Domain_Law = 12,
Domain_Luck = 13,
Domain_Magic = 14,
Domain_Plant = 15,
Domain_Protection = 16,
Domain_Strength = 17,
Domain_Sun = 18,
Domain_Travel = 19,
Domain_Trickery = 20,
Domain_War = 21,
Domain_Water = 22,
Domain_Special = 23,
Domain_Count = 24
};
#pragma endregion
#pragma region Critter
enum Stat : uint32_t {
stat_strength = 0x0,
stat_dexterity = 0x1,
stat_constitution = 0x2,
stat_intelligence = 0x3,
stat_wisdom = 0x4,
stat_charisma = 0x5,
stat_level = 0x6,
stat_level_barbarian = 0x7,
stat_level_bard = 0x8,
stat_level_cleric = 0x9,
stat_level_druid = 0xA,
stat_level_fighter = 0xB,
stat_level_monk = 0xC,
stat_level_paladin = 0xD,
stat_level_ranger = 0xE,
stat_level_rogue = 0xF,
stat_level_sorcerer = 0x10,
stat_level_wizard = 0x11,
stat_level_arcane_archer = 18,
stat_level_arcane_trickster = 19,
stat_level_archmage = 20,
stat_level_assassin = 21,
stat_level_blackguard = 22,
stat_level_dragon_disciple = 23,
stat_level_duelist = 24,
stat_level_dwarven_defender = 25,
stat_level_eldritch_knight = 26,
stat_level_hierophant = 27,
stat_level_horizon_walker = 28,
stat_level_loremaster = 29,
stat_level_mystic_theurge = 30,
stat_level_shadowdancer = 31,
stat_level_thaumaturgist = 32,
stat_level_warlock = 33,
stat_level_favored_soul = 34,
stat_level_red_avenger = 35,
stat_level_iaijutsu_master = 36,
stat_level_sacred_fist = 37,
stat_level_stormlord = 38,
stat_level_elemental_savant = 39,
stat_level_blood_magus = 40,
stat_level_beastmaster = 41,
stat_level_cryokineticist = 42,
stat_level_frost_mage = 43,
stat_level_artificer = 44,
stat_level_abjurant_champion = 45,
stat_level_scout = 46,
stat_level_warmage = 47,
stat_level_beguilers = 48,
stat_level_swashbuckler = 49,
stat_level_psion = 58,
stat_level_psychic_warrior = 59,
stat_level_soulknife = 60,
stat_level_wilder = 61,
stat_level_cerebmancer = 62,
stat_level_elocator = 63,
stat_level_metamind = 64,
stat_level_psion_uncarnate = 65,
stat_level_psionic_fist = 66,
stat_level_pyrokineticist = 67,
stat_level_slayer = 68,
stat_level_thrallherd = 69,
stat_level_war_mind = 70,
stat_level_crusader = 71,
stat_level_swordsage = 72,
stat_level_warblade = 73,
stat_level_bloodclaw_master = 74,
stat_level_bloodstorm_blade = 75,
stat_level_deepstone_sentinel = 76,
stat_level_eternal_blade = 77,
stat_level_jade_phoenix_mage = 78,
stat_level_master_of_nine = 79,
stat_level_ruby_knight_vindicator = 80,
stat_level_shadow_sun_ninja = 81,
stat_level_fochlucan_lyrist = 82,
stat_hp_max = 0xE4,
stat_hp_current = 0xE5,
stat_race = 0xE6,
stat_category = 0xE7,
stat_gender = 0xE8,
stat_age = 0xE9,
stat_height = 0xEA,
stat_weight = 0xEB,
stat_size = 0xEC,
stat_experience = 0xED,
stat_alignment = 0xEE,
stat_deity = 0xEF,
stat_domain_1 = 0xF0,
stat_domain_2 = 0xF1,
stat_alignment_choice = 0xF2,
stat_favored_enemies = 0xF3,
stat_known_spells = 0xF4,
stat_memorized_spells = 0xF5,
stat_spells_per_day = 0xF6,
stat_school_specialization = 0xF7,
stat_school_prohibited = 0xF8,
stat_money = 0xF9,
stat_money_pp = 0xFA,
stat_money_gp = 0xFB,
stat_money_ep = 0xFC,
stat_money_sp = 0xFD,
stat_money_cp = 0xFE,
stat_str_mod = 0xFF,
stat_dex_mod = 0x100,
stat_con_mod = 0x101,
stat_int_mod = 0x102,
stat_wis_mod = 0x103,
stat_cha_mod = 0x104,
stat_ac = 0x105,
stat_initiative_bonus = 0x106,
stat_save_reflexes = 0x107,
stat_save_fortitude = 0x108,
stat_save_willpower = 0x109,
stat_attack_bonus = 0x10A,
stat_damage_bonus = 0x10B,
stat_carried_weight = 0x10C,
stat_movement_speed = 0x10D,
stat_run_speed = 0x10E,
stat_load = 0x10F,
stat_subdual_damage = 0x110,
stat_caster_level = 0x111,
stat_caster_level_barbarian = 0x112,
stat_caster_level_bard = 0x113,
stat_caster_level_cleric = 0x114,
stat_caster_level_druid = 0x115,
stat_caster_level_fighter = 0x116,
stat_caster_level_monk = 0x117,
stat_caster_level_paladin = 0x118,
stat_caster_level_ranger = 0x119,
stat_caster_level_rogue = 0x11A,
stat_caster_level_sorcerer = 283,
stat_caster_level_wizard = 284,
stat_subrace = 285,
stat_melee_attack_bonus = 286,
stat_ranged_attack_bonus = 287,
stat_spell_list_level = 288, // NEW! used for getting the extended spell lists (modified by PrC's and such)
stat_psi_points_max = 300,
stat_psi_points_cur = 301,
_stat_count // for internal use
};
enum MonsterCategory : uint32_t {
mc_type_aberration = 0,
mc_type_animal = 1,
mc_type_beast = 2,
mc_type_construct = 3,
mc_type_dragon = 4,
mc_type_elemental = 5,
mc_type_fey = 6,
mc_type_giant = 7,
mc_type_humanoid = 8,
mc_type_magical_beast = 9,
mc_type_monstrous_humanoid = 10,
mc_type_ooze = 11,
mc_type_outsider = 12,
mc_type_plant = 13,
mc_type_shapechanger = 14,
mc_type_undead = 15,
mc_type_vermin = 16
};
enum MonsterSubcategoryFlag: uint32_t
{
mc_subtype_air = 1,
mc_subtype_aquatic = 2,
mc_subtype_extraplanar = 4,
mc_subtype_cold = 8,
mc_subtype_chaotic = 16,
mc_subtype_demon = 32,
mc_subtype_devil = 64,
mc_subtype_dwarf = 128,
mc_subtype_earth = 256,
mc_subtype_electricity = 512,
mc_subtype_elf = 1024,
mc_subtype_evil = 2048,
mc_subtype_fire = 0x1000,
mc_subtype_formian = 0x2000,
mc_subtype_gnoll = 0x4000,
mc_subtype_gnome = 0x8000,
mc_subtype_goblinoid = 0x10000,
mc_subtype_good = 0x20000,
mc_subtype_guardinal = 0x40000,
mc_subtype_half_orc = 0x80000,
mc_subtype_halfling = 0x100000,
mc_subtype_human = 0x200000,
mc_subtype_lawful = 0x400000,
mc_subtype_incorporeal = 0x800000,
mc_subtype_orc = 0x1000000,
mc_subtype_reptilian = 0x2000000,
mc_subtype_slaadi = 0x4000000,
mc_subtype_water = 0x8000000
};
enum CritterFlag
{
OCF_IS_CONCEALED = 0x1,
OCF_MOVING_SILENTLY = 0x2,
OCF_EXPERIENCE_AWARDED = 0x4,
OCF_UNUSED_00000008 = 0x8,
OCF_FLEEING = 0x10,
OCF_STUNNED = 0x20,
OCF_PARALYZED = 0x40,
OCF_BLINDED = 0x80,
OCF_HAS_ARCANE_ABILITY = 0x100,
OCF_UNUSED_00000200 = 0x200,
OCF_UNUSED_00000400 = 0x400,
OCF_UNUSED_00000800 = 0x800,
OCF_SLEEPING = 0x1000,
OCF_MUTE = 0x2000,
OCF_SURRENDERED = 0x4000,
OCF_MONSTER = 0x8000,
OCF_SPELL_FLEE = 0x10000,
OCF_ENCOUNTER = 0x20000,
OCF_COMBAT_MODE_ACTIVE = 0x40000,
OCF_LIGHT_SMALL = 0x80000,
OCF_LIGHT_MEDIUM = 0x100000,
OCF_LIGHT_LARGE = 0x200000,
OCF_LIGHT_XLARGE = 0x400000,
OCF_UNREVIVIFIABLE = 0x800000,
OCF_UNRESURRECTABLE = 0x1000000,
OCF_UNUSED_02000000 = 0x2000000,
OCF_UNUSED_04000000 = 0x4000000,
OCF_NO_FLEE = 0x8000000,
OCF_NON_LETHAL_COMBAT = 0x10000000,
OCF_MECHANICAL = 0x20000000,
OCF_UNUSED_40000000 = 0x40000000,
OCF_FATIGUE_LIMITING = 0x80000000,
};
enum CritterFlags2
{
OCF2_ITEM_STOLEN = 0x1,
OCF2_AUTO_ANIMATES = 0x2,
OCF2_USING_BOOMERANG = 0x4,
OCF2_FATIGUE_DRAINING = 0x8,
OCF2_SLOW_PARTY = 0x10,
OCF2_20 = 0x20,
OCF2_NO_DECAY = 0x40,
OCF2_NO_PICKPOCKET = 0x80,
OCF2_NO_BLOOD_SPLOTCHES = 0x100,
OCF2_NIGH_INVULNERABLE = 0x200,
OCF2_ELEMENTAL = 0x400,
OCF2_DARK_SIGHT = 0x800,
OCF2_NO_SLIP = 0x1000,
OCF2_NO_DISINTEGRATE = 0x2000,
OCF2_REACTION_0 = 0x4000,
OCF2_REACTION_1 = 0x8000,
OCF2_REACTION_2 = 0x10000,
OCF2_REACTION_3 = 0x20000,
OCF2_REACTION_4 = 0x40000,
OCF2_REACTION_5 = 0x80000,
OCF2_REACTION_6 = 0x100000,
OCF2_TARGET_LOCK = 0x200000,
OCF2_ACTION0_PAUSED = 0x400000,
OCF2_ACTION1_PAUSED = 0x800000,
OCF2_ACTION2_PAUSED = 0x1000000,
OCF2_ACTION3_PAUSED = 0x2000000,
OCF2_ACTION4_PAUSED = 0x4000000,
OCF2_ACTION5_PAUSED = 0x8000000,
/*OCF2_ACTION6_PAUSED = 0x10000000,
OCF2_ = 0x20000000,
OCF2_ = 0x40000000,
OCF2_ = 0x80000000*/
};
enum Alignment : uint32_t {
ALIGNMENT_NEUTRAL = 0,
ALIGNMENT_LAWFUL = 1,
ALIGNMENT_CHAOTIC = 2,
ALIGNMENT_GOOD = 4,
ALIGNMENT_EVIL = 8,
ALIGNMENT_TRUE_NEUTRAL = 0,
ALIGNMENT_LAWFUL_NEUTRAL = 1,
ALIGNMENT_CHAOTIC_NEUTRAL = 2,
ALIGNMENT_NEUTRAL_GOOD = 4,
ALIGNMENT_LAWFUL_GOOD = 5,
ALIGNMENT_CHAOTIC_GOOD = 6,
ALIGNMENT_NEUTRAL_EVIL = 8,
ALIGNMENT_LAWFUL_EVIL = 9,
ALIGNMENT_CHAOTIC_EVIL = 10,
};
enum RaceBase
{
race_base_human = 0,
race_base_dwarf = 1,
race_base_elf = 2,
race_base_gnome = 3,
race_base_halfelf = 4,
race_base_half_elf = 4,
race_base_halforc = 5,
race_base_half_orc = 5,
race_base_halfling = 6,
race_base_goblin = 7,
race_base_bugbear = 8,
race_base_gnoll = 9,
race_base_hill_giant = 10,
race_base_troll = 11,
race_base_hobgoblin = 12,
race_base_lizardman = 13,
};
enum Race : uint32_t
{
race_human = 0,
race_dwarf = 1,
race_elf = 2,
race_gnome = 3,
race_halfelf = 4,
race_half_elf = 4,
race_halforc = 5,
race_half_orc = 5,
race_halfling = 6,
race_goblin = 7,
race_bugbear = 8,
race_gnoll = 9,
race_hill_giant = 10,
race_troll = 11,
race_hobgoblin = 12,
race_lizardman = 13,
// Dwarf subraces
race_deep_dwarf = 1,
race_derro = 1,
race_duergar = 1,
race_mountain_dwarf = 1,
// Elf subraces
race_aquatic_elf = 2,
race_drow = 2,
race_gray_elf = 2,
race_wild_elf = 2,
race_wood_elf = 2,
// Gnome subraces
race_svirfneblin = 3,
race_forest_gnome = 3,
// Halfling subraces
race_tallfellow = 6,
race_deep_halfling = 6,
};
enum Subrace : uint32_t
{
subrace_none = 0, // default
//Human subraces
subrace_aasumar = 2,
subrace_tiefling = 3,
// Dwarf subraces
subrace_deep_dwarf = 1,
subrace_derro = 2,
subrace_duergar = 3,
subrace_mountain_dwarf = 4,
subrace_gold_dwarf = 4,
// Elf
subrace_aquatic_elf = 1,
subrace_drow = 2,
subrace_gray_elf = 3,
subrace_wild_elf = 4,
subrace_wood_elf = 5,
// Gnomes
subrace_svirfneblin = 1,
subrace_forest_gnome = 2,
// Halflings
subrace_tallfellow = 1,
subrace_deep_halfling = 2,
subrace_strongheart_halfling = 3,
subrace_ghostwise_halfling = 4,
};
enum NpcFlag : uint32_t
{
ONF_EX_FOLLOWER = 1,
ONF_WAYPOINTS_DAY = 2,
ONF_WAYPOINTS_NIGHT = 4,
ONF_AI_WAIT_HERE = 8,
ONF_AI_SPREAD_OUT = 16,
ONF_JILTED = 32,
ONF_LOGBOOK_IGNORES = 64,
ONF_UNUSED_00000080 = 128,
ONF_KOS = 256,
ONF_USE_ALERTPOINTS = 512, // 0x200
ONF_FORCED_FOLLOWER = 1024,
ONF_KOS_OVERRIDE = 2048,
ONF_WANDERS = 4096,
ONF_WANDERS_IN_DARK = 8192,
ONF_FENCE = 16384,
ONF_FAMILIAR = 32768,
ONF_CHECK_LEADER = 65536,
ONF_NO_EQUIP = 131072,
ONF_CAST_HIGHEST = 262144,
ONF_GENERATOR = 0x80000,
ONF_GENERATED = 0x100000,
ONF_GENERATOR_RATE1 = 0x200000,
ONF_GENERATOR_RATE2 = 0x400000,
ONF_GENERATOR_RATE3 = 0x800000,
ONF_DEMAINTAIN_SPELLS = 16777216,
ONF_UNUSED_02000000 = 33554432,
ONF_UNUSED_04000000 = 67108864,
ONF_UNUSED_08000000 = 134217728,
ONF_BACKING_OFF = 0x10000000,
ONF_NO_ATTACK = 0x20000000,
ONF_BOSS_MONSTER = 0x40000000,
ONF_EXTRAPLANAR = 0x80000000
};
enum _standPointType_enum : uint32_t {
STANDPOINT_DAY = 0,
STANDPOINT_NIGHT = 1,
STANDPOINT_SCOUT = 2
};
enum Deities : uint32_t
{
DEITY_NONE = 0,
DEITY_BOCCOB = 1,
DEITY_CORELLON_LARETHIAN = 2,
DEITY_EHLONNA = 3,
DEITY_ERYTHNUL = 4,
DEITY_FHARLANGHN = 5,
DEITY_GARL_GLITTERGOLD = 6,
DEITY_GRUUMSH = 7,
DEITY_HEIRONEOUS = 8,
DEITY_HEXTOR = 9,
DEITY_KORD = 10,
DEITY_MORADIN = 11,
DEITY_NERULL = 12,
DEITY_OBAD_HAI = 13,
DEITY_OLIDAMMARA = 14,
DEITY_PELOR = 15,
DEITY_ST_CUTHBERT = 16,
DEITY_VECNA = 17,
DEITY_WEE_JAS = 18,
DEITY_YONDALLA = 19,
DEITY_OLD_FAITH = 20,
DEITY_ZUGGTMOY = 21,
DEITY_IUZ = 22,
DEITY_LOLTH = 23,
DEITY_PROCAN = 24,
DEITY_NOREBO = 25,
DEITY_PYREMIUS = 26,
DEITY_RALISHAZ = 27
};
#pragma endregion
#pragma region Portal / Container / Secretdoor flags
enum ContainerFlag : uint32_t {
OCOF_LOCKED = 0x1,
OCOF_JAMMED = 0x2,
OCOF_MAGICALLY_HELD = 0x4,
OCOF_NEVER_LOCKED = 0x8,
OCOF_ALWAYS_LOCKED = 0x10,
OCOF_LOCKED_DAY = 0x20,
OCOF_LOCKED_NIGHT = 0x40,
OCOF_BUSTED = 0x80,
OCOF_NOT_STICKY = 0x100,
OCOF_INVEN_SPAWN_ONCE = 0x200,
OCOF_INVEN_SPAWN_INDEPENDENT = 0x400,
OCOF_OPEN = 0x800,
OCOF_HAS_BEEN_OPENED = 0x1000
};
enum PortalFlag : uint32_t {
OPF_LOCKED = 0x1,
OPF_JAMMED = 0x2,
OPF_MAGICALLY_HELD = 0x4,
OPF_NEVER_LOCKED = 0x8,
OPF_ALWAYS_LOCKED = 0x10,
OPF_LOCKED_DAY = 0x20,
OPF_LOCKED_NIGHT = 0x40,
OPF_BUSTED = 0x80,
OPF_NOT_STICKY = 0x100,
OPF_OPEN = 0x200
};
enum SecretDoorFlag : uint32_t {
OSDF_DC_0 = 0x1,
OSDF_DC_1 = 0x2,
OSDF_DC_2 = 0x4,
OSDF_DC_3 = 0x8,
OSDF_DC_4 = 0x10,
OSDF_DC_5 = 0x20,
OSDF_DC_6 = 0x40,
OSDF_RANK_0 = 0x80,
OSDF_RANK_1 = 0x100,
OSDF_RANK_2 = 0x200,
OSDF_RANK_3 = 0x400,
OSDF_RANK_4 = 0x800,
OSDF_RANK_5 = 0x1000,
OSDF_RANK_6 = 0x2000,
OSDF_UNUSED = 0x4000,
OSDF_UNUSED2 = 0x8000,
OSDF_SECRET_DOOR = 0x10000,
OSDF_SECRET_DOOR_FOUND = 0x20000
};
#pragma endregion
#pragma region Items
enum ItemFlag : uint32_t {
OIF_IDENTIFIED = 0x1,
OIF_WONT_SELL = 0x2,
OIF_IS_MAGICAL = 0x4,
OIF_NO_PICKPOCKET = 0x8,
OIF_NO_DISPLAY = 0x10,
OIF_NO_DROP = 0x20,
OIF_NEEDS_SPELL = 0x40,
OIF_CAN_USE_BOX = 0x80,
OIF_NEEDS_TARGET = 0x100,
OIF_LIGHT_SMALL = 0x200,
OIF_LIGHT_MEDIUM = 0x400,
OIF_LIGHT_LARGE = 0x800,
OIF_LIGHT_XLARGE = 0x1000,
OIF_PERSISTENT = 0x2000,
OIF_MT_TRIGGERED = 0x4000,
OIF_STOLEN = 0x8000,
OIF_USE_IS_THROW = 0x10000,
OIF_NO_DECAY = 0x20000,
OIF_UBER = 0x40000,
OIF_NO_NPC_PICKUP = 0x80000,
OIF_NO_RANGED_USE = 0x100000,
OIF_VALID_AI_ACTION = 0x200000,
OIF_DRAW_WHEN_PARENTED = 0x400000,
OIF_EXPIRES_AFTER_USE = 0x800000,
OIF_NO_LOOT = 0x1000000,
OIF_USES_WAND_ANIM = 0x2000000,
OIF_NO_TRANSFER = 0x4000000,
OIF_NO_TRANSFER_SPECIAL = 0x8000000
};
enum OIF_WEAR : uint32_t
{
OIF_WEAR_HELMET = 1,
OIF_WEAR_NECKLACE = 2,
OIF_WEAR_GLOVES = 4,
OIF_WEAR_UNUSED_1 = 8,
OIF_WEAR_UNUSED_2 = 0x10,
OIF_WEAR_ARMOR = 0x20,
OIF_WEAR_RING = 0x40,
OIF_WEAR_UNUSED_3 = 0x80,
OIF_WEAR_BOOTS = 0x100,
OIF_WEAR_AMMO = 0x200,
OIF_WEAR_CLOAK = 0x400,
OIF_WEAR_BUCKLER = 0x800,
OIF_WEAR_ROBES = 0x1000,
OIF_WEAR_BRACERS = 0x2000,
OIF_WEAR_BARDIC_ITEM = 0x4000,
OIF_WEAR_LOCKPICKS = 0x8000,
OIF_WEAR_2HAND_REQUIRED = 0x10000
};
enum WeaponTypes : uint32_t
{
wt_gauntlet = 0,
wt_unarmed_strike_medium_sized_being,
wt_unarmed_strike_small_being,
wt_dagger,
wt_punching_dagger,
wt_spiked_gauntlet,
wt_light_mace,
wt_sickle,
wt_club,
wt_shortspear,
wt_heavy_mace,
wt_morningstar,
wt_quarterstaff,
wt_spear,
wt_light_crossbow, // 14
wt_dart,
wt_sling,
wt_heavy_crossbow, // 17
wt_javelin,
wt_throwing_axe,
wt_light_hammer,
wt_handaxe,
wt_light_lance,
wt_light_pick,
wt_sap,
wt_short_sword,
wt_battleaxe,
wt_light_flail,
wt_heavy_lance,
wt_longsword,
wt_heavy_pick,
wt_rapier,
wt_scimitar,
wt_trident,
wt_warhammer,
wt_falchion,
wt_heavy_flail,
wt_glaive,
wt_greataxe,
wt_greatclub,
wt_greatsword,
wt_guisarme,
wt_halberd,
wt_longspear, //43
wt_ranseur,
wt_scythe,
wt_shortbow,
wt_composite_shortbow,
wt_longbow,
wt_composite_longbow,
wt_halfling_kama, // 50
wt_kukri,
wt_halfling_nunchaku, //52
wt_halfling_siangham, //53
wt_kama, //54
wt_nunchaku, // 55
wt_siangham, // 56
wt_bastard_sword,
wt_dwarven_waraxe, // racial weapons - 58 and on
wt_gnome_hooked_hammer,
wt_orc_double_axe,
wt_spike_chain,
wt_dire_flail,
wt_two_bladed_sword,
wt_dwarven_urgrosh,
wt_hand_crossbow, // 65
wt_shuriken,
wt_whip,
wt_repeating_crossbow,
wt_net,
wt_grapple,
wt_ray,
wt_grenade, // 72
wt_mindblade,
wt_none = 0xFFFFffff
};
enum ArmorType : uint32_t
{
ARMOR_TYPE_LIGHT = 0,
ARMOR_TYPE_MEDIUM = 1,
ARMOR_TYPE_HEAVY = 2,
ARMOR_TYPE_SHIELD = 3,
ARMOR_TYPE_BITMASK = 3,
ARMOR_TYPE_NONE = 0x10
};
enum WeaponFlags : uint32_t
{
OWF_LOUD = 1,
OWF_SILENT= 2 ,
OWF_UNUSED_1 = 4,
OWF_UNUSED_2 = 8,
OWF_THROWABLE = 0x10,
OWF_TRANS_PROJECTILE = 0x20,
OWF_BOOMERANGS = 0x40,
OWF_IGNORE_RESISTANCE = 0x80,
OWF_DAMAGE_ARMOR = 0x100,
OWF_DEFAULT_THROWS = 0x200,
OWF_RANGED_WEAPON = 0x400,
OWF_WEAPON_LOADED = 0x800,
OWF_MAGIC_STAFF = 0x1000
};
enum WeaponAmmoType
{
wat_arrow = 0,
wat_bolt,
wat_bullet,
wat_magic_missile,
wat_dagger,
wat_club,
wat_shortspear,
wat_spear,
wat_dart,
wat_javelin,
wat_throwing_axe,
wat_light_hammer,
wat_trident,
wat_halfling_sai,
wat_sai,
wat_shuriken, // 15
wat_ball_of_fire,
wat_bottle,
wat_unk18,
};
#pragma endregion
// Keep in sync with Python enum
enum class DamageType : int {
Unspecified = -1,
Bludgeoning = 0,
Piercing = 1,
Slashing = 2,
BludgeoningAndPiercing = 3,
PiercingAndSlashing = 4,
SlashingAndBludgeoning = 5,
SlashingAndBludgeoningAndPiercing = 6,
Acid = 7,
Cold = 8,
Electricity = 9,
Fire = 10,
Sonic = 11,
NegativeEnergy = 12,
Subdual = 13,
Poison = 14,
PositiveEnergy = 15,
Force = 16,
BloodLoss = 17,
Magic = 18
};
enum class AttackPowerType : int
{
Normal = 0,
Unspecified = 1,
Silver,
Magic,
Holy,
Unholy,
Chaos,
Law,
Adamantium,
Bludgeoning,
Piercing,
Slashing,
Mithril,
Cold
};
enum class SavingThrowType : uint32_t {
Fortitude = 0,
Reflex,
Will
};
enum SpellFlags : uint32_t
{
SF_1 = 1,
SF_2 = 2,
SF_4 = 4,
SF_8 = 8,
SF_10 = 0x10,
SF_20 = 0x20,
SF_40 = 0x40,
SF_80 = 0x80 ,
SF_100 = 0x100,
SF_200 = 0x200,
SF_400 = 0x400,
SF_800 = 0x800,
SF_1000 = 0x1000,
SF_2000 = 0x2000,
SF_4000 = 0x4000,
SF_8000 = 0x8000,
SF_10000 = 0x10000, // Used in goalstatefunc_124
SF_20000 = 0x20000,
SF_40000 = 0x40000,
SF_80000 = 0x80000,
SF_100000 = 0x100000,
SF_200000 = 0x200000,
SF_400000 = 0x400000,
SF_800000 = 0x800000,
SF_1000000 = 0x1000000,
SF_2000000 = 0x2000000,
SF_4000000 = 0x4000000,
SF_SPELL_FLEE = 0x8000000,
}; | 31.112082 | 321 | 0.783195 | [
"object",
"model"
] |
08055fe44b9ab5bd8fec572a4f0d0a749e818d15 | 5,350 | h | C | src/eb.h | mdwarfgeek/eb | 1a03107399269eb1b4c268be1b77dbe4bcc477a1 | [
"MIT"
] | 6 | 2016-08-25T18:07:34.000Z | 2021-10-29T21:06:41.000Z | src/eb.h | mdwarfgeek/eb | 1a03107399269eb1b4c268be1b77dbe4bcc477a1 | [
"MIT"
] | null | null | null | src/eb.h | mdwarfgeek/eb | 1a03107399269eb1b4c268be1b77dbe4bcc477a1 | [
"MIT"
] | 2 | 2016-07-14T03:20:00.000Z | 2017-10-10T20:42:39.000Z | #ifndef EB_H
#define EB_H
#include <math.h>
/* Fundamental (defining) constants, mostly IAU and IERS */
#define EB_GMSUN 1.3271244e20 /* m^3 / s^2, IAU 2015 Resol B3 */
#define EB_AU 149597870700.0 /* m, IAU 2009 system */
#define EB_LIGHT 2.99792458e8 /* m/s, definition */
/* Other astrophysical quantities */
#define EB_RSUN 6.957e8 /* m, IAU 2015 Resol B3 */
#define EB_DAY 86400 /* s, length of day */
/* Planetary conversion constants, IAU 2015 Resol B3 */
#define EB_REARTH 6.3781e6 /* m, equatorial */
#define EB_RJUP 7.1492e7 /* m, equatorial */
#define EB_GMEARTH 3.986004e14 /* m^3 / s^2 */
#define EB_GMJUP 1.2668653e17 /* m^3 / s^2 */
/* This is pretty useful too */
#ifndef TWOPI
#define TWOPI (2.0*M_PI)
#endif
/* Parameters in the "parm" array. Order is for compatibility with jktebop. */
#define EB_PAR_J 0
#define EB_PAR_RASUM 1
#define EB_PAR_RR 2
#define EB_PAR_LDLIN1 3
#define EB_PAR_LDLIN2 4
#define EB_PAR_COSI 5
#define EB_PAR_ECOSW 6
#define EB_PAR_ESINW 7
#define EB_PAR_GD1 8
#define EB_PAR_GD2 9
#define EB_PAR_REFL1 10 /* albedo (default) or reflection */
#define EB_PAR_REFL2 11
#define EB_PAR_Q 12
#define EB_PAR_TIDANG 13 /* deg */
#define EB_PAR_L3 14
#define EB_PAR_PHI0 15 /* [0,1] */
#define EB_PAR_M0 16
#define EB_PAR_INTEG 17 /* not used */
#define EB_PAR_P 18
#define EB_PAR_T0 19 /* epoch of inferior conjunction if phi0=0 */
#define EB_PAR_LDNON1 20
#define EB_PAR_LDNON2 21
#define EB_PAR_CLTT 22 /* ktot / c if want light travel time corr */
#define EB_PAR_ROT1 23 /* rotation parameter */
#define EB_PAR_ROT2 24
#define EB_PAR_FSPOT1 25 /* fraction of spots eclipsed */
#define EB_PAR_FSPOT2 26
#define EB_PAR_OOE1O 27 /* base spottedness out of eclipse star 1 */
#define EB_PAR_OOE11A 28 /* sin(...) coeff star 1 */
#define EB_PAR_OOE11B 29 /* cos(...) coeff star 1 */
#define EB_PAR_OOE12A 30 /* sin(2*...) coeff star 1 */
#define EB_PAR_OOE12B 31 /* cos(2*...) coeff star 1 */
#define EB_PAR_OOE2O 32 /* base spottedness out of eclipse star 2 */
#define EB_PAR_OOE21A 33 /* sin(...) coeff star 2 */
#define EB_PAR_OOE21B 34 /* cos(...) coeff star 2 */
#define EB_PAR_OOE22A 35 /* sin(2*...) coeff star 2 */
#define EB_PAR_OOE22B 36 /* cos(2*...) coeff star 2 */
#define EB_PAR_DWDT 37 /* apsidal precession rate (rad/day) */
#define EB_NPAR 38
/* Flags */
#define EB_FLAG_REFL 0x01 /* reflection rather than albedo */
#define EB_FLAG_PHI 0x02 /* phase rather than time */
#define EB_FLAG_NOEC 0x04 /* disable eclipse calculation */
#define EB_FLAG_NOELL 0x08 /* disable ellipsoidal */
/* Observation types we can request from the light curve generator. */
#define EB_OBS_MAG 0 /* magnitude */
#define EB_OBS_LIGHT 1 /* total normalized light (as Agol) */
#define EB_OBS_LRAT 2 /* L_2 / L_1 */
#define EB_OBS_AVLR 3 /* orbit averaged L_2 / L_1 */
#define EB_OBS_VRAD1 4 /* cos(v+w) + e cos w for star 1 */
#define EB_OBS_VRAD2 5 /* cos(v+w) + e cos w for star 2 */
#define EB_OBS_PSS 6 /* plane of sky separation ("d" in our notation) */
#define EB_OBS_A 7 /* d - rr, used to test if in eclipse (< 1) */
#define EB_OBS_LSS 8 /* line of sight separation */
/* Function prototype for the generator. Fills "out" with model
observables. The array "t" is a time array in the same units as P
and T0, and "typ" is an array of the OBS_* parameters specifying
the observables to be computed. These may appear in any combination,
but note that a lot of unnecessary computations are done at each
function call if all you want are radial velocities. */
void eb_model_dbl (double *parm, double *t, double *ol1, double *ol2,
unsigned char *typ, double *out, unsigned char *iecl,
int flags, int npt);
void eb_model_flt (double *parm, double *t, float *ol1, float *ol2,
unsigned char *typ, float *out, unsigned char *iecl,
int flags, int npt);
/* Utility subroutines from ebutil.c */
double eb_phiperi (double esinw, double ecosw);
double eb_phisec (double esinw, double ecosw);
void eb_phicont (double esinw, double ecosw, double cosi,
double d, double *phi);
/* Parameters in the "vder" (derived) array */
#define EB_PAR_I 0
#define EB_PAR_R1A 1
#define EB_PAR_R2A 2
#define EB_PAR_E 3
#define EB_PAR_OMEGA 4
#define EB_PAR_A 5
#define EB_PAR_MTOT 6
#define EB_PAR_M1 7
#define EB_PAR_M2 8
#define EB_PAR_RTOT 9
#define EB_PAR_R1 10
#define EB_PAR_R2 11
#define EB_PAR_LOGG1 12
#define EB_PAR_LOGG2 13
#define EB_PAR_VSYNC1 14
#define EB_PAR_VSYNC2 15
#define EB_PAR_TSYNC 16
#define EB_PAR_TCIRC 17
#define EB_PAR_TSEC 18
#define EB_PAR_DURPRI 19
#define EB_PAR_DURSEC 20
#define EB_NDER 21
void eb_getvder (double *v, double gamma, double ktot, double *vder);
/* Arrays of names and units for parameters */
extern char *eb_parnames[EB_NPAR];
extern char *eb_partexsym[EB_NPAR];
extern char *eb_parunits[EB_NPAR];
extern char *eb_dernames[EB_NDER];
extern char *eb_dertexsym[EB_NDER];
extern char *eb_derunits[EB_NDER];
#endif /* EB_H */
| 38.489209 | 79 | 0.66972 | [
"model"
] |
080bf91018216e8f9dafb0b8668c4b204c613cc2 | 321 | h | C | MobileCenter/MobileCenter/Internals/Sender/MSSenderCallDelegate.h | Ajaybabu009/Workajay | de70f04e589631c3e0f2e8ed6cad64bbf0570180 | [
"MIT"
] | null | null | null | MobileCenter/MobileCenter/Internals/Sender/MSSenderCallDelegate.h | Ajaybabu009/Workajay | de70f04e589631c3e0f2e8ed6cad64bbf0570180 | [
"MIT"
] | null | null | null | MobileCenter/MobileCenter/Internals/Sender/MSSenderCallDelegate.h | Ajaybabu009/Workajay | de70f04e589631c3e0f2e8ed6cad64bbf0570180 | [
"MIT"
] | null | null | null | #import <Foundation/Foundation.h>
@class MSSenderCall;
@protocol MSSenderCallDelegate <NSObject>
/**
* Send call.
*
* @param call Call object.
*/
- (void)sendCallAsync:(MSSenderCall *)call;
/**
* Call completed callback.
*
* @param callId call id.
*/
- (void)callCompletedWithId:(NSString *)callId;
@end
| 14.590909 | 47 | 0.679128 | [
"object"
] |
081c0070cb9b4bed0b3425bfee06dc8fba9864db | 1,968 | h | C | include/dpen/DPErrors.h | bakercp/libdpen | 5efb0bb70a9f9f8fb713a104bd314fd394494b30 | [
"MIT"
] | 6 | 2015-06-05T07:08:13.000Z | 2018-05-02T17:39:39.000Z | include/dpen/DPErrors.h | bakercp/libdpen | 5efb0bb70a9f9f8fb713a104bd314fd394494b30 | [
"MIT"
] | null | null | null | include/dpen/DPErrors.h | bakercp/libdpen | 5efb0bb70a9f9f8fb713a104bd314fd394494b30 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2012 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#pragma once
#include <string>
#include <iostream>
#include "dpen/DPUtils.h"
namespace dpen {
static bool LOG_DEBUG = true;
static bool HEX_DEBUG = true;
enum DPError
{
DP_SUCCESS = 0,
DP_ERROR_UNKNOWN_FILE_ENDING,
DP_ERROR_UNABLE_TO_LOAD_FROM_DISK,
DP_ERROR_INVALID_XML,
DP_ERROR_INVALID_HEADER,
};
inline std::string DPErrorToString(const DPError& error)
{
switch (error)
{
case DP_SUCCESS:
return "SUCCESS";
case DP_ERROR_UNKNOWN_FILE_ENDING:
return "UNKNOWN FILE ENDING";
case DP_ERROR_UNABLE_TO_LOAD_FROM_DISK:
return "UNABLE TO LOAD FILE FROM DISK";
case DP_ERROR_INVALID_XML:
return "INVALID XML";
case DP_ERROR_INVALID_HEADER:
return "INVALID HEADER";
default:
return "UNKNOWN ERROR CODE";
}
}
inline void DPLogBlock(const std::string& prefix,
std::vector<uint8_t>& buf,
std::size_t i)
{
if(LOG_DEBUG)
{
uint8_t length = buf[i+1];
std::cout << prefix << " ";
for (uint8_t j = 0; j < length; ++j)
{
if (HEX_DEBUG)
{
std::cout << "0x" << DPToHex(buf[i+j]) << " ";
}
else
{
std::cout << DPToString( (std::size_t) buf[i+j], 0, 4, ' ');
}
}
std::cout << std::endl;
}
}
// logging utilities
inline void DPLogError(const std::string& error)
{
std::cerr << "Error: " << error << std::endl;
}
inline void DPLogWarning(const std::string& warning)
{
std::cout << "Warning: " << warning << std::endl;
}
inline void DPLogDebug(const std::string& verbose)
{
if (LOG_DEBUG)
{
std::cout << "Debug: " << verbose << std::endl;
}
}
} // namespace dpen
| 19.294118 | 76 | 0.557419 | [
"vector"
] |
081dd8fc0b09d8d12c343496c8c3a0d00d8cc5c6 | 50,237 | c | C | MISC/BIG/drawterm/libsec/x509.c | aryx/principia-softwarica | 4191ace48c70d7e70ef0002b27324c3a766f7672 | [
"LPL-1.02"
] | 82 | 2015-06-14T15:19:32.000Z | 2021-02-18T08:32:30.000Z | MISC/BIG/drawterm/libsec/x509.c | aryx/principia-softwarica | 4191ace48c70d7e70ef0002b27324c3a766f7672 | [
"LPL-1.02"
] | 10 | 2015-07-31T21:30:14.000Z | 2021-03-26T18:02:19.000Z | MISC/BIG/drawterm/libsec/x509.c | aryx/principia-softwarica | 4191ace48c70d7e70ef0002b27324c3a766f7672 | [
"LPL-1.02"
] | 17 | 2015-06-27T18:46:18.000Z | 2021-03-26T17:52:36.000Z | #include <u.h>
#include <libc.h>
#include <mp.h>
#include <libsec.h>
typedef DigestState*(*DigestFun)(uchar*,ulong,uchar*,DigestState*);
/* ANSI offsetof, backwards. */
#define OFFSETOF(a, b) offsetof(b, a)
/*=============================================================*/
/* general ASN1 declarations and parsing
*
* For now, this is used only for extracting the key from an
* X509 certificate, so the entire collection is hidden. But
* someday we should probably make the functions visible and
* give them their own man page.
*/
typedef struct Elem Elem;
typedef struct Tag Tag;
typedef struct Value Value;
typedef struct Bytes Bytes;
typedef struct Ints Ints;
typedef struct Bits Bits;
typedef struct Elist Elist;
/* tag classes */
#define Universal 0
#define Context 0x80
/* universal tags */
#define BOOLEAN 1
#define INTEGER 2
#define BIT_STRING 3
#define OCTET_STRING 4
#define NULLTAG 5
#define OBJECT_ID 6
#define ObjectDescriptor 7
#define EXTERNAL 8
#define REAL 9
#define ENUMERATED 10
#define EMBEDDED_PDV 11
#define SEQUENCE 16 /* also SEQUENCE OF */
#define SETOF 17 /* also SETOF OF */
#define NumericString 18
#define PrintableString 19
#define TeletexString 20
#define VideotexString 21
#define IA5String 22
#define UTCTime 23
#define GeneralizedTime 24
#define GraphicString 25
#define VisibleString 26
#define GeneralString 27
#define UniversalString 28
#define BMPString 30
struct Bytes {
int len;
uchar data[1];
};
struct Ints {
int len;
int data[1];
};
struct Bits {
int len; /* number of bytes */
int unusedbits; /* unused bits in last byte */
uchar data[1]; /* most-significant bit first */
};
struct Tag {
int class;
int num;
};
enum { VBool, VInt, VOctets, VBigInt, VReal, VOther,
VBitString, VNull, VEOC, VObjId, VString, VSeq, VSet };
struct Value {
int tag; /* VBool, etc. */
union {
int boolval;
int intval;
Bytes* octetsval;
Bytes* bigintval;
Bytes* realval; /* undecoded; hardly ever used */
Bytes* otherval;
Bits* bitstringval;
Ints* objidval;
char* stringval;
Elist* seqval;
Elist* setval;
} u; /* (Don't use anonymous unions, for ease of porting) */
};
struct Elem {
Tag tag;
Value val;
};
struct Elist {
Elist* tl;
Elem hd;
};
/* decoding errors */
enum { ASN_OK, ASN_ESHORT, ASN_ETOOBIG, ASN_EVALLEN,
ASN_ECONSTR, ASN_EPRIM, ASN_EINVAL, ASN_EUNIMPL };
/* here are the functions to consider making extern someday */
static Bytes* newbytes(int len);
static Bytes* makebytes(uchar* buf, int len);
static void freebytes(Bytes* b);
static Bytes* catbytes(Bytes* b1, Bytes* b2);
static Ints* newints(int len);
static Ints* makeints(int* buf, int len);
static void freeints(Ints* b);
static Bits* newbits(int len);
static Bits* makebits(uchar* buf, int len, int unusedbits);
static void freebits(Bits* b);
static Elist* mkel(Elem e, Elist* tail);
static void freeelist(Elist* el);
static int elistlen(Elist* el);
static int is_seq(Elem* pe, Elist** pseq);
static int is_set(Elem* pe, Elist** pset);
static int is_int(Elem* pe, int* pint);
static int is_bigint(Elem* pe, Bytes** pbigint);
static int is_bitstring(Elem* pe, Bits** pbits);
static int is_octetstring(Elem* pe, Bytes** poctets);
static int is_oid(Elem* pe, Ints** poid);
static int is_string(Elem* pe, char** pstring);
static int is_time(Elem* pe, char** ptime);
static int decode(uchar* a, int alen, Elem* pelem);
static int decode_seq(uchar* a, int alen, Elist** pelist);
static int decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval);
static int encode(Elem e, Bytes** pbytes);
static int oid_lookup(Ints* o, Ints** tab);
static void freevalfields(Value* v);
static mpint *asn1mpint(Elem *e);
#define TAG_MASK 0x1F
#define CONSTR_MASK 0x20
#define CLASS_MASK 0xC0
#define MAXOBJIDLEN 20
static int ber_decode(uchar** pp, uchar* pend, Elem* pelem);
static int tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr);
static int length_decode(uchar** pp, uchar* pend, int* plength);
static int value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval);
static int int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint);
static int uint7_decode(uchar** pp, uchar* pend, int* pint);
static int octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes);
static int seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist);
static int enc(uchar** pp, Elem e, int lenonly);
static int val_enc(uchar** pp, Elem e, int *pconstr, int lenonly);
static void uint7_enc(uchar** pp, int num, int lenonly);
static void int_enc(uchar** pp, int num, int unsgned, int lenonly);
static void *
emalloc(int n)
{
void *p;
if(n==0)
n=1;
p = malloc(n);
if(p == nil){
exits("out of memory");
}
memset(p, 0, n);
return p;
}
static char*
estrdup(char *s)
{
char *d, *d0;
if(!s)
return 0;
d = d0 = emalloc(strlen(s)+1);
while(*d++ = *s++)
;
return d0;
}
/*
* Decode a[0..len] as a BER encoding of an ASN1 type.
* The return value is one of ASN_OK, etc.
* Depending on the error, the returned elem may or may not
* be nil.
*/
static int
decode(uchar* a, int alen, Elem* pelem)
{
uchar* p = a;
return ber_decode(&p, &a[alen], pelem);
}
/*
* Like decode, but continue decoding after first element
* of array ends.
*/
static int
decode_seq(uchar* a, int alen, Elist** pelist)
{
uchar* p = a;
return seq_decode(&p, &a[alen], -1, 1, pelist);
}
/*
* Decode the whole array as a BER encoding of an ASN1 value,
* (i.e., the part after the tag and length).
* Assume the value is encoded as universal tag "kind".
* The constr arg is 1 if the value is constructed, 0 if primitive.
* If there's an error, the return string will contain the error.
* Depending on the error, the returned value may or may not
* be nil.
*/
static int
decode_value(uchar* a, int alen, int kind, int isconstr, Value* pval)
{
uchar* p = a;
return value_decode(&p, &a[alen], alen, kind, isconstr, pval);
}
/*
* All of the following decoding routines take arguments:
* uchar **pp;
* uchar *pend;
* Where parsing is supposed to start at **pp, and when parsing
* is done, *pp is updated to point at next char to be parsed.
* The pend pointer is just past end of string; an error should
* be returned parsing hasn't finished by then.
*
* The returned int is ASN_OK if all went fine, else ASN_ESHORT, etc.
* The remaining argument(s) are pointers to where parsed entity goes.
*/
/* Decode an ASN1 'Elem' (tag, length, value) */
static int
ber_decode(uchar** pp, uchar* pend, Elem* pelem)
{
int err;
int isconstr;
int length;
Tag tag;
Value val;
err = tag_decode(pp, pend, &tag, &isconstr);
if(err == ASN_OK) {
err = length_decode(pp, pend, &length);
if(err == ASN_OK) {
if(tag.class == Universal)
err = value_decode(pp, pend, length, tag.num, isconstr, &val);
else
err = value_decode(pp, pend, length, OCTET_STRING, 0, &val);
if(err == ASN_OK) {
pelem->tag = tag;
pelem->val = val;
}
}
}
return err;
}
/* Decode a tag field */
static int
tag_decode(uchar** pp, uchar* pend, Tag* ptag, int* pisconstr)
{
int err;
int v;
uchar* p;
err = ASN_OK;
p = *pp;
if(pend-p >= 2) {
v = *p++;
ptag->class = v&CLASS_MASK;
if(v&CONSTR_MASK)
*pisconstr = 1;
else
*pisconstr = 0;
v &= TAG_MASK;
if(v == TAG_MASK)
err = uint7_decode(&p, pend, &v);
ptag->num = v;
}
else
err = ASN_ESHORT;
*pp = p;
return err;
}
/* Decode a length field */
static int
length_decode(uchar** pp, uchar* pend, int* plength)
{
int err;
int num;
int v;
uchar* p;
err = ASN_OK;
num = 0;
p = *pp;
if(p < pend) {
v = *p++;
if(v&0x80)
err = int_decode(&p, pend, v&0x7F, 1, &num);
else if(v == 0x80)
num = -1;
else
num = v;
}
else
err = ASN_ESHORT;
*pp = p;
*plength = num;
return err;
}
/* Decode a value field */
static int
value_decode(uchar** pp, uchar* pend, int length, int kind, int isconstr, Value* pval)
{
int err;
Bytes* va;
int num;
int bitsunused;
int subids[MAXOBJIDLEN];
int isubid;
Elist* vl;
uchar* p;
uchar* pe;
err = ASN_OK;
p = *pp;
if(length == -1) { /* "indefinite" length spec */
if(!isconstr)
err = ASN_EINVAL;
}
else if(p + length > pend)
err = ASN_EVALLEN;
if(err != ASN_OK)
return err;
switch(kind) {
case 0:
/* marker for end of indefinite constructions */
if(length == 0)
pval->tag = VNull;
else
err = ASN_EINVAL;
break;
case BOOLEAN:
if(isconstr)
err = ASN_ECONSTR;
else if(length != 1)
err = ASN_EVALLEN;
else {
pval->tag = VBool;
pval->u.boolval = (*p++ != 0);
}
break;
case INTEGER:
case ENUMERATED:
if(isconstr)
err = ASN_ECONSTR;
else if(length <= 4) {
err = int_decode(&p, pend, length, 0, &num);
if(err == ASN_OK) {
pval->tag = VInt;
pval->u.intval = num;
}
}
else {
pval->tag = VBigInt;
pval->u.bigintval = makebytes(p, length);
p += length;
}
break;
case BIT_STRING:
pval->tag = VBitString;
if(isconstr) {
if(length == -1 && p + 2 <= pend && *p == 0 && *(p+1) ==0) {
pval->u.bitstringval = makebits(0, 0, 0);
p += 2;
}
else
/* TODO: recurse and concat results */
err = ASN_EUNIMPL;
}
else {
if(length < 2) {
if(length == 1 && *p == 0) {
pval->u.bitstringval = makebits(0, 0, 0);
p++;
}
else
err = ASN_EINVAL;
}
else {
bitsunused = *p;
if(bitsunused > 7)
err = ASN_EINVAL;
else if(length > 0x0FFFFFFF)
err = ASN_ETOOBIG;
else {
pval->u.bitstringval = makebits(p+1, length-1, bitsunused);
p += length;
}
}
}
break;
case OCTET_STRING:
case ObjectDescriptor:
err = octet_decode(&p, pend, length, isconstr, &va);
if(err == ASN_OK) {
pval->tag = VOctets;
pval->u.octetsval = va;
}
break;
case NULLTAG:
if(isconstr)
err = ASN_ECONSTR;
else if(length != 0)
err = ASN_EVALLEN;
else
pval->tag = VNull;
break;
case OBJECT_ID:
if(isconstr)
err = ASN_ECONSTR;
else if(length == 0)
err = ASN_EVALLEN;
else {
isubid = 0;
pe = p+length;
while(p < pe && isubid < MAXOBJIDLEN) {
err = uint7_decode(&p, pend, &num);
if(err != ASN_OK)
break;
if(isubid == 0) {
subids[isubid++] = num / 40;
subids[isubid++] = num % 40;
}
else
subids[isubid++] = num;
}
if(err == ASN_OK) {
if(p != pe)
err = ASN_EVALLEN;
else {
pval->tag = VObjId;
pval->u.objidval = makeints(subids, isubid);
}
}
}
break;
case EXTERNAL:
case EMBEDDED_PDV:
/* TODO: parse this internally */
if(p+length > pend)
err = ASN_EVALLEN;
else {
pval->tag = VOther;
pval->u.otherval = makebytes(p, length);
p += length;
}
break;
case REAL:
/* Let the application decode */
if(isconstr)
err = ASN_ECONSTR;
else if(p+length > pend)
err = ASN_EVALLEN;
else {
pval->tag = VReal;
pval->u.realval = makebytes(p, length);
p += length;
}
break;
case SEQUENCE:
err = seq_decode(&p, pend, length, isconstr, &vl);
if(err == ASN_OK) {
pval->tag = VSeq ;
pval->u.seqval = vl;
}
break;
case SETOF:
err = seq_decode(&p, pend, length, isconstr, &vl);
if(err == ASN_OK) {
pval->tag = VSet;
pval->u.setval = vl;
}
break;
case NumericString:
case PrintableString:
case TeletexString:
case VideotexString:
case IA5String:
case UTCTime:
case GeneralizedTime:
case GraphicString:
case VisibleString:
case GeneralString:
case UniversalString:
case BMPString:
/* TODO: figure out when character set conversion is necessary */
err = octet_decode(&p, pend, length, isconstr, &va);
if(err == ASN_OK) {
pval->tag = VString;
pval->u.stringval = (char*)emalloc(va->len+1);
memmove(pval->u.stringval, va->data, va->len);
pval->u.stringval[va->len] = 0;
free(va);
}
break;
default:
if(p+length > pend)
err = ASN_EVALLEN;
else {
pval->tag = VOther;
pval->u.otherval = makebytes(p, length);
p += length;
}
break;
}
*pp = p;
return err;
}
/*
* Decode an int in format where count bytes are
* concatenated to form value.
* Although ASN1 allows any size integer, we return
* an error if the result doesn't fit in a 32-bit int.
* If unsgned is not set, make sure to propagate sign bit.
*/
static int
int_decode(uchar** pp, uchar* pend, int count, int unsgned, int* pint)
{
int err;
int num;
uchar* p;
p = *pp;
err = ASN_OK;
num = 0;
if(p+count <= pend) {
if((count > 4) || (unsgned && count == 4 && (*p&0x80)))
err = ASN_ETOOBIG;
else {
if(!unsgned && count > 0 && count < 4 && (*p&0x80))
num = -1; // set all bits, initially
while(count--)
num = (num << 8)|(*p++);
}
}
else
err = ASN_ESHORT;
*pint = num;
*pp = p;
return err;
}
/*
* Decode an unsigned int in format where each
* byte except last has high bit set, and remaining
* seven bits of each byte are concatenated to form value.
* Although ASN1 allows any size integer, we return
* an error if the result doesn't fit in a 32 bit int.
*/
static int
uint7_decode(uchar** pp, uchar* pend, int* pint)
{
int err;
int num;
int more;
int v;
uchar* p;
p = *pp;
err = ASN_OK;
num = 0;
more = 1;
while(more && p < pend) {
v = *p++;
if(num&0x7F000000) {
err = ASN_ETOOBIG;
break;
}
num <<= 7;
more = v&0x80;
num |= (v&0x7F);
}
if(p == pend)
err = ASN_ESHORT;
*pint = num;
*pp = p;
return err;
}
/*
* Decode an octet string, recursively if isconstr.
* We've already checked that length==-1 implies isconstr==1,
* and otherwise that specified length fits within (*pp..pend)
*/
static int
octet_decode(uchar** pp, uchar* pend, int length, int isconstr, Bytes** pbytes)
{
int err;
uchar* p;
Bytes* ans;
Bytes* newans;
uchar* pstart;
uchar* pold;
Elem elem;
err = ASN_OK;
p = *pp;
ans = nil;
if(length >= 0 && !isconstr) {
ans = makebytes(p, length);
p += length;
}
else {
/* constructed, either definite or indefinite length */
pstart = p;
for(;;) {
if(length >= 0 && p >= pstart + length) {
if(p != pstart + length)
err = ASN_EVALLEN;
break;
}
pold = p;
err = ber_decode(&p, pend, &elem);
if(err != ASN_OK)
break;
switch(elem.val.tag) {
case VOctets:
newans = catbytes(ans, elem.val.u.octetsval);
freebytes(ans);
ans = newans;
break;
case VEOC:
if(length != -1) {
p = pold;
err = ASN_EINVAL;
}
goto cloop_done;
default:
p = pold;
err = ASN_EINVAL;
goto cloop_done;
}
}
cloop_done:
;
}
*pp = p;
*pbytes = ans;
return err;
}
/*
* Decode a sequence or set.
* We've already checked that length==-1 implies isconstr==1,
* and otherwise that specified length fits within (*p..pend)
*/
static int
seq_decode(uchar** pp, uchar* pend, int length, int isconstr, Elist** pelist)
{
int err;
uchar* p;
uchar* pstart;
uchar* pold;
Elist* ans;
Elem elem;
Elist* lve;
Elist* lveold;
err = ASN_OK;
ans = nil;
p = *pp;
if(!isconstr)
err = ASN_EPRIM;
else {
/* constructed, either definite or indefinite length */
lve = nil;
pstart = p;
for(;;) {
if(length >= 0 && p >= pstart + length) {
if(p != pstart + length)
err = ASN_EVALLEN;
break;
}
pold = p;
err = ber_decode(&p, pend, &elem);
if(err != ASN_OK)
break;
if(elem.val.tag == VEOC) {
if(length != -1) {
p = pold;
err = ASN_EINVAL;
}
break;
}
else
lve = mkel(elem, lve);
}
if(err == ASN_OK) {
/* reverse back to original order */
while(lve != nil) {
lveold = lve;
lve = lve->tl;
lveold->tl = ans;
ans = lveold;
}
}
}
*pp = p;
*pelist = ans;
return err;
}
/*
* Encode e by BER rules, putting answer in *pbytes.
* This is done by first calling enc with lenonly==1
* to get the length of the needed buffer,
* then allocating the buffer and using enc again to fill it up.
*/
static int
encode(Elem e, Bytes** pbytes)
{
uchar* p;
Bytes* ans;
int err;
uchar uc;
p = &uc;
err = enc(&p, e, 1);
if(err == ASN_OK) {
ans = newbytes(p-&uc);
p = ans->data;
err = enc(&p, e, 0);
*pbytes = ans;
}
return err;
}
/*
* The various enc functions take a pointer to a pointer
* into a buffer, and encode their entity starting there,
* updating the pointer afterwards.
* If lenonly is 1, only the pointer update is done,
* allowing enc to be called first to calculate the needed
* buffer length.
* If lenonly is 0, it is assumed that the answer will fit.
*/
static int
enc(uchar** pp, Elem e, int lenonly)
{
int err;
int vlen;
int constr;
Tag tag;
int v;
int ilen;
uchar* p;
uchar* psave;
p = *pp;
err = val_enc(&p, e, &constr, 1);
if(err != ASN_OK)
return err;
vlen = p - *pp;
p = *pp;
tag = e.tag;
v = tag.class|constr;
if(tag.num < 31) {
if(!lenonly)
*p = (v|tag.num);
p++;
}
else {
if(!lenonly)
*p = (v|31);
p++;
if(tag.num < 0)
return ASN_EINVAL;
uint7_enc(&p, tag.num, lenonly);
}
if(vlen < 0x80) {
if(!lenonly)
*p = vlen;
p++;
}
else {
psave = p;
int_enc(&p, vlen, 1, 1);
ilen = p-psave;
p = psave;
if(!lenonly) {
*p++ = (0x80 | ilen);
int_enc(&p, vlen, 1, 0);
}
else
p += 1 + ilen;
}
if(!lenonly)
val_enc(&p, e, &constr, 0);
else
p += vlen;
*pp = p;
return err;
}
static int
val_enc(uchar** pp, Elem e, int *pconstr, int lenonly)
{
int err;
uchar* p;
int kind;
int cl;
int v;
Bytes* bb = nil;
Bits* bits;
Ints* oid;
int k;
Elist* el;
char* s;
p = *pp;
err = ASN_OK;
kind = e.tag.num;
cl = e.tag.class;
*pconstr = 0;
if(cl != Universal) {
switch(e.val.tag) {
case VBool:
kind = BOOLEAN;
break;
case VInt:
kind = INTEGER;
break;
case VBigInt:
kind = INTEGER;
break;
case VOctets:
kind = OCTET_STRING;
break;
case VReal:
kind = REAL;
break;
case VOther:
kind = OCTET_STRING;
break;
case VBitString:
kind = BIT_STRING;
break;
case VNull:
kind = NULLTAG;
break;
case VObjId:
kind = OBJECT_ID;
break;
case VString:
kind = UniversalString;
break;
case VSeq:
kind = SEQUENCE;
break;
case VSet:
kind = SETOF;
break;
}
}
switch(kind) {
case BOOLEAN:
if(is_int(&e, &v)) {
if(v != 0)
v = 255;
int_enc(&p, v, 1, lenonly);
}
else
err = ASN_EINVAL;
break;
case INTEGER:
case ENUMERATED:
if(is_int(&e, &v))
int_enc(&p, v, 0, lenonly);
else {
if(is_bigint(&e, &bb)) {
if(!lenonly)
memmove(p, bb->data, bb->len);
p += bb->len;
}
else
err = ASN_EINVAL;
}
break;
case BIT_STRING:
if(is_bitstring(&e, &bits)) {
if(bits->len == 0) {
if(!lenonly)
*p = 0;
p++;
}
else {
v = bits->unusedbits;
if(v < 0 || v > 7)
err = ASN_EINVAL;
else {
if(!lenonly) {
*p = v;
memmove(p+1, bits->data, bits->len);
}
p += 1 + bits->len;
}
}
}
else
err = ASN_EINVAL;
break;
case OCTET_STRING:
case ObjectDescriptor:
case EXTERNAL:
case REAL:
case EMBEDDED_PDV:
bb = nil;
switch(e.val.tag) {
case VOctets:
bb = e.val.u.octetsval;
break;
case VReal:
bb = e.val.u.realval;
break;
case VOther:
bb = e.val.u.otherval;
break;
}
if(bb != nil) {
if(!lenonly)
memmove(p, bb->data, bb->len);
p += bb->len;
}
else
err = ASN_EINVAL;
break;
case NULLTAG:
break;
case OBJECT_ID:
if(is_oid(&e, &oid)) {
for(k = 0; k < oid->len; k++) {
v = oid->data[k];
if(k == 0) {
v *= 40;
if(oid->len > 1)
v += oid->data[++k];
}
uint7_enc(&p, v, lenonly);
}
}
else
err = ASN_EINVAL;
break;
case SEQUENCE:
case SETOF:
el = nil;
if(e.val.tag == VSeq)
el = e.val.u.seqval;
else if(e.val.tag == VSet)
el = e.val.u.setval;
else
err = ASN_EINVAL;
if(el != nil) {
*pconstr = CONSTR_MASK;
for(; el != nil; el = el->tl) {
err = enc(&p, el->hd, lenonly);
if(err != ASN_OK)
break;
}
}
break;
case NumericString:
case PrintableString:
case TeletexString:
case VideotexString:
case IA5String:
case UTCTime:
case GeneralizedTime:
case GraphicString:
case VisibleString:
case GeneralString:
case UniversalString:
case BMPString:
if(e.val.tag == VString) {
s = e.val.u.stringval;
if(s != nil) {
v = strlen(s);
if(!lenonly)
memmove(p, s, v);
p += v;
}
}
else
err = ASN_EINVAL;
break;
default:
err = ASN_EINVAL;
}
*pp = p;
return err;
}
/*
* Encode num as unsigned 7 bit values with top bit 1 on all bytes
* except last, only putting in bytes if !lenonly.
*/
static void
uint7_enc(uchar** pp, int num, int lenonly)
{
int n;
int v;
int k;
uchar* p;
p = *pp;
n = 1;
v = num >> 7;
while(v > 0) {
v >>= 7;
n++;
}
if(lenonly)
p += n;
else {
for(k = (n - 1)*7; k > 0; k -= 7)
*p++= ((num >> k)|0x80);
*p++ = (num&0x7F);
}
*pp = p;
}
/*
* Encode num as unsigned or signed integer,
* only putting in bytes if !lenonly.
* Encoding is length followed by bytes to concatenate.
*/
static void
int_enc(uchar** pp, int num, int unsgned, int lenonly)
{
int v;
int n;
int prevv;
int k;
uchar* p;
p = *pp;
v = num;
if(v < 0)
v = -(v + 1);
n = 1;
prevv = v;
v >>= 8;
while(v > 0) {
prevv = v;
v >>= 8;
n++;
}
if(!unsgned && (prevv&0x80))
n++;
if(lenonly)
p += n;
else {
for(k = (n - 1)*8; k >= 0; k -= 8)
*p++ = (num >> k);
}
*pp = p;
}
static int
ints_eq(Ints* a, Ints* b)
{
int alen;
int i;
alen = a->len;
if(alen != b->len)
return 0;
for(i = 0; i < alen; i++)
if(a->data[i] != b->data[i])
return 0;
return 1;
}
/*
* Look up o in tab (which must have nil entry to terminate).
* Return index of matching entry, or -1 if none.
*/
static int
oid_lookup(Ints* o, Ints** tab)
{
int i;
for(i = 0; tab[i] != nil; i++)
if(ints_eq(o, tab[i]))
return i;
return -1;
}
/*
* Return true if *pe is a SEQUENCE, and set *pseq to
* the value of the sequence if so.
*/
static int
is_seq(Elem* pe, Elist** pseq)
{
if(pe->tag.class == Universal && pe->tag.num == SEQUENCE && pe->val.tag == VSeq) {
*pseq = pe->val.u.seqval;
return 1;
}
return 0;
}
static int
is_set(Elem* pe, Elist** pset)
{
if(pe->tag.class == Universal && pe->tag.num == SETOF && pe->val.tag == VSet) {
*pset = pe->val.u.setval;
return 1;
}
return 0;
}
static int
is_int(Elem* pe, int* pint)
{
if(pe->tag.class == Universal) {
if(pe->tag.num == INTEGER && pe->val.tag == VInt) {
*pint = pe->val.u.intval;
return 1;
}
else if(pe->tag.num == BOOLEAN && pe->val.tag == VBool) {
*pint = pe->val.u.boolval;
return 1;
}
}
return 0;
}
/*
* for convience, all VInt's are readable via this routine,
* as well as all VBigInt's
*/
static int
is_bigint(Elem* pe, Bytes** pbigint)
{
int v, n, i;
if(pe->tag.class == Universal && pe->tag.num == INTEGER) {
if(pe->val.tag == VBigInt)
*pbigint = pe->val.u.bigintval;
else if(pe->val.tag == VInt){
v = pe->val.u.intval;
for(n = 1; n < 4; n++)
if((1 << (8 * n)) > v)
break;
*pbigint = newbytes(n);
for(i = 0; i < n; i++)
(*pbigint)->data[i] = (v >> ((n - 1 - i) * 8));
}else
return 0;
return 1;
}
return 0;
}
static int
is_bitstring(Elem* pe, Bits** pbits)
{
if(pe->tag.class == Universal && pe->tag.num == BIT_STRING && pe->val.tag == VBitString) {
*pbits = pe->val.u.bitstringval;
return 1;
}
return 0;
}
static int
is_octetstring(Elem* pe, Bytes** poctets)
{
if(pe->tag.class == Universal && pe->tag.num == OCTET_STRING && pe->val.tag == VOctets) {
*poctets = pe->val.u.octetsval;
return 1;
}
return 0;
}
static int
is_oid(Elem* pe, Ints** poid)
{
if(pe->tag.class == Universal && pe->tag.num == OBJECT_ID && pe->val.tag == VObjId) {
*poid = pe->val.u.objidval;
return 1;
}
return 0;
}
static int
is_string(Elem* pe, char** pstring)
{
if(pe->tag.class == Universal) {
switch(pe->tag.num) {
case NumericString:
case PrintableString:
case TeletexString:
case VideotexString:
case IA5String:
case GraphicString:
case VisibleString:
case GeneralString:
case UniversalString:
case BMPString:
if(pe->val.tag == VString) {
*pstring = pe->val.u.stringval;
return 1;
}
}
}
return 0;
}
static int
is_time(Elem* pe, char** ptime)
{
if(pe->tag.class == Universal
&& (pe->tag.num == UTCTime || pe->tag.num == GeneralizedTime)
&& pe->val.tag == VString) {
*ptime = pe->val.u.stringval;
return 1;
}
return 0;
}
/*
* malloc and return a new Bytes structure capable of
* holding len bytes. (len >= 0)
*/
static Bytes*
newbytes(int len)
{
Bytes* ans;
ans = (Bytes*)emalloc(OFFSETOF(data[0], Bytes) + len);
ans->len = len;
return ans;
}
/*
* newbytes(len), with data initialized from buf
*/
static Bytes*
makebytes(uchar* buf, int len)
{
Bytes* ans;
ans = newbytes(len);
memmove(ans->data, buf, len);
return ans;
}
static void
freebytes(Bytes* b)
{
if(b != nil)
free(b);
}
/*
* Make a new Bytes, containing bytes of b1 followed by those of b2.
* Either b1 or b2 or both can be nil.
*/
static Bytes*
catbytes(Bytes* b1, Bytes* b2)
{
Bytes* ans;
int n;
if(b1 == nil) {
if(b2 == nil)
ans = newbytes(0);
else
ans = makebytes(b2->data, b2->len);
}
else if(b2 == nil) {
ans = makebytes(b1->data, b1->len);
}
else {
n = b1->len + b2->len;
ans = newbytes(n);
ans->len = n;
memmove(ans->data, b1->data, b1->len);
memmove(ans->data+b1->len, b2->data, b2->len);
}
return ans;
}
/* len is number of ints */
static Ints*
newints(int len)
{
Ints* ans;
ans = (Ints*)emalloc(OFFSETOF(data[0], Ints) + len*sizeof(int));
ans->len = len;
return ans;
}
static Ints*
makeints(int* buf, int len)
{
Ints* ans;
ans = newints(len);
if(len > 0)
memmove(ans->data, buf, len*sizeof(int));
return ans;
}
static void
freeints(Ints* b)
{
if(b != nil)
free(b);
}
/* len is number of bytes */
static Bits*
newbits(int len)
{
Bits* ans;
ans = (Bits*)emalloc(OFFSETOF(data[0], Bits) + len);
ans->len = len;
ans->unusedbits = 0;
return ans;
}
static Bits*
makebits(uchar* buf, int len, int unusedbits)
{
Bits* ans;
ans = newbits(len);
memmove(ans->data, buf, len);
ans->unusedbits = unusedbits;
return ans;
}
static void
freebits(Bits* b)
{
if(b != nil)
free(b);
}
static Elist*
mkel(Elem e, Elist* tail)
{
Elist* el;
el = (Elist*)emalloc(sizeof(Elist));
el->hd = e;
el->tl = tail;
return el;
}
static int
elistlen(Elist* el)
{
int ans = 0;
while(el != nil) {
ans++;
el = el->tl;
}
return ans;
}
/* Frees elist, but not fields inside values of constituent elems */
static void
freeelist(Elist* el)
{
Elist* next;
while(el != nil) {
next = el->tl;
free(el);
el = next;
}
}
/* free any allocated structures inside v (recursively freeing Elists) */
static void
freevalfields(Value* v)
{
Elist* el;
Elist* l;
if(v == nil)
return;
switch(v->tag) {
case VOctets:
freebytes(v->u.octetsval);
break;
case VBigInt:
freebytes(v->u.bigintval);
break;
case VReal:
freebytes(v->u.realval);
break;
case VOther:
freebytes(v->u.otherval);
break;
case VBitString:
freebits(v->u.bitstringval);
break;
case VObjId:
freeints(v->u.objidval);
break;
case VString:
if (v->u.stringval)
free(v->u.stringval);
break;
case VSeq:
el = v->u.seqval;
for(l = el; l != nil; l = l->tl)
freevalfields(&l->hd.val);
if (el)
freeelist(el);
break;
case VSet:
el = v->u.setval;
for(l = el; l != nil; l = l->tl)
freevalfields(&l->hd.val);
if (el)
freeelist(el);
break;
}
}
/* end of general ASN1 functions */
/*=============================================================*/
/*
* Decode and parse an X.509 Certificate, defined by this ASN1:
* Certificate ::= SEQUENCE {
* certificateInfo CertificateInfo,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING }
*
* CertificateInfo ::= SEQUENCE {
* version [0] INTEGER DEFAULT v1 (0),
* serialNumber INTEGER,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo }
* (version v2 has two more fields, optional unique identifiers for
* issuer and subject; since we ignore these anyway, we won't parse them)
*
* Validity ::= SEQUENCE {
* notBefore UTCTime,
* notAfter UTCTime }
*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFER,
* parameters ANY DEFINED BY ALGORITHM OPTIONAL }
*
* Name ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SETOF SIZE(1..MAX) OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type OBJECT IDENTIFER,
* value DirectoryString }
* (selected attributes have these Object Ids:
* commonName {2 5 4 3}
* countryName {2 5 4 6}
* localityName {2 5 4 7}
* stateOrProvinceName {2 5 4 8}
* organizationName {2 5 4 10}
* organizationalUnitName {2 5 4 11}
* )
*
* DirectoryString ::= CHOICE {
* teletexString TeletexString,
* printableString PrintableString,
* universalString UniversalString }
*
* See rfc1423, rfc2437 for AlgorithmIdentifier, subjectPublicKeyInfo, signature.
*
* Not yet implemented:
* CertificateRevocationList ::= SIGNED SEQUENCE{
* signature AlgorithmIdentifier,
* issuer Name,
* lastUpdate UTCTime,
* nextUpdate UTCTime,
* revokedCertificates
* SEQUENCE OF CRLEntry OPTIONAL}
* CRLEntry ::= SEQUENCE{
* userCertificate SerialNumber,
* revocationDate UTCTime}
*/
typedef struct CertX509 {
int serial;
char* issuer;
char* validity_start;
char* validity_end;
char* subject;
int publickey_alg;
Bytes* publickey;
int signature_alg;
Bytes* signature;
} CertX509;
/* Algorithm object-ids */
enum {
ALG_rsaEncryption,
ALG_md2WithRSAEncryption,
ALG_md4WithRSAEncryption,
ALG_md5WithRSAEncryption,
ALG_sha1WithRSAEncryption,
ALG_md5,
NUMALGS
};
typedef struct Ints7 {
int len;
int data[7];
} Ints7;
static Ints7 oid_rsaEncryption = {7, 1, 2, 840, 113549, 1, 1, 1 };
static Ints7 oid_md2WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 2 };
static Ints7 oid_md4WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 3 };
static Ints7 oid_md5WithRSAEncryption = {7, 1, 2, 840, 113549, 1, 1, 4 };
static Ints7 oid_sha1WithRSAEncryption ={7, 1, 2, 840, 113549, 1, 1, 5 };
static Ints7 oid_md5 ={6, 1, 2, 840, 113549, 2, 5, 0 };
static Ints *alg_oid_tab[NUMALGS+1] = {
(Ints*)&oid_rsaEncryption,
(Ints*)&oid_md2WithRSAEncryption,
(Ints*)&oid_md4WithRSAEncryption,
(Ints*)&oid_md5WithRSAEncryption,
(Ints*)&oid_sha1WithRSAEncryption,
(Ints*)&oid_md5,
nil
};
static DigestFun digestalg[NUMALGS+1] = { md5, md5, md5, md5, sha1, md5, nil };
static void
freecert(CertX509* c)
{
if (!c) return;
if(c->issuer != nil)
free(c->issuer);
if(c->validity_start != nil)
free(c->validity_start);
if(c->validity_end != nil)
free(c->validity_end);
if(c->subject != nil)
free(c->subject);
freebytes(c->publickey);
freebytes(c->signature);
}
/*
* Parse the Name ASN1 type.
* The sequence of RelativeDistinguishedName's gives a sort of pathname,
* from most general to most specific. Each element of the path can be
* one or more (but usually just one) attribute-value pair, such as
* countryName="US".
* We'll just form a "postal-style" address string by concatenating the elements
* from most specific to least specific, separated by commas.
* Return name-as-string (which must be freed by caller).
*/
static char*
parse_name(Elem* e)
{
Elist* el;
Elem* es;
Elist* esetl;
Elem* eat;
Elist* eatl;
char* s;
enum { MAXPARTS = 100 };
char* parts[MAXPARTS];
int i;
int plen;
char* ans = nil;
if(!is_seq(e, &el))
goto errret;
i = 0;
plen = 0;
while(el != nil) {
es = &el->hd;
if(!is_set(es, &esetl))
goto errret;
while(esetl != nil) {
eat = &esetl->hd;
if(!is_seq(eat, &eatl) || elistlen(eatl) != 2)
goto errret;
if(!is_string(&eatl->tl->hd, &s) || i>=MAXPARTS)
goto errret;
parts[i++] = s;
plen += strlen(s) + 2; /* room for ", " after */
esetl = esetl->tl;
}
el = el->tl;
}
if(i > 0) {
ans = (char*)emalloc(plen);
*ans = '\0';
while(--i >= 0) {
s = parts[i];
strcat(ans, s);
if(i > 0)
strcat(ans, ", ");
}
}
errret:
return ans;
}
/*
* Parse an AlgorithmIdentifer ASN1 type.
* Look up the oid in oid_tab and return one of OID_rsaEncryption, etc..,
* or -1 if not found.
* For now, ignore parameters, since none of our algorithms need them.
*/
static int
parse_alg(Elem* e)
{
Elist* el;
Ints* oid;
if(!is_seq(e, &el) || el == nil || !is_oid(&el->hd, &oid))
return -1;
return oid_lookup(oid, alg_oid_tab);
}
static CertX509*
decode_cert(Bytes* a)
{
int ok = 0;
int n;
CertX509* c = nil;
Elem ecert;
Elem* ecertinfo;
Elem* esigalg;
Elem* esig;
Elem* eserial;
Elem* eissuer;
Elem* evalidity;
Elem* esubj;
Elem* epubkey;
Elist* el;
Elist* elcert = nil;
Elist* elcertinfo = nil;
Elist* elvalidity = nil;
Elist* elpubkey = nil;
Bits* bits = nil;
Bytes* b;
Elem* e;
if(decode(a->data, a->len, &ecert) != ASN_OK)
goto errret;
c = (CertX509*)emalloc(sizeof(CertX509));
c->serial = -1;
c->issuer = nil;
c->validity_start = nil;
c->validity_end = nil;
c->subject = nil;
c->publickey_alg = -1;
c->publickey = nil;
c->signature_alg = -1;
c->signature = nil;
/* Certificate */
if(!is_seq(&ecert, &elcert) || elistlen(elcert) !=3)
goto errret;
ecertinfo = &elcert->hd;
el = elcert->tl;
esigalg = &el->hd;
c->signature_alg = parse_alg(esigalg);
el = el->tl;
esig = &el->hd;
/* Certificate Info */
if(!is_seq(ecertinfo, &elcertinfo))
goto errret;
n = elistlen(elcertinfo);
if(n < 6)
goto errret;
eserial =&elcertinfo->hd;
el = elcertinfo->tl;
/* check for optional version, marked by explicit context tag 0 */
if(eserial->tag.class == Context && eserial->tag.num == 0) {
eserial = &el->hd;
if(n < 7)
goto errret;
el = el->tl;
}
if(parse_alg(&el->hd) != c->signature_alg)
goto errret;
el = el->tl;
eissuer = &el->hd;
el = el->tl;
evalidity = &el->hd;
el = el->tl;
esubj = &el->hd;
el = el->tl;
epubkey = &el->hd;
if(!is_int(eserial, &c->serial)) {
if(!is_bigint(eserial, &b))
goto errret;
c->serial = -1; /* else we have to change cert struct */
}
c->issuer = parse_name(eissuer);
if(c->issuer == nil)
goto errret;
/* Validity */
if(!is_seq(evalidity, &elvalidity))
goto errret;
if(elistlen(elvalidity) != 2)
goto errret;
e = &elvalidity->hd;
if(!is_time(e, &c->validity_start))
goto errret;
e->val.u.stringval = nil; /* string ownership transfer */
e = &elvalidity->tl->hd;
if(!is_time(e, &c->validity_end))
goto errret;
e->val.u.stringval = nil; /* string ownership transfer */
/* resume CertificateInfo */
c->subject = parse_name(esubj);
if(c->subject == nil)
goto errret;
/* SubjectPublicKeyInfo */
if(!is_seq(epubkey, &elpubkey))
goto errret;
if(elistlen(elpubkey) != 2)
goto errret;
c->publickey_alg = parse_alg(&elpubkey->hd);
if(c->publickey_alg < 0)
goto errret;
if(!is_bitstring(&elpubkey->tl->hd, &bits))
goto errret;
if(bits->unusedbits != 0)
goto errret;
c->publickey = makebytes(bits->data, bits->len);
/*resume Certificate */
if(c->signature_alg < 0)
goto errret;
if(!is_bitstring(esig, &bits))
goto errret;
c->signature = makebytes(bits->data, bits->len);
ok = 1;
errret:
freevalfields(&ecert.val); /* recurses through lists, too */
if(!ok){
freecert(c);
c = nil;
}
return c;
}
/*
* RSAPublickKey :: SEQUENCE {
* modulus INTEGER,
* publicExponent INTEGER
* }
*/
static RSApub*
decode_rsapubkey(Bytes* a)
{
Elem e;
Elist *el;
mpint *mp;
RSApub* key;
key = rsapuballoc();
if(decode(a->data, a->len, &e) != ASN_OK)
goto errret;
if(!is_seq(&e, &el) || elistlen(el) != 2)
goto errret;
key->n = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->ek = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
return key;
errret:
rsapubfree(key);
return nil;
}
/*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER -- (inverse of q) mod p }
*/
static RSApriv*
decode_rsaprivkey(Bytes* a)
{
int version;
Elem e;
Elist *el;
mpint *mp;
RSApriv* key;
key = rsaprivalloc();
if(decode(a->data, a->len, &e) != ASN_OK)
goto errret;
if(!is_seq(&e, &el) || elistlen(el) != 9)
goto errret;
if(!is_int(&el->hd, &version) || version != 0)
goto errret;
el = el->tl;
key->pub.n = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->pub.ek = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->dk = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->q = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->p = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->kq = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->kp = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
el = el->tl;
key->c2 = mp = asn1mpint(&el->hd);
if(mp == nil)
goto errret;
return key;
errret:
rsaprivfree(key);
return nil;
}
static mpint*
asn1mpint(Elem *e)
{
Bytes *b;
mpint *mp;
int v;
if(is_int(e, &v))
return itomp(v, nil);
if(is_bigint(e, &b)) {
mp = betomp(b->data, b->len, nil);
freebytes(b);
return mp;
}
return nil;
}
static mpint*
pkcs1pad(Bytes *b, mpint *modulus)
{
int n = (mpsignif(modulus)+7)/8;
int pm1, i;
uchar *p;
mpint *mp;
pm1 = n - 1 - b->len;
p = (uchar*)emalloc(n);
p[0] = 0;
p[1] = 1;
for(i = 2; i < pm1; i++)
p[i] = 0xFF;
p[pm1] = 0;
memcpy(&p[pm1+1], b->data, b->len);
mp = betomp(p, n, nil);
free(p);
return mp;
}
RSApriv*
asn1toRSApriv(uchar *kd, int kn)
{
Bytes *b;
RSApriv *key;
b = makebytes(kd, kn);
key = decode_rsaprivkey(b);
freebytes(b);
return key;
}
/*
* digest(CertificateInfo)
* Our ASN.1 library doesn't return pointers into the original
* data array, so we need to do a little hand decoding.
*/
static void
digest_certinfo(Bytes *cert, DigestFun digestfun, uchar *digest)
{
uchar *info, *p, *pend;
ulong infolen;
int isconstr, length;
Tag tag;
Elem elem;
p = cert->data;
pend = cert->data + cert->len;
if(tag_decode(&p, pend, &tag, &isconstr) != ASN_OK ||
tag.class != Universal || tag.num != SEQUENCE ||
length_decode(&p, pend, &length) != ASN_OK ||
p+length > pend)
return;
info = p;
if(ber_decode(&p, pend, &elem) != ASN_OK || elem.tag.num != SEQUENCE)
return;
infolen = p - info;
(*digestfun)(info, infolen, digest, nil);
}
static char*
verify_signature(Bytes* signature, RSApub *pk, uchar *edigest, Elem **psigalg)
{
Elem e;
Elist *el;
Bytes *digest;
uchar *pkcs1buf, *buf;
int buflen;
mpint *pkcs1;
/* see 9.2.1 of rfc2437 */
pkcs1 = betomp(signature->data, signature->len, nil);
mpexp(pkcs1, pk->ek, pk->n, pkcs1);
buflen = mptobe(pkcs1, nil, 0, &pkcs1buf);
buf = pkcs1buf;
if(buflen < 4 || buf[0] != 1)
return "expected 1";
buf++;
while(buf[0] == 0xff)
buf++;
if(buf[0] != 0)
return "expected 0";
buf++;
buflen -= buf-pkcs1buf;
if(decode(buf, buflen, &e) != ASN_OK || !is_seq(&e, &el) || elistlen(el) != 2 ||
!is_octetstring(&el->tl->hd, &digest))
return "signature parse error";
*psigalg = &el->hd;
if(memcmp(digest->data, edigest, digest->len) == 0)
return nil;
return "digests did not match";
}
RSApub*
X509toRSApub(uchar *cert, int ncert, char *name, int nname)
{
char *e;
Bytes *b;
CertX509 *c;
RSApub *pk;
b = makebytes(cert, ncert);
c = decode_cert(b);
freebytes(b);
if(c == nil)
return nil;
if(name != nil && c->subject != nil){
e = strchr(c->subject, ',');
if(e != nil)
*e = 0; // take just CN part of Distinguished Name
strncpy(name, c->subject, nname);
}
pk = decode_rsapubkey(c->publickey);
freecert(c);
return pk;
}
char*
X509verify(uchar *cert, int ncert, RSApub *pk)
{
char *e;
Bytes *b;
CertX509 *c;
uchar digest[SHA1dlen];
Elem *sigalg;
b = makebytes(cert, ncert);
c = decode_cert(b);
if(c != nil)
digest_certinfo(b, digestalg[c->signature_alg], digest);
freebytes(b);
if(c == nil)
return "cannot decode cert";
e = verify_signature(c->signature, pk, digest, &sigalg);
freecert(c);
return e;
}
/* ------- Elem constructors ---------- */
static Elem
Null(void)
{
Elem e;
e.tag.class = Universal;
e.tag.num = NULLTAG;
e.val.tag = VNull;
return e;
}
static Elem
mkint(int j)
{
Elem e;
e.tag.class = Universal;
e.tag.num = INTEGER;
e.val.tag = VInt;
e.val.u.intval = j;
return e;
}
static Elem
mkbigint(mpint *p)
{
Elem e;
uchar *buf;
int buflen;
e.tag.class = Universal;
e.tag.num = INTEGER;
e.val.tag = VBigInt;
buflen = mptobe(p, nil, 0, &buf);
e.val.u.bigintval = makebytes(buf, buflen);
free(buf);
return e;
}
static Elem
mkstring(char *s)
{
Elem e;
e.tag.class = Universal;
e.tag.num = IA5String;
e.val.tag = VString;
e.val.u.stringval = estrdup(s);
return e;
}
static Elem
mkoctet(uchar *buf, int buflen)
{
Elem e;
e.tag.class = Universal;
e.tag.num = OCTET_STRING;
e.val.tag = VOctets;
e.val.u.octetsval = makebytes(buf, buflen);
return e;
}
static Elem
mkbits(uchar *buf, int buflen)
{
Elem e;
e.tag.class = Universal;
e.tag.num = BIT_STRING;
e.val.tag = VBitString;
e.val.u.bitstringval = makebits(buf, buflen, 0);
return e;
}
static Elem
mkutc(long t)
{
Elem e;
char utc[50];
Tm *tm = gmtime(t);
e.tag.class = Universal;
e.tag.num = UTCTime;
e.val.tag = VString;
snprint(utc, 50, "%.2d%.2d%.2d%.2d%.2d%.2dZ",
tm->year % 100, tm->mon+1, tm->mday, tm->hour, tm->min, tm->sec);
e.val.u.stringval = estrdup(utc);
return e;
}
static Elem
mkoid(Ints *oid)
{
Elem e;
e.tag.class = Universal;
e.tag.num = OBJECT_ID;
e.val.tag = VObjId;
e.val.u.objidval = makeints(oid->data, oid->len);
return e;
}
static Elem
mkseq(Elist *el)
{
Elem e;
e.tag.class = Universal;
e.tag.num = SEQUENCE;
e.val.tag = VSeq;
e.val.u.seqval = el;
return e;
}
static Elem
mkset(Elist *el)
{
Elem e;
e.tag.class = Universal;
e.tag.num = SETOF;
e.val.tag = VSet;
e.val.u.setval = el;
return e;
}
static Elem
mkalg(int alg)
{
return mkseq(mkel(mkoid(alg_oid_tab[alg]), mkel(Null(), nil)));
}
typedef struct Ints7pref {
int len;
int data[7];
char prefix[4];
} Ints7pref;
Ints7pref DN_oid[] = {
{4, 2, 5, 4, 6, 0, 0, 0, "C="},
{4, 2, 5, 4, 8, 0, 0, 0, "ST="},
{4, 2, 5, 4, 7, 0, 0, 0, "L="},
{4, 2, 5, 4, 10, 0, 0, 0, "O="},
{4, 2, 5, 4, 11, 0, 0, 0, "OU="},
{4, 2, 5, 4, 3, 0, 0, 0, "CN="},
{7, 1,2,840,113549,1,9,1, "E="},
};
static Elem
mkname(Ints7pref *oid, char *subj)
{
return mkset(mkel(mkseq(mkel(mkoid((Ints*)oid), mkel(mkstring(subj), nil))), nil));
}
static Elem
mkDN(char *dn)
{
int i, j, nf;
char *f[20], *prefix, *d2 = estrdup(dn);
Elist* el = nil;
nf = tokenize(d2, f, nelem(f));
for(i=nf-1; i>=0; i--){
for(j=0; j<nelem(DN_oid); j++){
prefix = DN_oid[j].prefix;
if(strncmp(f[i],prefix,strlen(prefix))==0){
el = mkel(mkname(&DN_oid[j],f[i]+strlen(prefix)), el);
break;
}
}
}
free(d2);
return mkseq(el);
}
uchar*
X509gen(RSApriv *priv, char *subj, ulong valid[2], int *certlen)
{
int serial = 0;
uchar *cert = nil;
RSApub *pk = rsaprivtopub(priv);
Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
Elem e, certinfo, issuer, subject, pubkey, validity, sig;
uchar digest[MD5dlen], *buf;
int buflen;
mpint *pkcs1;
e.val.tag = VInt; /* so freevalfields at errret is no-op */
issuer = mkDN(subj);
subject = mkDN(subj);
pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
if(encode(pubkey, &pkbytes) != ASN_OK)
goto errret;
freevalfields(&pubkey.val);
pubkey = mkseq(
mkel(mkalg(ALG_rsaEncryption),
mkel(mkbits(pkbytes->data, pkbytes->len),
nil)));
freebytes(pkbytes);
validity = mkseq(
mkel(mkutc(valid[0]),
mkel(mkutc(valid[1]),
nil)));
certinfo = mkseq(
mkel(mkint(serial),
mkel(mkalg(ALG_md5WithRSAEncryption),
mkel(issuer,
mkel(validity,
mkel(subject,
mkel(pubkey,
nil)))))));
if(encode(certinfo, &certinfobytes) != ASN_OK)
goto errret;
md5(certinfobytes->data, certinfobytes->len, digest, 0);
freebytes(certinfobytes);
sig = mkseq(
mkel(mkalg(ALG_md5),
mkel(mkoctet(digest, MD5dlen),
nil)));
if(encode(sig, &sigbytes) != ASN_OK)
goto errret;
pkcs1 = pkcs1pad(sigbytes, pk->n);
freebytes(sigbytes);
rsadecrypt(priv, pkcs1, pkcs1);
buflen = mptobe(pkcs1, nil, 0, &buf);
mpfree(pkcs1);
e = mkseq(
mkel(certinfo,
mkel(mkalg(ALG_md5WithRSAEncryption),
mkel(mkbits(buf, buflen),
nil))));
free(buf);
if(encode(e, &certbytes) != ASN_OK)
goto errret;
if(certlen)
*certlen = certbytes->len;
cert = certbytes->data;
errret:
freevalfields(&e.val);
return cert;
}
uchar*
X509req(RSApriv *priv, char *subj, int *certlen)
{
/* RFC 2314, PKCS #10 Certification Request Syntax */
int version = 0;
uchar *cert = nil;
RSApub *pk = rsaprivtopub(priv);
Bytes *certbytes, *pkbytes, *certinfobytes, *sigbytes;
Elem e, certinfo, subject, pubkey, sig;
uchar digest[MD5dlen], *buf;
int buflen;
mpint *pkcs1;
e.val.tag = VInt; /* so freevalfields at errret is no-op */
subject = mkDN(subj);
pubkey = mkseq(mkel(mkbigint(pk->n),mkel(mkint(mptoi(pk->ek)),nil)));
if(encode(pubkey, &pkbytes) != ASN_OK)
goto errret;
freevalfields(&pubkey.val);
pubkey = mkseq(
mkel(mkalg(ALG_rsaEncryption),
mkel(mkbits(pkbytes->data, pkbytes->len),
nil)));
freebytes(pkbytes);
certinfo = mkseq(
mkel(mkint(version),
mkel(subject,
mkel(pubkey,
nil))));
if(encode(certinfo, &certinfobytes) != ASN_OK)
goto errret;
md5(certinfobytes->data, certinfobytes->len, digest, 0);
freebytes(certinfobytes);
sig = mkseq(
mkel(mkalg(ALG_md5),
mkel(mkoctet(digest, MD5dlen),
nil)));
if(encode(sig, &sigbytes) != ASN_OK)
goto errret;
pkcs1 = pkcs1pad(sigbytes, pk->n);
freebytes(sigbytes);
rsadecrypt(priv, pkcs1, pkcs1);
buflen = mptobe(pkcs1, nil, 0, &buf);
mpfree(pkcs1);
e = mkseq(
mkel(certinfo,
mkel(mkalg(ALG_md5),
mkel(mkbits(buf, buflen),
nil))));
free(buf);
if(encode(e, &certbytes) != ASN_OK)
goto errret;
if(certlen)
*certlen = certbytes->len;
cert = certbytes->data;
errret:
freevalfields(&e.val);
return cert;
}
static char*
tagdump(Tag tag)
{
if(tag.class != Universal)
return smprint("class%d,num%d", tag.class, tag.num);
switch(tag.num){
case BOOLEAN: return "BOOLEAN"; break;
case INTEGER: return "INTEGER"; break;
case BIT_STRING: return "BIT STRING"; break;
case OCTET_STRING: return "OCTET STRING"; break;
case NULLTAG: return "NULLTAG"; break;
case OBJECT_ID: return "OID"; break;
case ObjectDescriptor: return "OBJECT_DES"; break;
case EXTERNAL: return "EXTERNAL"; break;
case REAL: return "REAL"; break;
case ENUMERATED: return "ENUMERATED"; break;
case EMBEDDED_PDV: return "EMBEDDED PDV"; break;
case SEQUENCE: return "SEQUENCE"; break;
case SETOF: return "SETOF"; break;
case NumericString: return "NumericString"; break;
case PrintableString: return "PrintableString"; break;
case TeletexString: return "TeletexString"; break;
case VideotexString: return "VideotexString"; break;
case IA5String: return "IA5String"; break;
case UTCTime: return "UTCTime"; break;
case GeneralizedTime: return "GeneralizedTime"; break;
case GraphicString: return "GraphicString"; break;
case VisibleString: return "VisibleString"; break;
case GeneralString: return "GeneralString"; break;
case UniversalString: return "UniversalString"; break;
case BMPString: return "BMPString"; break;
default:
return smprint("Universal,num%d", tag.num);
}
}
static void
edump(Elem e)
{
Value v;
Elist *el;
int i;
print("%s{", tagdump(e.tag));
v = e.val;
switch(v.tag){
case VBool: print("Bool %d",v.u.boolval); break;
case VInt: print("Int %d",v.u.intval); break;
case VOctets: print("Octets[%d] %.2x%.2x...",v.u.octetsval->len,v.u.octetsval->data[0],v.u.octetsval->data[1]); break;
case VBigInt: print("BigInt[%d] %.2x%.2x...",v.u.bigintval->len,v.u.bigintval->data[0],v.u.bigintval->data[1]); break;
case VReal: print("Real..."); break;
case VOther: print("Other..."); break;
case VBitString: print("BitString..."); break;
case VNull: print("Null"); break;
case VEOC: print("EOC..."); break;
case VObjId: print("ObjId");
for(i = 0; i<v.u.objidval->len; i++)
print(" %d", v.u.objidval->data[i]);
break;
case VString: print("String \"%s\"",v.u.stringval); break;
case VSeq: print("Seq\n");
for(el = v.u.seqval; el!=nil; el = el->tl)
edump(el->hd);
break;
case VSet: print("Set\n");
for(el = v.u.setval; el!=nil; el = el->tl)
edump(el->hd);
break;
}
print("}\n");
}
void
asn1dump(uchar *der, int len)
{
Elem e;
if(decode(der, len, &e) != ASN_OK){
print("didn't parse\n");
exits("didn't parse");
}
edump(e);
}
void
X509dump(uchar *cert, int ncert)
{
char *e;
Bytes *b;
CertX509 *c;
RSApub *pk;
uchar digest[SHA1dlen];
Elem *sigalg;
print("begin X509dump\n");
b = makebytes(cert, ncert);
c = decode_cert(b);
if(c != nil)
digest_certinfo(b, digestalg[c->signature_alg], digest);
freebytes(b);
if(c == nil){
print("cannot decode cert");
return;
}
print("serial %d\n", c->serial);
print("issuer %s\n", c->issuer);
print("validity %s %s\n", c->validity_start, c->validity_end);
print("subject %s\n", c->subject);
pk = decode_rsapubkey(c->publickey);
print("pubkey e=%B n(%d)=%B\n", pk->ek, mpsignif(pk->n), pk->n);
print("sigalg=%d digest=%.*H\n", c->signature_alg, MD5dlen, digest);
e = verify_signature(c->signature, pk, digest, &sigalg);
if(e==nil){
e = "nil (meaning ok)";
print("sigalg=\n");
if(sigalg)
edump(*sigalg);
}
print("self-signed verify_signature returns: %s\n", e);
rsapubfree(pk);
freecert(c);
print("end X509dump\n");
}
| 19.92741 | 119 | 0.62237 | [
"object"
] |
08224d6097a593bb2be1bf191c793b8c637412ce | 415 | h | C | src/component/PostProcessComponent.h | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 45 | 2018-08-24T12:57:38.000Z | 2021-11-12T11:21:49.000Z | src/component/PostProcessComponent.h | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | null | null | null | src/component/PostProcessComponent.h | Lyatus/L | 0b594d722200d5ee0198b5d7b9ee72a5d1e12611 | [
"Unlicense"
] | 4 | 2019-09-16T02:48:42.000Z | 2020-07-10T03:50:31.000Z | #pragma once
#include "Component.h"
#include "../rendering/Material.h"
#include "../engine/Resource.h"
namespace L {
class PostProcessComponent : public TComponent<PostProcessComponent> {
protected:
Material _material;
public:
static void script_registration();
void render(const Camera& camera, const RenderPassImpl* render_pass);
inline Material& material() { return _material; }
};
}
| 21.842105 | 73 | 0.722892 | [
"render"
] |
08294e167ee72031a4cbb5af29b674cbbb9d9112 | 11,409 | c | C | test/cmocka/src/audio/eq_iir/eq_iir_process.c | jairaj-arava/sof | bcccf1253d8b52bfdfc2ba1c4b178d747ee0cf79 | [
"BSD-3-Clause"
] | 325 | 2018-06-08T11:41:48.000Z | 2022-03-30T06:09:11.000Z | test/cmocka/src/audio/eq_iir/eq_iir_process.c | jairaj-arava/sof | bcccf1253d8b52bfdfc2ba1c4b178d747ee0cf79 | [
"BSD-3-Clause"
] | 4,535 | 2018-05-31T20:56:48.000Z | 2022-03-31T23:44:25.000Z | test/cmocka/src/audio/eq_iir/eq_iir_process.c | jairaj-arava/sof | bcccf1253d8b52bfdfc2ba1c4b178d747ee0cf79 | [
"BSD-3-Clause"
] | 237 | 2018-06-12T08:29:07.000Z | 2022-03-30T21:33:09.000Z | // SPDX-License-Identifier: BSD-3-Clause
//
// Copyright(c) 2021 Intel Corporation. All rights reserved.
//
// Author: Seppo Ingalsuo <seppo.ingalsuo@linux.intel.com>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <stdint.h>
#include <cmocka.h>
#include <kernel/header.h>
#include <sof/audio/component_ext.h>
#include <sof/audio/eq_iir/eq_iir.h>
#include "../../util.h"
#include "../../../include/cmocka_chirp_2ch.h"
#include "cmocka_chirp_iir_ref_2ch.h"
#include "cmocka_iir_coef_2ch.h"
/* Allow some small error for fixed point. In IIR case due to float
* reference with float coefficients the difference can be quite
* large to scaled integer bi-quads. This could be re-visited with
* a more implementation like reference in Octave test vector
* generate script.
*/
#define ERROR_TOLERANCE_S16 2
#define ERROR_TOLERANCE_S24 128
#define ERROR_TOLERANCE_S32 32768
/* Thresholds for frames count jitter for rand() function */
#define THR_RAND_PLUS_ONE ((RAND_MAX >> 1) + (RAND_MAX >> 2))
#define THR_RAND_MINUS_ONE ((RAND_MAX >> 1) - (RAND_MAX >> 2))
struct buffer_fill {
int idx;
} buffer_fill_data;
struct buffer_verify {
int idx;
} buffer_verify_data;
struct test_parameters {
uint32_t channels;
uint32_t frames;
uint32_t buffer_size_mult;
uint32_t source_format;
uint32_t sink_format;
};
struct test_data {
struct comp_dev *dev;
struct comp_buffer *sink;
struct comp_buffer *source;
struct test_parameters *params;
bool continue_loop;
};
static int setup_group(void **state)
{
sys_comp_init(sof_get());
sys_comp_eq_iir_init();
return 0;
}
static struct sof_ipc_comp_process *create_eq_iir_comp_ipc(struct test_data *td)
{
struct sof_ipc_comp_process *ipc;
struct sof_eq_iir_config *eq;
size_t ipc_size = sizeof(struct sof_ipc_comp_process);
struct sof_abi_hdr *blob = (struct sof_abi_hdr *)iir_coef_2ch;
ipc = calloc(1, ipc_size + blob->size);
eq = (struct sof_eq_iir_config *)&ipc->data;
ipc->comp.hdr.size = sizeof(struct sof_ipc_comp_process);
ipc->comp.type = SOF_COMP_EQ_IIR;
ipc->config.hdr.size = sizeof(struct sof_ipc_comp_config);
ipc->size = blob->size;
memcpy_s(eq, blob->size, blob->data, blob->size);
return ipc;
}
static void prepare_sink(struct test_data *td)
{
struct test_parameters *parameters = td->params;
size_t size;
size_t free;
/* allocate new sink buffer */
size = parameters->frames * get_frame_bytes(parameters->sink_format, parameters->channels) *
parameters->buffer_size_mult;
td->sink = create_test_sink(td->dev, 0, parameters->sink_format,
parameters->channels, size);
free = audio_stream_get_free_bytes(&td->sink->stream);
assert_int_equal(free, size);
}
static void prepare_source(struct test_data *td)
{
struct test_parameters *parameters = td->params;
size_t size;
size_t free;
size = parameters->frames * get_frame_bytes(parameters->source_format,
parameters->channels) * parameters->buffer_size_mult;
td->source = create_test_source(td->dev, 0, parameters->source_format,
parameters->channels, size);
free = audio_stream_get_free_bytes(&td->source->stream);
assert_int_equal(free, size);
}
static int setup(void **state)
{
struct test_parameters *params = *state;
struct test_data *td;
struct sof_ipc_comp_process *ipc;
int ret;
td = test_malloc(sizeof(*td));
if (!td)
return -EINVAL;
td->params = test_malloc(sizeof(*params));
if (!td->params)
return -EINVAL;
memcpy_s(td->params, sizeof(*td->params), params, sizeof(*params));
ipc = create_eq_iir_comp_ipc(td);
buffer_fill_data.idx = 0;
buffer_verify_data.idx = 0;
td->dev = comp_new((struct sof_ipc_comp *)ipc);
free(ipc);
if (!td->dev)
return -EINVAL;
prepare_sink(td);
prepare_source(td);
ret = comp_prepare(td->dev);
if (ret)
return ret;
td->continue_loop = true;
*state = td;
return 0;
}
static int teardown(void **state)
{
struct test_data *td = *state;
test_free(td->params);
free_test_source(td->source);
free_test_sink(td->sink);
comp_free(td->dev);
test_free(td);
return 0;
}
#if CONFIG_FORMAT_S16LE
static void fill_source_s16(struct test_data *td, int frames_max)
{
struct comp_dev *dev = td->dev;
struct comp_buffer *sb;
struct audio_stream *ss;
int16_t *x;
int bytes_total;
int samples;
int frames;
int i;
int samples_processed = 0;
sb = list_first_item(&dev->bsource_list, struct comp_buffer, sink_list);
ss = &sb->stream;
frames = MIN(audio_stream_get_free_frames(ss), frames_max);
samples = frames * ss->channels;
for (i = 0; i < samples; i++) {
x = audio_stream_write_frag_s16(ss, i);
*x = sat_int16(Q_SHIFT_RND(chirp_2ch[buffer_fill_data.idx++], 31, 15));
samples_processed++;
if (buffer_fill_data.idx == CHIRP_2CH_LENGTH) {
td->continue_loop = false;
break;
}
}
if (samples_processed > 0) {
bytes_total = samples_processed * audio_stream_sample_bytes(ss);
comp_update_buffer_produce(sb, bytes_total);
}
}
static void verify_sink_s16(struct test_data *td)
{
struct comp_dev *dev = td->dev;
struct comp_buffer *sb;
struct audio_stream *ss;
int32_t delta;
int32_t ref;
int32_t out;
int16_t *x;
int samples;
int frames;
int i;
sb = list_first_item(&dev->bsink_list, struct comp_buffer, source_list);
ss = &sb->stream;
frames = audio_stream_get_avail_frames(ss);
samples = frames * ss->channels;
for (i = 0; i < samples; i++) {
x = audio_stream_read_frag_s16(ss, i);
out = *x;
ref = sat_int16(Q_SHIFT_RND(chirp_iir_ref_2ch[buffer_verify_data.idx++], 31, 15));
delta = ref - out;
if (delta > ERROR_TOLERANCE_S16 || delta < -ERROR_TOLERANCE_S16)
assert_int_equal(out, ref);
}
if (frames > 0)
comp_update_buffer_consume(sb, frames * audio_stream_frame_bytes(ss));
}
#endif /* CONFIG_FORMAT_S16LE */
#if CONFIG_FORMAT_S24LE
static void fill_source_s24(struct test_data *td, int frames_max)
{
struct comp_dev *dev = td->dev;
struct comp_buffer *sb;
struct audio_stream *ss;
int32_t *x;
int bytes_total;
int samples;
int frames;
int i;
int samples_processed = 0;
sb = list_first_item(&dev->bsource_list, struct comp_buffer, sink_list);
ss = &sb->stream;
frames = MIN(audio_stream_get_free_frames(ss), frames_max);
samples = frames * ss->channels;
for (i = 0; i < samples; i++) {
x = audio_stream_write_frag_s32(ss, i);
*x = sat_int24(Q_SHIFT_RND(chirp_2ch[buffer_fill_data.idx++], 31, 23));
samples_processed++;
if (buffer_fill_data.idx == CHIRP_2CH_LENGTH) {
td->continue_loop = false;
break;
}
}
if (samples_processed > 0) {
bytes_total = samples_processed * audio_stream_sample_bytes(ss);
comp_update_buffer_produce(sb, bytes_total);
}
}
static void verify_sink_s24(struct test_data *td)
{
struct comp_dev *dev = td->dev;
struct comp_buffer *sb;
struct audio_stream *ss;
int32_t delta;
int32_t ref;
int32_t out;
int32_t *x;
int samples;
int frames;
int i;
sb = list_first_item(&dev->bsink_list, struct comp_buffer, source_list);
ss = &sb->stream;
frames = audio_stream_get_avail_frames(ss);
samples = frames * ss->channels;
for (i = 0; i < samples; i++) {
x = audio_stream_read_frag_s32(ss, i);
out = (*x << 8) >> 8; /* Make sure there's no 24 bit overflow */
ref = sat_int24(Q_SHIFT_RND(chirp_iir_ref_2ch[buffer_verify_data.idx++], 31, 23));
delta = ref - out;
if (delta > ERROR_TOLERANCE_S24 || delta < -ERROR_TOLERANCE_S24)
assert_int_equal(out, ref);
}
if (frames > 0)
comp_update_buffer_consume(sb, frames * audio_stream_frame_bytes(ss));
}
#endif /* CONFIG_FORMAT_S24LE */
#if CONFIG_FORMAT_S32LE
static void fill_source_s32(struct test_data *td, int frames_max)
{
struct comp_dev *dev = td->dev;
struct comp_buffer *sb;
struct audio_stream *ss;
int32_t *x;
int bytes_total;
int samples;
int frames;
int i;
int samples_processed = 0;
sb = list_first_item(&dev->bsource_list, struct comp_buffer, sink_list);
ss = &sb->stream;
frames = MIN(audio_stream_get_free_frames(ss), frames_max);
samples = frames * ss->channels;
for (i = 0; i < samples; i++) {
x = audio_stream_write_frag_s32(ss, i);
*x = chirp_2ch[buffer_fill_data.idx++];
samples_processed++;
if (buffer_fill_data.idx == CHIRP_2CH_LENGTH) {
td->continue_loop = false;
break;
}
}
if (samples_processed > 0) {
bytes_total = samples_processed * audio_stream_sample_bytes(ss);
comp_update_buffer_produce(sb, bytes_total);
}
}
static void verify_sink_s32(struct test_data *td)
{
struct comp_dev *dev = td->dev;
struct comp_buffer *sb;
struct audio_stream *ss;
int64_t delta;
int32_t ref;
int32_t out;
int32_t *x;
int samples;
int frames;
int i;
sb = list_first_item(&dev->bsink_list, struct comp_buffer, source_list);
ss = &sb->stream;
frames = audio_stream_get_avail_frames(ss);
samples = frames * ss->channels;
for (i = 0; i < samples; i++) {
x = audio_stream_read_frag_s32(ss, i);
out = *x;
ref = chirp_iir_ref_2ch[buffer_verify_data.idx++];
delta = (int64_t)ref - (int64_t)out;
if (delta > ERROR_TOLERANCE_S32 || delta < -ERROR_TOLERANCE_S32)
assert_int_equal(out, ref);
}
if (frames > 0)
comp_update_buffer_consume(sb, frames * audio_stream_frame_bytes(ss));
}
#endif /* CONFIG_FORMAT_S32LE */
static int frames_jitter(int frames)
{
int r = rand();
if (r > THR_RAND_PLUS_ONE)
return frames + 1;
else if (r < THR_RAND_MINUS_ONE)
return frames - 1;
else
return frames;
}
static void test_audio_eq_iir(void **state)
{
struct test_data *td = *state;
struct comp_buffer *source = td->source;
struct comp_buffer *sink = td->sink;
int ret;
int frames;
while (td->continue_loop) {
frames = frames_jitter(td->params->frames);
switch (source->stream.frame_fmt) {
case SOF_IPC_FRAME_S16_LE:
fill_source_s16(td, frames);
break;
case SOF_IPC_FRAME_S24_4LE:
fill_source_s24(td, frames);
break;
case SOF_IPC_FRAME_S32_LE:
fill_source_s32(td, frames);
break;
case SOF_IPC_FRAME_S24_3LE:
break;
default:
assert(0);
break;
}
ret = comp_copy(td->dev);
assert_int_equal(ret, 0);
switch (sink->stream.frame_fmt) {
case SOF_IPC_FRAME_S16_LE:
verify_sink_s16(td);
break;
case SOF_IPC_FRAME_S24_4LE:
verify_sink_s24(td);
break;
case SOF_IPC_FRAME_S32_LE:
verify_sink_s32(td);
break;
default:
assert(0);
break;
}
}
}
static struct test_parameters parameters[] = {
#if CONFIG_FORMAT_S16LE
{ 2, 48, 2, SOF_IPC_FRAME_S16_LE, SOF_IPC_FRAME_S16_LE },
#endif /* CONFIG_FORMAT_S16LE */
#if CONFIG_FORMAT_S24LE
{ 2, 48, 2, SOF_IPC_FRAME_S24_4LE, SOF_IPC_FRAME_S24_4LE },
#endif /* CONFIG_FORMAT_S24LE */
#if CONFIG_FORMAT_S32LE
{ 2, 48, 2, SOF_IPC_FRAME_S32_LE, SOF_IPC_FRAME_S32_LE },
#endif /* CONFIG_FORMAT_S32LE */
#if CONFIG_FORMAT_S32LE && CONFIG_FORMAT_S16LE
{ 2, 48, 2, SOF_IPC_FRAME_S32_LE, SOF_IPC_FRAME_S16_LE },
#endif /* CONFIG_FORMAT_S32LE && CONFIG_FORMAT_S16LE */
#if CONFIG_FORMAT_S32LE && CONFIG_FORMAT_S24LE
{ 2, 48, 2, SOF_IPC_FRAME_S32_LE, SOF_IPC_FRAME_S24_4LE },
#endif /* CONFIG_FORMAT_S32LE && CONFIG_FORMAT_S24LE */
};
int main(void)
{
int i;
struct CMUnitTest tests[ARRAY_SIZE(parameters)];
for (i = 0; i < ARRAY_SIZE(parameters); i++) {
tests[i].name = "test_audio_eq_iir";
tests[i].test_func = test_audio_eq_iir;
tests[i].setup_func = setup;
tests[i].teardown_func = teardown;
tests[i].initial_state = ¶meters[i];
}
cmocka_set_message_output(CM_OUTPUT_TAP);
return cmocka_run_group_tests(tests, setup_group, NULL);
}
| 25.18543 | 93 | 0.72285 | [
"vector"
] |
082c74896faf7b76cd41bb09184a13e9ad119780 | 25,022 | h | C | driverlib/inc/hw_aes.h | HectorTa1989/SMART-GREENHOUSE-MONITORING-CONTROL-SYSTEM | f64be2272fb990e5b63d53ed9c58d5bbfcdd28b0 | [
"MIT"
] | null | null | null | driverlib/inc/hw_aes.h | HectorTa1989/SMART-GREENHOUSE-MONITORING-CONTROL-SYSTEM | f64be2272fb990e5b63d53ed9c58d5bbfcdd28b0 | [
"MIT"
] | null | null | null | driverlib/inc/hw_aes.h | HectorTa1989/SMART-GREENHOUSE-MONITORING-CONTROL-SYSTEM | f64be2272fb990e5b63d53ed9c58d5bbfcdd28b0 | [
"MIT"
] | null | null | null | //*****************************************************************************
//
// hw_aes.h - Macros used when accessing the AES hardware.
//
// Copyright (c) 2012-2014 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// Neither the name of Texas Instruments Incorporated nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// This is part of revision 2.1.0.12573 of the Tiva Firmware Development Package.
//
//*****************************************************************************
#ifndef __HW_AES_H__
#define __HW_AES_H__
//*****************************************************************************
//
// The following are defines for the AES register offsets.
//
//*****************************************************************************
#define AES_O_KEY2_6 0x00000000 // AES Key 2_6
#define AES_O_KEY2_7 0x00000004 // AES Key 2_7
#define AES_O_KEY2_4 0x00000008 // AES Key 2_4
#define AES_O_KEY2_5 0x0000000C // AES Key 2_5
#define AES_O_KEY2_2 0x00000010 // AES Key 2_2
#define AES_O_KEY2_3 0x00000014 // AES Key 2_3
#define AES_O_KEY2_0 0x00000018 // AES Key 2_0
#define AES_O_KEY2_1 0x0000001C // AES Key 2_1
#define AES_O_KEY1_6 0x00000020 // AES Key 1_6
#define AES_O_KEY1_7 0x00000024 // AES Key 1_7
#define AES_O_KEY1_4 0x00000028 // AES Key 1_4
#define AES_O_KEY1_5 0x0000002C // AES Key 1_5
#define AES_O_KEY1_2 0x00000030 // AES Key 1_2
#define AES_O_KEY1_3 0x00000034 // AES Key 1_3
#define AES_O_KEY1_0 0x00000038 // AES Key 1_0
#define AES_O_KEY1_1 0x0000003C // AES Key 1_1
#define AES_O_IV_IN_0 0x00000040 // AES Initialization Vector Input
// 0
#define AES_O_IV_IN_1 0x00000044 // AES Initialization Vector Input
// 1
#define AES_O_IV_IN_2 0x00000048 // AES Initialization Vector Input
// 2
#define AES_O_IV_IN_3 0x0000004C // AES Initialization Vector Input
// 3
#define AES_O_CTRL 0x00000050 // AES Control
#define AES_O_C_LENGTH_0 0x00000054 // AES Crypto Data Length 0
#define AES_O_C_LENGTH_1 0x00000058 // AES Crypto Data Length 1
#define AES_O_AUTH_LENGTH 0x0000005C // AES Authentication Data Length
#define AES_O_DATA_IN_0 0x00000060 // AES Data RW Plaintext/Ciphertext
// 0
#define AES_O_DATA_IN_1 0x00000064 // AES Data RW Plaintext/Ciphertext
// 1
#define AES_O_DATA_IN_2 0x00000068 // AES Data RW Plaintext/Ciphertext
// 2
#define AES_O_DATA_IN_3 0x0000006C // AES Data RW Plaintext/Ciphertext
// 3
#define AES_O_TAG_OUT_0 0x00000070 // AES Hash Tag Out 0
#define AES_O_TAG_OUT_1 0x00000074 // AES Hash Tag Out 1
#define AES_O_TAG_OUT_2 0x00000078 // AES Hash Tag Out 2
#define AES_O_TAG_OUT_3 0x0000007C // AES Hash Tag Out 3
#define AES_O_REVISION 0x00000080 // AES IP Revision Identifier
#define AES_O_SYSCONFIG 0x00000084 // AES System Configuration
#define AES_O_SYSSTATUS 0x00000088 // AES System Status
#define AES_O_IRQSTATUS 0x0000008C // AES Interrupt Status
#define AES_O_IRQENABLE 0x00000090 // AES Interrupt Enable
#define AES_O_DIRTYBITS 0x00000094 // AES Dirty Bits
#define AES_O_DMAIM 0xFFFFA020 // AES DMA Interrupt Mask
#define AES_O_DMARIS 0xFFFFA024 // AES DMA Raw Interrupt Status
#define AES_O_DMAMIS 0xFFFFA028 // AES DMA Masked Interrupt Status
#define AES_O_DMAIC 0xFFFFA02C // AES DMA Interrupt Clear
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_6 register.
//
//*****************************************************************************
#define AES_KEY2_6_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_6_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_7 register.
//
//*****************************************************************************
#define AES_KEY2_7_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_7_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_4 register.
//
//*****************************************************************************
#define AES_KEY2_4_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_4_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_5 register.
//
//*****************************************************************************
#define AES_KEY2_5_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_5_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_2 register.
//
//*****************************************************************************
#define AES_KEY2_2_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_2_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_3 register.
//
//*****************************************************************************
#define AES_KEY2_3_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_3_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_0 register.
//
//*****************************************************************************
#define AES_KEY2_0_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_0_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY2_1 register.
//
//*****************************************************************************
#define AES_KEY2_1_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY2_1_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_6 register.
//
//*****************************************************************************
#define AES_KEY1_6_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_6_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_7 register.
//
//*****************************************************************************
#define AES_KEY1_7_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_7_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_4 register.
//
//*****************************************************************************
#define AES_KEY1_4_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_4_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_5 register.
//
//*****************************************************************************
#define AES_KEY1_5_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_5_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_2 register.
//
//*****************************************************************************
#define AES_KEY1_2_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_2_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_3 register.
//
//*****************************************************************************
#define AES_KEY1_3_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_3_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_0 register.
//
//*****************************************************************************
#define AES_KEY1_0_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_0_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_KEY1_1 register.
//
//*****************************************************************************
#define AES_KEY1_1_KEY_M 0xFFFFFFFF // Key Data
#define AES_KEY1_1_KEY_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_IV_IN_0 register.
//
//*****************************************************************************
#define AES_IV_IN_0_DATA_M 0xFFFFFFFF // Initialization Vector Input
#define AES_IV_IN_0_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_IV_IN_1 register.
//
//*****************************************************************************
#define AES_IV_IN_1_DATA_M 0xFFFFFFFF // Initialization Vector Input
#define AES_IV_IN_1_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_IV_IN_2 register.
//
//*****************************************************************************
#define AES_IV_IN_2_DATA_M 0xFFFFFFFF // Initialization Vector Input
#define AES_IV_IN_2_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_IV_IN_3 register.
//
//*****************************************************************************
#define AES_IV_IN_3_DATA_M 0xFFFFFFFF // Initialization Vector Input
#define AES_IV_IN_3_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_CTRL register.
//
//*****************************************************************************
#define AES_CTRL_CTXTRDY 0x80000000 // Context Data Registers Ready
#define AES_CTRL_SVCTXTRDY 0x40000000 // AES TAG/IV Block(s) Ready
#define AES_CTRL_SAVE_CONTEXT 0x20000000 // TAG or Result IV Save
#define AES_CTRL_CCM_M_M 0x01C00000 // Counter with CBC-MAC (CCM)
#define AES_CTRL_CCM_L_M 0x00380000 // L Value
#define AES_CTRL_CCM_L_2 0x00080000 // width = 2
#define AES_CTRL_CCM_L_4 0x00180000 // width = 4
#define AES_CTRL_CCM_L_8 0x00380000 // width = 8
#define AES_CTRL_CCM 0x00040000 // AES-CCM Mode Enable
#define AES_CTRL_GCM_M 0x00030000 // AES-GCM Mode Enable
#define AES_CTRL_GCM_NOP 0x00000000 // No operation
#define AES_CTRL_GCM_HLY0ZERO 0x00010000 // GHASH with H loaded and
// Y0-encrypted forced to zero
#define AES_CTRL_GCM_HLY0CALC 0x00020000 // GHASH with H loaded and
// Y0-encrypted calculated
// internally
#define AES_CTRL_GCM_HY0CALC 0x00030000 // Autonomous GHASH (both H and
// Y0-encrypted calculated
// internally)
#define AES_CTRL_CBCMAC 0x00008000 // AES-CBC MAC Enable
#define AES_CTRL_F9 0x00004000 // AES f9 Mode Enable
#define AES_CTRL_F8 0x00002000 // AES f8 Mode Enable
#define AES_CTRL_XTS_M 0x00001800 // AES-XTS Operation Enabled
#define AES_CTRL_XTS_NOP 0x00000000 // No operation
#define AES_CTRL_XTS_TWEAKJL 0x00000800 // Previous/intermediate tweak
// value and j loaded (value is
// loaded via IV, j is loaded via
// the AAD length register)
#define AES_CTRL_XTS_K2IJL 0x00001000 // Key2, n and j are loaded (n is
// loaded via IV, j is loaded via
// the AAD length register)
#define AES_CTRL_XTS_K2ILJ0 0x00001800 // Key2 and n are loaded; j=0 (n is
// loaded via IV)
#define AES_CTRL_CFB 0x00000400 // Full block AES cipher feedback
// mode (CFB128) Enable
#define AES_CTRL_ICM 0x00000200 // AES Integer Counter Mode (ICM)
// Enable
#define AES_CTRL_CTR_WIDTH_M 0x00000180 // AES-CTR Mode Counter Width
#define AES_CTRL_CTR_WIDTH_32 0x00000000 // Counter is 32 bits
#define AES_CTRL_CTR_WIDTH_64 0x00000080 // Counter is 64 bits
#define AES_CTRL_CTR_WIDTH_96 0x00000100 // Counter is 96 bits
#define AES_CTRL_CTR_WIDTH_128 0x00000180 // Counter is 128 bits
#define AES_CTRL_CTR 0x00000040 // Counter Mode
#define AES_CTRL_MODE 0x00000020 // ECB/CBC Mode
#define AES_CTRL_KEY_SIZE_M 0x00000018 // Key Size
#define AES_CTRL_KEY_SIZE_128 0x00000008 // Key is 128 bits
#define AES_CTRL_KEY_SIZE_192 0x00000010 // Key is 192 bits
#define AES_CTRL_KEY_SIZE_256 0x00000018 // Key is 256 bits
#define AES_CTRL_DIRECTION 0x00000004 // Encryption/Decryption Selection
#define AES_CTRL_INPUT_READY 0x00000002 // Input Ready Status
#define AES_CTRL_OUTPUT_READY 0x00000001 // Output Ready Status
#define AES_CTRL_CCM_M_S 22
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_C_LENGTH_0
// register.
//
//*****************************************************************************
#define AES_C_LENGTH_0_LENGTH_M 0xFFFFFFFF // Data Length
#define AES_C_LENGTH_0_LENGTH_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_C_LENGTH_1
// register.
//
//*****************************************************************************
#define AES_C_LENGTH_1_LENGTH_M 0xFFFFFFFF // Data Length
#define AES_C_LENGTH_1_LENGTH_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_AUTH_LENGTH
// register.
//
//*****************************************************************************
#define AES_AUTH_LENGTH_AUTH_M 0xFFFFFFFF // Authentication Data Length
#define AES_AUTH_LENGTH_AUTH_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DATA_IN_0
// register.
//
//*****************************************************************************
#define AES_DATA_IN_0_DATA_M 0xFFFFFFFF // Secure Data RW
// Plaintext/Ciphertext
#define AES_DATA_IN_0_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DATA_IN_1
// register.
//
//*****************************************************************************
#define AES_DATA_IN_1_DATA_M 0xFFFFFFFF // Secure Data RW
// Plaintext/Ciphertext
#define AES_DATA_IN_1_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DATA_IN_2
// register.
//
//*****************************************************************************
#define AES_DATA_IN_2_DATA_M 0xFFFFFFFF // Secure Data RW
// Plaintext/Ciphertext
#define AES_DATA_IN_2_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DATA_IN_3
// register.
//
//*****************************************************************************
#define AES_DATA_IN_3_DATA_M 0xFFFFFFFF // Secure Data RW
// Plaintext/Ciphertext
#define AES_DATA_IN_3_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_TAG_OUT_0
// register.
//
//*****************************************************************************
#define AES_TAG_OUT_0_HASH_M 0xFFFFFFFF // Hash Result
#define AES_TAG_OUT_0_HASH_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_TAG_OUT_1
// register.
//
//*****************************************************************************
#define AES_TAG_OUT_1_HASH_M 0xFFFFFFFF // Hash Result
#define AES_TAG_OUT_1_HASH_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_TAG_OUT_2
// register.
//
//*****************************************************************************
#define AES_TAG_OUT_2_HASH_M 0xFFFFFFFF // Hash Result
#define AES_TAG_OUT_2_HASH_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_TAG_OUT_3
// register.
//
//*****************************************************************************
#define AES_TAG_OUT_3_HASH_M 0xFFFFFFFF // Hash Result
#define AES_TAG_OUT_3_HASH_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_REVISION register.
//
//*****************************************************************************
#define AES_REVISION_M 0xFFFFFFFF // Revision number
#define AES_REVISION_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_SYSCONFIG
// register.
//
//*****************************************************************************
#define AES_SYSCONFIG_K3 0x00001000 // K3 Select
#define AES_SYSCONFIG_KEYENC 0x00000800 // Key Encoding
#define AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUT \
0x00000200 // Map Context Out on Data Out
// Enable
#define AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_EN \
0x00000100 // DMA Request Context Out Enable
#define AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_EN \
0x00000080 // DMA Request Context In Enable
#define AES_SYSCONFIG_DMA_REQ_DATA_OUT_EN \
0x00000040 // DMA Request Data Out Enable
#define AES_SYSCONFIG_DMA_REQ_DATA_IN_EN \
0x00000020 // DMA Request Data In Enable
#define AES_SYSCONFIG_SOFTRESET 0x00000002 // Soft reset
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_SYSSTATUS
// register.
//
//*****************************************************************************
#define AES_SYSSTATUS_RESETDONE 0x00000001 // Reset Done
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_IRQSTATUS
// register.
//
//*****************************************************************************
#define AES_IRQSTATUS_CONTEXT_OUT \
0x00000008 // Context Output Interrupt Status
#define AES_IRQSTATUS_DATA_OUT 0x00000004 // Data Out Interrupt Status
#define AES_IRQSTATUS_DATA_IN 0x00000002 // Data In Interrupt Status
#define AES_IRQSTATUS_CONTEXT_IN \
0x00000001 // Context In Interrupt Status
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_IRQENABLE
// register.
//
//*****************************************************************************
#define AES_IRQENABLE_CONTEXT_OUT \
0x00000008 // Context Out Interrupt Enable
#define AES_IRQENABLE_DATA_OUT 0x00000004 // Data Out Interrupt Enable
#define AES_IRQENABLE_DATA_IN 0x00000002 // Data In Interrupt Enable
#define AES_IRQENABLE_CONTEXT_IN \
0x00000001 // Context In Interrupt Enable
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DIRTYBITS
// register.
//
//*****************************************************************************
#define AES_DIRTYBITS_S_DIRTY 0x00000002 // AES Dirty Bit
#define AES_DIRTYBITS_S_ACCESS 0x00000001 // AES Access Bit
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DMAIM register.
//
//*****************************************************************************
#define AES_DMAIM_DOUT 0x00000008 // Data Out DMA Done Interrupt Mask
#define AES_DMAIM_DIN 0x00000004 // Data In DMA Done Interrupt Mask
#define AES_DMAIM_COUT 0x00000002 // Context Out DMA Done Interrupt
// Mask
#define AES_DMAIM_CIN 0x00000001 // Context In DMA Done Interrupt
// Mask
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DMARIS register.
//
//*****************************************************************************
#define AES_DMARIS_DOUT 0x00000008 // Data Out DMA Done Raw Interrupt
// Status
#define AES_DMARIS_DIN 0x00000004 // Data In DMA Done Raw Interrupt
// Status
#define AES_DMARIS_COUT 0x00000002 // Context Out DMA Done Raw
// Interrupt Status
#define AES_DMARIS_CIN 0x00000001 // Context In DMA Done Raw
// Interrupt Status
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DMAMIS register.
//
//*****************************************************************************
#define AES_DMAMIS_DOUT 0x00000008 // Data Out DMA Done Masked
// Interrupt Status
#define AES_DMAMIS_DIN 0x00000004 // Data In DMA Done Masked
// Interrupt Status
#define AES_DMAMIS_COUT 0x00000002 // Context Out DMA Done Masked
// Interrupt Status
#define AES_DMAMIS_CIN 0x00000001 // Context In DMA Done Raw
// Interrupt Status
//*****************************************************************************
//
// The following are defines for the bit fields in the AES_O_DMAIC register.
//
//*****************************************************************************
#define AES_DMAIC_DOUT 0x00000008 // Data Out DMA Done Interrupt
// Clear
#define AES_DMAIC_DIN 0x00000004 // Data In DMA Done Interrupt Clear
#define AES_DMAIC_COUT 0x00000002 // Context Out DMA Done Masked
// Interrupt Status
#define AES_DMAIC_CIN 0x00000001 // Context In DMA Done Raw
// Interrupt Status
#endif // __HW_AES_H__
| 45.827839 | 81 | 0.505835 | [
"vector"
] |
0832b8180e9a6aac4f79529291c508e695aede59 | 6,892 | h | C | code/components/gta-streaming-five/include/Streaming.h | AmirLynx/fivem | fc7621cf5e5cec52772c970d4665cfc3993b0f1d | [
"MIT"
] | 1 | 2021-05-08T14:44:28.000Z | 2021-05-08T14:44:28.000Z | code/components/gta-streaming-five/include/Streaming.h | AmirLynx/fivem | fc7621cf5e5cec52772c970d4665cfc3993b0f1d | [
"MIT"
] | 5 | 2021-08-31T21:09:22.000Z | 2022-03-24T03:51:14.000Z | code/components/gta-streaming-five/include/Streaming.h | AmirLynx/fivem | fc7621cf5e5cec52772c970d4665cfc3993b0f1d | [
"MIT"
] | 1 | 2020-12-03T11:17:16.000Z | 2020-12-03T11:17:16.000Z | #pragma once
#include <atArray.h>
#ifdef COMPILING_GTA_STREAMING_FIVE
#define STREAMING_EXPORT DLL_EXPORT
#else
#define STREAMING_EXPORT DLL_IMPORT
#endif
#include <fiCollectionWrapper.h>
struct StreamingPackfileEntry
{
FILETIME modificationTime; // +0
uint8_t pad0[8]; // +8
uint32_t nameHash; // +16
uint8_t pad[20]; // +20
uint64_t packfileParentHandle; // +40
uint64_t pad1; // +48
#ifdef GTA_FIVE
rage::fiPackfile* packfile; // +56
#elif IS_RDR3
void* packfile; // +56
#endif
uint8_t pad2[2]; // +64
uint8_t loadedFlag; // +66
uint8_t pad3; // +67
uint8_t enabled; // +68
uint8_t pad4; // +69
uint8_t isDLC; // +70
uint8_t isUnk; // +71
uint8_t cacheFlags; // +72
uint8_t pad5[15]; // +73
uint32_t parentIdentifier; // +88
uint32_t pad6; // +92
uint8_t isHdd; // +96
uint8_t isHdd_2; // +97
uint16_t pad7; // +98
uint32_t pad8; // +100
#ifdef IS_RDR3
char pad9[40];
#endif
};
struct StreamingDataEntry
{
uint32_t handle;
uint32_t flags;
size_t STREAMING_EXPORT ComputePhysicalSize(uint32_t strIndex);
size_t STREAMING_EXPORT ComputeVirtualSize(uint32_t strIndex, void* a3, bool a4);
};
namespace streaming
{
struct StreamingListEntry
{
StreamingListEntry* Prev;
StreamingListEntry* Next;
uint32_t Index;
};
// in reality a blockmap, but at least fwAssetRscStore only uses the first block reference pointer
struct strAssetReference
{
void* unknown;
void* asset;
};
class strStreamingModule
{
public:
virtual ~strStreamingModule() = 0;
#ifdef IS_RDR3
virtual void m_8() = 0;
virtual void m_10() = 0;
//
// Creates a new asset for `name`, or returns the existing index in this module for it.
//
virtual uint32_t* FindSlotFromHashKey(uint32_t* id, uint32_t name) = 0;
#elif GTA_FIVE
//
// Creates a new asset for `name`, or returns the existing index in this module for it.
//
virtual uint32_t* FindSlotFromHashKey(uint32_t* id, const char* name) = 0;
#endif
//
// Returns the index in this streaming module for the asset specified by `name`.
//
virtual uint32_t* FindSlot(uint32_t* id, const char* name) = 0;
//
// Unloads the specified asset from the streaming module.
// This won't update the asset state in CStreaming, use these functions instead.
//
virtual void Remove(uint32_t id) = 0;
//
// Removes the specified asset from the streaming module.
//
virtual void RemoveSlot(uint32_t object) = 0;
//
// Loads an asset from an in-memory RSC file.
//
virtual bool Load(uint32_t object, const void* buffer, uint32_t length) = 0;
//
// Loads an asset from a block map.
//
virtual void PlaceResource(uint32_t object, void* blockMap, const char* name) = 0;
//
// Sets the asset pointer directly.
//
virtual void SetResource(uint32_t object, strAssetReference& reference) = 0;
//
// Gets the asset pointer for a loaded asset.
// Returns NULL if not loaded.
//
virtual void* GetPtr(uint32_t object) = 0;
virtual void* GetDataPtr(uint32_t object) = 0;
virtual void* Defragment(uint32_t object, void* blockMap, const char* name) = 0;
// nullsub
virtual void m_58() = 0;
// nullsub
virtual void m_60() = 0;
// only overridden in specific modules
virtual void* GetResource(uint32_t object) = 0;
// nullsub
virtual void m_70() = 0;
// unknown function, involving releasing
virtual void m_78(uint32_t object, int) = 0;
virtual void AddRef(uint32_t id) = 0;
virtual void RemoveRef(uint32_t id) = 0;
virtual void ResetAllRefs() = 0; // resetrefcount
virtual int GetNumRefs(uint32_t id) = 0;
//
// Formats the reference count as a string.
//
virtual const char* GetRefCountString(uint32_t id, char* buffer, size_t length) = 0;
virtual int GetDependencies(uint32_t object, uint32_t* outDependencies, size_t count) = 0;
// nullsub?
virtual void m_B0() = 0;
virtual void m_B8() = 0;
virtual void m_C0() = 0;
// ...
uint32_t baseIdx;
};
class STREAMING_EXPORT strStreamingModuleMgr
{
public:
virtual ~strStreamingModuleMgr() = default;
strStreamingModule* GetStreamingModule(int index);
strStreamingModule* GetStreamingModule(const char* extension);
};
// actually CStreaming
class STREAMING_EXPORT Manager
{
private:
inline Manager() {}
public:
void RequestObject(uint32_t objectId, int flags);
bool ReleaseObject(uint32_t objectId);
bool ReleaseObject(uint32_t objectId, int flags);
bool IsObjectReadyToDelete(uint32_t streamingIndex, int flags);
void FindAllDependents(atArray<uint32_t>& outIndices, uint32_t objectId);
template<typename TPred>
void FindAllDependentsCustomPred(atArray<uint32_t>& outIndices, uint32_t objectId, TPred&& pred)
{
for (size_t i = 0; i < numEntries; i++)
{
if (pred(Entries[i]))
{
FindDependentsInner(i, outIndices, objectId);
}
}
}
static Manager* GetInstance();
private:
void FindDependentsInner(uint32_t selfId, atArray<uint32_t>& outIndices, uint32_t objectId);
public:
StreamingDataEntry* Entries;
char pad3[16];
int numEntries;
int f;
char pad[88 - 16 - 8];
StreamingListEntry* RequestListHead;
StreamingListEntry* RequestListTail;
#ifndef IS_RDR3
char pad2[368 - 40];
#endif
strStreamingModuleMgr moduleMgr;
char pad4[32];
int NumPendingRequests;
int NumPendingRequests3;
int NumPendingRequestsPrio;
};
void STREAMING_EXPORT LoadObjectsNow(bool a1);
uint32_t STREAMING_EXPORT GetStreamingIndexForName(const std::string& name);
STREAMING_EXPORT const std::string& GetStreamingNameForIndex(uint32_t index);
STREAMING_EXPORT const std::string& GetStreamingBaseNameForHash(uint32_t hash);
STREAMING_EXPORT StreamingPackfileEntry* GetStreamingPackfileByIndex(int index);
STREAMING_EXPORT uint32_t RegisterRawStreamingFile(uint32_t* fileId, const char* fileName, bool unkTrue, const char* registerAs, bool errorIfFailed);
STREAMING_EXPORT StreamingPackfileEntry* GetStreamingPackfileForEntry(StreamingDataEntry* entry);
// are we trying to shut down?
STREAMING_EXPORT bool IsStreamerShuttingDown();
atArray<StreamingPackfileEntry>& GetStreamingPackfileArray();
}
namespace rage
{
class strStreamingAllocator : public sysMemAllocator
{
public:
static STREAMING_EXPORT strStreamingAllocator* GetInstance();
};
}
#if 0
namespace rage
{
class strStreamingModule
{
};
class STREAMING_EXPORT strStreamingModuleMgr
{
private:
inline strStreamingModuleMgr() {}
public:
strStreamingModule* GetModuleFromExtension(const char* extension);
static strStreamingModuleMgr* GetInstance();
};
}
#endif
| 23.847751 | 150 | 0.693558 | [
"object"
] |
08332dd9feb6364676ac4b802081f5bd49a22025 | 48,603 | h | C | blocks/QuickTime/include/msw/CMICCProfile.h | rsh/Cinder-Emscripten | 4a08250c56656865c7c3a52fb9380980908b1439 | [
"BSD-2-Clause"
] | 24 | 2015-12-07T23:03:27.000Z | 2021-04-03T14:55:54.000Z | blocks/QuickTime/include/msw/CMICCProfile.h | rsh/Cinder-Emscripten | 4a08250c56656865c7c3a52fb9380980908b1439 | [
"BSD-2-Clause"
] | 8 | 2020-01-05T23:38:51.000Z | 2020-02-23T22:18:18.000Z | blocks/QuickTime/include/msw/CMICCProfile.h | rsh/Cinder-Emscripten | 4a08250c56656865c7c3a52fb9380980908b1439 | [
"BSD-2-Clause"
] | 6 | 2015-12-17T18:26:57.000Z | 2018-11-22T00:11:55.000Z | /*
File: CMICCProfile.h
Contains: ICC Profile Format Definitions
Version: QuickTime 7.3
Copyright: (c) 2007 (c) 1994-2001 by Apple Computer, Inc., all rights reserved.
Bugs?: For bug reports, consult the following page on
the World Wide Web:
http://developer.apple.com/bugreporter/
*/
#ifndef __CMICCPROFILE__
#define __CMICCPROFILE__
#ifndef __MACTYPES__
#include <MacTypes.h>
#endif
#if PRAGMA_ONCE
#pragma once
#endif
#if PRAGMA_IMPORT
#pragma import on
#endif
#if PRAGMA_STRUCT_ALIGN
#pragma options align=mac68k
#elif PRAGMA_STRUCT_PACKPUSH
#pragma pack(push, 2)
#elif PRAGMA_STRUCT_PACK
#pragma pack(2)
#endif
/* ICC Profile version constants */
enum {
cmICCProfileVersion4 = 0x04000000,
cmICCProfileVersion2 = 0x02000000,
cmICCProfileVersion21 = 0x02100000,
cmCS2ProfileVersion = cmICCProfileVersion2,
cmCS1ProfileVersion = 0x00000100 /* ColorSync 1.0 profile version */
};
/* Current Major version number */
enum {
cmProfileMajorVersionMask = (long)0xFF000000,
cmCurrentProfileMajorVersion = 0x02000000
};
/* magic cookie number for anonymous file ID */
enum {
cmMagicNumber = FOUR_CHAR_CODE('acsp')
};
/************************************************************************/
/*************** ColorSync 2.0 profile specification ********************/
/************************************************************************/
/**** flags field ****/
enum {
cmICCReservedFlagsMask = 0x0000FFFF, /* these bits of the flags field are defined and reserved by ICC */
cmEmbeddedMask = 0x00000001, /* if bit 0 is 0 then not embedded profile, if 1 then embedded profile */
cmEmbeddedUseMask = 0x00000002, /* if bit 1 is 0 then ok to use anywhere, if 1 then ok to use as embedded profile only */
cmCMSReservedFlagsMask = (long)0xFFFF0000, /* these bits of the flags field are defined and reserved by CMS vendor */
cmQualityMask = 0x00030000, /* if bits 16-17 is 0 then normal, if 1 then draft, if 2 then best */
cmInterpolationMask = 0x00040000, /* if bit 18 is 0 then interpolation, if 1 then lookup only */
cmGamutCheckingMask = 0x00080000 /* if bit 19 is 0 then create gamut checking info, if 1 then no gamut checking info */
};
/* copyright-protection flag options */
enum {
cmEmbeddedProfile = 0, /* 0 is not embedded profile, 1 is embedded profile */
cmEmbeddedUse = 1 /* 0 is to use anywhere, 1 is to use as embedded profile only */
};
/* speed and quality flag options */
enum {
cmNormalMode = 0, /* it uses the least significent two bits in the high word of flag */
cmDraftMode = 1, /* it should be evaulated like this: right shift 16 bits first, mask off the */
cmBestMode = 2 /* high 14 bits, and then compare with the enum to determine the option value */
};
/**** deviceAttributes fields ****/
/* deviceAttributes[0] is defined by and reserved for device vendors */
/* deviceAttributes[1] is defined by and reserved for ICC */
/* The following bits of deviceAttributes[1] are currently defined */
enum {
cmReflectiveTransparentMask = 0x00000001, /* if bit 0 is 0 then reflective media, if 1 then transparency media */
cmGlossyMatteMask = 0x00000002 /* if bit 1 is 0 then glossy, if 1 then matte */
};
/* device/media attributes element values */
enum {
cmReflective = 0, /* if bit 0 is 0 then reflective media, if 1 then transparency media */
cmGlossy = 1 /* if bit 1 is 0 then glossy, if 1 then matte */
};
/**** renderingIntent field ****/
enum {
cmPerceptual = 0, /* Photographic images */
cmRelativeColorimetric = 1, /* Logo Colors */
cmSaturation = 2, /* Business graphics */
cmAbsoluteColorimetric = 3 /* Logo Colors */
};
/* data type element values */
enum {
cmAsciiData = 0,
cmBinaryData = 1
};
/* screen encodings */
enum {
cmPrtrDefaultScreens = 0, /* Use printer default screens. 0 is false, 1 is ture */
cmLinesPer = 1 /* 0 is LinesPerCm, 1 is LinesPerInch */
};
/* 2.0 tag type information */
enum {
cmNumHeaderElements = 10
};
/* public tags */
enum {
cmAToB0Tag = FOUR_CHAR_CODE('A2B0'),
cmAToB1Tag = FOUR_CHAR_CODE('A2B1'),
cmAToB2Tag = FOUR_CHAR_CODE('A2B2'),
cmBlueColorantTag = FOUR_CHAR_CODE('bXYZ'),
cmBlueTRCTag = FOUR_CHAR_CODE('bTRC'),
cmBToA0Tag = FOUR_CHAR_CODE('B2A0'),
cmBToA1Tag = FOUR_CHAR_CODE('B2A1'),
cmBToA2Tag = FOUR_CHAR_CODE('B2A2'),
cmCalibrationDateTimeTag = FOUR_CHAR_CODE('calt'),
cmChromaticAdaptationTag = FOUR_CHAR_CODE('chad'),
cmCharTargetTag = FOUR_CHAR_CODE('targ'),
cmCopyrightTag = FOUR_CHAR_CODE('cprt'),
cmDeviceMfgDescTag = FOUR_CHAR_CODE('dmnd'),
cmDeviceModelDescTag = FOUR_CHAR_CODE('dmdd'),
cmGamutTag = FOUR_CHAR_CODE('gamt'),
cmGrayTRCTag = FOUR_CHAR_CODE('kTRC'),
cmGreenColorantTag = FOUR_CHAR_CODE('gXYZ'),
cmGreenTRCTag = FOUR_CHAR_CODE('gTRC'),
cmLuminanceTag = FOUR_CHAR_CODE('lumi'),
cmMeasurementTag = FOUR_CHAR_CODE('meas'),
cmMediaBlackPointTag = FOUR_CHAR_CODE('bkpt'),
cmMediaWhitePointTag = FOUR_CHAR_CODE('wtpt'),
cmNamedColorTag = FOUR_CHAR_CODE('ncol'),
cmNamedColor2Tag = FOUR_CHAR_CODE('ncl2'),
cmPreview0Tag = FOUR_CHAR_CODE('pre0'),
cmPreview1Tag = FOUR_CHAR_CODE('pre1'),
cmPreview2Tag = FOUR_CHAR_CODE('pre2'),
cmProfileDescriptionTag = FOUR_CHAR_CODE('desc'),
cmProfileSequenceDescTag = FOUR_CHAR_CODE('pseq'),
cmPS2CRD0Tag = FOUR_CHAR_CODE('psd0'),
cmPS2CRD1Tag = FOUR_CHAR_CODE('psd1'),
cmPS2CRD2Tag = FOUR_CHAR_CODE('psd2'),
cmPS2CRD3Tag = FOUR_CHAR_CODE('psd3'),
cmPS2CSATag = FOUR_CHAR_CODE('ps2s'),
cmPS2RenderingIntentTag = FOUR_CHAR_CODE('ps2i'),
cmRedColorantTag = FOUR_CHAR_CODE('rXYZ'),
cmRedTRCTag = FOUR_CHAR_CODE('rTRC'),
cmScreeningDescTag = FOUR_CHAR_CODE('scrd'),
cmScreeningTag = FOUR_CHAR_CODE('scrn'),
cmTechnologyTag = FOUR_CHAR_CODE('tech'),
cmUcrBgTag = FOUR_CHAR_CODE('bfd '),
cmViewingConditionsDescTag = FOUR_CHAR_CODE('vued'),
cmViewingConditionsTag = FOUR_CHAR_CODE('view')
};
/* custom tags */
enum {
cmPS2CRDVMSizeTag = FOUR_CHAR_CODE('psvm'),
cmVideoCardGammaTag = FOUR_CHAR_CODE('vcgt'),
cmMakeAndModelTag = FOUR_CHAR_CODE('mmod'),
cmProfileDescriptionMLTag = FOUR_CHAR_CODE('dscm'),
cmNativeDisplayInfoTag = FOUR_CHAR_CODE('ndin')
};
/* public type signatures */
enum {
cmSigCrdInfoType = FOUR_CHAR_CODE('crdi'),
cmSigCurveType = FOUR_CHAR_CODE('curv'),
cmSigDataType = FOUR_CHAR_CODE('data'),
cmSigDateTimeType = FOUR_CHAR_CODE('dtim'),
cmSigLut16Type = FOUR_CHAR_CODE('mft2'),
cmSigLut8Type = FOUR_CHAR_CODE('mft1'),
cmSigMeasurementType = FOUR_CHAR_CODE('meas'),
cmSigMultiFunctA2BType = FOUR_CHAR_CODE('mAB '),
cmSigMultiFunctB2AType = FOUR_CHAR_CODE('mBA '),
cmSigNamedColorType = FOUR_CHAR_CODE('ncol'),
cmSigNamedColor2Type = FOUR_CHAR_CODE('ncl2'),
cmSigParametricCurveType = FOUR_CHAR_CODE('para'),
cmSigProfileDescriptionType = FOUR_CHAR_CODE('desc'),
cmSigProfileSequenceDescType = FOUR_CHAR_CODE('pseq'),
cmSigScreeningType = FOUR_CHAR_CODE('scrn'),
cmSigS15Fixed16Type = FOUR_CHAR_CODE('sf32'),
cmSigSignatureType = FOUR_CHAR_CODE('sig '),
cmSigTextType = FOUR_CHAR_CODE('text'),
cmSigU16Fixed16Type = FOUR_CHAR_CODE('uf32'),
cmSigU1Fixed15Type = FOUR_CHAR_CODE('uf16'),
cmSigUInt8Type = FOUR_CHAR_CODE('ui08'),
cmSigUInt16Type = FOUR_CHAR_CODE('ui16'),
cmSigUInt32Type = FOUR_CHAR_CODE('ui32'),
cmSigUInt64Type = FOUR_CHAR_CODE('ui64'),
cmSigUcrBgType = FOUR_CHAR_CODE('bfd '),
cmSigUnicodeTextType = FOUR_CHAR_CODE('utxt'),
cmSigViewingConditionsType = FOUR_CHAR_CODE('view'),
cmSigXYZType = FOUR_CHAR_CODE('XYZ ')
};
/* custom type signatures */
enum {
cmSigPS2CRDVMSizeType = FOUR_CHAR_CODE('psvm'),
cmSigVideoCardGammaType = FOUR_CHAR_CODE('vcgt'),
cmSigMakeAndModelType = FOUR_CHAR_CODE('mmod'),
cmSigNativeDisplayInfoType = FOUR_CHAR_CODE('ndin'),
cmSigMultiLocalizedUniCodeType = FOUR_CHAR_CODE('mluc')
};
/* technology tag descriptions */
enum {
cmTechnologyDigitalCamera = FOUR_CHAR_CODE('dcam'),
cmTechnologyFilmScanner = FOUR_CHAR_CODE('fscn'),
cmTechnologyReflectiveScanner = FOUR_CHAR_CODE('rscn'),
cmTechnologyInkJetPrinter = FOUR_CHAR_CODE('ijet'),
cmTechnologyThermalWaxPrinter = FOUR_CHAR_CODE('twax'),
cmTechnologyElectrophotographicPrinter = FOUR_CHAR_CODE('epho'),
cmTechnologyElectrostaticPrinter = FOUR_CHAR_CODE('esta'),
cmTechnologyDyeSublimationPrinter = FOUR_CHAR_CODE('dsub'),
cmTechnologyPhotographicPaperPrinter = FOUR_CHAR_CODE('rpho'),
cmTechnologyFilmWriter = FOUR_CHAR_CODE('fprn'),
cmTechnologyVideoMonitor = FOUR_CHAR_CODE('vidm'),
cmTechnologyVideoCamera = FOUR_CHAR_CODE('vidc'),
cmTechnologyProjectionTelevision = FOUR_CHAR_CODE('pjtv'),
cmTechnologyCRTDisplay = FOUR_CHAR_CODE('CRT '),
cmTechnologyPMDisplay = FOUR_CHAR_CODE('PMD '),
cmTechnologyAMDisplay = FOUR_CHAR_CODE('AMD '),
cmTechnologyPhotoCD = FOUR_CHAR_CODE('KPCD'),
cmTechnologyPhotoImageSetter = FOUR_CHAR_CODE('imgs'),
cmTechnologyGravure = FOUR_CHAR_CODE('grav'),
cmTechnologyOffsetLithography = FOUR_CHAR_CODE('offs'),
cmTechnologySilkscreen = FOUR_CHAR_CODE('silk'),
cmTechnologyFlexography = FOUR_CHAR_CODE('flex')
};
/* Measurement type encodings */
/* Measurement Flare */
enum {
cmFlare0 = 0x00000000,
cmFlare100 = 0x00000001
};
/* Measurement Geometry */
enum {
cmGeometryUnknown = 0x00000000,
cmGeometry045or450 = 0x00000001,
cmGeometry0dord0 = 0x00000002
};
/* Standard Observer */
enum {
cmStdobsUnknown = 0x00000000,
cmStdobs1931TwoDegrees = 0x00000001,
cmStdobs1964TenDegrees = 0x00000002
};
/* Standard Illuminant */
enum {
cmIlluminantUnknown = 0x00000000,
cmIlluminantD50 = 0x00000001,
cmIlluminantD65 = 0x00000002,
cmIlluminantD93 = 0x00000003,
cmIlluminantF2 = 0x00000004,
cmIlluminantD55 = 0x00000005,
cmIlluminantA = 0x00000006,
cmIlluminantEquiPower = 0x00000007,
cmIlluminantF8 = 0x00000008
};
/* Spot Function Value */
enum {
cmSpotFunctionUnknown = 0,
cmSpotFunctionDefault = 1,
cmSpotFunctionRound = 2,
cmSpotFunctionDiamond = 3,
cmSpotFunctionEllipse = 4,
cmSpotFunctionLine = 5,
cmSpotFunctionSquare = 6,
cmSpotFunctionCross = 7
};
/* Color Space Signatures */
enum {
cmXYZData = FOUR_CHAR_CODE('XYZ '),
cmLabData = FOUR_CHAR_CODE('Lab '),
cmLuvData = FOUR_CHAR_CODE('Luv '),
cmYCbCrData = FOUR_CHAR_CODE('YCbr'),
cmYxyData = FOUR_CHAR_CODE('Yxy '),
cmRGBData = FOUR_CHAR_CODE('RGB '),
cmSRGBData = FOUR_CHAR_CODE('sRGB'),
cmGrayData = FOUR_CHAR_CODE('GRAY'),
cmHSVData = FOUR_CHAR_CODE('HSV '),
cmHLSData = FOUR_CHAR_CODE('HLS '),
cmCMYKData = FOUR_CHAR_CODE('CMYK'),
cmCMYData = FOUR_CHAR_CODE('CMY '),
cmMCH5Data = FOUR_CHAR_CODE('MCH5'),
cmMCH6Data = FOUR_CHAR_CODE('MCH6'),
cmMCH7Data = FOUR_CHAR_CODE('MCH7'),
cmMCH8Data = FOUR_CHAR_CODE('MCH8'),
cm3CLRData = FOUR_CHAR_CODE('3CLR'),
cm4CLRData = FOUR_CHAR_CODE('4CLR'),
cm5CLRData = FOUR_CHAR_CODE('5CLR'),
cm6CLRData = FOUR_CHAR_CODE('6CLR'),
cm7CLRData = FOUR_CHAR_CODE('7CLR'),
cm8CLRData = FOUR_CHAR_CODE('8CLR'),
cm9CLRData = FOUR_CHAR_CODE('9CLR'),
cm10CLRData = FOUR_CHAR_CODE('ACLR'),
cm11CLRData = FOUR_CHAR_CODE('BCLR'),
cm12CLRData = FOUR_CHAR_CODE('CCLR'),
cm13CLRData = FOUR_CHAR_CODE('DCLR'),
cm14CLRData = FOUR_CHAR_CODE('ECLR'),
cm15CLRData = FOUR_CHAR_CODE('FCLR'),
cmNamedData = FOUR_CHAR_CODE('NAME')
};
/* profileClass enumerations */
enum {
cmInputClass = FOUR_CHAR_CODE('scnr'),
cmDisplayClass = FOUR_CHAR_CODE('mntr'),
cmOutputClass = FOUR_CHAR_CODE('prtr'),
cmLinkClass = FOUR_CHAR_CODE('link'),
cmAbstractClass = FOUR_CHAR_CODE('abst'),
cmColorSpaceClass = FOUR_CHAR_CODE('spac'),
cmNamedColorClass = FOUR_CHAR_CODE('nmcl')
};
/* platform enumerations */
enum {
cmMacintosh = FOUR_CHAR_CODE('APPL'),
cmMicrosoft = FOUR_CHAR_CODE('MSFT'),
cmSolaris = FOUR_CHAR_CODE('SUNW'),
cmSiliconGraphics = FOUR_CHAR_CODE('SGI '),
cmTaligent = FOUR_CHAR_CODE('TGNT')
};
/* parametric curve type enumerations */
enum {
cmParametricType0 = 0, /* Y = X^gamma */
cmParametricType1 = 1, /* Y = (aX+b)^gamma [X>=-b/a], Y = 0 [X<-b/a] */
cmParametricType2 = 2, /* Y = (aX+b)^gamma + c [X>=-b/a], Y = c [X<-b/a] */
cmParametricType3 = 3, /* Y = (aX+b)^gamma [X>=d], Y = cX [X<d] */
cmParametricType4 = 4 /* Y = (aX+b)^gamma + e [X>=d], Y = cX+f [X<d] */
};
/* ColorSync 1.0 elements */
enum {
cmCS1ChromTag = FOUR_CHAR_CODE('chrm'),
cmCS1TRCTag = FOUR_CHAR_CODE('trc '),
cmCS1NameTag = FOUR_CHAR_CODE('name'),
cmCS1CustTag = FOUR_CHAR_CODE('cust')
};
/* General element data types */
struct CMDateTime {
UInt16 year;
UInt16 month;
UInt16 dayOfTheMonth;
UInt16 hours;
UInt16 minutes;
UInt16 seconds;
};
typedef struct CMDateTime CMDateTime;
struct CMFixedXYColor {
Fixed x;
Fixed y;
};
typedef struct CMFixedXYColor CMFixedXYColor;
struct CMFixedXYZColor {
Fixed X;
Fixed Y;
Fixed Z;
};
typedef struct CMFixedXYZColor CMFixedXYZColor;
typedef UInt16 CMXYZComponent;
struct CMXYZColor {
CMXYZComponent X;
CMXYZComponent Y;
CMXYZComponent Z;
};
typedef struct CMXYZColor CMXYZColor;
/* Typedef for Profile MD5 message digest */
/* Derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm */
typedef unsigned char CMProfileMD5[16];
typedef CMProfileMD5 * CMProfileMD5Ptr;
/*
* CMProfileMD5AreEqual()
*
* Availability: available as macro/inline
*/
#ifdef __cplusplus
inline Boolean CMProfileMD5AreEqual(CMProfileMD5 a, CMProfileMD5 b)
{
return ((long*)a)[0]==((long*)b)[0] && ((long*)a)[1]==((long*)b)[1] &&
((long*)a)[2]==((long*)b)[2] && ((long*)a)[3]==((long*)b)[3];
}
#else
#define CMProfileMD5AreEqual(a, b) (\
((long*)a)[0]==((long*)b)[0] && ((long*)a)[1]==((long*)b)[1] && \
((long*)a)[2]==((long*)b)[2] && ((long*)a)[3]==((long*)b)[3])
#endif
struct CM2Header {
UInt32 size; /* This is the total size of the Profile */
OSType CMMType; /* CMM signature, Registered with CS2 consortium */
UInt32 profileVersion; /* Version of CMProfile format */
OSType profileClass; /* input, display, output, devicelink, abstract, or color conversion profile type */
OSType dataColorSpace; /* color space of data */
OSType profileConnectionSpace; /* profile connection color space */
CMDateTime dateTime; /* date and time of profile creation */
OSType CS2profileSignature; /* 'acsp' constant ColorSync 2.0 file ID */
OSType platform; /* primary profile platform, Registered with CS2 consortium */
UInt32 flags; /* profile flags */
OSType deviceManufacturer; /* Registered with ICC consortium */
UInt32 deviceModel; /* Registered with ICC consortium */
UInt32 deviceAttributes[2]; /* Attributes[0] is for device vendors, [1] is for ICC */
UInt32 renderingIntent; /* preferred rendering intent of tagged object */
CMFixedXYZColor white; /* profile illuminant */
OSType creator; /* profile creator */
char reserved[44]; /* reserved for future use */
};
typedef struct CM2Header CM2Header;
struct CM4Header {
UInt32 size; /* This is the total size of the Profile */
OSType CMMType; /* CMM signature, Registered with CS2 consortium */
UInt32 profileVersion; /* Version of CMProfile format */
OSType profileClass; /* input, display, output, devicelink, abstract, or color conversion profile type */
OSType dataColorSpace; /* color space of data */
OSType profileConnectionSpace; /* profile connection color space */
CMDateTime dateTime; /* date and time of profile creation */
OSType CS2profileSignature; /* 'acsp' constant ColorSync 2.0 file ID */
OSType platform; /* primary profile platform, Registered with CS2 consortium */
UInt32 flags; /* profile flags */
OSType deviceManufacturer; /* Registered with ICC consortium */
UInt32 deviceModel; /* Registered with ICC consortium */
UInt32 deviceAttributes[2]; /* Attributes[0] is for device vendors, [1] is for ICC */
UInt32 renderingIntent; /* preferred rendering intent of tagged object */
CMFixedXYZColor white; /* profile illuminant */
OSType creator; /* profile creator */
CMProfileMD5 digest; /* Profile message digest */
char reserved[28]; /* reserved for future use */
};
typedef struct CM4Header CM4Header;
struct CMTagRecord {
OSType tag; /* Registered with CS2 consortium */
UInt32 elementOffset; /* Relative to start of CMProfile */
UInt32 elementSize;
};
typedef struct CMTagRecord CMTagRecord;
struct CMTagElemTable {
UInt32 count;
CMTagRecord tagList[1]; /* variable size, determined by count */
};
typedef struct CMTagElemTable CMTagElemTable;
struct CM2Profile {
CM2Header header;
CMTagElemTable tagTable;
char elemData[1]; /* variable size data for tagged element storage */
};
typedef struct CM2Profile CM2Profile;
typedef CM2Profile * CM2ProfilePtr;
typedef CM2ProfilePtr * CM2ProfileHandle;
/* Tag Type Definitions */
struct CMAdaptationMatrixType {
OSType typeDescriptor; /* 'sf32' = cmSigS15Fixed16Type */
unsigned long reserved; /* fill with 0x00 */
Fixed adaptationMatrix[9]; /* fixed size of nine matrix entries */
};
typedef struct CMAdaptationMatrixType CMAdaptationMatrixType;
struct CMCurveType {
OSType typeDescriptor; /* 'curv' = cmSigCurveType */
UInt32 reserved; /* fill with 0x00 */
UInt32 countValue; /* number of entries in table that follows */
UInt16 data[1]; /* variable size, determined by countValue */
};
typedef struct CMCurveType CMCurveType;
struct CMDataType {
OSType typeDescriptor; /* 'data' = cmSigDataType*/
UInt32 reserved; /* fill with 0x00 */
UInt32 dataFlag; /* 0 = ASCII, 1 = binary */
char data[1]; /* variable size, determined by tag element size */
};
typedef struct CMDataType CMDataType;
struct CMDateTimeType {
OSType typeDescriptor; /* 'dtim' = cmSigDateTimeType */
UInt32 reserved; /* fill with 0x00 */
CMDateTime dateTime; /* */
};
typedef struct CMDateTimeType CMDateTimeType;
struct CMLut16Type {
OSType typeDescriptor; /* 'mft2' = cmSigLut16Type */
UInt32 reserved; /* fill with 0x00 */
UInt8 inputChannels; /* Number of input channels */
UInt8 outputChannels; /* Number of output channels */
UInt8 gridPoints; /* Number of clutTable grid points */
UInt8 reserved2; /* fill with 0x00 */
Fixed matrix[3][3]; /* */
UInt16 inputTableEntries; /* Number of entries in 1-D input luts */
UInt16 outputTableEntries; /* Number of entries in 1-D output luts */
UInt16 inputTable[1]; /* variable size, determined by inputChannels*inputTableEntries */
#if 0 /* NOTE: Field offsets are variable from here on. */
/* In order to correctly reflect the actual format of this tag, some of the fields in */
/* this structure have been removed because they follow an array field of variable size. */
/* As a result, the size of this structure has changed from previous versions of this interface. */
/* Code that relies on sizeof(CMLut16Type) should be changed. */
UInt16 CLUT[]; /* variable size, determined by (gridPoints^inputChannels)*outputChannels */
UInt16 outputTable[]; /* variable size, determined by outputChannels*outputTableEntries */
#endif
};
typedef struct CMLut16Type CMLut16Type;
struct CMLut8Type {
OSType typeDescriptor; /* 'mft1' = cmSigLut8Type */
UInt32 reserved; /* fill with 0x00 */
UInt8 inputChannels; /* Number of input channels */
UInt8 outputChannels; /* Number of output channels */
UInt8 gridPoints; /* Number of clutTable grid points */
UInt8 reserved2; /* fill with 0x00 */
Fixed matrix[3][3]; /* */
UInt8 inputTable[1]; /* variable size, determined by inputChannels*256 */
#if 0 /* NOTE: Field offsets are variable from here on. */
/* In order to correctly reflect the actual format of this tag, some of the fields in */
/* this structure have been removed because they follow an array field of variable size. */
/* As a result, the size of this structure has changed from previous versions of this interface. */
/* Code that relies on sizeof(CMLut8Type) should be changed. */
UInt8 CLUT[]; /* variable size, determined by (gridPoints^inputChannels)*outputChannels */
UInt8 outputTable[]; /* variable size, determined by outputChannels*256 */
#endif
};
typedef struct CMLut8Type CMLut8Type;
struct CMMultiFunctLutType {
OSType typeDescriptor; /* 'mAB ' = cmSigMultiFunctA2BType or 'mBA ' = cmSigMultiFunctB2AType */
UInt32 reserved; /* fill with 0x00 */
UInt8 inputChannels; /* Number of input channels */
UInt8 outputChannels; /* Number of output channels */
UInt16 reserved2; /* fill with 0x00 */
UInt32 offsetBcurves; /* offset to first "B" curve */
UInt32 offsetMatrix; /* offset to 3x4 matrix */
UInt32 offsetMcurves; /* offset to first "M" curve */
UInt32 offsetCLUT; /* offset to multi-dimensional LUT of type CMMultiFunctCLUTType */
UInt32 offsetAcurves; /* offset to first "A" curve */
UInt8 data[1]; /* variable size */
};
typedef struct CMMultiFunctLutType CMMultiFunctLutType;
typedef CMMultiFunctLutType CMMultiFunctLutA2BType;
typedef CMMultiFunctLutType CMMultiFunctLutB2AType;
struct CMMultiFunctCLUTType {
UInt8 gridPoints[16]; /* grigpoints for each input channel dimension (remaining are 0) */
UInt8 entrySize; /* bytes per lut enrty (1 or 2) */
UInt8 reserved[3]; /* fill with 0x00 */
UInt8 data[1]; /* variable size, determined by above */
};
typedef struct CMMultiFunctCLUTType CMMultiFunctCLUTType;
struct CMMeasurementType {
OSType typeDescriptor; /* 'meas' = cmSigMeasurementType */
UInt32 reserved; /* fill with 0x00 */
UInt32 standardObserver; /* cmStdobsUnknown, cmStdobs1931TwoDegrees, cmStdobs1964TenDegrees */
CMFixedXYZColor backingXYZ; /* absolute XYZ values of backing */
UInt32 geometry; /* cmGeometryUnknown, cmGeometry045or450 (0/45), cmGeometry0dord0 (0/d or d/0) */
UInt32 flare; /* cmFlare0, cmFlare100 */
UInt32 illuminant; /* cmIlluminantUnknown, cmIlluminantD50, ... */
};
typedef struct CMMeasurementType CMMeasurementType;
struct CMNamedColorType {
OSType typeDescriptor; /* 'ncol' = cmSigNamedColorType */
UInt32 reserved; /* fill with 0x00 */
UInt32 vendorFlag; /* */
UInt32 count; /* count of named colors in array that follows */
UInt8 prefixName[1]; /* variable size, max = 32 */
#if 0 /* NOTE: Field offsets are variable from here on. */
/* In order to correctly reflect the actual format of this tag, some of the fields in */
/* this structure have been removed because they follow an array field of variable size. */
/* As a result, the size of this structure has changed from previous versions of this interface. */
/* Code that relies on sizeof(CMNamedColorType) should be changed. */
UInt8 suffixName[]; /* variable size, max = 32 */
struct {
UInt8 rootName[]; /* variable size, max = 32 */
UInt8 colorCoords[]; /* variable size */
} colorName[]; /* variable size */
#endif
};
typedef struct CMNamedColorType CMNamedColorType;
struct CMNamedColor2EntryType {
UInt8 rootName[32]; /* 32 byte field. 7 bit ASCII null terminated */
UInt16 PCSColorCoords[3]; /* Lab or XYZ color */
UInt16 DeviceColorCoords[1]; /* variable size */
};
typedef struct CMNamedColor2EntryType CMNamedColor2EntryType;
struct CMNamedColor2Type {
OSType typeDescriptor; /* 'ncl2' = cmSigNamedColor2Type */
UInt32 reserved; /* fill with 0x00 */
UInt32 vendorFlag; /* lower 16 bits reserved for ICC use */
UInt32 count; /* count of named colors in array that follows */
UInt32 deviceChannelCount; /* number of device channels, 0 indicates no device value available */
UInt8 prefixName[32]; /* Fixed 32 byte size. 7 bit ASCII null terminated */
UInt8 suffixName[32]; /* Fixed 32 byte size. 7 bit ASCII null terminated */
char data[1]; /* variable size data for CMNamedColor2EntryType */
};
typedef struct CMNamedColor2Type CMNamedColor2Type;
struct CMNativeDisplayInfo {
UInt32 dataSize; /* Size of this structure */
CMFixedXYColor redPhosphor; /* Phosphors - native cromaticity values of the display */
CMFixedXYColor greenPhosphor;
CMFixedXYColor bluePhosphor;
CMFixedXYColor whitePoint;
Fixed redGammaValue; /* Gammas - native gamma values of the display */
Fixed greenGammaValue;
Fixed blueGammaValue;
/* Gamma tables - if if gammaChannels is not zero, */
/* native gamma tables are preferred over values */
/* redGammaValue, greenGammaValue, blueGammaValue */
UInt16 gammaChannels; /* # of gamma channels (1 or 3) */
UInt16 gammaEntryCount; /* 1-based number of entries per channel */
UInt16 gammaEntrySize; /* size in bytes of each entry */
char gammaData[1]; /* variable size, determined by channels*entryCount*entrySize */
};
typedef struct CMNativeDisplayInfo CMNativeDisplayInfo;
struct CMNativeDisplayInfoType {
OSType typeDescriptor; /* 'ndin' = cmSigNativeDisplayInfoType */
unsigned long reserved; /* fill with 0x00 */
CMNativeDisplayInfo nativeDisplayInfo; /* data of type CMNativeDisplayInfo */
};
typedef struct CMNativeDisplayInfoType CMNativeDisplayInfoType;
struct CMParametricCurveType {
OSType typeDescriptor; /* 'para' = cmSigParametricCurveType */
UInt32 reserved; /* fill with 0x00 */
UInt16 functionType; /* cmParametricType0, cmParametricType1, etc. */
UInt16 reserved2; /* fill with 0x00 */
Fixed value[1]; /* variable size, determined by functionType */
};
typedef struct CMParametricCurveType CMParametricCurveType;
struct CMTextDescriptionType {
OSType typeDescriptor; /* 'desc' = cmSigProfileDescriptionType */
UInt32 reserved; /* fill with 0x00 */
UInt32 ASCIICount; /* Count of bytes (including null terminator) */
UInt8 ASCIIName[2]; /* variable size, determined by ASCIICount. 7 bit ASCII null terminated */
#if 0 /* NOTE: Field offsets are variable from here on. */
/* In order to correctly reflect the actual format of this tag, some of the fields in */
/* this structure have been removed because they follow an array field of variable size. */
/* As a result, the size of this structure has changed from previous versions of this interface. */
/* Code that relies on sizeof(CMTextDescriptionType) should be changed. */
UInt32 UniCodeCode; /* Unused */
UInt32 UniCodeCount; /* Count of 2-byte characters (including null terminator) */
UInt8 UniCodeName[]; /* variable size, determined by UniCodeCount */
SInt16 ScriptCodeCode; /* Mac-defined script code */
UInt8 ScriptCodeCount; /* Count of bytes (including null terminator) */
UInt8 ScriptCodeName[]; /* variable size, determined by ScriptCodeCount */
#endif
};
typedef struct CMTextDescriptionType CMTextDescriptionType;
struct CMTextType {
OSType typeDescriptor; /* 'text' = cmSigTextType */
UInt32 reserved; /* fill with 0x00 */
UInt8 text[1]; /* variable size, determined by tag element size */
};
typedef struct CMTextType CMTextType;
struct CMUnicodeTextType {
OSType typeDescriptor; /* 'utxt' = cmSigUnicodeTextType */
UInt32 reserved; /* fill with 0x00 */
UniChar text[1]; /* variable size, determined by tag element size */
};
typedef struct CMUnicodeTextType CMUnicodeTextType;
struct CMScreeningChannelRec {
Fixed frequency;
Fixed angle;
UInt32 spotFunction;
};
typedef struct CMScreeningChannelRec CMScreeningChannelRec;
struct CMScreeningType {
OSType typeDescriptor; /* 'scrn' = cmSigScreeningType */
UInt32 reserved; /* fill with 0x00 */
UInt32 screeningFlag; /* bit 0 : use printer default screens, bit 1 : inch/cm */
UInt32 channelCount; /* */
CMScreeningChannelRec channelInfo[1]; /* variable size, determined by channelCount */
};
typedef struct CMScreeningType CMScreeningType;
struct CMSignatureType {
OSType typeDescriptor; /* 'sig ' = cmSigSignatureType */
UInt32 reserved; /* fill with 0x00 */
OSType signature;
};
typedef struct CMSignatureType CMSignatureType;
struct CMS15Fixed16ArrayType {
OSType typeDescriptor; /* 'sf32' = cmSigS15Fixed16Type */
UInt32 reserved; /* fill with 0x00 */
Fixed value[1]; /* variable size, determined by tag element size */
};
typedef struct CMS15Fixed16ArrayType CMS15Fixed16ArrayType;
struct CMU16Fixed16ArrayType {
OSType typeDescriptor; /* 'uf32' = cmSigU16Fixed16Type */
UInt32 reserved; /* fill with 0x00 */
UInt32 value[1]; /* variable size, determined by tag element size */
};
typedef struct CMU16Fixed16ArrayType CMU16Fixed16ArrayType;
struct CMUInt8ArrayType {
OSType typeDescriptor; /* 'ui08' = cmSigUInt8Type */
UInt32 reserved; /* fill with 0x00 */
UInt8 value[1]; /* variable size, determined by tag element size */
};
typedef struct CMUInt8ArrayType CMUInt8ArrayType;
struct CMUInt16ArrayType {
OSType typeDescriptor; /* 'ui16' = cmSigUInt16Type */
UInt32 reserved; /* fill with 0x00 */
UInt16 value[1]; /* variable size, determined by tag element size */
};
typedef struct CMUInt16ArrayType CMUInt16ArrayType;
struct CMUInt32ArrayType {
OSType typeDescriptor; /* 'ui32' = cmSigUInt32Type */
UInt32 reserved; /* fill with 0x00 */
UInt32 value[1]; /* variable size, determined by tag element size */
};
typedef struct CMUInt32ArrayType CMUInt32ArrayType;
struct CMUInt64ArrayType {
OSType typeDescriptor; /* 'ui64' = cmSigUInt64Type */
UInt32 reserved; /* fill with 0x00 */
UInt32 value[1]; /* variable size, determined by tag element size */
};
typedef struct CMUInt64ArrayType CMUInt64ArrayType;
struct CMViewingConditionsType {
OSType typeDescriptor; /* 'view' = cmSigViewingConditionsType */
UInt32 reserved; /* fill with 0x00 */
CMFixedXYZColor illuminant; /* absolute XYZs of illuminant in cd/m^2 */
CMFixedXYZColor surround; /* absolute XYZs of surround in cd/m^2 */
UInt32 stdIlluminant; /* see definitions of std illuminants */
};
typedef struct CMViewingConditionsType CMViewingConditionsType;
struct CMXYZType {
OSType typeDescriptor; /* 'XYZ ' = cmSigXYZType */
UInt32 reserved; /* fill with 0x00 */
CMFixedXYZColor XYZ[1]; /* variable size, determined by tag element size */
};
typedef struct CMXYZType CMXYZType;
struct CMProfileSequenceDescType {
OSType typeDescriptor; /* 'pseq' = cmProfileSequenceDescTag */
UInt32 reserved; /* fill with 0x00 */
UInt32 count; /* Number of descriptions */
char data[1]; /* variable size data explained in ICC spec */
};
typedef struct CMProfileSequenceDescType CMProfileSequenceDescType;
struct CMUcrBgType {
OSType typeDescriptor; /* 'bfd ' = cmSigUcrBgType */
UInt32 reserved; /* fill with 0x00 */
UInt32 ucrCount; /* Number of UCR entries */
UInt16 ucrValues[1]; /* variable size, determined by ucrCount */
#if 0 /* NOTE: Field offsets are variable from here on. */
/* In order to correctly reflect the actual format of this tag, some of the fields in */
/* this structure have been removed because they follow an array field of variable size. */
/* As a result, the size of this structure has changed from previous versions of this interface. */
/* Code that relies on sizeof(CMUcrBgType) should be changed. */
UInt32 bgCount; /* Number of BG entries */
UInt16 bgValues[]; /* variable size, determined by bgCount */
UInt8 ucrbgASCII[]; /* null terminated ASCII string */
#endif
};
typedef struct CMUcrBgType CMUcrBgType;
/* Private Tag Type Definitions */
struct CMIntentCRDVMSize {
long renderingIntent; /* rendering intent */
UInt32 VMSize; /* VM size taken up by the CRD */
};
typedef struct CMIntentCRDVMSize CMIntentCRDVMSize;
struct CMPS2CRDVMSizeType {
OSType typeDescriptor; /* 'psvm' = cmSigPS2CRDVMSizeType */
UInt32 reserved; /* fill with 0x00 */
UInt32 count; /* number of intent entries */
CMIntentCRDVMSize intentCRD[1]; /* variable size, determined by count */
};
typedef struct CMPS2CRDVMSizeType CMPS2CRDVMSizeType;
enum {
cmVideoCardGammaTableType = 0,
cmVideoCardGammaFormulaType = 1
};
struct CMVideoCardGammaTable {
UInt16 channels; /* # of gamma channels (1 or 3) */
UInt16 entryCount; /* 1-based number of entries per channel */
UInt16 entrySize; /* size in bytes of each entry */
char data[1]; /* variable size, determined by channels*entryCount*entrySize */
};
typedef struct CMVideoCardGammaTable CMVideoCardGammaTable;
struct CMVideoCardGammaFormula {
Fixed redGamma; /* must be > 0.0 */
Fixed redMin; /* must be > 0.0 and < 1.0 */
Fixed redMax; /* must be > 0.0 and < 1.0 */
Fixed greenGamma; /* must be > 0.0 */
Fixed greenMin; /* must be > 0.0 and < 1.0 */
Fixed greenMax; /* must be > 0.0 and < 1.0 */
Fixed blueGamma; /* must be > 0.0 */
Fixed blueMin; /* must be > 0.0 and < 1.0 */
Fixed blueMax; /* must be > 0.0 and < 1.0 */
};
typedef struct CMVideoCardGammaFormula CMVideoCardGammaFormula;
struct CMVideoCardGamma {
UInt32 tagType;
union {
CMVideoCardGammaTable table;
CMVideoCardGammaFormula formula;
} u;
};
typedef struct CMVideoCardGamma CMVideoCardGamma;
struct CMVideoCardGammaType {
OSType typeDescriptor; /* 'vcgt' = cmSigVideoCardGammaType */
UInt32 reserved; /* fill with 0x00 */
CMVideoCardGamma gamma;
};
typedef struct CMVideoCardGammaType CMVideoCardGammaType;
struct CMMakeAndModel {
OSType manufacturer;
UInt32 model;
UInt32 serialNumber;
UInt32 manufactureDate;
UInt32 reserved1; /* fill with 0x00 */
UInt32 reserved2; /* fill with 0x00 */
UInt32 reserved3; /* fill with 0x00 */
UInt32 reserved4; /* fill with 0x00 */
};
typedef struct CMMakeAndModel CMMakeAndModel;
struct CMMakeAndModelType {
OSType typeDescriptor; /* 'mmod' = cmSigMakeAndModelType */
UInt32 reserved; /* fill with 0x00 */
CMMakeAndModel makeAndModel;
};
typedef struct CMMakeAndModelType CMMakeAndModelType;
struct CMMultiLocalizedUniCodeEntryRec {
char languageCode[2]; /* language code from ISO-639 */
char regionCode[2]; /* region code from ISO-3166 */
UInt32 textLength; /* the length in bytes of the string */
UInt32 textOffset; /* the offset from the start of tag in bytes */
};
typedef struct CMMultiLocalizedUniCodeEntryRec CMMultiLocalizedUniCodeEntryRec;
struct CMMultiLocalizedUniCodeType {
OSType typeDescriptor; /* 'mluc' = cmSigMultiLocalizedUniCodeType */
UInt32 reserved; /* fill with 0x00 */
UInt32 entryCount; /* 1-based number of name records that follow */
UInt32 entrySize; /* size in bytes of name records that follow */
/* variable-length data for storage of CMMultiLocalizedUniCodeEntryRec */
/* variable-length data for storage of Unicode strings*/
};
typedef struct CMMultiLocalizedUniCodeType CMMultiLocalizedUniCodeType;
/************************************************************************/
/*************** ColorSync 1.0 profile specification ********************/
/************************************************************************/
enum {
cmGrayResponse = 0,
cmRedResponse = 1,
cmGreenResponse = 2,
cmBlueResponse = 3,
cmCyanResponse = 4,
cmMagentaResponse = 5,
cmYellowResponse = 6,
cmUcrResponse = 7,
cmBgResponse = 8,
cmOnePlusLastResponse = 9
};
/* Device types */
enum {
cmMonitorDevice = FOUR_CHAR_CODE('mntr'),
cmScannerDevice = FOUR_CHAR_CODE('scnr'),
cmPrinterDevice = FOUR_CHAR_CODE('prtr')
};
struct CMIString {
ScriptCode theScript;
Str63 theString;
};
typedef struct CMIString CMIString;
/* Profile options */
enum {
cmPerceptualMatch = 0x0000, /* Default. For photographic images */
cmColorimetricMatch = 0x0001, /* Exact matching when possible */
cmSaturationMatch = 0x0002 /* For solid colors */
};
/* Profile flags */
enum {
cmNativeMatchingPreferred = 0x00000001, /* Default to native not preferred */
cmTurnOffCache = 0x00000002 /* Default to turn on CMM cache */
};
typedef long CMMatchOption;
typedef long CMMatchFlag;
struct CMHeader {
UInt32 size;
OSType CMMType;
UInt32 applProfileVersion;
OSType dataType;
OSType deviceType;
OSType deviceManufacturer;
UInt32 deviceModel;
UInt32 deviceAttributes[2];
UInt32 profileNameOffset;
UInt32 customDataOffset;
CMMatchFlag flags;
CMMatchOption options;
CMXYZColor white;
CMXYZColor black;
};
typedef struct CMHeader CMHeader;
struct CMProfileChromaticities {
CMXYZColor red;
CMXYZColor green;
CMXYZColor blue;
CMXYZColor cyan;
CMXYZColor magenta;
CMXYZColor yellow;
};
typedef struct CMProfileChromaticities CMProfileChromaticities;
struct CMProfileResponse {
UInt16 counts[9];
UInt16 data[1]; /* Variable size */
};
typedef struct CMProfileResponse CMProfileResponse;
struct CMProfile {
CMHeader header;
CMProfileChromaticities profile;
CMProfileResponse response;
CMIString profileName;
char customData[1]; /* Variable size */
};
typedef struct CMProfile CMProfile;
typedef CMProfile * CMProfilePtr;
typedef CMProfilePtr * CMProfileHandle;
#if OLDROUTINENAMES
enum {
kCMApplProfileVersion = cmCS1ProfileVersion
};
enum {
grayResponse = cmGrayResponse,
redResponse = cmRedResponse,
greenResponse = cmGreenResponse,
blueResponse = cmBlueResponse,
cyanResponse = cmCyanResponse,
magentaResponse = cmMagentaResponse,
yellowResponse = cmYellowResponse,
ucrResponse = cmUcrResponse,
bgResponse = cmBgResponse,
onePlusLastResponse = cmOnePlusLastResponse
};
enum {
rgbData = cmRGBData,
cmykData = cmCMYKData,
grayData = cmGrayData,
xyzData = cmXYZData
};
enum {
XYZData = cmXYZData
};
enum {
monitorDevice = cmMonitorDevice,
scannerDevice = cmScannerDevice,
printerDevice = cmPrinterDevice
};
enum {
CMNativeMatchingPreferred = cmNativeMatchingPreferred, /* Default to native not preferred */
CMTurnOffCache = cmTurnOffCache /* Default to turn on CMM cache */
};
enum {
CMPerceptualMatch = cmPerceptualMatch, /* Default. For photographic images */
CMColorimetricMatch = cmColorimetricMatch, /* Exact matching when possible */
CMSaturationMatch = cmSaturationMatch /* For solid colors */
};
typedef UInt16 XYZComponent;
typedef CMXYZColor XYZColor;
typedef UInt16 CMResponseData;
typedef CMIString IString;
typedef long CMResponseColor;
typedef CMResponseColor responseColor;
#endif /* OLDROUTINENAMES */
#if PRAGMA_STRUCT_ALIGN
#pragma options align=reset
#elif PRAGMA_STRUCT_PACKPUSH
#pragma pack(pop)
#elif PRAGMA_STRUCT_PACK
#pragma pack()
#endif
#ifdef PRAGMA_IMPORT_OFF
#pragma import off
#elif PRAGMA_IMPORT
#pragma import reset
#endif
#endif /* __CMICCPROFILE__ */
| 47.371345 | 135 | 0.569883 | [
"geometry",
"object",
"model",
"solid"
] |
083b7f981845286a4043e79ee0461251f58fb56a | 2,698 | h | C | ACL/include/ACL/Transport/TransportFactoryInterface.h | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,272 | 2017-08-17T04:58:05.000Z | 2022-03-27T03:28:29.000Z | ACL/include/ACL/Transport/TransportFactoryInterface.h | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,948 | 2017-08-17T03:39:24.000Z | 2022-03-30T15:52:41.000Z | ACL/include/ACL/Transport/TransportFactoryInterface.h | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 630 | 2017-08-17T06:35:59.000Z | 2022-03-29T04:04:44.000Z | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef ALEXA_CLIENT_SDK_ACL_INCLUDE_ACL_TRANSPORT_TRANSPORTFACTORYINTERFACE_H_
#define ALEXA_CLIENT_SDK_ACL_INCLUDE_ACL_TRANSPORT_TRANSPORTFACTORYINTERFACE_H_
#include <memory>
#include <string>
#include <AVSCommon/SDKInterfaces/AuthDelegateInterface.h>
#include <AVSCommon/AVS/Attachment/AttachmentManagerInterface.h>
#include "ACL/Transport/TransportInterface.h"
#include "ACL/Transport/MessageConsumerInterface.h"
#include "ACL/Transport/TransportObserverInterface.h"
#include "ACL/Transport/SynchronizedMessageRequestQueue.h"
namespace alexaClientSDK {
namespace acl {
/**
* This is the interface for the transport factory
*/
class TransportFactoryInterface {
public:
/**
* Creates a new transport.
*
* @param authDelegate The AuthDelegateInterface to use for authentication and authorization with AVS.
* @param attachmentManager The attachment manager that manages the attachments.
* @param avsGateway The URL for the AVS server we will connect to.
* @param messageConsumerInterface The object which should be notified on messages which arrive from AVS.
* @param transportObserverInterface A pointer to the transport observer the new transport should notify.
* @param sharedRequestQueue Request queue shared by all instances of TransportInterface.
* @return A new MessageRouter object.
*/
virtual std::shared_ptr<TransportInterface> createTransport(
std::shared_ptr<avsCommon::sdkInterfaces::AuthDelegateInterface> authDelegate,
std::shared_ptr<avsCommon::avs::attachment::AttachmentManagerInterface> attachmentManager,
const std::string& avsGateway,
std::shared_ptr<MessageConsumerInterface> messageConsumerInterface,
std::shared_ptr<TransportObserverInterface> transportObserverInterface,
std::shared_ptr<SynchronizedMessageRequestQueue> sharedMessageRequestQueue) = 0;
/**
* Destructor.
*/
virtual ~TransportFactoryInterface() = default;
};
} // namespace acl
} // namespace alexaClientSDK
#endif // ALEXA_CLIENT_SDK_ACL_INCLUDE_ACL_TRANSPORT_TRANSPORTFACTORYINTERFACE_H_
| 40.268657 | 109 | 0.770941 | [
"object"
] |
083d76024e7c5d26f2a018d1c65f0bc57f0db9bd | 751 | h | C | Commands/DelinkCommand.h | 5ko99/SDP-Practicum-Social-Network | 16589f46b6a2049b002c1f61070675cb1635267c | [
"MIT"
] | null | null | null | Commands/DelinkCommand.h | 5ko99/SDP-Practicum-Social-Network | 16589f46b6a2049b002c1f61070675cb1635267c | [
"MIT"
] | null | null | null | Commands/DelinkCommand.h | 5ko99/SDP-Practicum-Social-Network | 16589f46b6a2049b002c1f61070675cb1635267c | [
"MIT"
] | null | null | null | //
// Created by petko on 16/12/2019.
//
#ifndef SDP_PRACTICUM_SOCIAL_NETWORK_DELINKCOMMAND_H
#define SDP_PRACTICUM_SOCIAL_NETWORK_DELINKCOMMAND_H
#include <iostream>
#include "Command.h"
class DelinkCommand: public Command {
FriendshipType type;
public:
DelinkCommand(std::vector<std::string> const & _args){
commandType= Delink;
User _user1(_args[1].c_str(),0,"");
User _user2(_args[2].c_str(),0,"");
users.push_back(_user1);
users.push_back(_user2);
type=delink;
}
void execute(DynamicArray& arr, DynamicGraph& friendships){
linkUsers(users[0].name,users[1].name,type,arr,friendships);
}
~DelinkCommand(){}
};
#endif //SDP_PRACTICUM_SOCIAL_NETWORK_DELINKCOMMAND_H
| 25.896552 | 68 | 0.691079 | [
"vector"
] |
083ec0d9a64e41583d25a9d91cc621de2e2b5836 | 3,444 | h | C | collision_detection/include/collision_detection/collision_detection_octomap.h | anpl-technion/anpl_mrbsp | 973734fd2d1c7bb5e1405922300add489f088e81 | [
"MIT"
] | 1 | 2021-12-03T03:11:20.000Z | 2021-12-03T03:11:20.000Z | collision_detection/include/collision_detection/collision_detection_octomap.h | anpl-technion/anpl_mrbsp | 973734fd2d1c7bb5e1405922300add489f088e81 | [
"MIT"
] | null | null | null | collision_detection/include/collision_detection/collision_detection_octomap.h | anpl-technion/anpl_mrbsp | 973734fd2d1c7bb5e1405922300add489f088e81 | [
"MIT"
] | 1 | 2021-12-03T03:11:23.000Z | 2021-12-03T03:11:23.000Z | /* ---------------------------------------------------------------------------
*
* Autonomous Navigation and Perception Lab (ANPL),
* Technion, Israel Institute of Technology,
* Faculty of Aerospace Engineering,
* Haifa, Israel, 32000
* All Rights Reserved
*
* See LICENSE for the license information
*
* -------------------------------------------------------------------------- */
/**
* @file: collision_detection_octomap.h
* @brief:
* @author: Asaf Feniger
*/
#ifndef COLLISION_DETECTIONS_OCTOMAP_H
#define COLLISION_DETECTIONS_OCTOMAP_H
#include "collision_detection_base.h"
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/PointCloud2.h>
#include <octomap/OcTree.h>
#include <fcl/octree.h>
#include <fcl/shape/geometric_shapes.h>
namespace MRBSP {
/**
*/
class CollisionDetectionOctomap : public CollisionDetectionBase {
public:
/**
* Default constructor - empty
*/
CollisionDetectionOctomap();
/**
* Copy constructor
* @param collision_detection
*/
CollisionDetectionOctomap(const CollisionDetectionOctomap& other);
/**
* Copy assignment operator.
* @param collision_detection
* @return
*/
CollisionDetectionOctomap& operator=(const CollisionDetectionOctomap& other);
/**
* Destructor
*/
virtual ~CollisionDetectionOctomap();
private:
// **ROS publishers and subscribers**
/// ros subscriber for laser scans messages
ros::Subscriber m_laser_sub;
/// ros publisher for local map
ros::Publisher m_local_map_pub;
/// flag whether to publish empty collision warning
bool m_publish_empty_msg;
/**
* @brief Callback function to handle ros laser messages
* @param scan - pointer to ros laser message
*/
void laserCallback(const sensor_msgs::LaserScanConstPtr& scan);
// **Octomap**
/// local map resolution
double m_map_resolution;
/// sensor pose in the robot body frame
octomap::pose6d m_senor_pose;
/**
* @brief Function to generate octomap from laser scan message
* @param scan - ros laser scan msg
* @param p_octree_local_map - pointer to octree object
*/
void insertLaserScan(const sensor_msgs::LaserScanConstPtr& scan,
std::shared_ptr<octomap::OcTree> p_octree_map);
// **FCL**
/// smart pointer to robot box fcl model
std::shared_ptr<fcl::Box> m_robot_box;
/// maximum robot acceleration to calculate safe stopping distance at the current speed before hitting obstacles
double m_a_max;
/**
* @brief Function to generate FCL boxes from fcl::octree object
* @param tree - fcl's octree representation
* @param boxes - collision objects from the octree
*/
void generateBoxesFromOctomap(const fcl::OcTree &tree, std::vector<fcl::CollisionObject> &boxes);
/**
* @brief Function to detect collisions with respect to the robot size
* @param boxes - collision object to check for collisions
* @return
*/
bool isObstacleAheadFCL(const std::vector<fcl::CollisionObject>& boxes, const fcl::Vec3f& vel_vec);
};
}
#endif // COLLISION_DETECTIONS_OCTOMAP_H
| 28.229508 | 120 | 0.605691 | [
"object",
"shape",
"vector",
"model"
] |
0847f2d235fe9f4ff68eb311e0bd65d54de2b340 | 3,324 | h | C | pi4home-core/src/pi4home/log_component.h | khzd/pi4home | 937bcdcf77bab111cca10af1fe45c63a55c29aae | [
"MIT"
] | 1 | 2019-05-16T02:52:12.000Z | 2019-05-16T02:52:12.000Z | pi4home-core/src/pi4home/log_component.h | khzd/pi4home | 937bcdcf77bab111cca10af1fe45c63a55c29aae | [
"MIT"
] | null | null | null | pi4home-core/src/pi4home/log_component.h | khzd/pi4home | 937bcdcf77bab111cca10af1fe45c63a55c29aae | [
"MIT"
] | null | null | null | #ifndef PI4HOME_LOG_COMPONENT_H
#define PI4HOME_LOG_COMPONENT_H
#include <cstdarg>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include <cassert>
#include <unordered_map>
#include "pi4home/component.h"
#include "pi4home/mqtt/mqtt_component.h"
#include "pi4home/helpers.h"
#include "pi4home/log.h"
#include "pi4home/defines.h"
PI4HOME_NAMESPACE_BEGIN
/** Enum for logging UART selection
*
* Advanced configuration (pin selection, etc) is not supported.
*/
enum UARTSelection {
UART_SELECTION_UART0 = 0,
UART_SELECTION_UART1,
#ifdef ARDUINO_ARCH_ESP32
UART_SELECTION_UART2
#endif
#ifdef ARDUINO_ARCH_ESP8266
UART_SELECTION_UART0_SWAP
#endif
};
/** A simple component that enables logging to Serial via the ESP_LOG* macros.
*
* This component should optimally be setup very early because only after its setup log messages are actually sent.
* To do this, simply call pre_setup() as early as possible.
*/
class LogComponent : public Component {
public:
/** Construct the LogComponent.
*
* @param baud_rate The baud_rate for the serial interface. 0 to disable UART logging.
* @param tx_buffer_size The buffer size (in bytes) used for constructing log messages.
*/
explicit LogComponent(uint32_t baud_rate = 115200, size_t tx_buffer_size = 512,
UARTSelection uart = UART_SELECTION_UART0);
/// Manually set the baud rate for serial, set to 0 to disable.
void set_baud_rate(uint32_t baud_rate);
/// Set the buffer size that's used for constructing log messages. Log messages longer than this will be truncated.
void set_tx_buffer_size(size_t tx_buffer_size);
/// Get the UART used by the logger.
UARTSelection get_uart() const;
/// Set the global log level. Note: Use the PI4HOME_LOG_LEVEL define to also remove the logs from the build.
void set_global_log_level(int log_level);
int get_global_log_level() const;
/// Set the log level of the specified tag.
void set_log_level(const std::string &tag, int log_level);
// ========== INTERNAL METHODS ==========
// (In most use cases you won't need these)
/// Set up this component.
void pre_setup();
uint32_t get_baud_rate() const;
void dump_config() override;
size_t get_tx_buffer_size() const;
int level_for(const char *tag);
/// Register a callback that will be called for every log message sent
void add_on_log_callback(std::function<void(int, const char *, const char *)> &&callback);
float get_setup_priority() const override;
int log_vprintf_(int level, const char *tag, const char *format, va_list args); // NOLINT
#ifdef USE_STORE_LOG_STR_IN_FLASH
int log_vprintf_(int level, const char *tag, const __FlashStringHelper *format, va_list args); // NOLINT
#endif
protected:
void log_message_(int level, const char *tag, char *msg, int ret);
uint32_t baud_rate_;
std::vector<char> tx_buffer_;
int global_log_level_{PI4HOME_LOG_LEVEL};
UARTSelection uart_{UART_SELECTION_UART0};
HardwareSerial *hw_serial_{nullptr};
struct LogLevelOverride {
std::string tag;
int level;
};
std::vector<LogLevelOverride> log_levels_;
CallbackManager<void(int, const char *, const char *)> log_callback_{};
};
extern LogComponent *global_log_component;
PI4HOME_NAMESPACE_END
#endif // PI4HOME_LOG_COMPONENT_H
| 30.777778 | 117 | 0.744284 | [
"vector"
] |
084e66b9fc98fcb1c4cba759263d9abae0313c28 | 5,493 | h | C | booster/booster/locale/boundary/boundary_point.h | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 388 | 2017-03-01T07:39:21.000Z | 2022-03-30T19:38:41.000Z | booster/booster/locale/boundary/boundary_point.h | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 81 | 2017-03-08T20:28:00.000Z | 2022-01-23T08:19:31.000Z | booster/booster/locale/boundary/boundary_point.h | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 127 | 2017-03-05T21:53:40.000Z | 2022-02-25T02:31:01.000Z | //
// Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOSTER_LOCALE_BOUNDARY_BOUNDARY_POINT_H_INCLUDED
#define BOOSTER_LOCALE_BOUNDARY_BOUNDARY_POINT_H_INCLUDED
#include <booster/locale/boundary/types.h>
namespace booster {
namespace locale {
namespace boundary {
///
/// \addtogroup boundary
/// @{
///
/// \brief This class represents a boundary point in the text.
///
/// It represents a pair - an iterator and a rule that defines this
/// point.
///
/// This type of object is dereference by the iterators of boundary_point_index. Using a rule()
/// member function you can get the reason why this specific boundary point was selected.
///
/// For example, When you use a sentence boundary analysis, the (rule() & \ref sentence_term) != 0 means
/// that this boundary point was selected because a sentence terminator (like .?!) was spotted
/// and the (rule() & \ref sentence_sep)!=0 means that a separator like line feed or carriage
/// return was observed.
///
/// \note
///
/// - The beginning of analyzed range is always considered a boundary point and its rule is always 0.
/// - when using a word boundary analysis the returned rule relates to a chunk of text preceding
/// this point.
///
/// \see
///
/// - \ref boundary_point_index
/// - \ref segment
/// - \ref segment_index
///
template<typename IteratorType>
class boundary_point {
public:
///
/// The type of the base iterator that iterates the original text
///
typedef IteratorType iterator_type;
///
/// Empty default constructor
///
boundary_point() : rule_(0) {}
///
/// Create a new boundary_point using iterator \p and a rule \a r
///
boundary_point(iterator_type p,rule_type r) :
iterator_(p),
rule_(r)
{
}
///
/// Set an new iterator value \a i
///
void iterator(iterator_type i)
{
iterator_ = i;
}
///
/// Set an new rule value \a r
///
void rule(rule_type r)
{
rule_ = r;
}
///
/// Fetch an iterator
///
iterator_type iterator() const
{
return iterator_;
}
///
/// Fetch a rule
///
rule_type rule() const
{
return rule_;
}
///
/// Check if two boundary points are the same
///
bool operator==(boundary_point const &other) const
{
return iterator_ == other.iterator_ && rule_ = other.rule_;
}
///
/// Check if two boundary points are different
///
bool operator!=(boundary_point const &other) const
{
return !(*this==other);
}
///
/// Check if the boundary point points to same location as an iterator \a other
///
bool operator==(iterator_type const &other) const
{
return iterator_ == other;
}
///
/// Check if the boundary point points to different location from an iterator \a other
///
bool operator!=(iterator_type const &other) const
{
return iterator_ != other;
}
///
/// Automatic cast to the iterator it represents
///
operator iterator_type ()const
{
return iterator_;
}
private:
iterator_type iterator_;
rule_type rule_;
};
///
/// Check if the boundary point \a r points to same location as an iterator \a l
///
template<typename BaseIterator>
bool operator==(BaseIterator const &l,boundary_point<BaseIterator> const &r)
{
return r==l;
}
///
/// Check if the boundary point \a r points to different location from an iterator \a l
///
template<typename BaseIterator>
bool operator!=(BaseIterator const &l,boundary_point<BaseIterator> const &r)
{
return r!=l;
}
/// @}
typedef boundary_point<std::string::const_iterator> sboundary_point; ///< convenience typedef
typedef boundary_point<std::wstring::const_iterator> wsboundary_point; ///< convenience typedef
#ifdef BOOSTER_HAS_CHAR16_T
typedef boundary_point<std::u16string::const_iterator> u16sboundary_point;///< convenience typedef
#endif
#ifdef BOOSTER_HAS_CHAR32_T
typedef boundary_point<std::u32string::const_iterator> u32sboundary_point;///< convenience typedef
#endif
typedef boundary_point<char const *> cboundary_point; ///< convenience typedef
typedef boundary_point<wchar_t const *> wcboundary_point; ///< convenience typedef
#ifdef BOOSTER_HAS_CHAR16_T
typedef boundary_point<char16_t const *> u16cboundary_point; ///< convenience typedef
#endif
#ifdef BOOSTER_HAS_CHAR32_T
typedef boundary_point<char32_t const *> u32cboundary_point; ///< convenience typedef
#endif
} // boundary
} // locale
} // boost
#endif
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| 29.853261 | 108 | 0.586383 | [
"object"
] |
08536c664c6aa76dd8c4cb45826804d8edc734cd | 56,447 | c | C | samtools/bam_consensus.c.pysam.c | ajcr/pysam | 527bb239ddaa799fce5ca005939d83805ae86e1d | [
"MIT"
] | null | null | null | samtools/bam_consensus.c.pysam.c | ajcr/pysam | 527bb239ddaa799fce5ca005939d83805ae86e1d | [
"MIT"
] | null | null | null | samtools/bam_consensus.c.pysam.c | ajcr/pysam | 527bb239ddaa799fce5ca005939d83805ae86e1d | [
"MIT"
] | null | null | null | #include "samtools.pysam.h"
/* bam_consensus.c -- consensus subcommand.
Copyright (C) 1998-2001,2003 Medical Research Council (Gap4/5 source)
Copyright (C) 2003-2005,2007-2022 Genome Research Ltd.
Author: James Bonfield <jkb@sanger.ac.uk>
The primary work here is GRL since 2021, under an MIT license.
Sections derived from Gap5, which include calculate_consensus_gap5()
associated functions, are mostly copyright Genome Research Limited from
2003 onwards. These were originally under a BSD license, but as GRL is
copyright holder these portions can be considered to also be under the
same MIT license below:
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. */
/*
* The Gap5 consensus algorithm was in turn derived from the earlier Gap4
* tool, developed by the Medical Research Council as part of the
* Staden Package. It is unsure how much of this source code is still
* extant, without deep review, but the license used was a compatible
* modified BSD license, included below.
*/
/*
Modified BSD license for any legacy components from the Staden Package:
Copyright (c) 2003 MEDICAL RESEARCH COUNCIL
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 MEDICAL RESEARCH COUNCIL, THE LABORATORY OF
MOLECULAR BIOLOGY 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.
*/
// FIXME: also use strand to spot possible basecalling errors.
// Specifically het calls where mods are predominantly on one
// strand. So maybe require + and - calls and check concordance
// before calling a het as confident. (Still call, but low qual?)
// TODO: call by kmers rather than individual bases? Or use kmers to skew
// quality at least. It can identify variants that are low quality due to
// neighbouring edits that aren't consistently correlated.
// TODO: pileup callback ought to know when it's the last in the region /
// chromosome. This means the caller code doesn't have to handle the
// termination phase and deduplicates the code. (Changing from
// one chr to the next is the same as ending the last.)
//
// TODO: track which reads contribute to multiple confirmed (HQ) differences
// vs which contribute to only one (LQ) difference. Correlated changes
// are more likely to be real. Ie consensus more of a path than solely
// isolated columns.
//
// Either that or a dummy "end of data" call is made to signify end to
// permit tidying up. Maybe add a "start of data" call too?
// Eg 50T 20A seems T/A het,
// but 30T+ 20T- 18A+ 2A- seems like a consistent A miscall on one strand
// only, while T is spread evenly across both strands.
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
#include <limits.h>
#include <float.h>
#include <ctype.h>
#include <htslib/sam.h>
#include "samtools.h"
#include "sam_opts.h"
#include "bam_plbuf.h"
#include "consensus_pileup.h"
#ifdef __SSE__
# include <xmmintrin.h>
#else
# define _mm_prefetch(a,b)
#endif
#ifndef MIN
# define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
# define MAX(a,b) ((a)>(b)?(a):(b))
#endif
// Minimum cutoff for storing mod data; => at least 10% chance
#define MOD_CUTOFF 0.46
enum format {
FASTQ,
FASTA,
PILEUP
};
typedef unsigned char uc;
typedef struct {
// User options
char *reg;
int use_qual;
int min_qual;
int adj_qual;
int use_mqual;
double scale_mqual;
int nm_adjust;
int nm_halo;
int sc_cost;
int low_mqual;
int high_mqual;
int min_depth;
double call_fract;
double het_fract;
int gap5;
enum format fmt;
int cons_cutoff;
int ambig;
int line_len;
int default_qual;
int het_only;
int all_bases;
int show_del;
int show_ins;
int excl_flags;
int incl_flags;
int min_mqual;
double P_het;
// Internal state
samFile *fp;
FILE *fp_out;
sam_hdr_t *h;
hts_idx_t *idx;
hts_itr_t *iter;
kstring_t ks_line;
kstring_t ks_ins_seq;
kstring_t ks_ins_qual;
int last_tid;
hts_pos_t last_pos;
} consensus_opts;
/* --------------------------------------------------------------------------
* A bayesian consensus algorithm that analyses the data to work out
* which hypothesis of pure A/C/G/T/absent and all combinations of two
* such bases meets the observations.
*
* This has its origins in Gap4 (homozygous) -> Gap5 (heterozygous)
* -> Crumble (tidied up to use htslib's pileup) -> here.
*
*/
#define CONS_DISCREP 4
#define CONS_ALL 15
#define CONS_MQUAL 16
typedef struct {
/* the most likely base call - we never call N here */
/* A=0, C=1, G=2, T=3, *=4 */
int call;
/* The most likely heterozygous base call */
/* Use "ACGT*"[het / 5] vs "ACGT*"[het % 5] for the combination */
int het_call;
/* Log-odds for het_call */
int het_logodd;
/* Single phred style call */
int phred;
/* Sequence depth */
int depth;
/* Discrepancy search score */
float discrep;
} consensus_t;
#define P_HET 1e-4
#define LOG10 2.30258509299404568401
#define TENOVERLOG10 4.34294481903251827652
#define TENLOG2OVERLOG10 3.0103
#ifdef __GNUC__
#define ALIGNED(x) __attribute((aligned(x)))
#else
#define ALIGNED(x)
#endif
static double prior[25] ALIGNED(16); /* Sum to 1.0 */
static double lprior15[15] ALIGNED(16); /* 15 combinations of {ACGT*} */
/* Precomputed matrices for the consensus algorithm */
static double pMM[101] ALIGNED(16);
static double p__[101] ALIGNED(16);
static double p_M[101] ALIGNED(16);
static double e_tab_a[1002] ALIGNED(16);
static double *e_tab = &e_tab_a[500];
static double e_tab2_a[1002] ALIGNED(16);
static double *e_tab2 = &e_tab2_a[500];
static double e_log[501] ALIGNED(16);
/*
* Lots of confusing matrix terms here, so some definitions will help.
*
* M = match base
* m = match pad
* _ = mismatch
* o = overcall
* u = undercall
*
* We need to distinguish between homozygous columns and heterozygous columns,
* done using a flat prior. This is implemented by treating every observation
* as coming from one of two alleles, giving us a 2D matrix of possibilities
* (the hypotheses) for each and every call (the observation).
*
* So pMM[] is the chance that given a call 'x' that it came from the
* x/x allele combination. Similarly p_o[] is the chance that call
* 'x' came from a mismatch (non-x) / overcall (consensus=*) combination.
*
* Examples with observation (call) C and * follows
*
* C | A C G T * * | A C G T *
* ----------------- -----------------
* A | __ _M __ __ o_ A | uu uu uu uu um
* C | _M MM _M _M oM C | uu uu uu uu um
* G | __ _M __ __ o_ G | uu uu uu uu um
* T | __ _M __ __ o_ T | uu uu uu uu um
* * | o_ oM o_ o_ oo * | um um um um mm
*
* In calculation terms, the _M is half __ and half MM, similarly o_ and um.
*
* Relative weights of substitution vs overcall vs undercall are governed on a
* per base basis using the P_OVER and P_UNDER scores (subst is
* 1-P_OVER-P_UNDER).
*
* The heterozygosity weight though is a per column calculation as we're
* trying to model whether the column is pure or mixed. Hence this is done
* once via a prior and has no affect on the individual matrix cells.
*/
static void consensus_init(double p_het) {
int i;
for (i = -500; i <= 500; i++)
e_tab[i] = exp(i);
for (i = -500; i <= 500; i++)
e_tab2[i] = exp(i/10.);
for (i = 0; i <= 500; i++)
e_log[i] = log(i);
// Heterozygous locations
for (i = 0; i < 25; i++)
prior[i] = p_het / 20;
prior[0] = prior[6] = prior[12] = prior[18] = prior[24] = (1-p_het)/5;
lprior15[0] = log(prior[0]);
lprior15[1] = log(prior[1]*2);
lprior15[2] = log(prior[2]*2);
lprior15[3] = log(prior[3]*2);
lprior15[4] = log(prior[4]*2);
lprior15[5] = log(prior[6]);
lprior15[6] = log(prior[7]*2);
lprior15[7] = log(prior[8]*2);
lprior15[8] = log(prior[9]*2);
lprior15[9] = log(prior[12]);
lprior15[10] = log(prior[13]*2);
lprior15[11] = log(prior[14]*2);
lprior15[12] = log(prior[18]);
lprior15[13] = log(prior[19]*2);
lprior15[14] = log(prior[24]);
// Rewrite as new form
for (i = 1; i < 101; i++) {
double prob = 1 - pow(10, -i / 10.0);
// May want to multiply all these by 5 so pMM[i] becomes close
// to -0 for most data. This makes the sums increment very slowly,
// keeping bit precision in the accumulator.
pMM[i] = log(prob/5);
p__[i] = log((1-prob)/20);
p_M[i] = log((exp(pMM[i]) + exp(p__[i]))/2);
}
pMM[0] = pMM[1];
p__[0] = p__[1];
p_M[0] = p_M[1];
}
static inline double fast_exp(double y) {
if (y >= -50 && y <= 50)
return e_tab2[(int)(y*10)];
if (y < -500)
y = -500;
if (y > 500)
y = 500;
return e_tab[(int)y];
}
/* Taylor (deg 3) implementation of the log */
static inline double fast_log2(double val)
{
// FP representation is exponent & mantissa, where
// value = 2^E * M.
// Hence log2(value) = log2(2^E * M)
// = log2(2^E)+ log2(M)
// = E + log2(M)
union { double d; uint64_t x; } u = {val};
const int E = ((u.x >> 52) & 2047) - 1024; // exponent E
// Initial log2(M) based on mantissa
u.x &= ~(2047LL << 52);
u.x += 1023LL << 52;
val = ((-1/3.) * u.d + 2) * u.d - 2/3.;
return E + val;
}
#define ph_log(x) (-TENLOG2OVERLOG10*fast_log2((x)))
int nins(const bam1_t *b){
int i, indel = 0;
uint32_t *cig = bam_get_cigar(b);
for (i = 0; i < b->core.n_cigar; i++) {
int op = bam_cigar_op(cig[i]);
if (op == BAM_CINS || op == BAM_CDEL)
indel += bam_cigar_oplen(cig[i]);
}
return indel;
}
// Return the local NM figure within halo (+/- HALO) of pos.
// This local NM is used as a way to modify MAPQ to get a localised MAPQ
// score via an adhoc fashion.
double nm_local(const pileup_t *p, const bam1_t *b, hts_pos_t pos) {
int *nm = (int *)p->cd;
if (!nm)
return 0;
pos -= b->core.pos;
if (pos < 0)
return nm[0];
if (pos >= b->core.l_qseq)
return nm[b->core.l_qseq-1];
return nm[pos] / 10.0;
}
/*
* Initialise a new sequence appearing in the pileup. We use this to
* precompute some metrics that we'll repeatedly use in the consensus
* caller; the localised NM score.
*
* We also directly amend the BAM record (which will be discarded later
* anyway) to modify qualities to account for local quality minima.
*
* Returns 0 (discard) or 1 (keep) on success, -1 on failure.
*/
int nm_init(void *client_data, samFile *fp, sam_hdr_t *h, pileup_t *p) {
consensus_opts *opts = (consensus_opts *)client_data;
if (!opts->use_mqual)
return 1;
const bam1_t *b = &p->b;
int qlen = b->core.l_qseq, i;
int *local_nm = calloc(qlen, sizeof(*local_nm));
if (!local_nm)
return -1;
p->cd = local_nm;
if (opts->adj_qual) {
#if 0
// Tweak by localised quality.
// Quality is reduced by a significant portion of the minimum quality
// in neighbouring bases, on the pretext that if the region is bad, then
// this base is bad even if it claims otherwise.
uint8_t *qual = bam_get_qual(b);
const int qhalo = 8; // 2?
int qmin = 50; // effectively caps PacBio qual too
for (i = 0; i < qlen && i < qhalo; i++) {
local_nm[i] = qual[i];
if (qmin > qual[i])
qmin = qual[i];
}
for (;i < qlen-qhalo; i++) {
//int t = (qual[i]*1 + 3*qmin)/4; // good on 60x
int t = (qual[i] + 5*qmin)/4; // good on 15x
local_nm[i] = t < qual[i] ? t : qual[i];
if (qmin > qual[i+qhalo])
qmin = qual[i+qhalo];
else if (qmin <= qual[i-qhalo]) {
int j;
qmin = 50;
for (j = i-qhalo+1; j <= i+qhalo; j++)
if (qmin > qual[j])
qmin = qual[j];
}
}
for (; i < qlen; i++) {
local_nm[i] = qual[i];
local_nm[i] = (local_nm[i] + 6*qmin)/4;
}
for (i = 0; i < qlen; i++) {
qual[i] = local_nm[i];
// Plus overall rescale.
// Lower becomes lower, very high becomes a little higher.
// Helps deep GIAB, but detrimental elsewhere. (What this really
// indicates is quality calibration differs per data set.)
// It's probably something best accounted for somewhere else.
//qual[i] = qual[i]*qual[i]/40+1;
}
memset(local_nm, 0, qlen * sizeof(*local_nm));
#else
// Skew local NM by qual vs min-qual delta
uint8_t *qual = bam_get_qual(b);
const int qhalo = 8; // 4
int qmin = 99;
for (i = 0; i < qlen && i < qhalo; i++) {
if (qmin > qual[i])
qmin = qual[i];
}
for (;i < qlen-qhalo; i++) {
int t = (qual[i] + 5*qmin)/4; // good on 15x
local_nm[i] += t < qual[i] ? (qual[i]-t) : 0;
if (qmin > qual[i+qhalo])
qmin = qual[i+qhalo];
else if (qmin <= qual[i-qhalo]) {
int j;
qmin = 99;
for (j = i-qhalo+1; j <= i+qhalo; j++)
if (qmin > qual[j])
qmin = qual[j];
}
}
for (; i < qlen; i++) {
int t = (qual[i] + 5*qmin)/4; // good on 15x
local_nm[i] += t < qual[i] ? (qual[i]-t) : 0;
}
#endif
}
// Adjust local_nm array by the number of edits within
// a defined region (pos +/- halo).
const int halo = opts->nm_halo;
const uint8_t *md = bam_aux_get(b, "MD");
if (!md)
return 1;
md = (const uint8_t *)bam_aux2Z(md);
// Handle cost of being near a soft-clip
uint32_t *cig = bam_get_cigar(b);
int ncig = b->core.n_cigar;
if ( (cig[0] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP ||
((cig[0] & BAM_CIGAR_MASK) == BAM_CHARD_CLIP && ncig > 1 &&
(cig[1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP)) {
for (i = 0; i < halo && i < qlen; i++)
local_nm[i]+=opts->sc_cost;
for (; i < halo*2 && i < qlen; i++)
local_nm[i]+=opts->sc_cost>>1;
}
if ( (cig[ncig-1] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP ||
((cig[ncig-1] & BAM_CIGAR_MASK) == BAM_CHARD_CLIP && ncig > 1 &&
(cig[ncig-2] & BAM_CIGAR_MASK) == BAM_CSOFT_CLIP)) {
for (i = qlen-1; i >= qlen-halo && i >= 0; i--)
local_nm[i]+=opts->sc_cost;
for (; i >= qlen-halo*2 && i >= 0; i--)
local_nm[i]+=opts->sc_cost>>1;
}
// Now iterate over MD tag
int pos = 0;
while (*md) {
if (isdigit(*md)) {
uint8_t *endptr;
long i = strtol((char *)md, (char **)&endptr, 10);
md = endptr;
pos += i;
continue;
}
// deletion.
// Should we bump local_nm here too? Maybe
if (*md == '^') {
while (*++md && !isdigit(*md))
continue;
continue;
}
// substitution
for (i = pos-halo*2 >= 0 ? pos-halo*2 : 0; i < pos-halo; i++)
local_nm[i]+=5;
for (; i < pos+halo && i < qlen; i++)
local_nm[i]+=10;
for (; i < pos+halo*2 && i < qlen; i++)
local_nm[i]+=5;
md++;
}
return 1;
}
static
int calculate_consensus_gap5(hts_pos_t pos, int flags, int depth,
pileup_t *plp, consensus_opts *opts,
consensus_t *cons, int default_qual) {
int i, j;
static int init_done =0;
static double q2p[101], mqual_pow[256];
double min_e_exp = DBL_MIN_EXP * log(2) + 1;
double S[15] ALIGNED(16) = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
double sumsC[6] = {0,0,0,0,0,0}; // A C G T * N
// Small hash on seq to check for uniqueness of surrounding bases.
// If it's frequent, then it's more likely to be correctly called than
// if it's rare.
// Helps a bit on deep data, especially with K2=3, but detrimental on
// shallow and (currently) quite a slow down.
//#define K2 2
#ifdef K2
int hashN[1<<(K2*4+2)] = {0};
int hash1[1<<2] = {0};
#endif
/* Map the 15 possible combinations to 1-base or 2-base encodings */
static int map_sing[15] ALIGNED(16) =
{0, 5, 5, 5, 5,
1, 5, 5, 5,
2, 5, 5,
3, 5,
4};
static int map_het[15] ALIGNED(16) =
{0, 1, 2, 3, 4,
6, 7, 8, 9,
12, 13, 14,
18, 19,
24};
if (!init_done) {
init_done = 1;
consensus_init(opts->P_het);
for (i = 0; i <= 100; i++) {
q2p[i] = pow(10, -i/10.0);
}
for (i = 0; i < 255; i++) {
//mqual_pow[i] = 1-pow(10, -(i+.01)/10.0);
mqual_pow[i] = 1-pow(10, -(i*.9)/10.0);
//mqual_pow[i] = 1-pow(10, -(i/3+.1)/10.0);
//mqual_pow[i] = 1-pow(10, -(i/2+.05)/10.0);
}
// unknown mqual
mqual_pow[255] = mqual_pow[10];
}
/* Initialise */
int counts[6] = {0};
/* Accumulate */
#ifdef K2
const pileup_t *ptmp = plp;
for (; ptmp; ptmp = ptmp->next) {
const pileup_t *p = ptmp;
if (p->qual < opts->min_qual)
continue;
int hb = 0;
#define _ 0
static int X[16] = {_,0,1,_,2,_,_,_,3,_,_,_,_,_,_,_};
#undef _
uint8_t *seq = bam_get_seq(&p->b);
int i, base1 = X[p->base4];
hash1[base1]++;
for (i = p->seq_offset-K2; i <= p->seq_offset+K2; i++) {
int base = i >= 0 && i < p->b.core.l_qseq ? X[bam_seqi(seq,i)] : _;
hb = (hb<<2)|base;
}
hashN[hb]++;
}
#endif
int td = depth; // original depth
depth = 0;
for (; plp; plp = plp->next) {
pileup_t *p = plp;
if (p->next)
_mm_prefetch(p->next, _MM_HINT_T0);
if (p->qual < opts->min_qual)
continue;
if (p->ref_skip)
continue;
#ifdef K2
int hb = 0;
#define _ 0
static int X[16] = {_,0,1,_,2,_,_,_,3,_,_,_,_,_,_,_};
int i, base1 = X[p->base4];
for (i = p->seq_offset-K2; i <= p->seq_offset+K2; i++) {
int base = i >= 0 && i < p->b.core.l_qseq ? X[bam_seqi(seq,i)] : _;
hb = (hb<<2)|base;
}
// fprintf(samtools_stderr, "%c: %d %d of %d\t%d %d\n", p->base, hashN[hb], hash1[base1], td, p->qual, p->qual * hashN[hb] / hash1[base1]);
#undef _
#endif
const bam1_t *b = &p->b;
uint8_t base = p->base4;
uint8_t *qual_arr = bam_get_qual(b);
uint8_t qual = p->qual;
//qual = qual*qual/40+1;
if (qual == 255 || (qual == 0 && *qual_arr == 255))
qual = default_qual;
#ifdef K2
//qual = qual * hashN[hb] / hash1[base1];
qual -= -TENOVERLOG10*log(hashN[hb] / (hash1[base1]+.1));
if (qual < 1)
qual = 1;
#endif
// =ACM GRSV TWYH KDBN *
static int L[32] = {
5,0,1,5, 2,5,5,5, 3,5,5,5, 5,5,5,5,
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
};
// convert from sam base to acgt*n order.
base = L[base];
double MM, __, _M, qe;
// Correction for mapping quality. Maybe speed up via lookups?
// Cannot nullify mapping quality completely. Lots of (true)
// SNPs means low mapping quality. (Ideally need to know
// hamming distance to next best location.)
if (flags & CONS_MQUAL) {
int mqual = b->core.qual;
if (opts->nm_adjust) {
mqual /= (nm_local(p, b, pos)+1);
mqual *= 1 + 2*(0.5-(td>30?30:td)/60.0); // depth fudge
}
// higher => call more; +FP, -FN
// lower => call less; -FP, +FN
mqual *= opts->scale_mqual;
// Drop these? They don't seem to ever help.
if (mqual < opts->low_mqual)
mqual = opts->low_mqual;
if (mqual > opts->high_mqual)
mqual = opts->high_mqual;
double _p = 1-q2p[qual];
double _m = mqual_pow[mqual];
qual = ph_log(1-(_m * _p + (1 - _m)/4)); // CURRENT
//qual = ph_log(1-_p*_m); // testing
//qual *= 6/sqrt(td);
}
/* Quality 0 should never be permitted as it breaks the maths */
if (qual < 1)
qual = 1;
__ = p__[qual]; // neither match
MM = pMM[qual] - __; // both match
_M = p_M[qual] - __; // one allele only (half match)
if (flags & CONS_DISCREP) {
qe = q2p[qual];
sumsC[base] += 1 - qe;
}
counts[base]++;
switch (base) {
case 0: // A
S[0] += MM;
S[1] += _M;
S[2] += _M;
S[3] += _M;
S[4] += _M;
break;
case 1: // C
S[1] += _M;
S[5] += MM;
S[6] += _M;
S[7] += _M;
S[8] += _M;
break;
case 2: // G
S[ 2] += _M;
S[ 6] += _M;
S[ 9] += MM;
S[10] += _M;
S[11] += _M;
break;
case 3: // T
S[ 3] += _M;
S[ 7] += _M;
S[10] += _M;
S[12] += MM;
S[13] += _M;
break;
case 4: // *
S[ 4] += _M;
S[ 8] += _M;
S[11] += _M;
S[13] += _M;
S[14] += MM;
break;
case 5: /* N => equal weight to all A,C,G,T but not a pad */
S[ 0] += MM;
S[ 1] += MM;
S[ 2] += MM;
S[ 3] += MM;
S[ 4] += _M;
S[ 5] += MM;
S[ 6] += MM;
S[ 7] += MM;
S[ 8] += _M;
S[ 9] += MM;
S[10] += MM;
S[11] += _M;
S[12] += MM;
S[13] += _M;
break;
}
depth++;
if (p->eof && p->cd) {
free(p->cd);
p->cd = NULL;
}
}
/* We've accumulated stats, so now we speculate on the consensus call */
double shift, max, max_het, norm[15];
int call = 0, het_call = 0;
double tot1 = 0, tot2 = 0;
/*
* Scale numbers so the maximum score is 0. This shift is essentially
* a multiplication in non-log scale to both numerator and denominator,
* so it cancels out. We do this to avoid calling exp(-large_num) and
* ending up with norm == 0 and hence a 0/0 error.
*
* Can also generate the base-call here too.
*/
shift = -DBL_MAX;
max = -DBL_MAX;
max_het = -DBL_MAX;
for (j = 0; j < 15; j++) {
S[j] += lprior15[j];
if (shift < S[j])
shift = S[j];
/* Only call pure AA, CC, GG, TT, ** for now */
if (j != 0 && j != 5 && j != 9 && j != 12 && j != 14) {
if (max_het < S[j]) {
max_het = S[j];
het_call = j;
}
continue;
}
if (max < S[j]) {
max = S[j];
call = j;
}
}
/*
* Shift and normalise.
* If call is, say, b we want p = b/(a+b+c+...+n), but then we do
* p/(1-p) later on and this has exceptions when p is very close
* to 1.
*
* Hence we compute b/(a+b+c+...+n - b) and
* rearrange (p/norm) / (1 - (p/norm)) to be p/norm2.
*/
for (j = 0; j < 15; j++) {
S[j] -= shift;
double e = fast_exp(S[j]);
S[j] = (S[j] > min_e_exp) ? e : DBL_MIN;
norm[j] = 0;
}
for (j = 0; j < 15; j++) {
norm[j] += tot1;
norm[14-j] += tot2;
tot1 += S[j];
tot2 += S[14-j];
}
/* And store result */
if (!depth || depth == counts[5] /* all N */) {
cons->call = 4; /* N */
cons->het_call = 0;
cons->het_logodd = 0;
cons->phred = 0;
cons->depth = 0;
cons->discrep = 0;
return 0;
}
cons->depth = depth;
/* Call */
if (norm[call] == 0) norm[call] = DBL_MIN;
// Approximation of phred for when S[call] ~= 1 and norm[call]
// is small. Otherwise we need the full calculation.
int ph;
if (S[call] == 1 && norm[call] < .01)
ph = ph_log(norm[call]) + .5;
else
ph = ph_log(1-S[call]/(norm[call]+S[call])) + .5;
cons->call = map_sing[call];
cons->phred = ph < 0 ? 0 : ph;
if (norm[het_call] == 0) norm[het_call] = DBL_MIN;
ph = TENLOG2OVERLOG10 * (fast_log2(S[het_call])
- fast_log2(norm[het_call])) + .5;
cons->het_call = map_het[het_call];
cons->het_logodd = ph;
/* Compute discrepancy score */
if (flags & CONS_DISCREP) {
double m = sumsC[0]+sumsC[1]+sumsC[2]+sumsC[3]+sumsC[4];
double c;
if (cons->het_logodd > 0)
c = sumsC[cons->het_call%5] + sumsC[cons->het_call/5];
else
c = sumsC[cons->call];
cons->discrep = (m-c)/sqrt(m);
}
return 0;
}
/* --------------------------------------------------------------------------
* Main processing logic
*/
static void dump_fastq(consensus_opts *opts,
const char *name,
const char *seq, size_t seq_l,
const char *qual, size_t qual_l) {
enum format fmt = opts->fmt;
int line_len = opts->line_len;
FILE *fp = opts->fp_out;
fprintf(fp, "%c%s\n", ">@"[fmt==FASTQ], name);
size_t i;
for (i = 0; i < seq_l; i += line_len)
fprintf(fp, "%.*s\n", (int)MIN(line_len, seq_l - i), seq+i);
if (fmt == FASTQ) {
fprintf(fp, "+\n");
for (i = 0; i < seq_l; i += line_len)
fprintf(fp, "%.*s\n", (int)MIN(line_len, seq_l - i), qual+i);
}
}
//---------------------------------------------------------------------------
/*
* Reads a single alignment record, using either the iterator
* or a direct sam_read1 call.
*/
static int readaln2(void *dat, samFile *fp, sam_hdr_t *h, bam1_t *b) {
consensus_opts *opts = (consensus_opts *)dat;
for (;;) {
int ret = opts->iter
? sam_itr_next(fp, opts->iter, b)
: sam_read1(fp, h, b);
if (ret < 0)
return ret;
// Apply hard filters
if (opts->incl_flags && !(b->core.flag & opts->incl_flags))
continue;
if (opts->excl_flags && (b->core.flag & opts->excl_flags))
continue;
if (b->core.qual < opts->min_mqual)
continue;
return ret;
}
}
/* --------------------------------------------------------------------------
* A simple summing algorithm, either pure base frequency, or by
* weighting them according to their quality values.
*
* This is crude, but easy to understand and fits with several
* standard pileup criteria (eg COG-UK / CLIMB Covid-19 seq project).
*
*
* call1 / score1 / depth1 is the highest scoring allele.
* call2 / score2 / depth2 is the second highest scoring allele.
*
* Het_fract: score2/score1
* Call_fract: score1 or score1+score2 over total score
* Min_depth: minimum total depth of utilised bases (depth1+depth2)
* Min_score: minimum total score of utilised bases (score1+score2)
*
* Eg het_fract 0.66, call_fract 0.75 and min_depth 10.
* 11A, 2C, 2G (14 total depth) is A.
* 9A, 2C, 2G (12 total depth) is N as depth(A) < 10.
* 11A, 5C, 5G (21 total depth) is N as 11/21 < 0.75 (call_fract)
*
*
* 6A, 5G, 1C (12 total depth) is AG het as depth(A)+depth(G) >= 10
* and 5/6 >= 0.66 and 11/12 >= 0.75.
*
* 6A, 5G, 4C (15 total depth) is N as (6+5)/15 < 0.75 (call_fract).
*
*
* Note for the purpose of deletions, a base/del has an ambiguity
* code of lower-case base (otherwise it is uppercase).
*/
static int calculate_consensus_simple(const pileup_t *plp,
consensus_opts *opts, int *qual) {
int i, min_qual = opts->min_qual;
// Map "seqi" nt16 to A,C,G,T compatibility with weights on pure bases.
// where seqi is A | (C<<1) | (G<<2) | (T<<3)
// * A C M G R S V T W Y H K D B N
static int seqi2A[16] = { 0,8,0,4, 0,4,0,2, 0,4,0,2, 0,2,0,1 };
static int seqi2C[16] = { 0,0,8,4, 0,0,4,2, 0,0,4,2, 0,0,2,1 };
static int seqi2G[16] = { 0,0,0,0, 8,4,4,1, 0,0,0,0, 4,2,2,1 };
static int seqi2T[16] = { 0,0,0,0, 0,0,0,0, 8,4,4,2, 8,2,2,1 };
// Ignore ambiguous bases in seq for now, so we don't treat R, Y, etc
// as part of one base and part another. Based on BAM seqi values.
// We also use freq[16] as "*" for gap.
int freq[17] = {0}; // base frequency, aka depth
int score[17] = {0}; // summation of base qualities
// Accumulate
for (; plp; plp = plp->next) {
const pileup_t *p = plp;
if (p->next)
_mm_prefetch(p->next, _MM_HINT_T0);
int q = p->qual;
if (q < min_qual)
// Should we still record these in freq[] somewhere so
// we can use them in the fracts?
// Difference between >= X% of high-qual bases calling Y
// and >= X% of all bases are high-quality Y calls.
continue;
//int b = p->is_del ? 16 : bam_seqi(bam_get_seq(&p->b), p->seq_offset);
int b = p->base4;
// Map ambiguity codes to one or more component bases.
if (b < 16) {
int Q = seqi2A[b] * (opts->use_qual ? q : 1);
freq[1] += Q?1:0;
score[1] += Q?Q:0;
Q = seqi2C[b] * (opts->use_qual ? q : 1);
freq[2] += Q?1:0;
score[2] += Q?Q:0;
Q = seqi2G[b] * (opts->use_qual ? q : 1);
freq[4] += Q?1:0;
score[4] += Q?Q:0;
Q = seqi2T[b] * (opts->use_qual ? q : 1);
freq[8] += Q?1:0;
score[8] += Q?Q:0;
} else { /* * */
freq[16] ++;
score[16]+=8 * (opts->use_qual ? q : 1);
}
}
// Total usable depth
int tscore = 0;
for (i = 0; i < 5; i++)
tscore += score[1<<i];
// Best and second best potential calls
int call1 = 15, call2 = 15;
int depth1 = 0, depth2 = 0;
int score1 = 0, score2 = 0;
for (i = 0; i < 5; i++) {
int c = 1<<i; // A C G T *
if (score1 < score[c]) {
depth2 = depth1;
score2 = score1;
call2 = call1;
depth1 = freq[c];
score1 = score[c];
call1 = c;
} else if (score2 < score[c]) {
depth2 = freq[c];
score2 = score[c];
call2 = c;
}
}
// Work out which best and second best are usable as a call
int used_score = score1;
int used_depth = depth1;
int used_base = call1;
if (score2 >= opts->het_fract * score1 && opts->ambig) {
used_base |= call2;
used_score += score2;
used_depth += depth2;
}
// N is too shallow, or insufficient proportion of total
if (used_depth < opts->min_depth ||
used_score < opts->call_fract * tscore) {
used_depth = 0;
// But note shallow gaps are still called gaps, not N, as
// we're still more confident there is no base than it is
// A, C, G or T.
used_base = call1 == 16 /*&& depth1 >= call_fract * depth*/
? 16 : 0; // * or N
}
// Our final call. "?" shouldn't be possible to generate
const char *het =
"NACMGRSVTWYHKDBN"
"*ac?g???t???????";
//printf("%c %d\n", het[used_base], used_depth);
if (qual)
*qual = used_base ? 100.0 * used_score / tscore : 0;
return het[used_base];
}
static int empty_pileup2(consensus_opts *opts, sam_hdr_t *h, int tid,
hts_pos_t start, hts_pos_t end) {
const char *name = sam_hdr_tid2name(h, tid);
hts_pos_t i;
int err = 0;
for (i = start; i < end; i++)
err |= fprintf(opts->fp_out, "%s\t%"PRIhts_pos"\t0\t0\tN\t0\t*\t*\n", name, i+1) < 0;
return err ? -1 : 0;
}
/*
* Returns 0 on success
* -1 on failure
*/
static int basic_pileup(void *cd, samFile *fp, sam_hdr_t *h, pileup_t *p,
int depth, hts_pos_t pos, int nth, int is_insert) {
unsigned char *qp, *cp;
char *rp;
int ref, cb, cq;
consensus_opts *opts = (consensus_opts *)cd;
int tid = p->b.core.tid;
// opts->show_ins=0;
// opts->show_del=1;
if (!opts->show_ins && nth)
return 0;
if (opts->iter) {
if (opts->iter->beg >= pos || opts->iter->end < pos)
return 0;
}
if (opts->all_bases) {
if (tid != opts->last_tid && opts->last_tid >= 0) {
hts_pos_t len = sam_hdr_tid2len(opts->h, opts->last_tid);
if (opts->iter)
len = MIN(opts->iter->end, len);
if (empty_pileup2(opts, opts->h, opts->last_tid, opts->last_pos,
len) < 0)
return -1;
if (tid >= 0) {
if (empty_pileup2(opts, opts->h, tid,
opts->iter ? opts->iter->beg : 0,
pos-1) < 0)
return -1;
}
}
if (opts->last_pos >= 0 && pos > opts->last_pos+1) {
if (empty_pileup2(opts, opts->h, p->b.core.tid, opts->last_pos,
pos-1) < 0)
return -1;
} else if (opts->last_pos < 0) {
if (empty_pileup2(opts, opts->h, p->b.core.tid,
opts->iter ? opts->iter->beg : 0, pos-1) < 0)
return -1;
}
}
if (opts->gap5) {
consensus_t cons;
calculate_consensus_gap5(pos, opts->use_mqual ? CONS_MQUAL : 0,
depth, p, opts, &cons, opts->default_qual);
if (cons.het_logodd > 0 && opts->ambig) {
cb = "AMRWa" // 5x5 matrix with ACGT* per row / col
"MCSYc"
"RSGKg"
"WYKTt"
"acgt*"[cons.het_call];
cq = cons.het_logodd;
} else{
cb = "ACGT*"[cons.call];
cq = cons.phred;
}
if (cq < opts->cons_cutoff && cb != '*') {
cb = 'N';
cq = 0;
}
} else {
cb = calculate_consensus_simple(p, opts, &cq);
}
if (cb < 0)
return -1;
if (!p)
return 0;
if (!opts->show_del && cb == '*')
return 0;
/* Ref, pos, nth, score, seq, qual */
kstring_t *ks = &opts->ks_line;
ks->l = 0;
ref = p->b.core.tid;
rp = (char *)sam_hdr_tid2name(h, ref);
int err = 0;
err |= kputs(rp, ks) < 0;
err |= kputc_('\t', ks) < 0;
err |= kputw(pos, ks) < 0;
err |= kputc_('\t', ks) < 0;
err |= kputw(nth, ks) < 0;
err |= kputc_('\t', ks) < 0;
err |= kputw(depth, ks) < 0;
err |= kputc_('\t', ks) < 0;
err |= kputc_(cb, ks) < 0;
err |= kputc_('\t', ks) < 0;
err |= kputw(cq, ks) < 0;
err |= kputc_('\t', ks) < 0;
if (err)
return -1;
/* Seq + qual at predetermined offsets */
if (ks_resize(ks, ks->l + depth*2 + 2) < 0)
return -1;
cp = (unsigned char *)ks->s + ks->l;
ks->l += depth*2 + 2;
qp = cp+depth+1;
for (; p; p = p->next) {
// Too tight a loop to help much, but some benefit still
if (p->next && p->next->next)
_mm_prefetch(p->next->next, _MM_HINT_T0);
if (p->b_is_rev) {
*cp++ = p->base == '*' ? '#' : tolower(p->base);
} else {
*cp++ = p->base;
}
*qp++ = MIN(p->qual,93) + '!';
}
*cp++ = '\t';
*qp++ = '\n';
if (fwrite(ks->s, 1, ks->l, opts->fp_out) != ks->l)
return -1;
opts->last_pos = pos;
opts->last_tid = tid;
return 0;
}
static int basic_fasta(void *cd, samFile *fp, sam_hdr_t *h, pileup_t *p,
int depth, hts_pos_t pos, int nth, int is_insert) {
int cb, cq;
consensus_opts *opts = (consensus_opts *)cd;
int tid = p->b.core.tid;
kstring_t *seq = &opts->ks_ins_seq;
kstring_t *qual = &opts->ks_ins_qual;
if (!opts->show_ins && nth)
return 0;
if (opts->iter) {
if (opts->iter->beg >= pos || opts->iter->end < pos)
return 0;
}
if (tid != opts->last_tid) {
if (opts->last_tid != -1) {
if (opts->all_bases) {
int i, N;
if (opts->iter) {
opts->last_pos = MAX(opts->last_pos, opts->iter->beg-1);
N = opts->iter->end;
} else {
N = INT_MAX;
}
N = MIN(N, sam_hdr_tid2len(opts->h, opts->last_tid))
- opts->last_pos;
if (N > 0) {
if (ks_expand(seq, N+1) < 0)
return -1;
if (ks_expand(qual, N+1) < 0)
return -1;
for (i = 0; i < N; i++) {
seq->s[seq->l++] = 'N';
qual->s[qual->l++] = '!';
}
seq->s[seq->l] = 0;
qual->s[qual->l] = 0;
}
}
dump_fastq(opts, sam_hdr_tid2name(opts->h, opts->last_tid),
seq->s, seq->l, qual->s, qual->l);
}
seq->l = 0; qual->l = 0;
opts->last_tid = tid;
// if (opts->all_bases)
// opts->last_pos = 0;
if (opts->iter)
opts->last_pos = opts->iter->beg;
else
opts->last_pos = opts->all_bases ? 0 : pos-1;
}
// share this with basic_pileup
if (opts->gap5) {
consensus_t cons;
calculate_consensus_gap5(pos, opts->use_mqual ? CONS_MQUAL : 0,
depth, p, opts, &cons, opts->default_qual);
if (cons.het_logodd > 0 && opts->ambig) {
cb = "AMRWa" // 5x5 matrix with ACGT* per row / col
"MCSYc"
"RSGKg"
"WYKTt"
"acgt*"[cons.het_call];
cq = cons.het_logodd;
} else{
cb = "ACGT*"[cons.call];
cq = cons.phred;
}
if (cq < opts->cons_cutoff && cb != '*' &&
cons.het_call % 5 != 4 && cons.het_call / 5 != 4) {
// het base/* keeps base or * as most likely pure call, else N.
// This is because we don't have a traditional way of representing
// base or not-base ambiguity.
cb = 'N';
cq = 0;
}
} else {
cb = calculate_consensus_simple(p, opts, &cq);
}
if (cb < 0)
return -1;
if (!p)
return 0;
if (!opts->show_del && cb == '*') {
opts->last_pos = pos;
opts->last_tid = tid;
return 0;
}
// end of share
// Append consensus base/qual to seqs
if (pos > opts->last_pos) {
if (opts->last_pos >= 0 || opts->all_bases) {
// FIXME: don't expand qual if fasta
if (ks_expand(seq, pos - opts->last_pos) < 0 ||
ks_expand(qual, pos - opts->last_pos) < 0)
return -1;
memset(seq->s + seq->l, 'N', pos - (opts->last_pos+1));
memset(qual->s + qual->l, '!', pos - (opts->last_pos+1));
seq->l += pos - (opts->last_pos+1);
qual->l += pos - (opts->last_pos+1);
}
}
if ((nth && opts->show_ins && cb != '*')
|| cb != '*' || (pos > opts->last_pos && opts->show_del)) {
int err = 0;
err |= kputc(cb, seq) < 0;
err |= kputc(MIN(cq, '~'-'!')+'!', qual) < 0;
if (err)
return -1;
}
opts->last_pos = pos;
opts->last_tid = tid;
return 0;
}
// END OF NEW PILEUP
//---------------------------------------------------------------------------
static void usage_exit(FILE *fp, int exit_status) {
fprintf(fp, "Usage: samtools consensus [options] <in.bam>\n");
fprintf(fp, "\nOptions:\n");
fprintf(fp, " -r, --region REG Limit query to REG. Requires an index\n");
fprintf(fp, " -f, --format FMT Output in format FASTA, FASTQ or PILEUP [FASTA]\n");
fprintf(fp, " -l, --line-len INT Wrap FASTA/Q at line length INT [70]\n");
fprintf(fp, " -o, --output FILE Output consensus to FILE\n");
fprintf(fp, " -m, --mode STR Switch consensus mode to \"simple\"/\"bayesian\" [bayesian]\n");
fprintf(fp, " -a Output all bases (start/end of reference)\n");
fprintf(fp, " --rf, --incl-flags STR|INT\n");
fprintf(fp, " Only include reads with any flag bit set [0]\n");
fprintf(fp, " --ff, --excl-flags STR|INT\n");
fprintf(fp, " Exclude reads with any flag bit set\n");
fprintf(fp, " [UNMAP,SECONDARY,QCFAIL,DUP]\n");
fprintf(fp, " --min-MQ INT Exclude reads with mapping quality below INT [0]\n");
fprintf(fp, " --show-del yes/no Whether to show deletion as \"*\" [no]\n");
fprintf(fp, " --show-ins yes/no Whether to show insertions [yes]\n");
fprintf(fp, " -A, --ambig Enable IUPAC ambiguity codes [off]\n");
fprintf(fp, "\nFor simple consensus mode:\n");
fprintf(fp, " -q, --(no-)use-qual Use quality values in calculation [off]\n");
fprintf(fp, " -c, --call-fract INT At least INT portion of bases must agree [0.75]\n");
fprintf(fp, " -d, --min-depth INT Minimum depth of INT [1]\n");
fprintf(fp, " -H, --het-fract INT Minimum fraction of 2nd-most to most common base [0.5]\n");
fprintf(fp, "\nFor default \"Bayesian\" consensus mode:\n");
fprintf(fp, " -C, --cutoff C Consensus cutoff quality C [10]\n");
fprintf(fp, " --(no-)adj-qual Modify quality with local minima [on]\n");
fprintf(fp, " --(no-)use-MQ Use mapping quality in calculation [on]\n");
fprintf(fp, " --(no-)adj-MQ Modify mapping quality by local NM [on]\n");
fprintf(fp, " --NM-halo INT Size of window for NM count in --adj-MQ [50]\n");
fprintf(fp, " --scale-MQ FLOAT Scale mapping quality by FLOAT [1.00]\n");
fprintf(fp, " --low-MQ INT Cap minimum mapping quality [1]\n");
fprintf(fp, " --high-MQ INT Cap maximum mapping quality [60]\n");
fprintf(fp, " --P-het FLOAT Probability of heterozygous site[%.1e]\n",
P_HET);
fprintf(fp, "\nGlobal options:\n");
sam_global_opt_help(fp, "-.---@-.");
samtools_exit(exit_status);
}
int main_consensus(int argc, char **argv) {
int c, ret = 1;
consensus_opts opts = {
// User options
.gap5 = 1,
.use_qual = 0,
.min_qual = 0,
.adj_qual = 1,
.use_mqual = 1,
.scale_mqual = 1.00,
.nm_adjust = 1,
.nm_halo = 50,
.sc_cost = 60,
.low_mqual = 1,
.high_mqual = 60,
.min_depth = 1,
.call_fract = 0.75,
.het_fract = 0.5,
.het_only = 0,
.fmt = FASTA,
.cons_cutoff = 10,
.ambig = 0,
.line_len = 70,
.default_qual = 10,
.all_bases = 0,
.show_del = 0,
.show_ins = 1,
.incl_flags = 0,
.excl_flags = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP,
.min_mqual = 0,
.P_het = P_HET,
// Internal state
.ks_line = {0,0},
.ks_ins_seq = {0,0},
.ks_ins_qual = {0,0},
.fp = NULL,
.fp_out = samtools_stdout,
.iter = NULL,
.idx = NULL,
.last_tid = -1,
.last_pos = -1,
};
sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
static const struct option lopts[] = {
SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', '-', '-', '@'),
{"use-qual", no_argument, NULL, 'q'},
{"no-use-qual", no_argument, NULL, 'q'+1000},
{"adj-qual", no_argument, NULL, 'q'+100},
{"no-adj-qual", no_argument, NULL, 'q'+101},
{"use-MQ", no_argument, NULL, 'm'+1000},
{"no-use-MQ", no_argument, NULL, 'm'+1001},
{"adj-MQ", no_argument, NULL, 'm'+100},
{"no-adj-MQ", no_argument, NULL, 'm'+101},
{"NM-halo", required_argument, NULL, 'h'+100},
{"SC-cost", required_argument, NULL, 'h'+101},
{"scale-MQ", required_argument, NULL, 14},
{"low-MQ" , required_argument, NULL, 9},
{"high-MQ", required_argument, NULL, 10},
{"min-depth", required_argument, NULL, 'd'},
{"call-fract", required_argument, NULL, 'c'},
{"het-fract", required_argument, NULL, 'H'},
{"region", required_argument, NULL, 'r'},
{"format", required_argument, NULL, 'f'},
{"cutoff", required_argument, NULL, 'C'},
{"ambig", no_argument, NULL, 'A'},
{"line-len", required_argument, NULL, 'l'},
{"default-qual", required_argument, NULL, 1},
{"het-only", no_argument, NULL, 6},
{"show-del", required_argument, NULL, 7},
{"show-ins", required_argument, NULL, 8},
{"output", required_argument, NULL, 'o'},
{"incl-flags", required_argument, NULL, 11},
{"rf", required_argument, NULL, 11},
{"excl-flags", required_argument, NULL, 12},
{"ff", required_argument, NULL, 12},
{"min-MQ", required_argument, NULL, 13},
{"P-het", required_argument, NULL, 15},
{"mode", required_argument, NULL, 'm'},
{NULL, 0, NULL, 0}
};
while ((c = getopt_long(argc, argv, "@:qd:c:H:r:5f:C:aAl:o:m:",
lopts, NULL)) >= 0) {
switch (c) {
case 'a': opts.all_bases++; break;
case 'q': opts.use_qual=1; break;
case 'q'+1000: opts.use_qual=0; break;
case 'm'+1000: opts.use_mqual=1; break;
case 'm'+1001: opts.use_mqual=0; break;
case 14: opts.scale_mqual = atof(optarg); break;
case 9: opts.low_mqual = atoi(optarg); break;
case 10: opts.high_mqual = atoi(optarg); break;
case 'd': opts.min_depth = atoi(optarg); break;
case 'c': opts.call_fract = atof(optarg); break;
case 'H': opts.het_fract = atof(optarg); break;
case 'r': opts.reg = optarg; break;
case 'C': opts.cons_cutoff = atoi(optarg); break;
case 'A': opts.ambig = 1; break;
case 1: opts.default_qual = atoi(optarg); break;
case 6: opts.het_only = 1; break;
case 7: opts.show_del = (*optarg == 'y' || *optarg == 'Y'); break;
case 8: opts.show_ins = (*optarg == 'y' || *optarg == 'Y'); break;
case 13: opts.min_mqual = atoi(optarg); break;
case 15: opts.P_het = atof(optarg); break;
case 'q'+100: opts.adj_qual = 1; break;
case 'q'+101: opts.adj_qual = 0; break;
case 'm'+100: opts.nm_adjust = 1; break;
case 'm'+101: opts.nm_adjust = 0; break;
case 'h'+100: opts.nm_halo = atoi(optarg); break;
case 'h'+101: opts.sc_cost = atoi(optarg); break;
case 'm': // mode
if (strcasecmp(optarg, "simple") == 0) {
opts.gap5 = 0;
} else if (strcasecmp(optarg, "bayesian") == 0) {
opts.gap5 = 1;
} else {
fprintf(samtools_stderr, "Unknown mode %s\n", optarg);
return 1;
}
break;
case 'l':
if ((opts.line_len = atoi(optarg)) <= 0)
opts.line_len = INT_MAX;
break;
case 'f':
if (strcasecmp(optarg, "fasta") == 0) {
opts.fmt = FASTA;
} else if (strcasecmp(optarg, "fastq") == 0) {
opts.fmt = FASTQ;
} else if (strcasecmp(optarg, "pileup") == 0) {
opts.fmt = PILEUP;
} else {
fprintf(samtools_stderr, "Unknown format %s\n", optarg);
return 1;
}
break;
case 'o':
if (!(opts.fp_out = fopen(optarg, "w"))) {
perror(optarg);
return 1;
}
break;
case 11:
if ((opts.incl_flags = bam_str2flag(optarg)) < 0) {
print_error("consensus", "could not parse --rf %s", optarg);
return 1;
}
break;
case 12:
if ((opts.excl_flags = bam_str2flag(optarg)) < 0) {
print_error("consensus", "could not parse --ff %s", optarg);
return 1;
}
break;
default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
/* else fall-through */
case '?':
usage_exit(samtools_stderr, EXIT_FAILURE);
}
}
if (argc != optind+1) {
if (argc == optind) usage_exit(samtools_stdout, EXIT_SUCCESS);
else usage_exit(samtools_stderr, EXIT_FAILURE);
}
opts.fp = sam_open_format(argv[optind], "r", &ga.in);
if (opts.fp == NULL) {
print_error_errno("consensus", "Cannot open input file \"%s\"",
argv[optind]);
goto err;
}
if (ga.nthreads > 0)
hts_set_threads(opts.fp, ga.nthreads);
if (hts_set_opt(opts.fp, CRAM_OPT_DECODE_MD, 0)) {
fprintf(samtools_stderr, "Failed to set CRAM_OPT_DECODE_MD value\n");
goto err;
}
if (!(opts.h = sam_hdr_read(opts.fp))) {
fprintf(samtools_stderr, "Failed to read header for \"%s\"\n", argv[optind]);
goto err;
}
if (opts.reg) {
opts.idx = sam_index_load(opts.fp, argv[optind]);
if (!opts.idx) {
print_error("consensus", "Cannot load index for input file \"%s\"",
argv[optind]);
goto err;
}
opts.iter = sam_itr_querys(opts.idx, opts.h, opts.reg);
if (!opts.iter) {
print_error("consensus", "Failed to parse region \"%s\"",
opts.reg);
goto err;
}
}
if (opts.fmt == PILEUP) {
if (pileup_loop(opts.fp, opts.h, readaln2, opts.gap5 ? nm_init : NULL,
basic_pileup, &opts) < 0)
goto err;
if (opts.all_bases) {
int tid = opts.iter ? opts.iter->tid : opts.last_tid;
int len = sam_hdr_tid2len(opts.h, tid);
int pos = opts.last_pos;
if (opts.iter) {
len = MIN(opts.iter->end, len);
pos = MAX(opts.iter->beg, pos);
}
if (empty_pileup2(&opts, opts.h, tid, pos, len) < 0)
goto err;
}
} else {
if (pileup_loop(opts.fp, opts.h, readaln2, opts.gap5 ? nm_init : NULL,
basic_fasta,
&opts) < 0)
goto err;
if (opts.all_bases) {
// fill out terminator
int tid = opts.iter ? opts.iter->tid : opts.last_tid;
int len = sam_hdr_tid2len(opts.h, tid);
int pos = opts.last_pos;
if (opts.iter) {
len = MIN(opts.iter->end, len);
pos = MAX(opts.iter->beg, pos);
opts.last_tid = opts.iter->tid;
}
if (pos < len) {
if (ks_expand(&opts.ks_ins_seq, len-pos+1) < 0)
goto err;
if (ks_expand(&opts.ks_ins_qual, len-pos+1) < 0)
goto err;
while (pos++ < len) {
opts.ks_ins_seq.s [opts.ks_ins_seq.l++] = 'N';
opts.ks_ins_qual.s[opts.ks_ins_qual.l++] = '!';
}
opts.ks_ins_seq.s [opts.ks_ins_seq.l] = 0;
opts.ks_ins_qual.s[opts.ks_ins_qual.l] = 0;
}
}
if (opts.last_tid >= 0)
dump_fastq(&opts, sam_hdr_tid2name(opts.h, opts.last_tid),
opts.ks_ins_seq.s, opts.ks_ins_seq.l,
opts.ks_ins_qual.s, opts.ks_ins_qual.l);
// if (consensus_loop(&opts) < 0) {
// print_error_errno("consensus", "Failed");
// goto err;
// }
}
ret = 0;
err:
if (opts.iter)
hts_itr_destroy(opts.iter);
if (opts.idx)
hts_idx_destroy(opts.idx);
if (opts.fp && sam_close(opts.fp) < 0) {
print_error_errno("consensus", "Closing input file \"%s\"",
argv[optind]);
ret = 1;
}
if (opts.h)
sam_hdr_destroy(opts.h);
sam_global_args_free(&ga);
if (opts.fp_out && opts.fp_out != samtools_stdout)
ret |= fclose(opts.fp_out) != 0;
else
ret |= fflush(samtools_stdout) != 0;
ks_free(&opts.ks_line);
ks_free(&opts.ks_ins_seq);
ks_free(&opts.ks_ins_qual);
if (ret)
print_error("consensus", "failed");
return ret;
}
| 32.913703 | 154 | 0.511648 | [
"model"
] |
0858839c87aed2b826dbb6d62a83eee95c6d9b3c | 658 | h | C | src/editor/EntityTree.h | loafofpiecrust/lfant | a38826e325a50dffb5d030d71abcd58de59e8389 | [
"Apache-2.0"
] | 4 | 2017-03-06T16:59:27.000Z | 2021-07-23T12:57:07.000Z | src/editor/EntityTree.h | loafofpiecrust/lfant | a38826e325a50dffb5d030d71abcd58de59e8389 | [
"Apache-2.0"
] | null | null | null | src/editor/EntityTree.h | loafofpiecrust/lfant | a38826e325a50dffb5d030d71abcd58de59e8389 | [
"Apache-2.0"
] | null | null | null | #ifndef LFANT_EDITOR_ENTITYTREE_H
#define LFANT_EDITOR_ENTITYTREE_H
#include <lfant/Entity.h>
#include <QTreeWidget>
namespace lfant {
namespace editor {
class EntityTree : public QTreeWidget, public Object
{
Q_OBJECT
public:
explicit EntityTree(QWidget *parent = 0);
signals:
void EntityChanged(lfant::Entity*);
public slots:
void ItemChanged(QTreeWidgetItem* selected, QTreeWidgetItem* deselected);
void SetGame(lfant::Game* game);
private:
void EntityAdded(Entity* ent);
lfant::Game* game = nullptr;
void AddEntity(Entity* ent, QTreeWidgetItem* parent);
};
} // namespace editor
} // namespace lfant
#endif // LFANT_EDITOR_ENTITYTREE_H
| 18.277778 | 74 | 0.765957 | [
"object"
] |
085c5a50b3aa1b7531dfd7c837bcc204f4847d42 | 10,368 | h | C | src/Configuration.h | Nikitosh/Vehicles_SVO_Case | 505205ddbd533617e353dce9166490741a5c013a | [
"MIT"
] | null | null | null | src/Configuration.h | Nikitosh/Vehicles_SVO_Case | 505205ddbd533617e353dce9166490741a5c013a | [
"MIT"
] | null | null | null | src/Configuration.h | Nikitosh/Vehicles_SVO_Case | 505205ddbd533617e353dce9166490741a5c013a | [
"MIT"
] | null | null | null | const string AIRCRAFT_CLASS_COLUMN = "Aircraft_Class";
const string MAX_SEATS_COLUMN = "Max_Seats";
const string JET_BRIDGE_HANDLING_TIME_COLUMN = "JetBridge_Handling_Time";
const string AWAY_HANDLING_TIME_COLUMN = "Away_Handling_Time";
const string VALUE_COLUMN = "Value";
const string AIRCRAFT_STAND_COLUMN = "Aircraft_Stand";
const string JET_BRIDGE_ON_ARRIVAL_COLUMN = "JetBridge_on_Arrival";
const string JET_BRIDGE_ON_DEPARTURE_COLUMN = "JetBridge_on_Departure";
const string T1_COLUMN = "1";
const string T2_COLUMN = "2";
const string T3_COLUMN = "3";
const string T4_COLUMN = "4";
const string T5_COLUMN = "5";
const string TERMINAL_COLUMN = "Terminal";
const string TAXIING_TIME_COLUMN = "Taxiing_Time";
const string AD_COLUMN = "flight_AD";
const string DATETIME_COLUMN = "flight_datetime";
const string AL_CODE_COLUMN = "flight_AL_Synchron_code";
const string FLIGHT_NUMBER_COLUMN = "flight_number";
const string FLIGHT_TYPE_COLUMN = "flight_ID";
const string FLIGHT_TERMINAL_COLUMN = "flight_terminal_#";
const string FLIGHT_AP_COLUMN = "flight_AP";
const string AC_COLUMN = "flight_AC_Synchron_code";
const string FLIGHT_CAPACITY_COLUMN = "flight_AC_PAX_capacity_total";
const string FLIGHT_PASSENGERS_COLUMN = "flight_PAX";
const string BUS_COST_PER_MINUTE_ROW = "Bus_Cost_per_Minute";
const string AWAY_AIRCRAFT_STAND_COST_PER_MINUTE_ROW = "Away_Aircraft_Stand_Cost_per_Minute";
const string JET_BRIDGE_AIRCRAFT_STAND_COST_PER_MINUTE_ROW = "JetBridge_Aircraft_Stand_Cost_per_Minute";
const string AIRCRAFT_TAXIING_COST_PER_MINUTE_ROW = "Aircraft_Taxiing_Cost_per_Minute";
const string WIDE_BODY_CLASS = "Wide_Body";
const int BUS_CAPACITY = 80;
// Stores the whole configuration for original problem.
struct Configuration {
// Handling times: <jet bridge, away>.
unordered_map<string, pair<int, int>> aircraftClassHandlingTime;
vector<pair<int, string>> maxSeatsClasses;
int busCost;
int parkingCostAway;
int parkingCostJetBridge;
int taxiingCost;
vector<Stand> stands;
vector<Flight> flights;
vector<vector<int>> costs;
vector<vector<pair<int, int>>> sortedCosts;
vector<vector<Event>> handlingSegments;
vector<vector<int>> neighboringStands;
void clear() {
for (Stand& stand : stands)
stand.clear();
}
string getAircraftClassByCapacity(int capacity) {
return lower_bound(maxSeatsClasses.begin(), maxSeatsClasses.end(), pair<int, string>(capacity, ""))->second;
}
bool canFit(Flight& flight, int standIndex) {
int flightId = flight.id;
Event handlingSegment = handlingSegments[flightId][standIndex];
if (!stands[standIndex].canFit(handlingSegment, /*isWide=*/false))
return false;
if (flight.isWide) {
for (int neighboringStandId : neighboringStands[standIndex])
if (!stands[neighboringStandId].canFit(handlingSegment, /*isWide=*/true))
return false;
}
return true;
}
void adjustFlights() {
for (auto& flight : flights) {
flight.aircraftClass = getAircraftClassByCapacity(flight.capacity);
flight.isWide = (flight.aircraftClass == WIDE_BODY_CLASS);
flight.handlingTimes = aircraftClassHandlingTime[flight.aircraftClass];
}
int minTimestamp = min_element(flights.begin(), flights.end(),
[](const Flight &f1, const Flight &f2) { return f1.timestamp < f2.timestamp; })->timestamp;
int maxTaxiingTime = max_element(stands.begin(), stands.end(),
[](const Stand &s1, const Stand &s2) { return s1.taxiingTime < s2.taxiingTime; })->taxiingTime;
int maxHandlingTime = numeric_limits<int>::min();
for (const auto& handlingTime : aircraftClassHandlingTime)
maxHandlingTime = max(maxHandlingTime, max(handlingTime.second.first, handlingTime.second.second));
for (auto& flight: flights)
flight.timestamp += maxTaxiingTime + maxHandlingTime - minTimestamp;
}
int calculateCost(int flightIndex, int standIndex, Event& handlingSegment) {
Flight& flight = flights[flightIndex];
Stand& stand = stands[standIndex];
int cost = stand.taxiingTime * taxiingCost;
char jetBridge = (flight.adType == 'A' ? stand.jetBridgeArrival : stand.jetBridgeDeparture);
int parkingCost = (jetBridge == 'N' ? parkingCostAway : parkingCostJetBridge);
int handlingTime = 0;
if (jetBridge == flight.idType && flight.terminal == stand.terminal) {
handlingTime = flight.handlingTimes.first;
} else {
handlingTime = flight.handlingTimes.second;
cost += (flight.passengers + BUS_CAPACITY - 1) / BUS_CAPACITY * busCost
* stand.busRideTimeToTerminal[flight.terminal - 1];
}
cost += handlingTime * parkingCost;
handlingSegment = flight.getHandlingSegment(stand.taxiingTime, handlingTime);
return cost;
}
// Precalculates all the costs.
void calculateCosts() {
costs.resize(flights.size(), vector<int>(stands.size()));
sortedCosts.resize(flights.size(), vector<pair<int, int>>(stands.size()));
handlingSegments.resize(flights.size(), vector<Event>(stands.size()));
for (int i = 0; i < (int) flights.size(); i++) {
for (int j = 0; j < (int) stands.size(); j++) {
costs[i][j] = calculateCost(i, j, handlingSegments[i][j]);
sortedCosts[i][j] = make_pair(costs[i][j], j);
}
sort(sortedCosts[i].begin(), sortedCosts[i].end());
}
}
// Precalculates neighboring stands.
void calculateNeighboringStands() {
neighboringStands.resize(stands.size());
for (int i = 0; i < (int) stands.size(); i++) {
if (stands[i].jetBridgeArrival == 'N')
continue;
for (int j = i - 1; j <= i + 1; j += 2)
if (j >= 0 && j < (int) stands.size() && abs(stands[i].id - stands[j].id) == 1
&& stands[i].terminal == stands[j].terminal
&& stands[j].jetBridgeArrival != 'N') {
neighboringStands[i].push_back(j);
}
}
}
// Reads all configurations from given paths.
static Configuration readConfiguration(const string& aircraftClassesPath,
const string& aircraftStandsPath,
const string& handlingRatesPath,
const string& handlingTimePath,
const string& timetablePath) {
Configuration config;
config.aircraftClassHandlingTime = readHandlingTime(handlingTimePath);
config.maxSeatsClasses = readAircraftClasses(aircraftClassesPath);
vector<int> handlingRates = readHandlingRates(handlingRatesPath);
config.busCost = handlingRates[0];
config.parkingCostAway = handlingRates[1];
config.parkingCostJetBridge = handlingRates[2];
config.taxiingCost = handlingRates[3];
config.stands = readAircraftStands(aircraftStandsPath);
config.flights = readTimetable(timetablePath);
config.adjustFlights();
config.calculateCosts();
config.calculateNeighboringStands();
return config;
}
static unordered_map<string, pair<int, int>> readHandlingTime(const string& handlingTimePath) {
rapidcsv::Document doc(handlingTimePath);
int rows = (int) doc.GetRowCount();
unordered_map<string, pair<int, int>> aircraftClassHandlingTime;
for (int i = 0; i < rows; i++) {
string aircraftClass = doc.GetCell<string>(AIRCRAFT_CLASS_COLUMN, i);
int handlingTimeJetBridge = doc.GetCell<int>(JET_BRIDGE_HANDLING_TIME_COLUMN, i);
int handlingTimeAway = doc.GetCell<int>(AWAY_HANDLING_TIME_COLUMN, i);
aircraftClassHandlingTime[aircraftClass] = {handlingTimeJetBridge, handlingTimeAway};
}
return aircraftClassHandlingTime;
}
static vector<pair<int, string>> readAircraftClasses(const string& aircraftClassesPath) {
rapidcsv::Document doc(aircraftClassesPath);
int rows = (int) doc.GetRowCount();
vector<pair<int, string>> maxSeatsClasses;
for (int i = 0; i < rows; i++) {
string aircraftClass = doc.GetCell<string>(AIRCRAFT_CLASS_COLUMN, i);
int maxSeats = doc.GetCell<int>(MAX_SEATS_COLUMN, i);
maxSeatsClasses.push_back({maxSeats, aircraftClass});
}
sort(maxSeatsClasses.begin(), maxSeatsClasses.end());
return maxSeatsClasses;
}
static vector<int> readHandlingRates(const string& handlingRatesPath) {
rapidcsv::Document doc(handlingRatesPath, rapidcsv::LabelParams(0, 0));
int busCost = doc.GetCell<int>(VALUE_COLUMN, BUS_COST_PER_MINUTE_ROW);
int parkingCostAway = doc.GetCell<int>(VALUE_COLUMN, AWAY_AIRCRAFT_STAND_COST_PER_MINUTE_ROW);
int parkingCostJetBridge = doc.GetCell<int>(VALUE_COLUMN, JET_BRIDGE_AIRCRAFT_STAND_COST_PER_MINUTE_ROW);
int taxiingCost = doc.GetCell<int>(VALUE_COLUMN, AIRCRAFT_TAXIING_COST_PER_MINUTE_ROW);
return vector<int>({busCost, parkingCostAway, parkingCostJetBridge, taxiingCost});
}
static vector<Stand> readAircraftStands(const string& aircraftStandsPath) {
rapidcsv::Document doc(aircraftStandsPath);
int rows = (int) doc.GetRowCount();
vector<Stand> stands;
for (int i = 0; i < rows; i++) {
stands.push_back(Stand{
.id = doc.GetCell<int>(AIRCRAFT_STAND_COLUMN, i),
.jetBridgeArrival = doc.GetCell<char>(JET_BRIDGE_ON_ARRIVAL_COLUMN, i),
.jetBridgeDeparture = doc.GetCell<char>(JET_BRIDGE_ON_DEPARTURE_COLUMN, i),
.busRideTimeToTerminal = {
doc.GetCell<int>(T1_COLUMN, i),
doc.GetCell<int>(T2_COLUMN, i),
doc.GetCell<int>(T3_COLUMN, i),
doc.GetCell<int>(T4_COLUMN, i),
doc.GetCell<int>(T5_COLUMN, i)
},
.terminal = doc.GetCell<int>(TERMINAL_COLUMN, i,
[](const string& t, int& val) { val = t.empty() ? 0 : stoi(t); }),
.taxiingTime = doc.GetCell<int>(TAXIING_TIME_COLUMN, i),
.occupiedSegments = {},
.wideOccupiedSegments = {}
});
}
return stands;
}
static vector<Flight> readTimetable(const string& timetablePath) {
rapidcsv::Document doc(timetablePath);
int rows = (int) doc.GetRowCount();
vector<Flight> flights;
for (int i = 0; i < rows; i++) {
flights.push_back(Flight{
.id = i,
.adType = doc.GetCell<char>(AD_COLUMN, i),
.timestamp = doc.GetCell<int>(DATETIME_COLUMN, i,
[](const string& t, int& val) {
val = parseTimestamp(t);
}),
.airlines = doc.GetCell<string>(AL_CODE_COLUMN, i),
.number = doc.GetCell<int>(FLIGHT_NUMBER_COLUMN, i),
.idType = doc.GetCell<char>(FLIGHT_TYPE_COLUMN, i),
.terminal = doc.GetCell<int>(FLIGHT_TERMINAL_COLUMN, i),
.capacity = doc.GetCell<int>(FLIGHT_CAPACITY_COLUMN, i),
.passengers = doc.GetCell<int>(FLIGHT_PASSENGERS_COLUMN, i),
.aircraftClass = "",
.isWide = false,
.handlingTimes = {0, 0},
.adjustedTimestamp = 0
});
}
return flights;
}
};
| 41.638554 | 110 | 0.723476 | [
"vector"
] |
085f9f7185b872ee11d521976fc5fcfcda00f1a9 | 5,737 | h | C | src/Core/Datatypes/Legacy/Field/FieldIndex.h | mhansen1/SCIRun | 9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba | [
"Unlicense"
] | 1 | 2019-05-30T06:00:15.000Z | 2019-05-30T06:00:15.000Z | src/Core/Datatypes/Legacy/Field/FieldIndex.h | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | src/Core/Datatypes/Legacy/Field/FieldIndex.h | manual123/SCIRun | 3816b1dc4ebd0c5bd4539b7e50e08592acdac903 | [
"MIT"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
///
///@author
/// Marty Cole
/// Department of Computer Science
/// University of Utah
///@date January 2001
///
///
#ifndef Datatypes_FieldIndex_h
#define Datatypes_FieldIndex_h
#include <Core/Utils/Legacy/TypeDescription.h>
#include <Core/Datatypes/Legacy/Base/TypeName.h>
#include <vector>
namespace SCIRun {
/// Base type for index types.
template <class T>
class FieldIndexBase {
public:
typedef T value_type;
FieldIndexBase(T i) :
index_(i) {}
/// Required interface for an Index.
operator T const &() const { return index_; }
std::ostream& str_render(std::ostream& os) const {
os << index_;
return os;
}
T index_;
};
/// Distinct type for node index.
template <class T>
struct NodeIndex : public FieldIndexBase<T> {
NodeIndex() :
FieldIndexBase<T>(0) {}
NodeIndex(T index) :
FieldIndexBase<T>(index) {}
};
/// Distinct type for edge index.
template <class T>
struct EdgeIndex : public FieldIndexBase<T> {
EdgeIndex() :
FieldIndexBase<T>(0) {}
EdgeIndex(T index) :
FieldIndexBase<T>(index) {}
};
/// Distinct type for face index.
template <class T>
struct FaceIndex : public FieldIndexBase<T> {
FaceIndex() :
FieldIndexBase<T>(0) {}
FaceIndex(T index) :
FieldIndexBase<T>(index) {}
};
/// Distinct type for cell index.
template <class T>
struct CellIndex : public FieldIndexBase<T> {
CellIndex() :
FieldIndexBase<T>(0) {}
CellIndex(T index) :
FieldIndexBase<T>(index) {}
};
// the following operators only exist to get the generic interpolate to compile
//
template <class T>
std::vector<CellIndex<T> >
operator*(const std::vector<CellIndex<T> >& r, double &) {
ASSERTFAIL("FieldIndex.h Bogus operator");
return r;
}
template <class T>
std::vector<CellIndex<T> >
operator+=(const std::vector<CellIndex<T> >& l, const std::vector<CellIndex<T> >& r) {
ASSERTFAIL("FieldIndex.h Bogus operator");
return l;
}
template <class T>
const TypeDescription* get_type_description(NodeIndex<T>*)
{
static TypeDescription* td = 0;
if(!td){
const TypeDescription *sub = get_type_description(static_cast<T*>(0));
TypeDescription::td_vec *subs = new TypeDescription::td_vec(1);
(*subs)[0] = sub;
td = new TypeDescription("NodeIndex", subs, __FILE__, "SCIRun");
}
return td;
}
template <class T>
const TypeDescription* get_type_description(EdgeIndex<T>*)
{
static TypeDescription* td = 0;
if(!td){
const TypeDescription *sub = get_type_description(static_cast<T*>(0));
TypeDescription::td_vec *subs = new TypeDescription::td_vec(1);
(*subs)[0] = sub;
td = new TypeDescription("EdgeIndex", subs, __FILE__, "SCIRun");
}
return td;
}
template <class T>
const TypeDescription* get_type_description(FaceIndex<T>*)
{
static TypeDescription* td = 0;
if(!td){
const TypeDescription *sub = get_type_description(static_cast<T*>(0));
TypeDescription::td_vec *subs = new TypeDescription::td_vec(1);
(*subs)[0] = sub;
td = new TypeDescription("FaceIndex", subs, __FILE__, "SCIRun");
}
return td;
}
template <class T>
const TypeDescription* get_type_description(CellIndex<T>*)
{
static TypeDescription* td = 0;
if(!td){
const TypeDescription *sub = get_type_description(static_cast<T*>(0));
TypeDescription::td_vec *subs = new TypeDescription::td_vec(1);
(*subs)[0] = sub;
td = new TypeDescription("CellIndex", subs, __FILE__, "SCIRun");
}
return td;
}
#define FIELDINDEXBASE_VERSION 1
template<class T>
void Pio(Piostream& stream, FieldIndexBase<T>& data)
{
Pio(stream, data.index_);
}
template <class T> const std::string find_type_name(NodeIndex<T> *)
{
static const std::string name = TypeNameGenerator::make_template_id("NodeIndex", find_type_name(static_cast<T*>(0)));
return name;
}
template <class T> const std::string find_type_name(EdgeIndex<T> *)
{
static const std::string name = TypeNameGenerator::make_template_id("EdgeIndex", find_type_name(static_cast<T*>(0)));
return name;
}
template <class T> const std::string find_type_name(FaceIndex<T> *)
{
static const std::string name = TypeNameGenerator::make_template_id("FaceIndex", find_type_name(static_cast<T*>(0)));
return name;
}
template <class T> const std::string find_type_name(CellIndex<T> *)
{
static const std::string name = TypeNameGenerator::make_template_id("CellIndex", find_type_name(static_cast<T*>(0)));
return name;
}
} // end namespace SCIRun
#endif // Datatypes_FieldIndex_h
| 27.319048 | 119 | 0.708907 | [
"vector"
] |
0860f33b6d7cf025303a833ce405a775bb88dd5c | 745 | c | C | mudlib/d/latemoon/room/bathroom1.c | mudchina/es2-mudlib-utf8 | 87bba6bd2249beec8424b0d6623486a0dd1f7b30 | [
"MIT"
] | 30 | 2016-06-18T08:56:50.000Z | 2021-11-17T17:08:31.000Z | mudlib/d/latemoon/room/bathroom1.c | mudchina/es2-mudlib-utf8 | 87bba6bd2249beec8424b0d6623486a0dd1f7b30 | [
"MIT"
] | 4 | 2017-08-07T19:57:15.000Z | 2020-04-13T03:07:06.000Z | mudlib/d/latemoon/room/bathroom1.c | mudchina/es2-mudlib-utf8 | 87bba6bd2249beec8424b0d6623486a0dd1f7b30 | [
"MIT"
] | 29 | 2016-05-19T13:24:55.000Z | 2022-02-03T02:50:50.000Z | #include <room.h>
#include <ansi.h>
inherit ROOM;
void create()
{
set("short", "沐浴更衣室");
set("long", @LONG
这是一间更衣室,你看到许多柜子,衣架上挂了许多的衣服饰
品。墙上的架上挂了一些丝巾,你可以闻到淡淡的香气围绕四周。
东侧一蓝青洒花软帘,隔帘望去,隐约可看到小花池,一团的雾气
你有点想去冲凉沐浴,让精神好些。当然此处是禁止男性进入!
LONG
);
set("no_fight", 1);
set("objects", ([
__DIR__"npc/shinyu" : 1,
]) );
set("exits", ([
"west" :__DIR__"flower1",
"east" :__DIR__"bathroom",
]));
create_door("west","小帘门","east", DOOR_CLOSED);
setup();
replace_program(ROOM);
}
int valid_leave(object me, string dir)
{
if( (string)me->query("gender") != "女性" ) {
me->apply_condition("rose_poison", 5);
tell_object(me, HIG "你觉得有人向你身上洒下一些粉末!\n" NOR );
}
return 1;
}
| 19.605263 | 55 | 0.591946 | [
"object"
] |
0861724c68eeb6759765f6cb1e77700324469c83 | 3,625 | c | C | packages/seacas/libraries/chaco/eigen/get_extval.c | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 82 | 2016-02-04T18:38:25.000Z | 2022-03-29T03:01:49.000Z | packages/seacas/libraries/chaco/eigen/get_extval.c | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 206 | 2015-11-20T01:57:47.000Z | 2022-03-31T21:12:04.000Z | packages/seacas/libraries/chaco/eigen/get_extval.c | jschueller/seacas | 14c34ae08b757cba43a3a03ec0f129c8a168a9d3 | [
"Python-2.0",
"Zlib",
"BSD-2-Clause",
"MIT",
"NetCDF",
"BSL-1.0",
"X11",
"BSD-3-Clause"
] | 68 | 2016-01-13T22:46:51.000Z | 2022-03-31T06:25:05.000Z | /*
* Copyright(C) 1999-2020 National Technology & Engineering Solutions
* of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
* NTESS, the U.S. Government retains certain rights in this software.
*
* See packages/seacas/LICENSE for details
*/
#include <math.h>
#include <stdio.h>
/* Finds first extended eigenpair of system corresponding to
tridiagonal T using using Rafael's bisection technique. */
void get_extval(double *alpha, /* j-vector of Lanczos scalars (using elements 1 to j) */
double *beta, /* (j+1)-vector of " " (has 0 element but using 1 to j-1) */
int j, /* number of Lanczos iterations taken */
double ritzval, /* Ritz value */
double *s, /* Ritz vector (length n, re-computed in this routine) */
double eigtol, /* tolerance on eigenpair */
double wnorm_g, /* W-norm of n-vector g, the rhs in the extended eig. problem */
double sigma, /* the norm constraint on the extended eigenvector */
double *extval, /* the extended eigenvalue this routine computes */
double *v, /* the j-vector solving the extended eig problem in T */
double *work1, /* j-vector of workspace */
double *work2 /* j-vector of workspace */
)
{
extern int DEBUG_EVECS; /* debug flag for eigen computation */
double lambda_low; /* lower bound on extended eval */
double lambda_high; /* upper bound on extended eval */
double tol; /* bisection tolerance */
double norm_v; /* norm of the extended T eigenvector v */
double lambda; /* the parameter that iterates to extval */
int cnt; /* debug iteration counter */
double diff; /* distance between lambda limits */
double ch_norm(), Tevec();
void tri_solve(), cpvec();
/* Compute the Ritz vector */
Tevec(alpha, beta - 1, j, ritzval, s);
/* Shouldn't happen, but just in case ... */
if (wnorm_g == 0.0) {
*extval = ritzval;
cpvec(v, 1, j, s);
if (DEBUG_EVECS > 0) {
printf("Degenerate extended eigenvector problem (g = 0).\n");
}
return;
/* ... not really an extended eigenproblem; just return Ritz pair */
}
/* Set up the bisection parameters */
lambda_low = ritzval - wnorm_g / sigma;
lambda_high = ritzval - (wnorm_g / sigma) * s[1];
lambda = 0.5 * (lambda_low + lambda_high);
tol = eigtol * eigtol * (1 + fabs(lambda_low) + fabs(lambda_high));
if (DEBUG_EVECS > 2) {
printf("Computing extended eigenpairs of T\n");
printf(" target norm_v (= sigma) %g\n", sigma);
printf(" bisection tolerance %g\n", tol);
}
if (DEBUG_EVECS > 3) {
printf(" lambda iterates to the extended eigenvalue\n");
printf(" lambda_low lambda lambda_high norm_v\n");
}
/* Bisection loop - iterate until norm constraint is satisfied */
cnt = 1;
diff = 2 * tol;
while (diff > tol) {
lambda = 0.5 * (lambda_low + lambda_high);
tri_solve(alpha, beta, j, lambda, v, wnorm_g, work1, work2);
norm_v = ch_norm(v, 1, j);
if (DEBUG_EVECS > 3) {
printf("%2i %18.16f %18.16f %18.16f %g\n", cnt++, lambda_low, lambda, lambda_high,
norm_v);
}
if (norm_v <= sigma) {
lambda_low = lambda;
}
if (norm_v >= sigma) {
lambda_high = lambda;
}
diff = lambda_high - lambda_low;
}
/* Return the extended eigenvalue (eigvec is automatically returned) */
*extval = lambda;
}
| 38.978495 | 97 | 0.593103 | [
"vector"
] |
0865ce5d04eae28dd7f5cab42ae93684a943b7d6 | 8,053 | c | C | head/contrib/ofed/management/opensm/opensm/osm_req.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | 4 | 2016-08-22T22:02:55.000Z | 2017-03-04T22:56:44.000Z | head/contrib/ofed/management/opensm/opensm/osm_req.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | head/contrib/ofed/management/opensm/opensm/osm_req.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2004-2008 Voltaire, Inc. All rights reserved.
* Copyright (c) 2002-2005 Mellanox Technologies LTD. All rights reserved.
* Copyright (c) 1996-2003 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* 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.
*
* 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.
*
*/
/*
* Abstract:
* Implementation of osm_req_t.
* This object represents the generic attribute requester.
* This object is part of the opensm family of objects.
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
#include <string.h>
#include <iba/ib_types.h>
#include <complib/cl_debug.h>
#include <opensm/osm_madw.h>
#include <opensm/osm_attrib_req.h>
#include <opensm/osm_log.h>
#include <opensm/osm_helper.h>
#include <opensm/osm_mad_pool.h>
#include <opensm/osm_vl15intf.h>
#include <opensm/osm_msgdef.h>
#include <opensm/osm_opensm.h>
/**********************************************************************
The plock MAY or MAY NOT be held before calling this function.
**********************************************************************/
ib_api_status_t
osm_req_get(IN osm_sm_t * sm,
IN const osm_dr_path_t * const p_path,
IN const uint16_t attr_id,
IN const uint32_t attr_mod,
IN const cl_disp_msgid_t err_msg,
IN const osm_madw_context_t * const p_context)
{
osm_madw_t *p_madw;
ib_api_status_t status = IB_SUCCESS;
ib_net64_t tid;
CL_ASSERT(sm);
OSM_LOG_ENTER(sm->p_log);
CL_ASSERT(p_path);
CL_ASSERT(attr_id);
/* do nothing if we are exiting ... */
if (osm_exit_flag)
goto Exit;
/* p_context may be NULL. */
p_madw = osm_mad_pool_get(sm->p_mad_pool,
p_path->h_bind, MAD_BLOCK_SIZE, NULL);
if (p_madw == NULL) {
OSM_LOG(sm->p_log, OSM_LOG_ERROR,
"ERR 1101: Unable to acquire MAD\n");
status = IB_INSUFFICIENT_RESOURCES;
goto Exit;
}
tid = cl_hton64((uint64_t) cl_atomic_inc(&sm->sm_trans_id));
OSM_LOG(sm->p_log, OSM_LOG_DEBUG,
"Getting %s (0x%X), modifier 0x%X, TID 0x%" PRIx64 "\n",
ib_get_sm_attr_str(attr_id), cl_ntoh16(attr_id),
cl_ntoh32(attr_mod), cl_ntoh64(tid));
ib_smp_init_new(osm_madw_get_smp_ptr(p_madw),
IB_MAD_METHOD_GET,
tid,
attr_id,
attr_mod,
p_path->hop_count,
sm->p_subn->opt.m_key,
p_path->path, IB_LID_PERMISSIVE, IB_LID_PERMISSIVE);
p_madw->mad_addr.dest_lid = IB_LID_PERMISSIVE;
p_madw->mad_addr.addr_type.smi.source_lid = IB_LID_PERMISSIVE;
p_madw->resp_expected = TRUE;
p_madw->fail_msg = err_msg;
/*
Fill in the mad wrapper context for the recipient.
In this case, the only thing the recipient needs is the
guid value.
*/
if (p_context)
p_madw->context = *p_context;
osm_vl15_post(sm->p_vl15, p_madw);
Exit:
OSM_LOG_EXIT(sm->p_log);
return (status);
}
/**********************************************************************
The plock MAY or MAY NOT be held before calling this function.
**********************************************************************/
ib_api_status_t
osm_req_set(IN osm_sm_t * sm,
IN const osm_dr_path_t * const p_path,
IN const uint8_t * const p_payload,
IN const size_t payload_size,
IN const uint16_t attr_id,
IN const uint32_t attr_mod,
IN const cl_disp_msgid_t err_msg,
IN const osm_madw_context_t * const p_context)
{
osm_madw_t *p_madw;
ib_api_status_t status = IB_SUCCESS;
ib_net64_t tid;
CL_ASSERT(sm);
OSM_LOG_ENTER(sm->p_log);
CL_ASSERT(p_path);
CL_ASSERT(attr_id);
CL_ASSERT(p_payload);
/* do nothing if we are exiting ... */
if (osm_exit_flag)
goto Exit;
/* p_context may be NULL. */
p_madw = osm_mad_pool_get(sm->p_mad_pool,
p_path->h_bind, MAD_BLOCK_SIZE, NULL);
if (p_madw == NULL) {
OSM_LOG(sm->p_log, OSM_LOG_ERROR,
"ERR 1102: Unable to acquire MAD\n");
status = IB_INSUFFICIENT_RESOURCES;
goto Exit;
}
tid = cl_hton64((uint64_t) cl_atomic_inc(&sm->sm_trans_id));
OSM_LOG(sm->p_log, OSM_LOG_DEBUG,
"Setting %s (0x%X), modifier 0x%X, TID 0x%" PRIx64 "\n",
ib_get_sm_attr_str(attr_id), cl_ntoh16(attr_id),
cl_ntoh32(attr_mod), cl_ntoh64(tid));
ib_smp_init_new(osm_madw_get_smp_ptr(p_madw),
IB_MAD_METHOD_SET,
tid,
attr_id,
attr_mod,
p_path->hop_count,
sm->p_subn->opt.m_key,
p_path->path, IB_LID_PERMISSIVE, IB_LID_PERMISSIVE);
p_madw->mad_addr.dest_lid = IB_LID_PERMISSIVE;
p_madw->mad_addr.addr_type.smi.source_lid = IB_LID_PERMISSIVE;
p_madw->resp_expected = TRUE;
p_madw->fail_msg = err_msg;
/*
Fill in the mad wrapper context for the recipient.
In this case, the only thing the recipient needs is the
guid value.
*/
if (p_context)
p_madw->context = *p_context;
memcpy(osm_madw_get_smp_ptr(p_madw)->data, p_payload, payload_size);
osm_vl15_post(sm->p_vl15, p_madw);
Exit:
OSM_LOG_EXIT(sm->p_log);
return (status);
}
int osm_send_trap144(osm_sm_t *sm, ib_net16_t local)
{
osm_madw_t *madw;
ib_smp_t *smp;
ib_mad_notice_attr_t *ntc;
osm_port_t *port;
ib_port_info_t *pi;
port = osm_get_port_by_guid(sm->p_subn, sm->p_subn->sm_port_guid);
if (!port) {
OSM_LOG(sm->p_log, OSM_LOG_ERROR,
"ERR 1104: cannot find SM port by guid 0x%" PRIx64 "\n",
cl_ntoh64(sm->p_subn->sm_port_guid));
return -1;
}
pi = &port->p_physp->port_info;
/* don't bother with sending trap when SMA supports this */
if (!local &&
pi->capability_mask&(IB_PORT_CAP_HAS_TRAP|IB_PORT_CAP_HAS_CAP_NTC))
return 0;
madw = osm_mad_pool_get(sm->p_mad_pool,
osm_sm_mad_ctrl_get_bind_handle(&sm->mad_ctrl),
MAD_BLOCK_SIZE, NULL);
if (madw == NULL) {
OSM_LOG(sm->p_log, OSM_LOG_ERROR,
"ERR 1105: Unable to acquire MAD\n");
return -1;
}
madw->mad_addr.dest_lid = pi->master_sm_base_lid;
madw->mad_addr.addr_type.smi.source_lid = pi->base_lid;
madw->fail_msg = CL_DISP_MSGID_NONE;
smp = osm_madw_get_smp_ptr(madw);
memset(smp, 0, sizeof(*smp));
smp->base_ver = 1;
smp->mgmt_class = IB_MCLASS_SUBN_LID;
smp->class_ver = 1;
smp->method = IB_MAD_METHOD_TRAP;
smp->trans_id = cl_hton64((uint64_t)cl_atomic_inc(&sm->sm_trans_id));
smp->attr_id = IB_MAD_ATTR_NOTICE;
smp->m_key = sm->p_subn->opt.m_key;
ntc = (ib_mad_notice_attr_t *)smp->data;
ntc->generic_type = 0x80 | IB_NOTICE_TYPE_INFO;
ib_notice_set_prod_type_ho(ntc, IB_NODE_TYPE_CA);
ntc->g_or_v.generic.trap_num = cl_hton16(144);
ntc->issuer_lid = pi->base_lid;
ntc->data_details.ntc_144.lid = pi->base_lid;
ntc->data_details.ntc_144.local_changes = local ?
TRAP_144_MASK_OTHER_LOCAL_CHANGES : 0;
ntc->data_details.ntc_144.new_cap_mask = pi->capability_mask;
ntc->data_details.ntc_144.change_flgs = local;
OSM_LOG(sm->p_log, OSM_LOG_DEBUG,
"Sending Trap 144, TID 0x%" PRIx64 " to SM lid %u\n",
cl_ntoh64(smp->trans_id), cl_ntoh16(pi->master_sm_base_lid));
osm_vl15_post(sm->p_vl15, madw);
return 0;
}
| 28.658363 | 74 | 0.69738 | [
"object"
] |
08685561a22f65d76def060b54eee32404cfac7d | 509 | h | C | uMobile/AppDelegate.h | aclissold/uMobile-iOS-app | f7419b1c629464e34ed0c878a6a69d1b9e27b3e0 | [
"Apache-2.0"
] | null | null | null | uMobile/AppDelegate.h | aclissold/uMobile-iOS-app | f7419b1c629464e34ed0c878a6a69d1b9e27b3e0 | [
"Apache-2.0"
] | null | null | null | uMobile/AppDelegate.h | aclissold/uMobile-iOS-app | f7419b1c629464e34ed0c878a6a69d1b9e27b3e0 | [
"Apache-2.0"
] | null | null | null | //
// AppDelegate.h
// uMobile
//
// This singleton object provides the ability to perform custom tasks if any of the events
// handled by the UIApplicationDelegate protocol occur, such as low memory warnings or
// state restoration.
//
// Created by Andrew Clissold & Skye Schneider 11/20/13.
// Copyright (c) 2014 Oakland University. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| 25.45 | 91 | 0.742633 | [
"object"
] |
086c5b5041d9de4287f65594782bf6b22c80aa26 | 2,740 | h | C | shootermain/Collider.h | RobLach/Red-Girder | a4364597ba790a38184ed07348b1c586e1e766fe | [
"MIT"
] | null | null | null | shootermain/Collider.h | RobLach/Red-Girder | a4364597ba790a38184ed07348b1c586e1e766fe | [
"MIT"
] | null | null | null | shootermain/Collider.h | RobLach/Red-Girder | a4364597ba790a38184ed07348b1c586e1e766fe | [
"MIT"
] | null | null | null | #ifndef COLLIDER_H
#define COLLIDER_H
/**
A contact point represents a point at which a collision occurs.
Simple collision geometries will typically produce a single contact when colliding,
but more complex geometries such as the composite geometry can produce multiple contact points.
*/
struct ContactPoint {
ContactPoint(){
}
ContactPoint(const Vector2 &p, const Vector2 &n, const float d){
pos = p;
normal = n;
depth = d;
}
void flip(){
normal = -normal;
}
Vector2 pos, normal;
float depth;
};
/**
Collision2D represents the geometry of two touching collision geometries.
*/
class Collision2D {
public:
/** Changes the direction of the collision by swapping the entity IDs and reversing the contact normals.
This is used so the same Collision2D structure can be used to inform both entities of the collision
without needed to special case which "side" of the collision the entity is on.
*/
void flip(){
for(int i=0;i<contactPoints.length();i++){
contactPoints[i].flip();
}
int temp = eid1;
eid1 = eid2;
eid2 = temp;
}
void reset(){
contactPoints.clear();
}
void addContact(const Vector2 &pos, const Vector2 &normal, const float depth){
contactPoints.append(ContactPoint(pos, normal, depth));
}
int eid1, eid2;
Array<ContactPoint> contactPoints;
bool bounce;
};
class Body;
class CircleCollider2D;
class PlaneCollider2D;
/** Base class for all collision geometries. Uses double disbatch to determine
the type of each geometry in a collision.*/
class Collider2D {
public:
Collider2D(){
setEID(0);
isShot = false;
}
void setEID(int id){
eid = id;
}
void setTranslation(float x, float y, float angle) {
setTranslation(Vector3(x, y, angle));
}
/** @todo Remove. */
void setTranslation(const Vector3 &trans) {
translation = trans;
}
void syncBody(const Body &b);
virtual bool collide(const Collider2D * const other, Collision2D &c) const = 0;
// Double disbatch functions.
virtual bool collideCircle(const CircleCollider2D * const other, Collision2D &c) const = 0;
virtual bool collidePlane(const PlaneCollider2D * const other, Collision2D &c) const = 0;
int eid;
Vector3 translation;
Vector3 velocity;
bool isShot;
bool isFriendly;
};
extern bool resolvePhysicalCollision(const Collision2D &c, Body *a, Body *b, const float epsilon, const float deltaT);
extern bool collideCircleCircle(const CircleCollider2D * const a, const CircleCollider2D * const b, Collision2D &c);
extern bool collideCirclePlane(const CircleCollider2D * const a, const PlaneCollider2D * const b, Collision2D &c, float polarity=1);
extern bool collidePlaneCircle(const PlaneCollider2D * const a, const CircleCollider2D * const b, Collision2D &c, float polarity=1);
#endif | 25.607477 | 132 | 0.739051 | [
"geometry"
] |
087b41f954468780df3dc21ef5d4d9c3fcd7657e | 2,439 | h | C | winrt/test.internal/mocks/MockGeometryAdapter.h | r2d2rigo/Win2D | 3f06d4f19b7d16b67859a1b30ac770215ef3e52d | [
"MIT"
] | 1,002 | 2015-01-09T19:40:01.000Z | 2019-05-04T12:05:09.000Z | winrt/test.internal/mocks/MockGeometryAdapter.h | r2d2rigo/Win2D | 3f06d4f19b7d16b67859a1b30ac770215ef3e52d | [
"MIT"
] | 667 | 2015-01-02T19:04:11.000Z | 2019-05-03T14:43:51.000Z | winrt/test.internal/mocks/MockGeometryAdapter.h | SunburstApps/Win2D.WinUI | 75a33f8f4c0c785c2d1b478589fd4d3a9c5b53df | [
"MIT"
] | 258 | 2015-01-06T07:44:49.000Z | 2019-05-01T15:50:59.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
#pragma once
namespace canvas
{
class MockGeometryAdapter : public GeometryAdapter
{
public:
CALL_COUNTER_WITH_MOCK(CreateRectangleGeometryMethod, ComPtr<ID2D1RectangleGeometry>(D2D1_RECT_F const&));
CALL_COUNTER_WITH_MOCK(CreateEllipseGeometryMethod, ComPtr<ID2D1EllipseGeometry>(D2D1_ELLIPSE const&));
CALL_COUNTER_WITH_MOCK(CreateRoundedRectangleGeometryMethod, ComPtr<ID2D1RoundedRectangleGeometry>(D2D1_ROUNDED_RECT const&));
CALL_COUNTER_WITH_MOCK(CreatePathGeometryMethod, ComPtr<ID2D1PathGeometry1>());
CALL_COUNTER_WITH_MOCK(CreateGeometryGroupMethod, ComPtr<ID2D1GeometryGroup>(D2D1_FILL_MODE, ID2D1Geometry**, UINT32));
CALL_COUNTER_WITH_MOCK(CreateTransformedGeometryMethod, ComPtr<ID2D1TransformedGeometry>(ID2D1Geometry*, D2D1_MATRIX_3X2_F*));
virtual ComPtr<ID2D1RectangleGeometry> CreateRectangleGeometry(GeometryDevicePtr const&, D2D1_RECT_F const& rect) override
{
return CreateRectangleGeometryMethod.WasCalled(rect);
}
virtual ComPtr<ID2D1EllipseGeometry> CreateEllipseGeometry(GeometryDevicePtr const&, D2D1_ELLIPSE const& ellipse) override
{
return CreateEllipseGeometryMethod.WasCalled(ellipse);
}
virtual ComPtr<ID2D1RoundedRectangleGeometry> CreateRoundedRectangleGeometry(GeometryDevicePtr const&, D2D1_ROUNDED_RECT const& roundedRect) override
{
return CreateRoundedRectangleGeometryMethod.WasCalled(roundedRect);
}
virtual ComPtr<ID2D1PathGeometry1> CreatePathGeometry(GeometryDevicePtr const&) override
{
return CreatePathGeometryMethod.WasCalled();
}
virtual ComPtr<ID2D1GeometryGroup> CreateGeometryGroup(GeometryDevicePtr const&, D2D1_FILL_MODE fillMode, ID2D1Geometry** d2dGeometries, uint32_t geometryCount) override
{
return CreateGeometryGroupMethod.WasCalled(fillMode, d2dGeometries, geometryCount);
}
virtual ComPtr<ID2D1TransformedGeometry> CreateTransformedGeometry(GeometryDevicePtr const&, ID2D1Geometry* d2dGeometry, D2D1_MATRIX_3X2_F* transform) override
{
return CreateTransformedGeometryMethod.WasCalled(d2dGeometry, transform);
}
};
}
| 47.823529 | 177 | 0.757278 | [
"transform"
] |
087d29fc60ca52ab67d9690c2811836436d8e7a6 | 6,672 | h | C | Examples/SearchResultsExample/Pods/Headers/Public/YapDatabase/YapDatabaseRelationshipEdge.h | fabiankr/YapDatabase | 5de14c36f59447bdf6c1d6f02b94f2dab50b6d54 | [
"BSD-3-Clause"
] | 2,592 | 2015-01-02T02:10:21.000Z | 2022-03-21T14:59:33.000Z | Examples/SearchResultsExample/Pods/Headers/Public/YapDatabase/YapDatabaseRelationshipEdge.h | fabiankr/YapDatabase | 5de14c36f59447bdf6c1d6f02b94f2dab50b6d54 | [
"BSD-3-Clause"
] | 414 | 2015-01-06T17:51:55.000Z | 2022-03-25T02:00:02.000Z | Examples/SearchResultsExample/Pods/Headers/Public/YapDatabase/YapDatabaseRelationshipEdge.h | fabiankr/YapDatabase | 5de14c36f59447bdf6c1d6f02b94f2dab50b6d54 | [
"BSD-3-Clause"
] | 378 | 2015-01-04T02:06:06.000Z | 2022-03-28T13:35:14.000Z | #import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Welcome to YapDatabase!
*
* The project page has a wealth of documentation if you have any questions.
* https://github.com/yapstudios/YapDatabase
*
* If you're new to the project you may want to visit the wiki.
* https://github.com/yapstudios/YapDatabase/wiki
*
* The YapDatabaseRelationship extension allow you to create relationships between objects,
* and configure automatic deletion rules.
*
* For tons of information about this extension, see the wiki article:
* https://github.com/yapstudios/YapDatabase/wiki/Relationships
**/
typedef NS_OPTIONS(uint16_t, YDB_NodeDeleteRules) {
// notify only
YDB_NotifyIfSourceDeleted = 1 << 0,
YDB_NotifyIfDestinationDeleted = 1 << 1,
// one-to-one
YDB_DeleteSourceIfDestinationDeleted = 1 << 2,
YDB_DeleteDestinationIfSourceDeleted = 1 << 3,
// one-to-many & many-to-many
YDB_DeleteSourceIfAllDestinationsDeleted = 1 << 4,
YDB_DeleteDestinationIfAllSourcesDeleted = 1 << 5,
};
@interface YapDatabaseRelationshipEdge : NSObject <NSCopying>
/**
* Returns an edge with the given name, destination & nodeDeleteRules.
*
* This method is suitable for use with the YapDatabaseRelationshipNode protocol.
* When using this protocol, the source object is directly queried by the YapDatabaseRelationship extension.
* Thus the extension already knows what the source node is,
* and so the source node information (sourceKey & sourceCollection) doesn't need to be explicitly set on the edge.
*
* This method is not suitable for use with manual edge management.
* When manually adding an edge, you must fully specify the source node.
**/
+ (instancetype)edgeWithName:(NSString *)name
destinationKey:(NSString *)destinationKey
collection:(nullable NSString *)destinationCollection
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
/**
* Returns an edge with the given name, destinationFileURL & nodeDeleteRules.
*
* When using a destinationFileURL, only a subset of the nodeDeleteRules apply.
* Specifically only the following work:
* - YDB_DeleteDestinationIfSourceDeleted
* - YDB_DeleteDestinationIfAllSourcesDeleted
*
* This method is suitable for use with the YapDatabaseRelationshipNode protocol.
* When using this protocol, the source object is directly queried by the YapDatabaseRelationship extension.
* Thus the extension already knows what the source node is,
* and so the source node information (sourceKey & sourceCollection) doesn't need to be explicitly set on the edge.
*
* This method is not suitable for use with manual edge management.
* When directly adding an edge, you must fully specify the source node.
**/
+ (instancetype)edgeWithName:(NSString *)name
destinationFileURL:(NSURL *)destinationFileURL
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
/**
* Returns a fully specified edge.
*
* This method is suitable for use with manual edge management.
*
* If you're using the YapDatabaseRelationshipNode protocol, then you can use the shorter version of this method
* which doesn't specify the source node. This is because the source node is implied with the
* YapDatabaseRelationshipNode protocol, and thus doesn't need to be explicitly specified in the edge.
**/
+ (instancetype)edgeWithName:(NSString *)name
sourceKey:(NSString *)sourceKey
collection:(nullable NSString *)sourceCollection
destinationKey:(NSString *)destinationKey
collection:(nullable NSString *)destinationCollection
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
/**
* Returns a fully specified edge.
*
* When using a destinationFileURL, only a subset of the nodeDeleteRules apply.
* Specifically only the following work:
* - YDB_DeleteDestinationIfSourceDeleted
* - YDB_DeleteDestinationIfAllSourcesDeleted
*
* This method is suitable for use with manual edge management.
*
* If you're using the YapDatabaseRelationshipNode protocol, then you can use the shorter version of this method
* which doesn't specify the source node. This is because the source node is implied with the
* YapDatabaseRelationshipNode protocol, and thus doesn't need to be explicitly specified in the edge.
**/
+ (instancetype)edgeWithName:(NSString *)name
sourceKey:(NSString *)sourceKey
collection:(nullable NSString *)sourceCollection
destinationFileURL:(NSURL *)destinationFileURL
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
#pragma mark Init
/**
* For documentation @see edgeWithName:destinationKey:collection:nodeDeleteRules:
**/
- (id)initWithName:(NSString *)name
destinationKey:(NSString *)key
collection:(nullable NSString *)collection
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
/**
* For documentation @see edgeWithName:destinationFileURL:nodeDeleteRules:
**/
- (id)initWithName:(NSString *)name destinationFileURL:(NSURL *)destinationFileURL
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
/**
* For documentation @see edgeWithName:sourceKey:collection:destinationKey:collection:nodeDeleteRules:
**/
- (id)initWithName:(NSString *)name
sourceKey:(NSString *)sourceKey
collection:(nullable NSString *)sourceCollection
destinationKey:(NSString *)destinationKey
collection:(nullable NSString *)destinationCollection
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
/**
* For documentation @see edgeWithName:sourceKey:collection:destinationFileURL:nodeDeleteRules:
**/
- (id)initWithName:(NSString *)name sourceKey:(NSString *)sourceKey
collection:(nullable NSString *)sourceCollection
destinationFileURL:(NSURL *)destinationFileURL
nodeDeleteRules:(YDB_NodeDeleteRules)rules;
#pragma mark Properties
@property (nonatomic, copy, readonly) NSString *name;
@property (nonatomic, copy, readonly) NSString *sourceKey;
@property (nonatomic, copy, readonly) NSString *sourceCollection;
@property (nonatomic, copy, readonly) NSString *destinationKey;
@property (nonatomic, copy, readonly) NSString *destinationCollection;
@property (nonatomic, copy, readonly) NSURL *destinationFileURL;
@property (nonatomic, assign, readonly) YDB_NodeDeleteRules nodeDeleteRules;
/**
* NO if the edge was created via the YapDatabaseRelationshipNode protocol.
* YES if the edge was created via "manual edge management" methods.
**/
@property (nonatomic, assign, readonly) BOOL isManualEdge;
@end
NS_ASSUME_NONNULL_END
| 40.192771 | 115 | 0.740108 | [
"object"
] |
087fa1c94bc993a26e4f1d22200b4c97ec51adbe | 1,397 | h | C | mclib/include/mclib/block/BlockEntity.h | EndlessArch/mclib | bba3ace1519f51e94aba9bc6d481be48aa0cd69d | [
"MIT"
] | 73 | 2016-05-14T21:35:44.000Z | 2022-03-11T15:27:02.000Z | mclib/include/mclib/block/BlockEntity.h | EndlessArch/mclib | bba3ace1519f51e94aba9bc6d481be48aa0cd69d | [
"MIT"
] | 9 | 2017-08-12T22:26:59.000Z | 2021-04-19T14:27:02.000Z | mclib/include/mclib/block/BlockEntity.h | EndlessArch/mclib | bba3ace1519f51e94aba9bc6d481be48aa0cd69d | [
"MIT"
] | 30 | 2017-05-21T13:21:11.000Z | 2022-03-06T00:31:33.000Z | #ifndef MCLIB_BLOCK_BLOCK_ENTITY_H_
#define MCLIB_BLOCK_BLOCK_ENTITY_H_
#include <mclib/mclib.h>
#include <mclib/common/Vector.h>
#include <mclib/nbt/NBT.h>
#include <mclib/inventory/Slot.h>
#include <string>
#include <memory>
#include <array>
#include <vector>
namespace mc {
namespace block {
enum class BlockEntityType {
Banner,
Beacon,
Bed,
Cauldron,
BrewingStand,
Chest,
Comparator,
CommandBlock,
DaylightSensor,
Dispenser,
Dropper,
EnchantingTable,
EnderChest,
EndGateway,
EndPortal,
FlowerPot,
Furnace,
Hopper,
Jukebox,
MonsterSpawner,
Noteblock,
Piston,
ShulkerBox,
Sign,
Skull,
StructureBlock,
TrappedChest,
Unknown
};
class BlockEntity {
private:
BlockEntityType m_Type;
Vector3i m_Position;
nbt::NBT m_NBT;
protected:
virtual MCLIB_API bool ImportNBT(nbt::NBT* nbt) { return true; }
public:
MCLIB_API BlockEntity(BlockEntityType type, Vector3i position) noexcept;
MCLIB_API BlockEntityType GetType() const noexcept { return m_Type; }
MCLIB_API Vector3i GetPosition() const noexcept { return m_Position; }
MCLIB_API nbt::NBT* GetNBT() noexcept { return &m_NBT; }
MCLIB_API static std::unique_ptr<BlockEntity> CreateFromNBT(nbt::NBT* nbt);
};
using BlockEntityPtr = std::shared_ptr<BlockEntity>;
} // ns block
} // ns mc
#endif
| 19.136986 | 79 | 0.695777 | [
"vector"
] |
088be3aed8068acd45128907c2c0a3e3003f9336 | 2,474 | h | C | src/dial/gtkdial.h | andrewshadura/gnocl | dd7b7c823cce460e5fc5be74a706d9e45af2c445 | [
"TCL"
] | null | null | null | src/dial/gtkdial.h | andrewshadura/gnocl | dd7b7c823cce460e5fc5be74a706d9e45af2c445 | [
"TCL"
] | null | null | null | src/dial/gtkdial.h | andrewshadura/gnocl | dd7b7c823cce460e5fc5be74a706d9e45af2c445 | [
"TCL"
] | null | null | null | /* GTK - The GIMP Toolkit
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GTK_DIAL_H__
#define __GTK_DIAL_H__
#include <gdk/gdk.h>
#include <gtk/gtkadjustment.h>
#include <gtk/gtkwidget.h>
G_BEGIN_DECLS
#define GTK_DIAL(obj) G_TYPE_CHECK_INSTANCE_CAST (obj, gtk_dial_get_type (), GtkDial)
#define GTK_DIAL_CLASS(klass) G_TYPE_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
#define GTK_IS_DIAL(obj) G_TYPE_CHECK_INSTANCE_TYPE (obj, gtk_dial_get_type ())
typedef struct _GtkDial GtkDial;
typedef struct _GtkDialClass GtkDialClass;
struct _GtkDial
{
GtkWidget widget;
/* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
guint policy : 2;
/* Button currently pressed or 0 if none */
guint8 button;
/* Dimensions of dial components */
gint radius;
gint pointer_width;
/* ID of update timer, or 0 if none */
guint32 timer;
/* Current angle */
gfloat angle;
gfloat last_angle;
/* Old values from adjustment stored so we know when something changes */
gfloat old_value;
gfloat old_lower;
gfloat old_upper;
/* The adjustment object that stores the data for this dial */
GtkAdjustment *adjustment;
};
struct _GtkDialClass
{
GtkWidgetClass parent_class;
};
GtkWidget* gtk_dial_new ( GtkAdjustment *adjustment );
GType gtk_dial_get_type ( void );
GtkAdjustment* gtk_dial_get_adjustment ( GtkDial *dial );
void gtk_dial_set_update_policy ( GtkDial *dial,
GtkUpdateType policy );
void gtk_dial_set_adjustment ( GtkDial *dial,
GtkAdjustment *adjustment );
G_END_DECLS
#endif /* __GTK_DIAL_H__ */
| 27.488889 | 98 | 0.719483 | [
"object"
] |
08919ab390137295fb6eafe61ba79090a882e42a | 532 | h | C | Squeaky Engine/Entities/SpeedPowerUp.h | Abdullah-AlAttar/3D-Maze- | 5cf815af15f9e432479dcfb90db033e0c9903e86 | [
"MIT"
] | 2 | 2019-03-20T02:56:02.000Z | 2019-08-05T20:33:14.000Z | Squeaky Engine/Entities/SpeedPowerUp.h | Abdullah-AlAttar/3D-Maze- | 5cf815af15f9e432479dcfb90db033e0c9903e86 | [
"MIT"
] | null | null | null | Squeaky Engine/Entities/SpeedPowerUp.h | Abdullah-AlAttar/3D-Maze- | 5cf815af15f9e432479dcfb90db033e0c9903e86 | [
"MIT"
] | 1 | 2020-07-02T12:54:52.000Z | 2020-07-02T12:54:52.000Z | #pragma once
#include "GameObject.h"
#include "..\Models\RawModel.h"
#include "..\Models\TexturedModel.h"
#include "..\Rendering\ModelMesh.h"
#include "..\\Rendering\Loader.h"
#include "..\\Physics\BoxCollider.h"
class SpeedPowerUp
{
public:
SpeedPowerUp(TexturedModel texuredModel, Transform transform);
HitInfo IsColliding(BoxCollider other);
BoxCollider GetBoxCollider();
GameObject *gameObject;
void UpdateCollider();
bool IsEnabled();
void Disable();
void Enable();
private:
bool enabled;
BoxCollider boxCollider;
}; | 23.130435 | 63 | 0.753759 | [
"transform"
] |
ec5aef1506aa70c3b42bf92733ee9206d9e5b9b3 | 962 | h | C | src/renderer/renderer.h | cptaffe/actor | 4faf785fba098481b5e5582f53e15cfa5d431a73 | [
"MIT"
] | null | null | null | src/renderer/renderer.h | cptaffe/actor | 4faf785fba098481b5e5582f53e15cfa5d431a73 | [
"MIT"
] | null | null | null | src/renderer/renderer.h | cptaffe/actor | 4faf785fba098481b5e5582f53e15cfa5d431a73 | [
"MIT"
] | null | null | null | // Copyright 2016 Connor Taffe
#ifndef SRC_RENDERER_RENDERER_H_
#define SRC_RENDERER_RENDERER_H_
#include <glm/glm.hpp>
#include <vector>
#include "src/base.h"
#include "src/renderer/timer.h"
namespace renderer {
class Rasterizable {
public:
virtual ~Rasterizable();
virtual std::vector<double> Vertices() const = 0;
};
// Renderable interface
class Renderable {
public:
virtual ~Renderable();
virtual std::vector<glm::mat4> Render() const = 0;
std::vector<glm::mat4> Apply(std::vector<glm::mat4> m);
std::vector<glm::mat4> Apply(Renderable *r);
};
namespace shapes {
class Factory {
public:
virtual ~Factory();
virtual std::shared_ptr<Rasterizable> Cube() = 0;
};
} // namespace shapes
// Renderer interface
class Renderer : public Actor {
public:
virtual ~Renderer();
virtual void Render() = 0;
virtual std::unique_ptr<shapes::Factory> ShapeFactory() = 0;
};
} // namespace renderer
#endif // SRC_RENDERER_RENDERER_H_
| 18.862745 | 62 | 0.706861 | [
"render",
"vector"
] |
ec5b938daa9b74a7ddc0eec0194542d4e61ced6c | 3,507 | h | C | src/QMCWaveFunctions/TWFdispatcher.h | eugeneswalker/qmcpack | 352ff27f163bb92e0c232c48bec8ae7951ed9d8c | [
"NCSA"
] | null | null | null | src/QMCWaveFunctions/TWFdispatcher.h | eugeneswalker/qmcpack | 352ff27f163bb92e0c232c48bec8ae7951ed9d8c | [
"NCSA"
] | 11 | 2020-05-09T20:57:21.000Z | 2020-06-10T00:00:17.000Z | src/QMCWaveFunctions/TWFdispatcher.h | williamfgc/qmcpack | 732b473841e7823a21ab55ff397eed059f0f2e96 | [
"NCSA"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2021 QMCPACK developers.
//
// File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
//
// File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
//////////////////////////////////////////////////////////////////////////////////////
#ifndef QMCPLUSPLUS_TWFDISPATCH_H
#define QMCPLUSPLUS_TWFDISPATCH_H
#include "TrialWaveFunction.h"
namespace qmcplusplus
{
/** Wrappers for dispatching to TrialWaveFunction single walker APIs or mw_ APIs.
* This should be only used by QMC drivers.
* member function names must match mw_ APIs in TrialWaveFunction
*/
class TWFdispatcher
{
public:
using PsiValueType = TrialWaveFunction::PsiValueType;
using ComputeType = TrialWaveFunction::ComputeType;
using ValueType = TrialWaveFunction::ValueType;
using GradType = TrialWaveFunction::GradType;
TWFdispatcher(bool use_batch);
void flex_evaluateLog(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list) const;
void flex_recompute(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list,
const std::vector<bool>& recompute) const;
void flex_calcRatio(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list,
int iat,
std::vector<PsiValueType>& ratios,
ComputeType ct = ComputeType::ALL) const;
void flex_prepareGroup(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list,
int ig) const;
void flex_evalGrad(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list,
int iat,
std::vector<GradType>& grad_now) const;
void flex_calcRatioGrad(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list,
int iat,
std::vector<PsiValueType>& ratios,
std::vector<GradType>& grad_new) const;
void flex_accept_rejectMove(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list,
int iat,
const std::vector<bool>& isAccepted,
bool safe_to_delay) const;
void flex_completeUpdates(const RefVectorWithLeader<TrialWaveFunction>& wf_list) const;
void flex_evaluateGL(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVectorWithLeader<ParticleSet>& p_list,
bool fromscratch) const;
void flex_evaluateRatios(const RefVectorWithLeader<TrialWaveFunction>& wf_list,
const RefVector<const VirtualParticleSet>& vp_list,
const RefVector<std::vector<ValueType>>& ratios_list,
ComputeType ct) const;
private:
bool use_batch_;
};
} // namespace qmcplusplus
#endif
| 40.77907 | 89 | 0.62304 | [
"vector"
] |
ec5b96a87f7ebb4e3ddf69516836107046bb5004 | 1,437 | h | C | psol/include/net/instaweb/rewriter/public/process_context.h | creativeprogramming/ngx_pagespeed | 85a36b8133a1dc8fbb24afecacfb0a2c05616605 | [
"Apache-2.0"
] | 1 | 2019-06-12T19:54:57.000Z | 2019-06-12T19:54:57.000Z | psol/include/net/instaweb/rewriter/public/process_context.h | creativeprogramming/ngx_pagespeed | 85a36b8133a1dc8fbb24afecacfb0a2c05616605 | [
"Apache-2.0"
] | null | null | null | psol/include/net/instaweb/rewriter/public/process_context.h | creativeprogramming/ngx_pagespeed | 85a36b8133a1dc8fbb24afecacfb0a2c05616605 | [
"Apache-2.0"
] | null | null | null | // Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jmarantz@google.com (Joshua Marantz)
#ifndef NET_INSTAWEB_REWRITER_PUBLIC_PROCESS_CONTEXT_H_
#define NET_INSTAWEB_REWRITER_PUBLIC_PROCESS_CONTEXT_H_
namespace net_instaweb {
// This class encapsulates the initialization and cleanup of static and
// global variables across Pagespeed Automatic. The usage of this class
// is optional, but can help with cleaning up valgrind messages.
//
// It is up to the user to ensure the destructor is called at an appropriate
// time in their flow. There is no statically constructed object declared
// in mem_clean_up.cc, although this class can be instantiated statically
// if that's the best mechanism in the environment.
class ProcessContext {
public:
ProcessContext();
~ProcessContext();
};
} // namespace net_instaweb
#endif // NET_INSTAWEB_REWRITER_PUBLIC_PROCESS_CONTEXT_H_
| 36.846154 | 76 | 0.773138 | [
"object"
] |
ec5be998dedeba4b2e961d6f1439bc6259e567b7 | 9,941 | h | C | src/prod/src/Management/ClusterManager/FabricClientProxy.h | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Management/ClusterManager/FabricClientProxy.h | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Management/ClusterManager/FabricClientProxy.h | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Management
{
namespace ClusterManager
{
//
// This class does CM specific logging and then forwards the calls to the fabric client implementation.
//
class FabricClientProxy : public Store::PartitionedReplicaTraceComponent<Common::TraceTaskCodes::ClusterManager>
{
DENY_COPY(FabricClientProxy);
public:
__declspec(property(get=get_ClientFactory)) Api::IClientFactoryPtr const & Factory;
Api::IClientFactoryPtr const & get_ClientFactory() const { return clientFactory_; }
public:
FabricClientProxy(Api::IClientFactoryPtr const &, Store::PartitionedReplicaId const &);
Common::ErrorCode Initialize();
Common::AsyncOperationSPtr BeginCreateName(
Common::NamingUri const &,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndCreateName(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginDeleteName(
Common::NamingUri const &,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndDeleteName(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginSubmitPropertyBatch(
Naming::NamePropertyOperationBatch &&,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndSubmitPropertyBatch(
Common::AsyncOperationSPtr const &,
__inout Api::IPropertyBatchResultPtr &) const;
Common::AsyncOperationSPtr BeginCreateService(
Naming::PartitionedServiceDescriptor const &,
ServiceModelVersion const & packageVersion,
uint64 packageInstance,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndCreateService(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginUpdateService(
Common::NamingUri const &,
Naming::ServiceUpdateDescription const &,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndUpdateService(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginDeleteService(
Common::NamingUri const & appName,
ServiceModel::DeleteServiceDescription const &,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndDeleteService(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginGetServiceDescription(
Common::NamingUri const &,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndGetServiceDescription(
Common::AsyncOperationSPtr const &,
__out Naming::PartitionedServiceDescriptor &) const;
Common::AsyncOperationSPtr BeginGetProperty(
Common::NamingUri const &,
std::wstring const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndGetProperty(
Common::AsyncOperationSPtr const &,
__inout Naming::NamePropertyResult &) const;
Common::AsyncOperationSPtr BeginPutProperty(
Common::NamingUri const &,
std::wstring const &,
std::vector<byte> const &,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndPutProperty(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginDeleteProperty(
Common::NamingUri const &,
std::wstring const &,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndDeleteProperty(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginDeactivateNodesBatch(
std::map<Federation::NodeId, Reliability::NodeDeactivationIntent::Enum> const &,
std::wstring const & batchId,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndDeactivateNodesBatch(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginRemoveNodeDeactivations(
std::wstring const & batchId,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndRemoveNodeDeactivations(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginGetNodeDeactivationStatus(
std::wstring const & batchId,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndGetNodeDeactivationStatus(
Common::AsyncOperationSPtr const &,
__out Reliability::NodeDeactivationStatus::Enum &) const;
Common::AsyncOperationSPtr BeginNodeStateRemoved(
std::wstring const & nodeName,
Federation::NodeId const & nodeId,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndNodeStateRemoved(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginReportStartTaskSuccess(
TaskInstance const & taskInstance,
Common::Guid const & targetPartitionId,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndReportStartTaskSuccess(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginReportFinishTaskSuccess(
TaskInstance const & taskInstance,
Common::Guid const & targetPartitionId,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndReportFinishTaskSuccess(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginReportTaskFailure(
TaskInstance const & taskInstance,
Common::Guid const & targetPartitionId,
Common::ActivityId const &,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndReportTaskFailure(Common::AsyncOperationSPtr const &) const;
Common::AsyncOperationSPtr BeginUnprovisionApplicationType(
Management::ClusterManager::UnprovisionApplicationTypeDescription const &,
Common::TimeSpan const timeout,
Common::AsyncCallback const & callback,
Common::AsyncOperationSPtr const &) const;
Common::ErrorCode EndUnprovisionApplicationType(
Common::AsyncOperationSPtr const &) const;
private:
class ServiceAsyncOperationBase;
class CreateServiceAsyncOperation;
class DeleteServiceAsyncOperation;
Api::IClientFactoryPtr clientFactory_;
Api::IInternalInfrastructureServiceClientPtr infrastructureClient_;
Api::IServiceManagementClientPtr serviceMgmtClient_;
Api::IPropertyManagementClientPtr propertyMgmtClient_;
Api::IClusterManagementClientPtr clusterMgmtClient_;
Api::IApplicationManagementClientPtr applicationManagementClient_;
};
}
}
| 48.257282 | 121 | 0.588975 | [
"vector"
] |
ec6ac475cb5eda6297148291289172c02b880a5d | 1,104 | h | C | src/tools.h | joustava/SensorFusion_P5 | dd06f4c30c27ad1818e17a9961ce08785721431f | [
"MIT"
] | null | null | null | src/tools.h | joustava/SensorFusion_P5 | dd06f4c30c27ad1818e17a9961ce08785721431f | [
"MIT"
] | null | null | null | src/tools.h | joustava/SensorFusion_P5 | dd06f4c30c27ad1818e17a9961ce08785721431f | [
"MIT"
] | null | null | null | #ifndef _TOOLS_H_
#define _TOOLS_H_
#include <vector>
#include "Eigen/Dense"
class Tools {
public:
/**
* Constructor.
*/
Tools();
/**
* Destructor.
*/
virtual ~Tools();
/**
* @brief Calculate Root Mean Square Error
*
* @param estimations std::vector<Eigen::VectorXd>
* @param ground_truth std::vector<Eigen::VectorXd>
* @return Eigen::VectorXd
*/
Eigen::VectorXd CalculateRMSE(const std::vector<Eigen::VectorXd> &estimations,
const std::vector<Eigen::VectorXd> &ground_truth);
/**
* @brief Calculate Jacobian matrix to handle non-linearity in Radar measurement
*
* @param x_state Eigen::VectorXd
* @return Eigen::MatrixXd a Jacobian matrix
*/
Eigen::MatrixXd CalculateJacobian(const Eigen::VectorXd &x_state);
/**
* @brief Public: Convert cartesian measurment vector to polar vector.
*
* @param x_state Eigen::VectorXd (px, py, vx, vy)T
* @return Eigen::VectorXd (ρ,φ,ρ_dot)T
*/
Eigen::VectorXd ConvertCartesianToPolar(const Eigen::VectorXd &x_state);
};
#endif // _TOOLS_H_
| 23.489362 | 82 | 0.650362 | [
"vector"
] |
ec7020732f56b198d497dfd0c1d6a8002267394f | 1,654 | h | C | src/BabylonImGui/include/babylon/inspector/components/actiontabs/tabs/propertygrids/lights/hemispheric_light_property_grid_component.h | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | null | null | null | src/BabylonImGui/include/babylon/inspector/components/actiontabs/tabs/propertygrids/lights/hemispheric_light_property_grid_component.h | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | null | null | null | src/BabylonImGui/include/babylon/inspector/components/actiontabs/tabs/propertygrids/lights/hemispheric_light_property_grid_component.h | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | null | null | null | #ifndef BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_TABS_PROPERTY_GRIDS_LIGHTS_HEMISPHERIC_LIGHT_PROPERTY_GRID_COMPONENT_H
#define BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_TABS_PROPERTY_GRIDS_LIGHTS_HEMISPHERIC_LIGHT_PROPERTY_GRID_COMPONENT_H
#include <memory>
#include <babylon/babylon_api.h>
#include <babylon/inspector/components/actiontabs/lines/color3_line_component.h>
#include <babylon/inspector/components/actiontabs/lines/vector3_line_component.h>
#include <babylon/inspector/components/actiontabs/tabs/propertygrids/lights/common_light_property_grid_component.h>
#include <babylon/lights/hemispheric_light.h>
namespace BABYLON {
class HemisphericLight;
using HemisphericLightPtr = std::shared_ptr<HemisphericLight>;
struct BABYLON_SHARED_EXPORT HemisphericLightPropertyGridComponent {
static void render(const HemisphericLightPtr& light)
{
CommonLightPropertyGridComponent::render(
std::static_pointer_cast<Light>(light));
// --- SETUP ---
static auto setupContainerOpened = true;
ImGui::SetNextTreeNodeOpen(setupContainerOpened, ImGuiCond_Always);
if (ImGui::CollapsingHeader("SETUP")) {
Color3LineComponent::render("Diffuse", light->diffuse);
Color3LineComponent::render("Ground", light->groundColor);
Vector3LineComponent::render("Direction", light->direction);
setupContainerOpened = true;
}
else {
setupContainerOpened = false;
}
}
}; // end of struct HemisphericLightPropertyGridComponent
} // end of namespace BABYLON
#endif // end of
// BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_TABS_PROPERTY_GRIDS_LIGHTS_HEMISPHERIC_LIGHT_PROPERTY_GRID_COMPONENT_H
| 38.465116 | 121 | 0.80653 | [
"render"
] |
ec7742c749848e1074fbb02d9cab833fb6bbc5d0 | 13,727 | h | C | src-qt5/desktop-utils/lumina-fm/widgets/DDListWidgets.h | q5sys/lumina | d3654eb6a83d7f8aad5530ba10816a245c9f55b3 | [
"BSD-3-Clause"
] | 246 | 2018-04-13T20:07:34.000Z | 2022-03-29T01:33:37.000Z | src-qt5/desktop-utils/lumina-fm/widgets/DDListWidgets.h | q5sys/lumina | d3654eb6a83d7f8aad5530ba10816a245c9f55b3 | [
"BSD-3-Clause"
] | 332 | 2016-06-21T13:37:10.000Z | 2018-04-06T13:06:41.000Z | src-qt5/desktop-utils/lumina-fm/widgets/DDListWidgets.h | q5sys/lumina | d3654eb6a83d7f8aad5530ba10816a245c9f55b3 | [
"BSD-3-Clause"
] | 69 | 2018-04-12T15:46:09.000Z | 2022-03-20T21:21:45.000Z | //===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
// This is a couple simple widget subclasses to enable drag and drop functionality
// NOTE: The "whatsThis()" item information needs to correspond to the "[cut/copy]::::<file path>" syntax
//NOTE2: The "whatsThis()" information on the widget itself should be the current dir path *if* it can accept drops
//===========================================
#ifndef _LUMINA_FM_DRAG_DROP_WIDGETS_H
#define _LUMINA_FM_DRAG_DROP_WIDGETS_H
#define MIME QString("x-special/lumina-copied-files")
#include <QListWidget>
#include <QTreeWidget>
#include <QDropEvent>
#include <QMimeData>
#include <QDrag>
#include <QFileInfo>
#include <QDebug>
#include <QMouseEvent>
#include <QUrl>
#include <QDir>
#include <QApplication>
#include <LUtils.h>
//==============
// LIST WIDGET
//==============
class DDListWidget : public QListWidget{
Q_OBJECT
public:
DDListWidget(QWidget *parent=0) : QListWidget(parent){
//Drag and Drop Properties
this->setDragDropMode(QAbstractItemView::DragDrop);
this->setDefaultDropAction(Qt::MoveAction); //prevent any built-in Qt actions - the class handles it
//Other custom properties necessary for the FM
this->setFocusPolicy(Qt::StrongFocus);
this->setContextMenuPolicy(Qt::CustomContextMenu);
this->setSelectionMode(QAbstractItemView::ExtendedSelection);
this->setSelectionBehavior(QAbstractItemView::SelectRows);
this->setFlow(QListView::TopToBottom);
this->setWrapping(true);
this->setMouseTracking(true);
this->setSortingEnabled(true); //This sorts *only* by name - type is not preserved
//this->setStyleSheet("QListWidget::item{ border: 1px solid transparent; border-radius: 5px; background-color: transparent;} QListWidget::item:hover{ border-color: black; } QListWidget::item:focus{ border-color: lightblue; }");
}
~DDListWidget(){}
signals:
void DataDropped(QString, QStringList); //Dir path, List of commands
void GotFocus();
protected:
void focusInEvent(QFocusEvent *ev){
QListWidget::focusInEvent(ev);
emit GotFocus();
}
void startDrag(Qt::DropActions act){
QList<QListWidgetItem*> items = this->selectedItems();
if(items.length()<1){ return; }
QList<QUrl> urilist;
for(int i=0; i<items.length(); i++){
urilist << QUrl::fromLocalFile(items[i]->whatsThis());
}
//Create the mime data
//qDebug() << "Start Drag:" << urilist;
QMimeData *mime = new QMimeData;
mime->setUrls(urilist);
//Create the drag structure
QDrag *drag = new QDrag(this);
drag->setMimeData(mime);
/*if(info.first().section("::::",0,0)=="cut"){
drag->exec(act | Qt::MoveAction);
}else{*/
drag->exec(act | Qt::CopyAction);
//}
}
void dragEnterEvent(QDragEnterEvent *ev){
//qDebug() << "Drag Enter Event:" << ev->mimeData()->hasFormat(MIME);
if(ev->mimeData()->hasUrls() && !this->whatsThis().isEmpty() ){
ev->acceptProposedAction(); //allow this to be dropped here
}else{
ev->ignore();
}
}
void dragMoveEvent(QDragMoveEvent *ev){
if(ev->mimeData()->hasUrls() && !this->whatsThis().isEmpty() ){
//Change the drop type depending on the data/dir
QString home = QDir::homePath();
//qDebug() << "Drag Move:" << home << this->whatsThis();
if( this->whatsThis().startsWith(home) ){ ev->setDropAction(Qt::MoveAction); this->setCursor(Qt::DragMoveCursor); }
else{ ev->setDropAction(Qt::CopyAction); this->setCursor(Qt::DragCopyCursor);}
ev->acceptProposedAction(); //allow this to be dropped here
//this->setCursor(Qt::CrossCursor);
}else{
this->setCursor(Qt::ForbiddenCursor);
ev->ignore();
}
this->update();
}
void dropEvent(QDropEvent *ev){
if(this->whatsThis().isEmpty() || !ev->mimeData()->hasUrls() ){ ev->ignore(); return; } //not supported
//qDebug() << "Drop Event:";
ev->accept(); //handled here
QString dirpath = this->whatsThis();
//See if the item under the drop point is a directory or not
QListWidgetItem *it = this->itemAt( ev->pos());
if(it!=0){
//qDebug() << "Drop Item:" << it->whatsThis();
QFileInfo info(it->whatsThis());
if(info.isDir() && info.isWritable()){
dirpath = info.absoluteFilePath();
}
}
//Now turn the input urls into local file paths
QStringList files;
QString home = QDir::homePath();
foreach(const QUrl &url, ev->mimeData()->urls()){
const QString filepath = url.toLocalFile();
//If the target file is modifiable, assume a move - otherwise copy
if(QFileInfo(filepath).isWritable() && (filepath.startsWith(home) && dirpath.startsWith(home))){
if(filepath.section("/",0,-2)!=dirpath){ files << "cut::::"+filepath; } //don't "cut" a file into the same dir
}else{ files << "copy::::"+filepath; }
}
//qDebug() << "Drop Event:" << dirpath << files;
if(!files.isEmpty()){ emit DataDropped( dirpath, files ); }
this->setCursor(Qt::ArrowCursor);
}
void mouseReleaseEvent(QMouseEvent *ev){
if(ev->button() != Qt::RightButton && ev->button() != Qt::LeftButton){ ev->ignore(); }
else{ QListWidget::mouseReleaseEvent(ev); } //pass it along to the widget
}
void mousePressEvent(QMouseEvent *ev){
if(ev->button() != Qt::RightButton && ev->button() != Qt::LeftButton){ ev->ignore(); }
else{ QListWidget::mousePressEvent(ev); } //pass it along to the widget
}
/*void mouseMoveEvent(QMouseEvent *ev){
if(ev->button() != Qt::RightButton && ev->button() != Qt::LeftButton){ ev->ignore(); }
else{ QListWidget::mouseMoveEvent(ev); } //pass it along to the widget
}*/
};
//================
// TreeWidget
//================
class DDTreeWidget : public QTreeWidget{
Q_OBJECT
public:
DDTreeWidget(QWidget *parent=0) : QTreeWidget(parent){
//Drag and Drop Properties
this->setDragDropMode(QAbstractItemView::DragDrop);
this->setDefaultDropAction(Qt::MoveAction); //prevent any built-in Qt actions - the class handles it
this->setDropIndicatorShown(true);
this->setAcceptDrops(true);
//Other custom properties necessary for the FM
this->setFocusPolicy(Qt::StrongFocus);
this->setContextMenuPolicy(Qt::CustomContextMenu);
this->setSelectionMode(QAbstractItemView::ExtendedSelection);
this->setSelectionBehavior(QAbstractItemView::SelectRows);
this->setMouseTracking(true);
this->setSortingEnabled(true);
this->setIndentation(0);
this->setItemsExpandable(false);
}
~DDTreeWidget(){}
signals:
void DataDropped(QString, QStringList); //Dir path, List of commands
void GotFocus();
void sortColumnChanged(int);
protected:
void focusInEvent(QFocusEvent *ev){
QTreeWidget::focusInEvent(ev);
emit GotFocus();
}
void startDrag(Qt::DropActions act){
QList<QTreeWidgetItem*> items = this->selectedItems();
if(items.length()<1){ return; }
QList<QUrl> urilist;
for(int i=0; i<items.length(); i++){
urilist << QUrl::fromLocalFile(items[i]->whatsThis(0));
}
//Create the mime data
QMimeData *mime = new QMimeData;
mime->setUrls(urilist);
//Create the drag structure
QDrag *drag = new QDrag(this);
drag->setMimeData(mime);
//qDebug() << "Start Drag:" << urilist;
drag->exec(act | Qt::CopyAction| Qt::MoveAction);
//qDebug() << " - Drag Finished";
}
void dragEnterEvent(QDragEnterEvent *ev){
//qDebug() << "Drag Enter Event:" << ev->mimeData()->hasUrls() << this->whatsThis();
//QTreeWidget::dragEnterEvent(ev);
if(ev->mimeData()->hasUrls() && !this->whatsThis().isEmpty() ){
ev->acceptProposedAction(); //allow this to be dropped here
}else{
ev->ignore();
}
}
void dragMoveEvent(QDragMoveEvent *ev){
//qDebug() << "Drag Move Event:" << ev->mimeData()->hasUrls() << this->whatsThis();
//QTreeWidget::dragMoveEvent(ev);
if(ev->mimeData()->hasUrls() && !this->whatsThis().isEmpty() ){
//Change the drop type depending on the data/dir
QString home = QDir::homePath();
if( this->whatsThis().startsWith(home) ){ ev->setDropAction(Qt::MoveAction); this->setCursor(Qt::DragMoveCursor); }
else{ ev->setDropAction(Qt::CopyAction); this->setCursor(Qt::DragCopyCursor);}
ev->acceptProposedAction(); //allow this to be dropped here
//this->setAcceptDrops(true);
}else{
//this->setAcceptDrops(false);
this->setCursor(Qt::ForbiddenCursor);
ev->ignore();
}
//this->setDropIndicatorShown(true);
//this->update();
//QTreeWidget::dragMoveEvent(ev);
}
void dropEvent(QDropEvent *ev){
//qDebug() << "Drop Event:" << ev->mimeData()->hasUrls() << this->whatsThis();
if(this->whatsThis().isEmpty() || !ev->mimeData()->hasUrls() ){ ev->ignore(); return; } //not supported
ev->accept(); //handled here
QString dirpath = this->whatsThis();
//See if the item under the drop point is a directory or not
QTreeWidgetItem *it = this->itemAt( ev->pos());
if(it!=0){
QFileInfo info(it->whatsThis(0));
if(info.isDir() && info.isWritable()){
dirpath = info.absoluteFilePath();
}
}
//qDebug() << "Drop Event:" << dirpath;
//Now turn the input urls into local file paths
QStringList files;
QString home = QDir::homePath();
foreach(const QUrl &url, ev->mimeData()->urls()){
const QString filepath = url.toLocalFile();
//If the target file is modifiable, assume a move - otherwise copy
if(QFileInfo(filepath).isWritable() && (filepath.startsWith(home) && dirpath.startsWith(home))){
if(filepath.section("/",0,-2)!=dirpath){ files << "cut::::"+filepath; } //don't "cut" a file into the same dir
}else{ files << "copy::::"+filepath; }
}
//qDebug() << "Drop Event:" << dirpath;
emit DataDropped( dirpath, files );
}
void mouseReleaseEvent(QMouseEvent *ev){
if(ev->button() != Qt::RightButton && ev->button() != Qt::LeftButton){ ev->ignore(); }
else{ QTreeWidget::mouseReleaseEvent(ev); } //pass it along to the widget
}
void mousePressEvent(QMouseEvent *ev){
if(ev->button() != Qt::RightButton && ev->button() != Qt::LeftButton){ ev->ignore(); }
else{ QTreeWidget::mousePressEvent(ev); } //pass it along to the widget
}
/*void mouseMoveEvent(QMouseEvent *ev){
if(ev->button() != Qt::RightButton && ev->button() != Qt::LeftButton){ ev->ignore(); }
else{ QTreeWidget::mouseMoveEvent(ev); } //pass it along to the widget
}*/
};
/*
* Virtual class for managing the sort of folders/files items. The problem with base class is that it only manages texts fields and
* we have dates and sizes.
*
* On this class, we overwrite the function operator<.
*/
class CQTreeWidgetItem : public QTreeWidgetItem {
public:
CQTreeWidgetItem(int type = Type) : QTreeWidgetItem(type) {}
CQTreeWidgetItem(const QStringList & strings, int type = Type) : QTreeWidgetItem(strings, type) {}
CQTreeWidgetItem(QTreeWidget * parent, int type = Type) : QTreeWidgetItem(parent, type) {}
CQTreeWidgetItem(QTreeWidget * parent, const QStringList & strings, int type = Type) : QTreeWidgetItem(parent, strings, type) {}
CQTreeWidgetItem(QTreeWidget * parent, QTreeWidgetItem * preceding, int type = Type) : QTreeWidgetItem(parent, preceding, type) {}
CQTreeWidgetItem(QTreeWidgetItem * parent, int type = Type) : QTreeWidgetItem(parent, type) {}
CQTreeWidgetItem(QTreeWidgetItem * parent, const QStringList & strings, int type = Type) : QTreeWidgetItem(parent, strings, type) {}
CQTreeWidgetItem(QTreeWidgetItem * parent, QTreeWidgetItem * preceding, int type = Type) : QTreeWidgetItem(parent, preceding, type) {}
virtual ~CQTreeWidgetItem() {}
inline virtual bool operator<(const QTreeWidgetItem &tmp) const {
int column = this->treeWidget()->sortColumn();
// We are in date text
if(column == 3 || column == 4){
return this->whatsThis(column) < tmp.whatsThis(column);
// We are in size text
}else if(column == 1) {
QString text = this->text(column);
QString text_tmp = tmp.text(column);
double filesize, filesize_tmp;
// On folders, text is empty so we check for that
// In case we are in folders, we put -1 for differentiate of regular files with 0 bytes.
// Doing so, all folders we'll be together instead of mixing with files with 0 bytes.
if(text.isEmpty())
filesize = -1;
else
filesize = LUtils::DisplaySizeToBytes(text);
if(text_tmp.isEmpty())
filesize_tmp = -1;
else
filesize_tmp = LUtils::DisplaySizeToBytes(text_tmp);
return filesize < filesize_tmp;
//Name column - still sort by type too (folders first)
}else if(column == 0 && (this->text(2).isEmpty() || tmp.text(2).isEmpty()) ){
if(this->text(2) != tmp.text(2)){ return this->text(2).isEmpty(); }
}
// In other cases, we trust base class implementation
return QTreeWidgetItem::operator<(tmp);
}
};
//Item override for sorting purposes of list widget items
class CQListWidgetItem : public QListWidgetItem {
public:
CQListWidgetItem(const QIcon &icon, const QString &text, QListWidget *parent = Q_NULLPTR) : QListWidgetItem(icon,text,parent) {}
virtual ~CQListWidgetItem() {}
inline virtual bool operator<(const QListWidgetItem &tmp) const {
QString type = this->data(Qt::UserRole).toString();
QString tmptype = tmp.data(Qt::UserRole).toString();
//Sort by type first
if(type!=tmptype){ return (QString::compare(type,tmptype)<0); }
//Then sort by name using the normal rules
return QListWidgetItem::operator<(tmp);
}
};
#endif
| 40.020408 | 230 | 0.658265 | [
"solid"
] |
ec7f038fe879d0348ebc42131aabc0bbd3b74a76 | 6,243 | h | C | mame/src/emu/ui.h | nitrologic/emu | be2c9b72d81c3aea85ad4fd18fa4f731b31f338a | [
"Unlicense"
] | null | null | null | mame/src/emu/ui.h | nitrologic/emu | be2c9b72d81c3aea85ad4fd18fa4f731b31f338a | [
"Unlicense"
] | null | null | null | mame/src/emu/ui.h | nitrologic/emu | be2c9b72d81c3aea85ad4fd18fa4f731b31f338a | [
"Unlicense"
] | null | null | null | /***************************************************************************
ui.h
Functions used to handle MAME's crude user interface.
Copyright Nicola Salmoria and the MAME Team.
Visit http://mamedev.org for licensing and usage restrictions.
***************************************************************************/
#pragma once
#ifndef __USRINTRF_H__
#define __USRINTRF_H__
#include "mamecore.h"
#include "render.h"
#include "unicode.h"
/***************************************************************************
CONSTANTS
***************************************************************************/
/* preferred font height; use ui_get_line_height() to get actual height */
#define UI_TARGET_FONT_ROWS (25)
#define UI_TARGET_FONT_HEIGHT (1.0f / (float)UI_TARGET_FONT_ROWS)
#define UI_MAX_FONT_HEIGHT (1.0f / 15.0f)
/* width of lines drawn in the UI */
#define UI_LINE_WIDTH (1.0f / 500.0f)
/* border between outlines and inner text on left/right and top/bottom sides */
#define UI_BOX_LR_BORDER (UI_TARGET_FONT_HEIGHT * 0.25f)
#define UI_BOX_TB_BORDER (UI_TARGET_FONT_HEIGHT * 0.25f)
/* handy colors */
#define ARGB_WHITE MAKE_ARGB(0xff,0xff,0xff,0xff)
#define ARGB_BLACK MAKE_ARGB(0xff,0x00,0x00,0x00)
#define UI_BORDER_COLOR MAKE_ARGB(0xff,0xff,0xff,0xff)
#define UI_BACKGROUND_COLOR MAKE_ARGB(0xe0,0x10,0x10,0x30)
#define UI_GFXVIEWER_BG_COLOR MAKE_ARGB(0xe0,0x10,0x10,0x30)
#define UI_GREEN_COLOR MAKE_ARGB(0xe0,0x10,0x60,0x10)
#define UI_YELLOW_COLOR MAKE_ARGB(0xe0,0x60,0x60,0x10)
#define UI_RED_COLOR MAKE_ARGB(0xf0,0x60,0x10,0x10)
#define UI_UNAVAILABLE_COLOR MAKE_ARGB(0xff,0x40,0x40,0x40)
#define UI_TEXT_COLOR MAKE_ARGB(0xff,0xff,0xff,0xff)
#define UI_TEXT_BG_COLOR MAKE_ARGB(0xe0,0x00,0x00,0x00)
#define UI_SUBITEM_COLOR MAKE_ARGB(0xff,0xff,0xff,0xff)
#define UI_CLONE_COLOR MAKE_ARGB(0xff,0x80,0x80,0x80)
#define UI_SELECTED_COLOR MAKE_ARGB(0xff,0xff,0xff,0x00)
#define UI_SELECTED_BG_COLOR MAKE_ARGB(0xe0,0x80,0x80,0x00)
#define UI_MOUSEOVER_COLOR MAKE_ARGB(0xff,0xff,0xff,0x80)
#define UI_MOUSEOVER_BG_COLOR MAKE_ARGB(0x70,0x40,0x40,0x00)
#define UI_MOUSEDOWN_COLOR MAKE_ARGB(0xff,0xff,0xff,0x80)
#define UI_MOUSEDOWN_BG_COLOR MAKE_ARGB(0xb0,0x60,0x60,0x00)
#define UI_DIPSW_COLOR MAKE_ARGB(0xff,0xff,0xff,0x00)
#define UI_SLIDER_COLOR MAKE_ARGB(0xff,0xff,0xff,0xff)
/* cancel return value for a UI handler */
#define UI_HANDLER_CANCEL ((UINT32)~0)
/* justification options for ui_draw_text_full */
enum
{
JUSTIFY_LEFT = 0,
JUSTIFY_CENTER,
JUSTIFY_RIGHT
};
/* word wrapping options for ui_draw_text_full */
enum
{
WRAP_NEVER,
WRAP_TRUNCATE,
WRAP_WORD
};
/* drawing options for ui_draw_text_full */
enum
{
DRAW_NONE,
DRAW_NORMAL,
DRAW_OPAQUE
};
#define SLIDER_NOCHANGE 0x12345678
/***************************************************************************
TYPE DEFINITIONS
***************************************************************************/
typedef INT32 (*slider_update)(running_machine *machine, void *arg, astring *string, INT32 newval);
typedef struct _slider_state slider_state;
struct _slider_state
{
slider_state * next; /* pointer to next slider */
slider_update update; /* callback */
void * arg; /* argument */
INT32 minval; /* minimum value */
INT32 defval; /* default value */
INT32 maxval; /* maximum value */
INT32 incval; /* increment value */
char description[1]; /* textual description */
};
/***************************************************************************
MACROS
***************************************************************************/
#define ui_draw_message_window(text) ui_draw_text_box(text, JUSTIFY_LEFT, 0.5f, 0.5f, UI_BACKGROUND_COLOR)
/***************************************************************************
FUNCTION PROTOTYPES
***************************************************************************/
/* main init/exit routines */
int ui_init(running_machine *machine);
/* display the startup screens */
int ui_display_startup_screens(running_machine *machine, int first_time, int show_disclaimer);
/* set the current text to display at startup */
void ui_set_startup_text(running_machine *machine, const char *text, int force);
/* once-per-frame update and render */
void ui_update_and_render(running_machine *machine);
/* returns the current UI font */
render_font *ui_get_font(void);
/* returns the line height of the font used by the UI system */
float ui_get_line_height(void);
/* returns the width of a character or string in the UI font */
float ui_get_char_width(unicode_char ch);
float ui_get_string_width(const char *s);
/* draw an outlined box filled with a given color */
void ui_draw_outlined_box(float x0, float y0, float x1, float y1, rgb_t backcolor);
/* simple text draw at the given coordinates */
void ui_draw_text(const char *buf, float x, float y);
/* full-on text draw with all the options */
void ui_draw_text_full(const char *origs, float x, float y, float wrapwidth, int justify, int wrap, int draw, rgb_t fgcolor, rgb_t bgcolor, float *totalwidth, float *totalheight);
/* draw a multi-line message with a box around it */
void ui_draw_text_box(const char *text, int justify, float xpos, float ypos, rgb_t backcolor);
/* display a temporary message at the bottom of the screen */
void CLIB_DECL ui_popup_time(int seconds, const char *text, ...) ATTR_PRINTF(2,3);
/* get/set whether or not the FPS is displayed */
void ui_show_fps_temp(double seconds);
void ui_set_show_fps(int show);
int ui_get_show_fps(void);
/* get/set whether or not the profiler is displayed */
void ui_set_show_profiler(int show);
int ui_get_show_profiler(void);
/* force the menus to display */
void ui_show_menu(void);
/* return true if a menu is displayed */
int ui_is_menu_active(void);
/* print the game info string into a buffer */
astring *game_info_astring(running_machine *machine, astring *string);
/* get the list of sliders */
const slider_state *ui_get_slider_list(void);
#endif /* __USRINTRF_H__ */
| 33.929348 | 180 | 0.643761 | [
"render"
] |
ec83114bc96f8c96724c871b884d487793489aef | 2,468 | h | C | System/Library/PrivateFrameworks/CoreRecognition.framework/CRBoxLayer.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 12 | 2019-06-02T02:42:41.000Z | 2021-04-13T07:22:20.000Z | System/Library/PrivateFrameworks/CoreRecognition.framework/CRBoxLayer.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/CoreRecognition.framework/CRBoxLayer.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 3 | 2019-06-11T02:46:10.000Z | 2019-12-21T14:58:16.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Saturday, June 1, 2019 at 6:45:56 PM Mountain Standard Time
* Operating System: Version 12.1.1 (Build 16C5050a)
* Image Source: /System/Library/PrivateFrameworks/CoreRecognition.framework/CoreRecognition
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <CoreRecognition/CoreRecognition-Structs.h>
#import <QuartzCore/CAReplicatorLayer.h>
@class CAShapeLayer, CATextLayer, NSMutableArray;
@interface CRBoxLayer : CAReplicatorLayer {
BOOL _customInit;
double _frameRatio;
CAShapeLayer* _reticleLayer;
CATextLayer* _codeLayer;
NSMutableArray* _completionBlocks;
double _demoSpeed;
}
@property (retain) CAShapeLayer * reticleLayer; //@synthesize reticleLayer=_reticleLayer - In the implementation block
@property (retain) CATextLayer * codeLayer; //@synthesize codeLayer=_codeLayer - In the implementation block
@property (retain) NSMutableArray * completionBlocks; //@synthesize completionBlocks=_completionBlocks - In the implementation block
@property (assign) double demoSpeed; //@synthesize demoSpeed=_demoSpeed - In the implementation block
@property (assign) BOOL customInit; //@synthesize customInit=_customInit - In the implementation block
@property (assign,nonatomic) double frameRatio; //@synthesize frameRatio=_frameRatio - In the implementation block
+(id)layer;
-(void)setFrameRatio:(double)arg1 ;
-(void)positionForCodeBoxPoints:(id)arg1 ;
-(void)setString:(id)arg1 mirrored:(BOOL)arg2 inverted:(BOOL)arg3 ;
-(void)animatePulseColor:(id)arg1 ;
-(void)setDemoSpeed:(double)arg1 ;
-(id)initWithCodeFrameRatio:(double)arg1 ;
-(double)frameRatio;
-(CAShapeLayer *)reticleLayer;
-(void)setReticleLayer:(CAShapeLayer *)arg1 ;
-(CATextLayer *)codeLayer;
-(void)setCodeLayer:(CATextLayer *)arg1 ;
-(BOOL)customInit;
-(void)animateReveal;
-(void)animateConceal;
-(void)animateToPosition:(CGPoint)arg1 transform:(CATransform3D)arg2 opacity:(double)arg3 type:(long long)arg4 ;
-(double)demoSpeed;
-(void)setCustomInit:(BOOL)arg1 ;
-(id)init;
-(void)dealloc;
-(void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void*)arg4 ;
-(NSMutableArray *)completionBlocks;
-(void)addCompletionBlock:(/*^block*/id)arg1 ;
-(void)setCompletionBlocks:(NSMutableArray *)arg1 ;
-(void)layoutSublayers;
@end
| 42.551724 | 145 | 0.742301 | [
"transform"
] |
ec87ef096f24214c7faf2ad91d37f952293549b8 | 3,958 | h | C | lib/Utilities/ScriptLoader.h | sonali-mishra-22/arangodb | 0fb224af784247252e164f5ab9a83702ac80772c | [
"Apache-2.0"
] | null | null | null | lib/Utilities/ScriptLoader.h | sonali-mishra-22/arangodb | 0fb224af784247252e164f5ab9a83702ac80772c | [
"Apache-2.0"
] | null | null | null | lib/Utilities/ScriptLoader.h | sonali-mishra-22/arangodb | 0fb224af784247252e164f5ab9a83702ac80772c | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#ifndef ARANGODB_UTILITIES_SCRIPT_LOADER_H
#define ARANGODB_UTILITIES_SCRIPT_LOADER_H 1
#include <map>
#include "Basics/Common.h"
#include "Basics/Mutex.h"
namespace arangodb {
////////////////////////////////////////////////////////////////////////////////
/// @brief JavaScript source code loader
////////////////////////////////////////////////////////////////////////////////
class ScriptLoader {
public:
//////////////////////////////////////////////////////////////////////////////
/// @brief constructs a loader
//////////////////////////////////////////////////////////////////////////////
ScriptLoader();
public:
//////////////////////////////////////////////////////////////////////////////
/// @brief gets the directory for scripts
//////////////////////////////////////////////////////////////////////////////
std::string const& getDirectory() const;
//////////////////////////////////////////////////////////////////////////////
/// @brief sets the directory for scripts
//////////////////////////////////////////////////////////////////////////////
void setDirectory(std::string const&);
//////////////////////////////////////////////////////////////////////////////
/// @brief build a script from an array of strings
//////////////////////////////////////////////////////////////////////////////
std::string buildScript(char const** script);
//////////////////////////////////////////////////////////////////////////////
/// @brief defines a new named script
//////////////////////////////////////////////////////////////////////////////
void defineScript(std::string const& name, std::string const& script);
void defineScript(std::string const& name, char const** script);
//////////////////////////////////////////////////////////////////////////////
/// @brief finds a named script
//////////////////////////////////////////////////////////////////////////////
std::string const& findScript(std::string const& name);
protected:
//////////////////////////////////////////////////////////////////////////////
/// @brief gets a list of all specified directory parts
//////////////////////////////////////////////////////////////////////////////
std::vector<std::string> getDirectoryParts();
protected:
//////////////////////////////////////////////////////////////////////////////
/// @brief all scripts
//////////////////////////////////////////////////////////////////////////////
std::map<std::string, std::string> _scripts;
//////////////////////////////////////////////////////////////////////////////
/// @brief script directory
//////////////////////////////////////////////////////////////////////////////
std::string _directory;
//////////////////////////////////////////////////////////////////////////////
/// @brief mutex for _scripts
//////////////////////////////////////////////////////////////////////////////
Mutex _lock;
};
} // namespace arangodb
#endif
| 36.648148 | 80 | 0.363315 | [
"vector"
] |
ec88d0094c8b9af53cb4198d490c3c5dbc42658c | 5,795 | h | C | p2core/reporting.h | declarativitydotnet/p2 | 59fa258b222a5ff0e6930da4f08acd6155cd378e | [
"BSD-3-Clause"
] | 3 | 2016-01-26T22:19:12.000Z | 2019-07-10T02:12:38.000Z | p2core/reporting.h | declarativitydotnet/p2 | 59fa258b222a5ff0e6930da4f08acd6155cd378e | [
"BSD-3-Clause"
] | null | null | null | p2core/reporting.h | declarativitydotnet/p2 | 59fa258b222a5ff0e6930da4f08acd6155cd378e | [
"BSD-3-Clause"
] | null | null | null | // -*- c-basic-offset: 2; related-file-name: "reporting.h" -*-
/*
* @(#)$Id$
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
* Or
* UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776,
* Berkeley, CA, 94707. Attention: P2 Group.
*
* DESCRIPTION: (Simple) error reporting facility for P2. Reporting
* level is encoded in the output stream name. When the reporting
* facility is not enabled, output on the stream is a no-op.
*
*/
#ifndef __REPORTING_H__
#define __REPORTING_H__
#include <map>
#include <string>
#include <ostream>
class Reporting {
public:
virtual ~Reporting() {};
/** What are the different reporting levels? */
enum
Level { ALL = 0, // Print everything. This means WORDY
// currently, unless another level is
// added below WORDY.
WORDY, // Print excruciatingly detailed
// info. This is where per-tuple, per
// event, per fixpoint details belong.
INFO, // Print informational messages (setup,
// configuration, etc.) No per-tuple,
// per runtime iteration messages should
// be here!
WARN, // Print warnings. The system can keep
// going but these are things someone
// should look at.
ERROR, // Print outright errors. The system
// can't keep going and this will help
// someone fix the problem. All
// assertions should be accompanied by
// such error messages and, eventually,
// replaced by them.
OUTPUT, // Print application output
NONE // Print nothing. This means not even
// OUTPUT.
};
private:
static std::map< std::string, Reporting::Level >* _levelFromName;
static std::map< Reporting::Level, std::string >* _levelToName;
/** The wordy stream */
static std::ostream* _wordy;
/** The info stream */
static std::ostream* _info;
/** The warn stream */
static std::ostream* _warn;
/** The error stream */
static std::ostream* _error;
/** The error stream */
static std::ostream* _output;
/** Convenience function to share level setting functionality with
initializers and external clients. Only to be used internally. */
static void
innerSetLevel(Level l);
public:
static std::map< std::string, Reporting::Level >&
levelFromName();
static std::map< Reporting::Level, std::string >&
levelToName();
/** Set the logging level. Everything at and above it is
enabled. Everything below it is disabled. */
static void
setLevel(Level l);
/** Obtain the logging level. */
static Level
level();
/** The wordy stream */
static std::ostream* wordy();
/** The info stream */
static std::ostream* info();
/** The warn stream */
static std::ostream* warn();
/** The error stream */
static std::ostream* error();
/** The error stream */
static std::ostream* output();
/** The leaky stream buffer. */
class LeakyStreambuf : public std::streambuf {
/** Override the overflow method to do nothing */
int
overflow(int c = EOF);
};
class Initializer {
public:
Initializer();
};
/** Fetch the initializer to construct it */
static Initializer*
theInitializer();
private:
/** Can't create objects */
Reporting() {}
/** The leaky stream buffer */
static LeakyStreambuf* _leakyStreambuf;
/** The null stream */
static std::ostream* _nullOStream;
/** The Logging Level */
static Level _level;
};
////////////////////////////////////////////////////////////
// MACROS
////////////////////////////////////////////////////////////
#define TELL_WORDY (*Reporting::wordy()) << "##"
#define TELL_INFO (*Reporting::info()) << "##"
#define TELL_WARN (*Reporting::warn()) << "##"
#define TELL_ERROR (*Reporting::error()) << "##"
#define TELL_OUTPUT (*Reporting::output()) << "##"
#define TRACE_WORDY ((*Reporting::wordy()) << __PRETTY_FUNCTION__)
#define TRACE_INFO (*Reporting::info() << __PRETTY_FUNCTION__)
#define TRACE_WARN (*Reporting::warn() << __PRETTY_FUNCTION__)
#define TRACE_ERROR (*Reporting::error() << __PRETTY_FUNCTION__)
#define TRACE_OUTPUT (*Reporting::output() << __PRETTY_FUNCTION__)
////////////////////////////////////////////////////////////
// Tracing
////////////////////////////////////////////////////////////
/** A trace object is allocated in the stack of a function, so that its
constructor and destructor can report entering into and exiting from
the function */
class TraceObj {
private:
/** The name of the function to trace */
const char *fn;
public:
/** The constructor reports entering a scope. */
TraceObj(const char *s)
: fn(s)
{
TELL_INFO << "Entering " << fn << "\n";
}
/** The destructor reports exiting from the scope */
~TraceObj()
{
TELL_INFO << "Exiting " << fn << "\n";
}
};
#ifndef TRACE_OFF
// Place this in a function that must be traced
#define TRACE_FUNCTION TraceObj _t(__PRETTY_FUNCTION__)
#else
#define TRACE_FUNCTION
#endif /* TRACE_OFF */
#endif /* __REPORTING_H_ */
| 23.946281 | 73 | 0.566005 | [
"object"
] |
ec8b62098e3ca6416ac3b472730cfb0f2233ddf8 | 4,225 | h | C | Tau/src/core/Midi/MidiTypes.h | cymheart/ventrue | 57219117a40077ffdde76c7183ea744c0ac2a08f | [
"MIT"
] | 4 | 2021-03-29T07:26:03.000Z | 2021-10-02T02:07:24.000Z | Tau/src/core/Midi/MidiTypes.h | cymheart/ventrue | 57219117a40077ffdde76c7183ea744c0ac2a08f | [
"MIT"
] | 1 | 2021-09-21T07:25:53.000Z | 2021-10-02T02:02:10.000Z | Tau/src/core/Midi/MidiTypes.h | cymheart/ventrue | 57219117a40077ffdde76c7183ea744c0ac2a08f | [
"MIT"
] | null | null | null | #ifndef _MidiTypes_h_
#define _MidiTypes_h_
#include"scutils/ByteStream.h"
using namespace scutils;
namespace tau
{
enum class MidiControllerType;
class MidiEvent;
class NoteOnEvent;
class NoteOffEvent;
class MidiTrack;
using MidiEventList = vector<MidiEvent*>;
using MidiTrackList = vector<MidiTrack*>;
using MidiControllerTypeList = vector<MidiControllerType>;
/// <summary>
/// Midi控制器类型
/// </summary>
enum class MidiControllerType
{
CC_None = -1,
BankSelectMSB,
ModulationWheelMSB,
BreathControlMSB,
CC_003,
FootControllerMSB,
PortamentoTimeMSB,
DataEntryMSB,
ChannelVolumeMSB,
BalanceMSB,
CC_009,
PanMSB,
ExpressionControllerMSB,
EffectControl1MSB,
EffectControl2MSB,
CC_014,
CC_015,
GeneralPurposeController1MSB,
GeneralPurposeController2MSB,
GeneralPurposeController3MSB,
GeneralPurposeController4MSB,
CC_020,
CC_021,
CC_022,
CC_023,
CC_024,
CC_025,
CC_026,
CC_027,
CC_028,
CC_029,
CC_030,
CC_031,
BankSelectLSB,
ModulationWheelLSB,
BreathControlLSB,
CC_035,
FootControllerLSB,
PortamentoTimeLSB,
DataEntryLSB,
ChannelVolumeLSB,
BalanceLSB,
CC_041,
PanLSB,
ExpressionControllerLSB,
EffectControl1LSB,
EffectControl2LSB,
CC_046,
CC_047,
GeneralPurposeController1LSB,
GeneralPurposeController2LSB,
GeneralPurposeController3LSB,
GeneralPurposeController4LSB,
CC_052,
CC_053,
CC_054,
CC_055,
CC_056,
CC_057,
CC_058,
CC_059,
CC_060,
CC_061,
CC_062,
CC_063,
SustainPedalOnOff,
PortamentoOnOff,
SustenutoOnOff,
SoftPedalOnOff,
LegatoFootSwitch,
Hold2,
SoundController1Variation,
SoundController2Timbre,
SoundController3ReleaseTime,
SoundController4AttackTime,
SoundController5Brightness,
SoundController6,
SoundController7,
SoundController8,
SoundController9,
SoundController10,
GeneralPurposeController5LSB,
GeneralPurposeController6LSB,
GeneralPurposeController7LSB,
GeneralPurposeController8LSB,
PortamentoControl,
CC_085,
CC_086,
CC_087,
CC_088,
CC_089,
CC_090,
Effects1DepthReverbSend,
Effects2DepthTremoloDepth,
Effects3DepthChorusSend,
Effects4DepthCelesteDepth,
Effects5DepthPhaserDepth,
DataEntryInc,
DataEntryDec,
NRPNLSB,
NRPNMSB,
RPNLSB,
RPNMSB,
CC_102,
CC_103,
CC_104,
CC_105,
CC_106,
CC_107,
CC_108,
CC_109,
CC_110,
CC_111,
CC_112,
CC_113,
CC_114,
CC_115,
CC_116,
CC_117,
CC_118,
CC_119,
AllSoundOff,
ResetAllControllers,
LocalControlOnOff,
AllNotesOff,
OmniModeOff,
OmniModeOn,
PolyModeOff,
PolyModeOn
};
/// <summary>
/// Midi事件类型
/// </summary>
enum class MidiEventType
{
/// <summary>
/// 未定义
/// </summary>
Unknown = -1,
/// <summary>
/// 按下音符
/// </summary>
NoteOn,
/// <summary>
/// 松开音符
/// </summary>
NoteOff,
/// <summary>
/// 速度设置
/// </summary>
Tempo,
/// <summary>
/// 节拍设置
/// </summary>
TimeSignature,
/// <summary>
/// 音调符号
/// </summary>
KeySignature,
/// <summary>
/// 控制器
/// </summary>
Controller,
/// <summary>
/// 乐器更换
/// </summary>
ProgramChange,
/// <summary>
/// 音符触后力度
/// </summary>
KeyPressure,
/// <summary>
/// 通道力度
/// </summary>
ChannelPressure,
/// <summary>
/// 滑音
/// </summary>
PitchBend,
/// <summary>
/// 文本
/// </summary>
Text,
/// <summary>
/// 系统码
/// </summary>
Sysex,
/// <summary>
/// 元事件
/// </summary>
Meta,
};
/// <summary>
/// midi文本类型
/// </summary>
enum class MidiTextType
{
GeneralText,
Copyright,
TrackName,
InstrumentName,
Lyric,
Marker,
Comment
};
/// <summary>
/// midi文件格式
/// </summary>
enum class MidiFileFormat
{
/// <summary>
/// 单轨
/// </summary>
SingleTrack,
/// <summary>
/// 同步多轨道
/// </summary>
SyncTracks,
/// <summary>
/// 异步多轨道
/// </summary>
AsyncTracks,
};
/// <summary>
/// 轨道通道合并模式
/// </summary>
enum TrackChannelMergeMode
{
//自动判断合并
AutoMerge,
//总是合并
AlwaysMerge,
//从不合并
NoMerge
};
/// <summary>
/// 弹奏方式
/// </summary>
enum MidiEventPlayType
{
//左手
LeftHand,
//右手
RightHand,
//背景
Background,
//自定
Custom
};
}
#endif
| 13.943894 | 59 | 0.660355 | [
"vector"
] |
ec8edbb31915708735e2a1add7eb3283ad7c6c70 | 2,011 | h | C | src/project.h | stillwwater/spritepacker | 62dc85e61574b31c28174288b0eb632d8fba3407 | [
"Zlib"
] | null | null | null | src/project.h | stillwwater/spritepacker | 62dc85e61574b31c28174288b0eb632d8fba3407 | [
"Zlib"
] | null | null | null | src/project.h | stillwwater/spritepacker | 62dc85e61574b31c28174288b0eb632d8fba3407 | [
"Zlib"
] | null | null | null | // Copyright (c) 2020 stillwwater
//
// 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.
#ifndef SPACK_PROJECT_H
#define SPACK_PROJECT_H
#include <memory>
#include <cassert>
#include "SDL.h"
#include "atlas.h"
namespace spack {
class Project {
public:
std::string filename;
std::vector<std::pair<std::string, AtlasExporter>> exporters;
std::vector<std::unique_ptr<Atlas>> atlases;
size_t current_atlas = 0;
const char *error_id = nullptr;
std::string error_msg;
Project();
void LoadEmptyProject(SDL_Renderer *device);
bool Load(SDL_Renderer *device, const std::string &file);
bool Save() const;
void RegisterExportFunc(const std::string &name, AtlasExporter fn);
bool ExportAllAtlases() const;
void AddAtlas(std::unique_ptr<Atlas> atlas);
std::unique_ptr<Atlas> MakeEmptyAtlas(SDL_Renderer *device) const;
const std::unique_ptr<Atlas> &GetAtlas() const;
void Error(const char *id, const std::string &msg);
};
inline const std::unique_ptr<Atlas> &Project::GetAtlas() const {
assert(current_atlas >= 0 && current_atlas < atlases.size());
return atlases[current_atlas];
}
} // namespace spack
#endif // SPACK_PROJECT_H
| 31.421875 | 77 | 0.726007 | [
"vector"
] |
ec8faa40e8f0f186ee2c8c190e55d512376725ca | 11,497 | h | C | GDLL/registry.h | Physticz/GABB | 57dfc4313f0db3476e35e3eda918cfab4de4eb57 | [
"MIT"
] | 3 | 2021-03-25T08:35:17.000Z | 2022-01-05T22:43:33.000Z | GDLL/registry.h | Physticz/GABB | 57dfc4313f0db3476e35e3eda918cfab4de4eb57 | [
"MIT"
] | 3 | 2021-01-22T15:42:51.000Z | 2021-09-13T05:55:35.000Z | GDLL/registry.h | Physticz/GABB | 57dfc4313f0db3476e35e3eda918cfab4de4eb57 | [
"MIT"
] | 6 | 2021-12-27T15:26:02.000Z | 2022-03-24T14:47:26.000Z | #pragma once
#ifndef __REGISTRY_REIJI_
#define __REGISTRY_REIJI_
#include <Windows.h>
#include <string>
#include <vector>
#include <sstream>
#include "md5.h"
#include <wincrypt.h>
#define MAX_KEY_LENGTH 255
#define MAX_VALUE_NAME 16383
bool NaN(std::wstring text) {
for (int i = 0; i < (int)text.length(); i++) if (text[i] < 48 || text[i] > 57) return true;
return false;
}
std::wstring FindKey(HKEY hKey, std::wstring value, bool keys = false) {
TCHAR achKey[MAX_KEY_LENGTH];
DWORD cbName;
TCHAR achClass[MAX_PATH] = TEXT("");
DWORD cchClassName = MAX_PATH;
DWORD cSubKeys = 0;
DWORD cbMaxSubKey;
DWORD cchMaxClass;
DWORD cValues;
DWORD cchMaxValue;
DWORD cbMaxValueData;
DWORD cbSecurityDescriptor;
FILETIME ftLastWriteTime;
DWORD _i, retCode;
TCHAR achValue[MAX_VALUE_NAME];
DWORD cchValue = MAX_VALUE_NAME;
retCode = RegQueryInfoKey(hKey, achClass, &cchClassName, NULL, &cSubKeys, &cbMaxSubKey, &cchMaxClass, &cValues, &cchMaxValue, &cbMaxValueData, &cbSecurityDescriptor, &ftLastWriteTime);
if (keys && cSubKeys) {
for (_i = 0; _i < cSubKeys; _i++) {
cbName = MAX_KEY_LENGTH;
retCode = RegEnumKeyEx(hKey, _i, achKey, &cbName, NULL, NULL, NULL, &ftLastWriteTime);
if (retCode == ERROR_SUCCESS && ( (value.length() && std::wstring(achKey).find(value) != std::string::npos) || (!value.length() && !NaN(achKey)))) return std::wstring(achKey);
//if (retCode == ERROR_SUCCESS && std::wstring(achKey).find(value) != std::string::npos) return achKey;
}
}
if (!keys && cValues) {
for (_i = 0, retCode = ERROR_SUCCESS; _i < cValues; _i++) {
cchValue = MAX_VALUE_NAME;
achValue[0] = '\0';
retCode = RegEnumValue(hKey, _i, achValue, &cchValue, NULL, NULL, NULL, NULL);
if (retCode == ERROR_SUCCESS && std::wstring(achValue).find(value) != std::string::npos) return (std::wstring)achValue;
//if (retCode == ERROR_SUCCESS && std::wstring(achValue).find(value) != std::string::npos) std::wstring(achValue);
}
}
return L"";
}
std::vector<std::wstring> FindKeyAll(HKEY hKey, std::wstring subkey, bool keys = false) {
TCHAR achKey[MAX_KEY_LENGTH];
DWORD cbName;
TCHAR achClass[MAX_PATH] = TEXT("");
DWORD cchClassName = MAX_PATH;
DWORD cSubKeys = 0;
DWORD cbMaxSubKey;
DWORD cchMaxClass;
DWORD cValues;
DWORD cchMaxValue;
DWORD cbMaxValueData;
DWORD cbSecurityDescriptor;
FILETIME ftLastWriteTime;
DWORD _i, retCode;
TCHAR achValue[MAX_VALUE_NAME];
DWORD cchValue = MAX_VALUE_NAME;
HKEY HK;
if (RegOpenKeyEx(hKey, subkey.c_str(), 0, KEY_READ | KEY_WOW64_32KEY, &HK) != ERROR_SUCCESS) {
if (RegOpenKeyEx(hKey, subkey.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &HK) != ERROR_SUCCESS) {
return {};
}
}
retCode = RegQueryInfoKey(HK, achClass, &cchClassName, NULL, &cSubKeys, &cbMaxSubKey, &cchMaxClass, &cValues, &cchMaxValue, &cbMaxValueData, &cbSecurityDescriptor, &ftLastWriteTime);
std::vector<std::wstring> result;
if (keys && cSubKeys) {
for (_i = 0; _i < cSubKeys; _i++) {
cbName = MAX_KEY_LENGTH;
retCode = RegEnumKeyEx(HK, _i, achKey, &cbName, NULL, NULL, NULL, &ftLastWriteTime);
if (retCode == ERROR_SUCCESS) result.push_back(achKey);
//if (retCode == ERROR_SUCCESS && std::wstring(achKey).find(value) != std::string::npos) return achKey;
}
}
if (!keys && cValues) {
for (_i = 0, retCode = ERROR_SUCCESS; _i < cValues; _i++) {
cchValue = MAX_VALUE_NAME;
achValue[0] = '\0';
retCode = RegEnumValue(HK, _i, achValue, &cchValue, NULL, NULL, NULL, NULL);
if (retCode == ERROR_SUCCESS) result.push_back(achValue);
//if (retCode == ERROR_SUCCESS && std::wstring(achValue).find(value) != std::string::npos) std::wstring(achValue);
}
}
RegCloseKey(HK);
return result;
}
bool RegKeyExists(HKEY hKey, std::wstring key) {
HKEY HK = NULL;
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_READ | KEY_WOW64_32KEY, &HK) != ERROR_SUCCESS) {
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &HK) != ERROR_SUCCESS) {
return false;
}
else RegCloseKey(HK);
}
else RegCloseKey(HK);
return true;
}
bool RegKeyGetValueBinary(HKEY hKey, std::wstring key, std::wstring value, std::wstring &_32bit, std::wstring &_64bit, std::wstring &devaultValue) {
HKEY HK = NULL;
bool oneget = false;
BYTE dwBuffer[501];
DWORD dwType = REG_BINARY, dwSize = 500;
int flags[2] = { KEY_WOW64_32KEY, KEY_WOW64_64KEY };
std::wstring * values[2] = { &_32bit, &_64bit };
for (int i = 0; i < 2; i++) {
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_READ | flags[i], &HK) == ERROR_SUCCESS) {
DWORD error = RegQueryValueEx(HK, value.c_str(), 0, &dwType, dwBuffer, &dwSize);
if (error == ERROR_SUCCESS) {
std::wstring buf = L"";
for (unsigned int i = 0; i < dwSize; i++) {
std::wstringstream wstream;
wstream << std::hex << dwBuffer[i];
std::wstring res(wstream.str());
if (res.length() == 1) res = L"0" + res;
buf += res;
}
*values[i] = buf;
if (!oneget) devaultValue = buf;
oneget = true;
}
RegCloseKey(HK);
}
}
return oneget;
}
bool RegKeySetValueBinary(HKEY hKey, std::wstring key, std::wstring value, std::string content) {
DWORD BinLength = content.length() / 2;
BYTE * Bin = new BYTE[BinLength];
CryptStringToBinaryA(content.c_str(), content.length(), CRYPT_STRING_HEX, Bin, &BinLength, NULL, NULL);
bool setter = false;
HKEY HK = NULL;
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_WRITE | KEY_WOW64_32KEY, &HK) == ERROR_SUCCESS) {
if (RegSetValueEx(HK, value.c_str(), 0, REG_BINARY, Bin, BinLength) == ERROR_SUCCESS) {
setter = true;
}
RegCloseKey(HK);
}
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_WRITE | KEY_WOW64_64KEY, &HK) == ERROR_SUCCESS) {
if (RegSetValueEx(HK, value.c_str(), 0, REG_BINARY, Bin, BinLength) == ERROR_SUCCESS) {
setter = true;
}
RegCloseKey(HK);
}
return setter;
}
bool RegKeyGetValueRegSz(HKEY hKey, std::wstring key, std::wstring value, std::wstring &_32bit, std::wstring &_64bit, std::wstring &devaultValue) {
HKEY HK = NULL;
wchar_t szBuffer[1001];
DWORD dwBufferSize = 1000;
DWORD dwType = REG_SZ;
int flags[2] = { KEY_WOW64_32KEY, KEY_WOW64_64KEY };
std::wstring * values[2] = { &_32bit, &_64bit };
bool oneget = false;
for (int i = 1; i >= 0; i--) {
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_READ | flags[i], &HK) == ERROR_SUCCESS) {
if (RegQueryValueEx(HK, value.c_str(), 0, &dwType, (LPBYTE)szBuffer, &dwBufferSize) == ERROR_SUCCESS) {
*values[i] = std::wstring(szBuffer);
if (!oneget) devaultValue = std::wstring(szBuffer);
oneget = true;
}
RegCloseKey(HK);
}
}
return oneget;
}
bool RegKeySetValueRegSz(HKEY hKey, std::wstring key, std::wstring value, std::wstring content) {
bool setter = false;
HKEY HK = NULL;
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_WRITE | KEY_WOW64_32KEY, &HK) == ERROR_SUCCESS) {
if (RegSetValueEx(HK, value.c_str(), 0, REG_SZ, (const BYTE*)content.c_str(), content.size() * 2) == ERROR_SUCCESS) setter = true;
RegCloseKey(HK);
}
if (RegOpenKeyEx(hKey, key.c_str(), 0, KEY_WRITE | KEY_WOW64_64KEY, &HK) == ERROR_SUCCESS) {
if (RegSetValueEx(HK, value.c_str(), 0, REG_SZ, (const BYTE*)content.c_str(), content.size() * 2) == ERROR_SUCCESS) setter = true;
RegCloseKey(HK);
}
return setter;
}
std::string GetHWID() {
std::string buffer = "";
std::vector<std::string> result;
HKEY hKey;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\BIOS", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
char buf[1000];
DWORD dwRegsz = REG_SZ;
DWORD dwBufSize = 999;
if (RegQueryValueExA(hKey, "SystemProductName", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey, "BIOSVendor", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey, "BaseBoardProduct", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
RegCloseKey(hKey);
}
buffer.length() > 0 ? result.push_back(std::string(md5(buffer) + std::to_string(buffer.length())).substr(0, 10)) : result.push_back("0000000000");
buffer = "";
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
char buf[1000];
DWORD dwRegsz = REG_SZ;
DWORD dwBufSize = 999;
if (RegQueryValueExA(hKey, "Identifier", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey, "ProcessorNameString", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey, "VendorIdentifier", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
RegCloseKey(hKey);
}
buffer.length() > 0 ? result.push_back(std::string(md5(buffer) + std::to_string(buffer.length())).substr(0, 10)) : result.push_back("0000000000");
buffer = "";
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\VIDEO", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
char buf[1000];
DWORD dwRegsz = REG_SZ;
DWORD dwBufSize = 999;
if (RegQueryValueExA(hKey, "\\Device\\Video0", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) {
std::string videomap = buf;
int pos = videomap.find("System\\");
if (pos != -1) {
videomap = videomap.substr(pos);
HKEY hKey2;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, videomap.c_str(), 0, KEY_READ, &hKey2) == ERROR_SUCCESS) {
DWORD dwRegsz = REG_SZ;
DWORD dwBufSize = 999;
if (RegQueryValueExA(hKey2, "ProviderName", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey2, "InstalledDisplayDrivers", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey2, "DriverDesc", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
RegCloseKey(hKey2);
}
}
}
RegCloseKey(hKey);
}
buffer.length() > 0 ? result.push_back(std::string(md5(buffer) + std::to_string(buffer.length())).substr(0, 10)) : result.push_back("0000000000");
buffer = "";
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 0\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
char buf[1000];
DWORD dwRegsz = REG_SZ;
DWORD dwBufSize = 999;
if (RegQueryValueExA(hKey, "DeviceName", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey, "Identifier", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
dwBufSize = 999;
if (RegQueryValueExA(hKey, "SerialNumber", NULL, &dwRegsz, (LPBYTE)buf, &dwBufSize) == ERROR_SUCCESS) buffer += buf;
RegCloseKey(hKey);
}
buffer.length() > 0 ? result.push_back(std::string(md5(buffer) + std::to_string(buffer.length())).substr(0, 10)) : result.push_back("0000000000");
buffer = "";
for (unsigned int i = 0; i < result.size(); i++) {
buffer += result[i];
if (i < result.size() - 1) buffer += '-';
}
return buffer;
}
#endif | 36.382911 | 186 | 0.656258 | [
"vector"
] |
ec90095c43e6d3031fb5a9880310834eb15d5d4f | 1,591 | h | C | game/server/entities/NPCs/CPenguinGrenade.h | xalalau/HLEnhanced | f108222ab7d303c9ed5a8e81269f9e949508e78e | [
"Unlicense"
] | 83 | 2016-06-10T20:49:23.000Z | 2022-02-13T18:05:11.000Z | game/server/entities/NPCs/CPenguinGrenade.h | xalalau/HLEnhanced | f108222ab7d303c9ed5a8e81269f9e949508e78e | [
"Unlicense"
] | 26 | 2016-06-16T22:27:24.000Z | 2019-04-30T19:25:51.000Z | game/server/entities/NPCs/CPenguinGrenade.h | xalalau/HLEnhanced | f108222ab7d303c9ed5a8e81269f9e949508e78e | [
"Unlicense"
] | 58 | 2016-06-10T23:52:33.000Z | 2021-12-30T02:30:50.000Z | #if USE_OPFOR
/***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#ifndef GAME_SERVER_ENTITIES_NPCS_CPENGUINGRENADE_H
#define GAME_SERVER_ENTITIES_NPCS_CPENGUINGRENADE_H
enum PenguinGrenadeAnim
{
PENGUINGRENADE_IDLE = 0,
PENGUINGRENADE_FIDGET,
PENGUINGRENADE_JUMP,
PENGUINGRENADE_RUN
};
#define PENGUIN_DETONATE_DELAY 15.0
class CPenguinGrenade : public CGrenade
{
public:
DECLARE_CLASS( CPenguinGrenade, CGrenade );
DECLARE_DATADESC();
void Precache() override;
void Spawn() override;
EntityClassification_t GetClassification() override;
int BloodColor() const override { return BLOOD_COLOR_YELLOW; }
void Killed( const CTakeDamageInfo& info, GibAction gibAction ) override;
void GibMonster() override;
void SuperBounceTouch( CBaseEntity *pOther );
void HuntThink();
void Smoke();
private:
static float m_flNextBounceSoundTime;
float m_flDie;
Vector m_vecTarget;
float m_flNextHunt;
float m_flNextHit;
Vector m_posPrev;
EHANDLE m_hOwner;
EntityClassification_t m_iMyClass = EntityClassifications().GetNoneId();
};
#endif //GAME_SERVER_ENTITIES_NPCS_CPENGUINGRENADE_H
#endif //USE_OPFOR
| 23.746269 | 77 | 0.781898 | [
"object",
"vector"
] |
ec9370ebaf41aab8a53ad972b29cbafb0b23c627 | 936 | c | C | addons/blender_xatlas/source/xatlas_src/extra/thirdparty/mimalloc/src/static.c | trisadmeslek/V-Sekai-Blender-tools | 0d8747387c58584b50c69c61ba50a881319114f8 | [
"MIT"
] | 1,097 | 2018-07-11T13:53:00.000Z | 2022-03-31T09:57:44.000Z | addons/blender_xatlas/source/xatlas_src/extra/thirdparty/mimalloc/src/static.c | trisadmeslek/V-Sekai-Blender-tools | 0d8747387c58584b50c69c61ba50a881319114f8 | [
"MIT"
] | 1,215 | 2019-09-09T14:31:33.000Z | 2022-03-30T20:20:14.000Z | addons/blender_xatlas/source/xatlas_src/extra/thirdparty/mimalloc/src/static.c | trisadmeslek/V-Sekai-Blender-tools | 0d8747387c58584b50c69c61ba50a881319114f8 | [
"MIT"
] | 117 | 2018-08-01T03:35:39.000Z | 2022-03-31T09:06:48.000Z | /* ----------------------------------------------------------------------------
Copyright (c) 2018, Microsoft Research, Daan Leijen
This is free software; you can redistribute it and/or modify it under the
terms of the MIT license. A copy of the license can be found in the file
"LICENSE" at the root of this distribution.
-----------------------------------------------------------------------------*/
#define _DEFAULT_SOURCE
#include "mimalloc.h"
#include "mimalloc-internal.h"
// For a static override we create a single object file
// containing the whole library. If it is linked first
// it will override all the standard library allocation
// functions (on Unix's).
#include "stats.c"
#include "random.c"
#include "os.c"
#include "arena.c"
#include "region.c"
#include "segment.c"
#include "page.c"
#include "heap.c"
#include "alloc.c"
#include "alloc-aligned.c"
#include "alloc-posix.c"
#include "init.c"
#include "options.c"
| 32.275862 | 79 | 0.617521 | [
"object"
] |
ec99604c43231ae8ec706bd17ef5740fb6e32413 | 1,475 | h | C | include/retdec/llvmir2hll/optimizer/optimizers/c_array_arg_optimizer.h | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 521 | 2019-03-29T15:44:08.000Z | 2022-03-22T09:46:19.000Z | include/retdec/llvmir2hll/optimizer/optimizers/c_array_arg_optimizer.h | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 30 | 2019-06-04T17:00:49.000Z | 2021-09-08T20:44:19.000Z | include/retdec/llvmir2hll/optimizer/optimizers/c_array_arg_optimizer.h | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 99 | 2019-03-29T16:04:13.000Z | 2022-03-28T16:59:34.000Z | /**
* @file include/retdec/llvmir2hll/optimizer/optimizers/c_array_arg_optimizer.h
* @brief Optimizes array arguments of function calls.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#ifndef RETDEC_LLVMIR2HLL_OPTIMIZER_OPTIMIZERS_C_ARRAY_ARG_OPTIMIZER_H
#define RETDEC_LLVMIR2HLL_OPTIMIZER_OPTIMIZERS_C_ARRAY_ARG_OPTIMIZER_H
#include "retdec/llvmir2hll/optimizer/func_optimizer.h"
#include "retdec/llvmir2hll/support/smart_ptr.h"
namespace retdec {
namespace llvmir2hll {
/**
* @brief Optimizes array arguments of function calls.
*
* This optimizer simplifies array arguments of function calls. More
* specifically, each argument of the form
* @code
* &x[0]
* @endcode
* is converted to
* @code
* x
* @endcode
* In this way, the following code
* @code
* int x[256];
* scanf("%s", &x[0]);
* return strlen(&x[0]);
* @endcode
* can be optimized to
* @code
* int x[256];
* scanf("%s", x);
* return strlen(x);
* @endcode
*
* Instances of this class have reference object semantics.
*
* This is a concrete optimizer which should not be subclassed.
*/
class CArrayArgOptimizer final: public FuncOptimizer {
public:
CArrayArgOptimizer(ShPtr<Module> module);
virtual ~CArrayArgOptimizer() override;
virtual std::string getId() const override { return "CArrayArg"; }
/// @name Visitor Interface
/// @{
using OrderedAllVisitor::visit;
void visit(ShPtr<CallExpr> expr) override;
/// @}
};
} // namespace llvmir2hll
} // namespace retdec
#endif
| 23.046875 | 78 | 0.744407 | [
"object"
] |
eca25590dedca33b2b4b8bba30bc5082826b2165 | 26,768 | h | C | prod/attestation_server/include/CkNtlm.h | aanciaes/secure-redis-container | 405a34a3a6ab493dbbb21e2ea6d70837b27facbf | [
"BSD-2-Clause"
] | 4 | 2021-04-16T14:46:05.000Z | 2021-07-02T20:14:29.000Z | prod/attestation_server/include/CkNtlm.h | aanciaes/secure-redis-container | 405a34a3a6ab493dbbb21e2ea6d70837b27facbf | [
"BSD-2-Clause"
] | 9 | 2021-04-16T14:05:58.000Z | 2021-07-21T19:46:34.000Z | SIMSmeCoreLib/__SIMSme__/ObjC/Chilkat/ChilkatHeaders/C++ Headers/CkNtlm.h | cdskev/ginlo-ios | 458d0eea0519f055e013ae1f2f6d7b051e9bc23a | [
"Apache-2.0"
] | null | null | null | // CkNtlm.h: interface for the CkNtlm class.
//
//////////////////////////////////////////////////////////////////////
// This header is generated for Chilkat 9.5.0.83
#ifndef _CkNtlm_H
#define _CkNtlm_H
#include "chilkatDefs.h"
#include "CkString.h"
#include "CkMultiByteBase.h"
#if !defined(__sun__) && !defined(__sun)
#pragma pack (push, 8)
#endif
#undef Copy
// CLASS: CkNtlm
class CK_VISIBLE_PUBLIC CkNtlm : public CkMultiByteBase
{
private:
// Don't allow assignment or copying these objects.
CkNtlm(const CkNtlm &);
CkNtlm &operator=(const CkNtlm &);
public:
CkNtlm(void);
virtual ~CkNtlm(void);
static CkNtlm *createNew(void);
void CK_VISIBLE_PRIVATE inject(void *impl);
// May be called when finished with the object to free/dispose of any
// internal resources held by the object.
void dispose(void);
// BEGIN PUBLIC INTERFACE
// ----------------------
// Properties
// ----------------------
// The ClientChallenge is passed in the Type 3 message from the client to the
// server. It must contain exactly 8 bytes. Because this is a string property, the
// bytes are get/set in encoded form (such as hex or base64) based on the value of
// the EncodingMode property. For example, if the EncodingMode property = "hex",
// then a hex representation of 8 bytes should be used to set the ClientChallenge.
//
// Note: Setting the ClientChallenge is optional. If the ClientChallenge remains
// unset, it will be automatically set to 8 random bytes when the GenType3 method
// is called.
//
void get_ClientChallenge(CkString &str);
// The ClientChallenge is passed in the Type 3 message from the client to the
// server. It must contain exactly 8 bytes. Because this is a string property, the
// bytes are get/set in encoded form (such as hex or base64) based on the value of
// the EncodingMode property. For example, if the EncodingMode property = "hex",
// then a hex representation of 8 bytes should be used to set the ClientChallenge.
//
// Note: Setting the ClientChallenge is optional. If the ClientChallenge remains
// unset, it will be automatically set to 8 random bytes when the GenType3 method
// is called.
//
const char *clientChallenge(void);
// The ClientChallenge is passed in the Type 3 message from the client to the
// server. It must contain exactly 8 bytes. Because this is a string property, the
// bytes are get/set in encoded form (such as hex or base64) based on the value of
// the EncodingMode property. For example, if the EncodingMode property = "hex",
// then a hex representation of 8 bytes should be used to set the ClientChallenge.
//
// Note: Setting the ClientChallenge is optional. If the ClientChallenge remains
// unset, it will be automatically set to 8 random bytes when the GenType3 method
// is called.
//
void put_ClientChallenge(const char *newVal);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void get_DnsComputerName(CkString &str);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
const char *dnsComputerName(void);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void put_DnsComputerName(const char *newVal);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void get_DnsDomainName(CkString &str);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
const char *dnsDomainName(void);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void put_DnsDomainName(const char *newVal);
// Optional. May be set by the client for inclusion in the Type 1 message.
void get_Domain(CkString &str);
// Optional. May be set by the client for inclusion in the Type 1 message.
const char *domain(void);
// Optional. May be set by the client for inclusion in the Type 1 message.
void put_Domain(const char *newVal);
// Determines the encoding mode used for getting/setting various properties, such
// as ClientChallenge. The valid case-insensitive modes are "Base64", "modBase64",
// "Base32", "UU", "QP" (for quoted-printable), "URL" (for url-encoding), "Hex",
// "Q", "B", "url_oath", "url_rfc1738", "url_rfc2396", and "url_rfc3986".
void get_EncodingMode(CkString &str);
// Determines the encoding mode used for getting/setting various properties, such
// as ClientChallenge. The valid case-insensitive modes are "Base64", "modBase64",
// "Base32", "UU", "QP" (for quoted-printable), "URL" (for url-encoding), "Hex",
// "Q", "B", "url_oath", "url_rfc1738", "url_rfc2396", and "url_rfc3986".
const char *encodingMode(void);
// Determines the encoding mode used for getting/setting various properties, such
// as ClientChallenge. The valid case-insensitive modes are "Base64", "modBase64",
// "Base32", "UU", "QP" (for quoted-printable), "URL" (for url-encoding), "Hex",
// "Q", "B", "url_oath", "url_rfc1738", "url_rfc2396", and "url_rfc3986".
void put_EncodingMode(const char *newVal);
// The negotiate flags that are set in the Type 1 message generated by the client
// and sent to the server. These flags have a default value and should ONLY be set
// by a programmer that is an expert in the NTLM protocol and knows what they mean.
// In general, this property should be left at it's default value.
//
// The flags are represented as a string of letters, where each letter represents a
// bit. The full set of possible flags (bit values) are shown below:
// NegotiateUnicode 0x00000001
// NegotiateOEM 0x00000002
// RequestTarget 0x00000004
// NegotiateSign 0x00000010
// NegotiateSeal 0x00000020
// NegotiateDatagramStyle 0x00000040
// NegotiateLanManagerKey 0x00000080
// NegotiateNetware 0x00000100
// NegotiateNTLMKey 0x00000200
// NegotiateDomainSupplied 0x00001000
// NegotiateWorkstationSupplied 0x00002000
// NegotiateLocalCall 0x00004000
// NegotiateAlwaysSign 0x00008000
// TargetTypeDomain 0x00010000
// TargetTypeServer 0x00020000
// TargetTypeShare 0x00040000
// NegotiateNTLM2Key 0x00080000
// RequestInitResponse 0x00100000
// RequestAcceptResponse 0x00200000
// RequestNonNTSessionKey 0x00400000
// NegotiateTargetInfo 0x00800000
// Negotiate128 0x20000000
// NegotiateKeyExchange 0x40000000
// Negotiate56 0x80000000
// The mapping of letters to bit values are as follows:
// 0x01 - "A"
// 0x02 - "B"
// 0x04 - "C"
// 0x10 - "D"
// 0x20 - "E"
// 0x40 - "F"
// 0x80 - "G"
// 0x200 - "H"
// 0x400 - "I"
// 0x800 - "J"
// 0x1000 - "K"
// 0x2000 - "L"
// 0x8000 - "M"
// 0x10000 - "N"
// 0x20000 - "O"
// 0x40000 - "P"
// 0x80000 - "Q"
// 0x100000 - "R"
// 0x400000 - "S"
// 0x800000 - "T"
// 0x2000000 - "U"
// 0x20000000 - "V"
// 0x40000000 - "W"
// 0x80000000 - "X"
// The default Flags value has the following flags set: NegotiateUnicode,
// NegotiateOEM, RequestTarget, NegotiateNTLMKey, NegotiateAlwaysSign,
// NegotiateNTLM2Key. The corresponds to the string "ABCHMQ".
//
void get_Flags(CkString &str);
// The negotiate flags that are set in the Type 1 message generated by the client
// and sent to the server. These flags have a default value and should ONLY be set
// by a programmer that is an expert in the NTLM protocol and knows what they mean.
// In general, this property should be left at it's default value.
//
// The flags are represented as a string of letters, where each letter represents a
// bit. The full set of possible flags (bit values) are shown below:
// NegotiateUnicode 0x00000001
// NegotiateOEM 0x00000002
// RequestTarget 0x00000004
// NegotiateSign 0x00000010
// NegotiateSeal 0x00000020
// NegotiateDatagramStyle 0x00000040
// NegotiateLanManagerKey 0x00000080
// NegotiateNetware 0x00000100
// NegotiateNTLMKey 0x00000200
// NegotiateDomainSupplied 0x00001000
// NegotiateWorkstationSupplied 0x00002000
// NegotiateLocalCall 0x00004000
// NegotiateAlwaysSign 0x00008000
// TargetTypeDomain 0x00010000
// TargetTypeServer 0x00020000
// TargetTypeShare 0x00040000
// NegotiateNTLM2Key 0x00080000
// RequestInitResponse 0x00100000
// RequestAcceptResponse 0x00200000
// RequestNonNTSessionKey 0x00400000
// NegotiateTargetInfo 0x00800000
// Negotiate128 0x20000000
// NegotiateKeyExchange 0x40000000
// Negotiate56 0x80000000
// The mapping of letters to bit values are as follows:
// 0x01 - "A"
// 0x02 - "B"
// 0x04 - "C"
// 0x10 - "D"
// 0x20 - "E"
// 0x40 - "F"
// 0x80 - "G"
// 0x200 - "H"
// 0x400 - "I"
// 0x800 - "J"
// 0x1000 - "K"
// 0x2000 - "L"
// 0x8000 - "M"
// 0x10000 - "N"
// 0x20000 - "O"
// 0x40000 - "P"
// 0x80000 - "Q"
// 0x100000 - "R"
// 0x400000 - "S"
// 0x800000 - "T"
// 0x2000000 - "U"
// 0x20000000 - "V"
// 0x40000000 - "W"
// 0x80000000 - "X"
// The default Flags value has the following flags set: NegotiateUnicode,
// NegotiateOEM, RequestTarget, NegotiateNTLMKey, NegotiateAlwaysSign,
// NegotiateNTLM2Key. The corresponds to the string "ABCHMQ".
//
const char *flags(void);
// The negotiate flags that are set in the Type 1 message generated by the client
// and sent to the server. These flags have a default value and should ONLY be set
// by a programmer that is an expert in the NTLM protocol and knows what they mean.
// In general, this property should be left at it's default value.
//
// The flags are represented as a string of letters, where each letter represents a
// bit. The full set of possible flags (bit values) are shown below:
// NegotiateUnicode 0x00000001
// NegotiateOEM 0x00000002
// RequestTarget 0x00000004
// NegotiateSign 0x00000010
// NegotiateSeal 0x00000020
// NegotiateDatagramStyle 0x00000040
// NegotiateLanManagerKey 0x00000080
// NegotiateNetware 0x00000100
// NegotiateNTLMKey 0x00000200
// NegotiateDomainSupplied 0x00001000
// NegotiateWorkstationSupplied 0x00002000
// NegotiateLocalCall 0x00004000
// NegotiateAlwaysSign 0x00008000
// TargetTypeDomain 0x00010000
// TargetTypeServer 0x00020000
// TargetTypeShare 0x00040000
// NegotiateNTLM2Key 0x00080000
// RequestInitResponse 0x00100000
// RequestAcceptResponse 0x00200000
// RequestNonNTSessionKey 0x00400000
// NegotiateTargetInfo 0x00800000
// Negotiate128 0x20000000
// NegotiateKeyExchange 0x40000000
// Negotiate56 0x80000000
// The mapping of letters to bit values are as follows:
// 0x01 - "A"
// 0x02 - "B"
// 0x04 - "C"
// 0x10 - "D"
// 0x20 - "E"
// 0x40 - "F"
// 0x80 - "G"
// 0x200 - "H"
// 0x400 - "I"
// 0x800 - "J"
// 0x1000 - "K"
// 0x2000 - "L"
// 0x8000 - "M"
// 0x10000 - "N"
// 0x20000 - "O"
// 0x40000 - "P"
// 0x80000 - "Q"
// 0x100000 - "R"
// 0x400000 - "S"
// 0x800000 - "T"
// 0x2000000 - "U"
// 0x20000000 - "V"
// 0x40000000 - "W"
// 0x80000000 - "X"
// The default Flags value has the following flags set: NegotiateUnicode,
// NegotiateOEM, RequestTarget, NegotiateNTLMKey, NegotiateAlwaysSign,
// NegotiateNTLM2Key. The corresponds to the string "ABCHMQ".
//
void put_Flags(const char *newVal);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void get_NetBiosComputerName(CkString &str);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
const char *netBiosComputerName(void);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void put_NetBiosComputerName(const char *newVal);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void get_NetBiosDomainName(CkString &str);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
const char *netBiosDomainName(void);
// Optional. This is information that would be set by the server for inclusion in
// the "Target Info" internal portion of the Type 2 message. Note: If any optional
// "Target Info" fields are provided, then both NetBiosComputerName and
// NetBiosDomainName must be provided.
void put_NetBiosDomainName(const char *newVal);
// The version of the NTLM protocol to be used. Must be set to either 1 or 2. The
// default value is 1 (for NTLMv1). Setting this property equal to 2 selects
// NTLMv2.
int get_NtlmVersion(void);
// The version of the NTLM protocol to be used. Must be set to either 1 or 2. The
// default value is 1 (for NTLMv1). Setting this property equal to 2 selects
// NTLMv2.
void put_NtlmVersion(int newVal);
// If the "A" flag is unset, then Unicode strings are not used internally in the
// NTLM messages. Strings are instead represented using the OEM code page (i.e.
// charset, or character encoding) as specified here. In general, given that the
// Flags property should rarely be modified, and given that the "A" flag is set by
// default (meaning that Unicode is used), the OemCodePage property will not apply.
// The default value is the default OEM code page of the local computer.
int get_OemCodePage(void);
// If the "A" flag is unset, then Unicode strings are not used internally in the
// NTLM messages. Strings are instead represented using the OEM code page (i.e.
// charset, or character encoding) as specified here. In general, given that the
// Flags property should rarely be modified, and given that the "A" flag is set by
// default (meaning that Unicode is used), the OemCodePage property will not apply.
// The default value is the default OEM code page of the local computer.
void put_OemCodePage(int newVal);
// The password corresponding to the username of the account to be authenticated.
// This must be set by the client prior to generating and sending the Type 3
// message.
void get_Password(CkString &str);
// The password corresponding to the username of the account to be authenticated.
// This must be set by the client prior to generating and sending the Type 3
// message.
const char *password(void);
// The password corresponding to the username of the account to be authenticated.
// This must be set by the client prior to generating and sending the Type 3
// message.
void put_Password(const char *newVal);
// This is similar to the ClientChallenge in that it must contain 8 bytes.
//
// The ServerChallenge is passed in the Type 2 message from the server to the
// client. Because this is a string property, the bytes are get/set in encoded form
// (such as hex or base64) based on the value of the EncodingMode property. For
// example, if the EncodingMode property = "hex", then a hex representation of 8
// bytes should be used to set the ServerChallenge.
//
// Note: Setting the ServerChallenge is optional. If the ServerChallenge remains
// unset, it will be automatically set to 8 random bytes when the GenType2 method
// is called.
//
void get_ServerChallenge(CkString &str);
// This is similar to the ClientChallenge in that it must contain 8 bytes.
//
// The ServerChallenge is passed in the Type 2 message from the server to the
// client. Because this is a string property, the bytes are get/set in encoded form
// (such as hex or base64) based on the value of the EncodingMode property. For
// example, if the EncodingMode property = "hex", then a hex representation of 8
// bytes should be used to set the ServerChallenge.
//
// Note: Setting the ServerChallenge is optional. If the ServerChallenge remains
// unset, it will be automatically set to 8 random bytes when the GenType2 method
// is called.
//
const char *serverChallenge(void);
// This is similar to the ClientChallenge in that it must contain 8 bytes.
//
// The ServerChallenge is passed in the Type 2 message from the server to the
// client. Because this is a string property, the bytes are get/set in encoded form
// (such as hex or base64) based on the value of the EncodingMode property. For
// example, if the EncodingMode property = "hex", then a hex representation of 8
// bytes should be used to set the ServerChallenge.
//
// Note: Setting the ServerChallenge is optional. If the ServerChallenge remains
// unset, it will be automatically set to 8 random bytes when the GenType2 method
// is called.
//
void put_ServerChallenge(const char *newVal);
// The authentication realm in which the authenticating account has membership,
// such as a domain for domain accounts, or a server name for local machine
// accounts. The TargetName is used in the Type2 message sent from the server to
// the client.
void get_TargetName(CkString &str);
// The authentication realm in which the authenticating account has membership,
// such as a domain for domain accounts, or a server name for local machine
// accounts. The TargetName is used in the Type2 message sent from the server to
// the client.
const char *targetName(void);
// The authentication realm in which the authenticating account has membership,
// such as a domain for domain accounts, or a server name for local machine
// accounts. The TargetName is used in the Type2 message sent from the server to
// the client.
void put_TargetName(const char *newVal);
// The username of the account to be authenticated. This must be set by the client
// prior to generating and sending the Type 3 message.
void get_UserName(CkString &str);
// The username of the account to be authenticated. This must be set by the client
// prior to generating and sending the Type 3 message.
const char *userName(void);
// The username of the account to be authenticated. This must be set by the client
// prior to generating and sending the Type 3 message.
void put_UserName(const char *newVal);
// The value to be used in the optional workstation field in Type 1 message.
void get_Workstation(CkString &str);
// The value to be used in the optional workstation field in Type 1 message.
const char *workstation(void);
// The value to be used in the optional workstation field in Type 1 message.
void put_Workstation(const char *newVal);
// ----------------------
// Methods
// ----------------------
// Compares the internal contents of two Type3 messages to verify that the LM and
// NTLM response parts match. A server would typically compute the Type3 message by
// calling GenType3, and then compare it with the Type3 message received from the
// client. The method returns true if the responses match, and false if they do
// not.
bool CompareType3(const char *msg1, const char *msg2);
// Generates the Type 1 message. The Type 1 message is sent from Client to Server
// and initiates the NTLM authentication exchange.
bool GenType1(CkString &outStr);
// Generates the Type 1 message. The Type 1 message is sent from Client to Server
// and initiates the NTLM authentication exchange.
const char *genType1(void);
// Generates a Type2 message from a received Type1 message. The server-side
// generates the Type2 message and sends it to the client. This is the 2nd step in
// the NTLM protocol. The 1st step is the client generating the initial Type1
// message which is sent to the server.
bool GenType2(const char *type1Msg, CkString &outStr);
// Generates a Type2 message from a received Type1 message. The server-side
// generates the Type2 message and sends it to the client. This is the 2nd step in
// the NTLM protocol. The 1st step is the client generating the initial Type1
// message which is sent to the server.
const char *genType2(const char *type1Msg);
// Generates the final message in the NTLM authentication exchange. This message is
// sent from the client to the server. The Type 2 message received from the server
// is passed to GenType3. The Username and Password properties are finally used
// here in the generation of the Type 3 message. Note, the Password is never
// actually sent. It is used to compute a binary response that the server can then
// check, using the password it has on file, to verify that indeed the client
// must've used the correct password.
bool GenType3(const char *type2Msg, CkString &outStr);
// Generates the final message in the NTLM authentication exchange. This message is
// sent from the client to the server. The Type 2 message received from the server
// is passed to GenType3. The Username and Password properties are finally used
// here in the generation of the Type 3 message. Note, the Password is never
// actually sent. It is used to compute a binary response that the server can then
// check, using the password it has on file, to verify that indeed the client
// must've used the correct password.
const char *genType3(const char *type2Msg);
// The server-side should call this method with the Type 3 message received from
// the client. The LoadType3 method sets the following properties: Username,
// Domain, Workstation, and ClientChallenge, all of which are embedded within the
// Type 3 message.
//
// The server-side code may then use the Username to lookup the associated password
// and then it will itself call the GenType3 method to do the same computation as
// done by the client. The server then compares it's computed Type 3 message with
// the Type 3 message received from the client. If the Type 3 messages are exactly
// the same, then it must be that the client used the correct password, and
// therefore the client authentication is successful.
//
bool LoadType3(const char *type3Msg);
// For informational purposes only. Allows for the server-side to parse a Type 1
// message to get human-readable information about the contents.
bool ParseType1(const char *type1Msg, CkString &outStr);
// For informational purposes only. Allows for the server-side to parse a Type 1
// message to get human-readable information about the contents.
const char *parseType1(const char *type1Msg);
// For informational purposes only. Allows for the client-side to parse a Type 2
// message to get human-readable information about the contents.
bool ParseType2(const char *type2Msg, CkString &outStr);
// For informational purposes only. Allows for the client-side to parse a Type 2
// message to get human-readable information about the contents.
const char *parseType2(const char *type2Msg);
// For informational purposes only. Allows for the server-side to parse a Type 3
// message to get human-readable information about the contents.
bool ParseType3(const char *type3Msg, CkString &outStr);
// For informational purposes only. Allows for the server-side to parse a Type 3
// message to get human-readable information about the contents.
const char *parseType3(const char *type3Msg);
// Sets one of the negotiate flags to be used in the Type 1 message sent by the
// client. It should normally be unnecessary to modify the default flag settings.
// For more information about flags, see the description for the Flags property
// above.
bool SetFlag(const char *flagLetter, bool onOrOff);
// Unlocks the component. This must be called once prior to calling any other
// method.
bool UnlockComponent(const char *unlockCode);
// END PUBLIC INTERFACE
};
#if !defined(__sun__) && !defined(__sun)
#pragma pack (pop)
#endif
#endif
| 45.679181 | 85 | 0.69527 | [
"object"
] |
eca56cae15452fd4d4716b7d7b45cae4da4ef464 | 1,461 | h | C | camera/hal/rockchip/common/imageProcess/ImageScalerCore.h | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | camera/hal/rockchip/common/imageProcess/ImageScalerCore.h | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | camera/hal/rockchip/common/imageProcess/ImageScalerCore.h | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | /*
* Copyright (C) 2012-2017 Intel Corporation
* Copyright (c) 2017, Fuzhou Rockchip Electronics Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _IMAGESCALER_CORE_H_
#define _IMAGESCALER_CORE_H_
#include <memory>
#include <vector>
#include "CameraBuffer.h"
NAMESPACE_DECLARATION {
/**
* \class ImageScalerCore
*
*/
class ImageScalerCore {
public:
static status_t scaleFrame(std::shared_ptr<CameraBuffer> input,
std::shared_ptr<CameraBuffer> output);
static status_t cropRotateScaleFrame(std::shared_ptr<CameraBuffer> input,
std::shared_ptr<CameraBuffer> output,
int angle,
std::vector<uint8_t>& tempRotationBuffer,
std::vector<uint8_t>& tempScaleBuffer);
};
} NAMESPACE_DECLARATION_END
#endif // _IMAGESCALER_CORE_H_
| 33.976744 | 82 | 0.658453 | [
"vector"
] |
ecb3c4dbb987ac4a32c74a753372795c7bccb546 | 496 | h | C | src/geometry/bound.h | jonike/lumen | c35259f45a265d470afccb8b6282c8520eabdc95 | [
"MIT"
] | 2 | 2020-06-23T07:54:24.000Z | 2021-01-30T14:05:40.000Z | src/geometry/bound.h | jonike/lumen | c35259f45a265d470afccb8b6282c8520eabdc95 | [
"MIT"
] | null | null | null | src/geometry/bound.h | jonike/lumen | c35259f45a265d470afccb8b6282c8520eabdc95 | [
"MIT"
] | null | null | null | #ifndef LUMEN_BOUND_H
#define LUMEN_BOUND_H
#include "nex\matrix.h"
#include "nex\point.h"
#include "nex\ray.h"
namespace lumen {
class bound {
public:
bound();
bound(const nex::point& min, const nex::point& max);
bool intersect(const nex::ray&) const;
bool intersect(const nex::ray&, float* tmin, float* tmax) const;
void transform(const nex::matrix&);
void expand(const bound&);
nex::point min;
nex::point max;
};
}
#endif
| 18.37037 | 72 | 0.618952 | [
"transform"
] |
ecb93d352b5c7d4cdd6488fea42b2f30a7c23f66 | 6,551 | h | C | maptk/metrics.h | Purg/maptk | 3c6dbf441534bfc9bfe57268eae7c34a46753f2b | [
"BSD-3-Clause"
] | null | null | null | maptk/metrics.h | Purg/maptk | 3c6dbf441534bfc9bfe57268eae7c34a46753f2b | [
"BSD-3-Clause"
] | null | null | null | maptk/metrics.h | Purg/maptk | 3c6dbf441534bfc9bfe57268eae7c34a46753f2b | [
"BSD-3-Clause"
] | null | null | null | /*ckwg +29
* Copyright 2014-2016 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
* \brief Header for evaluation metric functions.
*/
#ifndef MAPTK_METRICS_H_
#define MAPTK_METRICS_H_
#include <vital/vital_config.h>
#include <maptk/maptk_export.h>
#include <vital/types/camera.h>
#include <vital/types/landmark.h>
#include <vital/types/feature.h>
#include <vital/types/track.h>
#include <vector>
#include <map>
#include <cmath>
namespace kwiver {
namespace maptk {
/// Compute the reprojection error vector of lm projected by cam compared to f
/**
* \param [in] cam is the camera used for projection
* \param [in] lm is the landmark projected into the camera
* \param [in] f is the measured feature point location
* \returns the vector between the projected lm and f in image space
*/
MAPTK_EXPORT
vital::vector_2d reprojection_error_vec(const vital::camera& cam,
const vital::landmark& lm,
const vital::feature& f);
/// Compute the square reprojection error of lm projected by cam compared to f
/**
* \param [in] cam is the camera used for projection
* \param [in] lm is the landmark projected into the camera
* \param [in] f is the measured feature point location
* \returns the squared distance between the projected lm and f in image space
*/
inline
double
reprojection_error_sqr(const vital::camera& cam,
const vital::landmark& lm,
const vital::feature& f)
{
return reprojection_error_vec(cam, lm, f).squaredNorm();
}
/// Compute the reprojection error of lm projected by cam compared to f
/**
* \param [in] cam is the camera used for projection
* \param [in] lm is the landmark projected into the camera
* \param [in] f is the measured feature point location
* \returns the distance between the projected lm and f in image space
*/
inline
double
reprojection_error(const vital::camera& cam,
const vital::landmark& lm,
const vital::feature& f)
{
return std::sqrt(reprojection_error_sqr(cam, lm, f));
}
/// Compute a vector of all reprojection errors in the data
/**
* \param [in] cameras is the map of frames/cameras used for projection
* \param [in] landmarks is the map ids/landmarks projected into the cameras
* \param [in] tracks is the set of tracks providing measurements
* \returns a vector containing one reprojection error for each observation
* (i.e. track state) that has a corresponding camera and landmark
*/
MAPTK_EXPORT
std::vector<double>
reprojection_errors(const std::map<vital::frame_id_t, vital::camera_sptr>& cameras,
const std::map<vital::landmark_id_t, vital::landmark_sptr>& landmarks,
const std::vector< vital::track_sptr>& tracks);
/// Compute the Root-Mean-Square-Error (RMSE) of the reprojections
/**
* \param [in] cameras is the map of frames/cameras used for projection
* \param [in] landmarks is the map ids/landmarks projected into the cameras
* \param [in] tracks is the set of tracks providing measurements
* \returns the RMSE between all landmarks projected by all cameras that have
* corresponding image measurements provided by the tracks
*/
MAPTK_EXPORT
double
reprojection_rmse(const std::map<vital::frame_id_t, vital::camera_sptr>& cameras,
const std::map<vital::landmark_id_t, vital::landmark_sptr>& landmarks,
const std::vector<vital::track_sptr>& tracks);
/// Compute the median of the reprojection errors
/**
* \param [in] cameras is the map of frames/cameras used for projection
* \param [in] landmarks is the map ids/landmarks projected into the cameras
* \param [in] tracks is the set of tracks providing measurements
* \returns the median reprojection error between all landmarks projected by
* all cameras that have corresponding image measurements provided
* by the tracks
*/
MAPTK_EXPORT
double
reprojection_median_error(const std::map<vital::frame_id_t, vital::camera_sptr>& cameras,
const std::map<vital::landmark_id_t, vital::landmark_sptr>& landmarks,
const std::vector<vital::track_sptr>& tracks);
/// Compute the median of the reprojection errors
/**
* \param [in] cameras is the map of frames/cameras used for projection
* \param [in] landmarks is the map ids/landmarks projected into the cameras
* \param [in] tracks is the set of tracks providing measurements
* \returns the median reprojection error between all landmarks projected by
* all cameras that have corresponding image measurements provided
* by the tracks
*/
MAPTK_EXPORT
double
reprojection_median_error(const std::map<vital::frame_id_t, vital::camera_sptr>& cameras,
const std::map<vital::landmark_id_t, vital::landmark_sptr>& landmarks,
const std::vector<vital::track_sptr>& tracks);
} // end namespace maptk
} // end namespace kwiver
#endif // MAPTK_METRICS_H_
| 39.227545 | 96 | 0.714395 | [
"vector"
] |
ecc0ea2ffd6cb0760220bc811a50021ab46735f1 | 16,946 | h | C | include/IDummyTransformationSceneNode.h | Erfan-Ahmadi/Nabla | 1ea023d3333f4fade4268b20ac878546fb4d5c82 | [
"Apache-2.0"
] | 2 | 2021-02-08T23:33:54.000Z | 2021-02-09T18:21:16.000Z | include/IDummyTransformationSceneNode.h | Erfan-Ahmadi/Nabla | 1ea023d3333f4fade4268b20ac878546fb4d5c82 | [
"Apache-2.0"
] | null | null | null | include/IDummyTransformationSceneNode.h | Erfan-Ahmadi/Nabla | 1ea023d3333f4fade4268b20ac878546fb4d5c82 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2019 - DevSH Graphics Programming Sp. z O.O.
// This file is part of the "Nabla Engine" and was originally part of the "Irrlicht Engine"
// For conditions of distribution and use, see copyright notice in nabla.h
// See the original file in irrlicht source for authors
#ifndef __NBL_I_DUMMY_TRANSFORMATION_SCENE_NODE_H_INCLUDED__
#define __NBL_I_DUMMY_TRANSFORMATION_SCENE_NODE_H_INCLUDED__
#include "nbl/core/IReferenceCounted.h"
#include "ISceneNodeAnimator.h"
#include <algorithm>
#include "matrix4x3.h"
#include "ESceneNodeTypes.h"
namespace nbl
{
namespace scene
{
class ISceneManager;
class ISceneNodeAnimator;
class IDummyTransformationSceneNode;
//! Typedef for array of scene nodes
typedef core::vector<IDummyTransformationSceneNode*> IDummyTransformationSceneNodeArray;
//! Typedef for array of scene node animators
typedef core::vector<ISceneNodeAnimator*> ISceneNodeAnimatorArray;
//! Dummy scene node for adding additional transformations to the scene tree.
/** This scene node does not render itself, and does not respond to set/getPosition,
set/getRotation and set/getScale. Its just a simple scene node that takes a
matrix as relative transformation, making it possible to insert any transformation
anywhere into the scene tree.
This scene node is for example used by the IAnimatedMeshSceneNode for emulating
joint scene nodes when playing skeletal animations.
*/
class IDummyTransformationSceneNode : public virtual core::IReferenceCounted
{
protected:
uint64_t lastTimeRelativeTransRead[5];
uint64_t relativeTransChanged;
bool relativeTransNeedsUpdate;
virtual ~IDummyTransformationSceneNode()
{
removeAll();
// delete all animators
ISceneNodeAnimatorArray::iterator ait = Animators.begin();
for (; ait != Animators.end(); ++ait)
(*ait)->drop();
}
public:
IDummyTransformationSceneNode(IDummyTransformationSceneNode* parent,
const core::vector3df& position = core::vector3df(0,0,0),
const core::vector3df& rotation = core::vector3df(0,0,0),
const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f)) :
RelativeTranslation(position), RelativeRotation(rotation), RelativeScale(scale),
Parent(0), relativeTransChanged(1), relativeTransNeedsUpdate(true)
{
memset(lastTimeRelativeTransRead,0,sizeof(uint64_t)*5);
if (parent)
parent->addChild(this);
updateAbsolutePosition();
}
virtual bool isISceneNode() const {return false;}
//! Returns a reference to the current relative transformation matrix.
/** This is the matrix, this scene node uses instead of scale, translation
and rotation. */
inline virtual const core::matrix4x3& getRelativeTransformationMatrix()
{
if (relativeTransNeedsUpdate)
{
RelativeTransformation.setRotationDegrees(RelativeRotation);
RelativeTransformation.setTranslation(RelativeTranslation);
//
RelativeTransformation(0,0) *= RelativeScale.X;
RelativeTransformation(1,0) *= RelativeScale.X;
RelativeTransformation(2,0) *= RelativeScale.X;
RelativeTransformation(0,1) *= RelativeScale.Y;
RelativeTransformation(1,1) *= RelativeScale.Y;
RelativeTransformation(2,1) *= RelativeScale.Y;
RelativeTransformation(0,2) *= RelativeScale.Z;
RelativeTransformation(1,2) *= RelativeScale.Z;
RelativeTransformation(2,2) *= RelativeScale.Z;
//
relativeTransChanged++;
relativeTransNeedsUpdate = false;
}
return RelativeTransformation;
}
//!
inline void setRelativeTransformationMatrix(const core::matrix4x3& tform)
{
RelativeTransformation = tform;
relativeTransChanged++;
relativeTransNeedsUpdate = false;
}
inline const uint64_t& getRelativeTransChangedHint() const {return relativeTransChanged;}
inline const uint64_t& getAbsoluteTransformLastRecomputeHint() const {return lastTimeRelativeTransRead[3];}
inline const core::vector3df& getScale()
{
if (lastTimeRelativeTransRead[0]<relativeTransChanged)
{
const core::matrix4x3& rel = getRelativeTransformationMatrix();
RelativeScale = rel.getScale();
lastTimeRelativeTransRead[0] = relativeTransChanged;
}
return RelativeScale;
}
inline void setScale(const core::vector3df& scale)
{
RelativeScale = scale;
relativeTransNeedsUpdate = true;
}
inline const core::vector3df& getRotation()
{
if (lastTimeRelativeTransRead[1]<relativeTransChanged)
{
const core::matrix4x3& rel = getRelativeTransformationMatrix();
RelativeRotation = rel.getRotationDegrees();
lastTimeRelativeTransRead[1] = relativeTransChanged;
}
return RelativeRotation;
}
inline void setRotation(const core::vector3df& rotation)
{
RelativeRotation = rotation;
relativeTransNeedsUpdate = true;
}
inline const core::vector3df& getPosition()
{
if (lastTimeRelativeTransRead[2]<relativeTransChanged)
{
const core::matrix4x3& rel = getRelativeTransformationMatrix();
RelativeTranslation = rel.getTranslation();
lastTimeRelativeTransRead[2] = relativeTransChanged;
}
return RelativeTranslation;
}
inline void setPosition(const core::vector3df& newpos)
{
RelativeTranslation = newpos;
relativeTransNeedsUpdate = true;
}
inline virtual bool needsAbsoluteTransformRecompute() const
{
if (relativeTransNeedsUpdate||lastTimeRelativeTransRead[3]<relativeTransChanged)
return true;
if (Parent)
return lastTimeRelativeTransRead[4]<Parent->getAbsoluteTransformLastRecomputeHint();
return false;
}
inline virtual size_t needsDeepAbsoluteTransformRecompute() const
{
const IDummyTransformationSceneNode* parentStack[1024];
parentStack[0] = this;
size_t stackSize=0;
while (parentStack[stackSize])
{
parentStack[++stackSize] = parentStack[stackSize];
if (stackSize>=1024)
break;
}
size_t maxStackSize = stackSize-1;
while (--stackSize)
{
if (parentStack[stackSize]->relativeTransNeedsUpdate||parentStack[stackSize]->lastTimeRelativeTransRead[3]<parentStack[stackSize]->relativeTransChanged)
return stackSize;
if (stackSize<maxStackSize)
{
if (parentStack[stackSize]->lastTimeRelativeTransRead[4]<parentStack[stackSize+1]->getAbsoluteTransformLastRecomputeHint())
return stackSize;
}
}
return 0xdeadbeefu;
}
inline const core::matrix4x3& getAbsoluteTransformation()
{
return AbsoluteTransformation;
}
//! Gets the absolute position of the node in world coordinates.
/** If you want the position of the node relative to its parent,
use getPosition() instead.
NOTE: For speed reasons the absolute position is not
automatically recalculated on each change of the relative
position or by a position change of an parent. Instead the
update usually happens once per frame in OnAnimate. You can enforce
an update with updateAbsolutePosition().
\return The current absolute position of the scene node (updated on last call of updateAbsolutePosition). */
inline core::vector3df getAbsolutePosition() const
{
return AbsoluteTransformation.getTranslation();
}
//! Updates the absolute position based on the relative and the parents position
/** Note: This does not recursively update the parents absolute positions, so if you have a deeper
hierarchy you might want to update the parents first.*/
inline virtual void updateAbsolutePosition()
{
bool recompute = relativeTransNeedsUpdate||lastTimeRelativeTransRead[3]<relativeTransChanged;
if (Parent)
{
uint64_t parentAbsoluteHint = Parent->getAbsoluteTransformLastRecomputeHint();
if (lastTimeRelativeTransRead[4] < parentAbsoluteHint)
{
lastTimeRelativeTransRead[4] = parentAbsoluteHint;
recompute = true;
}
// recompute if local transform has changed
if (recompute)
{
const core::matrix4x3& rel = getRelativeTransformationMatrix();
AbsoluteTransformation = concatenateBFollowedByA(Parent->getAbsoluteTransformation(),rel);
lastTimeRelativeTransRead[3] = relativeTransChanged;
}
}
else if (recompute)
{
AbsoluteTransformation = getRelativeTransformationMatrix();
lastTimeRelativeTransRead[3] = relativeTransChanged;
}
}
//! Returns a const reference to the list of all children.
/** \return The list of all children of this node. */
inline const IDummyTransformationSceneNodeArray& getChildren() const
{
return Children;
}
//! Changes the parent of the scene node.
/** \param newParent The new parent to be used. */
virtual void setParent(IDummyTransformationSceneNode* newParent)
{
if (newParent==Parent)
return;
if (newParent)
{
newParent->addChild(this);
lastTimeRelativeTransRead[4] = 0;
}
else
remove();
}
//! Returns the parent of this scene node
/** \return A pointer to the parent. */
inline IDummyTransformationSceneNode* getParent() const
{
return Parent;
}
//! Adds a child to this scene node.
/** If the scene node already has a parent it is first removed
from the other parent.
\param child A pointer to the new child. */
virtual void addChild(IDummyTransformationSceneNode* child)
{
if (!child || child == this || child->getParent() == this)
return;
child->grab();
child->remove(); // remove from old parent
IDummyTransformationSceneNodeArray::iterator insertionPoint = std::lower_bound(Children.begin(),Children.end(),child);
Children.insert(insertionPoint,child);
child->Parent = this;
child->lastTimeRelativeTransRead[4] = 0;
}
//! Removes a child from this scene node.
/** If found in the children list, the child pointer is also
dropped and might be deleted if no other grab exists.
\param child A pointer to the child which shall be removed.
\return True if the child was removed, and false if not,
e.g. because it couldn't be found in the children list. */
virtual bool removeChild(IDummyTransformationSceneNode* child)
{
IDummyTransformationSceneNodeArray::iterator found = std::lower_bound(Children.begin(),Children.end(),child);
if (found==Children.end() || *found!=child)
return false;
(*found)->Parent = 0;
(*found)->drop();
Children.erase(found);
return true;
}
//! Removes all children of this scene node
/** The scene nodes found in the children list are also dropped
and might be deleted if no other grab exists on them.
*/
virtual void removeAll()
{
IDummyTransformationSceneNodeArray::iterator it = Children.begin();
for (; it != Children.end(); ++it)
{
(*it)->Parent = 0;
(*it)->drop();
}
Children.clear();
}
//! Removes this scene node from the scene
/** If no other grab exists for this node, it will be deleted.
*/
virtual void remove()
{
if (Parent)
Parent->removeChild(this);
}
//! Adds an animator which should animate this node.
/** \param animator A pointer to the new animator. */
virtual void addAnimator(ISceneNodeAnimator* animator)
{
if (!animator)
return;
ISceneNodeAnimatorArray::iterator found = std::lower_bound(Animators.begin(),Animators.end(),animator);
///if (found!=Animators.end() && *found==animator) //already in there
///return;
animator->grab();
Animators.insert(found,animator);
}
//! Get a list of all scene node animators.
/** \return The list of animators attached to this node. */
inline const ISceneNodeAnimatorArray& getAnimators() const
{
return Animators;
}
//! Removes an animator from this scene node.
/** If the animator is found, it is also dropped and might be
deleted if not other grab exists for it.
\param animator A pointer to the animator to be deleted. */
virtual void removeAnimator(ISceneNodeAnimator* animator)
{
ISceneNodeAnimatorArray::iterator found = std::lower_bound(Animators.begin(),Animators.end(),animator);
if (found==Animators.end() || *found!=animator)
return;
(*found)->drop();
Animators.erase(found);
return;
}
//! Removes all animators from this scene node.
/** The animators might also be deleted if no other grab exists
for them. */
virtual void removeAnimators()
{
ISceneNodeAnimatorArray::iterator it = Animators.begin();
for (; it != Animators.end(); ++it)
(*it)->drop();
Animators.clear();
}
//! Returns type of the scene node
virtual ESCENE_NODE_TYPE getType() const { return ESNT_DUMMY_TRANSFORMATION; }
//! Creates a clone of this scene node and its children.
virtual IDummyTransformationSceneNode* clone(IDummyTransformationSceneNode* newParent=0, ISceneManager* newManager=0)
{
if (!newParent)
newParent = Parent;
IDummyTransformationSceneNode* nb = new IDummyTransformationSceneNode(newParent);
nb->cloneMembers(this, newManager);
nb->setRelativeTransformationMatrix(RelativeTransformation);
if ( newParent )
nb->drop();
return nb;
}
protected:
//! Pointer to the parent
IDummyTransformationSceneNode* Parent;
//! List of all children of this node
IDummyTransformationSceneNodeArray Children;
//! List of all animator nodes
ISceneNodeAnimatorArray Animators;
//! Absolute transformation of the node.
core::matrix4x3 AbsoluteTransformation;
//! Relative transformation of the node.
core::matrix4x3 RelativeTransformation;
//! Relative translation of the scene node.
core::vector3df RelativeTranslation;
//! Relative rotation of the scene node.
core::vector3df RelativeRotation;
//! Relative scale of the scene node.
core::vector3df RelativeScale;
//! A clone function for the IDummy... members.
/** This method can be used by clone() implementations of
derived classes
\param toCopyFrom The node from which the values are copied */
virtual void cloneMembers(IDummyTransformationSceneNode* toCopyFrom, ISceneManager* newManager)
{
AbsoluteTransformation = toCopyFrom->AbsoluteTransformation;
RelativeTranslation = toCopyFrom->RelativeTranslation;
RelativeTranslation = toCopyFrom->RelativeTranslation;
RelativeRotation = toCopyFrom->RelativeRotation;
RelativeScale = toCopyFrom->RelativeScale;
// clone children
IDummyTransformationSceneNodeArray::iterator it = toCopyFrom->Children.begin();
for (; it != toCopyFrom->Children.end(); ++it)
(*it)->clone(this, newManager);
// clone animators
ISceneNodeAnimatorArray::iterator ait = toCopyFrom->Animators.begin();
for (; ait != toCopyFrom->Animators.end(); ++ait)
{
ISceneNodeAnimator* anim = (*ait)->createClone(this, newManager);
if (anim)
{
addAnimator(anim);
anim->drop();
}
}
}
};
} // end namespace scene
} // end namespace nbl
#endif
| 34.868313 | 169 | 0.631653 | [
"render",
"vector",
"transform"
] |
eccd4c09566098bf83a159d4d61a80ff24c44d96 | 3,171 | c | C | c++/libvips/colour/XYZ2scRGB.c | aisaac-lab/washi | f7158cc2647dd2b688ab4cffb9f21d1a7fb76ef8 | [
"MIT"
] | 4 | 2019-05-12T09:24:03.000Z | 2022-03-21T15:34:17.000Z | c++/libvips/colour/XYZ2scRGB.c | aisaac-lab/washi | f7158cc2647dd2b688ab4cffb9f21d1a7fb76ef8 | [
"MIT"
] | null | null | null | c++/libvips/colour/XYZ2scRGB.c | aisaac-lab/washi | f7158cc2647dd2b688ab4cffb9f21d1a7fb76ef8 | [
"MIT"
] | 1 | 2019-10-17T18:00:50.000Z | 2019-10-17T18:00:50.000Z | /* Turn XYZ to scRGB colourspace.
*
* 11/12/12
* - from Yxy2XYZ.c
* 1/7/13
* - remove any ICC profile
* 25/11/14
* - oh argh, revert the above
*/
/*
This file is part of VIPS.
VIPS is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <stdio.h>
#include <math.h>
#include <vips/vips.h>
#include "pcolour.h"
typedef VipsColourTransform VipsXYZ2scRGB;
typedef VipsColourTransformClass VipsXYZ2scRGBClass;
G_DEFINE_TYPE( VipsXYZ2scRGB, vips_XYZ2scRGB, VIPS_TYPE_COLOUR_TRANSFORM );
/* We used to have the comment:
* We've converted to sRGB without a profile. We must remove any ICC
* profile left over from import or there will be a mismatch between
* pixel values and the attached profile.
But this isn't right, we often call things sRGB that we know are not true
sRGB, for example:
vips sharpen k2.jpg x.jpg
sharpen will treat k2 as being in sRGB space even if that image has a
profile. If we drop the profile, x.jpg is suddenly untagged.
*/
void
vips_XYZ2scRGB_line( VipsColour *colour, VipsPel *out, VipsPel **in, int width )
{
float * restrict p = (float *) in[0];
float * restrict q = (float *) out;
int i;
for( i = 0; i < width; i++ ) {
float X = p[0];
float Y = p[1];
float Z = p[2];
float R, G, B;
p += 3;
vips_col_XYZ2scRGB( X, Y, Z, &R, &G, &B );
q[0] = R;
q[1] = G;
q[2] = B;
q += 3;
}
}
static void
vips_XYZ2scRGB_class_init( VipsXYZ2scRGBClass *class )
{
VipsObjectClass *object_class = (VipsObjectClass *) class;
VipsColourClass *colour_class = VIPS_COLOUR_CLASS( class );
object_class->nickname = "XYZ2scRGB";
object_class->description = _( "transform XYZ to scRGB" );
colour_class->process_line = vips_XYZ2scRGB_line;
}
static void
vips_XYZ2scRGB_init( VipsXYZ2scRGB *XYZ2scRGB )
{
VipsColour *colour = VIPS_COLOUR( XYZ2scRGB );
colour->interpretation = VIPS_INTERPRETATION_scRGB;
}
/**
* vips_XYZ2scRGB:
* @in: input image
* @out: output image
* @...: %NULL-terminated list of optional named arguments
*
* Turn XYZ to scRGB.
*
* Returns: 0 on success, -1 on error
*/
int
vips_XYZ2scRGB( VipsImage *in, VipsImage **out, ... )
{
va_list ap;
int result;
va_start( ap, out );
result = vips_call_split( "XYZ2scRGB", ap, in, out );
va_end( ap );
return( result );
}
| 22.489362 | 80 | 0.692211 | [
"transform"
] |
eccfc3b64a39a6847bc9b3def1391e8b2636d943 | 2,006 | h | C | esphome/components/modbus_controller/switch/modbus_switch.h | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 249 | 2018-04-07T12:04:11.000Z | 2019-01-25T01:11:34.000Z | esphome/components/modbus_controller/switch/modbus_switch.h | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 243 | 2018-04-11T16:37:11.000Z | 2019-01-25T16:50:37.000Z | esphome/components/modbus_controller/switch/modbus_switch.h | OttoWinter/esphomeyaml | 6a85259e4d6d1b0a0f819688b8e555efcb99ecb0 | [
"MIT"
] | 40 | 2018-04-10T05:50:14.000Z | 2019-01-25T15:20:36.000Z | #pragma once
#include "esphome/components/modbus_controller/modbus_controller.h"
#include "esphome/components/switch/switch.h"
#include "esphome/core/component.h"
namespace esphome {
namespace modbus_controller {
class ModbusSwitch : public Component, public switch_::Switch, public SensorItem {
public:
ModbusSwitch(ModbusRegisterType register_type, uint16_t start_address, uint8_t offset, uint32_t bitmask,
uint8_t skip_updates, bool force_new_range) {
this->register_type = register_type;
this->start_address = start_address;
this->offset = offset;
this->bitmask = bitmask;
this->sensor_value_type = SensorValueType::BIT;
this->skip_updates = skip_updates;
this->register_count = 1;
if (register_type == ModbusRegisterType::HOLDING || register_type == ModbusRegisterType::COIL) {
this->start_address += offset;
this->offset = 0;
}
this->force_new_range = force_new_range;
};
void setup() override;
void write_state(bool state) override;
void dump_config() override;
void set_state(bool state) { this->state = state; }
void parse_and_publish(const std::vector<uint8_t> &data) override;
void set_parent(ModbusController *parent) { this->parent_ = parent; }
using transform_func_t = std::function<optional<bool>(ModbusSwitch *, bool, const std::vector<uint8_t> &)>;
using write_transform_func_t = std::function<optional<bool>(ModbusSwitch *, bool, std::vector<uint8_t> &)>;
void set_template(transform_func_t &&f) { this->publish_transform_func_ = f; }
void set_write_template(write_transform_func_t &&f) { this->write_transform_func_ = f; }
void set_use_write_mutiple(bool use_write_multiple) { this->use_write_multiple_ = use_write_multiple; }
protected:
ModbusController *parent_;
bool use_write_multiple_;
optional<transform_func_t> publish_transform_func_{nullopt};
optional<write_transform_func_t> write_transform_func_{nullopt};
};
} // namespace modbus_controller
} // namespace esphome
| 40.938776 | 109 | 0.752243 | [
"vector"
] |
ecd07734b0b8f2957450029dcee68a5ada44b7f9 | 3,230 | h | C | src/csapex_core/include/csapex/param/set_parameter.h | betwo/csapex | f2c896002cf6bd4eb7fba2903ebeea4a1e811191 | [
"BSD-3-Clause"
] | 21 | 2016-09-02T15:33:25.000Z | 2021-06-10T06:34:39.000Z | src/csapex_core/include/csapex/param/set_parameter.h | cogsys-tuebingen/csAPEX | e80051384e08d81497d7605e988cab8c19f6280f | [
"BSD-3-Clause"
] | null | null | null | src/csapex_core/include/csapex/param/set_parameter.h | cogsys-tuebingen/csAPEX | e80051384e08d81497d7605e988cab8c19f6280f | [
"BSD-3-Clause"
] | 10 | 2016-10-12T00:55:17.000Z | 2020-04-24T19:59:02.000Z | #ifndef SET_PARAMETER_H
#define SET_PARAMETER_H
/// COMPONENT
#include <csapex/param/parameter_impl.hpp>
#include <csapex_core/csapex_param_export.h>
#include <csapex/utility/any.h>
/// SYSTEM
#include <vector>
namespace csapex
{
namespace param
{
class CSAPEX_PARAM_EXPORT SetParameter : public ParameterImplementation<SetParameter>
{
public:
typedef std::shared_ptr<SetParameter> Ptr;
public:
SetParameter();
explicit SetParameter(const std::string& name, const ParameterDescription& description);
template <typename T>
SetParameter(const std::string& name, const ParameterDescription& description, T def) : SetParameter(name, description)
{
def_ = def;
}
virtual ~SetParameter();
const std::type_info& type() const override;
std::string toStringImpl() const override;
bool cloneDataFrom(const Clonable& other) override;
void doSerialize(YAML::Node& e) const override;
void doDeserialize(const YAML::Node& n) override;
void serialize(SerializationBuffer& data, SemanticVersion& version) const override;
void deserialize(const SerializationBuffer& data, const SemanticVersion& version) override;
bool accepts(const std::type_info& type) const override;
std::string defText() const;
template <typename T>
void setSet(const std::vector<std::pair<std::string, T> >& set)
{
set_.clear();
for (typename std::vector<std::pair<std::string, T> >::const_iterator it = set.begin(); it != set.end(); ++it) {
set_[it->first] = it->second;
}
}
template <typename T>
void setSet(const std::map<std::string, T>& set)
{
set_.clear();
for (typename std::map<std::string, T>::const_iterator it = set.begin(); it != set.end(); ++it) {
set_[it->first] = it->second;
}
scope_changed(this);
}
void setSet(const std::vector<std::string>& set);
std::vector<std::string> getSetTexts() const;
void setByName(const std::string& name);
std::string getText(int idx) const;
std::string getText() const;
template <typename T>
bool contains(const T& value);
bool contains(const std::any& value);
int noParameters() const;
protected:
void get_unsafe(std::any& out) const override;
bool set_unsafe(const std::any& v) override;
template <typename T>
void doSerializeImplementation(const std::string& type_name, YAML::Node& e) const;
template <typename T>
void doDeserializeImplementation(const std::string& type_name, const YAML::Node& n);
std::string convertToString(const std::any& v) const;
private:
template <typename T>
T read(const std::any& var) const
{
try {
return std::any_cast<T>(var);
} catch (const std::bad_any_cast& e) {
throw std::logic_error(std::string("typeof SetParameter is not ") + typeid(T).name() + ": " + e.what());
}
}
private:
std::any value_;
std::string txt_;
std::map<std::string, std::any> set_;
std::any def_;
};
template <>
inline std::string serializationName<SetParameter>()
{
return "set";
}
} // namespace param
} // namespace csapex
#endif // SET_PARAMETER_H
| 26.694215 | 123 | 0.660062 | [
"vector"
] |
ecd15afdac6353449653ba46094ebcec018550aa | 3,390 | h | C | WebLayoutCore/Source/WebCore/dom/ExtensionStyleSheets.h | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | 1 | 2020-05-25T16:06:49.000Z | 2020-05-25T16:06:49.000Z | WebLayoutCore/Source/WebCore/dom/ExtensionStyleSheets.h | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | null | null | null | WebLayoutCore/Source/WebCore/dom/ExtensionStyleSheets.h | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | 1 | 2018-07-10T10:53:18.000Z | 2018-07-10T10:53:18.000Z | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2004-2010, 2012-2013, 2015 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#pragma once
#include <memory>
#include <wtf/FastMalloc.h>
#include <wtf/HashMap.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include <wtf/text/WTFString.h>
#if ENABLE(CONTENT_EXTENSIONS)
#include "ContentExtensionStyleSheet.h"
#endif
namespace WebCore {
class CSSStyleSheet;
class Document;
class Node;
class StyleSheet;
class StyleSheetContents;
class StyleSheetList;
class ExtensionStyleSheets {
WTF_MAKE_FAST_ALLOCATED;
public:
explicit ExtensionStyleSheets(Document&);
CSSStyleSheet* pageUserSheet();
const Vector<RefPtr<CSSStyleSheet>>& documentUserStyleSheets() const { return m_userStyleSheets; }
const Vector<RefPtr<CSSStyleSheet>>& injectedUserStyleSheets() const;
const Vector<RefPtr<CSSStyleSheet>>& injectedAuthorStyleSheets() const;
const Vector<RefPtr<CSSStyleSheet>>& authorStyleSheetsForTesting() const { return m_authorStyleSheetsForTesting; }
void clearPageUserSheet();
void updatePageUserSheet();
void invalidateInjectedStyleSheetCache();
void updateInjectedStyleSheetCache() const;
void addUserStyleSheet(Ref<StyleSheetContents>&&);
void addAuthorStyleSheetForTesting(Ref<StyleSheetContents>&&);
#if ENABLE(CONTENT_EXTENSIONS)
void addDisplayNoneSelector(const String& identifier, const String& selector, uint32_t selectorID);
void maybeAddContentExtensionSheet(const String& identifier, StyleSheetContents&);
#endif
void detachFromDocument();
private:
Document& m_document;
RefPtr<CSSStyleSheet> m_pageUserSheet;
mutable Vector<RefPtr<CSSStyleSheet>> m_injectedUserStyleSheets;
mutable Vector<RefPtr<CSSStyleSheet>> m_injectedAuthorStyleSheets;
mutable bool m_injectedStyleSheetCacheValid { false };
Vector<RefPtr<CSSStyleSheet>> m_userStyleSheets;
Vector<RefPtr<CSSStyleSheet>> m_authorStyleSheetsForTesting;
#if ENABLE(CONTENT_EXTENSIONS)
HashMap<String, RefPtr<CSSStyleSheet>> m_contentExtensionSheets;
HashMap<String, RefPtr<ContentExtensions::ContentExtensionStyleSheet>> m_contentExtensionSelectorSheets;
#endif
};
} // namespace WebCore
| 35.3125 | 118 | 0.760472 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.