hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 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 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | 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 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
862dbd381c687467d22b0b25f68e05d5030ee81b
| 828
|
cc
|
C++
|
src/engine/assets/audio_manager.cc
|
ProjectSulphur/ProjectSulphur
|
cb9ee8298f5020fda4a9130802e72034408f050f
|
[
"Apache-2.0"
] | 11
|
2017-12-19T14:33:02.000Z
|
2022-03-26T00:34:48.000Z
|
src/engine/assets/audio_manager.cc
|
ProjectSulphur/ProjectSulphur
|
cb9ee8298f5020fda4a9130802e72034408f050f
|
[
"Apache-2.0"
] | 1
|
2018-05-28T10:32:32.000Z
|
2018-05-28T10:32:35.000Z
|
src/engine/assets/audio_manager.cc
|
ProjectSulphur/ProjectSulphur
|
cb9ee8298f5020fda4a9130802e72034408f050f
|
[
"Apache-2.0"
] | 1
|
2021-01-25T11:31:57.000Z
|
2021-01-25T11:31:57.000Z
|
#include "engine/assets/audio_manager.h"
#include "engine/audio/audio_bank.h"
#include <foundation/io/binary_reader.h>
#include <foundation/memory/memory.h>
#include <foundation/pipeline-assets/audio.h>
#include <foundation/io/filesystem.h>
namespace sulphur
{
namespace engine
{
//--------------------------------------------------------------------------------
AudioBankData* AudioManager::ImportAsset(const foundation::Path& asset_file)
{
foundation::BinaryReader reader(
foundation::Path(application_->project_directory()) + asset_file);
if (reader.is_ok())
{
AudioBankData* audio_bank = foundation::Memory::Construct<AudioBankData>();
*audio_bank = reader.Read<foundation::AudioBankData>();
return audio_bank;
}
return nullptr;
}
}
}
| 26.709677
| 86
| 0.621981
|
ProjectSulphur
|
863449e05350490113ac883727fff2a77329627f
| 742
|
cpp
|
C++
|
plugins/x11input/src/device/valuator/make_absolute.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
plugins/x11input/src/device/valuator/make_absolute.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
plugins/x11input/src/device/valuator/make_absolute.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// 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)
#include <sge/x11input/device/valuator/absolute.hpp>
#include <sge/x11input/device/valuator/make_absolute.hpp>
#include <sge/x11input/device/valuator/value.hpp>
#include <fcppt/config/external_begin.hpp>
#include <X11/extensions/XInput2.h>
#include <fcppt/config/external_end.hpp>
sge::x11input::device::valuator::absolute
sge::x11input::device::valuator::make_absolute(XIValuatorClassInfo const &_info)
{
return sge::x11input::device::valuator::absolute{
sge::x11input::device::valuator::value{_info.value}};
}
| 39.052632
| 80
| 0.747978
|
cpreh
|
863524fffb7b903b4b172c469a7f4f11c4fa1c22
| 4,199
|
cpp
|
C++
|
NbrhdNash/Scenes/scene_Settings.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
NbrhdNash/Scenes/scene_Settings.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
NbrhdNash/Scenes/scene_Settings.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <thread>
#include "LevelSystem.h"
#include "scene_Settings.h"
#include "scene_MainMenu.h"
#include "../lib_ecm/components/cmp_text.h"
#include "../game.h"
#include "SFML/Window.hpp"
#include "SFML/Window/Joystick.hpp"
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
using namespace sf;
void Settings::Load() {
tag = -1;
sf::Joystick::Identification joystickID = sf::Joystick::getIdentification(0);
auto esc = makeEntity();
esc->setPosition(Vector2f(5, 5));
if (Joystick::isConnected(0)) {
auto y = esc->addComponent<ESCTextComponent>("Press Start to exit the game");
}
else {
auto y = esc->addComponent<ESCTextComponent>("Press ESC to exit the game");
}
auto info = makeEntity();
info->setPosition(Vector2f(Engine::getWindowSize().x * 0.3, Engine::getWindowSize().y * 0.2));
if (Joystick::isConnected(0)) {
auto i = info->addComponent<TextComponent>("CONTROLS:\nRT for acceleration\nLT for braking\nLeft Joystick for turning\n\nPress BACK to save settings");
}
else {
auto i = info->addComponent<TextComponent>("CONTROLS:\nW for acceleration\nS for braking\nA for turning left\nD for turning rightz\n\nPress X to save settings");
}
auto info2 = makeEntity();
info2->setPosition(Vector2f(Engine::getWindowSize().x * 0.5, Engine::getWindowSize().y * 0.2));
if (Joystick::isConnected(0)) {
auto i2 = info2->addComponent<TextComponent>("SELECT RESOLUTION:\nA: 1280 x 720\nY: 1920 x 1080\nX: 2560 x 1440\n\nV-SYNC:\nLB: On\nRB: Off");
}
else {
auto i2 = info2->addComponent<TextComponent>("SELECT RESOLUTION:\nQ: 1280 x 720\nW: 1920 x 1080\nE: 2560 x 1440\n\nV-SYNC:\nV: On\nB: Off");
}
setLoaded(true);
}
void Settings::UnLoad() {
Scene::UnLoad();
}
void Settings::Update(const double& dt) {
Scene::Update(dt);
if (Keyboard::isKeyPressed(Keyboard::Q)) {
resTag = 1;
imageSetting = "Q ";
Settings::UnLoad();
Settings::Load();
}
if (Keyboard::isKeyPressed(Keyboard::W)) {
resTag = 2;
imageSetting = "W ";
Settings::UnLoad();
Settings::Load();
}
if (Keyboard::isKeyPressed(Keyboard::E)) {
resTag = 3;
imageSetting = "E ";
Settings::UnLoad();
Settings::Load();
}
if (Keyboard::isKeyPressed(Keyboard::V)) {
Engine::setVsync(true);
vsyncSetting = "V ";
}
if (Keyboard::isKeyPressed(Keyboard::B)) {
Engine::setVsync(false);
vsyncSetting = "B ";
}
if (Keyboard::isKeyPressed(Keyboard::X)) {
saveSettings();
}
if (Joystick::isConnected(0)) {
if (sf::Joystick::isButtonPressed(0, 0)) {
resTag = 1;
imageSetting = "Q ";
Settings::UnLoad();
Settings::Load();
}
if (sf::Joystick::isButtonPressed(0, 3)) {
resTag = 2;
imageSetting = "W ";
Settings::UnLoad();
Settings::Load();
}
if (sf::Joystick::isButtonPressed(0, 2)) {
resTag = 3;
imageSetting = "E ";
Settings::UnLoad();
Settings::Load();
}
if (sf::Joystick::isButtonPressed(0, 4)) {
Engine::setVsync(true);
vsyncSetting = "V ";
}
if (sf::Joystick::isButtonPressed(0, 5)) {
Engine::setVsync(false);
vsyncSetting = "B ";
}
if (sf::Joystick::isButtonPressed(0, 7)) {
saveSettings();
}
}
}
void Settings::Render() {
Scene::Render();
}
void Settings::saveSettings() {
settingsFile.open("settings.txt", std::ios_base::out);
settingsFile << imageSetting;
settingsFile << vsyncSetting;
settingsFile.close();
}
//Helper function for ingesting file if it exists
void Settings::ingestFile() {
std::string line;
ifstream settingsFileIn;
settingsFileIn.open("settings.txt", std::ios_base::in);
//checking if file is empty
if (settingsFileIn.is_open()) {
while (!settingsFileIn.eof()) {
line.resize(settingsFileIn.tellg());
settingsFileIn >> line;
lines.push_back(line);
counter++;
}
}
if (counter-1 == 1) {
if (lines[0] == "Q") {
imageSetting = lines[0];
}
if (lines[0] == "W") {
imageSetting = lines[0];
}
if (lines[0] == "E") {
imageSetting = lines[0];
}
if (lines[0] == "V") {
vsyncSetting = lines[0];
}
if (lines[0] == "B") {
vsyncSetting = lines[0];
}
}
if (counter-1 == 2) {
imageSetting = lines[0];
vsyncSetting = lines[1];
}
settingsFileIn.close();
}
| 24.412791
| 163
| 0.652536
|
OlavJDigranes
|
8636367d660d21365ef92c917705ef5c797ce508
| 25,150
|
cpp
|
C++
|
src/runtime/Spprintf.cpp
|
normal-coder/polarphp
|
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
|
[
"PHP-3.01"
] | 1
|
2019-01-28T01:33:49.000Z
|
2019-01-28T01:33:49.000Z
|
src/runtime/Spprintf.cpp
|
normal-coder/polarphp
|
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
|
[
"PHP-3.01"
] | null | null | null |
src/runtime/Spprintf.cpp
|
normal-coder/polarphp
|
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
|
[
"PHP-3.01"
] | null | null | null |
// This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2018 polarphp software foundation
// Copyright (c) 2017 - 2018 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/12/25.
/* This is the spprintf implementation.
* It has emerged from apache snprintf. See original header:
*/
/* ====================================================================
* Copyright (c) 1995-1998 The Apache Group. 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.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the Apache Group
* for use in the Apache HTTP server project (http://www.apache.org/)."
*
* 4. The names "Apache Server" and "Apache Group" must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 5. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the Apache Group
* for use in the Apache HTTP server project (http://www.apache.org/)."
*
* THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``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 THE APACHE GROUP OR
* ITS 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Group and was originally based
* on public domain software written at the National Center for
* Supercomputing Applications, University of Illinois, Urbana-Champaign.
* For more information on the Apache Group and the Apache HTTP server
* project, please see <http://www.apache.org/>.
*
* This code is based on, and used with the permission of, the
* SIO stdio-replacement strx_* functions by Panos Tsirigotis
* <panos@alumni.cs.colorado.edu> for xinetd.
*/
#include "polarphp/runtime/internal/DepsZendVmHeaders.h"
#include "polarphp/runtime/Spprintf.h"
#include "polarphp/runtime/Snprintf.h"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stddef.h>
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#ifdef ZTS
#define LCONV_DECIMAL_POINT (*lconv.decimal_point)
#else
#define LCONV_DECIMAL_POINT (*lconv->decimal_point)
#endif
#else
#define LCONV_DECIMAL_POINT '.'
#endif
#define FALSE 0
#define TRUE 1
#define NUL '\0'
#define INT_NULL ((int *)0)
#define S_NULL const_cast<char *>("(null)")
#define S_NULL_LEN 6
#define FLOAT_DIGITS 6
#define EXPONENT_LENGTH 10
#define INS_CHAR(xbuf, ch, is_char) do { \
if ((is_char)) { \
smart_string_appendc((smart_string *)(xbuf), (ch)); \
} else { \
smart_str_appendc((smart_str *)(xbuf), (ch)); \
} \
} while (0);
#define INS_STRING(xbuf, str, len, is_char) do { \
if ((is_char)) { \
smart_string_appendl((smart_string *)(xbuf), (str), (len)); \
} else { \
smart_str_appendl((smart_str *)(xbuf), (str), (len)); \
} \
} while (0);
#define PAD_CHAR(xbuf, ch, count, is_char) do { \
if ((is_char)) { \
smart_string_alloc(((smart_string *)(xbuf)), (count), 0); \
memset(((smart_string *)(xbuf))->c + ((smart_string *)(xbuf))->len, (ch), (count)); \
((smart_string *)(xbuf))->len += (count); \
} else { \
smart_str_alloc(((smart_str *)(xbuf)), (count), 0); \
memset(ZSTR_VAL(((smart_str *)(xbuf))->s) + ZSTR_LEN(((smart_str *)(xbuf))->s), (ch), (count)); \
ZSTR_LEN(((smart_str *)(xbuf))->s) += (count); \
} \
} while (0);
/*
* NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
* which can be at most max length of double
*/
#define NUM_BUF_SIZE PHP_DOUBLE_MAX_LENGTH
#define NUM(c) (c - '0')
#define STR_TO_DEC(str, num) do { \
num = NUM(*str++); \
while (isdigit((int)*str)) { \
num *= 10; \
num += NUM(*str++); \
if (num >= INT_MAX / 10) { \
while (isdigit((int)*str++)); \
break; \
} \
} \
} while (0)
/*
* This macro does zero padding so that the precision
* requirement is satisfied. The padding is done by
* adding '0's to the left of the string that is going
* to be printed.
*/
#define FIX_PRECISION(adjust, precision, s, s_len) do { \
if (adjust) \
while (s_len < (size_t)precision) { \
*--s = '0'; \
s_len++; \
} \
} while (0)
#if !HAVE_STRNLEN
static size_t strnlen(const char *s, size_t maxlen)
{
char *r = memchr(s, '\0', maxlen);
return r ? r-s : maxlen;
}
#endif
namespace polar {
namespace runtime {
/*
* Do format conversion placing the output in buffer
*/
static void xbuf_format_converter(void *xbuf, zend_bool is_char, const char *fmt, va_list ap) /* {{{ */
{
char *s = nullptr;
size_t s_len;
int free_zcopy;
zval *zvp, zcopy;
int min_width = 0;
int precision = 0;
enum {
LEFT, RIGHT
} adjust;
char pad_char;
char prefix_char;
double fp_num;
wide_int i_num = (wide_int) 0;
u_wide_int ui_num = (u_wide_int) 0;
char num_buf[NUM_BUF_SIZE];
char char_buf[2]; /* for printing %% and %<unknown> */
#ifdef HAVE_LOCALE_H
#ifdef ZTS
struct lconv lconv;
#else
struct lconv *lconv = nullptr;
#endif
#endif
/*
* Flag variables
*/
length_modifier_e modifier;
boolean_e alternate_form;
boolean_e print_sign;
boolean_e print_blank;
boolean_e adjust_precision;
boolean_e adjust_width;
bool_int is_negative;
while (*fmt) {
if (*fmt != '%') {
INS_CHAR(xbuf, *fmt, is_char);
} else {
/*
* Default variable settings
*/
adjust = RIGHT;
alternate_form = print_sign = print_blank = NO;
pad_char = ' ';
prefix_char = NUL;
free_zcopy = 0;
fmt++;
/*
* Try to avoid checking for flags, width or precision
*/
if (isascii((int)*fmt) && !islower((int)*fmt)) {
/*
* Recognize flags: -, #, BLANK, +
*/
for (;; fmt++) {
if (*fmt == '-')
adjust = LEFT;
else if (*fmt == '+')
print_sign = YES;
else if (*fmt == '#')
alternate_form = YES;
else if (*fmt == ' ')
print_blank = YES;
else if (*fmt == '0')
pad_char = '0';
else
break;
}
/*
* Check if a width was specified
*/
if (isdigit((int)*fmt)) {
STR_TO_DEC(fmt, min_width);
adjust_width = YES;
} else if (*fmt == '*') {
min_width = va_arg(ap, int);
fmt++;
adjust_width = YES;
if (min_width < 0) {
adjust = LEFT;
min_width = -min_width;
}
} else
adjust_width = NO;
/*
* Check if a precision was specified
*/
if (*fmt == '.') {
adjust_precision = YES;
fmt++;
if (isdigit((int)*fmt)) {
STR_TO_DEC(fmt, precision);
} else if (*fmt == '*') {
precision = va_arg(ap, int);
fmt++;
if (precision < -1)
precision = -1;
} else
precision = 0;
if (precision > FORMAT_CONV_MAX_PRECISION) {
precision = FORMAT_CONV_MAX_PRECISION;
}
} else
adjust_precision = NO;
} else
adjust_precision = adjust_width = NO;
/*
* Modifier check
*/
switch (*fmt) {
case 'L':
fmt++;
modifier = LM_LONG_DOUBLE;
break;
case 'I':
fmt++;
#if SIZEOF_LONG_LONG
if (*fmt == '6' && *(fmt+1) == '4') {
fmt += 2;
modifier = LM_LONG_LONG;
} else
#endif
if (*fmt == '3' && *(fmt+1) == '2') {
fmt += 2;
modifier = LM_LONG;
} else {
#ifdef _WIN64
modifier = LM_LONG_LONG;
#else
modifier = LM_LONG;
#endif
}
break;
case 'l':
fmt++;
#if SIZEOF_LONG_LONG
if (*fmt == 'l') {
fmt++;
modifier = LM_LONG_LONG;
} else
#endif
modifier = LM_LONG;
break;
case 'z':
fmt++;
modifier = LM_SIZE_T;
break;
case 'j':
fmt++;
#if SIZEOF_INTMAX_T
modifier = LM_INTMAX_T;
#else
modifier = LM_SIZE_T;
#endif
break;
case 't':
fmt++;
#if SIZEOF_PTRDIFF_T
modifier = LM_PTRDIFF_T;
#else
modifier = LM_SIZE_T;
#endif
break;
case 'p': {
char __next = *(fmt+1);
if ('d' == __next || 'u' == __next || 'x' == __next || 'o' == __next) {
fmt++;
modifier = LM_PHP_INT_T;
} else {
modifier = LM_STD;
}
}
break;
case 'h':
fmt++;
if (*fmt == 'h') {
fmt++;
}
POLAR_FALLTHROUGH;
/* these are promoted to int, so no break */
default:
modifier = LM_STD;
break;
}
/*
* Argument extraction and printing.
* First we determine the argument type.
* Then, we convert the argument to a string.
* On exit from the switch, s points to the string that
* must be printed, s_len has the length of the string
* The precision requirements, if any, are reflected in s_len.
*
* NOTE: pad_char may be set to '0' because of the 0 flag.
* It is reset to ' ' by non-numeric formats
*/
switch (*fmt) {
case 'Z': {
zvp = (zval*) va_arg(ap, zval*);
free_zcopy = zend_make_printable_zval(zvp, &zcopy);
if (free_zcopy) {
zvp = &zcopy;
}
s_len = Z_STRLEN_P(zvp);
s = Z_STRVAL_P(zvp);
if (adjust_precision && (size_t)precision < s_len) {
s_len = precision;
}
break;
}
case 'u':
switch(modifier) {
default:
i_num = (wide_int) va_arg(ap, unsigned int);
break;
case LM_LONG_DOUBLE:
goto fmt_error;
case LM_LONG:
i_num = (wide_int) va_arg(ap, unsigned long int);
break;
case LM_SIZE_T:
i_num = (wide_int) va_arg(ap, size_t);
break;
#if SIZEOF_LONG_LONG
case LM_LONG_LONG:
i_num = (wide_int) va_arg(ap, u_wide_int);
break;
#endif
#if SIZEOF_INTMAX_T
case LM_INTMAX_T:
i_num = (wide_int) va_arg(ap, uintmax_t);
break;
#endif
#if SIZEOF_PTRDIFF_T
case LM_PTRDIFF_T:
i_num = (wide_int) va_arg(ap, ptrdiff_t);
break;
#endif
case LM_PHP_INT_T:
i_num = (wide_int) va_arg(ap, zend_ulong);
break;
}
POLAR_FALLTHROUGH;
/*
* The rest also applies to other integer formats, so fall
* into that case.
*/
case 'd':
POLAR_FALLTHROUGH;
case 'i':
/*
* Get the arg if we haven't already.
*/
if ((*fmt) != 'u') {
switch(modifier) {
default:
i_num = (wide_int) va_arg(ap, int);
break;
case LM_LONG_DOUBLE:
goto fmt_error;
case LM_LONG:
i_num = (wide_int) va_arg(ap, long int);
break;
case LM_SIZE_T:
#if SIZEOF_SSIZE_T
i_num = (wide_int) va_arg(ap, ssize_t);
#else
i_num = (wide_int) va_arg(ap, size_t);
#endif
break;
#if SIZEOF_LONG_LONG
case LM_LONG_LONG:
i_num = (wide_int) va_arg(ap, wide_int);
break;
#endif
#if SIZEOF_INTMAX_T
case LM_INTMAX_T:
i_num = (wide_int) va_arg(ap, intmax_t);
break;
#endif
#if SIZEOF_PTRDIFF_T
case LM_PTRDIFF_T:
i_num = (wide_int) va_arg(ap, ptrdiff_t);
break;
#endif
case LM_PHP_INT_T:
i_num = (wide_int) va_arg(ap, zend_long);
break;
}
}
s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,
&num_buf[NUM_BUF_SIZE], &s_len);
FIX_PRECISION(adjust_precision, precision, s, s_len);
if (*fmt != 'u') {
if (is_negative)
prefix_char = '-';
else if (print_sign)
prefix_char = '+';
else if (print_blank)
prefix_char = ' ';
}
break;
case 'o':
switch(modifier) {
default:
ui_num = (u_wide_int) va_arg(ap, unsigned int);
break;
case LM_LONG_DOUBLE:
goto fmt_error;
case LM_LONG:
ui_num = (u_wide_int) va_arg(ap, unsigned long int);
break;
case LM_SIZE_T:
ui_num = (u_wide_int) va_arg(ap, size_t);
break;
#if SIZEOF_LONG_LONG
case LM_LONG_LONG:
ui_num = (u_wide_int) va_arg(ap, u_wide_int);
break;
#endif
#if SIZEOF_INTMAX_T
case LM_INTMAX_T:
ui_num = (u_wide_int) va_arg(ap, uintmax_t);
break;
#endif
#if SIZEOF_PTRDIFF_T
case LM_PTRDIFF_T:
ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
break;
#endif
case LM_PHP_INT_T:
ui_num = (u_wide_int) va_arg(ap, zend_ulong);
break;
}
s = ap_php_conv_p2(ui_num, 3, *fmt,
&num_buf[NUM_BUF_SIZE], &s_len);
FIX_PRECISION(adjust_precision, precision, s, s_len);
if (alternate_form && *s != '0') {
*--s = '0';
s_len++;
}
break;
case 'x':
case 'X':
switch(modifier) {
default:
ui_num = (u_wide_int) va_arg(ap, unsigned int);
break;
case LM_LONG_DOUBLE:
goto fmt_error;
case LM_LONG:
ui_num = (u_wide_int) va_arg(ap, unsigned long int);
break;
case LM_SIZE_T:
ui_num = (u_wide_int) va_arg(ap, size_t);
break;
#if SIZEOF_LONG_LONG
case LM_LONG_LONG:
ui_num = (u_wide_int) va_arg(ap, u_wide_int);
break;
#endif
#if SIZEOF_INTMAX_T
case LM_INTMAX_T:
ui_num = (u_wide_int) va_arg(ap, uintmax_t);
break;
#endif
#if SIZEOF_PTRDIFF_T
case LM_PTRDIFF_T:
ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
break;
#endif
case LM_PHP_INT_T:
ui_num = (u_wide_int) va_arg(ap, zend_ulong);
break;
}
s = ap_php_conv_p2(ui_num, 4, *fmt,
&num_buf[NUM_BUF_SIZE], &s_len);
FIX_PRECISION(adjust_precision, precision, s, s_len);
if (alternate_form && ui_num != 0) {
*--s = *fmt; /* 'x' or 'X' */
*--s = '0';
s_len += 2;
}
break;
case 's':
case 'v':
s = va_arg(ap, char *);
if (s != nullptr) {
if (!adjust_precision) {
s_len = strlen(s);
} else {
s_len = strnlen(s, precision);
}
} else {
s = S_NULL;
s_len = S_NULL_LEN;
}
pad_char = ' ';
break;
case 'f':
case 'F':
case 'e':
case 'E':
switch(modifier) {
case LM_LONG_DOUBLE:
fp_num = (double) va_arg(ap, long double);
break;
case LM_STD:
fp_num = va_arg(ap, double);
break;
default:
goto fmt_error;
}
if (zend_isnan(fp_num)) {
s = const_cast<char *>("nan");
s_len = 3;
} else if (zend_isinf(fp_num)) {
s = const_cast<char *>("inf");
s_len = 3;
} else {
#ifdef HAVE_LOCALE_H
#ifdef ZTS
localeconv_r(&lconv);
#else
if (!lconv) {
lconv = localeconv();
}
#endif
#endif
s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,
(adjust_precision == NO) ? FLOAT_DIGITS : precision,
(*fmt == 'f')?LCONV_DECIMAL_POINT:'.',
&is_negative, &num_buf[1], &s_len);
if (is_negative)
prefix_char = '-';
else if (print_sign)
prefix_char = '+';
else if (print_blank)
prefix_char = ' ';
}
break;
case 'g':
case 'k':
case 'G':
case 'H':
switch(modifier) {
case LM_LONG_DOUBLE:
fp_num = (double) va_arg(ap, long double);
break;
case LM_STD:
fp_num = va_arg(ap, double);
break;
default:
goto fmt_error;
}
if (zend_isnan(fp_num)) {
s = const_cast<char *>("NAN");
s_len = 3;
break;
} else if (zend_isinf(fp_num)) {
if (fp_num > 0) {
s = const_cast<char *>("INF");
s_len = 3;
} else {
s = const_cast<char *>("-INF");
s_len = 4;
}
break;
}
if (adjust_precision == NO)
precision = FLOAT_DIGITS;
else if (precision == 0)
precision = 1;
/*
* * We use &num_buf[ 1 ], so that we have room for the sign
*/
#ifdef HAVE_LOCALE_H
#ifdef ZTS
localeconv_r(&lconv);
#else
if (!lconv) {
lconv = localeconv();
}
#endif
#endif
s = php_gcvt(fp_num, precision, (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT, (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);
if (*s == '-')
prefix_char = *s++;
else if (print_sign)
prefix_char = '+';
else if (print_blank)
prefix_char = ' ';
s_len = strlen(s);
if (alternate_form && (strchr(s, '.')) == nullptr)
s[s_len++] = '.';
break;
case 'c':
char_buf[0] = (char) (va_arg(ap, int));
s = &char_buf[0];
s_len = 1;
pad_char = ' ';
break;
case '%':
char_buf[0] = '%';
s = &char_buf[0];
s_len = 1;
pad_char = ' ';
break;
case 'n':
*(va_arg(ap, int *)) = is_char? (int)((smart_string *)xbuf)->len : (int)ZSTR_LEN(((smart_str *)xbuf)->s);
goto skip_output;
/*
* Always extract the argument as a "char *" pointer. We
* should be using "void *" but there are still machines
* that don't understand it.
* If the pointer size is equal to the size of an unsigned
* integer we convert the pointer to a hex number, otherwise
* we print "%p" to indicate that we don't handle "%p".
*/
case 'p':
if (sizeof(char *) <= sizeof(u_wide_int)) {
ui_num = (u_wide_int)((size_t) va_arg(ap, char *));
s = ap_php_conv_p2(ui_num, 4, 'x',
&num_buf[NUM_BUF_SIZE], &s_len);
if (ui_num != 0) {
*--s = 'x';
*--s = '0';
s_len += 2;
}
} else {
s = const_cast<char *>("%p");
s_len = 2;
}
pad_char = ' ';
break;
case NUL:
/*
* The last character of the format string was %.
* We ignore it.
*/
continue;
fmt_error:
php_error(E_ERROR, "Illegal length modifier specified '%c' in s[np]printf call", *fmt);
/*
* The default case is for unrecognized %'s.
* We print %<char> to help the user identify what
* option is not understood.
* This is also useful in case the user wants to pass
* the output of format_converter to another function
* that understands some other %<char> (like syslog).
* Note that we can't point s inside fmt because the
* unknown <char> could be preceded by width etc.
*/
POLAR_FALLTHROUGH;
default:
char_buf[0] = '%';
char_buf[1] = *fmt;
s = char_buf;
s_len = 2;
pad_char = ' ';
break;
}
if (prefix_char != NUL) {
*--s = prefix_char;
s_len++;
}
if (adjust_width && adjust == RIGHT && (size_t)min_width > s_len) {
if (pad_char == '0' && prefix_char != NUL) {
INS_CHAR(xbuf, *s, is_char);
s++;
s_len--;
min_width--;
}
PAD_CHAR(xbuf, pad_char, min_width - s_len, is_char);
}
/*
* Print the string s.
*/
INS_STRING(xbuf, s, s_len, is_char);
if (adjust_width && adjust == LEFT && (size_t)min_width > s_len) {
PAD_CHAR(xbuf, pad_char, min_width - s_len, is_char);
}
if (free_zcopy) {
zval_ptr_dtor_str(&zcopy);
}
}
skip_output:
fmt++;
}
return;
}
/* }}} */
void php_printf_to_smart_string(smart_string *buf, const char *format, va_list ap) /* {{{ */
{
xbuf_format_converter(buf, 1, format, ap);
}
void php_printf_to_smart_str(smart_str *buf, const char *format, va_list ap) /* {{{ */
{
xbuf_format_converter(buf, 0, format, ap);
}
} // runtime
} // polar
| 30.04779
| 151
| 0.484453
|
normal-coder
|
8636c6931c7698a57238c12fd7388e91097d6d4c
| 5,189
|
cpp
|
C++
|
munin/src/tabbed_panel.cpp
|
KazDragon/paradice9
|
bb89ce8bff2f99d2526f45b064bfdd3412feb992
|
[
"MIT"
] | 9
|
2015-12-16T07:00:39.000Z
|
2021-05-05T13:29:28.000Z
|
munin/src/tabbed_panel.cpp
|
KazDragon/paradice9
|
bb89ce8bff2f99d2526f45b064bfdd3412feb992
|
[
"MIT"
] | 43
|
2015-07-18T11:13:15.000Z
|
2017-07-15T13:18:43.000Z
|
munin/src/tabbed_panel.cpp
|
KazDragon/paradice9
|
bb89ce8bff2f99d2526f45b064bfdd3412feb992
|
[
"MIT"
] | 3
|
2015-10-09T13:33:35.000Z
|
2016-07-11T02:23:08.000Z
|
// ==========================================================================
// Munin Tabbed Panel.
//
// Copyright (C) 2013 Matthew Chaplain, All Rights Reserved.
//
// Permission to reproduce, distribute, perform, display, and to prepare
// derivitive works from this file under the following conditions:
//
// 1. Any copy, reproduction or derivitive work of any part of this file
// contains this copyright notice and licence in its entirety.
//
// 2. The rights granted to you under this license automatically terminate
// should you attempt to assert any patent claims against the licensor
// or contributors, which in any way restrict the ability of any party
// from using this software or portions thereof in any form under the
// terms of this license.
//
// Disclaimer: 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 "munin/tabbed_panel.hpp"
#include "munin/card.hpp"
#include "munin/container.hpp"
#include "munin/framed_component.hpp"
#include "munin/grid_layout.hpp"
#include "munin/tabbed_frame.hpp"
namespace munin {
// ==========================================================================
// TABBED_PANEL::IMPLEMENTATION STRUCTURE
// ==========================================================================
struct tabbed_panel::impl
{
std::shared_ptr<card> card_;
std::shared_ptr<tabbed_frame> frame_;
// ======================================================================
// TAB_SELECTED
// ======================================================================
void tab_selected(std::string const &text)
{
card_->select_face(text);
}
// ======================================================================
// FOCUS_CHANGE
// ======================================================================
void focus_change()
{
frame_->set_highlight(card_->has_focus() || frame_->has_focus());
}
};
// ==========================================================================
// CONSTRUCTOR
// ==========================================================================
tabbed_panel::tabbed_panel()
: pimpl_(new impl)
{
pimpl_->card_ = make_card();
pimpl_->frame_ = make_tabbed_frame();
auto inner = make_framed_component(pimpl_->frame_, pimpl_->card_);
auto content = get_container();
content->set_layout(make_grid_layout(1, 1));
content->add_component(inner);
pimpl_->frame_->on_tab_selected.connect(
[wpthis=std::weak_ptr<impl>(pimpl_)]
(auto idx)
{
auto pthis = wpthis.lock();
if (pthis)
{
pthis->tab_selected(idx);
}
});
auto focus_callback =
[wpthis=std::weak_ptr<impl>(pimpl_)]
{
auto pthis = wpthis.lock();
if (pthis)
{
pthis->focus_change();
}
};
pimpl_->frame_->on_focus_set.connect(focus_callback);
pimpl_->frame_->on_focus_lost.connect(focus_callback);
pimpl_->card_->on_focus_set.connect(focus_callback);
pimpl_->card_->on_focus_lost.connect(focus_callback);
}
// ==========================================================================
// DESTRUCTOR
// ==========================================================================
tabbed_panel::~tabbed_panel()
{
}
// ==========================================================================
// INSERT_TAB
// ==========================================================================
void tabbed_panel::insert_tab(
std::string const &text,
std::shared_ptr<component> const &comp,
boost::optional<odin::u32> index /*= optional<u32>()*/)
{
pimpl_->card_->add_face(comp, text);
pimpl_->frame_->insert_tab(text, index);
if (pimpl_->card_->get_number_of_faces() == 1)
{
pimpl_->card_->select_face(text);
}
}
// ==========================================================================
// REMOVE_TAB
// ==========================================================================
void tabbed_panel::remove_tab(odin::u32 index)
{
pimpl_->frame_->remove_tab(index);
}
// ==========================================================================
// MAKE_TABBED_PANEL
// ==========================================================================
std::shared_ptr<tabbed_panel> make_tabbed_panel()
{
return std::make_shared<tabbed_panel>();
}
}
| 35.541096
| 78
| 0.45847
|
KazDragon
|
863917c98697564a59eea3d227901fc2de184cfc
| 10,843
|
hpp
|
C++
|
source/AsioExpress/EventHandling/ResourceCache.hpp
|
suhao/asioexpress
|
2f3453465934afdcdf4a575a2d933d86929b23c7
|
[
"BSL-1.0"
] | null | null | null |
source/AsioExpress/EventHandling/ResourceCache.hpp
|
suhao/asioexpress
|
2f3453465934afdcdf4a575a2d933d86929b23c7
|
[
"BSL-1.0"
] | null | null | null |
source/AsioExpress/EventHandling/ResourceCache.hpp
|
suhao/asioexpress
|
2f3453465934afdcdf4a575a2d933d86929b23c7
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Ross MacGregor 2013
// 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)
#pragma once
#include <vector>
#include <map>
#include <set>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include "AsioExpressError/CallStack.hpp"
#include "AsioExpress/CompletionHandler.hpp"
#include "AsioExpress/ErrorCodes.hpp"
#include "AsioExpress/Timer/Timer.hpp"
#include "AsioExpress/EventHandling/ResourceCachePrivate/CacheRequest.hpp"
#include "AsioExpress/EventHandling/ResourceCachePrivate/CacheUpdateProcessor.hpp"
#include "AsioExpress/EventHandling/ResourceCachePrivate/AddResourceItemsProcessor.hpp"
namespace AsioExpress {
template<typename R, typename K = int>
class ResourceCache
{
public:
typedef R ResourceItem;
typedef K Key;
typedef boost::shared_ptr<ResourceItem> ResourceItemPointer;
ResourceCache();
///
/// Determines the currently active caches and their sizes. You need to call
/// this to properly initialize the resource cache and perhaps occasionally
/// to remove caches that are no longer in use.
/// @param completionHandler The completion hander is called when the
/// operation is complete.
///
void AsyncUpdate(
CompletionHandler completionHandler);
///
/// Gets a resource item from the resource cache. The particular cache to
/// use is identified by the key.
/// @param key Identifies the cache to rerieve the item.
/// @param item A pointer to a resource item. This item will
/// be set to a valid resource item if the operation
/// successfully completes.
/// @param waitTimer How long to wait to receive a resource item.
/// @param completionHandler The completion hander is called when the
/// operation is complete.
///
void AsyncGet(
Key key,
ResourceItemPointer item,
TimerPointer waitTimer,
CompletionHandler completionHandler);
///
/// Gets a resource item from the resource cache. Use this if you do not need
/// multiple resource caches.
///
/// @param item A pointer to a resource item. This item will
/// be set to a valid resource item if the operation
/// successfully completes.
/// @param waitTimer How long to wait to receive a resource item.
/// @param completionHandler The completion hander is called when the
/// operation is complete.
///
void AsyncGet(
ResourceItemPointer item,
TimerPointer waitTimer,
CompletionHandler completionHandler);
///
/// Notify the resource cache that items have been added.
/// @param key Identifies the cache.
/// @param count The number of resoure items added to the cache.
///
void Add(Key key, int count);
///
/// Notify the resource cache that items have been added. Use this if you do
/// not need multiple resource caches.
/// @param count The number of resoure items added to the cache.
///
void Add(int count);
///
/// Gets the size of a resource cache.
/// @param key Identifies the cache.
///
unsigned int GetCacheSize(Key key) const;
///
/// This method cancels any pending operations on all caches. If
/// AsyncGet is called on a canceled cache an operation aborted error
/// is returned immediately.
///
void ShutDown();
public:
class CacheSize
{
public:
CacheSize(Key key, unsigned int size): m_key(key), m_size(size) {}
Key GetKey() { return m_key; }
unsigned int GetSize() { return m_size; }
bool operator==(CacheSize const & that) const { return m_key == that.m_key && m_size == that.m_size; }
private:
Key m_key;
unsigned int m_size;
};
///
/// Class used to update the active resource caches.
///
class CacheUpdate
{
public:
typedef std::vector<CacheSize> CacheSizes;
typedef typename CacheSizes::iterator Iterator;
void SetSize(Key key, unsigned int size) { m_sizes.push_back(CacheSize(key,size)); }
Iterator Begin() { return m_sizes.begin(); }
Iterator End() {return m_sizes.end(); }
bool operator==(CacheUpdate const & that) const { return m_sizes == that.m_sizes; }
bool operator!=(CacheUpdate const & that) const { return !operator==(that); }
private:
CacheSizes m_sizes;
};
typedef boost::shared_ptr<CacheUpdate> CacheUpdatePointer;
protected:
///
/// This virtual method must be implemented by derived classes. It is used
/// to extract the resource item from implemenattion defined storage.
/// @param key Identifies the cache to rerieve the item.
/// @param item A pointer to a resource item. This item will
/// be set to a valid resource item if the operation
/// successfully completes.
/// @param completionHandler The completion hander is called when the
/// operation is complete.
///
virtual void AsyncRemoveItem(
Key key,
ResourceItemPointer item,
CompletionHandler completionHandler) = 0;
///
/// This virtual method must be implemented by derived classes. It is used
/// to determine the currently active caches and their sizes. You need to call
/// this to properly initialize the resource cache and occasionally to remove
/// caches that are no longer in use.
/// Call update->SetSize(key,size) to update cache size of active resource
/// caches.
/// @param update The cache update object used to update the
/// resource cache information.
/// @param completionHandler The completion hander is called when the
/// operation is complete.
///
virtual void AsyncUpdateAllItems(
CacheUpdatePointer update,
CompletionHandler completionHandler) = 0;
///
/// If an error occurs as a result of an Add() operation this virtual method
/// is called for the derived class to handle.
///
virtual void ErrorHandler(
AsioExpress::Error error) = 0;
private:
typedef ResourceCachePrivate::CacheRequest<ResourceItem, Key> Request;
typedef std::vector<Request> Requests;
typedef boost::shared_ptr<Requests> RequestsPointer;
typedef std::map<Key,int> ItemCount;
typedef boost::shared_ptr<ItemCount> ItemCountPointer;
void Timeout(AsioExpress::Error error, ResourceItemPointer item);
void ReturnError(AsioExpress::Error error, ResourceItemPointer item);
bool CanDelete(Request const & request, Key key);
RequestsPointer m_requests;
ItemCountPointer m_itemCount;
bool m_isShutDown;
};
template<typename R, typename K>
ResourceCache<R,K>::ResourceCache() :
m_requests(new Requests),
m_itemCount(new ItemCount),
m_isShutDown(false)
{
}
template<typename R, typename K>
void ResourceCache<R,K>::AsyncUpdate(
CompletionHandler completionHandler)
{
ResourceCachePrivate::CacheUpdateProcessor<CacheUpdate, ItemCount> proc(
m_itemCount,
boost::bind(&ResourceCache<R,K>::AsyncUpdateAllItems, this, _1, _2),
completionHandler);
proc();
}
template<typename R, typename K>
void ResourceCache<R,K>::AsyncGet(
Key key,
ResourceItemPointer item,
TimerPointer waitTimer,
CompletionHandler completionHandler)
{
// If the event has been canceled return operation aborted immediately.
if ( m_isShutDown )
{
completionHandler(Error(boost::asio::error::operation_aborted));
return;
}
if ((*m_itemCount)[key] > 0)
{
--(*m_itemCount)[key];
AsyncRemoveItem(key, item, completionHandler);
return;
}
// Queue this event to be handled.
//
waitTimer->AsyncWait(boost::bind(&ResourceCache<R,K>::Timeout, this, _1, item));
m_requests->push_back(
Request(key, item, completionHandler, waitTimer));
}
template<typename R, typename K>
void ResourceCache<R,K>::AsyncGet(
ResourceItemPointer item,
TimerPointer waitTimer,
CompletionHandler completionHandler)
{
AsyncGet(Key(), item, waitTimer, completionHandler);
}
template<typename R, typename K>
void ResourceCache<R,K>::Add(Key key, int count)
{
(*m_itemCount)[key] += count;
ResourceCachePrivate::AddResourceItemsProcessor<ResourceItem, Key> proc(
key,
m_requests,
m_itemCount,
boost::bind(&ResourceCache<R,K>::AsyncRemoveItem, this, _1, _2, _3),
boost::bind(&ResourceCache<R,K>::ErrorHandler, this, _1));
proc();
}
template<typename R, typename K>
void ResourceCache<R,K>::Add(int count)
{
Add(Key(), count);
}
//template<typename R, typename K>
//void ResourceCache<R,K>::Delete(Key key)
//{
// Requests::iterator begin = m_requests->begin();
// Requests::iterator end = m_requests->end();
// Requests::iterator new_end = std::remove_if(
// begin,
// end,
// boost::bind(&ResourceCache<R,K>::CanDelete, this, _1, key));
//
// m_requests->erase(new_end, end);
//
// m_itemCount->erase(key);
//}
template<typename R, typename K>
unsigned int ResourceCache<R,K>::GetCacheSize(Key key) const
{
return (*m_itemCount)[key];
}
template<typename R, typename K>
void ResourceCache<R,K>::ShutDown()
{
// Indicate that this event is canceled.
m_isShutDown = true;
typename Requests::iterator request = m_requests->begin();
typename Requests::iterator end = m_requests->end();
for(; request != end; ++request)
{
request->timer->Stop();
}
}
template<typename R, typename K>
void ResourceCache<R,K>::Timeout(AsioExpress::Error error, ResourceItemPointer item)
{
ReturnError(error, item);
}
template<typename R, typename K>
void ResourceCache<R,K>::ReturnError(AsioExpress::Error error, ResourceItemPointer item)
{
typename Requests::iterator request
= std::find(m_requests->begin(), m_requests->end(), item);
if (request != m_requests->end())
{
CompletionHandler handler(request->completionHandler);
m_requests->erase(request);
if (error)
handler(error);
else
handler(Error(AsioExpress::ErrorCode::ResourceCacheTimeout));
}
}
template<typename R, typename K>
bool ResourceCache<R,K>::CanDelete(Request const & request, Key key)
{
return request.key == key;
}
} // namespace AsioExpress
| 32.464072
| 107
| 0.654063
|
suhao
|
86401129457fcbf250bf9a7419dd6cdc1a1ec5ce
| 5,602
|
cpp
|
C++
|
base/src/easywsclient/AndroidImplSockets.cpp
|
djdron/gamesparks-cpp-base
|
00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8
|
[
"Apache-2.0"
] | 7
|
2019-07-11T02:05:32.000Z
|
2020-11-01T18:57:51.000Z
|
base/src/easywsclient/AndroidImplSockets.cpp
|
djdron/gamesparks-cpp-base
|
00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8
|
[
"Apache-2.0"
] | 3
|
2019-02-26T15:59:03.000Z
|
2019-06-04T10:46:07.000Z
|
base/src/easywsclient/AndroidImplSockets.cpp
|
djdron/gamesparks-cpp-base
|
00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8
|
[
"Apache-2.0"
] | 6
|
2020-05-18T08:44:47.000Z
|
2022-02-26T12:18:17.000Z
|
#include "GameSparks/GSPlatformDeduction.h"
#include "easywsclient/easywsclient.hpp"
#if (GS_TARGET_PLATFORM == GS_PLATFORM_ANDROID)
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/net.h>
#include <mbedtls/error.h>
#include <mbedtls/platform.h>
#include <mbedtls/debug.h>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <string.h>
#include "GameSparks/GSLeakDetector.h"
#include "GameSparks/GSUtil.h"
#include "easywsclient/CertificateStore.hpp"
#if defined(__UNREAL__)
int GameSparks::Util::CertificateStore::numCerts = 0;
unsigned char *GameSparks::Util::CertificateStore::pCertsEncoded = NULL;
int *GameSparks::Util::CertificateStore::pCertsLength = NULL;
#endif
class BaseSocket;
class TCPSocket : public BaseSocket
{
private:
bool is_connected;
volatile bool is_aborted;
protected:
mbedtls_net_context net;
public:
TCPSocket() :is_connected(false), is_aborted(false)
{
mbedtls_net_init(&net);
}
virtual ~TCPSocket()
{
mbedtls_net_free(&net);
}
virtual bool connect(const char *host, short port)
{
if (is_connected)
return true;
char port_str[8];
snprintf(port_str, 8, "%hu", port);
int res = mbedtls_net_connect(&net, host, port_str, MBEDTLS_NET_PROTO_TCP);
if (res != 0)
{
set_errstr(res);
close();
return false;
}
if (is_aborted)
{
set_errstr("connection aborted!");
return false;
}
is_connected = true;
return true;
}
virtual void close()
{
is_connected = false;
}
virtual int send(const char *buf, size_t siz)
{
if (is_aborted) return MBEDTLS_ERR_NET_INVALID_CONTEXT;
return mbedtls_net_send(&net, (unsigned char *)buf, siz);
}
virtual int recv(char *buf, size_t siz)
{
if (is_aborted) return MBEDTLS_ERR_NET_INVALID_CONTEXT;
return mbedtls_net_recv(&net, (unsigned char *)buf, siz);
}
virtual void set_blocking(bool should_block)
{
assert(is_connected);
if (!is_connected || is_aborted)
return;
if (should_block)
mbedtls_net_set_block(&net);
else
mbedtls_net_set_nonblock(&net);
}
virtual void abort()
{
is_aborted = true;
is_connected = false;
mbedtls_net_free(&net);
mbedtls_net_init(&net);
}
};
class TLSSocket : public TCPSocket
{
private:
bool is_connected;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
static void debug_print(void *ctx, int level, const char *file, int line, const char *str)
{
((void)level);
mbedtls_fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
//fflush((FILE *)ctx);
}
public:
TLSSocket() :is_connected(false)
{
//mbedtls_debug_set_threshold( 1000 );
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_entropy_init(&entropy);
}
virtual ~TLSSocket()
{
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
}
virtual bool connect(const char *host, short port)
{
if (is_connected)
return true;
if (!TCPSocket::connect(host, port))
{
return false;
}
int res = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, nullptr, 0);
res = mbedtls_ssl_config_defaults(&conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if (res != 0)
{
set_errstr(res);
close();
return false;
}
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE);
// this performs platform specific initialisation by retrieving the certificate store from the OS.
// if implemented for this platform, it also sets mbedtls_ssl_conf_authmode to MBEDTLS_SSL_VERIFY_REQUIRED
res = GameSparks::Util::CertificateStore::setup(conf);
if (res != 0) {
set_errstr(res);
close();
return false;
}
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_dbg(&conf, debug_print, stderr);
res = mbedtls_ssl_setup(&ssl, &conf);
if (res != 0)
{
set_errstr(res);
close();
return false;
}
res = mbedtls_ssl_set_hostname(&ssl, host);
if (res != 0)
{
set_errstr(res);
close();
return false;
}
mbedtls_ssl_set_bio(&ssl, &net, mbedtls_net_send, mbedtls_net_recv, 0);// , mbedtls_net_recv_timeout);
do res = mbedtls_ssl_handshake(&ssl);
while (res == MBEDTLS_ERR_SSL_WANT_READ || res == MBEDTLS_ERR_SSL_WANT_WRITE);
if (res != 0)
{
set_errstr(res);
close();
return false;
}
uint32_t flags;
if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0)
{
char vrfy_buf[512];
mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", flags);
set_errstr(vrfy_buf);
close();
return false;
}
is_connected = true;
return true;
}
virtual void close()
{
TCPSocket::close();
is_connected = false;
}
virtual int send(const char *buf, size_t siz)
{
return mbedtls_ssl_write(&ssl, (unsigned char *)buf, siz);
/*int ret = 0;
do ret = mbedtls_ssl_write(&ssl, (unsigned char *)buf, siz);
while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
if (ret < 0) set_errstr(ret);
return ret;*/
}
virtual int recv(char *buf, size_t siz)
{
return mbedtls_ssl_read(&ssl, (unsigned char *)buf, siz);
/*int ret = 0;
do ret = mbedtls_ssl_read(&ssl, (unsigned char *)buf, siz);
while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
if (ret < 0) set_errstr(ret);
return ret;*/
}
};
BaseSocket *BaseSocket::create(bool useSSL) {
if (useSSL) {
return new TLSSocket();
}
else {
return new TCPSocket();
}
}
#endif
| 21.546154
| 108
| 0.704927
|
djdron
|
864e9604f4ed17b0987e1fe2e820882fe20f0e11
| 17,996
|
cpp
|
C++
|
scripts/da_cratemanager.cpp
|
mpforums/RenSharp
|
5b3fb8bff2a1772a82a4148bcf3e1265a11aa097
|
[
"Apache-2.0"
] | 1
|
2021-10-04T02:34:33.000Z
|
2021-10-04T02:34:33.000Z
|
scripts/da_cratemanager.cpp
|
TheUnstoppable/RenSharp
|
2a123c6018c18f3fc73501737d600e291ac3afa7
|
[
"Apache-2.0"
] | 9
|
2019-07-03T19:19:59.000Z
|
2020-03-02T22:00:21.000Z
|
scripts/da_cratemanager.cpp
|
TheUnstoppable/RenSharp
|
2a123c6018c18f3fc73501737d600e291ac3afa7
|
[
"Apache-2.0"
] | 2
|
2019-08-14T08:37:36.000Z
|
2020-09-29T06:44:26.000Z
|
/* Renegade Scripts.dll
Dragonade Crate Manager
Copyright 2017 Whitedragon, Tiberian Technologies
This file is part of the Renegade scripts.dll
The Renegade scripts.dll is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version. See the file COPYING for more details.
In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence.
Only the source code to the module(s) containing the licenced code has to be released.
*/
#include "general.h"
#include "scripts.h"
#include "engine.h"
#include "engine_da.h"
#include "da.h"
#include "da_crate.h"
#include "da_cratemanager.h"
#include "da_settings.h"
#include "da_player.h"
#include "da_log.h"
#include "da_game.h"
#include "da_gameobj.h"
#include "SpawnerClass.h"
#include "SpawnerDefClass.h"
#include "GameObjManager.h"
#pragma warning(disable: 4073)
#pragma init_seg(lib)
DynamicVectorClass <DACrateFactoryClass*> DACrateManager::Crates;
DynamicVectorClass <DACrateModifierFactoryClass*> DACrateManager::CrateModifiers;
float DACrateManager::Odds = 0;
void DACrateManager::Static_Init() {
DASettingsManager::Add_Settings("da_crates.ini");
}
void DACrateManager::Add_Crate(DACrateFactoryClass *Factory) {
for (int i = 0;i < Crates.Count();i++) {
if (!_stricmp(Crates[i]->Get_Name(),Factory->Get_Name())) {
Crates.Delete(i);
break;
}
}
Crates.Add(Factory);
}
void DACrateManager::Add_Crate_Modifier(DACrateModifierFactoryClass *Factory) {
for (int i = 0;i < CrateModifiers.Count();i++) {
if (!_stricmp(CrateModifiers[i]->Get_Name(),Factory->Get_Name())) {
CrateModifiers.Delete(i);
break;
}
}
CrateModifiers.Add(Factory);
}
DACrateClass *DACrateManager::Get_Crate(const char *Name) {
Iterate_Crates(Crate,i)
if (!_stricmp(Crate->Get_Name(),Name)) {
return Crate;
}
}
return 0;
}
DACrateModifierClass *DACrateManager::Create_Crate_Modifier(const char *Name,const char *Parameters) {
for (int i = 0;i < CrateModifiers.Count();i++) {
if (!_stricmp(CrateModifiers[i]->Get_Name(),Name)) {
return CrateModifiers[i]->Create(Parameters);
}
}
return 0;
}
void DACrateManager::Calculate_Odds(cPlayer *Player) {
Odds = 0;
float BaseOdds = 0;
float ModifiedOdds = 0;
Iterate_Crates(Crate,i) //Apply modifiers.
if (Crate->Check_Type(Player)) {
Crate->Calculate_Odds(Player);
BaseOdds += Crate->Get_Base_Odds();
ModifiedOdds += Crate->Get_Modified_Odds();
}
}
if (BaseOdds != ModifiedOdds) { //The odds difference from modified crates needs to be taken from crates with greater or equal base odds.
Iterate_Crates(Crate,i) //If this is not done the total odds will increase which will lead to the odds of other crates being unitentionally affected.
if (Crate->Check_Type(Player) && Crate->Get_Modified_Odds() != Crate->Get_Base_Odds()) { //This crate has modified odds.
float OddsDifference = Crate->Get_Base_Odds()-Crate->Get_Modified_Odds(); //Get the difference between base odds and modified odds.
float OddsGreater = 0;
int OddsEqual = 0;
if (OddsDifference > 0 && Crate->Get_Final_Odds() && !Crate->Get_Cap_Odds()) {
OddsEqual--;
}
Iterate_Crates(Crate2,x) //Add up the base odds of all crates with greater or equal base odds and not disabled(0 modified odds).
if (Crate2->Check_Type(Player) && Crate2->Get_Final_Odds() && (OddsDifference < 0 || !Crate2->Get_Cap_Odds())) {
if (Crate2->Get_Base_Odds() > Crate->Get_Base_Odds()) {
OddsGreater += Crate2->Get_Final_Odds();
}
else if (Crate2->Get_Base_Odds() == Crate->Get_Base_Odds()) {
OddsEqual++;
}
}
}
Iterate_Crates(Crate2,x)
if (Crate2->Check_Type(Player) && Crate2->Get_Final_Odds() && (OddsDifference < 0 || !Crate2->Get_Cap_Odds())) {
if (Crate2->Get_Base_Odds() > Crate->Get_Base_Odds()) {
float OddsBefore = Crate2->Get_Final_Odds();
Crate2->Adjust_Odds(OddsBefore/OddsGreater*OddsDifference); //Modify odds as a percentage of this crate's odds relative to the odds of all crates that are being modified.
OddsDifference += OddsBefore-Crate2->Get_Final_Odds(); //I.E Crates with higher odds get more odds taken/granted.
OddsGreater -= OddsBefore;
}
else if (Crate2->Get_Base_Odds() == Crate->Get_Base_Odds() && Crate != Crate2) {
float OddsBefore = Crate2->Get_Final_Odds();
Crate2->Adjust_Odds(OddsDifference/OddsEqual);
OddsDifference += OddsBefore-Crate2->Get_Final_Odds();
OddsEqual--;
}
}
}
if (OddsDifference < 0) {
Crate->Adjust_Odds(OddsDifference);
}
}
}
Iterate_Crates(Crate,i)
if (Crate->Check_Type(Player)) {
Odds += Crate->Get_Final_Odds();
}
}
}
else {
Odds = BaseOdds;
}
}
float DACrateManager::Get_Odds() {
return Odds;
}
DACrateClass *DACrateManager::Select_Crate(cPlayer *Player) {
Calculate_Odds(Player);
float Rand = Get_Random_Float(1,Odds);
float Total = 0;
Iterate_Crates(Crate,i)
if (Crate->Check_Type(Player)) {
if (Crate->Get_Final_Odds() && Rand <= (Total+=Crate->Get_Final_Odds())) {
return Crate;
}
}
}
return 0;
}
void DACrateManager::Init() {
Register_Event(DAEvent::LEVELLOADED);
Register_Event(DAEvent::SETTINGSLOADED);
Register_Event(DAEvent::GAMEOVER);
Register_Event(DAEvent::POWERUPGRANT);
Register_Object_Event(DAObjectEvent::DESTROYED,DAObjectEvent::POWERUP);
Register_Chat_Command((DAECC)&DACrateManager::Crate_Chat_Command,"!crate");
Register_Chat_Command((DAECC)&DACrateManager::Crates_Chat_Command,"!crates");
Register_Chat_Command((DAECC)&DACrateManager::ShowCrateSpawners_Chat_Command,"!showcratespawners",0,DAAccessLevel::ADMINISTRATOR);
Register_Chat_Command((DAECC)&DACrateManager::HideCrateSpawners_Chat_Command,"!hidecratespawners",0,DAAccessLevel::ADMINISTRATOR);
}
DACrateManager::~DACrateManager() {
for (int i = 0;i < Crates.Count();i++) {
Crates[i]->Destroy_Instance();
}
if (!DAGameManager::Is_Shutdown_Pending()) {
for (int i = 0;i < CrateObjs.Count();i++) {
CrateObjs[i]->Set_Delete_Pending();
}
}
}
void DACrateManager::Settings_Loaded_Event() {
//Basic settings
MaxCrates = DASettingsManager::Get_Int("MaxCrates",1);
DASettingsManager::Get_String(Model,"CrateModel","vehcol2m");
StringClass SpawnTime;
DASettingsManager::Get_String(SpawnTime,"CrateSpawnTime","120-180");
DATokenParserClass Parser(SpawnTime,'-');
if (!Parser.Get_Float(SpawnTimeMin) || !Parser.Get_Float(SpawnTimeMax)) {
SpawnTimeMin = 120.0f;
SpawnTimeMax = 180.0f;
}
DASettingsManager::Get_String(SpawnTime,"FirstCrateSpawnTime","60-90");
Parser.Set(SpawnTime,'-');
if (!Parser.Get_Float(FirstSpawnTimeMin) || !Parser.Get_Float(FirstSpawnTimeMax)) {
FirstSpawnTimeMin = 60.0f;
FirstSpawnTimeMax = 90.0f;
}
//Crates
for (int i = 0;i < Crates.Count();i++) {
if (Crates[i]->Get_Instance()) {
if (!Crates[i]->Check_Enabled()) {
Crates[i]->Destroy_Instance();
}
else {
Crates[i]->Get_Instance()->Settings_Loaded();
}
}
else if (Crates[i]->Check_Enabled()) {
Crates[i]->Create_Instance()->Settings_Loaded();
}
}
DynamicVectorClass<DACrateFactoryClass*> CratesCopy = Crates;
Crates.Delete_All();
for (int i = 0;i < CratesCopy.Count();i++) { //Order crates from highest base odds to lowest base odds.
bool Added = false;
if (CratesCopy[i]->Get_Instance()) {
for (int x = 0;x < Crates.Count();x++) {
if (Crates[x]->Get_Instance() && Crates[x]->Get_Instance()->Get_Base_Odds() < CratesCopy[i]->Get_Instance()->Get_Base_Odds()) {
Crates.Insert(x,CratesCopy[i]);
Added = true;
break;
}
}
}
if (!Added) {
Crates.Add(CratesCopy[i]);
}
}
//Spawn locations
ActiveSpawners.Delete_All();
Spawners.Delete_All();
LastCratePosition = Vector3(-1000.0f,-1000.0f,-1000.0f);
if (DASettingsManager::Get_Bool("EnableNewCrateSpawners",true)) { //Get new crate spawners from da_crates.ini if enabled.
for (int i = 1;;i++) {
Vector3 Buffer;
DASettingsManager::Get_Vector3(Buffer,StringFormat("Crate%d",i),Buffer);
if (Buffer.X || Buffer.Y || Buffer.Z) {
if (Spawners.ID(Buffer) == -1) {
Spawners.Add(Buffer);
}
}
else {
break;
}
}
}
if (DASettingsManager::Get_Bool("EnableOldCrateSpawners",true) || !Spawners.Count()) { //Get old crate spawners from level if enabled or if no new spawners could be loaded.
for (int i = 0;i < SpawnerList.Count();i++) {
const SpawnerDefClass *Def = SpawnerList[i]->Get_Definition();
if (Def->Get_Spawn_Definition_ID_List().Count() && stristr(Get_Definition_Name(Def->Get_Spawn_Definition_ID_List()[0]),"Crate")) {
Vector3 Buffer;
for (int x = 0;x < SpawnerList[i]->Get_Spawn_Point_List().Count();x++) { //Alternate positions.
SpawnerList[i]->Get_Spawn_Point_List()[x].Get_Translation(&Buffer);
if (Spawners.ID(Buffer) == -1 && (Buffer.X || Buffer.Y || Buffer.Z)) {
Spawners.Add(Buffer);
}
}
SpawnerList[i]->Get_TM().Get_Translation(&Buffer); //Default position.
if (Spawners.ID(Buffer) == -1 && (Buffer.X || Buffer.Y || Buffer.Z)) {
Spawners.Add(Buffer);
}
SpawnerList[i]->Enable(false); //Disable default crate spawner.
}
}
}
else {
for (int i = 0;i < SpawnerList.Count();i++) {
const SpawnerDefClass *Def = SpawnerList[i]->Get_Definition();
if (Def->Get_Spawn_Definition_ID_List().Count() && stristr(Get_Definition_Name(Def->Get_Spawn_Definition_ID_List()[0]),"Crate")) {
SpawnerList[i]->Enable(false); //Disable default crate spawner.
}
}
}
for (int i = 0;i < Spawners.Count();i++) {
ActiveSpawners.Add(&Spawners[i]);
}
//Start spawn timer
Stop_Timer(1);
if (Spawners.Count()) {
float Rand = Get_Random_Float(FirstSpawnTimeMin,FirstSpawnTimeMax);
for (int i = 1;i <= (MaxCrates-CrateObjs.Count());i++) {
Start_Timer(1,Rand*i);
}
}
}
void DACrateManager::Game_Over_Event() {
Stop_Timer(1);
}
Vector3 *DACrateManager::Select_Spawner() {
Vector3 *Spawner = 0;
if (CrateObjs.Count()) {
float MaxDistance = FLT_MIN;
for (int i = 0;i < ActiveSpawners.Count();i++) { //Select active spawner farthest from any crate.
float SpawnerMinDistance = FLT_MAX;
for (int x = 0;x < CrateObjs.Count();x++) {
float Distance = Commands->Get_Distance(CrateObjs[x]->Get_Position(),*ActiveSpawners[i]);
if (Distance < SpawnerMinDistance) {
SpawnerMinDistance = Distance;
}
}
float Distance = Commands->Get_Distance(LastCratePosition,*ActiveSpawners[i]);
if (Distance < SpawnerMinDistance) {
SpawnerMinDistance = Distance;
}
if (SpawnerMinDistance > MaxDistance) {
MaxDistance = SpawnerMinDistance;
Spawner = ActiveSpawners[i];
}
}
}
else if (ActiveSpawners.Count()) { //No crates exist, so get a random spawner.
int Rand = Get_Random_Int(0,ActiveSpawners.Count());
Spawner = ActiveSpawners[Rand];
}
ActiveSpawners.DeleteObj(Spawner);
if (!ActiveSpawners.Count()) { //All spawners have been used, refill active list.
for (int i = 0;i < Spawners.Count();i++) {
if (&Spawners[i] != Spawner) {
bool Valid = true;
for (int x = 0;x < CrateObjs.Count();x++) { //Don't use any spawner that is near an existing crate.
if (Commands->Get_Distance(CrateObjs[x]->Get_Position(),Spawners[i]) < 10.0f) {
Valid = false;
}
}
if (Valid) {
ActiveSpawners.Add(&Spawners[i]);
}
}
}
}
return Spawner;
}
void DACrateManager::Timer_Expired(int Number,unsigned int Data) {
if (The_Game()->Get_Current_Players() && The_Game()->Is_Gameplay_Permitted()) {
Vector3 *Position = Select_Spawner();
if (Position) {
PhysicalGameObj *Crate = Create_Object("Soldier PowerUps",*Position);
Commands->Set_Model(Crate,Model);
CrateObjs.Add(Crate);
return;
}
}
Start_Timer(1,Get_Random_Float(SpawnTimeMin,SpawnTimeMax));
}
void DACrateManager::PowerUp_Grant_Event(cPlayer *Player,const PowerUpGameObjDef *PowerUp,PowerUpGameObj *PowerUpObj) {
if (PowerUpObj && CrateObjs.ID(PowerUpObj) != -1 && (Player->Get_Player_Type() == 0 || Player->Get_Player_Type() == 1)) {
DACrateClass *Crate = DACrateManager::Select_Crate(Player);
if (Crate) {
SoldierGameObj *Soldier = Player->Get_GameObj();
Soldier->Get_Position(&LastCratePosition);
DALogManager::Write_Log("_CRATE","%ls picked up the %s Crate(%s).",Player->Get_Name(),Crate->Get_Name(),Soldier->Get_Vehicle()?"Vehicle":"Infantry");
DALogManager::Write_GameLog("CRATE;%s;%s;%d;%s;%f;%f;%f;%f;%f;%f;%d",Crate->Get_Name(),Soldier->Get_Vehicle()?"Vehicle":"Infantry",Soldier->Get_ID(),Soldier->Get_Definition().Get_Name(),LastCratePosition.Y,LastCratePosition.X,LastCratePosition.Z,Soldier->Get_Facing(),Soldier->Get_Defense_Object()->Get_Health_Max(),Soldier->Get_Defense_Object()->Get_Shield_Strength_Max(),Soldier->Get_Player_Type());
Crate->Activate(Player);
PowerUpObj->Set_Delete_Pending();
Start_Timer(1,Get_Random_Float(SpawnTimeMin,SpawnTimeMax));
DA::Private_HUD_Message(Player,COLORGRAY, "%s Crate", Crate->Get_Name());
}
}
}
void DACrateManager::Object_Destroyed_Event(GameObject *obj) {
CrateObjs.DeleteObj((PhysicalGameObj*)obj);
}
bool DACrateManager::Crate_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) {
if (!Text.Size()) {
DACrateClass *Crate = Select_Crate(Player);
if (Crate) {
DA::Page_Player(Player,"You got the %s Crate with a %.2f%% chance!",Crate->Get_Name(),Crate->Get_Final_Odds()/Odds*100);
}
else {
DA::Page_Player(Player,"A crate could not be selected.");
}
}
else if (Player->Get_DA_Player()->Get_Access_Level() >= DAAccessLevel::ADMINISTRATOR && (Player->Get_Player_Type() == 0 || Player->Get_Player_Type() == 1)) {
DACrateClass *Crate = Get_Crate(Text[0]);
if (Crate) {
if (!Crate->Check_Type(Player) || !Crate->Can_Activate(Player)) {
DA::Page_Player(Player,"You cannot currently receive that crate.");
}
else {
Crate->Activate(Player);
}
}
else {
DA::Page_Player(Player,"Crate could not be found.");
}
}
return true;
}
bool DACrateManager::Crates_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) {
float InfantryOdds = 0;
float VehicleOdds = 0;
Iterate_Crates(Crate,i)
if (Crate->Check_Type(DACrateType::INFANTRY)) {
InfantryOdds += Crate->Get_Base_Odds();
}
if (Crate->Check_Type(DACrateType::VEHICLE)) {
VehicleOdds += Crate->Get_Base_Odds();
}
}
Calculate_Odds(Player);
if (InfantryOdds) {
DA::Page_Player(Player,"Base Infantry Odds:");
StringClass Send;
Iterate_Crates(Crate,i)
if (Crate->Check_Type(DACrateType::INFANTRY)) {
StringClass Buffer;
Buffer.Format("%s(%.2f%%), ",Crates[i]->Get_Name(),Crate->Get_Base_Odds()/InfantryOdds*100);
if (Send.Get_Length() + Buffer.Get_Length() > 220) {
Send.TruncateRight(2);
DA::Page_Player(Player,"%s",Send);
Send = Buffer;
}
else {
Send += Buffer;
}
}
}
if (!Send.Is_Empty()) {
Send.TruncateRight(2);
DA::Page_Player(Player,"%s",Send);
}
}
if (VehicleOdds) {
DA::Page_Player(Player,"Base Vehicle Odds:");
StringClass Send;
Iterate_Crates(Crate,i)
if (Crate->Check_Type(DACrateType::VEHICLE)) {
StringClass Buffer;
Buffer.Format("%s(%.2f%%), ",Crates[i]->Get_Name(),Crate->Get_Base_Odds()/VehicleOdds*100);
if (Send.Get_Length() + Buffer.Get_Length() > 220) {
Send.TruncateRight(2);
DA::Page_Player(Player,"%s",Send);
Send = Buffer;
}
else {
Send += Buffer;
}
}
}
if (!Send.Is_Empty()) {
Send.TruncateRight(2);
DA::Page_Player(Player,"%s",Send);
}
}
if (Odds) {
DA::Page_Player(Player,"Current Odds:");
StringClass Send;
Iterate_Crates(Crate,i)
if (Crate->Check_Type(Player)) {
StringClass Buffer;
if (Crate->Get_Final_Odds()) {
Buffer.Format("%s(%.2f%%), ",Crates[i]->Get_Name(),Crate->Get_Final_Odds()/Odds*100);
}
else {
Buffer.Format("%s(0%%), ",Crates[i]->Get_Name());
}
if (Send.Get_Length() + Buffer.Get_Length() > 220) {
Send.TruncateRight(2);
DA::Page_Player(Player,"%s",Send);
Send = Buffer;
}
else {
Send += Buffer;
}
}
}
if (!Send.Is_Empty()) {
Send.TruncateRight(2);
DA::Page_Player(Player,"%s",Send);
}
}
return true;
}
class DAShowCrateSpawnersObserverClass : public DAGameObjObserverClass {
public:
virtual const char *Get_Name() {
return "DAShowCrateSpawnersObserverClass";
}
DAShowCrateSpawnersObserverClass(int Number) {
this->Number = Number;
}
virtual void Poked(GameObject *obj,GameObject *Poker) {
Vector3 Position;
Get_Owner()->Get_Position(&Position);
DA::Host_Message("Crate spawner #%d at %f %f %f",Number,Position.X,Position.Y,Position.Z);
}
int Number;
};
bool DACrateManager::ShowCrateSpawners_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) {
HideCrateSpawners_Chat_Command(Player,Text,ChatType);
int i = 0;
for (;i < Spawners.Count();i++) {
PhysicalGameObj *Marker = Create_Object("Invisible_Object",Spawners[i]);
Marker->Set_Collision_Group(TERRAIN_AND_BULLET_COLLISION_GROUP);
Marker->Peek_Physical_Object()->Set_Immovable(true);
Commands->Set_Model(Marker,"dsp_holo");
Marker->Add_Observer(new DAShowCrateSpawnersObserverClass(i+1));
}
DA::Host_Message("Created markers for %d crate spawners.",i);
return true;
}
bool DACrateManager::HideCrateSpawners_Chat_Command(cPlayer *Player,const DATokenClass &Text,TextMessageEnum ChatType) {
for (SLNode<BaseGameObj> *x = GameObjManager::GameObjList.Head();x;x = x->Next()) {
if (x->Data()->As_ScriptableGameObj() && ((ScriptableGameObj*)x->Data())->Find_Observer("DAShowCrateSpawnersObserverClass")) {
x->Data()->Set_Delete_Pending();
}
}
return true;
}
Register_Game_Feature(DACrateManager,"Crates","EnableCrates",0);
| 33.890772
| 404
| 0.692487
|
mpforums
|
8653002418fe6aad40b27089ade30361e7127879
| 3,343
|
cpp
|
C++
|
MathTutorRevised.cpp
|
krisf01/Computer-Systems-and-C-Programming
|
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
|
[
"MIT"
] | null | null | null |
MathTutorRevised.cpp
|
krisf01/Computer-Systems-and-C-Programming
|
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
|
[
"MIT"
] | null | null | null |
MathTutorRevised.cpp
|
krisf01/Computer-Systems-and-C-Programming
|
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
const int MIN_VALUE = 100;
const int MAX_VALUE = 1000;
const int addition = 1, subtraction = 2, multiplication = 3, division = 4, quit = 5;
int randomnumber1, randomnumber2, useranswer, randnumanswer;
int choice;
std::setw(5);
unsigned seed = time(0);
srand(seed);
do
{
randomnumber1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
randomnumber2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
cout << " " << "Math Tutor Menu" << endl;
cout << "----------------------------" << endl;
cout << "1. Addition problem" << endl;
cout << "2. Subtraction problem" << endl;
cout << "3. Multiplication problem" << endl;
cout << "4. Division problem" << endl;
cout << "5. Quit this program" << endl;
cout << "----------------------------" << endl;
cout << "Enter your choice (1-5): ";
while(!(cin >> choice) || choice < addition || choice > quit)
{
cout << "Choose numbers only between 1, 2, 3, 4, 5: ";
}
if (choice != quit)
{
switch (choice)
{
case 1:
{
randnumanswer = randomnumber1 + randomnumber2;
cout << setw(5) << randomnumber1 << endl;
cout << "+" << endl;
cout << setw(5) << randomnumber2 << endl;
cout << "------" << endl;
cout << " ";
cin >> useranswer;
cout << endl;
break;
}
case 2:
{
randnumanswer = randomnumber2 - randomnumber1;
cout << setw(5) << randomnumber2 << endl;
cout << "-" << endl;
cout << setw(5) << randomnumber1 << endl;
cout << "------" << endl;
cout << " ";
cin >> useranswer;
cout << endl;
break;
}
case 3:
{
randnumanswer = randomnumber1 * randomnumber2;
cout << setw(5) << randomnumber1 << endl;
cout << "*" << endl;
cout << setw(5) << randomnumber2 << endl;
cout << "------" << endl;
cout << " ";
cin >> useranswer;
cout << endl;
break;
}
case 4:
{
randnumanswer = randomnumber1 % randomnumber2;
cout << setw(5) << randomnumber1 << endl;
cout << "%" << endl;
cout << setw(5) << randomnumber2 << endl;
cout << "------" << endl;
cout << " ";
cin >> useranswer;
cout << endl;
break;
}
}
if (useranswer == randnumanswer)
{
cout << "\nCongratulations!"
<< endl
<< endl;
}
else if(useranswer != randnumanswer)
{
cout << "Sorry, the correct answer: "
<< randnumanswer
<< endl
<< endl;
}
}
else
cout << "Thank you for using Math Tutor." << endl;
} while (choice != quit);
cout << endl;
return 0;
}
| 30.117117
| 88
| 0.417589
|
krisf01
|
86586fa7d8409801b39c5a8d81f0ebfefcc6cd93
| 6,539
|
hpp
|
C++
|
fltl/include/tdop/Unbound.hpp
|
iambrosie/Grail-Plus
|
e102de735e86df241e4311394190ad39181f073b
|
[
"MIT"
] | null | null | null |
fltl/include/tdop/Unbound.hpp
|
iambrosie/Grail-Plus
|
e102de735e86df241e4311394190ad39181f073b
|
[
"MIT"
] | null | null | null |
fltl/include/tdop/Unbound.hpp
|
iambrosie/Grail-Plus
|
e102de735e86df241e4311394190ad39181f073b
|
[
"MIT"
] | 1
|
2020-07-14T03:58:19.000Z
|
2020-07-14T03:58:19.000Z
|
/*
* Unbound.hpp
*
* Created on: May 11, 2012
* Author: petergoodman
* Version: $Id$
*/
#ifndef Grail_Plus_TDOP_UNBOUND_HPP_
#define Grail_Plus_TDOP_UNBOUND_HPP_
namespace fltl { namespace tdop {
template <typename, typename> class Unbound;
template <typename, typename> class Bound;
/// unbound rules
template <typename AlphaT>
class Unbound<AlphaT, rule_tag> {
private:
friend class OpaqueRule<AlphaT>;
friend class TDOP<AlphaT>;
OpaqueRule<AlphaT> *expr;
Unbound(const OpaqueRule<AlphaT> *expr_) throw()
: expr(const_cast<OpaqueRule<AlphaT> *>(expr_))
{ }
public:
~Unbound(void) throw() {
expr = 0;
}
};
/// unbound symbol
template <typename AlphaT>
class Unbound<AlphaT, symbol_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class Symbol<AlphaT>;
friend class TDOP<AlphaT>;
Symbol<AlphaT> *expr;
Unbound(const Symbol<AlphaT> *expr_) throw()
: expr(const_cast<Symbol<AlphaT> *>(expr_))
{ }
public:
typedef Unbound<AlphaT, symbol_tag> self_type;
typedef unbound_symbol_tag tag_type;
~Unbound(void) throw() {
expr = 0;
}
/// unbound predicate symbol, e.g. *(~s), where 's' is a symbol.
const Unbound<AlphaT, ubound_symbol_predicate_tag>
operator*(void) const throw() {
return Unbound<AlphaT, ubound_symbol_predicate_tag>(expr);
}
};
/// unbound predicate symbol
template <typename AlphaT>
class Unbound<AlphaT, ubound_symbol_predicate_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class Unbound<AlphaT, symbol_tag>;
Symbol<AlphaT> *expr;
Unbound(const Symbol<AlphaT> *expr_) throw()
: expr(const_cast<Symbol<AlphaT> *>(expr_))
{ }
public:
typedef Unbound<AlphaT, ubound_symbol_predicate_tag> self_type;
typedef ubound_symbol_predicate_tag tag_type;
~Unbound(void) throw() {
expr = 0;
}
};
/// unbound operator
template <typename AlphaT>
class Unbound<AlphaT, operator_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class Operator<AlphaT>;
Operator<AlphaT> *expr;
Unbound(const Operator<AlphaT> *expr_) throw()
: expr(const_cast<Operator<AlphaT> *>(expr_))
{ }
public:
typedef Unbound<AlphaT, operator_tag> self_type;
typedef unbound_operator_tag tag_type;
~Unbound(void) throw() {
expr = 0;
}
};
/// unbound operator string
template <typename AlphaT>
class Unbound<AlphaT, operator_string_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class OperatorString<AlphaT>;
OperatorString<AlphaT> *expr;
Unbound(const OperatorString<AlphaT> *expr_) throw()
: expr(const_cast<OperatorString<AlphaT> *>(expr_))
{ }
public:
typedef Unbound<AlphaT, operator_string_tag> self_type;
typedef unbound_operator_string_tag tag_type;
~Unbound(void) throw() {
expr = 0;
}
};
/// unbound term
template <typename AlphaT>
class Unbound<AlphaT, term_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class Term<AlphaT>;
Term<AlphaT> *expr;
Unbound(const Term<AlphaT> *expr_) throw()
: expr(const_cast<Term<AlphaT> *>(expr_))
{ }
public:
typedef Unbound<AlphaT, term_tag> self_type;
typedef unbound_term_tag tag_type;
~Unbound(void) throw() {
expr = 0;
}
};
/// unbound category
template <typename AlphaT>
class Unbound<AlphaT, category_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class OpaqueCategory<AlphaT>;
friend class TDOP<AlphaT>;
OpaqueCategory<AlphaT> *expr;
Unbound(const OpaqueCategory<AlphaT> *expr_) throw()
: expr(const_cast<OpaqueCategory<AlphaT> *>(expr_))
{ }
public:
typedef Unbound<AlphaT, category_tag> self_type;
typedef unbound_category_tag tag_type;
/// (~c)[n], unbound category, unbound lower bound
const Unbound<AlphaT, category_lb_tag>
operator[](unsigned &lower_bound) const throw() {
return Unbound<AlphaT, category_lb_tag>(expr, &lower_bound);
}
// an initial rule, with an unbound category
FLTL_TDOP_RULE_PATTERN(unbound_category_tag)
~Unbound(void) throw() {
expr = 0;
}
};
/// unbound category, unbound lower bound
template <typename AlphaT>
class Unbound<AlphaT, category_lb_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class Unbound<AlphaT, category_tag>;
OpaqueCategory<AlphaT> *expr;
unsigned *lower_bound;
Unbound(const OpaqueCategory<AlphaT> *expr_, unsigned *lb) throw()
: expr(const_cast<OpaqueCategory<AlphaT> *>(expr_))
, lower_bound(lb)
{ }
public:
typedef Unbound<AlphaT, category_lb_tag> self_type;
typedef unbound_category_lb_tag tag_type;
// an extension rule, with an unbound category and upper bound
FLTL_TDOP_RULE_PATTERN(unbound_category_lb_tag)
~Unbound(void) throw() {
expr = 0;
lower_bound = 0;
}
};
/// bound category, unbound lower bound
template <typename AlphaT>
class Bound<AlphaT, category_lb_tag> {
private:
friend class detail::PatternData<AlphaT>;
friend class OpaqueCategory<AlphaT>;
OpaqueCategory<AlphaT> *expr;
unsigned *lower_bound;
Bound(const OpaqueCategory<AlphaT> *expr_, unsigned *lb) throw()
: expr(const_cast<OpaqueCategory<AlphaT> *>(expr_))
, lower_bound(lb)
{ }
public:
typedef Bound<AlphaT, category_lb_tag> self_type;
typedef category_lb_tag tag_type;
// an extension rule, with an unbound upper bound, and a definite
// category
FLTL_TDOP_RULE_PATTERN(category_lb_tag)
~Bound(void) throw() {
expr = 0;
lower_bound = 0;
}
};
}}
#endif /* Grail_Plus_TDOP_UNBOUND_HPP_ */
| 24.958015
| 74
| 0.605138
|
iambrosie
|
865a71163dedde3fcde4c7e3e55f582b7d27cef3
| 4,481
|
cpp
|
C++
|
PA3/lex.cpp
|
Elmojica/CS280
|
6feeb34ea4e577c09df77ded4e0e0d00638994d7
|
[
"CC0-1.0"
] | null | null | null |
PA3/lex.cpp
|
Elmojica/CS280
|
6feeb34ea4e577c09df77ded4e0e0d00638994d7
|
[
"CC0-1.0"
] | null | null | null |
PA3/lex.cpp
|
Elmojica/CS280
|
6feeb34ea4e577c09df77ded4e0e0d00638994d7
|
[
"CC0-1.0"
] | null | null | null |
/*
* lex.cpp
*
* CS280 - Fall 2021
*/
#include <cctype>
#include <map>
using std::map;
using namespace std;
#include "lex.h"
static map<Token,string> tokenPrint = {
{PROGRAM, "PROGRAM"},
{WRITE, "WRITE"},
{INT, "INT"},
{ END, "END" },
{ IF, "IF" },
{FLOAT, "FLOAT"},
{STRING, "STRING"},
{ REPEAT, "REPEAT" },
{BEGIN, "BEGIN"},
{ IDENT, "IDENT" },
{ ICONST, "ICONST" },
{ RCONST, "RCONST" },
{ SCONST, "SCONST" },
{ PLUS, "PLUS" },
{ MINUS, "MINUS" },
{ MULT, "MULT" },
{ DIV, "DIV" },
{REM, "REM"},
{ ASSOP, "ASSOP" },
{ LPAREN, "LPAREN" },
{ RPAREN, "RPAREN" },
{ COMMA, "COMMA" },
{ EQUAL, "EQUAL" },
{ GTHAN, "GTHAN" },
{ SEMICOL, "SEMICOL" },
{ ERR, "ERR" },
{ DONE, "DONE" },
};
//Keywords mapping
static map<string,Token> kwmap = {
{"PROGRAM", PROGRAM},
{"WRITE", WRITE},
{ "INT", INT},
{ "FLOAT", FLOAT},
{ "STRING", STRING},
{ "REPEAT", REPEAT },
{ "BEGIN", BEGIN },
{"IF", IF},
{ "END", END },
};
ostream& operator<<(ostream& out, const LexItem& tok) {
Token tt = tok.GetToken();
out << tokenPrint[ tt ];
if( tt == IDENT || tt == ICONST || tt == SCONST || tt == RCONST || tt == ERR ) {
out << "(" << tok.GetLexeme() << ")";
}
return out;
}
LexItem id_or_kw(const string& lexeme, int linenum)
{
Token tt = IDENT;
auto kIt = kwmap.find(lexeme);
if( kIt != kwmap.end() )
tt = kIt->second;
return LexItem(tt, lexeme, linenum);
}
LexItem
getNextToken(istream& in, int& linenum)
{
enum TokState { START, INID, INSTRING, ININT, INFLOAT, INCOMMENT } lexstate = START;
string lexeme;
char ch, nextch, nextchar;
//cout << "in getNestToken" << endl;
while(in.get(ch)) {
//cout << "in while " << ch << endl;
switch( lexstate ) {
case START:
if( ch == '\n' )
linenum++;
if( isspace(ch) )
continue;
lexeme = ch;
if( isalpha(ch) ) {
lexeme = toupper(ch);
lexstate = INID;
}
else if( ch == '"' ) {
lexstate = INSTRING;
}
else if( isdigit(ch) ) {
lexstate = ININT;
}
else if( ch == '#' ) {
lexstate = INCOMMENT;
}
else {
Token tt = ERR;
switch( ch ) {
case '+':
tt = PLUS;
break;
case '-':
tt = MINUS;
break;
case '*':
tt = MULT;
break;
case '/':
tt = DIV;
break;
case '%':
tt = REM;
break;
case '=':
nextchar = in.peek();
if(nextchar == '='){
in.get(ch);
tt = EQUAL;
break;
}
tt = ASSOP;
break;
case '(':
tt = LPAREN;
break;
case ')':
tt = RPAREN;
break;
case ';':
tt = SEMICOL;
break;
case ',':
tt = COMMA;
break;
case '>':
tt = GTHAN;
break;
case '.':
nextch = in.peek();
if(isdigit(nextch)){
lexstate = INFLOAT;
continue;
}
else {
lexeme += nextch;
return LexItem(ERR, lexeme, linenum);
cout << "Here what?" << endl;
}
}
return LexItem(tt, lexeme, linenum);
}
break;
case INID:
if( isalpha(ch) || isdigit(ch) || ch == '_') {
ch = toupper(ch);
//cout << "inid " << ch << endl;
lexeme += ch;
}
else {
in.putback(ch);
return id_or_kw(lexeme, linenum);
}
break;
case INSTRING:
if( ch == '\n' ) {
return LexItem(ERR, lexeme, linenum);
}
lexeme += ch;
if( ch == '"' ) {
lexeme = lexeme.substr(1, lexeme.length()-2);
return LexItem(SCONST, lexeme, linenum);
}
break;
case ININT:
if( isdigit(ch) ) {
lexeme += ch;
}
else if(ch == '.') {
lexstate = INFLOAT;
in.putback(ch);
}
else {
in.putback(ch);
return LexItem(ICONST, lexeme, linenum);
}
break;
case INFLOAT:
if( ch == '.' && isdigit(in.peek()) ) {
lexeme += ch;
}
else if(isdigit(ch)){
lexeme += ch;
}
else if(ch == '.' && !isdigit(in.peek())){
lexeme += ch;
return LexItem(ERR, lexeme, linenum);
}
else {
in.putback(ch);
return LexItem(RCONST, lexeme, linenum);
}
break;
case INCOMMENT:
if( ch == '\n' ) {
++linenum;
lexstate = START;
}
break;
}
}//end of while loop
if( in.eof() )
return LexItem(DONE, "", linenum);
return LexItem(ERR, "some strange I/O error", linenum);
}
| 16.782772
| 85
| 0.481143
|
Elmojica
|
86669d7d3fd632dcabacd5da344bf82a5807a691
| 444
|
cpp
|
C++
|
src/detail/flow.cpp
|
szdanowi/bflow
|
71cb2e6d8e55b0cd07337815d690ced8a0cb583a
|
[
"MIT"
] | null | null | null |
src/detail/flow.cpp
|
szdanowi/bflow
|
71cb2e6d8e55b0cd07337815d690ced8a0cb583a
|
[
"MIT"
] | null | null | null |
src/detail/flow.cpp
|
szdanowi/bflow
|
71cb2e6d8e55b0cd07337815d690ced8a0cb583a
|
[
"MIT"
] | null | null | null |
#include "flow.hpp"
#include <ostream>
namespace bflow
{
namespace
{
const char* to_str(result value) {
switch (value) {
case result::rejected: return "rejected";
case result::accepted: return "accepted";
case result::completed: return "completed";
default: return "[INVALID RESULT]";
}
}
} // namespace
std::ostream& operator<<(std::ostream& os, result value) {
os << to_str(value);
return os;
}
} // namespace bflow
| 19.304348
| 58
| 0.668919
|
szdanowi
|
866f2edae264cbdb37de5e4701e0fb4d6d3f0a44
| 2,517
|
hpp
|
C++
|
libvast/vast/system/start_command.hpp
|
a4z/vast
|
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
|
[
"BSD-3-Clause"
] | null | null | null |
libvast/vast/system/start_command.hpp
|
a4z/vast
|
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
|
[
"BSD-3-Clause"
] | null | null | null |
libvast/vast/system/start_command.hpp
|
a4z/vast
|
2ce9ddbac61cc7f195434b06fe3605f0bdeec520
|
[
"BSD-3-Clause"
] | null | null | null |
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include <functional>
#include "vast/command.hpp"
namespace vast::system {
/// Callback for adding additional application logic to `start_command_impl`.
/// @relates start_command_impl
using start_command_extra_steps = std::function<caf::error(
caf::scoped_actor& self, const caf::settings& options, const caf::actor&)>;
/// Extensible base implementation for the *start* command that allows
/// users to add additional application logic.
/// @param extra_steps Function that adds additional application logic after
/// the node is connected and before the command enters its
/// loop to wait for CTRL+C or system shutdown.
/// @param invocation Invocation object that dispatches to this function.
/// @param sys The hosting CAF actor system.
/// @returns An non-default error on if the extra steps fail and
/// `start_command_impl` needs to stop running, `caf::none` otherwise.
/// @relates start_command
caf::message start_command_impl(start_command_extra_steps extra_steps,
const invocation& inv, caf::actor_system& sys);
/// Default implementation for the *start* command.
/// @param invocation Invocation object that dispatches to this function.
/// @param sys The hosting CAF actor system.
/// @returns An error on invalid arguments or when unable to connect to the
/// remote node, an empty message otherwise.
/// @relates application
caf::message start_command(const invocation& inv, caf::actor_system& sys);
} // namespace vast::system
| 51.367347
| 80
| 0.57052
|
a4z
|
86725899a1ff01ae0ac03e5b7f105187ae1a3f86
| 1,260
|
cc
|
C++
|
tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc
|
alecgunny/tensorrt-inference-server
|
6a9ae2936489c681d5ab7b6589d8aff7dd48829a
|
[
"BSD-3-Clause"
] | 1
|
2019-02-25T22:50:58.000Z
|
2019-02-25T22:50:58.000Z
|
tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc
|
alecgunny/tensorrt-inference-server
|
6a9ae2936489c681d5ab7b6589d8aff7dd48829a
|
[
"BSD-3-Clause"
] | null | null | null |
tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc
|
alecgunny/tensorrt-inference-server
|
6a9ae2936489c681d5ab7b6589d8aff7dd48829a
|
[
"BSD-3-Clause"
] | null | null | null |
--- tensorflow_serving/util/net_http/server/internal/evhttp_request.cc 2018-11-01 12:04:22.185086318 -0700
+++ /home/david/dev/gitlab/dgx/tensorrtserver/tools/patch/tfs/util/net_http/server/internal/evhttp_request.cc 2018-11-02 11:47:57.254526547 -0700
@@ -44,6 +44,8 @@
evhttp_uri_free(decoded_uri);
}
+ evhttp_clear_headers(¶ms);
+
if (request && evhttp_request_is_owned(request)) {
evhttp_request_free(request);
}
@@ -98,6 +100,8 @@
path = "/";
}
+ evhttp_parse_query(uri, ¶ms);
+
headers = evhttp_request_get_input_headers(request);
return true;
@@ -123,6 +127,26 @@
return parsed_request_->method;
}
+bool EvHTTPRequest::QueryParam(absl::string_view key, std::string* str) const {
+ std::string key_str(key.data(), key.size());
+ const char* val =
+ evhttp_find_header(&parsed_request_->params, key_str.c_str());
+ if (val != nullptr) {
+ *str = val;
+ return true;
+ }
+
+ return false;
+}
+
+evbuffer* EvHTTPRequest::InputBuffer() const {
+ return evhttp_request_get_input_buffer(parsed_request_->request);
+}
+
+evbuffer* EvHTTPRequest::OutputBuffer() {
+ return output_buf;
+}
+
bool EvHTTPRequest::Initialize() {
output_buf = evbuffer_new();
return output_buf != nullptr;
| 26.25
| 145
| 0.688889
|
alecgunny
|
8672e2fd6634d5727b1d5434a132567378bfe01b
| 2,495
|
cpp
|
C++
|
src/solo/stb/SoloSTBTrueTypeFont.cpp
|
0xc0dec/solo
|
381276451767690b5fdb5a50a6b74a92ba78aa15
|
[
"Zlib"
] | 31
|
2015-02-20T04:03:43.000Z
|
2022-03-07T19:04:02.000Z
|
src/solo/stb/SoloSTBTrueTypeFont.cpp
|
0xc0dec/solo
|
381276451767690b5fdb5a50a6b74a92ba78aa15
|
[
"Zlib"
] | 14
|
2015-07-13T09:24:22.000Z
|
2016-10-24T10:09:58.000Z
|
src/solo/stb/SoloSTBTrueTypeFont.cpp
|
0xc0dec/solo
|
381276451767690b5fdb5a50a6b74a92ba78aa15
|
[
"Zlib"
] | 1
|
2020-02-22T15:09:36.000Z
|
2020-02-22T15:09:36.000Z
|
/*
* Copyright (c) Aleksey Fedotov
* MIT license
*/
#include "SoloSTBTrueTypeFont.h"
#include "SoloTexture.h"
#include "SoloDevice.h"
#include "SoloFileSystem.h"
#include "SoloStringUtils.h"
#include "SoloTextureData.h"
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
using namespace solo;
auto STBTrueTypeFont::glyphInfo(u32 character, float offsetX, float offsetY) -> GlyphInfo
{
const auto dimensions = atlas_->dimensions();
stbtt_aligned_quad quad;
stbtt_GetPackedQuad(charInfo_.get(), static_cast<u32>(dimensions.x()), static_cast<u32>(dimensions.y()),
character - firstChar_, &offsetX, &offsetY, &quad, 1);
auto xmin = quad.x0;
auto xmax = quad.x1;
auto ymin = -quad.y1;
auto ymax = -quad.y0;
GlyphInfo result{};
result.offsetX = offsetX;
result.offsetY = offsetY;
result.positions =
{
{ xmin, ymin, 0 },
{ xmin, ymax, 0 },
{ xmax, ymax, 0 },
{ xmax, ymin, 0 }
};
result.uvs =
{
{ quad.s0, quad.t1 },
{ quad.s0, quad.t0 },
{ quad.s1, quad.t0 },
{ quad.s1, quad.t1 }
};
return result; // TODO move
}
bool STBTrueTypeFont::canLoadFromFile(const str &path)
{
return stringutils::endsWith(path, ".ttf");
}
auto STBTrueTypeFont::loadFromFile(Device *device, const str &path, u32 size, u32 atlasWidth, u32 atlasHeight,
u32 firstChar, u32 charCount, u32 oversampleX, u32 oversampleY) -> sptr<STBTrueTypeFont>
{
auto data = device->fileSystem()->readBytes(path);
auto result = sptr<STBTrueTypeFont>(new STBTrueTypeFont());
result->firstChar_ = firstChar;
result->charInfo_ = std::make_unique<stbtt_packedchar[]>(charCount);
vec<u8> pixels;
pixels.resize(atlasWidth * atlasHeight);
stbtt_pack_context context;
const auto ret = stbtt_PackBegin(&context, pixels.data(), atlasWidth, atlasHeight, 0, 1, nullptr);
panicIf(!ret, "Unable to process font ", path);
stbtt_PackSetOversampling(&context, oversampleX, oversampleY);
stbtt_PackFontRange(&context, data.data(), 0, static_cast<float>(size), firstChar, charCount, result->charInfo_.get());
stbtt_PackEnd(&context);
const auto atlasData = Texture2DData::fromMemory(atlasWidth, atlasHeight, TextureDataFormat::Red, pixels);
result->atlas_ = Texture2D::fromData(device, atlasData, true);
result->atlas_->setFilter(TextureFilter::Linear, TextureFilter::Linear, TextureMipFilter::Linear);
return result;
}
| 30.426829
| 123
| 0.67976
|
0xc0dec
|
867536b48253f6ae10e7ffc8e0c299e3229da0ba
| 1,522
|
cpp
|
C++
|
mindsystem/mindsee/mindbase/baseDemo.cpp
|
Jack2Hub/mindproject
|
7d0e3651711fa3e8234e91ada7c2767f87d687d5
|
[
"BSD-2-Clause"
] | 2
|
2021-04-06T11:43:37.000Z
|
2021-08-31T10:50:02.000Z
|
mindsystem/mindsee/mindbase/baseDemo.cpp
|
Jack2Hub/mindproject
|
7d0e3651711fa3e8234e91ada7c2767f87d687d5
|
[
"BSD-2-Clause"
] | null | null | null |
mindsystem/mindsee/mindbase/baseDemo.cpp
|
Jack2Hub/mindproject
|
7d0e3651711fa3e8234e91ada7c2767f87d687d5
|
[
"BSD-2-Clause"
] | 2
|
2021-02-26T11:46:48.000Z
|
2021-09-15T09:54:03.000Z
|
#include <iostream>
#include <unistd.h>
#include "stream.hpp"
using namespace std;
int main()
{
Stream testStream1;
testStream1.SetCtrlCb([](std::string _cmd, void* userdata){return;}); // the cmd callback function must be set, you can just return without doing anything
testStream1.SetFrameCb([](Stream::sFrame_t& frame, void* userdata){
// TODO
// save frame to file
// just test here
printf("the %s Stream send %s data, CODEC typeis %s, size is %d\n",
"master",
(Stream::CHANNEL_VIDEO == frame.channel_type)?"video":"other data",
(Stream::VIDEO_CODEC_H265 == frame.codec_type)?"h265":"other type",
frame.data.c_str()
);
});
testStream1.Start("172.19.24.95/0"); //the url fotmat: ip/channel
Stream testStream2;
testStream2.SetCtrlCb([](std::string _cmd, void* userdata){return;});
testStream2.SetFrameCb([](Stream::sFrame_t& frame, void* userdata){
// TODO
// save frame to file
// just test here
printf("the %s Stream send %s data, CODEC typeis %s, size is %d\n",
"slave",
(Stream::CHANNEL_VIDEO == frame.channel_type)?"video":"other data",
(Stream::VIDEO_CODEC_H265 == frame.codec_type)?"h265":"other type",
frame.data.c_str()
);
});
testStream2.Start("172.19.24.95/1");
while(true)
{
printf("looping...\n");
sleep(1);
}
return 0;
}
| 32.382979
| 158
| 0.575558
|
Jack2Hub
|
867c8a204338df55f6778dd49c730737fdd07e19
| 3,882
|
cpp
|
C++
|
core/common/cstream.cpp
|
plonk/peercast-0.1218
|
30fc2401dc798336429a979fe7aaca8883e63ed9
|
[
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 28
|
2017-04-30T13:56:13.000Z
|
2022-03-20T06:54:37.000Z
|
core/common/cstream.cpp
|
plonk/peercast-0.1218
|
30fc2401dc798336429a979fe7aaca8883e63ed9
|
[
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 72
|
2017-04-25T03:42:58.000Z
|
2021-12-04T06:35:28.000Z
|
core/common/cstream.cpp
|
plonk/peercast-0.1218
|
30fc2401dc798336429a979fe7aaca8883e63ed9
|
[
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 12
|
2017-04-16T06:25:24.000Z
|
2021-07-07T13:28:27.000Z
|
// ------------------------------------------------
// File : cstream.cpp
// Date: 4-apr-2002
// Author: giles
// Desc:
// Channel streaming classes. These do the actual
// streaming of media between clients.
//
// (c) 2002 peercast.org
//
// ------------------------------------------------
// 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.
// ------------------------------------------------
#include "channel.h"
#include "cstream.h"
#include "pcp.h"
#include "servmgr.h"
#include "version2.h"
#include "chanmgr.h"
// ------------------------------------------
bool ChannelStream::getStatus(std::shared_ptr<Channel> ch, ChanPacket &pack)
{
unsigned int ctime = sys->getTime();
ChanHitList *chl = chanMgr->findHitListByID(ch->info.id);
if (!chl)
return false;
int newLocalListeners = ch->localListeners();
int newLocalRelays = ch->localRelays();
if (
(
(numListeners != newLocalListeners)
|| (numRelays != newLocalRelays)
|| (ch->isPlaying() != isPlaying)
|| (servMgr->getFirewall(ch->ipVersion) != fwState)
|| ((ctime - lastUpdate) > 120)
)
&& ((ctime - lastUpdate) > 10)
)
{
numListeners = newLocalListeners;
numRelays = newLocalRelays;
isPlaying = ch->isPlaying();
fwState = servMgr->getFirewall(ch->ipVersion);
lastUpdate = ctime;
ChanHit hit;
unsigned int oldp = ch->rawData.getOldestPos();
unsigned int newp = ch->rawData.getLatestPos();
hit.initLocal(numListeners, numRelays, ch->info.numSkips, ch->info.getUptime(), isPlaying, oldp, newp, ch->canAddRelay(), ch->sourceHost.host, (ch->ipVersion == Channel::IP_V6));
hit.tracker = ch->isBroadcasting();
MemoryStream pmem(pack.data, sizeof(pack.data));
AtomStream atom(pmem);
atom.writeParent(PCP_BCST, 10);
atom.writeChar(PCP_BCST_GROUP, PCP_BCST_GROUP_TRACKERS);
atom.writeChar(PCP_BCST_HOPS, 0);
atom.writeChar(PCP_BCST_TTL, 11);
atom.writeBytes(PCP_BCST_FROM, servMgr->sessionID.id, 16);
atom.writeInt(PCP_BCST_VERSION, PCP_CLIENT_VERSION);
atom.writeInt(PCP_BCST_VERSION_VP, PCP_CLIENT_VERSION_VP);
atom.writeBytes(PCP_BCST_VERSION_EX_PREFIX, PCP_CLIENT_VERSION_EX_PREFIX, 2);
atom.writeShort(PCP_BCST_VERSION_EX_NUMBER, PCP_CLIENT_VERSION_EX_NUMBER);
atom.writeBytes(PCP_BCST_CHANID, ch->info.id.id, 16);
hit.writeAtoms(atom, GnuID());
pack.len = pmem.pos;
pack.type = ChanPacket::T_PCP;
return true;
}else
return false;
}
// ------------------------------------------
void ChannelStream::updateStatus(std::shared_ptr<Channel> ch)
{
ChanPacket pack;
if (getStatus(ch, pack))
{
if (!ch->isBroadcasting())
{
int cnt = chanMgr->broadcastPacketUp(pack, ch->info.id, servMgr->sessionID, GnuID());
LOG_INFO("Sent channel status update to %d clients", cnt);
}
}
}
// -----------------------------------
void ChannelStream::readRaw(Stream &in, std::shared_ptr<Channel> ch)
{
ChanPacket pack;
const int readLen = 8192;
pack.init(ChanPacket::T_DATA, pack.data, readLen, ch->streamPos);
in.read(pack.data, pack.len);
ch->newPacket(pack);
ch->checkReadDelay(pack.len);
ch->streamPos += pack.len;
}
| 33.179487
| 186
| 0.600206
|
plonk
|
86849cf9a2c0ac1a5f11afdd2c94bb8083994bda
| 19,319
|
cc
|
C++
|
notification/src/macro_generator.cc
|
sdelafond/centreon-broker
|
21178d98ed8a061ca71317d23c2026dbc4edaca2
|
[
"Apache-2.0"
] | null | null | null |
notification/src/macro_generator.cc
|
sdelafond/centreon-broker
|
21178d98ed8a061ca71317d23c2026dbc4edaca2
|
[
"Apache-2.0"
] | null | null | null |
notification/src/macro_generator.cc
|
sdelafond/centreon-broker
|
21178d98ed8a061ca71317d23c2026dbc4edaca2
|
[
"Apache-2.0"
] | null | null | null |
/*
** Copyright 2011-2015 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <sstream>
#include <iomanip>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/notification/utilities/qhash_func.hh"
#include "com/centreon/broker/notification/macro_generator.hh"
#include "com/centreon/broker/notification/utilities/get_datetime_string.hh"
#include "com/centreon/broker/notification/macro_getters.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::notification;
// Used for contact macros.
const char* get_email_key() {return "email";}
const char* get_pager_key() {return "pager";}
macro_generator::x_macro_map macro_generator::_map;
/**
* Default constructor.
*/
macro_generator::macro_generator() {
if (_map.empty())
_fill_x_macro_map(_map);
}
/**
* Generate macros.
*
* @param[in,out] container A container of asked macro, which will be filled as a result.
* @param[in] id The id of the node for which we create macros.
* @param[in] cnt The contact.
* @param[in] st The state.
* @param[in] cache The node cache.
* @param[in] act The notification action.
*/
void macro_generator::generate(
macro_container& container,
objects::node_id id,
objects::contact const& cnt,
state const& st,
node_cache const& cache,
action const& act) const {
objects::node::ptr node = st.get_node_by_id(id);
if (!node)
throw (exceptions::msg()
<< "notification: can't find the node (" << id.get_host_id()
<< ", " << id.get_service_id()
<< ") while generating its macros");
objects::node::ptr host = node;
if (id.is_service())
host = st.get_node_by_id(objects::node_id(id.get_host_id()));
if (!host)
throw (exceptions::msg()
<< "notification: can't find the host "
<< id.get_host_id() << " while generating macros");
for (macro_container::iterator it(container.begin()),
end(container.end());
it != end;
++it) {
logging::debug(logging::low)
<< "notification: searching macro " << it.key();
if (_get_global_macros(it.key(), st, it.value()))
continue ;
else if (_get_x_macros(
it.key(),
macro_context(id, cnt, st, cache, act),
it.value()))
continue ;
else if (_get_custom_macros(
it.key(),
id,
cache,
it.value()))
continue ;
else {
logging::debug(logging::medium) << "notification: macro '"
<< it.key() << "' was not found for node (" << id.get_host_id()
<< ", " << id.get_service_id() << ")";
it->clear();
}
}
}
/**
* Get this macro if it's a global macro.
*
* @param[in] macro_name The name of the macro.
* @param[in] st The state.
* @param[out] result The result, filled if the macro is global.
* @return True if this macro was found in the global macros.
*/
bool macro_generator::_get_global_macros(
std::string const& macro_name,
state const& st,
std::string& result) {
QHash<std::string, std::string> const& global_macros =
st.get_global_macros();
QHash<std::string, std::string>::const_iterator found =
global_macros.find(macro_name);
if (found == global_macros.end())
return (false);
result = *found;
return (true);
}
/**
* Get standard nagios macros.
*
* @param[in] macro_name The macro name.
* @param[in] contact The macro context.
* @param[out] result The result, filled if the macro is standard.
*
* @return True if the macro was found in the standard macros.
*/
bool macro_generator::_get_x_macros(
std::string const& macro_name,
macro_context const& context,
std::string& result) const {
x_macro_map::const_iterator found = _map.find(macro_name);
if (found == _map.end())
return (false);
else {
result = (*found)(context);
return (true);
}
}
/**
* Get custom macros.
*
* @param[in] macro_name The macro name.
* @param[in] id The id of the node being notified.
* @param[in] cache The node cache.
* @param[out] result The result, filled if the macro is a custom macro.
*
* @return True if the macro was found in the custom macros.
*/
bool macro_generator::_get_custom_macros(
std::string const& macro_name,
objects::node_id id,
node_cache const& cache,
std::string& result) {
QHash<std::string, neb::custom_variable_status> const* custom_vars;
if (id.is_host())
custom_vars = &cache.get_host(id).get_custom_vars();
else
custom_vars = &cache.get_service(id).get_custom_vars();
QHash<std::string, neb::custom_variable_status>::const_iterator found =
custom_vars->find(macro_name);
if (found != custom_vars->end()) {
result = found->value.toStdString();
return (true);
}
else
return (false);
}
/**
* Fill the macro generator map with functions used to generate macros.
*
* @param[in] map The map to fill.
*/
void macro_generator::_fill_x_macro_map(x_macro_map& map) {
// Time macros.
map.insert(
"LONGDATETIME",
&get_datetime_string<utilities::long_date_time>);
map.insert(
"SHORTDATETIME",
&get_datetime_string<utilities::short_date_time>);
map.insert(
"DATE",
&get_datetime_string<utilities::short_date>);
map.insert(
"TIME",
&get_datetime_string<utilities::short_time>);
map.insert(
"TIMET",
&get_timet_string);
// Host specific macros.
map.insert(
"HOSTNAME",
&get_host_member_as_string<
neb::host,
QString,
&neb::host::host_name,
0>);
map.insert(
"HOSTALIAS",
&get_host_member_as_string<neb::host, QString, &neb::host::alias, 0>);
map.insert(
"HOSTADDRESS",
&get_host_member_as_string<neb::host, QString, &neb::host::address, 0>);
map.insert(
"HOSTSTATE",
&get_host_state);
map.insert(
"HOSTSTATEID",
&get_host_status_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::current_state,
0>);
map.insert(
"LASTHOSTSTATE",
&get_last_host_state);
map.insert(
"LASTHOSTSTATEID",
&get_host_prevstatus_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::current_state,
0>);
map.insert(
"HOSTSTATETYPE",
&get_host_state_type);
map.insert(
"HOSTATTEMPT",
&get_host_status_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::current_check_attempt,
0>);
map.insert(
"MAXHOSTATTEMPTS",
&get_host_status_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::max_check_attempts,
0>);
// Event and problem id macros are ignored.
map.insert("HOSTEVENTID", &null_getter);
map.insert("LASTHOSTEVENTID", &null_getter);
map.insert("HOSTPROBLEMID", &null_getter);
map.insert("LASTHOSTPROBLEMID", &null_getter);
map.insert(
"HOSTLATENCY",
&get_host_status_member_as_string<
neb::host_service_status,
double,
&neb::host_service_status::latency,
3>);
map.insert(
"HOSTEXECUTIONTIME",
&get_host_status_member_as_string<
neb::host_service_status,
double,
&neb::host_service_status::execution_time,
3>);
map.insert(
"HOSTDURATION",
get_host_duration);
map.insert(
"HOSTDURATIONSEC",
get_host_duration_sec);
map.insert(
"HOSTDOWNTIME",
&get_node_downtime_number);
map.insert(
"HOSTPERCENTCHANGE",
&get_host_status_member_as_string<
neb::host_service_status,
double,
&neb::host_service_status::percent_state_change,
2>);
map.insert(
"HOSTGROUPNAME",
&null_getter);
map.insert(
"HOSTGROUPNAMES",
&null_getter);
map.insert(
"LASTHOSTCHECK",
&get_host_status_member_as_string<
neb::host_service_status,
timestamp,
&neb::host_service_status::last_check,
0>);
map.insert(
"LASTHOSTSTATECHANGE",
&get_host_status_member_as_string<
neb::host_service_status,
timestamp,
&neb::host_service_status::last_state_change,
0>);
map.insert(
"LASTHOSTUP",
&get_host_status_member_as_string<
neb::host_status,
timestamp,
&neb::host_status::last_time_up,
0>);
map.insert(
"LASTHOSTDOWN",
&get_host_status_member_as_string<
neb::host_status,
timestamp,
&neb::host_status::last_time_down,
0>);
map.insert(
"LASTHOSTUNREACHABLE",
&get_host_status_member_as_string<
neb::host_status,
timestamp,
&neb::host_status::last_time_unreachable,
0>);
map.insert(
"HOSTOUTPUT",
&get_host_output<false>);
map.insert(
"LONGHOSTOUTPUT",
&get_host_output<true>);
map.insert(
"HOSTPERFDATA",
&get_host_status_member_as_string<
neb::host_service_status,
QString,
&neb::host_service_status::perf_data,
0>);
map.insert(
"HOSTCHECKCOMMAND",
&get_host_status_member_as_string<
neb::host_service_status,
QString,
&neb::host_service_status::check_command,
0>);
// Hst ack macros are deprecated and ignored.
map.insert("HOSTACKAUTHOR", &null_getter);
map.insert("HOSTACKAUTHORNAME", &null_getter);
map.insert("HOSTACKAUTHORALIAS", &null_getter);
map.insert("HOSTACKCOMMENT", &null_getter);
map.insert(
"TOTALHOSTSERVICES",
&get_total_host_services<-1>);
map.insert(
"TOTALHOSTSERVICESOK",
&get_total_host_services<objects::node_state::service_ok>);
map.insert(
"TOTALHOSTSERVICESWARNING",
&get_total_host_services<objects::node_state::service_warning>);
map.insert(
"TOTALHOSTSERVICESUNKNOWN",
&get_total_host_services<objects::node_state::service_unknown>);
map.insert(
"TOTALHOSTSERVICESCRITICAL",
&get_total_host_services<objects::node_state::service_critical>);
// Service macros
map.insert(
"SERVICEDESC",
&get_service_status_member_as_string<
neb::service_status,
QString,
&neb::service_status::service_description,
0>);
map.insert(
"SERVICESTATE",
&get_service_state);
map.insert(
"SERVICESTATEID",
&get_service_status_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::current_state,
0>);
map.insert(
"LASTSERVICESTATE",
&get_last_service_state);
map.insert(
"LASTSERVICESTATEID",
&get_service_prevstatus_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::current_state,
0>);
map.insert(
"SERVICESTATETYPE",
&get_service_state_type);
map.insert(
"SERVICEATTEMPT",
&get_service_status_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::current_check_attempt,
0>);
map.insert(
"MAXSERVICEATTEMPTS",
&get_service_status_member_as_string<
neb::host_service_status,
short,
&neb::host_service_status::max_check_attempts,
0>);
map.insert(
"SERVICEISVOLATILE",
&get_service_member_as_string<
neb::service,
bool,
&neb::service::is_volatile,
0>);
// Event id are ignored.
map.insert("SERVICEEVENTID", &null_getter);
map.insert("LASTSERVICEEVENTID", &null_getter);
map.insert("SERVICEPROBLEMID", &null_getter);
map.insert("LASTSERVICEPROBLEMID", &null_getter);
map.insert(
"SERVICELATENCY",
&get_service_status_member_as_string<
neb::host_service_status,
double,
&neb::host_service_status::latency,
3>);
map.insert(
"SERVICEEXECUTIONTIME",
&get_service_status_member_as_string<
neb::host_service_status,
double,
&neb::host_service_status::execution_time,
3>);
map.insert(
"SERVICEDURATION",
&get_service_duration);
map.insert(
"SERVICEDURATIONSEC",
&get_service_duration_sec);
// XXX map.insert(
// "SERVICEDOWNTIME",
// &get_service_status_member_as_string<
// neb::host_service_status,
// short,
// &neb::host_service_status::scheduled_downtime_depth,
// 0>);
map.insert(
"SERVICEPERCENTCHANGE",
&get_service_status_member_as_string<
neb::host_service_status,
double,
&neb::host_service_status::percent_state_change,
2>);
map.insert(
"SERVICEGROUPNAME",
&null_getter);
map.insert(
"SERVICEGROUPNAMES",
&null_getter);
map.insert(
"LASTSERVICECHECK",
&get_service_status_member_as_string<
neb::host_service_status,
timestamp,
&neb::host_service_status::last_check,
0>);
map.insert(
"LASTSERVICESTATECHANGE",
&get_service_status_member_as_string<
neb::host_service_status,
timestamp,
&neb::host_service_status::last_state_change,
0>);
map.insert(
"LASTSERVICEOK",
&get_service_status_member_as_string<
neb::service_status,
timestamp,
&neb::service_status::last_time_ok,
0>);
map.insert(
"LASTSERVICEWARNING",
&get_service_status_member_as_string<
neb::service_status,
timestamp,
&neb::service_status::last_time_warning,
0>);
map.insert(
"LASTSERVICEUNKNOWN",
&get_service_status_member_as_string<
neb::service_status,
timestamp,
&neb::service_status::last_time_unknown,
0>);
map.insert(
"LASTSERVICECRITICAL",
&get_service_status_member_as_string<
neb::service_status,
timestamp,
&neb::service_status::last_time_critical,
0>);
map.insert(
"SERVICEOUTPUT",
&get_service_output<false>);
map.insert(
"LONGSERVICEOUTPUT",
&get_service_output<true>);
map.insert(
"SERVICEPERFDATA",
&get_service_status_member_as_string<
neb::host_service_status,
QString,
&neb::host_service_status::perf_data,
0>);
map.insert(
"SERVICECHECKCOMMAND",
&get_service_status_member_as_string<
neb::host_service_status,
QString,
&neb::host_service_status::check_command,
0>);
// Deprecated, ignored.
map.insert("SERVICEACKAUTHOR", &null_getter);
map.insert("SERVICEACKAUTHORNAME", &null_getter);
map.insert("SERVICEACKAUTHORALIAS", &null_getter);
map.insert("SERVICEACKCOMMENT", &null_getter);
// Counting macros.
map.insert(
"TOTALHOSTSUP",
&get_total_hosts<objects::node_state::host_up>);
map.insert(
"TOTALHOSTSDOWN",
&get_total_hosts<objects::node_state::host_down>);
map.insert(
"TOTALHOSTSUNREACHABLE",
&get_total_hosts<objects::node_state::host_unreachable>);
map.insert(
"TOTALHOSTSDOWNUNHANDLED",
&get_total_hosts_unhandled<objects::node_state::host_down>);
map.insert(
"TOTALHOSTSUNREACHABLEUNHANDLED",
&get_total_hosts_unhandled<objects::node_state::host_unreachable>);
map.insert(
"TOTALHOSTPROBLEMS",
&get_total_hosts<-1>);
map.insert(
"TOTALHOSTPROBLEMSUNHANDLED",
&get_total_hosts_unhandled<-1>);
map.insert(
"TOTALSERVICESOK",
&get_total_services<objects::node_state::service_ok>);
map.insert(
"TOTALSERVICESWARNING",
&get_total_services<objects::node_state::service_warning>);
map.insert(
"TOTALSERVICESCRITICAL",
&get_total_services<objects::node_state::service_critical>);
map.insert(
"TOTALSERVICESUNKNOWN",
&get_total_services<objects::node_state::service_unknown>);
map.insert(
"TOTALSERVICESWARNINGUNHANDLED",
&get_total_services_unhandled<objects::node_state::service_warning>);
map.insert(
"TOTALSERVICESCRITICALUNHANDLED",
&get_total_services_unhandled<objects::node_state::service_critical>);
map.insert(
"TOTALSERVICESUNKNOWNUNHANDLED",
&get_total_services_unhandled<objects::node_state::service_unknown>);
map.insert(
"TOTALSERVICEPROBLEMS",
&get_total_services<-1>);
map.insert(
"TOTALSERVICEPROBLEMSUNHANDLED",
&get_total_services_unhandled<-1>);
// Groups macros.
map.insert(
"HOSTGROUPALIAS",
&null_getter);
map.insert(
"HOSTGROUPMEMBERS",
&null_getter);
map.insert(
"SERVICEGROUPALIAS",
&null_getter);
map.insert(
"SERVICEGROUPMEMBERS",
&null_getter);
// Contact macros.
map.insert(
"CONTACTNAME",
&get_contact_member<std::string const&, &objects::contact::get_description, 0>);
map.insert(
"CONTACTALIAS",
&get_contact_member<std::string const&, &objects::contact::get_description, 0>);
map.insert(
"CONTACTEMAIL",
&get_contact_info<get_email_key>);
map.insert(
"CONTACTPAGER",
&get_contact_info<get_pager_key>);
map.insert(
"CONTACTADDRESS1",
&get_address_of_contact<1>);
map.insert(
"CONTACTADDRESS2",
&get_address_of_contact<2>);
map.insert(
"CONTACTADDRESS3",
&get_address_of_contact<3>);
map.insert(
"CONTACTADDRESS4",
&get_address_of_contact<4>);
map.insert(
"CONTACTADDRESS5",
&get_address_of_contact<5>);
map.insert(
"CONTACTADDRESS6",
&get_address_of_contact<6>);
map.insert(
"CONTACTGROUPALIAS",
&null_getter);
map.insert(
"CONTACTGROUPMEMBERS",
&null_getter);
// Notification macro.
map.insert(
"NOTIFICATIONTYPE",
&get_notification_type);
map.insert(
"NOTIFICATIONRECIPIENTS",
&get_contact_member<std::string const&, &objects::contact::get_description, 0>);
map.insert(
"HOSTNOTIFICATIONNUMBER",
&get_action_member<unsigned int, &action::get_notification_number, 0>);
map.insert(
"SERVICENOTIFICATIONNUMBER",
&get_action_member<unsigned int, &action::get_notification_number, 0>);
// We will manage notification escalation/downtime macros
// when we will manage escalations and downtimes.
map.insert("NOTIFICATIONISESCALATED", &null_getter);
map.insert("NOTIFICATIONCOMMENT", &null_getter);
// For now, notification author macros are ignored.
map.insert("NOTIFICATIONAUTHOR", &null_getter);
map.insert("NOTIFICATIONAUTHORNAME", &null_getter);
map.insert("NOTIFICATIONAUTHORALIAS", &null_getter);
// Notification id rightfully ignored.
map.insert("HOSTNOTIFICATIONID", &null_getter);
map.insert("SERVICENOTIFICATIONID", &null_getter);
}
| 29.138763
| 91
| 0.661266
|
sdelafond
|
868504c3b01afe7814aed8af1def27d945d7d3c4
| 2,989
|
cpp
|
C++
|
2020/day24/main.cpp
|
bielskij/AOC-2019
|
e98d660412037b3fdac4a6b49adcb9230f518c99
|
[
"MIT"
] | null | null | null |
2020/day24/main.cpp
|
bielskij/AOC-2019
|
e98d660412037b3fdac4a6b49adcb9230f518c99
|
[
"MIT"
] | null | null | null |
2020/day24/main.cpp
|
bielskij/AOC-2019
|
e98d660412037b3fdac4a6b49adcb9230f518c99
|
[
"MIT"
] | null | null | null |
#include <climits>
#include "common/types.h"
#include "utils/file.h"
#include "utils/utils.h"
#define DEBUG_LEVEL 5
#include "common/debug.h"
enum Color {
WHITE,
BLACK
};
struct Floor {
Floor() {
this->minX = INT_MAX;
this->maxX = INT_MIN;
this->minY = INT_MAX;
this->maxY = INT_MIN;
}
Color getColor(const Point<int> &p) {
Color ret = WHITE;
auto row = this->floor.find(p.y());
if (row != this->floor.end()) {
auto col = row->second.find(p.x());
if (col != row->second.end()) {
ret = col->second;
}
}
return ret;
}
void setColor(const Point<int> &p, Color color) {
if (p.x() > this->maxX) this->maxX = p.x();
if (p.x() < this->minX) this->minX = p.x();
if (p.y() > this->maxY) this->maxY = p.y();
if (p.y() < this->minY) this->minY = p.y();
this->floor[p.y()][p.x()] = color;
}
void spread() {
this->minX--;
this->maxX++;
this->minY--;
this->maxY++;
}
void toggle(const Point<int> &p) {
this->setColor(p, (this->getColor(p) == WHITE) ? BLACK : WHITE);
}
int getBlack() {
int ret = 0;
for (auto row : this->floor) {
for (auto col : row.second) {
if (col.second == BLACK) {
ret++;
}
}
}
return ret;
}
std::map<int, std::map<int, Color>> floor;
int minX, maxX, minY, maxY;
};
int main(int argc, char *argv[]) {
auto lines = File::readAllLines(argv[1]);
Floor floor;
for (const auto &line : lines) {
Point<int> center;
for (int i = 0; i < line.size(); i++) {
switch (line[i]) {
// e, se, sw, w, nw, ne
case 'n':
{
center.incY();
if (line[i + 1] == 'e') {
center.incX();
}
i++;
}
break;
case 'e':
center.incX();
break;
case 's':
{
center.decY();
if (line[i + 1] == 'w') {
center.decX();
}
i++;
}
break;
case 'w':
center.decX();
break;
}
}
floor.toggle(center);
}
PRINTF(("PART_A: %d", floor.getBlack()));
for (int day = 0; day < 100; day++) {
floor.spread();
Floor oldFloor = floor;
for (int x = oldFloor.minX; x <= oldFloor.maxX; x++) {
for (int y = oldFloor.minY; y <= oldFloor.maxY; y++) {
int neighbours = 0;
if (oldFloor.getColor(Point<int>(x, y + 1)) == BLACK) neighbours++;
if (oldFloor.getColor(Point<int>(x + 1, y + 1)) == BLACK) neighbours++;
if (oldFloor.getColor(Point<int>(x + 1, y )) == BLACK) neighbours++;
if (oldFloor.getColor(Point<int>(x, y - 1)) == BLACK) neighbours++;
if (oldFloor.getColor(Point<int>(x - 1, y - 1)) == BLACK) neighbours++;
if (oldFloor.getColor(Point<int>(x - 1, y )) == BLACK) neighbours++;
if (oldFloor.getColor(Point<int>(x, y)) == BLACK) {
if (neighbours == 0 || neighbours > 2) {
floor.setColor(Point<int>(x, y), WHITE);
}
} else {
if (neighbours == 2) {
floor.setColor(Point<int>(x, y), BLACK);
}
}
}
}
}
PRINTF(("PART_B: %d", floor.getBlack()));
return 0;
}
| 18.337423
| 75
| 0.526932
|
bielskij
|
8692cf354b00f73644524d8b25e9052a004d8043
| 12,880
|
cpp
|
C++
|
temoto_action_assistant/src/ta_package_generator.cpp
|
temoto-framework/temoto_utils
|
208956e46a3d362a8db18c14ef0bcfc82bfb0b9a
|
[
"Apache-2.0"
] | null | null | null |
temoto_action_assistant/src/ta_package_generator.cpp
|
temoto-framework/temoto_utils
|
208956e46a3d362a8db18c14ef0bcfc82bfb0b9a
|
[
"Apache-2.0"
] | 1
|
2021-06-30T22:13:27.000Z
|
2021-06-30T22:13:27.000Z
|
temoto_action_assistant/src/ta_package_generator.cpp
|
temoto-telerobotics/temoto_utils
|
9492de31dbadeb7029e9746d55f934943acc3b99
|
[
"Apache-2.0"
] | null | null | null |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2019 TeMoto Telerobotics
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "temoto_action_assistant/ta_package_generator.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <set>
namespace temoto_action_assistant
{
ActionPackageGenerator::ActionPackageGenerator(const std::string& file_template_path)
: file_template_path_(file_template_path + "/")
, file_templates_loaded_(false)
{
if (file_template_path_.empty())
{
return;
}
// Import the CMakeLists template
t_cmakelists = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_cmakelists.xml");
// Import the package.xml template
t_packagexml = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_packagexml.xml");
// Import the action test templates
//t_testlaunch_standalone = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_action_test_standalone.xml");
t_testlaunch_separate = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_action_test_separate.xml");
t_umrf_graph = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_umrf_graphtxt.xml");
// Import the macros.h template
t_macros_header = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_macros_header.xml");
// Import the temoto_action.h template
t_bridge_header = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_bridge_header.xml");
t_bridge_header_elif = tp::TemplateContainer(file_template_path_ + "file_templates/temoto_ta_update_params_elif.xml");
// Import the action implementation c++ code templates
t_class_base = tp::TemplateContainer(file_template_path_ + "file_templates/ta_class_base.xml");
t_execute_action = tp::TemplateContainer(file_template_path_ + "file_templates/ta_execute_action.xml");
t_get_input_params = tp::TemplateContainer(file_template_path_ + "file_templates/ta_get_input_params.xml");
t_set_output_params = tp::TemplateContainer(file_template_path_ + "file_templates/ta_set_output_params.xml");
t_parameter_in = tp::TemplateContainer(file_template_path_ + "file_templates/ta_parameter_in.xml");
t_parameter_out = tp::TemplateContainer(file_template_path_ + "file_templates/ta_parameter_out.xml");
t_parameter_decl = tp::TemplateContainer(file_template_path_ + "file_templates/ta_parameter_decl.xml");
t_line_comment = tp::TemplateContainer(file_template_path_ + "file_templates/ta_line_comment.xml");
file_templates_loaded_ = true;
}
void ActionPackageGenerator::generatePackage(const UmrfNode& umrf, const std::string& package_path)
{
if (!file_templates_loaded_)
{
std::cout << "Could not generate a TeMoto action package because the file templates are not loaded" << std::endl;
return;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* CREATE AI PACKAGE DIRECTORY STRUCTURE
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// Get the name of the package
const std::string ta_package_name = umrf.getPackageName();
const std::string ta_dst_path = package_path + "/" + ta_package_name + "/";
// Create a package directory
boost::filesystem::create_directories(ta_dst_path + "/src");
boost::filesystem::create_directories(ta_dst_path + "/launch");
boost::filesystem::create_directories(ta_dst_path + "/test");
boost::filesystem::create_directories(ta_dst_path + "/include/" + ta_package_name);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GENERATE THE CONTENT
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Extract the necessary datastructures from the umrf
*/
std::string ta_class_name = umrf.getName();
/*
* Generate umrf.json
*/
std::ofstream umrf_json_file;
umrf_json_file.open (ta_dst_path + "/umrf.json");
umrf_json_file << umrf_json_converter::toUmrfJsonStr(umrf, true);
umrf_json_file.close();
/*
* Generate invoker umrf graph
*/
UmrfNode invoker_umrf = umrf;
invoker_umrf.getInputParametersNc().clear();
// Give input parameters some dummy values
for (auto& param_in : umrf.getInputParameters())
{
if (param_in.getType() == "string")
{
ActionParameters::ParameterContainer pc = param_in;
pc.setData(boost::any(std::string("MODIFY THIS FIELD")));
invoker_umrf.getInputParametersNc().setParameter(pc, true);
}
else if (param_in.getType() == "number")
{
ActionParameters::ParameterContainer pc = param_in;
pc.setData(boost::any(double(0.0)));
invoker_umrf.getInputParametersNc().setParameter(pc, true);
}
}
invoker_umrf.setSuffix(0);
UmrfGraph invoker_umrf_graph(ta_package_name, std::vector<UmrfNode>{invoker_umrf});
generateGraph(invoker_umrf_graph, ta_dst_path + "/test");
/*
* Generate CMakeLists.txt
*/
t_cmakelists.setArgument("ta_name", ta_package_name);
t_cmakelists.processAndSaveTemplate(ta_dst_path, "CMakeLists");
/*
* Generate package.xml
*/
t_packagexml.setArgument("ta_name", ta_package_name);
t_packagexml.processAndSaveTemplate(ta_dst_path, "package");
/*
* Generate the temoto_action header
*/
t_bridge_header.setArgument("ta_package_name", ta_package_name);
std::ofstream bridge_header_file;
bridge_header_file.open (ta_dst_path + "/include/" + ta_package_name + "/temoto_action.h");
bridge_header_file << t_bridge_header.processTemplate();
bridge_header_file.close();
/*
* Generate invoke_action.launch
*/
t_testlaunch_separate.setArgument("ta_package_name", ta_package_name);
t_testlaunch_separate.processAndSaveTemplate(ta_dst_path + "launch/", "invoke_action");
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Generate the action implementation c++ source file
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
std::string generated_content_cpp;
std::set<std::string> input_param_update_set;
/*
* Generate the "getInputParameters()" function
*/
std::string gen_content_get_input_params;
for (const auto& input_param : umrf.getInputParameters())
{
std::string parameter_name = "in_param_" + input_param.getName();
boost::replace_all(parameter_name, "::", "_");
t_parameter_in.setArgument("param_name", input_param.getName());
t_parameter_in.setArgument("param_name_us", parameter_name);
t_parameter_in.setArgument("param_type", input_param.getType());
t_bridge_header_elif.setArgument("param_type", input_param.getType());
if (action_parameter::PARAMETER_MAP.find(input_param.getType()) != action_parameter::PARAMETER_MAP.end())
{
t_parameter_in.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(input_param.getType()));
t_bridge_header_elif.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(input_param.getType()));
}
else
{
t_parameter_in.setArgument("param_type_us", input_param.getType());
t_bridge_header_elif.setArgument("param_type_us", input_param.getType());
}
gen_content_get_input_params += " " + t_parameter_in.processTemplate() + "\n";
input_param_update_set.insert(t_bridge_header_elif.processTemplate());
}
t_get_input_params.setArgument("function_body", gen_content_get_input_params);
/*
* Generate the "setOutputParameters()" function
*/
std::string gen_content_set_output_params;
for (const auto& output_param : umrf.getOutputParameters())
{
std::string parameter_name = "out_param_" + output_param.getName();
boost::replace_all(parameter_name, "::", "_");
t_parameter_out.setArgument("param_name_us", parameter_name);
t_parameter_out.setArgument("param_name", output_param.getName());
t_parameter_out.setArgument("param_type", output_param.getType());
// if (action_parameter::PARAMETER_MAP.find(output_param.getType()) != action_parameter::PARAMETER_MAP.end())
// {
// t_parameter_out.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(output_param.getType()));
// }
// else
// {
// t_parameter_out.setArgument("param_type_us", output_param.getType());
// }
gen_content_set_output_params += " " + t_parameter_out.processTemplate() + "\n";
}
t_set_output_params.setArgument("function_body", gen_content_set_output_params);
/*
* Declare input parameters
*/
std::string gen_content_input_param_decl;
if (!umrf.getInputParameters().empty())
{
t_line_comment.setArgument("comment", "Declaration of input parameters");
t_line_comment.setArgument("whitespace", "\n");
gen_content_input_param_decl += t_line_comment.processTemplate();
for (const auto& input_param : umrf.getInputParameters())
{
std::string parameter_name = "in_param_" + input_param.getName();
boost::replace_all(parameter_name, "::", "_");
t_parameter_decl.setArgument("param_name_us", parameter_name);
if (action_parameter::PARAMETER_MAP.find(input_param.getType()) != action_parameter::PARAMETER_MAP.end())
{
t_parameter_decl.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(input_param.getType()));
}
else
{
t_parameter_decl.setArgument("param_type_us", input_param.getType());
}
gen_content_input_param_decl += t_parameter_decl.processTemplate() + "\n";
}
}
/*
* Declare output parameters
*/
std::string gen_content_output_param_decl;
if (!umrf.getOutputParameters().empty())
{
t_line_comment.setArgument("comment", "Declaration of output parameters");
t_line_comment.setArgument("whitespace", "\n");
gen_content_output_param_decl += t_line_comment.processTemplate();
for (const auto& output_param : umrf.getOutputParameters())
{
std::string parameter_name = "out_param_" + output_param.getName();
boost::replace_all(parameter_name, "::", "_");
t_parameter_decl.setArgument("param_name_us", parameter_name);
if (action_parameter::PARAMETER_MAP.find(output_param.getType()) != action_parameter::PARAMETER_MAP.end())
{
t_parameter_decl.setArgument("param_type_us", action_parameter::PARAMETER_MAP.at(output_param.getType()));
}
else
{
t_parameter_decl.setArgument("param_type_us", output_param.getType());
}
gen_content_output_param_decl += t_parameter_decl.processTemplate() + "\n";
}
}
/*
* Put it all together and generate the whole class
*/
t_class_base.setArgument("ta_class_name", ta_class_name);
t_class_base.setArgument("ta_package_name", ta_package_name);
t_class_base.setArgument("fn_get_input_parameters", t_get_input_params.processTemplate());
t_class_base.setArgument("fn_set_output_parameters", t_set_output_params.processTemplate());
t_class_base.setArgument("fn_execute_action", t_execute_action.processTemplate());
t_class_base.setArgument("class_members", gen_content_input_param_decl + gen_content_output_param_decl);
/*
* Save the generated c++ content
*/
tp::saveStrToFile(t_class_base.processTemplate(), ta_dst_path + "/src", ta_package_name, ".cpp");
/*
* Generate the temoto_action header
*/
t_bridge_header.setArgument("ta_package_name", ta_package_name);
std::string elif_blocks;
for (const auto& elif_block : input_param_update_set)
{
elif_blocks += elif_block;
}
t_bridge_header.setArgument("update_parameters_content", elif_blocks);
tp::saveStrToFile(t_bridge_header.processTemplate(), ta_dst_path + "/include/" + ta_package_name, "temoto_action", ".h");
}
void ActionPackageGenerator::generateGraph(const UmrfGraph& umrf_graph, const std::string& graphs_path)
{
std::ofstream umrf_graph_json_file;
umrf_graph_json_file.open (graphs_path + "/" + umrf_graph.getName() + ".umrfg.json");
umrf_graph_json_file << umrf_json_converter::toUmrfGraphJsonStr(umrf_graph);
umrf_graph_json_file.close();
}
}// temoto_action_assistant namespace
| 41.548387
| 129
| 0.700233
|
temoto-framework
|
86950f91a7985ee46b02d1481306e0d3e26c72c8
| 921
|
cpp
|
C++
|
ex_12/principal.cpp
|
mihaioltean/poo
|
9c03eef52a0a03867af3e65f66f979b1ad702ccc
|
[
"MIT"
] | null | null | null |
ex_12/principal.cpp
|
mihaioltean/poo
|
9c03eef52a0a03867af3e65f66f979b1ad702ccc
|
[
"MIT"
] | null | null | null |
ex_12/principal.cpp
|
mihaioltean/poo
|
9c03eef52a0a03867af3e65f66f979b1ad702ccc
|
[
"MIT"
] | null | null | null |
// ConsoleApplication15.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "complex.h"
#include <stdio.h>
int main()
{
t_complex c1;
printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar());
t_complex c2(1, 2);
printf("real = %f, imaginar = %f\n", c2.get_real(), c2.get_imaginar());
c1.aduna(c2);
printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar());
c1.scade(c2);
printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar());
t_complex c3;
c3.set_real(4);
c3.set_imaginar(2);
c3.inmulteste(c2);
printf("real = %f, imaginar = %f\n", c3.get_real(), c3.get_imaginar());
c1.aduna(c2, c3);
printf("real = %f, imaginar = %f\n", c1.get_real(), c1.get_imaginar());
t_complex c4(c1);
printf("real = %f, imaginar = %f\n", c4.get_real(), c4.get_imaginar());
printf("modul = %f\n", c4.modul());
getchar();
}
| 22.463415
| 111
| 0.631922
|
mihaioltean
|
8695b55ae79442abf1e50bc76548f0d30957e7c1
| 5,288
|
cpp
|
C++
|
src/core/Log.cpp
|
ElmerDellson/deferred-shading-full
|
4ed351028fe13432327164a551f71fd368b933b7
|
[
"MIT"
] | null | null | null |
src/core/Log.cpp
|
ElmerDellson/deferred-shading-full
|
4ed351028fe13432327164a551f71fd368b933b7
|
[
"MIT"
] | null | null | null |
src/core/Log.cpp
|
ElmerDellson/deferred-shading-full
|
4ed351028fe13432327164a551f71fd368b933b7
|
[
"MIT"
] | null | null | null |
#include "config.hpp"
#include "Log.h"
#include <cstring>
#include <cstdio>
#include <sstream>
#include <string>
#include <iostream>
#include <thread>
#include <unordered_map>
#ifdef _WIN32
# include <Windows.h>
#endif
#include <mutex>
namespace Log {
#define RESULT_MAX_STRING_LENGTH 16384
FILE *logfile = nullptr;
void (* textout_func)(Type, const char *) = nullptr;
std::unordered_map<size_t, size_t> once_map;
size_t output_targets = LOG_OUT_STD | LOG_OUT_CUSTOM | LOG_OUT_FILE;
std::mutex fileMutex;
char log_result_string[RESULT_MAX_STRING_LENGTH];
bool logIncludeThreadID = false;
struct LogSettings {
Type type;
std::string prefix;
Verbosity verbosity;
Severity severity;
};
LogSettings logSettings[] = {
{ TYPE_SUCCESS , "Success: " , LOUD_UNSITUATED , OK },
{ TYPE_INFO , "" , LOUD_UNSITUATED , OK },
{ TYPE_NEUTRAL , "" , LOUD_UNSITUATED , OK },
{ TYPE_WARNING , "Warning: " , LOUD , OK },
{ TYPE_ERROR , "Error: " , LOUD , BAD },
{ TYPE_FILE , "" , LOUD_UNSITUATED , OK },
{ TYPE_ASSERT , "Assert: " , LOUD , BAD },
{ TYPE_PARAM , "Parameter error: " , LOUD , BAD },
{ TYPE_TRIVIA , "" , LOUD_UNSITUATED , OK }
};
/*----------------------------------------------------------------------------*/
void Init()
{
SetOutputTargets(output_targets);
}
/*----------------------------------------------------------------------------*/
void Destroy()
{
fileMutex.lock();
if (!logfile)
return;
fprintf(logfile, "\n === End of log === \n\n");
fflush(logfile);
fclose(logfile);
logfile = nullptr;
fileMutex.unlock();
}
/*----------------------------------------------------------------------------*/
void SetCustomOutputTargetFunc(void (* textout)(Type, const char *))
{
textout_func = textout;
}
/*----------------------------------------------------------------------------*/
void SetOutputTargets(size_t flags)
{
output_targets = flags;
if (flags & LOG_OUT_FILE) {
fileMutex.lock();
if (logfile == nullptr) {
// Lazily initiate file
logfile = fopen("log.txt", "w");
fprintf(logfile, "\n === Log (%s, %s) === \n\n", __DATE__, __TIME__);
fflush(logfile);
}
fileMutex.unlock();
}
}
/*----------------------------------------------------------------------------*/
void SetVerbosity(Type type, Verbosity verbosity)
{
logSettings[size_t(type)].verbosity = verbosity;
}
/*----------------------------------------------------------------------------*/
void SetIncludeThreadID(bool inc)
{
logIncludeThreadID = inc;
}
/*----------------------------------------------------------------------------*/
void Report(
unsigned int flags,
const char *file,
const char *function,
int line,
Type type,
const char *str,
...
)
{
if (output_targets == 0)
return;
size_t t = size_t(type);
#ifndef LOG_WHISPERS
if (logSettings[t].verbosity == Verbosity::WHISPER)
return;
#endif
size_t len;
va_list args;
va_start(args, str);
vsnprintf(log_result_string, RESULT_MAX_STRING_LENGTH - 1, str, args);
va_end(args);
len = strlen(log_result_string);
if (len >= (RESULT_MAX_STRING_LENGTH - 1))
strcat(&log_result_string[RESULT_MAX_STRING_LENGTH - 5], "...");
if (flags != 0) {
std::ostringstream os;
if ((flags & LOG_MESSAGE_ONCE_FLAG) != 0)
os << file << function << std::to_string(line) << log_result_string;
if ((type & LOG_LOCATION_ONCE_FLAG) != 0)
os << "_Loc" << file << function << std::to_string(line);
std::hash<std::string> hash_func;
size_t hash = hash_func(os.str());
auto elem = once_map.find(hash);
if (elem != once_map.end()) {
elem->second++; // Count the number of hits
return;
}
once_map[hash] = 1;
}
std::ostringstream os;
if (logIncludeThreadID) {
std::thread::id tid = std::this_thread::get_id();
os << "{" << tid << "} ";
}
if (logSettings[t].verbosity == LOUD) {
if (line == -1)
os << "[Unknown location]" << std::endl;
else
os << "[" << file << ", " << function << " (" << std::to_string(line) << ")]" << std::endl;
}
os << logSettings[t].prefix << log_result_string << std::endl;
if (output_targets & LOG_OUT_STD) {
#if defined(_WIN32)
auto const widened_string = utils::widen(os.str());
fwprintf(logSettings[t].severity != Severity::OK ? stderr : stdout, L"%s", widened_string.c_str());
#else
fprintf(logSettings[t].severity != Severity::OK ? stderr : stdout, "%s", os.str().c_str());
#endif
}
if (output_targets & LOG_OUT_FILE) {
fileMutex.lock();
fprintf(logfile, "%s", os.str().c_str());
fflush(logfile);
fileMutex.unlock();
}
if (output_targets & LOG_OUT_CUSTOM && textout_func != nullptr)
textout_func(type, os.str().c_str());
#ifdef _WIN32
if (logSettings[t].severity != Severity::OK && IsDebuggerPresent())
__debugbreak();
#endif
if (logSettings[t].severity == Severity::TERMINAL) {
Destroy();
exit(1); // TODO: Proper deconstruction
}
}
/*----------------------------------------------------------------------------*/
bool ReportParam(
unsigned int test,
const char *file,
const char *function,
int line
)
{
bool t = test != 0;
if (!t) Report(0, file, function, line, Type::TYPE_PARAM, "Bad parameter!");
return t;
}
/*----------------------------------------------------------------------------*/
};
| 25.669903
| 101
| 0.559191
|
ElmerDellson
|
8695dbf74fe9a4aa6113a3ddb2ffb2d1c86f0238
| 2,025
|
cpp
|
C++
|
bin/libs/systemc-2.3.1/src/sysc/kernel/sc_main.cpp
|
buaawj/Research
|
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
|
[
"OML"
] | 9
|
2019-07-15T10:05:29.000Z
|
2022-03-14T12:55:19.000Z
|
bin/libs/systemc-2.3.1/src/sysc/kernel/sc_main.cpp
|
buaawj/Research
|
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
|
[
"OML"
] | 2
|
2019-11-30T23:27:47.000Z
|
2021-11-02T12:01:05.000Z
|
systemc-2.3.1/src/sysc/kernel/sc_main.cpp
|
tianzhuqiao/bsmedit
|
3e443ed6db7b44b3b0da0e4bc024b65dcfe8e7a4
|
[
"MIT"
] | null | null | null |
/*****************************************************************************
The following code is derived, directly or indirectly, from the SystemC
source code Copyright (c) 1996-2014 by all Contributors.
All Rights reserved.
The contents of this file are subject to the restrictions and limitations
set forth in the SystemC Open Source License (the "License");
You may not use this file except in compliance with such restrictions and
limitations. You may obtain instructions on how to receive a copy of the
License at http://www.accellera.org/. Software distributed by Contributors
under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
ANY KIND, either express or implied. See the License for the specific
language governing rights and limitations under the License.
*****************************************************************************/
/*****************************************************************************
sc_main.cpp - Wrapper around user's toplevel routine `sc_main'.
Original Author: Stan Y. Liao, Synopsys, Inc.
CHANGE LOG APPEARS AT THE END OF THE FILE
*****************************************************************************/
#include "sysc/kernel/sc_cmnhdr.h"
#include "sysc/kernel/sc_externs.h"
int
main( int argc, char* argv[] )
{
return sc_core::sc_elab_and_sim( argc, argv );
}
// $Log: sc_main.cpp,v $
// Revision 1.5 2011/08/26 20:46:09 acg
// Andy Goodrich: moved the modification log to the end of the file to
// eliminate source line number skew when check-ins are done.
//
// Revision 1.4 2011/02/18 20:27:14 acg
// Andy Goodrich: Updated Copyrights.
//
// Revision 1.3 2011/02/13 21:47:37 acg
// Andy Goodrich: update copyright notice.
//
// Revision 1.2 2008/05/22 17:06:25 acg
// Andy Goodrich: updated copyright notice to include 2008.
//
// Revision 1.1.1.1 2006/12/15 20:20:05 acg
// SystemC 2.3
//
// Revision 1.3 2006/01/13 18:44:29 acg
// Added $Log to record CVS changes into the source.
//
| 35.526316
| 79
| 0.614321
|
buaawj
|
8697a4bc2ddf75656c2d4f98a5b5280861daa1b2
| 1,796
|
cpp
|
C++
|
vulkan/source/QueryPool.cpp
|
mtezych/cpp
|
05c1b85eb89117a9b406f3f32470367937331614
|
[
"BSD-3-Clause"
] | null | null | null |
vulkan/source/QueryPool.cpp
|
mtezych/cpp
|
05c1b85eb89117a9b406f3f32470367937331614
|
[
"BSD-3-Clause"
] | null | null | null |
vulkan/source/QueryPool.cpp
|
mtezych/cpp
|
05c1b85eb89117a9b406f3f32470367937331614
|
[
"BSD-3-Clause"
] | 2
|
2019-12-21T00:31:17.000Z
|
2021-07-14T23:16:23.000Z
|
#include <vulkan/QueryPool.h>
#include <vulkan/Symbols.h>
#include <vulkan/Device.h>
namespace vk
{
QueryPool::CreateInfo::CreateInfo
(
const VkQueryType queryType, const uint32_t queryCount
):
createInfo
{
VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
nullptr,
0,
queryType, queryCount,
VkQueryPipelineStatisticFlags { 0 },
}
{
assert(queryType != VK_QUERY_TYPE_PIPELINE_STATISTICS);
}
QueryPool::CreateInfo::CreateInfo
(
const VkQueryType queryType, const uint32_t queryCount,
const VkQueryPipelineStatisticFlags pipelineStatistics
):
createInfo
{
VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
nullptr,
0,
queryType, queryCount,
pipelineStatistics,
}
{
assert(queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS);
}
QueryPool::QueryPool
(
const Device& device, const CreateInfo& createInfo
):
device { &device },
vkQueryPool { VK_NULL_HANDLE }
{
const auto result = device.vkCreateQueryPool
(
device.vkDevice, &createInfo.createInfo, nullptr, &vkQueryPool
);
assert(result == VK_SUCCESS);
}
QueryPool::~QueryPool ()
{
if (vkQueryPool != VK_NULL_HANDLE)
{
device->vkDestroyQueryPool(device->vkDevice, vkQueryPool, nullptr);
}
}
QueryPool::QueryPool (QueryPool&& queryPool)
:
device { queryPool.device },
vkQueryPool { queryPool.vkQueryPool }
{
queryPool.device = nullptr;
queryPool.vkQueryPool = VK_NULL_HANDLE;
}
QueryPool& QueryPool::operator = (QueryPool&& queryPool)
{
if (vkQueryPool != VK_NULL_HANDLE)
{
device->vkDestroyQueryPool(device->vkDevice, vkQueryPool, nullptr);
}
device = queryPool.device;
vkQueryPool = queryPool.vkQueryPool;
queryPool.device = nullptr;
queryPool.vkQueryPool = VK_NULL_HANDLE;
return *this;
}
}
| 20.179775
| 70
| 0.711581
|
mtezych
|
869d12cee80b66df20a9d0c75be4533dab9e912e
| 18,679
|
hpp
|
C++
|
orb/include/morbid/handle_request_body.hpp
|
felipealmeida/mORBid
|
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
|
[
"BSL-1.0"
] | 2
|
2018-01-31T07:06:23.000Z
|
2021-02-18T00:49:05.000Z
|
orb/include/morbid/handle_request_body.hpp
|
felipealmeida/mORBid
|
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
|
[
"BSL-1.0"
] | null | null | null |
orb/include/morbid/handle_request_body.hpp
|
felipealmeida/mORBid
|
3ebc133f9dbe8af1c5cfb39349a0fbf5c125229b
|
[
"BSL-1.0"
] | null | null | null |
/* (c) Copyright 2012 Felipe Magno de Almeida
*
* 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 MORBID_HANDLE_REQUEST_BODY_HPP
#define MORBID_HANDLE_REQUEST_BODY_HPP
#include <morbid/any.hpp>
#include <morbid/detail/max_args.hpp>
#include <morbid/primitive_types.hpp>
#include <morbid/type_tag.hpp>
#include <morbid/in_out_traits.hpp>
#include <morbid/arguments_traits.hpp>
#include <morbid/transforms.hpp>
#include <morbid/giop/grammars/arguments.hpp>
#include <morbid/giop/grammars/message_1_0.hpp>
#include <morbid/giop/grammars/reply_1_0.hpp>
#include <morbid/iiop/all.hpp>
#include <boost/fusion/include/fused.hpp>
#include <boost/fusion/include/as_vector.hpp>
#include <boost/fusion/include/make_vector.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/copy_if.hpp>
#include <boost/type_traits/is_fundamental.hpp>
namespace morbid {
namespace fusion = boost::fusion;
template <typename T>
struct create_argument_transform;
template <typename T>
struct create_argument_transform<type_tag::value_type_tag<T, type_tag::in_tag> >
{
typedef type_tag::value_type_tag<T, type_tag::in_tag> tagged;
BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename tagged::type> >));
typedef typename boost::add_reference<typename tagged::type>::type type;
typedef type result_type;
result_type operator()(result_type r) const { return r; }
};
template <typename T>
struct create_argument_transform<type_tag::value_type_tag<T, type_tag::out_tag> >
{
typedef type_tag::value_type_tag<T, type_tag::out_tag> tagged;
typedef typename tagged::type type;
typedef type result_type;
result_type operator()(result_type r) const { return r; }
};
template <typename T>
struct create_argument_transform<type_tag::value_type_tag<T, type_tag::inout_tag> >
{
typedef type_tag::value_type_tag<T, type_tag::inout_tag> tagged;
BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename tagged::type> >));
typedef typename boost::add_reference<typename tagged::type>::type type;
typedef type result_type;
result_type operator()(result_type r) const { return r; }
};
template <>
struct create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::in_tag> >
{
typedef const char* type;
typedef type result_type;
result_type operator()(std::string const& str) const
{
return str.c_str();
}
};
template <>
struct create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::out_tag> >
: create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::in_tag> >
{
};
template <>
struct create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::inout_tag> >
: create_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::in_tag> >
{
};
template <typename T>
struct reply_argument_transform;
template <typename T>
struct reply_argument_transform<type_tag::value_type_tag<T, type_tag::out_tag> >
{
typedef type_tag::value_type_tag<T, type_tag::in_tag> tagged;
typedef typename boost::add_reference<typename tagged::type>::type type;
typedef type result_type;
result_type operator()(result_type r) const { return r; }
};
template <typename T>
struct reply_argument_transform<type_tag::value_type_tag<T, type_tag::inout_tag> >
: reply_argument_transform<type_tag::value_type_tag<T, type_tag::out_tag> >
{
};
template <>
struct reply_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::out_tag> >
{
typedef std::string type;
typedef type result_type;
result_type operator()(const char* str) const
{
return str;
}
};
template <>
struct reply_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::inout_tag> >
: reply_argument_transform<type_tag::value_type_tag<morbid::string, type_tag::out_tag> >
{
};
template <typename T>
struct tag
{
};
template <typename ParseArguments, typename Condition, typename ResultLambda>
struct initialize_arguments
{
template <typename R>
struct result;
template <typename This, int I, typename S, typename T>
struct result<This(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>
{
typedef typename mpl::apply1<typename mpl::lambda<Condition>::type, T>::type condition;
typedef typename mpl::apply1<typename mpl::lambda<ResultLambda>::type, T>::type transform_result;
typedef typename mpl::if_
<condition
, std::pair<mpl::int_<I>
, fusion::cons
<transform_result, S> >
, std::pair<mpl::int_<I+1>
, fusion::cons
<transform_result, S> >
>::type type;
};
initialize_arguments(ParseArguments& parse_arguments)
: parse_arguments(parse_arguments)
{}
template <int I, typename S, typename T>
typename result<initialize_arguments<ParseArguments, Condition, ResultLambda>
(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type
call(std::pair<mpl::int_<I>, S>const& s, tag<T>const&, mpl::true_) const
{
BOOST_MPL_ASSERT((mpl::not_<boost::is_fundamental<T> >));
typedef typename mpl::apply1<typename mpl::lambda<ResultLambda>::type, T>::type type;
return std::pair<mpl::int_<I>, fusion::cons<type, S> >
(mpl::int_<I>(), fusion::cons<type, S>(type(), s.second));
}
template <int I, typename S, typename T>
typename result<initialize_arguments<ParseArguments, Condition, ResultLambda>
(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type
call(std::pair<mpl::int_<I>, S>const& s, tag<T>const&, mpl::false_) const
{
BOOST_MPL_ASSERT((mpl::not_<boost::is_fundamental<T> >));
typedef typename mpl::apply1<typename mpl::lambda<ResultLambda>::type, T>::type type;
typedef create_argument_transform<T> transform;
typedef fusion::result_of::at_c<ParseArguments, I> arg_type;
// BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename boost::remove_reference<arg_type>::type> >));
// BOOST_MPL_ASSERT((mpl::not_<boost::is_const<typename boost::remove_reference<typename transform::result_type>::type> >));
BOOST_MPL_ASSERT((boost::is_same<typename boost::result_of<transform(arg_type)>::type, type>));
return std::pair<mpl::int_<I+1>, fusion::cons<type, S> >
(mpl::int_<I+1>(), fusion::cons<type, S>
(transform()(fusion::at_c<I>(parse_arguments)), s.second));
}
template <int I, typename S, typename T>
typename result<initialize_arguments<ParseArguments, Condition, ResultLambda>
(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type
operator()(std::pair<mpl::int_<I>, S>const& s, tag<T>const& t) const
{
BOOST_MPL_ASSERT((mpl::not_<boost::is_fundamental<T> >));
typedef typename mpl::apply1<typename mpl::lambda<Condition>::type, T>::type condition;
return call(s, t, condition());
}
ParseArguments& parse_arguments;
};
template <typename ParseArguments>
struct reply_arguments_generator
{
template <typename R>
struct result;
template <typename This, int I, typename S, typename T>
struct result<This(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>
{
template <typename U>
struct create_pair
{
typedef std::pair<mpl::int_<I+1>, fusion::cons<typename reply_argument_transform<U>::type, S> > type;
};
typedef type_tag::is_not_in_type_tag<T> is_not_in;
typedef typename mpl::eval_if
<is_not_in
, create_pair<T>
, mpl::identity<std::pair<mpl::int_<I>, S> >
>::type
type;
};
reply_arguments_generator(ParseArguments& parse_arguments)
: parse_arguments(parse_arguments)
{}
template <int I, typename S, typename T>
typename result<reply_arguments_generator<ParseArguments>(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type
call(std::pair<mpl::int_<I>, S> const& s, tag<T>const&, type_tag::in_tag) const
{
return s;
}
template <int I, typename S, typename T, typename Tag>
typename result<reply_arguments_generator<ParseArguments>(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type
call(std::pair<mpl::int_<I>, S> const& s, tag<T>const&, Tag) const
{
typedef reply_argument_transform<T> transform;
typedef typename transform::type type;
return std::pair<mpl::int_<I+1>, fusion::cons<type, S> >
(mpl::int_<I+1>(), fusion::cons<type, S>(transform()(fusion::at_c<I>(parse_arguments)), s.second));
}
template <int I, typename S, typename T>
typename result<reply_arguments_generator<ParseArguments>(std::pair<mpl::int_<I>, S>const&, tag<T>const&)>::type
operator()(std::pair<mpl::int_<I>, S> const& s, tag<T>const& t) const
{
return call(s, t, typename T::tag());
}
ParseArguments& parse_arguments;
};
template <typename NotInParams, typename ReplyArguments>
void make_request_reply(reply& r, ReplyArguments& reply_arguments)
{
std::cout << "Generating reply with reply arguments " << typeid(ReplyArguments).name() << std::endl;
typedef ReplyArguments reply_argument_types;
typedef giop::forward_back_insert_iterator<std::vector<char> > output_iterator_type;
typedef std::vector<fusion::vector2<unsigned int, std::vector<char> > > service_context_list;
typedef fusion::vector4<service_context_list
, unsigned int, unsigned int
, typename reply_argument_types::second_type>
reply_attribute_type;
typedef fusion::vector1<fusion::vector1<reply_attribute_type> >
message_reply_attribute_type;
typedef giop::grammars::arguments<iiop::generator_domain
, output_iterator_type, NotInParams
, typename reply_argument_types::second_type>
arguments_grammar;
typedef giop::grammars::reply_1_0<iiop::generator_domain
, output_iterator_type, reply_attribute_type>
reply_grammar;
typedef giop::grammars::message_1_0<iiop::generator_domain
, output_iterator_type, message_reply_attribute_type
, 1u /* reply */>
message_reply_grammar;
morbid::arguments_traits arguments_traits;
arguments_grammar arguments_grammar_(arguments_traits);
reply_grammar reply_grammar_(arguments_grammar_);
message_reply_grammar message_grammar_(reply_grammar_);
service_context_list l;
message_reply_attribute_type message_attribute
(fusion::make_vector
(reply_attribute_type
(l
, r.request_id
, 0u /* NO_EXCEPTION */
, reply_arguments.second)));
output_iterator_type iterator(r.reply_body);
namespace karma = boost::spirit::karma;
if(karma::generate(iterator, giop::compile<iiop::generator_domain>
(message_grammar_(giop::native_endian))
, message_attribute))
{
std::cout << "reply generated" << std::endl;
}
else
{
std::cout << "Failed generating reply" << std::endl;
throw morbid::MARSHALL();
}
}
template <typename R, typename SeqParam, typename F, typename T, typename Args>
void handle_request_reply(F f, T* self, reply& r, Args& args, mpl::identity<void>)
{
fusion::single_view<T*> self_view(self);
fusion::joint_view<fusion::single_view<T*> const, Args> new_args(self_view, args);
f(new_args);
typedef Args argument_types;
typedef typename mpl::lambda<type_tag::is_not_in_type_tag<mpl::_1> >::type is_not_in_lambda;
typedef typename mpl::copy_if<SeqParam, is_not_in_lambda>::type not_in_params;
typedef typename mpl::transform<SeqParam, create_argument_transform<mpl::_1> >::type mpl_argument_types;
typedef typename mpl::transform<SeqParam, tag<mpl::_1> >::type mpl_identity_argument_types;
typedef typename fusion::result_of::as_vector<mpl_identity_argument_types>::type identity_argument_types;
identity_argument_types const identity_arguments;
typedef typename boost::remove_reference<
typename fusion::result_of::fold<identity_argument_types const, std::pair<mpl::int_<0>, fusion::nil>
, reply_arguments_generator<argument_types> >::type
>::type
reply_argument_types;
std::cout << "reply_argument_types " << typeid(reply_argument_types).name() << std::endl;
reply_argument_types reply_arguments = fusion::fold(identity_arguments, std::pair<mpl::int_<0>, fusion::nil>()
, reply_arguments_generator<argument_types>(args));
make_request_reply<not_in_params>(r, reply_arguments);
}
template <typename R, typename SeqParam, typename F, typename T, typename Args>
void handle_request_reply(F f, T* self, reply& r, Args& args, mpl::identity<R>)
{
fusion::single_view<T*> self_view(self);
fusion::joint_view<fusion::single_view<T*> const, Args> new_args(self_view, args);
typename return_traits<R>::type result = f(new_args);
typedef Args argument_types;
typedef type_tag::value_type_tag<R, type_tag::out_tag> result_tag;
typedef typename mpl::push_front<SeqParam, result_tag>::type sequence_params;
typedef typename mpl::lambda<type_tag::is_not_in_type_tag<mpl::_1> >::type is_not_in_lambda;
typedef typename mpl::copy_if<sequence_params, is_not_in_lambda>::type not_in_params;
typedef typename mpl::transform<sequence_params, create_argument_transform<mpl::_1> >::type mpl_argument_types;
typedef typename mpl::transform<sequence_params, tag<mpl::_1> >::type mpl_identity_argument_types;
typedef typename fusion::result_of::as_vector<mpl_identity_argument_types>::type identity_argument_types;
identity_argument_types const identity_arguments;
typedef fusion::cons<typename return_traits<R>::type, argument_types> args_with_result_type;
typedef typename boost::remove_reference<
typename fusion::result_of::fold<identity_argument_types const, std::pair<mpl::int_<0>, fusion::nil>
, reply_arguments_generator<args_with_result_type> >::type
>::type
reply_argument_types;
std::cout << "reply_argument_types " << typeid(reply_argument_types).name() << std::endl;
args_with_result_type args_with_result(result, args);
reply_argument_types reply_arguments = fusion::fold(identity_arguments, std::pair<mpl::int_<0>, fusion::nil>()
, reply_arguments_generator
<args_with_result_type>
(args_with_result));
make_request_reply<not_in_params>(r, reply_arguments);
}
template <typename R, typename SeqParam, typename T, typename F>
void handle_request_body(T* self, F f, std::size_t align_offset
, const char* rq_first, const char* rq_last
, bool little_endian, reply& r)
{
std::cout << "handle_request_body " << typeid(f).name() << " align_offset " << align_offset << std::endl;
typedef typename mpl::lambda<type_tag::is_not_out_type_tag<mpl::_1> >::type
is_not_out_lambda;
typedef typename mpl::copy_if<SeqParam, is_not_out_lambda>::type not_out_params;
typedef typename mpl::transform
<not_out_params, transforms::from_unmanaged_to_managed<mpl::_1> >::type
mpl_parse_argument_types;
typedef typename fusion::result_of::as_vector<mpl_parse_argument_types>::type
parse_argument_types;
parse_argument_types parse_arguments;
morbid::arguments_traits arguments_traits;
typedef giop::grammars::arguments<iiop::parser_domain
, const char*, not_out_params
, parse_argument_types>
arguments_grammar;
arguments_grammar arguments_grammar_(arguments_traits);
namespace qi = boost::spirit::qi;
if(qi::parse(rq_first, rq_last
, giop::compile<iiop::parser_domain>
(iiop::aligned(align_offset)[arguments_grammar_(giop::endian(little_endian))])
, parse_arguments))
{
std::cout << "Parsed arguments correctly " << typeid(parse_arguments).name() << std::endl;
std::cout << "Arguments parsed " << parse_arguments << std::endl;
std::cout << "handle_request_body not_out_params " << typeid(parse_argument_types).name() << std::endl;
typedef typename mpl::transform<SeqParam, create_argument_transform<mpl::_1> >::type mpl_argument_types;
typedef typename mpl::transform<SeqParam, tag<mpl::_1> >::type mpl_identity_argument_types;
typedef typename fusion::result_of::as_vector<mpl_identity_argument_types>::type identity_argument_types;
identity_argument_types const identity_arguments;
typedef typename boost::remove_reference<
typename fusion::result_of::fold
<identity_argument_types const
, std::pair<mpl::int_<0>, fusion::nil>
, initialize_arguments
<parse_argument_types
, type_tag::is_out_type_tag<mpl::_>
,
mpl::if_
<
mpl::and_
<type_tag::is_not_out_type_tag<mpl::_1>
, mpl::not_<boost::is_same
<mpl::_1, type_tag::value_type_tag<morbid::string, type_tag::in_tag> >
>
>
, boost::add_reference<type_tag::value_type<mpl::_1> >
, boost::remove_reference<type_tag::value_type<mpl::_1> >
>
> >::type
>::type
argument_types;
std::cout << "handle_request_body not_out_params " << typeid(identity_argument_types).name() << std::endl;
std::cout << "handle_request_body not_out_params " << typeid(argument_types).name() << std::endl;
std::pair<mpl::int_<0>, fusion::nil> const pair;
argument_types arguments = fusion::fold
(identity_arguments, pair, initialize_arguments
<parse_argument_types
// Default construct out types
, type_tag::is_out_type_tag<mpl::_>
// Add reference to not out types (to avoid copying)
,
mpl::if_
<
mpl::and_
<type_tag::is_not_out_type_tag<mpl::_1>
, mpl::not_<boost::is_same
<mpl::_1, type_tag::value_type_tag<morbid::string, type_tag::in_tag> >
>
>
, boost::add_reference<type_tag::value_type<mpl::_1> >
, boost::remove_reference<type_tag::value_type<mpl::_1> >
>
>
(parse_arguments));
// Calling function with arguments
fusion::fused<F> fused(f);
// Create reply
handle_request_reply<R, SeqParam>(fused, self, r, arguments.second
, mpl::identity<R>());
}
else
{
throw morbid::MARSHALL();
}
}
}
#endif
| 38.198364
| 128
| 0.693506
|
felipealmeida
|
869f10223b79d175e5bdc5e96de65f67f7c57dfe
| 2,050
|
cpp
|
C++
|
week 1/Arrays/10First_Repeating_Element.cpp
|
arpit456jain/gfg-11-Weeks-Workshop-on-DSA-in-CPP
|
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
|
[
"MIT"
] | 6
|
2021-08-06T14:36:41.000Z
|
2022-03-22T11:22:07.000Z
|
week 1/Arrays/10First_Repeating_Element.cpp
|
arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP
|
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
|
[
"MIT"
] | 1
|
2021-08-09T05:09:48.000Z
|
2021-08-09T05:09:48.000Z
|
week 1/Arrays/10First_Repeating_Element.cpp
|
arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP
|
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
|
[
"MIT"
] | 1
|
2021-08-09T14:25:17.000Z
|
2021-08-09T14:25:17.000Z
|
// Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest.
// Input:
// n = 7
// arr[] = {1, 5, 3, 4, 3, 5, 6}
// Output: 2
// Explanation:
// 5 is appearing twice and
// its first appearence is at index 2
// which is less than 3 whose first
// occuring index is 3.
#include<bits/stdc++.h>
using namespace std;
class Solution{
public:
int optimizeApproch(int arr[],int n)
{
// T.C : O(N)
// logic is i will take a another array and will store position of 1st occurence at that number
vector<int> arr2(1000000,0);
int min=-1;
for(int i = 0; i < n; i++)
{
if(arr2[arr[i]]==0)
arr2[arr[i]] = i+1; // inserting index of 1st occurence of element at that number
else
{
// min = arr2[arr[i]];
if(min == -1)
min = arr2[arr[i]];
else
{
if(arr2[arr[i]]<=min)
min = arr2[arr[i]];
}
}
// cout<<min<<"\n";
}
return min;
}
int naiveApproch(int arr[],int n)
{
// T.C : O(n*n)
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i] == arr[j])
return i+1;
}
}
}
//Function to return the position of the first repeating element.
int firstRepeated(int arr[], int n) {
//code here
// int res = naiveApproch(arr,n);
int res = optimizeApproch(arr,n);
return res;
}
};
// { Driver Code Starts.
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int arr[n];
for(int i = 0 ; i < n ; ++ i )
cin >> arr[i] ;
Solution ob;
cout << ob.firstRepeated(arr,n) << "\n";
}
return 0;
}
// } Driver Code Ends
| 24.698795
| 171
| 0.46
|
arpit456jain
|
869fbf4e6e0ec99cada0c4b1137a78c2d16fe019
| 3,070
|
cpp
|
C++
|
trainings/2015-07-25-Multi-University-2015-1 /F.cpp
|
HcPlu/acm-icpc
|
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
|
[
"MIT"
] | 9
|
2017-10-07T13:35:45.000Z
|
2021-06-07T17:36:55.000Z
|
trainings/2015-07-25-Multi-University-2015-1 /F.cpp
|
zhijian-liu/acm-icpc
|
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
|
[
"MIT"
] | null | null | null |
trainings/2015-07-25-Multi-University-2015-1 /F.cpp
|
zhijian-liu/acm-icpc
|
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
|
[
"MIT"
] | 3
|
2018-04-24T05:27:21.000Z
|
2019-04-25T06:06:00.000Z
|
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 222222;
int n, m;
vector<int> adj[N];
int height[N], parent[N], dist[N], dp[N];
int father[N][20];
vector<pair<pair<int, int>, int> > chain[N];
int jump(int x, int k) {
for (int i = 0; i < 20; ++i) {
if (k >> i & 1) {
x = father[x][i];
}
}
return x;
}
int lca(int x, int y) {
if (height[x] < height[y]) {
swap(x, y);
}
x = jump(x, height[x] - height[y]);
if (x == y) {
return x;
}
for (int i = 19; i >= 0; --i) {
if (father[x][i] != father[y][i]) {
x = father[x][i];
y = father[y][i];
}
}
return father[x][0];
}
int find(int x) {
if (parent[x] != x) {
int root = find(parent[x]);
dist[x] += dist[parent[x]];
return parent[x] = root;
} else {
return x;
}
}
void mergy(int x, int y, int w) {
x = find(x);
y = find(y);
parent[x] = y;
dist[x] = w;
}
void solve(void) {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
adj[i].clear();
chain[i].clear();
}
for (int i = 1; i < n; ++i) {
int x, y;
scanf("%d%d", &x, &y);
adj[x].push_back(y);
adj[y].push_back(x);
}
vector<int> queue;
height[1] = 0;
father[1][0] = 0;
queue.push_back(1);
for (int head = 0; head < (int)queue.size(); ++head) {
int x = queue[head];
for (int i = 0; i < (int)adj[x].size(); ++i) {
int y = adj[x][i];
if (y == father[x][0]) {
continue;
}
height[y] = height[x] + 1;
father[y][0] = x;
queue.push_back(y);
}
}
for (int j = 1; j < 20; ++j) {
for (int i = 1; i <= n; ++i) {
father[i][j] = father[father[i][j - 1]][j - 1];
}
}
for (int i = 1; i <= m; ++i) {
int x, y, w;
scanf("%d%d%d", &x, &y, &w);
chain[lca(x, y)].push_back(make_pair(make_pair(x, y), w));
}
for (int i = 1; i <= n; ++i) {
parent[i] = i;
dist[i] = 0;
}
for (int head = n - 1; head >= 0; --head) {
int x = queue[head];
int sum = 0;
for (int i = 0; i < (int)adj[x].size(); ++i) {
int y = adj[x][i];
if (y == father[x][0]) {
continue;
}
sum += dp[y];
}
dp[x] = sum;
for (int i = 0; i < (int)chain[x].size(); ++i) {
int a = chain[x][i].first.first;
int b = chain[x][i].first.second;
int son1 = jump(a, height[a] - height[x] - 1);
int son2 = jump(b, height[b] - height[x] - 1);
find(a);
find(b);
dp[x] = max(dp[x], chain[x][i].second + sum + dist[a] + dist[b]);
}
mergy(x, father[x][0], sum - dp[x]);
}
printf("%d\n", dp[1]);
}
int main(void) {
int tests;
for (scanf("%d", &tests); tests--; solve()) {
}
}
| 21.928571
| 77
| 0.400977
|
HcPlu
|
86a1de77dee7fd33df55aee618ae8d1601b75d41
| 191
|
cpp
|
C++
|
regression/esbmc-cpp/cbmc/Templates14/main.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 143
|
2015-06-22T12:30:01.000Z
|
2022-03-21T08:41:17.000Z
|
regression/esbmc-cpp/cbmc/Templates14/main.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 542
|
2017-06-02T13:46:26.000Z
|
2022-03-31T16:35:17.000Z
|
regression/esbmc-cpp/cbmc/Templates14/main.cpp
|
shmarovfedor/esbmc
|
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
|
[
"BSD-3-Clause"
] | 81
|
2015-10-21T22:21:59.000Z
|
2022-03-24T14:07:55.000Z
|
#include<cassert>
namespace n1
{
template <class S>
struct A{
S a;
};
}
template <class T>
struct B{
n1::A<T> b;
};
int main()
{
B<bool> o;
o.b.a = true;
assert(o.b.a==true);
};
| 8.681818
| 22
| 0.560209
|
shmarovfedor
|
86a62e1bbf39a71c8842b26242f5954e67788ccd
| 505
|
cpp
|
C++
|
test/TestCell.cpp
|
samsparks/climaze
|
a49dc0a926f86311212a61e837ebb46e2a387fe2
|
[
"MIT"
] | null | null | null |
test/TestCell.cpp
|
samsparks/climaze
|
a49dc0a926f86311212a61e837ebb46e2a387fe2
|
[
"MIT"
] | null | null | null |
test/TestCell.cpp
|
samsparks/climaze
|
a49dc0a926f86311212a61e837ebb46e2a387fe2
|
[
"MIT"
] | null | null | null |
#include <boost/test/unit_test.hpp>
#include "Cell.hpp"
BOOST_AUTO_TEST_SUITE(TestCell)
BOOST_AUTO_TEST_CASE( Initialization )
{
Cell c;
BOOST_CHECK_EQUAL( c.Visited(), false );
BOOST_CHECK_EQUAL( c.Opened(), false );
}
BOOST_AUTO_TEST_CASE( Accessors )
{
Cell c;
BOOST_CHECK_EQUAL( c.Visited(), false );
BOOST_CHECK_EQUAL( c.Visit().Visited(), true );
BOOST_CHECK_EQUAL( c.Opened(), false );
BOOST_CHECK_EQUAL( c.Open().Opened(), true );
}
BOOST_AUTO_TEST_SUITE_END()
| 21.956522
| 51
| 0.69901
|
samsparks
|
86a696f79263c4449c62684bb7931f717285dd35
| 3,711
|
cpp
|
C++
|
src/game/cmd/LsPlayers.cpp
|
jumptohistory/jaymod
|
92d0a0334ac27da94b12280b0b42b615b8813c23
|
[
"Apache-2.0"
] | 25
|
2016-05-27T11:53:58.000Z
|
2021-10-17T00:13:41.000Z
|
src/game/cmd/LsPlayers.cpp
|
jumptohistory/jaymod
|
92d0a0334ac27da94b12280b0b42b615b8813c23
|
[
"Apache-2.0"
] | 1
|
2016-07-09T05:25:03.000Z
|
2016-07-09T05:25:03.000Z
|
src/game/cmd/LsPlayers.cpp
|
jumptohistory/jaymod
|
92d0a0334ac27da94b12280b0b42b615b8813c23
|
[
"Apache-2.0"
] | 16
|
2016-05-28T23:06:50.000Z
|
2022-01-26T13:47:12.000Z
|
#include <bgame/impl.h>
namespace cmd {
///////////////////////////////////////////////////////////////////////////////
LsPlayers::LsPlayers()
: AbstractBuiltin( "lsplayers" )
{
__usage << xvalue( "!" + _name );
__descr << "Display all players connected, their client numbers and admin levels.";
}
///////////////////////////////////////////////////////////////////////////////
LsPlayers::~LsPlayers()
{
}
///////////////////////////////////////////////////////////////////////////////
AbstractCommand::PostAction
LsPlayers::doExecute( Context& txt )
{
if (txt._args.size() != 1)
return PA_USAGE;
// bail if nothing to display
if (level.numConnectedClients < 1) {
txt._ebuf << "There are no players online.";
return PA_ERROR;
}
InlineText colA = xheader;
InlineText colB = xheader;
InlineText colC = xheader;
InlineText colD = xheader;
InlineText colE = xheader;
InlineText colF = xheader;
InlineText colG = xheader;
InlineText colH = xheader;
InlineText colI = xheader;
colC.flags |= ios::left;
colD.flags |= ios::left;
colE.flags |= ios::left;
colF.flags |= ios::left;
colA.width = 2;
colB.width = 1;
colC.width = 1;
colD.width = 31;
colE.width = 15;
colF.width = 6;
colG.width = 6;
colH.width = 4;
colI.width = 2;
colB.prefixOutside = " ";
colD.prefixOutside = " ";
colE.prefixOutside = " ";
colF.prefixOutside = " ";
colG.prefixOutside = " ";
colH.prefixOutside = " ";
colI.prefixOutside = " ";
Buffer buf;
buf << colA( "##" )
<< colB( "C" )
<< colC( "M" )
<< colD( "NAME" )
<< colE( "LEVEL" )
<< colF( "TEAM" )
<< colG( "XP" )
<< colH( "PING" )
<< colI( "NC" )
<< '\n';
colA.color = xcnone;
colB.color = xcnone;
colC.color = xcnone;
colD.color = xcnone;
colE.color = xcnone;
colF.color = xcnone;
colG.color = xcnone;
colH.color = xcnone;
colI.color = xcnone;
string tmp;
for (int i = 0; i < MAX_CLIENTS; i++) {
User& user = *connectedUsers[i];
if (user == User::BAD)
continue;
Client& cobj = g_clientObjects[i];
string err;
Level& lev = levelDB.fetchByKey( user.authLevel, err );
gclient_t& client = level.clients[i];
buf << colA( i )
<< colB( (client.pers.connected == CON_CONNECTING ? 'C' : '-') )
<< colC( (user.muted ? 'M' : '-') )
<< colD( str::etAlignLeft( user.namex, colD.width, tmp ));
if (lev.namex.empty())
buf << colE( lev.level );
else
buf << colE( str::etAlignLeft( lev.namex, colE.width, tmp ));
switch (client.sess.sessionTeam) {
case TEAM_ALLIES:
colF.color = xcblue;
buf << colF( "allies" );
break;
case TEAM_AXIS:
colF.color = xcred;
buf << colF( "axis" );
break;
case TEAM_SPECTATOR:
default:
colF.color = xcyellow;
buf << colF( "spec" );
break;
}
// FIELD: XP
float xp = 0.0f;
for (int si = 0; si < SK_NUM_SKILLS; si++)
xp += client.sess.skillpoints[si];
buf << colG( int(xp) )
<< colH( client.ps.ping )
<< colI( cobj.numNameChanges > 99 ? 99 : cobj.numNameChanges )
<< '\n';
}
print( txt._client, buf );
return PA_NONE;
}
///////////////////////////////////////////////////////////////////////////////
} // namespace cmd
| 25.244898
| 87
| 0.466451
|
jumptohistory
|
86ab04821b716af2f4d5e29a2f3d8159b6f8e943
| 1,255
|
cc
|
C++
|
src/constants.cc
|
IoanaIleana/SigmodContest
|
589bc86deecea953b40c2ce07759d35e397bd9c8
|
[
"MIT"
] | null | null | null |
src/constants.cc
|
IoanaIleana/SigmodContest
|
589bc86deecea953b40c2ce07759d35e397bd9c8
|
[
"MIT"
] | null | null | null |
src/constants.cc
|
IoanaIleana/SigmodContest
|
589bc86deecea953b40c2ce07759d35e397bd9c8
|
[
"MIT"
] | null | null | null |
#include <sys/types.h>
#include <stdint.h>
#include "constants.h"
uint64_t one64 = (uint64_t)1;
uint64_t zero64 = (uint64_t)0;
uint64_t max64 = ~zero64;
uint64_t mod64mask=(uint64_t)63;
uint64_t masks64[(int)64] = {
one64<<(int)0, one64<<(int)1, one64<<(int)2, one64<<(int)3, one64<<(int)4, one64<<(int)5, one64<<(int)6, one64<<(int)7,
one64<<(int)8, one64<<(int)9, one64<<(int)10, one64<<(int)11, one64<<(int)12, one64<<(int)13, one64<<(int)14, one64<<(int)15,
one64<<(int)16, one64<<(int)17, one64<<(int)18, one64<<(int)19, one64<<(int)20, one64<<(int)21, one64<<(int)22, one64<<(int)23,
one64<<(int)24, one64<<(int)25, one64<<(int)26, one64<<(int)27, one64<<(int)28, one64<<(int)29, one64<<(int)30, one64<<(int)31,
one64<<(int)32, one64<<(int)33, one64<<(int)34, one64<<(int)35, one64<<(int)36, one64<<(int)37, one64<<(int)38, one64<<(int)39,
one64<<(int)40, one64<<(int)41, one64<<(int)42, one64<<(int)43, one64<<(int)44, one64<<(int)45, one64<<(int)46, one64<<(int)47,
one64<<(int)48, one64<<(int)49, one64<<(int)50, one64<<(int)51, one64<<(int)52, one64<<(int)53, one64<<(int)54, one64<<(int)55,
one64<<(int)56, one64<<(int)57, one64<<(int)58, one64<<(int)59, one64<<(int)60, one64<<(int)61, one64<<(int)62, one64<<(int)63
};
| 54.565217
| 129
| 0.627888
|
IoanaIleana
|
86bd7fc0594dfde72fb9d711ca70b6741b599ffe
| 3,199
|
cpp
|
C++
|
src/basegui/TextViewControllerImplementor.cpp
|
0of/WebOS-Magna
|
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
|
[
"Apache-2.0"
] | 1
|
2016-03-26T13:25:08.000Z
|
2016-03-26T13:25:08.000Z
|
src/basegui/TextViewControllerImplementor.cpp
|
0of/WebOS-Magna
|
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
|
[
"Apache-2.0"
] | null | null | null |
src/basegui/TextViewControllerImplementor.cpp
|
0of/WebOS-Magna
|
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
|
[
"Apache-2.0"
] | null | null | null |
#include "TextViewControllerImplementor.h"
#include "TextViewController.h"
#include "qt_glue/FontMetrics.h"
using namespace Magna::Glue;
namespace Magna{
namespace GUI{
TextViewControllerImplementor::TextViewControllerImplementor( TextViewController & binding )
:m_textBoundingRect()
,m_binding( binding )
,m_avgHeight( 0 )
,m_lineBreakStrings()
,m_vtextSpacing(0)
,m_text(){
_remeasureText();
}
TextViewControllerImplementor::TextViewControllerImplementor( TextViewController & binding , const String& text )
:m_textBoundingRect()
,m_binding( binding )
,m_avgHeight( 0 )
,m_lineBreakStrings()
,m_vtextSpacing(0)
,m_text( text ){
_remeasureText();
}
TextViewControllerImplementor::~TextViewControllerImplementor(){
}
void TextViewControllerImplementor::rendering( RenderingEventArgs& eventArgs ){
if( eventArgs.isAccepted() ){
auto *_2d_manager = eventArgs.getRenderManager2D();
if( _2d_manager != Nullptr ){
Canvas2DDrawer _drawer;
if( _2d_manager->retrieveDrawer( _drawer ) != false ){
//normal state
_drawer.clearRectRegion( eventArgs.getRenderingRectRegion() );
_drawer.setFont( m_binding.getFont() );
auto _each_x = m_textBoundingRect.getBottomLeftCoord().getX();
auto _each_y = m_textBoundingRect.getBottomLeftCoord().getY();
for( auto _iter = m_lineBreakStrings.begin(); _iter != m_lineBreakStrings.end(); ++_iter ){
_each_y += m_avgHeight;
_drawer.drawText( IntegerDyadCoordinate(_each_x, _each_y ), *_iter );
_each_y += m_vtextSpacing;
}
_2d_manager->pullbackDrawer( _drawer );
}
}
}
}
void TextViewControllerImplementor::_remeasureText(){
//get split strings
m_lineBreakStrings = m_text.split( L"\\n" );
FontMetrics _metrics = FontMetrics( m_binding.getFont() );
IntegerSize _boundingTextSize;
for( auto _iter = m_lineBreakStrings.begin(); _iter != m_lineBreakStrings.end(); ++_iter ){
_metrics.setMetricsText( *_iter );
const auto &_each_size = _metrics.measureSize();
m_avgHeight += _each_size.getHeight();
_boundingTextSize.joinedBy( _each_size );
}
//get average height
m_avgHeight /= m_lineBreakStrings.size();
m_textBoundingRect.setSize( _boundingTextSize );
//get bounding size and center pos
const auto &_half_size = (m_binding.getSize() / 2);
if( _half_size.getWidth() - _boundingTextSize.getWidth() > 0
&& _half_size.getHeight() - _boundingTextSize.getHeight() > 0){
IntegerDyadCoordinate _translated_coord( _half_size.getWidth() - (_boundingTextSize.getWidth() / 2 )
, _half_size.getHeight() - (_boundingTextSize.getHeight() / 2 ) - (_boundingTextSize.getHeight() / 4 ) ); /* normalized value */
m_textBoundingRect.translatedBy( _translated_coord );
}
}
}
}
| 33.673684
| 147
| 0.626758
|
0of
|
f864a7c0098829c3fb06d77aee813880b0866700
| 4,521
|
cpp
|
C++
|
sources/test/Main.cpp
|
Naoki-Nakagawa/GameLibrary
|
0b20938a19a293f76c177726a8e70ddce0dbeeb5
|
[
"MIT"
] | 2
|
2017-05-23T17:19:17.000Z
|
2017-05-30T10:28:38.000Z
|
sources/test/Main.cpp
|
Naoki-Nakagawa/GameDevelopmentKit
|
0b20938a19a293f76c177726a8e70ddce0dbeeb5
|
[
"MIT"
] | 61
|
2018-02-11T08:27:32.000Z
|
2018-06-01T11:01:57.000Z
|
sources/test/Main.cpp
|
itukikikuti/GameLibrary
|
0b20938a19a293f76c177726a8e70ddce0dbeeb5
|
[
"MIT"
] | null | null | null |
#define XLIBRARY_NAMESPACE_BEGIN
#define XLIBRARY_NAMESPACE_END
#include "../Library.hpp"
#include "../LibraryGenerator.cpp"
#include <sstream>
#include "Sub.hpp"
using namespace std;
int Main()
{
LibraryGenerator::Generate(L"sources/Library.hpp", L"XLibrary11.hpp");
Debug::OpenConsole();
printf("aaaaaa");
Sprite sprite1(L"assets/box.jpg");
Camera camera;
camera.position = Float3(0.0f, 1.0f, -5.0f);
camera.SetupPerspective();
camera.color = Float4(0.0f, 0.0f, 0.0f, 1.0f);
Camera uiCamera;
uiCamera.color = Float4(1.0f, 0.0f, 1.0f, 1.0f);
uiCamera.clear = false;
uiCamera.SetupOrthographic((float)Window::GetSize().y, true);
Texture texture(L"assets/box.jpg");
Texture playerTexture(L"assets/player.png");
Mesh mesh;
mesh.CreateCube(Float3(2.0f, 1.0f, 0.5f));
mesh.SetTexture(&texture);
Mesh sphere;
sphere.CreateSphere();
sphere.SetTexture(&playerTexture);
sphere.position.y = 2.0f;
Light directionalLight;
directionalLight.type = Light::Type::Directional;
directionalLight.angles = Float3(-50.0f, 30.0f, 0.0);
directionalLight.intensity = 0.5f;
directionalLight.Update();
Light light;
light.type = Light::Type::Point;
light.position.z = -1.0f;
light.color = Float4(0.0f, 1.0f, 0.0f, 0.0f);
Light light2;
light2.type = Light::Type::Point;
light2.position = Float3(1.0f, 1.0f, 0.5f);
light2.range = 2.0f;
light2.color = Float4(1.0f, 0.0f, 0.0f, 0.0f);
light2.intensity = 2.0f;
light2.Update();
Light light3;
light3.type = Light::Type::Point;
light3.position = Float3(-0.5f, 1.0f, -2.0f);
light3.range = 3.0f;
light3.color = Float4(0.0f, 0.0f, 1.0f, 0.0f);
light3.intensity = 10.0f;
light3.Update();
Text number(L"0", 100.0f);
number.position.y = 3.0f;
number.scale = 1.0f / 100.0f;
number.color = Float4(1.0f, 0.0f, 0.0f, 1.0f);
number.antialias = false;
Sound music(L"assets/music.mp3");
music.SetPitch(1.0f);
music.SetVolume(0.5f);
music.SetPan(0.0f);
music.SetLoop(true);
music.Play();
Sound sound(L"assets/sound.wav");
sprite1.position.x = 1.0f;
sprite1.scale = 1.0f / 256.0f;
Text text(L"あいうえおかきくけこさしすせそ\nabcdefghijklmnopqrstuvwxyz", 16.0f);
//text.SetPivot(Float2(-1.0f, 1.0f));
text.position.x = 200.0f;
text.position.y = 100.0f;
text.scale = 2.0f;
text.color = Float4(1.0f, 1.0f, 1.0f, 1.0f);
Sprite sprite(L"assets/box.jpg");
sprite.scale = 0.5f;
sprite.color.w = 0.5f;
Sprite clock(L"assets/clock.png");
clock.scale = 0.2f;
clock.angles.z = -135.0f;
float pos1 = -2.0f;
float pos2 = -3.0f;
while (Refresh())
{
camera.Update();
PrintFrameRate();
//printf("%d\n", Random::Range(0, 10));
light.position.x = Input::GetMousePosition().x * 0.01f;
light.position.y = Input::GetMousePosition().y * 0.01f;
light.Update();
music.SetPitch(Input::GetMousePosition().x / (Window::GetSize().x / 2.0f));
if (Input::GetKeyDown('J'))
music.Play();
if (Input::GetKeyDown('K'))
music.Pause();
if (Input::GetKeyDown('L'))
music.Stop();
if (Input::GetKeyDown(VK_SPACE))
{
sound.Play();
}
if (Input::GetPadButtonDown(0, XINPUT_GAMEPAD_A))
{
sound.Play();
}
if (Input::GetKeyDown('3'))
{
Window::SetMode(Window::Mode::FullScreen);
}
number.angles.y += 1.0f;
number.Create(std::to_wstring(Input::GetMouseWheel()), 100.0f);
if (Input::GetKey('2'))
{
wstringstream ss;
ss << Timer::GetTime();
number.Create(ss.str(), 100.0f);
}
number.position.x = pos1;
number.color = Float4(1.0f, 0.0f, 0.0f, 1.0f);
number.Draw();
pos2 += 0.01f;
number.position.x = pos2;
number.color = Float4(0.0f, 0.0f, 1.0f, 1.0f);
number.Draw();
mesh.angles.z += Input::GetPadLeftThumb(0).y * 3.0f;
mesh.angles.y += -Input::GetPadLeftThumb(0).x * 3.0f;
mesh.position.x = 0.5f;
mesh.angles.x = Input::GetPadRightTrigger(0) * 90.0f;
mesh.Draw();
mesh.position.x = -0.5f;
mesh.angles.x = Input::GetPadLeftTrigger(0) * 90.0f;
mesh.Draw();
sphere.angles.x += Input::GetMouseWheel() * 0.5f;
sphere.Draw();
if (Input::GetKey('1'))
Input::SetMousePosition(0.0f, 0.0f);
sprite1.angles.z = Random::GetValue() * 360.0f;
sprite1.Draw();
uiCamera.Update();
text.angles.z += Timer::GetDeltaTime() * 30.0f;
text.Draw();
sprite.position.x = Window::GetSize().x / 2.0f - sprite.GetSize().x * sprite.scale.x / 2.0f;
sprite.position.y = Window::GetSize().y / 2.0f - sprite.GetSize().y * sprite.scale.y / 2.0f;
//sprite.angles.z += 10.0f;
sprite.Draw();
clock.position = Input::GetMousePosition();
clock.Draw();
}
return 0;
}
| 23.670157
| 94
| 0.65605
|
Naoki-Nakagawa
|
f874668564f613d9c24db90e684e040d5d3ee28e
| 678
|
hh
|
C++
|
include/helper.hh
|
kretash/old_school_fps
|
c9c1951939fdf810fff58ebc04818972e92ffc77
|
[
"MIT"
] | null | null | null |
include/helper.hh
|
kretash/old_school_fps
|
c9c1951939fdf810fff58ebc04818972e92ffc77
|
[
"MIT"
] | null | null | null |
include/helper.hh
|
kretash/old_school_fps
|
c9c1951939fdf810fff58ebc04818972e92ffc77
|
[
"MIT"
] | null | null | null |
#pragma once
#include <stdint.h>
#include "math.hh"
static inline uint32_t create_color( float r, float g, float b, float a ) {
uint32_t color =
( uint8_t ) ( def_clamp( a * 255.0f, 0.0f, 255.0f ) ) << 24 |
( uint8_t ) ( def_clamp( b * 255.0f, 0.0f, 255.0f ) ) << 16 |
( uint8_t ) ( def_clamp( g * 255.0f, 0.0f, 255.0f ) ) << 8 |
( uint8_t ) ( def_clamp( r * 255.0f, 0.0f, 255.0f ) );
return color;
}
static inline uint32_t create_color( float r, float g, float b ) {
return create_color( r, g, b, 1.0f );
}
static inline uint32_t create_color( float4 color ) {
return create_color( color.x, color.y, color.z, color.w );
}
| 27.12
| 75
| 0.591445
|
kretash
|
f87521729fac8e1404a245d2045aa299107a68f2
| 1,374
|
cpp
|
C++
|
Samples/ObjectInOffice/IDataObject.cpp
|
ntclark/Graphic
|
86acc119d172bb53c1666432538836b461d8a3f2
|
[
"BSD-3-Clause"
] | 12
|
2018-03-15T00:20:55.000Z
|
2021-08-11T10:02:15.000Z
|
Samples/ObjectInOffice/IDataObject.cpp
|
ntclark/Graphic
|
86acc119d172bb53c1666432538836b461d8a3f2
|
[
"BSD-3-Clause"
] | null | null | null |
Samples/ObjectInOffice/IDataObject.cpp
|
ntclark/Graphic
|
86acc119d172bb53c1666432538836b461d8a3f2
|
[
"BSD-3-Clause"
] | 2
|
2019-04-09T17:15:31.000Z
|
2020-12-05T19:52:59.000Z
|
// Copyright 2018 InnoVisioNate Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ObjectInOffice.h"
STDMETHODIMP ObjectInOffice::GetData(FORMATETC *,STGMEDIUM *) {
return S_OK;
}
STDMETHODIMP ObjectInOffice::GetDataHere(FORMATETC *,STGMEDIUM *) {
return S_OK;
}
STDMETHODIMP ObjectInOffice::QueryGetData(FORMATETC *) {
return S_OK;
}
STDMETHODIMP ObjectInOffice::GetCanonicalFormatEtc(FORMATETC *,FORMATETC *) {
return S_OK;
}
STDMETHODIMP ObjectInOffice::SetData(FORMATETC *,STGMEDIUM *,BOOL) {
return S_OK;
}
STDMETHODIMP ObjectInOffice::EnumFormatEtc(DWORD,IEnumFORMATETC **) {
return S_OK;
}
STDMETHODIMP ObjectInOffice::DAdvise(FORMATETC *pFormatEtc,DWORD advf,IAdviseSink *pIAS,DWORD *pdwConnection) {
return E_NOTIMPL;
//if ( ! pDataAdviseHolder )
// CreateDataAdviseHolder(&pDataAdviseHolder);
//if ( pDataAdviseHolder )
// pDataAdviseHolder -> Advise(static_cast<IDataObject *>(this),pFormatEtc,advf,pIAS,pdwConnection);
//return S_OK;
}
STDMETHODIMP ObjectInOffice::DUnadvise(DWORD dwConnection) {
if ( pDataAdviseHolder )
pDataAdviseHolder -> Unadvise(dwConnection);
return S_OK;
}
STDMETHODIMP ObjectInOffice::EnumDAdvise(IEnumSTATDATA **) {
return S_OK;
}
| 28.040816
| 114
| 0.720524
|
ntclark
|
f8767f849911f1eca9300a2ea16e8808007407f3
| 476
|
cc
|
C++
|
2021_1011_1017/887.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
2021_1011_1017/887.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
2021_1011_1017/887.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int superEggDrop(int k, int n) {
vector<vector<int>> dp(10001,vector<int>(k+1,0));
int m = 0;
// m: #move
// dp[m][k]: the #floors can be tested using m moves and k eggs
while (dp[m][k]<n){
m++;
for (int j=1; j<=k; ++j){
// the j-th drop + not break + break
dp[m][j] = 1 + dp[m-1][j] + dp[m-1][j-1];
}
}
return m;
}
};
| 26.444444
| 71
| 0.413866
|
guohaoqiang
|
f879833a3b649dfc90b7f50ad0a2c0bbb8b3b7bf
| 1,677
|
cpp
|
C++
|
solutions/c++/problems/[0017_Medium] Letter Combinations of a Phone Number.cpp
|
RageBill/leetcode
|
a11d411f4e38b5c3f05ca506a193f50b25294497
|
[
"MIT"
] | 6
|
2021-02-20T14:00:22.000Z
|
2022-03-31T15:26:44.000Z
|
solutions/c++/problems/[0017_Medium] Letter Combinations of a Phone Number.cpp
|
RageBill/leetcode
|
a11d411f4e38b5c3f05ca506a193f50b25294497
|
[
"MIT"
] | null | null | null |
solutions/c++/problems/[0017_Medium] Letter Combinations of a Phone Number.cpp
|
RageBill/leetcode
|
a11d411f4e38b5c3f05ca506a193f50b25294497
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<char>> cart_product(const vector<vector<char>> &v) {
vector<vector<char>> s = {{}};
for (auto &u: v) {
vector<vector<char>> r;
for (auto &x: s) {
for (auto y: u) {
r.push_back(x);
r.back().push_back(y);
}
}
s.swap(r);
}
return s;
}
vector<char> getLetter(char num) {
switch (num) {
case '2':
return {'a', 'b', 'c'};
case '3':
return {'d', 'e', 'f'};
case '4':
return {'g', 'h', 'i'};
case '5':
return {'j', 'k', 'l'};
case '6':
return {'m', 'n', 'o'};
case '7':
return {'p', 'q', 'r', 's'};
case '8':
return {'t', 'u', 'v'};
case '9':
return {'w', 'x', 'y', 'z'};
default:
return {};
}
}
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return {};
vector<char> digitVector = vector<char>(digits.begin(), digits.end());
vector<vector<char>> lettersVector = {};
for (auto digit: digitVector) {
lettersVector.push_back(getLetter(digit));
}
vector<vector<char>> product = cart_product(lettersVector);
vector<string> ans = {};
for (auto res: product) {
ans.push_back(string(res.begin(), res.end()));
}
return ans;
}
};
| 27.95
| 78
| 0.408468
|
RageBill
|
f881f992d4faa5d20f4649883ba1b1a4687a8a1e
| 1,037
|
cpp
|
C++
|
algorithm-challenges/baekjoon-online-judge/challenges/9000/9251.cpp
|
nbsp1221/algorithm
|
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
|
[
"MIT"
] | null | null | null |
algorithm-challenges/baekjoon-online-judge/challenges/9000/9251.cpp
|
nbsp1221/algorithm
|
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
|
[
"MIT"
] | null | null | null |
algorithm-challenges/baekjoon-online-judge/challenges/9000/9251.cpp
|
nbsp1221/algorithm
|
a227bbc7cf43dbf2cadc8d47052b9a92875dfa77
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
string small, big, temponary;
cin >> small >> big;
if (small.size() > big.size()) {
temponary = small;
small = big;
big = temponary;
}
vector<vector<int>> lcs(big.size(), vector<int>(big.size(), 0));
lcs[0][0] = small[0] == big[0];
for (uint i = 1; i < small.size(); i++) {
lcs[i][0] = lcs[i - 1][0] ? 1 : small[i] == big[0];
}
for (uint i = 1; i < big.size(); i++) {
lcs[0][i] = lcs[0][i - 1] ? 1 : small[0] == big[i];
}
for (uint i = 1; i < small.size(); i++) {
for (uint j = 1; j < big.size(); j++) {
if (small[i] == big[j]) {
lcs[i][j] = lcs[i - 1][j - 1] + 1;
}
else {
lcs[i][j] = max(lcs[i][j - 1], lcs[i - 1][j]);
}
}
}
cout << lcs[small.size() - 1][big.size() - 1] << "\n";
return 0;
}
| 22.543478
| 68
| 0.427194
|
nbsp1221
|
f8837cbfab9cd082989c2ec26848513a735149e4
| 1,490
|
hpp
|
C++
|
include/boost/mysql/detail/auth/auth_calculator.hpp
|
AlexAndDad/mysql-asio
|
a56d390a2ef4426744483dcbaeb54a65af524356
|
[
"BSL-1.0"
] | null | null | null |
include/boost/mysql/detail/auth/auth_calculator.hpp
|
AlexAndDad/mysql-asio
|
a56d390a2ef4426744483dcbaeb54a65af524356
|
[
"BSL-1.0"
] | null | null | null |
include/boost/mysql/detail/auth/auth_calculator.hpp
|
AlexAndDad/mysql-asio
|
a56d390a2ef4426744483dcbaeb54a65af524356
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2019-2020 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// 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 BOOST_MYSQL_DETAIL_AUTH_AUTH_CALCULATOR_HPP
#define BOOST_MYSQL_DETAIL_AUTH_AUTH_CALCULATOR_HPP
#include "boost/mysql/error.hpp"
#include <array>
#include <string>
#include <string_view>
namespace boost {
namespace mysql {
namespace detail {
struct authentication_plugin
{
using calculator_signature = error_code (*)(
std::string_view password,
std::string_view challenge,
bool use_ssl,
std::string& output
);
std::string_view name;
calculator_signature calculator;
};
class auth_calculator
{
const authentication_plugin* plugin_ {nullptr};
std::string response_;
inline static const authentication_plugin* find_plugin(std::string_view name);
public:
inline error_code calculate(
std::string_view plugin_name,
std::string_view password,
std::string_view challenge,
bool use_ssl
);
std::string_view response() const noexcept { return response_; }
std::string_view plugin_name() const noexcept
{
assert(plugin_);
return plugin_->name;
}
};
} // detail
} // mysql
} // boost
#include "boost/mysql/detail/auth/impl/auth_calculator.ipp"
#endif /* INCLUDE_BOOST_MYSQL_DETAIL_AUTH_AUTH_CALCULATOR_HPP_ */
| 24.42623
| 82
| 0.715436
|
AlexAndDad
|
f886b196bebdc5e2f992f0cf120344c37ba5a990
| 7,678
|
cpp
|
C++
|
case-studies/PoDoFo/podofo/cib/podofo/base/PdfDataType.h.cpp
|
satya-das/cib
|
369333ea58b0530b8789a340e21096ba7d159d0e
|
[
"MIT"
] | 30
|
2018-03-05T17:35:29.000Z
|
2022-03-17T18:59:34.000Z
|
case-studies/PoDoFo/podofo/cib/podofo/base/PdfDataType.h.cpp
|
satya-das/cib
|
369333ea58b0530b8789a340e21096ba7d159d0e
|
[
"MIT"
] | 2
|
2016-05-26T04:47:13.000Z
|
2019-02-15T05:17:43.000Z
|
case-studies/PoDoFo/podofo/cib/podofo/base/PdfDataType.h.cpp
|
satya-das/cib
|
369333ea58b0530b8789a340e21096ba7d159d0e
|
[
"MIT"
] | 5
|
2019-02-15T05:09:22.000Z
|
2021-04-14T12:10:16.000Z
|
#include "podofo/base/PdfDataType.h"
#include "podofo/base/PdfDefines.h"
#include "podofo/base/PdfEncrypt.h"
#include "podofo/base/PdfOutputDevice.h"
#include "__zz_cib_CibPoDoFo-class-down-cast.h"
#include "__zz_cib_CibPoDoFo-delegate-helper.h"
#include "__zz_cib_CibPoDoFo-generic.h"
#include "__zz_cib_CibPoDoFo-ids.h"
#include "__zz_cib_CibPoDoFo-type-converters.h"
#include "__zz_cib_CibPoDoFo-mtable-helper.h"
#include "__zz_cib_CibPoDoFo-proxy-mgr.h"
namespace __zz_cib_ {
using namespace ::PoDoFo;
template<> struct __zz_cib_Delegator<::PoDoFo::PdfDataType>;
template <>
class __zz_cib_Generic<::PoDoFo::PdfDataType> : public ::PoDoFo::PdfDataType {
public:
using __zz_cib_Proxy = __zz_cib_Proxy_t<::PoDoFo::PdfDataType>;
using __zz_cib_ProxyDeleter = __zz_cib_ProxyDeleter_t<::PoDoFo::PdfDataType>;
__zz_cib_Generic(__zz_cib_Proxy __zz_cib_proxy, const __zz_cib_MethodTable* __zz_cib_GetMethodTable)
: ::PoDoFo::PdfDataType::PdfDataType()
, __zz_cib_h_(__zz_cib_proxy)
, __zz_cib_methodTableHelper(__zz_cib_GetMethodTable)
{}
void SetDirty(bool bDirty) override {
auto __zz_cib_h = __zz_cib_h_;
using __zz_cib_ProcType = __zz_cib_AbiType_t<void>(__zz_cib_decl *) (__zz_cib_Proxy, __zz_cib_AbiType_t<decltype(bDirty)>);
__zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::SetDirty_0>(
__zz_cib_h,
__zz_cib_::__zz_cib_ToAbiType<decltype(bDirty)>(std::move(bDirty))
);
}
void Write(::PoDoFo::PdfOutputDevice* pDevice, ::PoDoFo::EPdfWriteMode eWriteMode, const ::PoDoFo::PdfEncrypt* pEncrypt) const override {
auto __zz_cib_h = __zz_cib_h_;
using __zz_cib_ProcType = __zz_cib_AbiType_t<void>(__zz_cib_decl *) (const __zz_cib_Proxy, __zz_cib_AbiType_t<decltype(pDevice)>, __zz_cib_AbiType_t<decltype(eWriteMode)>, __zz_cib_AbiType_t<decltype(pEncrypt)>);
__zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::Write_1>(
__zz_cib_h,
__zz_cib_::__zz_cib_ToAbiType<decltype(pDevice)>(std::move(pDevice)),
__zz_cib_::__zz_cib_ToAbiType<decltype(eWriteMode)>(std::move(eWriteMode)),
__zz_cib_::__zz_cib_ToAbiType<decltype(pEncrypt)>(std::move(pEncrypt))
);
}
bool IsDirty() const override {
auto __zz_cib_h = __zz_cib_h_;
using __zz_cib_ProcType = __zz_cib_AbiType_t<bool>(__zz_cib_decl *) (const __zz_cib_Proxy);
return __zz_cib_FromAbiType<bool>(
__zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::IsDirty_2>(
__zz_cib_h
)
);
}
~__zz_cib_Generic() override {
if (!__zz_cib_h_) return;
auto __zz_cib_h = __zz_cib_h_;
using __zz_cib_ProcType = void(__zz_cib_decl *) (__zz_cib_Proxy);
__zz_cib_GetMethodTableHelper().Invoke<__zz_cib_ProcType, __zz_cib_MethodId::__zz_cib_Delete_3>(
__zz_cib_h
);
}
void __zz_cib_ReleaseProxy() { __zz_cib_h_ = nullptr; }
__ZZ_CIB_DELEGATOR_MEMBERS(__zz_cib_Generic, ::PoDoFo::PdfDataType)
private:
__zz_cib_Proxy __zz_cib_h_;
const __zz_cib_MethodTableHelper __zz_cib_methodTableHelper;
const __zz_cib_MethodTableHelper& __zz_cib_GetMethodTableHelper() const {
return __zz_cib_methodTableHelper;
}
friend struct __zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>;
using __zz_cib_MethodId = __zz_cib_::__zz_cib_ids::__zz_cib_Class333::__zz_cib_Class346::__zz_cib_Generic::__zz_cib_MethodId;
};
}
namespace __zz_cib_ {
using namespace ::PoDoFo;
template <>
struct __zz_cib_Delegator<::PoDoFo::PdfDataType> : public ::PoDoFo::PdfDataType {
using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Generic<::PoDoFo::PdfDataType>;
using __zz_cib_AbiType = __zz_cib_Delegatee*;
using __zz_cib_Proxy = __zz_cib_Proxy_t<::PoDoFo::PdfDataType>;
using __zz_cib_ProxyDeleter = __zz_cib_ProxyDeleter_t<::PoDoFo::PdfDataType>;
using ::PoDoFo::PdfDataType::PdfDataType;
static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_0(__zz_cib_Proxy __zz_cib_proxy, const __zz_cib_MethodTable* __zz_cib_GetMethodTable) {
return new __zz_cib_::__zz_cib_Generic<::PoDoFo::PdfDataType>(__zz_cib_proxy, __zz_cib_GetMethodTable);
}
static void __zz_cib_decl __zz_cib_Delete_1(__zz_cib_Delegatee* __zz_cib_obj) {
delete __zz_cib_obj;
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Write_2(const __zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::PdfOutputDevice*> pDevice, __zz_cib_AbiType_t<::PoDoFo::EPdfWriteMode> eWriteMode, __zz_cib_AbiType_t<const ::PoDoFo::PdfEncrypt*> pEncrypt) {
__zz_cib_obj->Write(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfOutputDevice*>(pDevice),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfWriteMode>(eWriteMode),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfEncrypt*>(pEncrypt)
);
}
static __zz_cib_AbiType_t<bool> __zz_cib_decl IsDirty_3(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<bool>(
__zz_cib_obj->::PoDoFo::PdfDataType::IsDirty()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetDirty_4(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<bool> bDirty) {
__zz_cib_obj->::PoDoFo::PdfDataType::SetDirty(
__zz_cib_::__zz_cib_FromAbiType<bool>(bDirty)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetImmutable_5(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<bool> bImmutable) {
__zz_cib_obj->::PoDoFo::PdfDataType::SetImmutable(
__zz_cib_::__zz_cib_FromAbiType<bool>(bImmutable)
);
}
static __zz_cib_AbiType_t<bool> __zz_cib_decl GetImmutable_6(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<bool>(
__zz_cib_obj->::PoDoFo::PdfDataType::GetImmutable()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl AssertMutable_7(const __zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfDataType::AssertMutable();
}
static void __zz_cib_decl __zz_cib_RegisterProxy(::PoDoFo::PdfDataType* obj, __zz_cib_Proxy proxy, __zz_cib_ProxyDeleter deleter) {
__zz_cib_ProxyManagerDelegator::__zz_cib_RegisterProxy(obj, proxy, deleter);
}
static void __zz_cib_decl __zz_cib_ReleaseProxy(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->__zz_cib_ReleaseProxy();
}
};
}
namespace __zz_cib_ {
namespace __zz_cib_Class333 {
using namespace ::PoDoFo;
namespace __zz_cib_Class346 {
const __zz_cib_MethodTable* __zz_cib_GetMethodTable() {
static const __zz_cib_MTableEntry methodArray[] = {
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_New_0),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_Delete_1),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::Write_2),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::IsDirty_3),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::SetDirty_4),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::SetImmutable_5),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::GetImmutable_6),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::AssertMutable_7),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_ReleaseProxy),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfDataType>::__zz_cib_RegisterProxy)
};
static const __zz_cib_MethodTable methodTable = { methodArray, 10 };
return &methodTable;
}
}}}
| 49.535484
| 267
| 0.784189
|
satya-das
|
f8890a3a056ff61efd82778c8997d1b70f77e01f
| 2,267
|
cpp
|
C++
|
PolyEngine/UnitTests/Src/AllocatorTests.cpp
|
MuniuDev/PolyEngine
|
9389537e4f551fa5dd621ebd3704e55b04c98792
|
[
"MIT"
] | 1
|
2017-04-30T13:55:54.000Z
|
2017-04-30T13:55:54.000Z
|
PolyEngine/UnitTests/Src/AllocatorTests.cpp
|
MuniuDev/PolyEngine
|
9389537e4f551fa5dd621ebd3704e55b04c98792
|
[
"MIT"
] | null | null | null |
PolyEngine/UnitTests/Src/AllocatorTests.cpp
|
MuniuDev/PolyEngine
|
9389537e4f551fa5dd621ebd3704e55b04c98792
|
[
"MIT"
] | 3
|
2017-11-22T16:37:26.000Z
|
2019-04-24T17:47:58.000Z
|
#include <catch.hpp>
#include <PoolAllocator.hpp>
#include <IterablePoolAllocator.hpp>
using namespace Poly;
TEST_CASE("Pool allocator", "[Allocator]") {
PoolAllocator<size_t> allocator(10);
REQUIRE(allocator.GetSize() == 0);
size_t* a = allocator.Alloc();
REQUIRE(a != nullptr);
REQUIRE(allocator.GetSize() == 1);
size_t* b = allocator.Alloc();
REQUIRE(b != nullptr);
REQUIRE((a + 1) == b);
REQUIRE(allocator.GetSize() == 2);
size_t* c = allocator.Alloc();
REQUIRE(c != nullptr);
REQUIRE((a + 2) == c);
REQUIRE((b + 1) == c);
REQUIRE(allocator.GetSize() == 3);
allocator.Free(b);
REQUIRE(allocator.GetSize() == 2);
size_t* d = allocator.Alloc();
REQUIRE(d == b);
REQUIRE(allocator.GetSize() == 3);
}
TEST_CASE("Iterable pool allocator", "[Allocator]") {
// test allocation
IterablePoolAllocator<size_t> allocator(10);
REQUIRE(allocator.GetSize() == 0);
size_t* a = allocator.Alloc();
REQUIRE(a != nullptr);
REQUIRE(allocator.GetSize() == 1);
size_t* b = allocator.Alloc();
REQUIRE(b != nullptr);
REQUIRE(allocator.GetSize() == 2);
size_t* c = allocator.Alloc();
REQUIRE(c != nullptr);
REQUIRE(allocator.GetSize() == 3);
allocator.Free(b);
REQUIRE(allocator.GetSize() == 2);
size_t* b_2 = allocator.Alloc();
REQUIRE(b_2 == b);
REQUIRE(allocator.GetSize() == 3);
// test iterators
*a = 1;
*b_2 = 2;
*c = 3;
size_t i = 0;
for (size_t val : allocator)
REQUIRE(val == ++i);
IterablePoolAllocator<size_t> empty_allocator(10);
REQUIRE(empty_allocator.Begin() == empty_allocator.End());
}
TEST_CASE("Iterable pool allocator corner case test", "[Allocator]") {
// test allocation
IterablePoolAllocator<size_t> allocator(3);
size_t* a = allocator.Alloc();
REQUIRE(a != nullptr);
REQUIRE(allocator.GetSize() == 1);
size_t* b = allocator.Alloc();
REQUIRE(b != nullptr);
REQUIRE(allocator.GetSize() == 2);
allocator.Free(a);
REQUIRE(allocator.GetSize() == 1);
size_t* c = allocator.Alloc();
REQUIRE(c != nullptr);
REQUIRE(allocator.GetSize() == 2);
size_t* d = allocator.Alloc();
REQUIRE(d != nullptr);
REQUIRE(allocator.GetSize() == 3);
allocator.Free(d);
REQUIRE(allocator.GetSize() == 2);
size_t* e = allocator.Alloc();
REQUIRE(e != nullptr);
REQUIRE(allocator.GetSize() == 3);
}
| 22.445545
| 70
| 0.659462
|
MuniuDev
|
f889a8743f81ad633163e794d37ae91c293f278d
| 1,134
|
cpp
|
C++
|
c++/remove_duplicates_from_sorted_list.cpp
|
SongZhao/leetcode
|
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
|
[
"Apache-2.0"
] | null | null | null |
c++/remove_duplicates_from_sorted_list.cpp
|
SongZhao/leetcode
|
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
|
[
"Apache-2.0"
] | null | null | null |
c++/remove_duplicates_from_sorted_list.cpp
|
SongZhao/leetcode
|
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
|
[
"Apache-2.0"
] | null | null | null |
/*
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
*/
/*
* note how to free memory
*/
#include "helper.h"
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
ListNode *p = head;
while (p && p->next) {
if (p->val == p->next->val) {
ListNode *tmp = p->next;
p->next = p->next->next;
delete tmp; // delete only works if the list node is allocated by new
} else {
p = p->next;
}
}
return head;
}
};
int main() {
Solution s;
vector<int> v1({1, 1, 1});
ListNode *headA = buildList(v1);
s.deleteDuplicates(headA);
printList(headA);
vector<int> v2({1, 1, 2, 3, 3});
ListNode *headB = buildList(v2);
s.deleteDuplicates(headB);
printList(headB);
return 0;
}
| 21
| 90
| 0.534392
|
SongZhao
|
f88e19a2599b4d3b6e63bb590eb7da1478dcf03b
| 480
|
cpp
|
C++
|
DP/746. Min Cost Climbing Stairs.cpp
|
sumiya-NJU/LeetCode-
|
8e6065e160da3db423a51aaf3ae53b2023068d05
|
[
"MIT"
] | 2
|
2019-10-28T06:40:09.000Z
|
2022-03-09T10:50:06.000Z
|
DP/746. Min Cost Climbing Stairs.cpp
|
sumiya-NJU/LeetCode
|
8e6065e160da3db423a51aaf3ae53b2023068d05
|
[
"MIT"
] | null | null | null |
DP/746. Min Cost Climbing Stairs.cpp
|
sumiya-NJU/LeetCode
|
8e6065e160da3db423a51aaf3ae53b2023068d05
|
[
"MIT"
] | 1
|
2018-12-09T13:46:06.000Z
|
2018-12-09T13:46:06.000Z
|
// author: ypz
// 数组dp表示落地到第i位的最低代价,注意返回值取落地到第n位和第n-1位中代价的较小者。
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
if(cost.size() == 0) return 0;
if(cost.size() == 1) return cost[0];
vector<int> dp(cost.size(), 0);
dp[0] = cost[0];
dp[1] = cost[1];
for(int i = 2; i < cost.size(); i++)
dp[i] = min(dp[i-1], dp[i-2]) + cost[i];
return min(dp[cost.size()-1], dp[cost.size()-2]);
}
};
| 28.235294
| 57
| 0.520833
|
sumiya-NJU
|
f8901f6e1876b927d707f7faa558179dfdfb3f08
| 9,194
|
cpp
|
C++
|
examples/ex28.cpp
|
ajithvallabai/mfem
|
5920fbf645f328c29a9d6489f2474d989f808451
|
[
"BSD-3-Clause"
] | 969
|
2015-07-10T02:28:17.000Z
|
2022-03-31T17:28:02.000Z
|
examples/ex28.cpp
|
ajithvallabai/mfem
|
5920fbf645f328c29a9d6489f2474d989f808451
|
[
"BSD-3-Clause"
] | 2,604
|
2015-07-14T08:22:22.000Z
|
2022-03-31T23:51:41.000Z
|
examples/ex28.cpp
|
ajithvallabai/mfem
|
5920fbf645f328c29a9d6489f2474d989f808451
|
[
"BSD-3-Clause"
] | 407
|
2015-08-26T14:14:22.000Z
|
2022-03-31T03:32:16.000Z
|
// MFEM Example 28
//
// Compile with: make ex28
//
// Sample runs: ex28
// ex28 --visit-datafiles
// ex28 --order 2
//
// Description: Demonstrates a sliding boundary condition in an elasticity
// problem. A trapezoid, roughly as pictured below, is pushed
// from the right into a rigid notch. Normal displacement is
// restricted, but tangential movement is allowed, so the
// trapezoid compresses into the notch.
//
// /-------+
// normal constrained --->/ | <--- boundary force (2)
// boundary (4) /---------+
// ^
// |
// normal constrained boundary (1)
//
// This example demonstrates the use of the ConstrainedSolver
// framework.
//
// We recommend viewing Example 2 before viewing this example.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include <set>
using namespace std;
using namespace mfem;
// Return a mesh with a single element with vertices (0, 0), (1, 0), (1, 1),
// (offset, 1) to demonstrate boundary conditions on a surface that is not
// axis-aligned.
Mesh * build_trapezoid_mesh(double offset)
{
MFEM_VERIFY(offset < 0.9, "offset is too large!");
const int dimension = 2;
const int nvt = 4; // vertices
const int nbe = 4; // num boundary elements
Mesh * mesh = new Mesh(dimension, nvt, 1, nbe);
// vertices
double vc[dimension];
vc[0] = 0.0; vc[1] = 0.0;
mesh->AddVertex(vc);
vc[0] = 1.0; vc[1] = 0.0;
mesh->AddVertex(vc);
vc[0] = offset; vc[1] = 1.0;
mesh->AddVertex(vc);
vc[0] = 1.0; vc[1] = 1.0;
mesh->AddVertex(vc);
// element
Array<int> vert(4);
vert[0] = 0; vert[1] = 1; vert[2] = 3; vert[3] = 2;
mesh->AddQuad(vert, 1);
// boundary
Array<int> sv(2);
sv[0] = 0; sv[1] = 1;
mesh->AddBdrSegment(sv, 1);
sv[0] = 1; sv[1] = 3;
mesh->AddBdrSegment(sv, 2);
sv[0] = 2; sv[1] = 3;
mesh->AddBdrSegment(sv, 3);
sv[0] = 0; sv[1] = 2;
mesh->AddBdrSegment(sv, 4);
mesh->FinalizeQuadMesh(1, 0, true);
return mesh;
}
int main(int argc, char *argv[])
{
// 1. Parse command-line options.
int order = 1;
bool visualization = 1;
double offset = 0.3;
bool visit = false;
OptionsParser args(argc, argv);
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree).");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&offset, "--offset", "--offset",
"How much to offset the trapezoid.");
args.AddOption(&visit, "-visit", "--visit-datafiles", "-no-visit",
"--no-visit-datafiles",
"Save data files for VisIt (visit.llnl.gov) visualization.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return 1;
}
args.PrintOptions(cout);
// 2. Build a trapezoidal mesh with a single quadrilateral element, where
// 'offset' determines how far off it is from a rectangle.
Mesh *mesh = build_trapezoid_mesh(offset);
int dim = mesh->Dimension();
// 3. Refine the mesh to increase the resolution. In this example we do
// 'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
// largest number that gives a final mesh with no more than 1,000
// elements.
{
int ref_levels =
(int)floor(log(1000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 4. Define a finite element space on the mesh. Here we use vector finite
// elements, i.e. dim copies of a scalar finite element space. The vector
// dimension is specified by the last argument of the FiniteElementSpace
// constructor.
FiniteElementCollection *fec = new H1_FECollection(order, dim);
FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec, dim);
cout << "Number of finite element unknowns: " << fespace->GetTrueVSize()
<< endl;
cout << "Assembling matrix and r.h.s... " << flush;
// 5. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, there are no essential boundary
// conditions in the usual sense, but we leave the machinery here for
// users to modify if they wish.
Array<int> ess_tdof_list, ess_bdr(mesh->bdr_attributes.Max());
ess_bdr = 0;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
// 6. Set up the linear form b(.) which corresponds to the right-hand side of
// the FEM linear system. In this case, b_i equals the boundary integral
// of f*phi_i where f represents a "push" force on the right side of the
// trapezoid.
VectorArrayCoefficient f(dim);
for (int i = 0; i < dim-1; i++)
{
f.Set(i, new ConstantCoefficient(0.0));
}
{
Vector push_force(mesh->bdr_attributes.Max());
push_force = 0.0;
push_force(1) = -5.0e-2; // index 1 attribute 2
f.Set(0, new PWConstCoefficient(push_force));
}
LinearForm *b = new LinearForm(fespace);
b->AddBoundaryIntegrator(new VectorBoundaryLFIntegrator(f));
b->Assemble();
// 7. Define the solution vector x as a finite element grid function
// corresponding to fespace.
GridFunction x(fespace);
x = 0.0;
// 8. Set up the bilinear form a(.,.) on the finite element space
// corresponding to the linear elasticity integrator with piece-wise
// constants coefficient lambda and mu. We use constant coefficients,
// but see ex2 for how to set up piecewise constant coefficients based
// on attribute.
Vector lambda(mesh->attributes.Max());
lambda = 1.0;
PWConstCoefficient lambda_func(lambda);
Vector mu(mesh->attributes.Max());
mu = 1.0;
PWConstCoefficient mu_func(mu);
BilinearForm *a = new BilinearForm(fespace);
a->AddDomainIntegrator(new ElasticityIntegrator(lambda_func, mu_func));
// 9. Assemble the bilinear form and the corresponding linear system,
// applying any necessary transformations such as: eliminating boundary
// conditions, applying conforming constraints for non-conforming AMR,
// static condensation, etc.
a->Assemble();
SparseMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
cout << "done." << endl;
cout << "Size of linear system: " << A.Height() << endl;
// 10. Set up constraint matrix to constrain normal displacement (but
// allow tangential displacement) on specified boundaries.
Array<int> constraint_atts(2);
constraint_atts[0] = 1; // attribute 1 bottom
constraint_atts[1] = 4; // attribute 4 left side
Array<int> lagrange_rowstarts;
SparseMatrix* local_constraints =
BuildNormalConstraints(*fespace, constraint_atts, lagrange_rowstarts);
// 11. Define and apply an iterative solver for the constrained system
// in saddle-point form with a Gauss-Seidel smoother for the
// displacement block.
GSSmoother M(A);
SchurConstrainedSolver * solver =
new SchurConstrainedSolver(A, *local_constraints, M);
solver->SetRelTol(1e-5);
solver->SetMaxIter(2000);
solver->SetPrintLevel(1);
solver->Mult(B, X);
// 12. Recover the solution as a finite element grid function. Move the
// mesh to reflect the displacement of the elastic body being
// simulated, for purposes of output.
a->RecoverFEMSolution(X, *b, x);
mesh->SetNodalFESpace(fespace);
GridFunction *nodes = mesh->GetNodes();
*nodes += x;
// 13. Save the refined mesh and the solution in VisIt format.
if (visit)
{
VisItDataCollection visit_dc("ex28", mesh);
visit_dc.SetLevelsOfDetail(4);
visit_dc.RegisterField("displacement", &x);
visit_dc.Save();
}
// 14. Save the displaced mesh and the inverted solution (which gives the
// backward displacements to the original grid). This output can be
// viewed later using GLVis: "glvis -m displaced.mesh -g sol.gf".
{
x *= -1; // sign convention for GLVis displacements
ofstream mesh_ofs("displaced.mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
ofstream sol_ofs("sol.gf");
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 15. Send the above data by socket to a GLVis server. Use the "n" and "b"
// keys in GLVis to visualize the displacements.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock.precision(8);
sol_sock << "solution\n" << *mesh << x << flush;
}
// 16. Free the used memory.
delete local_constraints;
delete solver;
delete a;
delete b;
if (fec)
{
delete fespace;
delete fec;
}
delete mesh;
return 0;
}
| 34.30597
| 80
| 0.618447
|
ajithvallabai
|
f8969197258efbec51f45e4510bdfccefbf47f61
| 1,350
|
cpp
|
C++
|
test/test_typed_test.cpp
|
ncihnegn/jctest
|
92139e9b6362c2cb1d252caba4a268a852652554
|
[
"MIT"
] | 38
|
2019-02-28T07:23:15.000Z
|
2021-11-22T14:08:00.000Z
|
test/test_typed_test.cpp
|
ncihnegn/jctest
|
92139e9b6362c2cb1d252caba4a268a852652554
|
[
"MIT"
] | 5
|
2019-04-13T21:37:03.000Z
|
2020-04-11T13:06:31.000Z
|
test/test_typed_test.cpp
|
ncihnegn/jctest
|
92139e9b6362c2cb1d252caba4a268a852652554
|
[
"MIT"
] | 4
|
2019-04-13T21:22:22.000Z
|
2020-07-13T20:09:13.000Z
|
#include <string.h>
#include <stdio.h>
#include "testutil.h"
// To test the testing framework /////////////
void GlobalTestSetup(); // to silence a warning
void GlobalTestSetup() {
printf("Setting up the test\n");
}
int GlobalTestTeardown(); // to silence a warning
int GlobalTestTeardown() {
printf("Verifying the the test\n");
return 0;
}
//////////////////////////////////////////////
struct TestClass1 {
int value;
int _pad;
TestClass1() : value(2) {}
};
struct TestClass2 {
int value;
int _pad;
TestClass2() : value(4) {}
};
//////////////////////////////////////////////
#if defined(USE_GTEST)
typedef ::testing::Types<TestClass1, TestClass2> TestTypes;
#else
typedef jc_test_type2<TestClass1, TestClass2> TestTypes;
#endif
TYPED_TEST_CASE(TypedTest, TestTypes);
//////////////////////////////////////////////
template<typename T>
class TypedTest : public jc_test_base_class
{
protected:
virtual void SetUp();
virtual void TearDown();
T instance;
};
template<typename T>
void TypedTest<T>::SetUp() {
}
template<typename T>
void TypedTest<T>::TearDown() {
}
TYPED_TEST(TypedTest, NonZero)
{
ASSERT_NE(0, TestFixture::instance.value);
}
TYPED_TEST(TypedTest, Even)
{
ASSERT_EQ(0, TestFixture::instance.value & 0x1);
}
//////////////////////////////////////////////
| 18.493151
| 63
| 0.586667
|
ncihnegn
|
f897961b41157b5c190c4a8a80a8199a2030e1c3
| 2,734
|
cpp
|
C++
|
src/StoneCold.3D.Game/GameCore.cpp
|
krck/StoneCold_3D
|
5661a96e5167922b0ba555714a6d337acdea48c5
|
[
"BSD-3-Clause"
] | null | null | null |
src/StoneCold.3D.Game/GameCore.cpp
|
krck/StoneCold_3D
|
5661a96e5167922b0ba555714a6d337acdea48c5
|
[
"BSD-3-Clause"
] | null | null | null |
src/StoneCold.3D.Game/GameCore.cpp
|
krck/StoneCold_3D
|
5661a96e5167922b0ba555714a6d337acdea48c5
|
[
"BSD-3-Clause"
] | null | null | null |
#include "GameCore.hpp"
using namespace StoneCold::Game;
//using namespace StoneCold::Resources;
GameCore::GameCore()
: _inputManager(InputManager())
, _windowManager(WindowManager())
{ };
bool GameCore::Initialize(const std::string& windowName) {
try {
if (_windowManager.Initialize(&_inputManager)) {
// Get the SDL_Renderer and setup the Engine
_windowManager.SetupWindow("StoneCold 3D", WINDOW_WIDTH, WINDOW_HEIGHT, false);
// Setup all the additional Managers in the correct order
// ...
// Setup the randomizer with a seed
std::srand(RNG_SEED);
//// Load all global Resources and create the basic States
//_simulation.CreateIntroState();
//_simulation.CreateGameState();
//_simulation.CreateMenuState();
//// Load a first Level and add it to the GameState
//_simulation.LoadLevel();
//// Push the first State to update and render
//auto firstState = _engine.GetState<IntroState>();
//_engine.PushState(firstState);
return true;
}
else {
return false;
}
}
catch (const std::exception & ex) {
std::cout << ex.what() << std::endl;
return false;
}
}
//
// Run the main Game-loop
//
int GameCore::Run() {
try {
const MouseClient mouse = MouseClient(MouseServer::GetInstance());
const KeyboardClient keyboard = KeyboardClient(KeyboardServer::GetInstance());
// Loop timer variables
uint64 timeStamp_new = GetTicks();
uint64 timeStamp_old = GetTicks();
uint64 frameTime = 0; // delta in ms
// FPS Counter variables
const uint8 frameTimeSize = 20;
auto frameTimes = std::array<uint64, frameTimeSize>();
uint64 frameCount = 0;
float averageFPS = 0.f;
// Start the main loop
while (!_windowManager.IsClosed())
{
timeStamp_new = GetTicks();
frameTime = timeStamp_new - timeStamp_old;
_windowManager.Clear();
// Handle Input
if (keyboard.IsKeyPressed(GLFW_KEY_A)) { std::cout << "A" << std::endl; }
if (keyboard.IsKeyPressed(GLFW_KEY_D)) { std::cout << "D" << std::endl; }
if (keyboard.IsKeyPressed(GLFW_KEY_W)) { std::cout << "W" << std::endl; }
if (keyboard.IsKeyPressed(GLFW_KEY_S)) { std::cout << "S" << std::endl; }
// Update Display-Screen and get Events
_windowManager.Update();
// FPS counter (average)
frameTimes[frameCount] = frameTime;
frameCount++;
if (frameCount == frameTimeSize) {
frameCount = 0;
averageFPS = 0.f;
for (uint8 i = 0; i < frameTimeSize; i++) { averageFPS += frameTimes[i]; }
averageFPS = 1000.f / (averageFPS / frameTimeSize);
std::cout << "FPS: " << (uint16)averageFPS << "\n";
}
timeStamp_old = timeStamp_new;
}
return 0;
}
catch (const std::exception & ex) {
std::cout << ex.what() << std::endl;
return -1;
}
}
| 26.288462
| 82
| 0.666057
|
krck
|
f8a085d06c69abbcb0c5afbf0d66bf04f7f7e40b
| 833
|
cpp
|
C++
|
rt/rt/solids/sky.cpp
|
DasNaCl/old-university-projects
|
af1c82afec4805ea672e0c353369035b394cb69d
|
[
"Apache-2.0"
] | null | null | null |
rt/rt/solids/sky.cpp
|
DasNaCl/old-university-projects
|
af1c82afec4805ea672e0c353369035b394cb69d
|
[
"Apache-2.0"
] | null | null | null |
rt/rt/solids/sky.cpp
|
DasNaCl/old-university-projects
|
af1c82afec4805ea672e0c353369035b394cb69d
|
[
"Apache-2.0"
] | null | null | null |
#include <rt/bbox.h>
#include <rt/intersection.h>
#include <rt/solids/sky.h>
namespace rt
{
Sky::Sky(CoordMapper* texMapper, Material* material)
: Solid(texMapper, material)
{
}
BBox Sky::getBounds() const
{
return BBox::full();
}
Intersection Sky::intersect(const Ray& ray, float previousBestDistance) const
{
if(previousBestDistance < std::numeric_limits<float>::infinity() &&
previousBestDistance != FLT_MAX)
return Intersection::failure();
return Intersection(std::numeric_limits<float>::infinity(), ray, this, ray.d,
Point::rep(std::numeric_limits<float>::infinity()));
}
Solid::Sample Sky::sample() const
{
const auto inv = Point::rep(std::numeric_limits<float>::infinity());
return { inv, inv - Point::rep(0.f) };
}
float Sky::getArea() const
{
return std::numeric_limits<float>::infinity();
}
}
| 23.8
| 79
| 0.70108
|
DasNaCl
|
f8a12320e7923737dd065eb25132e17ffc5a46dd
| 1,353
|
hpp
|
C++
|
ntree/hashentry.hpp
|
degarashi/boomstick
|
55dc5bfcfad6119d8401f578f91df7bbd44c192b
|
[
"MIT"
] | 1
|
2015-06-14T15:54:27.000Z
|
2015-06-14T15:54:27.000Z
|
ntree/hashentry.hpp
|
degarashi/boomstick
|
55dc5bfcfad6119d8401f578f91df7bbd44c192b
|
[
"MIT"
] | null | null | null |
ntree/hashentry.hpp
|
degarashi/boomstick
|
55dc5bfcfad6119d8401f578f91df7bbd44c192b
|
[
"MIT"
] | null | null | null |
#pragma once
#include "ntree.hpp"
namespace boom {
namespace ntree {
//! ハッシュマップによるエントリ実装
/*! \tparam Ent エントリクラス
\tparam NDiv 分割度
\tparam NL 次元数(2 or 3) */
template <class Ent, int NDiv, int Dim>
class CTEnt_Hash : public CTEnt_Base<NDiv,Dim> {
public:
using Entry = Ent;
private:
using ObjHash = std::unordered_map<MortonId, Entry>;
ObjHash _ent;
public:
CTEnt_Hash() {
// ルートノードだけは作成しておく
_ent[0];
}
bool hasEntry(MortonId n) const {
return _ent.count(n) == 1;
}
const Entry& getEntry(MortonId n) const {
return _ent.at(n);
}
Entry& refEntry(MortonId n) {
return _ent[n];
}
void remEntry(MortonId n) {
auto itr = _ent.find(n);
AssertP(Trap, itr->second.isEmpty())
if(n != 0)
_ent.erase(itr);
}
void increment(MortonId num) {
AssertP(Trap, _ent[num].getLowerCount() >= 0)
_ent[num].incrementLowerCount();
}
void decrement(MortonId num) {
// カウンタが0になったらエントリを削除 (ルートは消さない)
auto itr = _ent.find(num);
AssertP(Trap, itr!=_ent.end() && itr->second.getLowerCount()>0)
itr->second.decrementLowerCount();
if(itr->second.isEmpty() && num!=0) {
AssertP(Trap, itr->second.getObjList().empty())
_ent.erase(itr);
}
}
void clear() {
_ent.clear();
}
};
}
}
| 23.736842
| 68
| 0.593496
|
degarashi
|
f8a6e2740e2576bef26f842ac1bb9aaa0692e661
| 435
|
hpp
|
C++
|
src/world/timer.hpp
|
ComLarsic/FinishTheGame_Rayjam
|
a5ddb7af9c0c4fd285cad26b13f9b58440fe3a89
|
[
"MIT"
] | null | null | null |
src/world/timer.hpp
|
ComLarsic/FinishTheGame_Rayjam
|
a5ddb7af9c0c4fd285cad26b13f9b58440fe3a89
|
[
"MIT"
] | null | null | null |
src/world/timer.hpp
|
ComLarsic/FinishTheGame_Rayjam
|
a5ddb7af9c0c4fd285cad26b13f9b58440fe3a89
|
[
"MIT"
] | null | null | null |
#pragma once
/** Represents the game tumer */
class Timer {
public:
Timer();
~Timer();
/** Tick the timer */
void Tick();
/** Set the timer */
void Set(int minutes, int seconds);
/** Add time to the timer */
void Add(int minutes, int seconds);
/** Display the game timer */
void Draw();
/** Check if the timer is over */
bool IsOver();
private:
int _minutes;
float _seconds;
};
| 19.772727
| 39
| 0.572414
|
ComLarsic
|
f8a8f59476c5abb81b72122783847f8e1da98b0a
| 7,008
|
cxx
|
C++
|
TivaWare/third_party/windows/fltk-1.1.10/src/Fl_Menu_.cxx
|
bumblebee96/pacman
|
1b82f1747765e807bef3040e4dac72c744fc3bc1
|
[
"MIT"
] | 25
|
2015-04-20T13:03:05.000Z
|
2022-01-06T07:25:02.000Z
|
TivaWare/third_party/windows/fltk-1.1.10/src/Fl_Menu_.cxx
|
bumblebee96/pacman
|
1b82f1747765e807bef3040e4dac72c744fc3bc1
|
[
"MIT"
] | 1
|
2021-03-21T03:00:58.000Z
|
2021-03-22T10:05:45.000Z
|
TivaWare/third_party/windows/fltk-1.1.10/src/Fl_Menu_.cxx
|
bumblebee96/pacman
|
1b82f1747765e807bef3040e4dac72c744fc3bc1
|
[
"MIT"
] | 24
|
2015-09-22T12:08:11.000Z
|
2021-12-30T10:17:30.000Z
|
//
// "$Id: Fl_Menu_.cxx 5190 2006-06-09 16:16:34Z mike $"
//
// Common menu code for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2005 by Bill Spitzak and others.
//
// 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.
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
// This is a base class for all items that have a menu:
// Fl_Menu_Bar, Fl_Menu_Button, Fl_Choice
// This provides storage for a menu item, functions to add/modify/delete
// items, and a call for when the user picks a menu item.
// More code in Fl_Menu_add.cxx
#include <FL/Fl.H>
#include <FL/Fl_Menu_.H>
#include "flstring.h"
#include <stdio.h>
#include <stdlib.h>
// Set 'pathname' of specified menuitem
// If finditem==NULL, mvalue() is used (the most recently picked menuitem)
// Returns:
// 0 : OK
// -1 : item not found (name="")
// -2 : 'name' not large enough (name="")
//
#define SAFE_STRCAT(s) \
{ len += strlen(s); if ( len >= namelen ) { *name='\0'; return(-2); } else strcat(name,(s)); }
int Fl_Menu_::item_pathname(char *name, int namelen, const Fl_Menu_Item *finditem) const {
int len = 0;
finditem = finditem ? finditem : mvalue();
name[0] = '\0';
for ( int t=0; t<size(); t++ ) {
const Fl_Menu_Item *m = &(menu()[t]);
if ( m->submenu() ) { // submenu? descend
if (*name) SAFE_STRCAT("/");
if (m->label()) SAFE_STRCAT(m->label());
} else {
if (m->label()) { // menu item?
if ( m == finditem ) { // found? tack on itemname, done.
SAFE_STRCAT("/");
SAFE_STRCAT(m->label());
return(0);
}
} else { // end of submenu? pop
char *ss = strrchr(name, '/');
if ( ss ) { *ss = 0; len = strlen(name); } // "File/Edit" -> "File"
else { name[0] = '\0'; len = 0; } // "File" -> ""
continue;
}
}
}
*name = '\0';
return(-1); // item not found
}
// FIND MENU ITEM INDEX, GIVEN MENU PATHNAME
// eg. "Edit/Copy"
// Will also return submenus, eg. "Edit"
// Returns NULL if not found.
//
const Fl_Menu_Item *
Fl_Menu_::find_item(const char *name)
{
char menupath[1024] = ""; // File/Export
for ( int t=0; t < size(); t++ ) {
Fl_Menu_Item *m = menu_ + t;
if (m->flags&FL_SUBMENU) {
// IT'S A SUBMENU
// we do not support searches through FL_SUBMENU_POINTER links
if (menupath[0]) strlcat(menupath, "/", sizeof(menupath));
strlcat(menupath, m->label(), sizeof(menupath));
if (!strcmp(menupath, name)) return m;
} else {
if (!m->label()) {
// END OF SUBMENU? Pop back one level.
char *ss = strrchr(menupath, '/');
if ( ss ) *ss = 0;
else menupath[0] = '\0';
continue;
}
// IT'S A MENU ITEM
char itempath[1024]; // eg. Edit/Copy
strcpy(itempath, menupath);
if (itempath[0]) strlcat(itempath, "/", sizeof(itempath));
strlcat(itempath, m->label(), sizeof(itempath));
if (!strcmp(itempath, name)) return m;
}
}
return (const Fl_Menu_Item *)0;
}
int Fl_Menu_::value(const Fl_Menu_Item* m) {
clear_changed();
if (value_ != m) {value_ = m; return 1;}
return 0;
}
// When user picks a menu item, call this. It will do the callback.
// Unfortunatly this also casts away const for the checkboxes, but this
// was necessary so non-checkbox menus can really be declared const...
const Fl_Menu_Item* Fl_Menu_::picked(const Fl_Menu_Item* v) {
if (v) {
if (v->radio()) {
if (!v->value()) { // they are turning on a radio item
set_changed();
((Fl_Menu_Item*)v)->setonly();
}
redraw();
} else if (v->flags & FL_MENU_TOGGLE) {
set_changed();
((Fl_Menu_Item*)v)->flags ^= FL_MENU_VALUE;
redraw();
} else if (v != value_) { // normal item
set_changed();
}
value_ = v;
if (when()&(FL_WHEN_CHANGED|FL_WHEN_RELEASE)) {
if (changed() || when()&FL_WHEN_NOT_CHANGED) {
if (value_ && value_->callback_) value_->do_callback((Fl_Widget*)this);
else do_callback();
}
}
}
return v;
}
// turn on one of a set of radio buttons
void Fl_Menu_Item::setonly() {
flags |= FL_MENU_RADIO | FL_MENU_VALUE;
Fl_Menu_Item* j;
for (j = this; ; ) { // go down
if (j->flags & FL_MENU_DIVIDER) break; // stop on divider lines
j++;
if (!j->text || !j->radio()) break; // stop after group
j->clear();
}
for (j = this-1; ; j--) { // go up
if (!j->text || (j->flags&FL_MENU_DIVIDER) || !j->radio()) break;
j->clear();
}
}
Fl_Menu_::Fl_Menu_(int X,int Y,int W,int H,const char* l)
: Fl_Widget(X,Y,W,H,l) {
set_flag(SHORTCUT_LABEL);
box(FL_UP_BOX);
when(FL_WHEN_RELEASE_ALWAYS);
value_ = menu_ = 0;
alloc = 0;
selection_color(FL_SELECTION_COLOR);
textfont(FL_HELVETICA);
textsize((uchar)FL_NORMAL_SIZE);
textcolor(FL_FOREGROUND_COLOR);
down_box(FL_NO_BOX);
}
int Fl_Menu_::size() const {
if (!menu_) return 0;
return menu_->size();
}
void Fl_Menu_::menu(const Fl_Menu_Item* m) {
clear();
value_ = menu_ = (Fl_Menu_Item*)m;
}
// this version is ok with new Fl_Menu_add code with fl_menu_array_owner:
void Fl_Menu_::copy(const Fl_Menu_Item* m, void* ud) {
int n = m->size();
Fl_Menu_Item* newMenu = new Fl_Menu_Item[n];
memcpy(newMenu, m, n*sizeof(Fl_Menu_Item));
menu(newMenu);
alloc = 1; // make destructor free array, but not strings
// for convienence, provide way to change all the user data pointers:
if (ud) for (; n--;) {
if (newMenu->callback_) newMenu->user_data_ = ud;
newMenu++;
}
}
Fl_Menu_::~Fl_Menu_() {
clear();
}
// Fl_Menu::add() uses this to indicate the owner of the dynamically-
// expanding array. We must not free this array:
Fl_Menu_* fl_menu_array_owner = 0;
void Fl_Menu_::clear() {
if (alloc) {
if (alloc>1) for (int i = size(); i--;)
if (menu_[i].text) free((void*)menu_[i].text);
if (this == fl_menu_array_owner)
fl_menu_array_owner = 0;
else
delete[] menu_;
menu_ = 0;
value_ = 0;
alloc = 0;
}
}
//
// End of "$Id: Fl_Menu_.cxx 5190 2006-06-09 16:16:34Z mike $".
//
| 30.077253
| 99
| 0.60117
|
bumblebee96
|
f8b59b44718cd2acb8e291ab8d87881e209617c8
| 1,518
|
cpp
|
C++
|
LeetCode/ThousandOne/0682-baseball_game.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandOne/0682-baseball_game.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandOne/0682-baseball_game.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
#include "leetcode.hpp"
/* 682. 棒球比赛
你现在是棒球比赛记录员。
给定一个字符串列表,每个字符串可以是以下四种类型之一:
1.整数(一轮的得分):直接表示您在本轮中获得的积分数。
2. "+"(一轮的得分):表示本轮获得的得分是前两轮有效 回合得分的总和。
3. "D"(一轮的得分):表示本轮获得的得分是前一轮有效 回合得分的两倍。
4. "C"(一个操作,这不是一个回合的分数):表示您获得的最后一个有效 回合的分数是无效的,应该被移除。
每一轮的操作都是永久性的,可能会对前一轮和后一轮产生影响。
你需要返回你在所有回合中得分的总和。
示例 1:
输入: ["5","2","C","D","+"]
输出: 30
解释:
第1轮:你可以得到5分。总和是:5。
第2轮:你可以得到2分。总和是:7。
操作1:第2轮的数据无效。总和是:5。
第3轮:你可以得到10分(第2轮的数据已被删除)。总数是:15。
第4轮:你可以得到5 + 10 = 15分。总数是:30。
示例 2:
输入: ["5","-2","4","C","D","9","+","+"]
输出: 27
解释:
第1轮:你可以得到5分。总和是:5。
第2轮:你可以得到-2分。总数是:3。
第3轮:你可以得到4分。总和是:7。
操作1:第3轮的数据无效。总数是:3。
第4轮:你可以得到-4分(第三轮的数据已被删除)。总和是:-1。
第5轮:你可以得到9分。总数是:8。
第6轮:你可以得到-4 + 9 = 5分。总数是13。
第7轮:你可以得到9 + 5 = 14分。总数是27。
注意:
输入列表的大小将介于1和1000之间。
列表中的每个整数都将介于-30000和30000之间。
*/
int calPoints(vector<string>& ops)
{
int sum = 0;
vector<int> scores;
scores.reserve(ops.size());
for (string const& p : ops)
{
if (p == "C")
{
sum -= scores.back();
scores.pop_back();
}
else if (p == "D")
{
int t = scores.back() * 2;
scores.push_back(t);
sum += t;
}
else if (p == "+")
{
size_t len = scores.size();
int t = scores[len - 1] + scores[len - 2];
scores.push_back(t);
sum += t;
}
else
{
int t;
sscanf(p.c_str(), "%d", &t);
scores.push_back(t);
sum += t;
}
}
return sum;
}
int main()
{
vector<string> ops1 = { "5", "2", "C", "D", "+" };
vector<string> ops2 = { "5", "-2", "4", "C", "D", "9", "+", "+" };
OutExpr(calPoints(ops1), "%d");
OutExpr(calPoints(ops2), "%d");
}
| 17.25
| 67
| 0.589592
|
Ginkgo-Biloba
|
f8b5f363224aafce2447cb956d9a6a3f4838c93e
| 2,192
|
cpp
|
C++
|
Extensions/ZilchShaders/CodeRangeMapping.cpp
|
RachelWilSingh/ZeroCore
|
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
|
[
"MIT"
] | 52
|
2018-09-11T17:18:35.000Z
|
2022-03-13T15:28:21.000Z
|
Extensions/ZilchShaders/CodeRangeMapping.cpp
|
RachelWilSingh/ZeroCore
|
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
|
[
"MIT"
] | 1,409
|
2018-09-19T18:03:43.000Z
|
2021-06-09T08:33:33.000Z
|
Extensions/ZilchShaders/CodeRangeMapping.cpp
|
RachelWilSingh/ZeroCore
|
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
|
[
"MIT"
] | 26
|
2018-09-11T17:16:32.000Z
|
2021-11-22T06:21:19.000Z
|
///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Davis
/// Copyright 2015, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
//-------------------------------------------------------------------CodeRangeMapping
CodeRangeMapping::CodeRangeMapping()
{
mSourcePositionStart = 0;
mSourcePositionEnd = 0;
mDestPositionStart = 0;
mDestPositionEnd = 0;
mIsRoot = false;
}
void CodeRangeMapping::Set(Zilch::CodeLocation& sourceLocation)
{
mSourcePositionStart = sourceLocation.StartPosition;
mSourcePositionEnd = sourceLocation.EndPosition;
mSourceFile = sourceLocation.Origin;
}
//-------------------------------------------------------------------ScopedRangeMapping
ScopedRangeMapping::ScopedRangeMapping(ShaderCodeBuilder& builder, CodeRangeMapping* parent, Zilch::CodeLocation* zilchLocation, bool generateRanges, StringParam debugStr)
{
mGenerateRanges = generateRanges;
if(!mGenerateRanges)
return;
mBuilder = &builder;
mTotalOffset = builder.GetSize();
mParentTotalOffset = 0;
mRange = &parent->mChildren.PushBack();
mRange->mDestPositionStart = mTotalOffset;
mRange->mDebugString = debugStr;
}
ScopedRangeMapping::ScopedRangeMapping(ShaderCodeBuilder& builder, ScopedRangeMapping* parent, CodeRangeMapping* rangeToCopy, Zilch::CodeLocation* zilchLocation, bool generateRanges, StringParam debugStr)
{
mGenerateRanges = generateRanges;
if(!mGenerateRanges)
return;
mBuilder = &builder;
mParentTotalOffset = parent->mTotalOffset;
mTotalOffset = builder.GetSize();
mRange = &parent->mRange->mChildren.PushBack();
if(rangeToCopy)
*mRange = *rangeToCopy;
mRange->mDestPositionStart = builder.GetSize() - parent->mTotalOffset;
if(zilchLocation)
mRange->Set(*zilchLocation);
mRange->mDebugString = debugStr;
}
ScopedRangeMapping::~ScopedRangeMapping()
{
if(!mGenerateRanges)
return;
mRange->mDestPositionEnd = mBuilder->GetSize() - mParentTotalOffset;
}
}//namespace Zero
| 29.621622
| 205
| 0.635036
|
RachelWilSingh
|
f8be55bece8a975d5d896358b1dff13a14fb954c
| 715
|
cpp
|
C++
|
src/Shared/Utils/Observer.cpp
|
Marukyu/NecroEdit
|
4b2380cc3417c6578476a213e05f4cbc846e5a77
|
[
"MIT",
"Unlicense"
] | 13
|
2016-04-02T14:21:49.000Z
|
2021-01-10T17:32:43.000Z
|
src/Shared/Utils/Observer.cpp
|
Marukyu/NecroEdit
|
4b2380cc3417c6578476a213e05f4cbc846e5a77
|
[
"MIT",
"Unlicense"
] | 24
|
2016-04-02T12:08:39.000Z
|
2021-01-27T01:21:58.000Z
|
src/Shared/Utils/Observer.cpp
|
Marukyu/NecroEdit
|
4b2380cc3417c6578476a213e05f4cbc846e5a77
|
[
"MIT",
"Unlicense"
] | 6
|
2016-04-02T12:05:28.000Z
|
2017-05-10T14:13:39.000Z
|
#include "Shared/Utils/Observer.hpp"
Observer::~Observer()
{
while (!mySubjects.empty())
{
(*mySubjects.begin())->removeObserver(this);
}
}
Observable::~Observable()
{
while (!myObservers.empty())
{
removeObserver(*myObservers.begin());
}
}
void Observable::addObserver(Observer* observer)
{
myObservers.insert(observer);
observer->mySubjects.insert(this);
}
void Observable::removeObserver(Observer* observer)
{
myObservers.erase(observer);
observer->mySubjects.erase(this);
}
bool Observable::isObserving(Observer* observer) const
{
return myObservers.count(observer);
}
void Observable::notify(int message)
{
for (auto observer : myObservers)
{
observer->onNotify(*this, message);
}
}
| 16.25
| 54
| 0.723077
|
Marukyu
|
f8c05003e5ea6b242a520651c161b3c4edf0b049
| 98,404
|
cpp
|
C++
|
STrenD/TrendHeatmapWindow.cpp
|
RoysamLab/STrend
|
1e8d84adfb28c0a2ea78d311daeac6afd04bc275
|
[
"BSD-4-Clause-UC"
] | null | null | null |
STrenD/TrendHeatmapWindow.cpp
|
RoysamLab/STrend
|
1e8d84adfb28c0a2ea78d311daeac6afd04bc275
|
[
"BSD-4-Clause-UC"
] | null | null | null |
STrenD/TrendHeatmapWindow.cpp
|
RoysamLab/STrend
|
1e8d84adfb28c0a2ea78d311daeac6afd04bc275
|
[
"BSD-4-Clause-UC"
] | null | null | null |
#include "TrendHeatmapWindow.h"
#define pi 3.1415926
#define POWER_PARAM 0.2
TrendHeatmapWindow::TrendHeatmapWindow(const QString title, QWidget *parent)
: QMainWindow(parent)
{
this->mainQTRenderWidget;
this->view = NULL;
this->theme = NULL;
this->graph_Layout = NULL;
this->aPlane = NULL;
this->cellData = NULL;
this->celllut = NULL;
this->mapper = NULL;
this->actor = NULL;
this->v = NULL;
this->points = NULL;
this->vertexColors = NULL;
this->vetexlut = NULL;
this->myCellPicker = NULL;
this->ids1 = vtkSmartPointer<vtkIdTypeArray>::New();
this->ids2 = vtkSmartPointer<vtkIdTypeArray>::New();
this->ids1->SetNumberOfComponents(1);
this->ids2->SetNumberOfComponents(1);
this->dencolors1 = vtkSmartPointer<vtkUnsignedCharArray>::New();
this->denpoints1 = vtkSmartPointer<vtkPoints>::New();
this->denlines1 = vtkSmartPointer<vtkCellArray>::New();
this->denlinesPolyData1 =vtkSmartPointer<vtkPolyData>::New();
this->denmapper1 = vtkSmartPointer<vtkPolyDataMapper>::New();
this->denactor1 = vtkSmartPointer<vtkActor>::New();
this->dencolors2 = vtkSmartPointer<vtkUnsignedCharArray>::New();
this->denpoints2 = vtkSmartPointer<vtkPoints>::New();
this->denlines2 = vtkSmartPointer<vtkCellArray>::New();
this->denlinesPolyData2 =vtkSmartPointer<vtkPolyData>::New();
this->denmapper2 = vtkSmartPointer<vtkPolyDataMapper>::New();
this->denactor2 = vtkSmartPointer<vtkActor>::New();
this->removeActorflag = 0;
this->denResetflag1 = 0;
this->denResetflag2 = 0;
this->continueselectnum = 0;
this->continueselect = false;
this->intersectionselect = false;
this->clusflag = false;
this->mapdata = NULL;
this->Optimal_Leaf_Order1 = NULL;
this->Optimal_Leaf_Order2 = NULL;
this->connect_Data_Tree1 = NULL;
this->connect_Data_Tree2 = NULL;
this->ftreedata = NULL;
setWindowTitle(title);
}
TrendHeatmapWindow::~TrendHeatmapWindow()
{
if(this->mapdata)
{
for(int i=0; i<num_samples; i++)
delete this->mapdata[i];
delete this->mapdata;
}
if(this->Optimal_Leaf_Order1)
delete this->Optimal_Leaf_Order1;
if(this->Optimal_Leaf_Order2)
delete this->Optimal_Leaf_Order2;
if(this->connect_Data_Tree1)
for(int i = 0; i<this->num_samples - 1; i++)
delete this->connect_Data_Tree1[i];
delete this->connect_Data_Tree1;
if(this->connect_Data_Tree2)
for(int i = 0; i<this->num_features - 1; i++)
delete this->connect_Data_Tree2[i];
delete this->connect_Data_Tree2;
if(ftreedata)
{
for( int i = 0; i < this->table->GetNumberOfRows() - 1; i++)
{
delete ftreedata[i];
}
delete ftreedata;
}
}
void TrendHeatmapWindow::setDataForHeatmap(double** features, int* optimalleaforder1, int* optimalleaforder2,int num_samples, int num_features)
{
this->num_samples = num_samples;
this->num_features = num_features;
this->rowMapFromOriginalToReorder.clear();
this->columnMapFromOriginalToReorder.clear();
this->mapdata = new double*[num_samples];
for(int i=0; i<num_samples; i++)
{
this->mapdata[i] = new double[num_features];
for(int j = 0 ; j<num_features; j++)
this->mapdata[i][j] = features[i][j];
}
this->Optimal_Leaf_Order1 = new int[num_samples] ;
for(int i=0; i<num_samples; i++)
{
this->Optimal_Leaf_Order1[i] = optimalleaforder1[i];
this->rowMapFromOriginalToReorder.insert( std::pair< int, int>(optimalleaforder1[i], i));
}
this->Optimal_Leaf_Order2 = new int[num_features];
for(int i=0; i<num_features; i++)
{
this->Optimal_Leaf_Order2[i] = optimalleaforder2[i];
this->columnMapFromOriginalToReorder.insert( std::pair< int, int>(optimalleaforder2[i], i));
}
}
void TrendHeatmapWindow::creatDataForHeatmap(double powCof)
{
//double** mustd = new double*[2];
//mustd[0] = new double[107];
//mustd[1] = new double[107];
//this->readmustd(mustd);
//this->scaleData(mustd);
this->scaleData();
std::vector< double > temp;
temp.resize(num_features);
double** tempdata;
tempdata = new double*[this->num_samples];
for(int i = 0; i < this->num_samples; i++)
tempdata[i] = new double[this->num_features];
for(int i = 0; i < this->num_samples; i++)
{
double mean = 0.0;
double std = 0.0;
double sum = 0.0;
for(int j = 0; j < this->num_features; j++)
{
temp[j] = mapdata[i][Optimal_Leaf_Order2[j]];
}
for(int j = 0; j < this->num_features; j++)
tempdata[i][j] = temp[j];
}
for(int i = 0; i < this->num_samples; i++)
mapdata[this->num_samples - i - 1] = tempdata[Optimal_Leaf_Order1[i]];
//const char* filename = "mapdata.txt";
//FILE *fp1 = fopen(filename,"w");
//for(int i=0; i<num_samples; i++)
//{
// for(int j=0; j<num_features; j++)
// fprintf(fp1,"%f\t",mapdata[i][j]);
// fprintf(fp1,"\n");
//}
//fclose(fp1);
if( this->connect_Data_Tree1 != NULL)
{
this->createDataForDendogram1(powCof);
}
if( this->connect_Data_Tree2 != NULL)
{
this->createDataForDendogram2(powCof);
}
else
{
this->createDataForDendogram2();
}
}
void TrendHeatmapWindow::scaleData()
{
for(int i = 0; i<this->num_features; i++)
{
double mean = 0.0;
double std = 0.0;
double sum = 0.0;
for(int j = 0; j<this->num_samples; j++)
mean += mapdata[j][i];
mean /= this->num_samples;
for(int j = 0; j<this->num_samples; j++)
sum += (mapdata[j][i] - mean) * (mapdata[j][i] - mean);
std = sqrt(sum/this->num_samples);
if(std)
for(int j = 0; j<this->num_samples; j++)
mapdata[j][i] = (mapdata[j][i] - mean)/std;
else
for(int j = 0; j<this->num_samples; j++)
mapdata[j][i] = 0;
}
}
void TrendHeatmapWindow::scaleData(double** mustd)
{
for(int i = 0; i<this->num_features; i++)
{
if(mustd[1][i+1])
for(int j = 0; j<this->num_samples; j++)
mapdata[j][Optimal_Leaf_Order2[i]] = (mapdata[j][Optimal_Leaf_Order2[i]] - mustd[0][i+1])/mustd[1][i+1];
else
for(int j = 0; j<this->num_samples; j++)
mapdata[j][i] = 0;
}
}
void TrendHeatmapWindow::readmustd(double** mustd)
{
double temp[107];
const int MAXLINESIZE = 10024;
char line[MAXLINESIZE];
ifstream infile;
infile.open("mustd.txt");
if(infile.is_open())
{
int i = 0;
for(int t = 0 ;t<2; t++)
{
infile.getline(line, MAXLINESIZE);
char* pch = strtok(line, "\t");
int k = 0;
while(pch)
{
temp[k++] = atof(pch);
pch = strtok(NULL, "\t");
}
for(int j = 0; j<107; j++)
mustd[i][j] = temp[j];
i++;
}
}
infile.close();
for(int i=0; i<2 ;i++)
{
for(int j = 0; j<107; j++)
cout<<mustd[i][j]<<"\t";
cout<<endl;
}
}
void TrendHeatmapWindow::setModels(vtkSmartPointer<vtkTable> table, ObjectSelection * sels, ObjectSelection * sels2)
{
this->table = table;
this->indMapFromVertexToInd.clear();
this->indMapFromIndToVertex.clear();
if( this->table)
{
for( int i = 0; i < this->table->GetNumberOfRows(); i++)
{
int var = this->table->GetValue( i, 0).ToInt();
this->indMapFromVertexToInd.insert( std::pair< int, int>(var, i));
this->indMapFromIndToVertex.push_back( var);
}
}
if(!sels)
this->Selection = new ObjectSelection();
else
this->Selection = sels;
if(!sels2)
this->Selection2 = new ObjectSelection();
else
this->Selection2 = sels2;
connect(Selection, SIGNAL(changed()), this, SLOT(GetSelecectedIDs()));
}
void TrendHeatmapWindow::runClusclus()
{
double** datas;
vtkVariant temp;
datas = new double*[this->table->GetNumberOfRows()];
std::cout<<"number of rows"<<this->table->GetNumberOfRows()<<endl;
std::cout<<"number of columns"<<this->table->GetNumberOfColumns()<<endl;
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
datas[i] = new double[this->table->GetNumberOfColumns() - 1 + 2 ];
}
for(int i = 0; i < this->table->GetNumberOfRows(); i++)
{
for(int j = 1; j < this->table->GetNumberOfColumns(); j++)
{
temp = this->table->GetValue(i, j);
datas[i][j-1] = temp.ToDouble();
}
}
cc1 = new clusclus(datas, (int)this->table->GetNumberOfRows(), (int)this->table->GetNumberOfColumns() - 1);
cc1->Transpose();
cc2 = new clusclus(cc1->transposefeatures,cc1->num_features, cc1->num_samples);
#pragma omp parallel sections
{
#pragma omp section
{
cc1->RunClusClus();
/*cc1->WriteClusteringOutputToFile("mergers.txt","features.txt","progress.txt", "members.txt",
"gap.txt", "treedata.txt", "Optimalleaforder.txt");*/
}
#pragma omp section
{
cc2->RunClusClus();
/*cc2->WriteClusteringOutputToFile("mergers2.txt","features2.txt","progress2.txt", "members2.txt",
"gap2.txt", "treedata2.txt", "Optimalleaforder2.txt");*/
}
}
cout<<"finish clusclus....."<<endl;
this->setDataForHeatmap(cc1->features, cc1->optimalleaforder, cc2->optimalleaforder,cc1->num_samples, cc2->num_samples);
this->setDataForDendrograms(cc1->treedata, cc2->treedata);
this->creatDataForHeatmap(POWER_PARAM);
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
delete datas[i];
}
delete datas;
delete cc1;
delete cc2;
}
void TrendHeatmapWindow::runClus()
{
this->clusflag = true;
double** datas;
vtkVariant temp;
datas = new double*[this->table->GetNumberOfRows()];
std::cout<<this->table->GetNumberOfRows()<<endl;
std::cout<<this->table->GetNumberOfColumns()<<endl;
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
datas[i] = new double[this->table->GetNumberOfColumns() - 1 + 2 ];
}
for(int i = 0; i < this->table->GetNumberOfRows(); i++)
{
for(int j = 1; j < this->table->GetNumberOfColumns(); j++)
{
temp = this->table->GetValue(i, j);
datas[i][j-1] = temp.ToDouble();
}
}
cc1 = new clusclus(datas, (int)this->table->GetNumberOfRows(), (int)this->table->GetNumberOfColumns() - 1);
cc1->RunClusClus();
cout<<"finish clusclus....."<<endl;
cout<<this->table->GetNumberOfRows();
cout<<this->table->GetNumberOfColumns();
cc1->WriteClusteringOutputToFile("mergers.txt","features.txt","progress.txt", "members.txt", "gap.txt", "treedata.txt", "Optimalleaforder.txt");
int* optimalleaforder2 = new int[cc1->num_features];
for(int i = 0;i<cc1->num_features; i++)
optimalleaforder2[i]=i;
this->setDataForHeatmap(cc1->features, cc1->optimalleaforder, optimalleaforder2,cc1->num_samples, cc1->num_features);
this->setDataForDendrograms(cc1->treedata);
this->creatDataForHeatmap(POWER_PARAM);
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
delete datas[i];
}
delete datas;
delete cc1;
}
void TrendHeatmapWindow::showGraph()
{
if(this->clusflag == true)
this->drawPoints3();
else
this->drawPoints1();
this->aPlane = vtkSmartPointer<vtkPlaneSource>::New();
this->aPlane->SetXResolution(this->num_features);
this->aPlane->SetYResolution(this->num_samples);
this->cellData = vtkSmartPointer<vtkFloatArray>::New();
int index = 0;
for (int i = 0; i < this->num_samples; i++)
{
for(int j = 0; j < this->num_features; j++)
{
cellData->InsertNextValue(index++);
}
}
this->celllut = vtkSmartPointer<vtkLookupTable>::New();
this->celllut->SetNumberOfTableValues(this->num_samples*this->num_features);
this->celllut->SetTableRange(0, this->num_samples*this->num_features - 1);
this->celllut->Build();
//int k = 0;
//boost::math::normal N;
//try
//{
// for(int i = 0; i < this->num_samples; i++)
// {
// for(int j = 0; j < this->num_features; j++)
// {
// if(mapdata[num_samples - i - 1][j] < 0)
// celllut->SetTableValue(k++, 0, 1 - cdf(N,mapdata[num_samples - i - 1][j]), 0);
// else if(mapdata[num_samples - i - 1][j] > 0)
// celllut->SetTableValue(k++, cdf(N,mapdata[num_samples - i - 1][j]), 0, 0);
// else
// celllut->SetTableValue(k++, 0, 0, 0);
// }
// }
//}
//catch(...)
//{
// cout<<"Boost call failed! please try again!"<<endl;
//}
int k = 0;
for(int i = 0; i < this->num_samples; i++)
{
for(int j = 0; j < this->num_features; j++)
{
rgb rgb = GetRGBValue( mapdata[num_samples - i - 1][j]);
celllut->SetTableValue(k++, rgb.r, rgb.g, rgb.b);
}
}
this->aPlane->Update();
this->aPlane->GetOutput()->GetCellData()->SetScalars(cellData);
this->mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
this->mapper->SetInputConnection(aPlane->GetOutputPort());
this->mapper->SetScalarRange(0, this->num_samples*this->num_features - 1);
this->mapper->SetLookupTable(celllut);
this->actor = vtkSmartPointer<vtkActor>::New();
this->actor->SetMapper(mapper);
vtkSmartPointer<vtkLookupTable> scalarbarLut = vtkSmartPointer<vtkLookupTable>::New();
scalarbarLut->SetTableRange (-1, 1);
scalarbarLut->SetNumberOfTableValues(COLOR_MAP_SIZE);
for(int index = 0; index<COLOR_MAP_SIZE;index++)
{
rgb rgbscalar = COLORMAP[index];
scalarbarLut->SetTableValue(index, rgbscalar.r, rgbscalar.g, rgbscalar.b);
}
scalarbarLut->Build();
vtkSmartPointer<vtkScalarBarActor> scalarBar = vtkSmartPointer<vtkScalarBarActor>::New();
scalarBar->SetLookupTable(scalarbarLut);
scalarBar->SetTitle("Color Map");
scalarBar->SetNumberOfLabels(10);
scalarBar->GetTitleTextProperty()->SetColor(0,0,0);
scalarBar->GetTitleTextProperty()->SetFontSize (10);
scalarBar->GetLabelTextProperty()->SetColor(0,0,0);
scalarBar->GetTitleTextProperty()->SetFontSize (10);
scalarBar->SetMaximumHeightInPixels(1000);
scalarBar->SetMaximumWidthInPixels(100);
this->view->GetRenderer()->AddActor(actor);
this->view->GetRenderer()->AddActor2D(scalarBar);
this->SetInteractStyle();
this->view->GetRenderer()->GradientBackgroundOff();
this->view->GetRenderer()->SetBackground(1,1,1);
try
{
if(this->clusflag == true)
this->showDendrogram1();
else
{
this->showDendrogram1();
this->showDendrogram2();
}
}
catch(...)
{
cout<<"Draw dendrogram failed ! Please try again!"<<endl;
}
this->view->Render();
this->view->GetInteractor()->Start();
}
void TrendHeatmapWindow::SetInteractStyle()
{
this->theme->SetCellValueRange(0, this->num_samples*this->num_features - 1);
this->theme->SetSelectedCellColor(1,0,1);
this->theme->SetSelectedPointColor(1,0,1);
this->view->ApplyViewTheme(theme);
this->myCellPicker = vtkSmartPointer<vtkCellPicker>::New();
this->view->GetInteractor()->SetPicker(this->myCellPicker);
this->myCellPicker->SetTolerance(0.004);
vtkSmartPointer<vtkCallbackCommand> selectionCallback2 =vtkSmartPointer<vtkCallbackCommand>::New();
selectionCallback2->SetClientData(this);
selectionCallback2->SetCallback(SelectionCallbackFunction2 );
vtkSmartPointer<vtkCallbackCommand> selectionCallback3 =vtkSmartPointer<vtkCallbackCommand>::New();
selectionCallback3->SetClientData(this);
selectionCallback3->SetCallback(SelectionCallbackFunction3);
this->keyPress = vtkSmartPointer<vtkCallbackCommand>::New();
this->keyPress->SetCallback(HandleKeyPress);
this->keyPress->SetClientData(this);
this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonPressEvent);
this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonReleaseEvent);
this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyPressEvent);
this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyReleaseEvent);
this->view->GetInteractor()->AddObserver(vtkCommand::RightButtonPressEvent, selectionCallback2);
this->view->GetInteractor()->AddObserver(vtkCommand::RightButtonReleaseEvent, selectionCallback3);
this->view->GetInteractor()->AddObserver(vtkCommand::KeyPressEvent, this->keyPress);
this->mainQTRenderWidget.SetRenderWindow(view->GetRenderWindow());
this->mainQTRenderWidget.resize(600, 600);
this->mainQTRenderWidget.show();
}
rgb TrendHeatmapWindow::GetRGBValue(double val)
{
int index = 64 * (val+1) - 1; // when val = 1; index should be the max index
if( index >= COLOR_MAP_SIZE)
{
index = COLOR_MAP_SIZE - 1;
}
else if( index < 0)
{
index = 0;
}
return COLORMAP[index];
}
void TrendHeatmapWindow::setDataForDendrograms(double** treedata1, double** treedata2)
{
if(treedata1 != NULL)
{
this->connect_Data_Tree1 = new double*[this->num_samples-1];
this->rowMapForTreeData.clear();
for(int i = 0; i<this->num_samples - 1; i++)
{
this->connect_Data_Tree1[i] = new double[4];
for(int j = 0; j<4; j++)
this->connect_Data_Tree1[i][j] = treedata1[i][j];
this->rowMapForTreeData.insert( std::pair< int, int>(treedata1[i][3], i));
}
}
if( treedata2 != NULL)
{
this->connect_Data_Tree2 = new double*[this->num_features-1];
this->columnMapForTreeData.clear();
for(int i = 0; i<this->num_features - 1; i++)
{
this->connect_Data_Tree2[i] = new double[4];
for(int j = 0; j<4; j++)
this->connect_Data_Tree2[i][j] = treedata2[i][j];
this->columnMapForTreeData.insert( std::pair< int, int>(treedata2[i][3], i));
}
}
}
void TrendHeatmapWindow::createDataForDendogram1(double powCof)
{
this->Processed_Coordinate_Data_Tree1.resize(2*(this->num_samples) - 1);
for(int i = 0; i < 2*(this->num_samples) - 1; i++)
{
this->Processed_Coordinate_Data_Tree1[i].resize(4);
}
for(int i = 0; i < num_samples; i++)
{
Processed_Coordinate_Data_Tree1[i][0] = i;
int k = rowMapFromOriginalToReorder.find(i)->second;
Processed_Coordinate_Data_Tree1[i][2] = (k + 0.5)/(double)this->num_samples - 0.5;
Processed_Coordinate_Data_Tree1[i][1] = -0.5;
Processed_Coordinate_Data_Tree1[i][3] = 0;
}
std::cout<<std::endl;
std::cout<< "Max value:"<<connect_Data_Tree1[num_samples-2][2]<<std::endl;
std::cout<< "devided by:"<<2 * pow(connect_Data_Tree1[num_samples - 2][2], powCof)<<std::endl;
for(int i = 0; i < num_samples-1; i++)
{
connect_Data_Tree1[i][2] = pow(connect_Data_Tree1[i][2], powCof);
connect_Data_Tree1[i][2] /= pow(connect_Data_Tree1[num_samples-2][2], powCof);
connect_Data_Tree1[i][2] /= 2;
}
connect_Data_Tree1[num_samples-2][2] = 0.5;
for(int i = num_samples ; i < 2*num_samples - 1; i++)
{
Processed_Coordinate_Data_Tree1[i][0] = i;
for(int k = 0; k < num_samples -1 ; k++)
{
if(i == connect_Data_Tree1[k][3])
{
double temp1, temp2;
temp1 = connect_Data_Tree1[k][0];
temp2 = connect_Data_Tree1[k][1];
Processed_Coordinate_Data_Tree1[i][2] = (Processed_Coordinate_Data_Tree1[temp1][2] + Processed_Coordinate_Data_Tree1[temp2][2])/2;
Processed_Coordinate_Data_Tree1[i][1] = -connect_Data_Tree1[k][2] - 0.5;
}
}
Processed_Coordinate_Data_Tree1[i][3] = 0;
}
}
void TrendHeatmapWindow::createDataForDendogram2()
{
this->Processed_Coordinate_Data_Tree2.resize(this->num_features);
for(int i = 0; i < this->num_features; i++)
{
this->Processed_Coordinate_Data_Tree2[i].resize(4);
}
for(int i = 0; i < num_features; i++)
{
Processed_Coordinate_Data_Tree2[i][0] = i;
int k = columnMapFromOriginalToReorder.find(i)->second;
Processed_Coordinate_Data_Tree2[i][1] = (k+0.5)/(double)this->num_features - 0.5;
Processed_Coordinate_Data_Tree2[i][2] = 0.5;
Processed_Coordinate_Data_Tree2[i][3] = 0;
}
}
void TrendHeatmapWindow::createDataForDendogram2(double powCof)
{
this->Processed_Coordinate_Data_Tree2.resize(2*(this->num_features) - 1);
for(int i = 0; i < 2*(this->num_features) - 1; i++)
{
this->Processed_Coordinate_Data_Tree2[i].resize(4);
}
for(int i = 0; i < num_features; i++)
{
Processed_Coordinate_Data_Tree2[i][0] = i;
int k = columnMapFromOriginalToReorder.find(i)->second;
Processed_Coordinate_Data_Tree2[i][1] = (k+0.5)/(double)this->num_features - 0.5;
Processed_Coordinate_Data_Tree2[i][2] = 0.5;
Processed_Coordinate_Data_Tree2[i][3] = 0;
}
for(int i = 0; i < num_features-1; i++)
{
connect_Data_Tree2[i][2] = pow(connect_Data_Tree2[i][2], powCof);
connect_Data_Tree2[i][2] /= pow(connect_Data_Tree2[num_features - 2][2], powCof);
connect_Data_Tree2[i][2] /= 2;
}
connect_Data_Tree2[num_features - 2][2] = 0.5;
for(int i = num_features ; i < 2*num_features - 1; i++)
{
Processed_Coordinate_Data_Tree2[i][0] = i;
for(int k = 0; k < num_features -1 ; k++)
{
if(i == connect_Data_Tree2[k][3])
{
double temp1, temp2;
temp1 = connect_Data_Tree2[k][0];
temp2 = connect_Data_Tree2[k][1];
Processed_Coordinate_Data_Tree2[i][1] = (Processed_Coordinate_Data_Tree2[temp1][1] + Processed_Coordinate_Data_Tree2[temp2][1])/2;
Processed_Coordinate_Data_Tree2[i][2] = connect_Data_Tree2[k][2] + 0.5;
}
}
Processed_Coordinate_Data_Tree2[i][3] = 0;
}
}
void TrendHeatmapWindow::showDendrogram1()
{
double p1[3];
double p2[3];
double p3[3];
double p4[3];
this->dencolors1->SetNumberOfComponents(3);
this->dencolors1->SetName("denColors1");
unsigned char color[3] = {0, 0, 0};
for(int i=0; i<3*(this->num_samples - 1);i++)
this->dencolors1->InsertNextTupleValue(color);
for(int i=0; i<this->num_samples-1;i++)
{
double temp1 = this->connect_Data_Tree1[i][0];
double temp2 = this->connect_Data_Tree1[i][1];
for(int j=0; j<(2*(this->num_samples))-1; j++)
{
if(this->Processed_Coordinate_Data_Tree1[j][0]==temp1)
{
p1[0]=this->Processed_Coordinate_Data_Tree1[j][1];
p1[1]=this->Processed_Coordinate_Data_Tree1[j][2];
p1[2]=this->Processed_Coordinate_Data_Tree1[j][3];
}
if(this->Processed_Coordinate_Data_Tree1[j][0]==temp2)
{
p2[0]=this->Processed_Coordinate_Data_Tree1[j][1];
p2[1]=this->Processed_Coordinate_Data_Tree1[j][2];
p2[2]=this->Processed_Coordinate_Data_Tree1[j][3];
}
}
p3[0]=-connect_Data_Tree1[i][2] - 0.5;
p3[1]=p1[1];
p3[2]=p1[2];
p4[0]=-connect_Data_Tree1[i][2] - 0.5;
p4[1]=p2[1];
p4[2]=p2[2];
this->denpoints1->InsertNextPoint(p1);
this->denpoints1->InsertNextPoint(p2);
this->denpoints1->InsertNextPoint(p3);
this->denpoints1->InsertNextPoint(p4);
vtkSmartPointer<vtkLine> line0 = vtkSmartPointer<vtkLine>::New();
line0->GetPointIds()->SetId(0,0 + i*4);
line0->GetPointIds()->SetId(1,2 + i*4);
this->denlines1->InsertNextCell(line0);
vtkSmartPointer<vtkLine> line1 = vtkSmartPointer<vtkLine>::New();
line1->GetPointIds()->SetId(0,1 + i*4);
line1->GetPointIds()->SetId(1,3 + i*4);
this->denlines1->InsertNextCell(line1);
vtkSmartPointer<vtkLine> line2 = vtkSmartPointer<vtkLine>::New();
line2->GetPointIds()->SetId(0,2 + i*4);
line2->GetPointIds()->SetId(1,3 + i*4);
this->denlines1->InsertNextCell(line2);
}
this->denlinesPolyData1->SetPoints(denpoints1);
this->denlinesPolyData1->SetLines(denlines1);
this->denlinesPolyData1->GetCellData()->SetScalars(dencolors1);
this->denmapper1->SetInputData(denlinesPolyData1);
this->denmapper1->SetScalarRange(0, 3*this->num_samples-1);
this->denactor1 = vtkSmartPointer<vtkActor>::New();
this->denactor1->SetMapper(denmapper1);
this->view->GetRenderer()->AddActor(denactor1);
}
void TrendHeatmapWindow::showDendrogram2()
{
double p1[3];
double p2[3];
double p3[3];
double p4[3];
this->dencolors2->SetNumberOfComponents(3);
this->dencolors2->SetName("denColors2");
unsigned char color[3] = {0, 0, 0};
for(int i=0; i<3*(this->num_features - 1);i++)
this->dencolors2->InsertNextTupleValue(color);
for(int i=0; i<this->num_features-1; i++)
{
double temp1 = this->connect_Data_Tree2[i][0];
double temp2 = this->connect_Data_Tree2[i][1];
for(int j=0; j<(2*(this->num_features))-1; j++)
{
if(this->Processed_Coordinate_Data_Tree2[j][0]==temp1)
{
p1[0]=this->Processed_Coordinate_Data_Tree2[j][1];
p1[1]=this->Processed_Coordinate_Data_Tree2[j][2];
p1[2]=this->Processed_Coordinate_Data_Tree2[j][3];
}
if(this->Processed_Coordinate_Data_Tree2[j][0]==temp2)
{
p2[0]=this->Processed_Coordinate_Data_Tree2[j][1];
p2[1]=this->Processed_Coordinate_Data_Tree2[j][2];
p2[2]=this->Processed_Coordinate_Data_Tree2[j][3];
}
}
p3[0]=p1[0];
p3[1]=this->connect_Data_Tree2[i][2] + 0.5;
p3[2]=p1[2];
p4[0]=p2[0];
p4[1]=this->connect_Data_Tree2[i][2] + 0.5;
p4[2]=p2[2];
this->denpoints2->InsertNextPoint(p1);
this->denpoints2->InsertNextPoint(p2);
this->denpoints2->InsertNextPoint(p3);
this->denpoints2->InsertNextPoint(p4);
vtkSmartPointer<vtkLine> line0 = vtkSmartPointer<vtkLine>::New();
line0->GetPointIds()->SetId(0,0 + i*4);
line0->GetPointIds()->SetId(1,2 + i*4);
this->denlines2->InsertNextCell(line0);
vtkSmartPointer<vtkLine> line1 = vtkSmartPointer<vtkLine>::New();
line1->GetPointIds()->SetId(0,1 + i*4);
line1->GetPointIds()->SetId(1,3 + i*4);
this->denlines2->InsertNextCell(line1);
vtkSmartPointer<vtkLine> line2 = vtkSmartPointer<vtkLine>::New();
line2->GetPointIds()->SetId(0,2 + i*4);
line2->GetPointIds()->SetId(1,3 + i*4);
this->denlines2->InsertNextCell(line2);
}
this->denlinesPolyData2->SetPoints(denpoints2);
this->denlinesPolyData2->SetLines(denlines2);
this->denlinesPolyData2->GetCellData()->SetScalars(dencolors2);
this->denmapper2->SetInputData(denlinesPolyData2);
this->denmapper2->SetScalarRange(0, 3*this->num_features-1);
this->denactor2->SetMapper(denmapper2);
this->view->GetRenderer()->AddActor(denactor2);
}
void TrendHeatmapWindow::GetSelecectedIDs()
{
cout<<"get selected"<<endl;
std::set<long int> selectedIDs2 = this->Selection2->getSelections();
std::set<long int> selectedIDs1 = this->Selection->getSelections();
std::set<long int>::iterator iter1 = selectedIDs1.begin();
std::set<long int>::iterator iter2 = selectedIDs2.begin();
vtkSmartPointer<vtkIdTypeArray> cellids = vtkSmartPointer<vtkIdTypeArray>::New();
cellids->SetNumberOfComponents(1);
int num1 = selectedIDs1.size();
int num2 = selectedIDs2.size();
std::vector<int > IDs1;
std::vector<int > IDs2;
IDs1.resize(num1);
IDs2.resize(num2);
int count1 = 0;
int count2 = 0;
#pragma omp parallel sections
{
#pragma omp section
while(iter1 != selectedIDs1.end())
{
int index1 = *iter1;
int var = indMapFromVertexToInd.find(index1)->second;
int id1 = rowMapFromOriginalToReorder.find(var)->second;
IDs1[count1++] = id1;
iter1++;
}
#pragma omp section
while(iter2 != selectedIDs2.end())
{
int index2 = *iter2;
int id2 = columnMapFromOriginalToReorder.find(index2)->second;
IDs2[count2++] = id2;
iter2++;
}
}
if( num1 == 0 && num2 != 0)
{
num1 = this->num_samples;
IDs1.resize(num1);
for( int i = 0; i < this->num_samples; i++)
{
IDs1[i] = i;
}
}
if( num2 == 0 && num1 != 0)
{
num2 = this->num_features;
IDs2.resize(num2);
for( int i = 0; i < this->num_features; i++)
{
IDs2[i] = i;
}
}
for(int i = 0; i<num1; i++)
for(int j = 0; j<num2; j++)
cellids->InsertNextValue( (IDs1[i])*(this->num_features) + IDs2[j]);
vtkSmartPointer<vtkSelectionNode> selectionNode = vtkSmartPointer<vtkSelectionNode>::New();
selectionNode->SetFieldType(vtkSelectionNode::CELL);
selectionNode->SetContentType(vtkSelectionNode::INDICES);
selectionNode->SetSelectionList(cellids);
vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
selection->AddNode(selectionNode);
vtkSmartPointer<vtkExtractSelection> extractSelection = vtkSmartPointer<vtkExtractSelection>::New();
extractSelection->SetInputData(0, this->aPlane->GetOutput());
extractSelection->SetInputData(1, selection);
extractSelection->Update();
vtkSmartPointer<vtkUnstructuredGrid> selected = vtkSmartPointer<vtkUnstructuredGrid>::New();
selected->ShallowCopy(extractSelection->GetOutput());
vtkSmartPointer<vtkDataSetMapper> selectedMapper = vtkSmartPointer<vtkDataSetMapper>::New();
selectedMapper->SetInputData(selected);
vtkSmartPointer<vtkActor> selectedActor = vtkSmartPointer<vtkActor>::New();
selectedActor->SetMapper(selectedMapper);
selectedActor->GetProperty()->EdgeVisibilityOn();
selectedActor->GetProperty()->SetEdgeColor(1,1,1);
selectedActor->GetProperty()->SetLineWidth(0.5);
if(this->dragLineFlag)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(dragLineActor);
try
{
if(continueselect == false)
{
if(continueselectnum > 0)
{
cout<<"I'm here "<<continueselectnum<<endl;
for(int i = 0; i<continueselectnum + 1; i++)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor());
continueselectnum = 0;
}
else
{
if (this->removeActorflag != 0)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor());
}
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor);
this->removeActorflag += 1;
}
else
{
this->continueselectnum += 1;
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor);
}
if(this->dragLineFlag)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(dragLineActor);
this->view->Render();
}
catch(...)
{
cout<<"GetSelecectedIDs failed, please try it again!"<<endl;
}
}
void TrendHeatmapWindow::drawPoints1()
{
int max_table_values = 2*this->num_samples + 2*this->num_features-2;
this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New();
this->points = vtkSmartPointer<vtkPoints>::New();
this->v = vtkSmartPointer<vtkIdTypeArray>::New();
v->SetNumberOfValues (max_table_values);
for(int i=0; i<2*this->num_samples-1;i++)
{
v->SetValue (i,graph_Layout->AddVertex());
this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree1[i][1],this->Processed_Coordinate_Data_Tree1[i][2],this->Processed_Coordinate_Data_Tree1[i][3]);
}
for(int i=0; i<(2*this->num_features-1);i++)
{
v->SetValue (i+2*this->num_samples-1,graph_Layout->AddVertex());
this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1],this->Processed_Coordinate_Data_Tree2[i][2],this->Processed_Coordinate_Data_Tree2[i][3]);
}
this->graph_Layout->SetPoints(this->points);
this->vertexColors = vtkSmartPointer<vtkIntArray>::New();
vertexColors->SetNumberOfComponents(1);
vertexColors->SetName("Color1");
this->vetexlut = vtkSmartPointer<vtkLookupTable>::New();
vetexlut->SetNumberOfTableValues(max_table_values);
for(int i=0; i<max_table_values;i++)
{
vetexlut->SetTableValue(i, 0.5, 0.5,0.5); // color the vertices- blue
}
vetexlut->Build();
vtkSmartPointer<vtkFloatArray> scales1 = vtkSmartPointer<vtkFloatArray>::New(); /// scales for vertex size
scales1->SetNumberOfComponents(1);
scales1->SetName("Scales1");
for(int j=0;j<max_table_values;j++)
{
vertexColors->InsertNextValue(j);
scales1->InsertNextValue(1);
}
this->graph_Layout->GetVertexData()->AddArray(vertexColors);
this->graph_Layout->GetVertexData()->AddArray(scales1);
this->view = vtkSmartPointer<vtkGraphLayoutView>::New();
this->view->AddRepresentationFromInput(graph_Layout);
this->view->SetLayoutStrategy("Pass Through");
this->view->ScaledGlyphsOn();
this->view->SetScalingArrayName("Scales1");
this->view->ColorVerticesOn();
this->view->SetVertexColorArrayName("Color1");
vtkRenderedGraphRepresentation::SafeDownCast(this->view->GetRepresentation()) ->SetGlyphType(vtkGraphToGlyphs::CIRCLE);
this->theme = vtkSmartPointer<vtkViewTheme>::New();
this->theme->SetPointLookupTable(vetexlut);
vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New();
verts->SetNumberOfCells(1);
vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New();
orient->SetNumberOfComponents(1);
orient->SetName("orientation");
vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New();
label->SetNumberOfComponents(1);
label->SetName("label");
for(int i=0; i<max_table_values;i++)
{
verts->InsertNextCell(1);
verts->InsertCellPoint(i);
}
for(int i = 0; i < this->num_samples; i++)
{
vtkVariant v = i;
label->InsertNextValue(v.ToString());
orient->InsertNextValue(0.0);
}
for(int i = this->num_samples; i <2*(this->num_samples)-1; i++)
{
label->InsertNextValue("");
orient->InsertNextValue(0.0);
}
for(int i = 2*(this->num_samples)-1; i <2*(this->num_samples)-1 + this->num_features; i++)
{
vtkIdType id = i - (2*this->num_samples-1) + 1 ;
label->InsertNextValue(this->table->GetColumn(id)->GetName ());
orient->InsertNextValue(45.0);
}
for(int i = 2*(this->num_samples)-1 + this->num_features; i <2*(this->num_samples)-1 + 2*(this->num_features)-1; i++)
{
label->InsertNextValue("");
orient->InsertNextValue(0.0);
}
pd->SetPoints(points);
pd->SetVerts(verts);
pd->GetPointData()->AddArray(label);
pd->GetPointData()->AddArray(orient);
vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
hier->SetInputData(pd);
hier->SetOrientationArrayName("orientation");
hier->SetLabelArrayName("label");
hier->GetTextProperty()->SetColor(1.0, 1.0, 1.0);
vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New();
lmapper->SetInputConnection(hier->GetOutputPort());
vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New();
lmapper->SetRenderStrategy(strategy);
lmapper->SetShapeToNone();
lmapper->SetBackgroundOpacity(0.0);
lmapper->SetMargin(0);
vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New();
lactor->SetMapper(lmapper);
vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New();
rmapper->SetInputData(pd);
vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New();
ractor->SetMapper(rmapper);
this->view->GetRenderer()->AddActor(lactor);
this->view->GetRenderer()->AddActor(ractor);
this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New();
this->selectionCallback1->SetClientData(this);
this->selectionCallback1->SetCallback ( SelectionCallbackFunction1);
this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1);
}
void TrendHeatmapWindow::drawPoints3()
{
int max_table_values = 2*this->num_samples-1;
this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New();
this->points = vtkSmartPointer<vtkPoints>::New();
this->v = vtkSmartPointer<vtkIdTypeArray>::New();
v->SetNumberOfValues (max_table_values);
for(int i=0; i<max_table_values;i++)
{
v->SetValue (i,graph_Layout->AddVertex());
this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree1[i][1],this->Processed_Coordinate_Data_Tree1[i][2],this->Processed_Coordinate_Data_Tree1[i][3]);
}
this->graph_Layout->SetPoints(this->points);
this->vertexColors = vtkSmartPointer<vtkIntArray>::New();
vertexColors->SetNumberOfComponents(1);
vertexColors->SetName("Color1");
this->vetexlut = vtkSmartPointer<vtkLookupTable>::New();
vetexlut->SetNumberOfTableValues(max_table_values);
for(int i=0; i<max_table_values;i++)
{
vetexlut->SetTableValue(i, 0.5, 0.5,0.5);
}
vetexlut->Build();
vtkSmartPointer<vtkFloatArray> scales1 = vtkSmartPointer<vtkFloatArray>::New(); /// scales for vertex size
scales1->SetNumberOfComponents(1);
scales1->SetName("Scales1");
for(int j=0; j<max_table_values;j++)
{
vertexColors->InsertNextValue(j);
scales1->InsertNextValue(1);
}
this->graph_Layout->GetVertexData()->AddArray(scales1);
this->graph_Layout->GetVertexData()->AddArray(vertexColors);
this->view = vtkSmartPointer<vtkGraphLayoutView>::New();
this->view->AddRepresentationFromInput(graph_Layout);
this->view->SetLayoutStrategy("Pass Through");
this->view->ScaledGlyphsOn();
this->view->SetScalingArrayName("Scales1");
this->view->ColorVerticesOn();
this->view->SetVertexColorArrayName("Color1");
vtkRenderedGraphRepresentation::SafeDownCast(this->view->GetRepresentation()) ->SetGlyphType(vtkGraphToGlyphs::CIRCLE);
this->theme = vtkSmartPointer<vtkViewTheme>::New();
this->theme->SetPointLookupTable(vetexlut);
vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New();
verts->SetNumberOfCells(1);
vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New();
orient->SetNumberOfComponents(1);
orient->SetName("orientation");
vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New();
label->SetNumberOfComponents(1);
label->SetName("label");
vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
for(int i=0; i<this->num_features;i++)
{
pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0);
}
for(int i=0; i<this->num_features;i++)
{
verts->InsertNextCell(1);
verts->InsertCellPoint(i);
orient->InsertNextValue(45.0);
vtkIdType id = i+1 ;
label->InsertNextValue(this->table->GetColumn(id)->GetName());
}
pd->SetPoints(pts);
pd->SetVerts(verts);
pd->GetPointData()->AddArray(label);
pd->GetPointData()->AddArray(orient);
vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
hier->SetInputData(pd);
hier->SetOrientationArrayName("orientation");
hier->SetLabelArrayName("label");
hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0);
vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New();
lmapper->SetInputConnection(hier->GetOutputPort());
vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New();
lmapper->SetRenderStrategy(strategy);
lmapper->SetShapeToNone();
lmapper->SetBackgroundOpacity(0.0);
lmapper->SetMargin(0);
vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New();
lactor->SetMapper(lmapper);
vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New();
rmapper->SetInputData(pd);
vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New();
ractor->SetMapper(rmapper);
this->view->GetRenderer()->AddActor(lactor);
this->view->GetRenderer()->AddActor(ractor);
this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New();
this->selectionCallback1->SetClientData(this);
this->selectionCallback1->SetCallback (SelectionCallbackFunction1);
this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1);
}
void TrendHeatmapWindow::drawPointsForSPD()
{
int max_table_values = 2 * this->num_samples-1 + this->num_features;
this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New();
this->points = vtkSmartPointer<vtkPoints>::New();
this->v = vtkSmartPointer<vtkIdTypeArray>::New();
v->SetNumberOfValues (max_table_values);
for( int i = 0; i < 2 * this->num_samples - 1; i++)
{
v->SetValue(i, graph_Layout->AddVertex());
this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree1[i][1],this->Processed_Coordinate_Data_Tree1[i][2],this->Processed_Coordinate_Data_Tree1[i][3]);
}
for( int i = 0; i < this->num_features; i++)
{
v->SetValue(i + 2 * this->num_samples - 1, graph_Layout->AddVertex());
this->points->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1],this->Processed_Coordinate_Data_Tree2[i][2],this->Processed_Coordinate_Data_Tree2[i][3]);
}
this->graph_Layout->SetPoints(this->points);
this->vertexColors = vtkSmartPointer<vtkIntArray>::New();
vertexColors->SetNumberOfComponents(1);
vertexColors->SetName("Color1");
this->vetexlut = vtkSmartPointer<vtkLookupTable>::New();
vetexlut->SetNumberOfTableValues(max_table_values);
for(int i=0; i<max_table_values;i++)
{
vetexlut->SetTableValue(i, 0.5, 0.5,0.5);
}
vetexlut->Build();
vtkSmartPointer<vtkFloatArray> scales1 = vtkSmartPointer<vtkFloatArray>::New(); /// scales for vertex size
scales1->SetNumberOfComponents(1);
scales1->SetName("Scales1");
for(int j=0; j<max_table_values;j++)
{
vertexColors->InsertNextValue(j);
scales1->InsertNextValue(1);
}
this->graph_Layout->GetVertexData()->AddArray(scales1);
this->graph_Layout->GetVertexData()->AddArray(vertexColors);
this->view = vtkSmartPointer<vtkGraphLayoutView>::New();
this->view->AddRepresentationFromInput(graph_Layout);
this->view->SetLayoutStrategy("Pass Through");
this->view->ScaledGlyphsOn();
this->view->SetScalingArrayName("Scales1");
this->view->ColorVerticesOn();
this->view->SetVertexColorArrayName("Color1");
vtkRenderedGraphRepresentation::SafeDownCast(this->view->GetRepresentation()) ->SetGlyphType(vtkGraphToGlyphs::CIRCLE);
this->theme = vtkSmartPointer<vtkViewTheme>::New();
this->theme->SetPointLookupTable(vetexlut);
vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New();
verts->SetNumberOfCells(1);
vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New();
orient->SetNumberOfComponents(1);
orient->SetName("orientation");
vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New();
label->SetNumberOfComponents(1);
label->SetName("label");
vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
for(int i=0; i<this->num_features;i++)
{
pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0);
}
bool bplus = true;
if(this->num_features == table->GetNumberOfColumns())
{
bplus = false;
}
for(int i=0; i<this->num_features;i++)
{
verts->InsertNextCell(1);
verts->InsertCellPoint(i);
orient->InsertNextValue(45.0);
if(bplus)
{
label->InsertNextValue(this->table->GetColumn(i+1)->GetName());
}
else
{
label->InsertNextValue(this->table->GetColumn(i)->GetName());
}
}
pd->SetPoints(pts);
pd->SetVerts(verts);
pd->GetPointData()->AddArray(label);
pd->GetPointData()->AddArray(orient);
vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
hier->SetInputData(pd);
hier->SetOrientationArrayName("orientation");
hier->SetLabelArrayName("label");
hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0);
vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New();
lmapper->SetInputConnection(hier->GetOutputPort());
vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New();
lmapper->SetRenderStrategy(strategy);
lmapper->SetShapeToNone();
lmapper->SetBackgroundOpacity(0.0);
lmapper->SetMargin(0);
vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New();
lactor->SetMapper(lmapper);
vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New();
rmapper->SetInputData(pd);
vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New();
ractor->SetMapper(rmapper);
this->view->GetRenderer()->AddActor(lactor);
this->view->GetRenderer()->AddActor(ractor);
this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New();
this->selectionCallback1->SetClientData(this);
this->selectionCallback1->SetCallback (SelectionCallbackFunctionForSPD);
this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1);
}
void TrendHeatmapWindow::drawPointsForOrderHeatmap()
{
this->view = vtkSmartPointer<vtkGraphLayoutView>::New();
this->theme = vtkSmartPointer<vtkViewTheme>::New();
vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New();
verts->SetNumberOfCells(1);
vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New();
orient->SetNumberOfComponents(1);
orient->SetName("orientation");
vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New();
label->SetNumberOfComponents(1);
label->SetName("label");
vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
for(int i=0; i<this->num_features;i++)
{
pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0);
}
for(int i=0; i<this->num_features;i++)
{
verts->InsertNextCell(1);
verts->InsertCellPoint(i);
orient->InsertNextValue(45.0);
vtkIdType id = i+1 ;
label->InsertNextValue(this->table->GetColumn(id)->GetName());
}
pd->SetPoints(pts);
pd->SetVerts(verts);
pd->GetPointData()->AddArray(label);
pd->GetPointData()->AddArray(orient);
vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
hier->SetInputData(pd);
hier->SetOrientationArrayName("orientation");
hier->SetLabelArrayName("label");
hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0);
vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New();
lmapper->SetInputConnection(hier->GetOutputPort());
vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New();
lmapper->SetRenderStrategy(strategy);
lmapper->SetShapeToNone();
lmapper->SetBackgroundOpacity(0.0);
lmapper->SetMargin(0);
vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New();
lactor->SetMapper(lmapper);
vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New();
rmapper->SetInputData(pd);
vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New();
ractor->SetMapper(rmapper);
this->view->GetRenderer()->AddActor(lactor);
this->view->GetRenderer()->AddActor(ractor);
//this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New();
//this->selectionCallback1->SetClientData(this);
//this->selectionCallback1->SetCallback ( SelectionCallbackFunctionForSPD);
//this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1);
}
void TrendHeatmapWindow::SelectionCallbackFunction(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData )
{
vtkAnnotationLink* annotationLink = static_cast<vtkAnnotationLink*>(caller);
vtkSelection* selection = annotationLink->GetCurrentSelection();
TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData;
vtkSelectionNode* vertices = NULL;
vtkSelectionNode* edges = NULL;
vtkSelectionNode* cells = NULL;
if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = selection->GetNode(0);
}
else if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::EDGE)
{
edges = selection->GetNode(0);
}
if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = selection->GetNode(1);
}
else if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::EDGE)
{
edges = selection->GetNode(1);
}
if( vertices != NULL)
{
vtkIdTypeArray* vertexList = vtkIdTypeArray::SafeDownCast(vertices->GetSelectionList());
std::set<long int> IDs;
if(vertexList->GetNumberOfTuples() > 0)
{
for( vtkIdType i = 0; i < vertexList->GetNumberOfTuples(); i++)
{
long int value = vertexList->GetValue(i);
IDs.insert(value);
}
}
try
{
heatmapWin->SetdenSelectedIds1( IDs, false);
}
catch(...)
{
cout<<"SetdenSelectedIds1 failed, please try again !"<<endl;
}
}
}
void TrendHeatmapWindow::SelectionCallbackFunction1(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData )
{
vtkAnnotationLink* annotationLink = static_cast<vtkAnnotationLink*>(caller);
vtkSelection* selection = annotationLink->GetCurrentSelection();
TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData;
vtkSelectionNode* vertices = NULL;
vtkSelectionNode* edges = NULL;
vtkSelectionNode* cells = NULL;
if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = selection->GetNode(0);
}
else if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::EDGE)
{
edges = selection->GetNode(0);
}
if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = selection->GetNode(1);
}
else if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::EDGE)
{
edges = selection->GetNode(1);
}
if( vertices != NULL)
{
vtkIdTypeArray* vertexList = vtkIdTypeArray::SafeDownCast(vertices->GetSelectionList());
std::set<long int> IDs;
if(vertexList->GetNumberOfTuples() > 0)
{
for( vtkIdType i = 0; i < vertexList->GetNumberOfTuples(); i++)
{
long int value = vertexList->GetValue(i);
IDs.insert(value);
}
}
try
{
heatmapWin->SetdenSelectedIds1( IDs, true);
}
catch(...)
{
cout<<"SetdenSelectedIds1 failed, please try again !"<<endl;
}
}
}
void TrendHeatmapWindow::SelectionCallbackFunction2(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData )
{
TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData;
int* pos = heatmapWin->view->GetInteractor()->GetEventPosition();
vtkCellPicker *cell_picker = (vtkCellPicker *)heatmapWin->view->GetInteractor()->GetPicker();
cell_picker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer());
double* worldPosition = cell_picker->GetPickPosition();
if((worldPosition[0]<=0.5) && (worldPosition[0]>=-0.5) && (worldPosition[1]<=0.5) && (worldPosition[0]>=-0.5))
{
vtkSmartPointer<vtkCellPicker> cellpicker = vtkSmartPointer<vtkCellPicker>::New();
cellpicker->SetTolerance(0.0005);
// Pick from this location.
cellpicker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer());
double* worldPosition = cellpicker->GetPickPosition();
if(cellpicker->GetCellId() != -1)
heatmapWin->id1 = cellpicker->GetCellId();
}
if(worldPosition[0]<-0.5)
{
std::cout<<"world position: "<<worldPosition[0] <<endl;
std::cout<<"rescaled value: "<< - ( worldPosition[0] + 0.5) <<endl;
heatmapWin->addDragLineforSPD(worldPosition);
}
}
void TrendHeatmapWindow::SelectionCallbackFunction3(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData )
{
TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData;
int* pos = heatmapWin->view->GetInteractor()->GetEventPosition();
vtkCellPicker *cell_picker = (vtkCellPicker *)heatmapWin->view->GetInteractor()->GetPicker();
// Pick from this location.
cell_picker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer());
double* worldPosition = cell_picker->GetPickPosition();
if((worldPosition[0]<=0.5) && (worldPosition[0]>=-0.5) && (worldPosition[1]<=0.5) && (worldPosition[0]>=-0.5))
{
vtkSmartPointer<vtkCellPicker> cellpicker = vtkSmartPointer<vtkCellPicker>::New();
cellpicker->SetTolerance(0.0005);
// Pick from this location.
cellpicker->Pick(pos[0], pos[1], 0, heatmapWin->view->GetRenderer());
double* worldPosition = cellpicker->GetPickPosition();
if(cellpicker->GetCellId() != -1)
{
try
{
heatmapWin->id2 = cellpicker->GetCellId();
heatmapWin->ids = vtkSmartPointer<vtkIdTypeArray>::New();
heatmapWin->ids->SetNumberOfComponents(1);
heatmapWin->computeselectedcells();
heatmapWin->setselectedCellIds();
emit heatmapWin->SelChanged();
}
catch(...)
{
cout<<"SelectionCallbackFunction3 failed, please try again !"<<endl;
}
}
}
}
void TrendHeatmapWindow::HandleKeyPress(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData )
{
/*TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData;
char key = heatmapWin->view->GetInteractor()->GetKeyCode();
int size = 0;
switch (key)
{
case 'c':
heatmapWin->continueselect = true;
break;
case 'i':
heatmapWin->intersectionselect = true;
break;
case 'r':
heatmapWin->continueselect = false;
heatmapWin->intersectionselect = false;
break;
case 'd':
size = heatmapWin->Selection->getSelections().size();
if( size > 0)
{
std::cout<< size<< " items deleted! Please rerun STrenD analysis!"<<endl;
heatmapWin->Selection->DeleteCurrentSelectionInTable();
}
else
{
std::cout<< "No items have been selected!"<<endl;
}
break;
default:
break;
}*/
}
void TrendHeatmapWindow::SetdenSelectedIds1(std::set<long int>& IDs, bool bfirst)
{
std::set<long int> selectedIDs1;
std::set<long int> selectedIDs2;
std::set<long int>::iterator it;
long int id;
if(continueselect == false)
{
if(this->denResetflag1 == 1)
{
for(int i = 0; i<this->dencolors1->GetSize() ; i++)
this->dencolors1->SetValue(i, 0);
denlinesPolyData1->Modified();
//denlinesPolyData1->Update();
denmapper1->Modified();
denmapper1->Update();
denactor1->Modified();
}
if(this->denResetflag2 == 1)
{
for(int i = 0; i<this->dencolors2->GetSize() ; i++)
this->dencolors2->SetValue(i, 0);
denlinesPolyData2->Modified();
//denlinesPolyData2->Update();
denmapper2->Modified();
denmapper2->Update();
denactor2->Modified();
}
}
if( bfirst)
{
if( IDs.size() > 0)
{
for( it = IDs.begin(); it != IDs.end(); it++ )
{
id = *it;
//cout<<"id ====="<<id<<endl;
if(id < 2*this->num_samples-1)
{
reselectIds1(selectedIDs1, id);
}
else
{
try
{
reselectIds2(selectedIDs2, id - (2*this->num_samples-1));
}
catch(...)
{
cout<<"reselectIds2 failed, please try again!"<<endl;
}
}
}
}
}
else
{
if( IDs.size() > 0)
{
for( it = IDs.begin(); it != IDs.end(); it++ )
{
id = *it;
if(id < 2 * this->num_features - 1)
{
reselectIds2(selectedIDs2, id);
}
}
}
}
if(selectedIDs1.size() > 0)
{
for(int i = 0; i<this->num_features; i++)
{
selectedIDs2.insert(i);
}
denmapper1->ScalarVisibilityOn();
denlinesPolyData1->Modified();
//denlinesPolyData1->Update();
denmapper1->Modified();
denmapper1->Update();
denactor1->Modified();
this->view->Render();
this->denResetflag1 = 1;
if(intersectionselect == true)
this->interselectedIDs = selectedIDs1;
try
{
//cout<<"set select============="<<endl;
this->Selection2->select(selectedIDs2);
this->Selection->select(selectedIDs1);
}
catch(...)
{
cout<<"Setcelected id after reselect failed, please try again!"<<endl;
}
}
else if(selectedIDs2.size() > 0)
{
this->Selection2->select(selectedIDs2);
if(intersectionselect == false)
{
for(int i = 0; i<this->num_samples; i++)
selectedIDs1.insert( indMapFromIndToVertex[i]);
//cout<<"set select============="<<endl;
this->Selection->select(selectedIDs1);
}
else
{
//cout<<"set select============="<<endl;
this->Selection->select(interselectedIDs);
}
denmapper2->ScalarVisibilityOn();
denlinesPolyData2->Modified();
//denlinesPolyData2->Update();
denmapper2->Modified();
denmapper2->Update();
denactor2->Modified();
this->view->Render();
this->denResetflag2 = 1;
}
else
{
this->Selection2->clear();
//cout<<"set select============="<<endl;
this->Selection->clear();
}
}
void TrendHeatmapWindow::reselectIds1(std::set<long int>& selectedIDs, long int id)
{
if(id < this->num_samples)
{
selectedIDs.insert( indMapFromIndToVertex[id]);
}
else
{
this->dencolors1->SetValue((id - this->num_samples)*9, 153);
this->dencolors1->SetValue((id - this->num_samples)*9 + 1, 50);
this->dencolors1->SetValue((id - this->num_samples)*9 + 2, 204);
this->dencolors1->SetValue((id - this->num_samples)*9 + 3, 153);
this->dencolors1->SetValue((id - this->num_samples)*9 + 4, 50);
this->dencolors1->SetValue((id - this->num_samples)*9 + 5, 204);
this->dencolors1->SetValue((id - this->num_samples)*9 + 6, 153);
this->dencolors1->SetValue((id - this->num_samples)*9 + 7, 50);
this->dencolors1->SetValue((id - this->num_samples)*9 + 8, 204);
this->reselectIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][0]);
this->reselectIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][1]);
}
}
void TrendHeatmapWindow::reselectSPDIds1(std::set<long int>& selectedIDs, long int id)
{
if(id < this->num_samples)
{
for( int i = 0; i < indSPDMapFromIndToVertex[id].size(); i++)
{
selectedIDs.insert( indSPDMapFromIndToVertex[id][i]);
}
}
else
{
this->dencolors1->SetValue((id - this->num_samples)*9, 153);
this->dencolors1->SetValue((id - this->num_samples)*9 + 1, 50);
this->dencolors1->SetValue((id - this->num_samples)*9 + 2, 204);
this->dencolors1->SetValue((id - this->num_samples)*9 + 3, 153);
this->dencolors1->SetValue((id - this->num_samples)*9 + 4, 50);
this->dencolors1->SetValue((id - this->num_samples)*9 + 5, 204);
this->dencolors1->SetValue((id - this->num_samples)*9 + 6, 153);
this->dencolors1->SetValue((id - this->num_samples)*9 + 7, 50);
this->dencolors1->SetValue((id - this->num_samples)*9 + 8, 204);
this->reselectSPDIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][0]);
this->reselectSPDIds1(selectedIDs, connect_Data_Tree1[rowMapForTreeData.find(id)->second][1]);
}
}
void TrendHeatmapWindow::reselectIds2(std::set<long int>& selectedIDs2, long int id)
{
if(id < this->num_features)
{
selectedIDs2.insert( id);
}
else
{
this->dencolors2->SetValue((id - this->num_features)*9, 153);
this->dencolors2->SetValue((id - this->num_features)*9 + 1, 50);
this->dencolors2->SetValue((id - this->num_features)*9 + 2, 204);
this->dencolors2->SetValue((id - this->num_features)*9 + 3, 153);
this->dencolors2->SetValue((id - this->num_features)*9 + 4, 50);
this->dencolors2->SetValue((id - this->num_features)*9 + 5, 204);
this->dencolors2->SetValue((id - this->num_features)*9 + 6, 153);
this->dencolors2->SetValue((id - this->num_features)*9 + 7, 50);
this->dencolors2->SetValue((id - this->num_features)*9 + 8, 204);
this->reselectIds2(selectedIDs2, connect_Data_Tree2[columnMapForTreeData.find(id)->second][0]);
this->reselectIds2(selectedIDs2, connect_Data_Tree2[columnMapForTreeData.find(id)->second][1]);
}
}
void TrendHeatmapWindow::computeselectedcells()
{
this->r1 = id1/this->num_features;
this->r2 = id2/this->num_features;
this->c1 = id1%this->num_features;
this->c2 = id2%this->num_features;
cout<<r1<<endl;
cout<<r2<<endl;
for(int i = 0; i <= r1 - r2; i++)
{
for(int j = 0; j <= c2 - c1; j++)
{
ids->InsertNextValue(id2 - j + this->num_features*i);
}
}
}
void TrendHeatmapWindow::setselectedCellIds()
{
std::set<long int> selectedIDs1;
std::set<long int> selectedIDs2;
if(continueselect == false)
{
if(this->denResetflag1 == 1)
{
for(int i = 0; i<this->dencolors1->GetSize() ; i++)
this->dencolors1->SetValue(i, 0);
denmapper1->ScalarVisibilityOn();
denlinesPolyData1->Modified();
//denlinesPolyData1->Update();
denmapper1->Modified();
denmapper1->Update();
denactor1->Modified();
this->view->Render();
this->denResetflag1 = 0;
}
if(this->denResetflag2 == 1)
{
for(int i = 0; i<this->dencolors2->GetSize() ; i++)
this->dencolors2->SetValue(i, 0);
denmapper2->ScalarVisibilityOn();
denlinesPolyData2->Modified();
//denlinesPolyData2->Update();
denmapper2->Modified();
denmapper2->Update();
denactor2->Modified();
this->view->Render();
this->denResetflag2 = 0;
}
}
for(int i = r2; i<=r1; i++)
{
selectedIDs1.insert( indMapFromIndToVertex[ this->Optimal_Leaf_Order1[i]]);
}
for(int j = c1; j<=c2; j++)
{
selectedIDs2.insert(this->Optimal_Leaf_Order2[j]);
}
try
{
this->Selection2->select(selectedIDs2);
this->Selection->select(selectedIDs1);
}
catch(...)
{
cout<<"setselectedCellIds failed, please try again!"<<endl;
}
}
void TrendHeatmapWindow::GetSelRowCol(int &r1, int &c1, int &r2, int &c2)
{
r1 = this->r1;
r2 = this->r2;
c1 = this->c1;
c2 = this->c2;
}
void TrendHeatmapWindow::SetSelRowCol(int r1, int c1, int r2, int c2)
{
this->r1 = r1;
this->r2 = r2;
this->c1 = c1;
this->c2 = c2;
setselectedCellIds();
}
void TrendHeatmapWindow::SetSPDInteractStyle()
{
this->theme->SetCellValueRange(0, this->num_samples*this->num_features - 1);
this->theme->SetSelectedCellColor(1,0,1);
this->theme->SetSelectedPointColor(1,0,1);
this->view->ApplyViewTheme(theme);
this->myCellPicker = vtkSmartPointer<vtkCellPicker>::New();
this->view->GetInteractor()->SetPicker(this->myCellPicker);
this->myCellPicker->SetTolerance(0.004);
vtkSmartPointer<vtkCallbackCommand> selectionCallback2 =vtkSmartPointer<vtkCallbackCommand>::New();
selectionCallback2->SetClientData(this);
selectionCallback2->SetCallback(SelectionCallbackFunction2);
this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonPressEvent);
this->view->GetInteractor()->RemoveObservers(vtkCommand::RightButtonReleaseEvent);
this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyPressEvent);
this->view->GetInteractor()->RemoveObservers(vtkCommand::KeyReleaseEvent);
this->view->GetInteractor()->AddObserver(vtkCommand::RightButtonReleaseEvent, selectionCallback2);
this->mainQTRenderWidget.SetRenderWindow(view->GetRenderWindow());
this->mainQTRenderWidget.resize(600, 600);
this->mainQTRenderWidget.show();
}
void TrendHeatmapWindow::showGraphforSPD( int selCol, int unselCol, bool bprogressionHeatmap)
{
if(bprogressionHeatmap)
{
drawPointsForOrderHeatmap();
}
else
{
drawPointsForSPD();
}
this->dragLineFlag = false;
this->aPlane = vtkSmartPointer<vtkPlaneSource>::New();
this->aPlane->SetXResolution(this->num_features);
this->aPlane->SetYResolution(this->num_samples);
this->cellData = vtkSmartPointer<vtkFloatArray>::New();
int index = 0;
for (int i = 0; i < this->num_samples; i++)
{
for(int j = 0; j < this->num_features; j++)
{
cellData->InsertNextValue(index++);
}
}
this->celllut = vtkSmartPointer<vtkLookupTable>::New();
this->celllut->SetNumberOfTableValues(this->num_samples*this->num_features);
this->celllut->SetTableRange(0, this->num_samples*this->num_features - 1);
this->celllut->Build();
int k = 0;
for(int i = 0; i < this->num_samples; i++)
{
for(int j = 0; j < this->num_features; j++)
{
rgb rgb = GetRGBValue( mapdata[num_samples - i - 1][j]);
celllut->SetTableValue(k++, rgb.r, rgb.g, rgb.b);
}
}
this->aPlane->Update();
this->aPlane->GetOutput()->GetCellData()->SetScalars(cellData);
this->mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
this->mapper->SetInputConnection(aPlane->GetOutputPort());
this->mapper->SetScalarRange(0, this->num_samples*this->num_features - 1);
this->mapper->SetLookupTable(celllut);
this->actor = vtkSmartPointer<vtkActor>::New();
this->actor->SetMapper(mapper);
vtkSmartPointer<vtkLookupTable> scalarbarLut = vtkSmartPointer<vtkLookupTable>::New();
scalarbarLut->SetTableRange (-1, 1);
scalarbarLut->SetNumberOfTableValues(COLOR_MAP_SIZE);
for(int index = 0; index<COLOR_MAP_SIZE;index++)
{
rgb rgbscalar = COLORMAP[index];
scalarbarLut->SetTableValue(index, rgbscalar.r, rgbscalar.g, rgbscalar.b);
}
scalarbarLut->Build();
vtkSmartPointer<vtkScalarBarActor> scalarBar = vtkSmartPointer<vtkScalarBarActor>::New();
scalarBar->SetLookupTable(scalarbarLut);
scalarBar->SetTitle("Color Map");
scalarBar->SetNumberOfLabels(10);
scalarBar->GetTitleTextProperty()->SetColor(0,0,0);
scalarBar->GetTitleTextProperty()->SetFontSize (10);
scalarBar->GetLabelTextProperty()->SetColor(0,0,0);
scalarBar->GetTitleTextProperty()->SetFontSize (10);
scalarBar->SetMaximumHeightInPixels(1000);
scalarBar->SetMaximumWidthInPixels(100);
this->view->GetRenderer()->AddActor(actor);
this->view->GetRenderer()->AddActor2D(scalarBar);
this->SetSPDInteractStyle();
this->view->GetRenderer()->GradientBackgroundOff();
this->view->GetRenderer()->SetBackground(1,1,1);
if( selCol > 0 || unselCol > 0)
{
double p1[3];
double p2[3];
double p3[3];
double length = 0.3;
double angle = pi / 4;
p1[0]= -0.5 + 1.0 / (selCol + unselCol) * selCol;
p1[1]= -0.5;
p1[2]=0;
p2[0]= p1[0];
p2[1]=0.5;
p2[2]=0;
p3[0] = p2[0] + length * cos( angle);
p3[1] = p2[1] + length * sin( angle);
p3[2] = 0;
vtkSmartPointer<vtkLineSource> lineSource = vtkSmartPointer<vtkLineSource>::New();
vtkSmartPointer<vtkLineSource> lineSourceForText = vtkSmartPointer<vtkLineSource>::New();
vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkPolyDataMapper> lineMapperForText = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New();
vtkSmartPointer<vtkActor> lineActorForText = vtkSmartPointer<vtkActor>::New();
lineSource->SetPoint1(p1);
lineSource->SetPoint2(p2);
lineMapper->SetInputConnection(lineSource->GetOutputPort());
lineActor->SetMapper(lineMapper);
lineActor->GetProperty()->SetColor(1,1,1);
lineActor->GetProperty()->SetLineWidth(2);
lineSourceForText->SetPoint1(p2);
lineSourceForText->SetPoint2(p3);
lineMapperForText->SetInputConnection(lineSourceForText->GetOutputPort());
lineActorForText->SetMapper(lineMapperForText);
lineActorForText->GetProperty()->SetColor(1,0,0);
lineActorForText->GetProperty()->SetLineWidth(2);
this->view->GetRenderer()->AddActor(lineActor);
this->view->GetRenderer()->AddActor(lineActorForText);
}
try
{
if( bprogressionHeatmap == false)
{
if(this->clusflag == true)
this->showDendrogram1();
else
{
this->showDendrogram1();
this->showDendrogram2();
}
}
}
catch(...)
{
cout<<"Draw dendrogram failed ! Please try again!"<<endl;
}
this->view->Render();
this->view->GetInteractor()->Start();
}
void TrendHeatmapWindow::addDragLineforSPD(double* worldPosition)
{
if(this->dragLineFlag)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(dragLineActor);
double p1[3];
double p2[3];
p1[0]=worldPosition[0];
p1[1]=-0.75;
p1[2]=0;
p2[0]=worldPosition[0];
p2[1]=0.75;
p2[2]=0;
dragLineSource = vtkSmartPointer<vtkLineSource>::New();
dragLineSource->SetPoint1(p1);
dragLineSource->SetPoint2(p2);
dragLineMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
dragLineMapper->SetInputConnection(dragLineSource->GetOutputPort());
dragLineActor = vtkSmartPointer<vtkActor>::New();
dragLineActor->SetMapper(dragLineMapper);
dragLineActor->GetProperty()->SetColor(0.5,0.7,0);
dragLineActor->GetProperty()->SetLineWidth(1.5);
dragLineActor->DragableOn();
this->view->GetRenderer()->AddActor(dragLineActor);
this->dragLineFlag = true;
this->view->Render();
this->selectClustersforSPD(worldPosition);
}
void TrendHeatmapWindow::selectClustersforSPD(double* worldPosition)
{
reselectedClusterSPD.clear();
clusterNumVec.set_size(parentIndex.size());
for( int i = 0; i < clusterNumVec.size(); i++)
{
clusterNumVec[i] = 0;
}
std::set<long int> selectedClusterSPD;
for( long int index = 0; index < 2 * this->num_samples - 1; index++)
{
if(worldPosition[0] > Processed_Coordinate_Data_Tree1[index][1])
{
selectedClusterSPD.insert(index);
}
}
std::set<long int>::iterator it;
for(it = selectedClusterSPD.begin(); it != selectedClusterSPD.end(); it++)
{
long int id = *it;
long int id1 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][0];
long int id2 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][1];
std::set<long int>::iterator it1 = selectedClusterSPD.find(id1);
std::set<long int>::iterator it2 = selectedClusterSPD.find(id2);
unsigned char num = 0;
if( it1 == selectedClusterSPD.end() && it2 != selectedClusterSPD.end() || it2 == selectedClusterSPD.end() && it1 != selectedClusterSPD.end())
{
num = 1;
}
else if( it1 == selectedClusterSPD.end() && it2 == selectedClusterSPD.end())
{
num = 2;
}
else
{
num = 0;
}
if( parentIndex.size() > 0)
{
if( id <= parentIndex[0])
{
clusterNumVec[0] += num;
}
else
{
for( int j = 0; j < parentIndex.size() - 1; j++)
{
if( id > parentIndex[j] && id <= parentIndex[j+1])
{
clusterNumVec[j+1] += num;
break;
}
}
}
}
}
for( int i = 0; i < clusterNumVec.size(); i++)
{
if( clusterNumVec[i] == 0)
{
clusterNumVec[i] = 1;
}
}
this->reselectClustersforSPD(selectedClusterSPD);
}
void TrendHeatmapWindow::GetSubTreeClusterNum(std::vector<int> &clusterNum)
{
clusterNum.resize( clusterNumVec.size());
for( int i = 0; i < clusterNumVec.size(); i++)
{
clusterNum[i] = clusterNumVec[i];
}
}
void TrendHeatmapWindow::reselectClustersforSPD(std::set<long int>& selectedClusterSPD)
{
std::set<long int>::iterator it;
int clusternumber = 0;
for(it = selectedClusterSPD.begin(); it != selectedClusterSPD.end(); it++)
{
long int id = *it;
long int id1 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][0];
long int id2 = connect_Data_Tree1[rowMapForTreeData.find(id)->second][1];
std::set<long int>::iterator it1 = selectedClusterSPD.find(id1);
std::set<long int>::iterator it2 = selectedClusterSPD.find(id2);
if(it1 == selectedClusterSPD.end())
{
reselectedClusterSPD.insert(id1);
clusternumber++;
}
if(it2 == selectedClusterSPD.end())
{
reselectedClusterSPD.insert(id2);
clusternumber++;
}
}
//cout<<"cluster number is "<<clusternumber<<endl;
std::vector< std::vector< long int> > clusIndex;
std::vector< std::vector< long int> > sampleIndex;
for(it = reselectedClusterSPD.begin(); it != reselectedClusterSPD.end(); it++)
{
std::vector<long int> sampleIdsVec;
std::set<long int> clusIdsforSPD;
std::vector<long int> clusIdsVec;
this->reselectIdsforSPD(*it, &clusIdsforSPD);
for( int i = 0; i < this->num_samples; i++)
{
if(clusIdsforSPD.find(Optimal_Leaf_Order1[i]) != clusIdsforSPD.end())
{
for( int k = 0; k < clusIdsforSPD.size(); k++)
{
int ind = Optimal_Leaf_Order1[i + k];
clusIdsVec.push_back(ind);
for( int j = 0; j < indSPDMapFromIndToVertex[ind].size(); j++)
{
sampleIdsVec.push_back( indSPDMapFromIndToVertex[ind][j]);
}
}
break;
}
}
sampleIndex.push_back(sampleIdsVec);
clusIndex.push_back(clusIdsVec);
}
this->Selection->SetClusterIndex(clusIndex);
this->Selection->SetSampleIndex(sampleIndex);
}
vtkSmartPointer<vtkTable> TrendHeatmapWindow::GetTreeTable()
{
std::vector<std::string> headers;
headers.push_back("node1");
headers.push_back("node2");
headers.push_back("weight");
vtkSmartPointer<vtkTable> table = vtkSmartPointer<vtkTable>::New();
for(int i = 0; i < headers.size(); i++)
{
vtkSmartPointer<vtkDoubleArray> column = vtkSmartPointer<vtkDoubleArray>::New();
column->SetName( headers[i].c_str());
table->AddColumn(column);
}
/// ordering the tree by weight
std::multimap< double, int> treeMap;
for( int i = 0; i < this->table->GetNumberOfRows() - 1; i++)
{
treeMap.insert(std::pair<double, int>(ftreedata[i][2], i));
}
std::vector<int> orderInd(this->table->GetNumberOfRows() - 1);
std::multimap< double, int>::iterator treeMapIter;
int mt = 0;
for(treeMapIter = treeMap.begin(); treeMapIter != treeMap.end(); treeMapIter++)
{
orderInd[mt++] = treeMapIter->second;
}
if( reselectedClusterSPD.size() > 0 && this->ftreedata)
{
std::set<long int>::iterator it;
std::map<long int, int> idMap;
int ind = 0;
for(it = reselectedClusterSPD.begin(); it != reselectedClusterSPD.end(); it++)
{
idMap.insert(std::pair<long int, int>(*it, ind++));
}
for( int i = this->table->GetNumberOfRows() - reselectedClusterSPD.size(); i < this->table->GetNumberOfRows() - 1; i++)
{
vtkSmartPointer<vtkVariantArray> DataRow = vtkSmartPointer<vtkVariantArray>::New();
int pos = orderInd[i];
int node1 = ftreedata[pos][0];
int node2 = ftreedata[pos][1];
int parent = ftreedata[pos][3];
DataRow->InsertNextValue(idMap[ node1]);
DataRow->InsertNextValue(idMap[ node2]);
DataRow->InsertNextValue(pow(this->ftreedata[i][2], POWER_PARAM));
table->InsertNextRow(DataRow);
idMap.insert(std::pair<long int, int>(parent, idMap[ node2]));
}
}
//ftk::SaveTable("TreeTable.txt", table);
return table;
}
void TrendHeatmapWindow::reselectIdsforSPD(long int id, std::set<long int> *clusidforSPD)
{
if(id < this->num_samples)
{
//cout<<id<<"\t";
if( clusidforSPD != NULL)
{
clusidforSPD->insert(id);
}
}
else
{
this->reselectIdsforSPD(connect_Data_Tree1[rowMapForTreeData.find(id)->second][0], clusidforSPD);
this->reselectIdsforSPD(connect_Data_Tree1[rowMapForTreeData.find(id)->second][1], clusidforSPD);
}
}
void TrendHeatmapWindow::setModelsforSPD(vtkSmartPointer<vtkTable> table, ObjectSelection * sels, std::vector< int> selOrder, std::vector< int> unselOrder, std::map< int, int> *indexCluster,
std::vector<int> *component, int numOfComponenets, vnl_matrix<double> *subTreeDistance, ObjectSelection * sels2)
{
this->table = table;
this->indMapFromVertexToInd.clear();
this->indMapFromIndToVertex.clear();
std::cout<< "TrendHeatmapWindow input table: "<<this->table->GetNumberOfRows()<<"\t"<<this->table->GetNumberOfColumns()<<std::endl;
if( indexCluster)
{
indMapFromVertexToInd = *indexCluster;
indSPDMapFromIndToVertex.resize( table->GetNumberOfRows());
std::map<int, int>::iterator iter;
for( iter = indMapFromVertexToInd.begin(); iter != indMapFromVertexToInd.end(); iter++)
{
std::pair<int, int> pair = *iter;
indSPDMapFromIndToVertex[ pair.second].push_back( pair.first);
}
}
if(!sels)
this->Selection = new ObjectSelection();
else
this->Selection = sels;
if(!sels2)
this->Selection2 = new ObjectSelection();
else
this->Selection2 = sels2;
if(component)
{
connectedComponent = *component;
}
selectedFeatureIDs.clear();
for( int i = 0; i < selOrder.size(); i++)
{
selectedFeatureIDs.insert( selOrder[i]);
}
std::cout<< "TrendHeatmapWindow input selected features: "<<selectedFeatureIDs.size()<<std::endl;
connect(Selection, SIGNAL(changed()), this, SLOT(GetSelecectedIDsForSPD()));
if( subTreeDistance != NULL && numOfComponenets >= 1)
{
this->runClusforSPD(selOrder, unselOrder, numOfComponenets, *subTreeDistance);
}
else
{
this->runClusforSPD(selOrder, unselOrder);
}
}
void TrendHeatmapWindow::setModelsforSPD(vtkSmartPointer<vtkTable> table, ObjectSelection * sels, std::vector< int> sampleOrder, std::vector< int> selOrder, std::vector< int> unselOrder, std::map< int, int> *indexCluster, ObjectSelection * sels2)
{
this->table = table;
this->indMapFromVertexToInd.clear();
this->indMapFromIndToVertex.clear();
if( indexCluster)
{
indMapFromVertexToInd = *indexCluster;
indSPDMapFromIndToVertex.resize( table->GetNumberOfRows());
std::map<int, int>::iterator iter;
for( iter = indMapFromVertexToInd.begin(); iter != indMapFromVertexToInd.end(); iter++)
{
std::pair<int, int> pair = *iter;
indSPDMapFromIndToVertex[ pair.second].push_back( pair.first);
}
}
if(!sels)
this->Selection = new ObjectSelection();
else
this->Selection = sels;
if(!sels2)
this->Selection2 = new ObjectSelection();
else
this->Selection2 = sels2;
selectedFeatureIDs.clear();
for( int i = 0; i < selOrder.size(); i++)
{
selectedFeatureIDs.insert( selOrder[i]);
}
//connect(Selection, SIGNAL(thresChanged()), this, SLOT(GetSelecectedIDsforSPD()));
connect(Selection, SIGNAL(changed()), this, SLOT(GetSelecectedIDsForSPD()));
this->runClusforSPD( sampleOrder, selOrder, unselOrder);
}
void TrendHeatmapWindow::runClusforSPD(std::vector< int> selOrder, std::vector< int> unselOrder)
{
this->clusflag = true;
clock_t start_time = clock();
double** datas = new double*[this->table->GetNumberOfRows()];
double** datasforclus = new double*[this->table->GetNumberOfRows()];
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
datas[i] = new double[this->table->GetNumberOfColumns() - 1];
datasforclus[i] = new double[selOrder.size()];
for(int j = 1; j < this->table->GetNumberOfColumns(); j++)
{
vtkVariant temp = this->table->GetValue(i, j);
datas[i][j-1] = temp.ToDouble();
}
for(int j = 0; j < selOrder.size(); j++)
{
int coln = selOrder[j];
datasforclus[i][j] = datas[i][coln];
}
}
clusclus *cc = new clusclus(datasforclus, this->table->GetNumberOfRows(), (int)selOrder.size());
cc->RunClusClus();
int featureNum = selOrder.size() + unselOrder.size();
int* optimalleaforder2 = new int[featureNum];
int counter = 0;
for(int i = 0; i < selOrder.size(); i++)
{
optimalleaforder2[i] = selOrder[i];
counter++;
}
for(int i = 0; i < unselOrder.size(); i++)
{
optimalleaforder2[i + counter] = unselOrder[i];
}
this->setDataForHeatmap( datas, cc->optimalleaforder, optimalleaforder2, this->table->GetNumberOfRows(), featureNum);
this->setDataForDendrograms(cc->treedata);
this->creatDataForHeatmap(POWER_PARAM);
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
delete datas[i];
delete datasforclus[i];
}
delete datas;
delete datasforclus;
delete cc;
std::cout << "Total time to generate progression heatmap is: " << (clock() - start_time) / (float) CLOCKS_PER_SEC << std::endl;
}
void TrendHeatmapWindow::runClusforSPD(std::vector< int> selOrder, std::vector< int> unselOrder, int numberofcomponents, vnl_matrix<double> &subTreeDistance)
{
this->clusflag = true;
if(connectedComponent.size() == this->table->GetNumberOfRows())
{
clock_t start_time = clock();
std::vector< std::vector<int> > graphVertex;
graphVertex.resize(numberofcomponents);
for( int i = 0; i < connectedComponent.size(); i++)
{
int n = connectedComponent[i];
graphVertex[n].push_back(i);
}
double** datas = new double*[this->table->GetNumberOfRows()];
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
datas[i] = new double[this->table->GetNumberOfColumns() - 1];
for(int j = 1; j < this->table->GetNumberOfColumns(); j++)
{
vtkVariant temp = this->table->GetValue(i, j);
datas[i][j-1] = temp.ToDouble();
}
}
std::vector< std::vector< ClusterTree> > treeVec;
treeVec.resize( numberofcomponents);
#pragma omp parallel for
for( int i = 0; i < graphVertex.size(); i++)
{
double** datasforclus = new double*[graphVertex[i].size()];
for (int j = 0; j < graphVertex[i].size(); j++)
{
datasforclus[j] = new double[selOrder.size()];
}
int index = 0;
for(std::set<long int >::iterator iter = selectedFeatureIDs.begin(); iter != selectedFeatureIDs.end(); iter++)
{
for( int k = 0; k < graphVertex[i].size(); k++)
{
int ni = graphVertex[i][k];
datasforclus[k][index] = datas[ni][*iter];
}
index++;
}
clusclus *cc = new clusclus(datasforclus, (int)graphVertex[i].size(), (int)selOrder.size());
cc->RunClusClus();
///save the tree
cc->GetTreeStructure(treeVec[i]);
for (int j = 0; j < graphVertex[i].size(); j++)
{
delete datasforclus[j];
}
delete datasforclus;
delete cc;
}
//std::ofstream ofs("Tree.txt");
/// adjust the local tree index to fit the global tree index
int clusNo = this->table->GetNumberOfRows();
double maxdis = 0; // find the maximum distance of all the tree
std::vector< int> parentIndex;
parentIndex.resize(treeVec.size());
for( int i = 0; i < treeVec.size(); i++)
{
int maxi = treeVec[i].size() + 1;
//ofs<<maxi<<std::endl;
parentIndex[i] = 0;
for( int j = 0; j < treeVec[i].size(); j++)
{
ClusterTree tree = treeVec[i][j];
tree.first = tree.first < maxi ? graphVertex[i][tree.first] : tree.first - maxi + clusNo;
tree.second = tree.second < maxi ? graphVertex[i][tree.second] : tree.second - maxi + clusNo;
tree.parent = tree.parent < maxi ? graphVertex[i][tree.parent] : tree.parent - maxi + clusNo;
treeVec[i][j] = tree;
if(tree.dis > maxdis)
{
maxdis = tree.dis;
}
}
clusNo += treeVec[i].size();
parentIndex[i] = clusNo - 1;
}
this->parentIndex = parentIndex;
/// print out the tree structure
//for( int i = 0; i < treeVec.size(); i++)
//{
// for( int j = 0; j < treeVec[i].size(); j++)
// {
// ClusterTree tree = treeVec[i][j];
// ofs<< tree.first<< "\t"<< tree.second << "\t"<<tree.dis<< "\t"<< tree.parent <<std::endl;
// }
// ofs<< std::endl;
//}
/// construct the overal tree and the overal order
if( maxdis <= 1e-6)
{
maxdis = 1;
}
std::vector< ClusterTree> overallTree;
while(overallTree.size() < numberofcomponents - 1)
{
unsigned int location = subTreeDistance.arg_min();
int nrow = location / subTreeDistance.rows();
int ncol = location % subTreeDistance.rows();
if( parentIndex[nrow] != parentIndex[ncol])
{
ClusterTree tree( parentIndex[nrow], parentIndex[ncol], 2 * maxdis, clusNo);
overallTree.push_back(tree);
subTreeDistance(ncol, nrow)= 1e9;
subTreeDistance(nrow, ncol)= 1e9;
int ind1 = parentIndex[nrow];
int ind2 = parentIndex[ncol];
for( int i = 0; i < parentIndex.size(); i++)
{
if( parentIndex[i] == ind1 || parentIndex[i] == ind2)
{
parentIndex[i] = clusNo;
}
}
clusNo++;
}
else
{
subTreeDistance(ncol, nrow)= 1e9;
subTreeDistance(nrow, ncol)= 1e9;
}
}
//for( int i = 0; i < overallTree.size(); i++)
//{
// ClusterTree tree = overallTree[i];
// //ofs<< tree.first<< "\t"<< tree.second << "\t"<<tree.dis<< "\t"<< tree.parent <<std::endl;
//}
//ofs.close();
int featureNum = selOrder.size() + unselOrder.size();
int* optimalleaforder2 = new int[featureNum];
int counter = 0;
for(int i = 0; i < selOrder.size(); i++)
{
optimalleaforder2[i] = selOrder[i];
counter++;
}
for(int i = 0; i < unselOrder.size(); i++)
{
optimalleaforder2[i + counter] = unselOrder[i];
}
if(ftreedata)
{
for( int i = 0; i < this->table->GetNumberOfRows() - 1; i++)
{
delete ftreedata[i];
}
delete ftreedata;
}
ftreedata = new double*[ this->table->GetNumberOfRows() - 1];
int count = 0;
for( int i = 0; i < treeVec.size(); i++)
{
for( int j = 0; j < treeVec[i].size(); j++)
{
ClusterTree tree = treeVec[i][j];
ftreedata[count] = new double[4];
ftreedata[count][0] = tree.first;
ftreedata[count][1] = tree.second;
ftreedata[count][2] = tree.dis;
ftreedata[count][3] = tree.parent;
count++;
}
}
for(int i = 0; i < overallTree.size(); i++)
{
ClusterTree tree = overallTree[i];
ftreedata[count] = new double[4];
ftreedata[count][0] = tree.first;
ftreedata[count][1] = tree.second;
ftreedata[count][2] = tree.dis;
ftreedata[count][3] = tree.parent;
count++;
}
clusclus *cc1 = new clusclus();
cc1->Initialize(ftreedata, this->table->GetNumberOfRows());
cc1->GetOptimalLeafOrderD();
this->setDataForHeatmap( datas, cc1->optimalleaforder, optimalleaforder2, this->table->GetNumberOfRows(), featureNum);
this->setDataForDendrograms(cc1->treedata);
this->creatDataForHeatmap(POWER_PARAM);
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
delete datas[i];
}
delete datas;
std::cout << "Total time to generate progression heatmap is: " << (clock() - start_time) / (float) CLOCKS_PER_SEC << std::endl;
}
else
{
std::cout<< "Error in component array size"<<std::endl;
}
}
void TrendHeatmapWindow::runClusforSPD(std::vector< int> sampleOrder, std::vector< int> selOrder, std::vector< int> unselOrder)
{
this->clusflag = true;
double** datas;
vtkVariant temp;
int nFeature = selOrder.size() + unselOrder.size();
datas = new double*[this->table->GetNumberOfRows()];
std::cout<<this->table->GetNumberOfRows()<<endl;
std::cout<<this->table->GetNumberOfColumns()<<endl;
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
datas[i] = new double[nFeature + 2 ];
for(int j = 1; j <= nFeature; j++)
{
vtkVariant temp = this->table->GetValue(i, j);
datas[i][j-1] = temp.ToDouble();
}
}
int* optimalleaforder1 = new int[this->table->GetNumberOfRows()];
for(int i = 0; i < sampleOrder.size(); i++)
{
optimalleaforder1[i] = sampleOrder[i];
}
int* optimalleaforder2 = new int[ nFeature];
int counter = 0;
for(int i = 0; i < selOrder.size(); i++)
{
optimalleaforder2[i] = selOrder[i];
counter++;
}
for(int i = 0; i < unselOrder.size(); i++)
{
optimalleaforder2[i + counter] = unselOrder[i];
}
this->setDataForHeatmap( datas, optimalleaforder1, optimalleaforder2, this->table->GetNumberOfRows(), nFeature);
//this->setDataForDendrograms();
this->creatDataForHeatmap(POWER_PARAM);
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
delete datas[i];
}
delete datas;
}
void TrendHeatmapWindow::SelectionCallbackFunctionForSPD(vtkObject* caller, long unsigned int eventId, void* clientData, void* callData )
{
vtkAnnotationLink* annotationLink = static_cast<vtkAnnotationLink*>(caller);
vtkSelection* selection = annotationLink->GetCurrentSelection();
TrendHeatmapWindow* heatmapWin = (TrendHeatmapWindow*)clientData;
vtkSelectionNode* vertices = NULL;
vtkSelectionNode* edges = NULL;
vtkSelectionNode* cells = NULL;
if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = selection->GetNode(0);
}
else if(selection->GetNode(0)->GetFieldType() == vtkSelectionNode::EDGE)
{
edges = selection->GetNode(0);
}
if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::VERTEX)
{
vertices = selection->GetNode(1);
}
else if(selection->GetNode(1)->GetFieldType() == vtkSelectionNode::EDGE)
{
edges = selection->GetNode(1);
}
if( vertices != NULL)
{
vtkIdTypeArray* vertexList = vtkIdTypeArray::SafeDownCast(vertices->GetSelectionList());
std::set<long int> IDs;
if(vertexList->GetNumberOfTuples() > 0)
{
for( vtkIdType i = 0; i < vertexList->GetNumberOfTuples(); i++)
{
long int value = vertexList->GetValue(i);
if( value < 2 * heatmapWin->num_samples - 1)
{
if( heatmapWin->reselectedClusterSPD.find(value) != heatmapWin->reselectedClusterSPD.end())
{
IDs.insert(value);
}
}
else
{
value = value - 2 * heatmapWin->num_samples + 1;
emit heatmapWin->columnToColorChanged(value);
break;
}
}
}
try
{
heatmapWin->SetdenSelectedIdsForSPD( IDs);
}
catch(...)
{
cout<<"SetdenSelectedIds1 failed, please try again !"<<endl;
}
}
}
void TrendHeatmapWindow::SetdenSelectedIdsForSPD(std::set<long int>& IDs)
{
std::set<long int> selectedIDs1;
std::set<long int>::iterator it;
long int id;
if(continueselect == false)
{
if(this->denResetflag1 == 1)
{
for(int i = 0; i<this->dencolors1->GetSize() ; i++)
this->dencolors1->SetValue(i, 0);
denlinesPolyData1->Modified();
//denlinesPolyData1->Update();
denmapper1->Modified();
denmapper1->Update();
denactor1->Modified();
}
}
if( IDs.size() > 0)
{
for( it = IDs.begin(); it != IDs.end(); it++ )
{
id = *it;
if(id < 2*this->num_samples-1)
{
reselectSPDIds1(selectedIDs1, id);
}
}
}
if(selectedIDs1.size() > 0)
{
denmapper1->ScalarVisibilityOn();
denlinesPolyData1->Modified();
//denlinesPolyData1->Update();
denmapper1->Modified();
denmapper1->Update();
denactor1->Modified();
this->view->Render();
this->denResetflag1 = 1;
//std::set<long int>::iterator iter;
//std::set<long int> selectedIDs;
//for( iter = selectedIDs1.begin(); iter != selectedIDs1.end(); iter++)
//{
// long int var = *iter;
// for( int i = 0; i < indSPDMapFromIndToVertex[ var].size(); i++)
// {
// selectedIDs.insert( indSPDMapFromIndToVertex[ var][i]);
// }
//}
try
{
this->Selection2->select(selectedFeatureIDs);
this->Selection->select(selectedIDs1);
}
catch(...)
{
cout<<"Setcelected id after reselect failed, please try again!"<<endl;
}
}
//else
//{
// this->Selection2->clear();
// this->Selection->clear();
//}
}
void TrendHeatmapWindow::GetSelecectedIDsForSPD()
{
std::set<long int> selectedIDs2 = selectedFeatureIDs;
std::set<long int> selectedIDs1 = this->Selection->getSelections();
std::set<long int>::iterator iter1 = selectedIDs1.begin();
std::set<long int>::iterator iter2 = selectedIDs2.begin();
vtkSmartPointer<vtkIdTypeArray> cellids = vtkSmartPointer<vtkIdTypeArray>::New();
cellids->SetNumberOfComponents(1);
int num1 = selectedIDs1.size();
int num2 = selectedIDs2.size();
std::vector<int > IDs1;
std::vector<int > IDs2;
IDs1.resize(num1);
IDs2.resize(num2);
int count1 = 0;
int count2 = 0;
#pragma omp parallel sections
{
#pragma omp section
while(iter1 != selectedIDs1.end())
{
int index1 = *iter1;
int var = indMapFromVertexToInd.find(index1)->second;
int id1 = rowMapFromOriginalToReorder.find(var)->second;
IDs1[count1++] = id1;
iter1++;
}
#pragma omp section
while(iter2 != selectedIDs2.end())
{
int index2 = *iter2;
int id2 = columnMapFromOriginalToReorder.find(index2)->second;
IDs2[count2++] = id2;
iter2++;
}
}
for(int i = 0; i<num1; i++)
for(int j = 0; j<num2; j++)
cellids->InsertNextValue( (IDs1[i])*(this->num_features) + IDs2[j]);
vtkSmartPointer<vtkSelectionNode> selectionNode = vtkSmartPointer<vtkSelectionNode>::New();
selectionNode->SetFieldType(vtkSelectionNode::CELL);
selectionNode->SetContentType(vtkSelectionNode::INDICES);
selectionNode->SetSelectionList(cellids);
vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
selection->AddNode(selectionNode);
vtkSmartPointer<vtkExtractSelection> extractSelection = vtkSmartPointer<vtkExtractSelection>::New();
extractSelection->SetInputData(0, this->aPlane->GetOutput());
extractSelection->SetInputData(1, selection);
extractSelection->Update();
vtkSmartPointer<vtkUnstructuredGrid> selected = vtkSmartPointer<vtkUnstructuredGrid>::New();
selected->ShallowCopy(extractSelection->GetOutput());
vtkSmartPointer<vtkDataSetMapper> selectedMapper = vtkSmartPointer<vtkDataSetMapper>::New();
selectedMapper->SetInputData(selected);
vtkSmartPointer<vtkActor> selectedActor = vtkSmartPointer<vtkActor>::New();
selectedActor->SetMapper(selectedMapper);
selectedActor->GetProperty()->EdgeVisibilityOn();
selectedActor->GetProperty()->SetEdgeColor(1,1,1);
selectedActor->GetProperty()->SetLineWidth(0.5);
if(this->dragLineFlag)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor(dragLineActor);
try
{
if(continueselect == false)
{
if(continueselectnum > 0)
{
cout<<"I'm here "<<continueselectnum<<endl;
for(int i = 0; i<continueselectnum + 1; i++)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor());
continueselectnum = 0;
}
else
{
if (this->removeActorflag != 0)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->RemoveActor (this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActors()->GetLastActor());
}
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor);
this->removeActorflag += 1;
}
else
{
this->continueselectnum += 1;
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(selectedActor);
}
if(this->dragLineFlag)
this->view->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->AddActor(dragLineActor);
this->view->Render();
}
catch(...)
{
cout<<"GetSelecectedIDs failed, please try it again!"<<endl;
}
}
void TrendHeatmapWindow::closeEvent(QCloseEvent *event)
{
mainQTRenderWidget.close();
}
void TrendHeatmapWindow::reRunClus()
{
double** datas;
vtkVariant temp;
datas = new double*[this->table->GetNumberOfRows()];
std::cout<<this->table->GetNumberOfRows()<<endl;
std::cout<<this->table->GetNumberOfColumns()<<endl;
for (int i = 0; i < this->table->GetNumberOfRows(); i++)
{
datas[i] = new double[this->table->GetNumberOfColumns() - 1 + 2 ];
}
for(int i = 0; i < this->table->GetNumberOfRows(); i++)
{
for(int j = 1; j < this->table->GetNumberOfColumns(); j++)
{
temp = this->table->GetValue(i, j);
datas[i][j-1] = temp.ToDouble();
}
}
int* optimalleaforder1 = new int[this->table->GetNumberOfRows()];
for(int i = 0;i<this->table->GetNumberOfRows(); i++)
optimalleaforder1[i]=i;
int* optimalleaforder2 = new int[this->table->GetNumberOfColumns() - 1];
for(int i = 0;i<this->table->GetNumberOfColumns() - 1; i++)
optimalleaforder2[i]=i;
this->setDataForHeatmap(datas, optimalleaforder1, optimalleaforder2,this->table->GetNumberOfRows(), this->table->GetNumberOfColumns() - 1);
this->creatDataForHeatmap(POWER_PARAM);
}
void TrendHeatmapWindow::showGraphforNe()
{
this->drawPointsforNe();
this->aPlane = vtkSmartPointer<vtkPlaneSource>::New();
this->aPlane->SetXResolution(this->num_features);
this->aPlane->SetYResolution(this->num_samples);
this->cellData = vtkSmartPointer<vtkFloatArray>::New();
int index = 0;
for (int i = 0; i < this->num_samples; i++)
{
for(int j = 0; j < this->num_features; j++)
{
cellData->InsertNextValue(index++);
}
}
this->celllut = vtkSmartPointer<vtkLookupTable>::New();
this->celllut->SetNumberOfTableValues(this->num_samples*this->num_features);
this->celllut->SetTableRange(0, this->num_samples*this->num_features - 1);
this->celllut->Build();
int k = 0;
for(int i = 0; i < this->num_samples; i++)
{
for(int j = 0; j < this->num_features; j++)
{
rgb rgb = GetRGBValue( mapdata[num_samples - i - 1][j]);
celllut->SetTableValue(k++, rgb.r, rgb.g, rgb.b);
}
}
this->aPlane->Update();
this->aPlane->GetOutput()->GetCellData()->SetScalars(cellData);
this->mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
this->mapper->SetInputConnection(aPlane->GetOutputPort());
this->mapper->SetScalarRange(0, this->num_samples*this->num_features - 1);
this->mapper->SetLookupTable(celllut);
this->actor = vtkSmartPointer<vtkActor>::New();
this->actor->SetMapper(mapper);
vtkSmartPointer<vtkLookupTable> scalarbarLut = vtkSmartPointer<vtkLookupTable>::New();
scalarbarLut->SetTableRange (-1, 1);
scalarbarLut->SetNumberOfTableValues(COLOR_MAP_SIZE);
for(int index = 0; index<COLOR_MAP_SIZE;index++)
{
rgb rgbscalar = COLORMAP[index];
scalarbarLut->SetTableValue(index, rgbscalar.r, rgbscalar.g, rgbscalar.b);
}
scalarbarLut->Build();
vtkSmartPointer<vtkScalarBarActor> scalarBar = vtkSmartPointer<vtkScalarBarActor>::New();
scalarBar->SetLookupTable(scalarbarLut);
scalarBar->SetTitle("Color Map");
scalarBar->SetNumberOfLabels(10);
scalarBar->GetTitleTextProperty()->SetColor(0,0,0);
scalarBar->GetTitleTextProperty()->SetFontSize (10);
scalarBar->GetLabelTextProperty()->SetColor(0,0,0);
scalarBar->GetTitleTextProperty()->SetFontSize (10);
scalarBar->SetMaximumHeightInPixels(1000);
scalarBar->SetMaximumWidthInPixels(100);
this->view->GetRenderer()->AddActor(actor);
this->view->GetRenderer()->AddActor2D(scalarBar);
this->SetInteractStyle();
this->view->GetRenderer()->GradientBackgroundOff();
this->view->GetRenderer()->SetBackground(1,1,1);
//this->showDendrogram2();
this->view->Render();
//this->view->GetInteractor()->Start();
return;
}
void TrendHeatmapWindow::drawPointsforNe()
{
this->graph_Layout = vtkSmartPointer<vtkMutableUndirectedGraph>::New();
this->view = vtkSmartPointer<vtkGraphLayoutView>::New();
this->view->AddRepresentationFromInput(graph_Layout);
this->view->SetLayoutStrategy("Pass Through");
this->view->ScaledGlyphsOn();
this->theme = vtkSmartPointer<vtkViewTheme>::New();
vtkSmartPointer<vtkPolyData> pd = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New();
verts->SetNumberOfCells(1);
vtkSmartPointer<vtkDoubleArray> orient = vtkSmartPointer<vtkDoubleArray>::New();
orient->SetNumberOfComponents(1);
orient->SetName("orientation");
vtkSmartPointer<vtkStringArray> label = vtkSmartPointer<vtkStringArray>::New();
label->SetNumberOfComponents(1);
label->SetName("label");
vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
for(int i=0; i<this->num_features;i++)
{
pts->InsertNextPoint(this->Processed_Coordinate_Data_Tree2[i][1], 0.5, 0);
}
for(int i=0; i<this->num_features;i++)
{
verts->InsertNextCell(1);
verts->InsertCellPoint(i);
orient->InsertNextValue(45.0);
vtkIdType id = i+1 ;
label->InsertNextValue(this->table->GetColumn(id)->GetName());
}
pd->SetPoints(pts);
pd->SetVerts(verts);
pd->GetPointData()->AddArray(label);
pd->GetPointData()->AddArray(orient);
vtkSmartPointer<vtkPointSetToLabelHierarchy> hier = vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();
hier->SetInputData(pd);
hier->SetOrientationArrayName("orientation");
hier->SetLabelArrayName("label");
hier->GetTextProperty()->SetColor(0.0, 0.0, 0.0);
vtkSmartPointer<vtkLabelPlacementMapper> lmapper = vtkSmartPointer<vtkLabelPlacementMapper>::New();
lmapper->SetInputConnection(hier->GetOutputPort());
vtkSmartPointer<vtkQtLabelRenderStrategy> strategy = vtkSmartPointer<vtkQtLabelRenderStrategy>::New();
lmapper->SetRenderStrategy(strategy);
lmapper->SetShapeToNone();
lmapper->SetBackgroundOpacity(0.0);
lmapper->SetMargin(0);
vtkSmartPointer<vtkActor2D> lactor = vtkSmartPointer<vtkActor2D>::New();
lactor->SetMapper(lmapper);
vtkSmartPointer<vtkPolyDataMapper> rmapper = vtkSmartPointer<vtkPolyDataMapper>::New();
rmapper->SetInputData(pd);
vtkSmartPointer<vtkActor> ractor = vtkSmartPointer<vtkActor>::New();
ractor->SetMapper(rmapper);
this->view->GetRenderer()->AddActor(lactor);
this->view->GetRenderer()->AddActor(ractor);
this->selectionCallback1 = vtkSmartPointer<vtkCallbackCommand>::New();
this->selectionCallback1->SetClientData(this);
this->selectionCallback1->SetCallback (SelectionCallbackFunction1);
this->view->GetRepresentation()->GetAnnotationLink()->AddObserver("AnnotationChangedEvent", this->selectionCallback1);
}
| 30.399753
| 246
| 0.689606
|
RoysamLab
|
f8c183669d511351d46bb0da7553277ff7b2d98b
| 2,009
|
cpp
|
C++
|
src/base/throw_lock_exception.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
src/base/throw_lock_exception.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
src/base/throw_lock_exception.cpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "throw_lock_exception.hpp"
#include <cppdevtk/base/lock_exception.hpp>
#include <cppdevtk/base/deadlock_exception.hpp>
#include <cppdevtk/base/cassert.hpp>
namespace cppdevtk {
namespace base {
namespace detail {
#if (CPPDEVTK_HAVE_CPP11_SYSTEM_ERROR)
void ThrowLockException(const ::std::system_error& exc) {
const ::std::error_code& kErrorCode = exc.code();
if (kErrorCode == ::std::errc::resource_deadlock_would_occur) {
throw CPPDEVTK_DEADLOCK_EXCEPTION_WA(exc.what());
}
if (kErrorCode.category() == ::std::system_category()) {
throw CPPDEVTK_LOCK_EXCEPTION_W_EC_WA(ErrorCode(kErrorCode.value(), SystemCategoryRef()), exc.what());
}
CPPDEVTK_ASSERT(kErrorCode.category() == ::std::generic_category());
throw CPPDEVTK_LOCK_EXCEPTION_W_EC_WA(ErrorCode(kErrorCode.value(), GenericCategoryRef()), exc.what());
}
#endif
} // namespace detail
} // namespace base
} // namespace cppdevtk
| 37.203704
| 126
| 0.628173
|
CoSoSys
|
f8c629278f4b2e121781e1e7350441168f9c06a1
| 1,025
|
hpp
|
C++
|
a21/eeprom.hpp
|
biappi/a21
|
6d008bebdbd6c51816ed61aa45664fa3b2715d9b
|
[
"MIT"
] | 6
|
2017-07-28T13:36:24.000Z
|
2022-01-30T14:00:32.000Z
|
a21/eeprom.hpp
|
carkang/a21
|
8f472e75de5734514f152828033a93b88401069a
|
[
"MIT"
] | 3
|
2018-10-26T20:10:49.000Z
|
2021-05-15T20:31:45.000Z
|
a21/eeprom.hpp
|
carkang/a21
|
8f472e75de5734514f152828033a93b88401069a
|
[
"MIT"
] | 2
|
2021-02-14T14:12:58.000Z
|
2022-01-13T23:08:26.000Z
|
//
// a21 — Arduino Toolkit.
// Copyright (C) 2016-2018, Aleh Dzenisiuk. http://github.com/aleh/a21
//
#pragma once
#include "Arduino.h"
namespace a21 {
/**
* Digispark boards have no EEPROM library, so here is a simple one.
* TODO: something is wrong here, investigate
*/
class EEPROM {
public:
static uint8_t read(uint16_t address) {
// Wait for any previous write to complete.
while (EECR & _BV(EEPE))
;
EEARL = address;
EECR |= _BV(EERE);
return EEDR;
}
static void update(uint16_t address, uint8_t data) {
if (read(address) == data)
return;
// No need to wait for the prvious write to complete, already did this in read().
// Make sure we'll use Erase & Write in one operation.
EECR &= ~(_BV(EEPM1) | _BV(EEPM0));
EEARL = address;
EEDR = data;
// These two bits have to be set separately: first Master Program Enable, then Program Enable.
EECR |= _BV(EEMPE);
EECR |= _BV(EEPE);
}
};
} // namespace a21
| 21.354167
| 98
| 0.620488
|
biappi
|
f8c6dc2c4a65dcfd565e941fc5cb749c49236333
| 1,135
|
cc
|
C++
|
color_01.cc
|
bellcorreia/learn-gl
|
c9be56b1a9b7da984b0d499df8b92fbe11e8a75c
|
[
"MIT"
] | 3
|
2022-01-04T01:23:25.000Z
|
2022-01-04T01:28:45.000Z
|
color_01.cc
|
bellcorreia/learn-gl
|
c9be56b1a9b7da984b0d499df8b92fbe11e8a75c
|
[
"MIT"
] | null | null | null |
color_01.cc
|
bellcorreia/learn-gl
|
c9be56b1a9b7da984b0d499df8b92fbe11e8a75c
|
[
"MIT"
] | null | null | null |
/*
* Source code written by Gabriel Correia
*/
#include <iostream>
#include <GLFW/glfw3.h>
constexpr GLint WINDOW_WIDTH = 640, WINDOW_HEIGHT = 480;
static GLfloat current_colors[3];
int main (int argc, char **argv)
{
GLFWwindow *main_window;
glfwInit ();
/* Creating a window to render into it */
main_window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
"Color 01", nullptr, nullptr);
glfwMakeContextCurrent (main_window);
while (! glfwWindowShouldClose (main_window)) {
/* Collecting the current color buffer */
glGetFloatv (GL_CURRENT_COLOR, current_colors);
std::printf ("Current colors R: %f G: %f B: %f\n",
current_colors[0], current_colors[1], current_colors[2]);
glClear (GL_COLOR_BUFFER_BIT);
glBegin (GL_TRIANGLES);
glColor3f (1.0f, 0.0f, 0.0f);
glVertex2f (-0.5f, 0.0f);
glVertex2f (0.0f, 0.5f);
glVertex2f (0.5f, 0.0f);
glEnd ();
glfwSwapBuffers (main_window);
glfwPollEvents ();
}
glfwDestroyWindow (main_window);
glfwTerminate ();
return 0;
}
| 22.254902
| 69
| 0.626432
|
bellcorreia
|
f8c7df245a2677f66e71e3f19d199835a45839c7
| 661
|
cpp
|
C++
|
codeforces/cf584 div2/B.cpp
|
songhn233/ACM_Steps
|
6f2edeca9bf4fc999a8148bc90b2d8d0e59d48fe
|
[
"CC0-1.0"
] | 1
|
2020-08-10T21:40:21.000Z
|
2020-08-10T21:40:21.000Z
|
codeforces/cf584 div2/B.cpp
|
songhn233/Algorithm-Packages
|
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
|
[
"CC0-1.0"
] | null | null | null |
codeforces/cf584 div2/B.cpp
|
songhn233/Algorithm-Packages
|
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
|
[
"CC0-1.0"
] | null | null | null |
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#define ll long long
using namespace std;
const int inf=0x3f3f3f3f;
int n;
string s;
int a[110],b[110],c[110];
int p[10500];
int main()
{
int ans=0;
cin>>n;
cin>>s;
for(int i=1;i<=n;i++) cin>>a[i]>>b[i];
for(int i=0;i<s.size();i++) c[i+1]=s[i]-'0';
for(int i=1;i<=n;i++) if(c[i]==1) p[0]++;
ans=p[0];
for(int i=1;i<=n;i++)
{
for(int j=1;j<=b[i]-1;j++) p[j]+=c[i];
for(int j=0;j<=10000;j++)
{
if(b[i]+j>=10010) break;
if(j%a[i]==0)
{
c[i]^=1;
}
p[b[i]+j]+=c[i];
}
}
for(int i=1;i<=10000;i++) ans=max(ans,p[i]);
cout<<ans<<endl;
return 0;
}
| 16.525
| 45
| 0.526475
|
songhn233
|
f8c980368e2aee02760aeed67828c6e39659f62c
| 1,478
|
cpp
|
C++
|
samples/snippets/cpp/VS_Snippets_CLR/DateTime.ToLocalTime ToUniversalTime/CPP/class1.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 421
|
2018-04-01T01:57:50.000Z
|
2022-03-28T15:24:42.000Z
|
samples/snippets/cpp/VS_Snippets_CLR/DateTime.ToLocalTime ToUniversalTime/CPP/class1.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 5,797
|
2018-04-02T21:12:23.000Z
|
2022-03-31T23:54:38.000Z
|
samples/snippets/cpp/VS_Snippets_CLR/DateTime.ToLocalTime ToUniversalTime/CPP/class1.cpp
|
hamarb123/dotnet-api-docs
|
6aeb55784944a2f1f5e773b657791cbd73a92dd4
|
[
"CC-BY-4.0",
"MIT"
] | 1,482
|
2018-03-31T11:26:20.000Z
|
2022-03-30T22:36:45.000Z
|
// <Snippet1>
using namespace System;
void main()
{
Console::WriteLine("Enter a date and time.");
String^ strDateTime = Console::ReadLine();
DateTime localDateTime, univDateTime;
try
{
localDateTime = DateTime::Parse(strDateTime);
univDateTime = localDateTime.ToUniversalTime();
Console::WriteLine("{0} local time is {1} universal time.",
localDateTime, univDateTime );
}
catch (FormatException^)
{
Console::WriteLine("Invalid format.");
return;
}
Console::WriteLine("Enter a date and time in universal time.");
strDateTime = Console::ReadLine();
try
{
univDateTime = DateTime::Parse(strDateTime);
localDateTime = univDateTime.ToLocalTime();
Console::WriteLine("{0} universal time is {1} local time.",
univDateTime, localDateTime );
}
catch (FormatException^)
{
Console::WriteLine("Invalid format.");
return;
}
}
// The example displays output like the following when run on a
// computer whose culture is en-US in the Pacific Standard Time zone:
// Enter a date and time.
// 12/10/2015 6:18 AM
// 12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time.
// Enter a date and time in universal time.
// 12/20/2015 6:42:00
// 12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time.
// </Snippet1>
| 30.163265
| 82
| 0.610961
|
hamarb123
|
f8d257f0360fde0eb66b77bd3c933a66cf52e0bb
| 5,483
|
hpp
|
C++
|
tools/material_munge/src/terrain_materials_config.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 13
|
2019-03-25T09:40:12.000Z
|
2022-03-13T16:12:39.000Z
|
tools/material_munge/src/terrain_materials_config.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 110
|
2018-10-16T09:05:43.000Z
|
2022-03-16T23:32:28.000Z
|
tools/material_munge/src/terrain_materials_config.hpp
|
SleepKiller/swbfii-shaderpatch
|
b49ce3349d4dd09b19237ff4766652166ba1ffd4
|
[
"MIT"
] | 1
|
2020-02-06T20:32:50.000Z
|
2020-02-06T20:32:50.000Z
|
#pragma once
#include "glm_yaml_adapters.hpp"
#include <map>
#include <string>
#include <yaml-cpp/yaml.h>
namespace sp {
enum class Terrain_bumpmapping {
normal_mapping,
parallax_offset_mapping,
parallax_occlusion_mapping
};
enum class Terrain_blending { height, basic };
enum class Terrain_rendertype { normal_ext, pbr };
enum class Terrain_far { downsampled, fullres };
struct Terrain_material {
std::string albedo_map;
std::string normal_map;
std::string metallic_roughness_map;
std::string ao_map;
std::string height_map;
std::string diffuse_map;
std::string gloss_map;
float height_scale;
float specular_exponent;
};
struct Terrain_materials_config {
bool use_envmap = false;
std::string envmap_name;
bool use_ze_static_lighting = false;
bool srgb_diffuse_maps = false;
Terrain_bumpmapping bumpmapping = Terrain_bumpmapping::parallax_offset_mapping;
Terrain_blending blending = Terrain_blending::height;
Terrain_rendertype rendertype = Terrain_rendertype::normal_ext;
Terrain_far far_terrain = Terrain_far::fullres;
glm::vec3 base_color = {1.0f, 1.0f, 1.0f};
float base_metallicness = 1.0f;
float base_roughness = 1.0f;
glm::vec3 diffuse_color = {1.0f, 1.0f, 1.0f};
glm::vec3 specular_color = {1.0f, 1.0f, 1.0f};
glm::vec3 terrain_offset = {0.0f, 0.0f, 0.0f};
std::map<std::string, Terrain_material, std::less<>> materials;
};
}
namespace YAML {
template<>
struct convert<sp::Terrain_material> {
static bool decode(const Node& node, sp::Terrain_material& material)
{
using namespace std::literals;
material.albedo_map = node["AlbedoMap"s].as<std::string>("$null_albedomap"s);
material.normal_map = node["NormalMap"s].as<std::string>("$null_normalmap"s);
material.metallic_roughness_map =
node["MetallicRoughnessMap"s].as<std::string>("$null_metallic_roughnessmap"s);
material.ao_map = node["AOMap"s].as<std::string>("$null_ao"s);
material.height_map = node["HeightMap"s].as<std::string>("$null_heightmap"s);
material.diffuse_map = node["DiffuseMap"s].as<std::string>("$null_diffusemap"s);
material.gloss_map = node["GlossMap"s].as<std::string>("$null_glossmap"s);
material.height_scale = node["HeightScale"s].as<float>(0.05f);
material.specular_exponent = node["SpecularExponent"s].as<float>(64.0f);
return true;
}
};
template<>
struct convert<sp::Terrain_materials_config> {
static bool decode(const Node& node, sp::Terrain_materials_config& config)
{
using namespace std::literals;
auto global = node["Global"];
config.use_envmap = global["UseEnvironmentMapping"s].as<bool>(false);
config.envmap_name = global["EnvironmentMap"s].as<std::string>(""s);
config.use_ze_static_lighting = global["UseZEStaticLighting"s].as<bool>(false);
config.srgb_diffuse_maps = global["sRGBDiffuseMaps"s].as<bool>(true);
if (const auto bumpmapping =
global["BumpMappingType"s].as<std::string>("Normal Mapping"s);
bumpmapping == "Normal Mapping"sv) {
config.bumpmapping = sp::Terrain_bumpmapping::normal_mapping;
}
else if (bumpmapping == "Parallax Offset Mapping"sv) {
config.bumpmapping = sp::Terrain_bumpmapping::parallax_offset_mapping;
}
else if (bumpmapping == "Parallax Occlusion Mapping"sv) {
config.bumpmapping = sp::Terrain_bumpmapping::parallax_occlusion_mapping;
}
else {
throw std::runtime_error{"Invalid BumpMappingType"s};
}
if (const auto rendertype = global["Rendertype"s].as<std::string>("normal_ext"s);
rendertype == "normal_ext"sv) {
config.rendertype = sp::Terrain_rendertype::normal_ext;
}
else if (rendertype == "pbr"sv) {
config.rendertype = sp::Terrain_rendertype::pbr;
}
else {
throw std::runtime_error{"Invalid Rendertype"s};
}
if (const auto blending = global["BlendingMode"s].as<std::string>("Height"s);
blending == "Height"sv) {
config.blending = sp::Terrain_blending::height;
}
else if (blending == "Basic"sv) {
config.blending = sp::Terrain_blending::basic;
}
else {
throw std::runtime_error{"Invalid BlendingMode"s};
}
if (const auto lowres = global["FarTerrain"s].as<std::string>("Fullres"s);
lowres == "Downsampled"sv) {
config.far_terrain = sp::Terrain_far::downsampled;
}
else if (lowres == "Fullres"sv) {
config.far_terrain = sp::Terrain_far::fullres;
}
else {
throw std::runtime_error{"Invalid FarTerrain"s};
}
config.base_color =
global["BaseColor"s].as<glm::vec3>(glm::vec3{1.f, 1.f, 1.f});
config.base_metallicness = global["BaseMetallicness"s].as<float>(1.f);
config.base_roughness = global["BaseRoughness"s].as<float>(1.f);
config.diffuse_color =
global["DiffuseColor"s].as<glm::vec3>(glm::vec3{1.f, 1.f, 1.f});
config.specular_color =
global["SpecularColor"s].as<glm::vec3>(glm::vec3{1.f, 1.f, 1.f});
config.terrain_offset =
global["TerrainOffset"s].as<glm::vec3>(glm::vec3{0.f, 0.f, 0.f});
for (auto& entry : node["Materials"s]) {
config.materials.emplace(entry.first.as<std::string>(),
entry.second.as<sp::Terrain_material>());
}
return true;
}
};
}
| 33.03012
| 87
| 0.658216
|
SleepKiller
|
f8dae235fa90e0545ee41a44ec680b491ded08e2
| 1,248
|
cpp
|
C++
|
src/cheat.cpp
|
trademarks/OpenTTD
|
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
|
[
"Unlicense"
] | 8
|
2016-10-21T09:01:43.000Z
|
2021-05-31T06:32:14.000Z
|
src/cheat.cpp
|
blackberry/OpenTTD
|
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
|
[
"Unlicense"
] | null | null | null |
src/cheat.cpp
|
blackberry/OpenTTD
|
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
|
[
"Unlicense"
] | 4
|
2017-05-16T00:15:58.000Z
|
2020-08-06T01:46:31.000Z
|
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file cheat.cpp Handling (loading/saving/initializing) of cheats. */
#include "stdafx.h"
#include "cheat_type.h"
/** All the cheats. */
Cheats _cheats;
/** Reinitialise all the cheats. */
void InitializeCheats()
{
memset(&_cheats, 0, sizeof(Cheats));
}
/**
* Return true if any cheat has been used, false otherwise
* @return has a cheat been used?
*/
bool CheatHasBeenUsed()
{
/* Cannot use lengthof because _cheats is of type Cheats, not Cheat */
const Cheat *cht = (Cheat*)&_cheats;
const Cheat *cht_last = &cht[sizeof(_cheats) / sizeof(Cheat)];
for (; cht != cht_last; cht++) {
if (cht->been_used) return true;
}
return false;
}
| 31.2
| 185
| 0.717147
|
trademarks
|
f8e5ce73263ee7d6e7301d3ce396c89339d5b702
| 715
|
cc
|
C++
|
roommanager.cc
|
goon-3/roguekarako
|
8f745564dec9f17050eaff1097e52ae720695dd6
|
[
"BSD-3-Clause"
] | null | null | null |
roommanager.cc
|
goon-3/roguekarako
|
8f745564dec9f17050eaff1097e52ae720695dd6
|
[
"BSD-3-Clause"
] | null | null | null |
roommanager.cc
|
goon-3/roguekarako
|
8f745564dec9f17050eaff1097e52ae720695dd6
|
[
"BSD-3-Clause"
] | null | null | null |
//See the LICENSE file for details
#include <SDL/SDL.h>
#include <list>
#include <iostream>
#include "roommanager.h"
#include "roomkarakovillage.h"
RoomManager::RoomManager(int roomnr)
{
switch(roomnr) {
case 0:{
_current = RoomKarakoVillage();
}
default:
_current = RoomKarakoVillage();
}
}
RoomManager::~RoomManager()
{}
Room& RoomManager::getr()
{
return _current;
}
void RoomManager::update(Coord& xyz, Coord& mxyz)
{
_current.setx(xyz.getx());
_current.sety(xyz.gety());
}
void RoomManager::draw(Screen& screen)
{
SDL_Rect r;
r.x = _current.getx();
r.y = _current.gety();
SDL_Surface *bg = _current.getbg();
SDL_Surface *s = screen.gets();
SDL_BlitSurface(bg, NULL, s, &r);
}
| 15.212766
| 49
| 0.67972
|
goon-3
|
25c82a565ae26ce2539e1bc6dabf955d252d5ca0
| 12,802
|
cpp
|
C++
|
include/PKAssets/PKAsset.cpp
|
konstatoivanen/PKAssetTools
|
be14601ae31df164147e4ed8b8674b6deb0dbcb6
|
[
"MIT"
] | 2
|
2022-02-05T20:32:01.000Z
|
2022-02-13T10:50:05.000Z
|
include/PKAssets/PKAsset.cpp
|
konstatoivanen/PKAssetTools
|
be14601ae31df164147e4ed8b8674b6deb0dbcb6
|
[
"MIT"
] | 1
|
2022-02-01T07:04:31.000Z
|
2022-02-02T14:46:44.000Z
|
PKRenderer/include/PKAssets/PKAsset.cpp
|
konstatoivanen/PKRenderer
|
90a2856bf79a117d099981b63aef28331d085625
|
[
"MIT"
] | null | null | null |
#include "PKAsset.h"
#include <string>
namespace PK::Assets
{
PKElementType GetElementType(const char* string)
{
std::string format(string);
if (format == "half")
{
return PKElementType::Half;
}
if (format == "half2")
{
return PKElementType::Half2;
}
if (format == "half3")
{
return PKElementType::Half3;
}
if (format == "half4")
{
return PKElementType::Half4;
}
if (format == "float")
{
return PKElementType::Float;
}
if (format == "float2")
{
return PKElementType::Float2;
}
if (format == "float3")
{
return PKElementType::Float3;
}
if (format == "float4")
{
return PKElementType::Float4;
}
if (format == "double")
{
return PKElementType::Double;
}
if (format == "double2")
{
return PKElementType::Double2;
}
if (format == "double3")
{
return PKElementType::Double3;
}
if (format == "double4")
{
return PKElementType::Double4;
}
if (format == "short")
{
return PKElementType::Short;
}
if (format == "short2")
{
return PKElementType::Short2;
}
if (format == "short3")
{
return PKElementType::Short3;
}
if (format == "short4")
{
return PKElementType::Short4;
}
if (format == "ushort")
{
return PKElementType::Ushort;
}
if (format == "ushort2")
{
return PKElementType::Ushort2;
}
if (format == "ushort3")
{
return PKElementType::Ushort3;
}
if (format == "ushort4")
{
return PKElementType::Ushort4;
}
if (format == "int")
{
return PKElementType::Int;
}
if (format == "int2")
{
return PKElementType::Int2;
}
if (format == "int3")
{
return PKElementType::Int3;
}
if (format == "int4")
{
return PKElementType::Int4;
}
if (format == "uint")
{
return PKElementType::Uint;
}
if (format == "uint2")
{
return PKElementType::Uint2;
}
if (format == "uint3")
{
return PKElementType::Uint3;
}
if (format == "uint4")
{
return PKElementType::Uint4;
}
if (format == "long")
{
return PKElementType::Long;
}
if (format == "long2")
{
return PKElementType::Long2;
}
if (format == "long3")
{
return PKElementType::Long3;
}
if (format == "long4")
{
return PKElementType::Long4;
}
if (format == "ulong")
{
return PKElementType::Ulong;
}
if (format == "ulong2")
{
return PKElementType::Ulong2;
}
if (format == "ulong3")
{
return PKElementType::Ulong3;
}
if (format == "ulong4")
{
return PKElementType::Ulong4;
}
if (format == "half2x2")
{
return PKElementType::Half2x2;
}
if (format == "half3x3")
{
return PKElementType::Half3x3;
}
if (format == "half4x4")
{
return PKElementType::Half4x4;
}
if (format == "float2x2")
{
return PKElementType::Float2x2;
}
if (format == "float3x3")
{
return PKElementType::Float3x3;
}
if (format == "float4x4")
{
return PKElementType::Float4x4;
}
if (format == "double2x2")
{
return PKElementType::Double2x2;
}
if (format == "double3x3")
{
return PKElementType::Double3x3;
}
if (format == "double4x4")
{
return PKElementType::Double4x4;
}
if (format == "texture2D")
{
return PKElementType::Texture2DHandle;
}
if (format == "texture3D")
{
return PKElementType::Texture3DHandle;
}
if (format == "textureCube")
{
return PKElementType::TextureCubeHandle;
}
return PKElementType::Invalid;
}
uint32_t Assets::GetElementSize(PKElementType type)
{
switch (type)
{
case PKElementType::Float: return 4;
case PKElementType::Float2: return 4 * 2;
case PKElementType::Float3: return 4 * 3;
case PKElementType::Float4: return 4 * 4;
case PKElementType::Double: return 8;
case PKElementType::Double2: return 8 * 2;
case PKElementType::Double3: return 8 * 3;
case PKElementType::Double4: return 8 * 4;
case PKElementType::Half: return 2;
case PKElementType::Half2: return 2 * 2;
case PKElementType::Half3: return 2 * 3;
case PKElementType::Half4: return 2 * 4;
case PKElementType::Int: return 4;
case PKElementType::Int2: return 4 * 2;
case PKElementType::Int3: return 4 * 3;
case PKElementType::Int4: return 4 * 4;
case PKElementType::Uint: return 4;
case PKElementType::Uint2: return 4 * 2;
case PKElementType::Uint3: return 4 * 3;
case PKElementType::Uint4: return 4 * 4;
case PKElementType::Short: return 2;
case PKElementType::Short2: return 2 * 2;
case PKElementType::Short3: return 2 * 3;
case PKElementType::Short4: return 2 * 4;
case PKElementType::Ushort: return 2;
case PKElementType::Ushort2: return 2 * 2;
case PKElementType::Ushort3: return 2 * 3;
case PKElementType::Ushort4: return 2 * 4;
case PKElementType::Long: return 8;
case PKElementType::Long2: return 8 * 2;
case PKElementType::Long3: return 8 * 3;
case PKElementType::Long4: return 8 * 4;
case PKElementType::Ulong: return 8;
case PKElementType::Ulong2: return 8 * 2;
case PKElementType::Ulong3: return 8 * 3;
case PKElementType::Ulong4: return 8 * 4;
case PKElementType::Float2x2: return 4 * 2 * 2;
case PKElementType::Float3x3: return 4 * 3 * 3;
case PKElementType::Float4x4: return 4 * 4 * 4;
case PKElementType::Double2x2: return 8 * 2 * 2;
case PKElementType::Double3x3: return 8 * 3 * 3;
case PKElementType::Double4x4: return 8 * 4 * 4;
case PKElementType::Half2x2: return 2 * 2 * 2;
case PKElementType::Half3x3: return 2 * 3 * 3;
case PKElementType::Half4x4: return 2 * 4 * 4;
case PKElementType::Texture2DHandle: return 4;
case PKElementType::Texture3DHandle: return 4;
case PKElementType::TextureCubeHandle: return 4;
}
return 0;
}
uint32_t Assets::GetElementAlignment(PKElementType type)
{
switch (type)
{
case PKElementType::Float: return 4;
case PKElementType::Float2: return 4 * 2;
case PKElementType::Float3: return 4 * 4;
case PKElementType::Float4: return 4 * 4;
case PKElementType::Double: return 8;
case PKElementType::Double2: return 8 * 2;
case PKElementType::Double3: return 8 * 4;
case PKElementType::Double4: return 8 * 4;
case PKElementType::Half: return 2;
case PKElementType::Half2: return 2 * 2;
case PKElementType::Half3: return 2 * 4;
case PKElementType::Half4: return 2 * 4;
case PKElementType::Int: return 4;
case PKElementType::Int2: return 4 * 2;
case PKElementType::Int3: return 4 * 4;
case PKElementType::Int4: return 4 * 4;
case PKElementType::Uint: return 4;
case PKElementType::Uint2: return 4 * 2;
case PKElementType::Uint3: return 4 * 4;
case PKElementType::Uint4: return 4 * 4;
case PKElementType::Short: return 2;
case PKElementType::Short2: return 2 * 2;
case PKElementType::Short3: return 2 * 4;
case PKElementType::Short4: return 2 * 4;
case PKElementType::Ushort: return 2;
case PKElementType::Ushort2: return 2 * 2;
case PKElementType::Ushort3: return 2 * 4;
case PKElementType::Ushort4: return 2 * 4;
case PKElementType::Long: return 8;
case PKElementType::Long2: return 8 * 2;
case PKElementType::Long3: return 8 * 4;
case PKElementType::Long4: return 8 * 4;
case PKElementType::Ulong: return 8;
case PKElementType::Ulong2: return 8 * 2;
case PKElementType::Ulong3: return 8 * 4;
case PKElementType::Ulong4: return 8 * 4;
case PKElementType::Float2x2: return 4 * 2;
case PKElementType::Float3x3: return 4 * 4;
case PKElementType::Float4x4: return 4 * 4;
case PKElementType::Double2x2: return 8 * 2;
case PKElementType::Double3x3: return 8 * 4;
case PKElementType::Double4x4: return 8 * 4;
case PKElementType::Half2x2: return 2 * 2;
case PKElementType::Half3x3: return 2 * 4;
case PKElementType::Half4x4: return 2 * 4;
case PKElementType::Texture2DHandle: return 4;
case PKElementType::Texture3DHandle: return 4;
case PKElementType::TextureCubeHandle: return 4;
}
return 0;
}
uint32_t Assets::GetElementComponents(PKElementType type)
{
switch (type)
{
case PKElementType::Float: return 1;
case PKElementType::Float2: return 2;
case PKElementType::Float3: return 3;
case PKElementType::Float4: return 4;
case PKElementType::Double: return 1;
case PKElementType::Double2: return 2;
case PKElementType::Double3: return 3;
case PKElementType::Double4: return 4;
case PKElementType::Half: return 1;
case PKElementType::Half2: return 2;
case PKElementType::Half3: return 3;
case PKElementType::Half4: return 4;
case PKElementType::Int: return 1;
case PKElementType::Int2: return 2;
case PKElementType::Int3: return 3;
case PKElementType::Int4: return 4;
case PKElementType::Uint: return 1;
case PKElementType::Uint2: return 2;
case PKElementType::Uint3: return 3;
case PKElementType::Uint4: return 4;
case PKElementType::Short: return 1;
case PKElementType::Short2: return 2;
case PKElementType::Short3: return 3;
case PKElementType::Short4: return 4;
case PKElementType::Ushort: return 1;
case PKElementType::Ushort2: return 2;
case PKElementType::Ushort3: return 3;
case PKElementType::Ushort4: return 4;
case PKElementType::Long: return 1;
case PKElementType::Long2: return 2;
case PKElementType::Long3: return 3;
case PKElementType::Long4: return 4;
case PKElementType::Ulong: return 1;
case PKElementType::Ulong2: return 2;
case PKElementType::Ulong3: return 3;
case PKElementType::Ulong4: return 4;
case PKElementType::Float2x2: return 2;
case PKElementType::Float3x3: return 3;
case PKElementType::Float4x4: return 4;
case PKElementType::Double2x2: return 2;
case PKElementType::Double3x3: return 3;
case PKElementType::Double4x4: return 4;
case PKElementType::Half2x2: return 2;
case PKElementType::Half3x3: return 3;
case PKElementType::Half4x4: return 4;
case PKElementType::Texture2DHandle: return 1;
case PKElementType::Texture3DHandle: return 1;
case PKElementType::TextureCubeHandle: return 1;
}
return 0;
}
}
| 30.264775
| 61
| 0.524606
|
konstatoivanen
|
25d7e7e6d3bfb9512f36ced7dd1dd7638413ec53
| 4,380
|
cc
|
C++
|
test/alog_test1.cc
|
hfuj13/alog
|
5443a60ffafb0e9767710185257bb9c27711a452
|
[
"MIT"
] | null | null | null |
test/alog_test1.cc
|
hfuj13/alog
|
5443a60ffafb0e9767710185257bb9c27711a452
|
[
"MIT"
] | null | null | null |
test/alog_test1.cc
|
hfuj13/alog
|
5443a60ffafb0e9767710185257bb9c27711a452
|
[
"MIT"
] | null | null | null |
#include <thread>
#include "gtest/gtest.h"
#include "alog.hpp"
using namespace std;
using namespace hf;
TEST(alog, init)
{
// いきなり使っても落ちないことを確認
alog log;
log << "no print" << endl;
// ログレベル初期値を確認
alog::level_t expected = alog::SILENT;
alog::level_t actual = log.level();
ASSERT_EQ(expected, actual);
}
// UNDER_LVL, OVER_LVLは指定できないこと・落ちることを確認 (DEATH TEST)
TEST(alog, invalid_level)
{
alog log;
ASSERT_DEATH(log.level(alog::UNDER_LVL), "");
ASSERT_DEATH(log.level(alog::OVER_LVL), "");
}
// 設定したレベルであることを確認
TEST(alog, set_get_level)
{
alog log(cout);
{
alog::level_t expected = alog::VERBOSE;
log.level(expected);
alog::level_t actual = log.level();
ASSERT_EQ(expected, actual);
}
{
alog::level_t expected = alog::DEBUG;
log.level(expected);
alog::level_t actual = log.level();
ASSERT_EQ(expected, actual);
}
{
alog::level_t expected = alog::INFO;
log.level(expected);
alog::level_t actual = log.level();
ASSERT_EQ(expected, actual);
}
{
alog::level_t expected = alog::WARNING;
log.level(expected);
alog::level_t actual = log.level();
ASSERT_EQ(expected, actual);
}
{
alog::level_t expected = alog::ERROR;
log.level(expected);
alog::level_t actual = log.level();
ASSERT_EQ(expected, actual);
}
{
alog::level_t expected = alog::SILENT;
log.level(expected);
alog::level_t actual = log.level();
ASSERT_EQ(expected, actual);
}
}
TEST(alog, logoutput)
{
std::ostream& ost = cout;
alog log(ost);
{
log.force() << "====\n";
log.level(alog::VERBOSE);
log.v() << "@@@@ verbose @@@@" << endl;
log.d() << "@@@@ debug @@@@" << endl;
log.i() << "@@@@ info @@@@" << endl;
log.w() << "@@@@ warning @@@@" << endl;
log.e() << "@@@@ error @@@@" << endl;
SUCCEED();
}
{
log.force() << "====\n";
log.level(alog::DEBUG);
log.v() << "@@@@ verbose @@@@" << endl;
log.d() << "@@@@ debug @@@@" << endl;
log.i() << "@@@@ info @@@@" << endl;
log.w() << "@@@@ warning @@@@" << endl;
log.e() << "@@@@ error @@@@" << endl;
SUCCEED();
}
{
log.force() << "====\n";
log.level(alog::INFO);
log.v() << "@@@@ verbose @@@@" << endl;
log.d() << "@@@@ debug @@@@" << endl;
log.i() << "@@@@ info @@@@" << endl;
log.w() << "@@@@ warning @@@@" << endl;
log.e() << "@@@@ error @@@@" << endl;
SUCCEED();
}
{
log.force() << "====\n";
log.level(alog::WARNING);
log.v() << "@@@@ verbose @@@@" << endl;
log.d() << "@@@@ debug @@@@" << endl;
log.i() << "@@@@ info @@@@" << endl;
log.w() << "@@@@ warning @@@@" << endl;
log.e() << "@@@@ error @@@@" << endl;
SUCCEED();
}
{
log.force() << "====\n";
log.level(alog::ERROR);
SUCCEED();
log.v() << "@@@@ verbose @@@@" << endl;
log.d() << "@@@@ debug @@@@" << endl;
log.i() << "@@@@ info @@@@" << endl;
log.w() << "@@@@ warning @@@@" << endl;
log.e() << "@@@@ error @@@@" << endl;
}
{
log.force() << "====\n";
log.level(alog::SILENT);
log.v() << "@@@@ verbose @@@@" << endl;
log.d() << "@@@@ debug @@@@" << endl;
log.i() << "@@@@ info @@@@" << endl;
log.w() << "@@@@ warning @@@@" << endl;
log.e() << "@@@@ error @@@@" << endl;
SUCCEED();
}
}
TEST(alog, format)
{
std::ostream& ost = cout;
alog log(ost);
{
log.force() << "====\n";
log.level(alog::VERBOSE);
log.v("%s %d%s", "[verbose", 10, "]") << endl;
log.v("[verbose 20]") << endl;
// log.d() << "@@@@ debug @@@@" << endl;
// log.i() << "@@@@ info @@@@" << endl;
// log.w() << "@@@@ warning @@@@" << endl;
// log.e() << "@@@@ error @@@@" << endl;
SUCCEED();
}
}
TEST(alog_singleton, init)
{
alog& log1 = alog_single::get_instance();
alog& log2 = alog_single::get_instance();
ASSERT_EQ(&log1, &log2);
}
void worker1(alog* & p)
{
alog& log = alog_single::get_instance();
p = &log;
}
extern void worker2(alog* & p);
extern void worker3(alog* & p);
TEST(alog_singleton, multithread)
{
alog* p1 = reinterpret_cast<alog*>(1);
alog* p2 = reinterpret_cast<alog*>(2);
alog* p3 = reinterpret_cast<alog*>(3);
std::thread th1(worker1, ref(p1));
std::thread th2(worker2, ref(p2));
std::thread th3(worker3, ref(p3));
th1.join();
th2.join();
th3.join();
ASSERT_EQ(p1, p2);
ASSERT_NE(p1, p3);
}
| 22.931937
| 53
| 0.502055
|
hfuj13
|
25db27c8066e2357b4822e97522b298de28413d2
| 2,943
|
cpp
|
C++
|
examples/profiling/primitive_instrumentation.cpp
|
rhecto1/phylanx
|
524eb7f2497afc9b67c76059767dfb2e4b694a47
|
[
"BSL-1.0"
] | null | null | null |
examples/profiling/primitive_instrumentation.cpp
|
rhecto1/phylanx
|
524eb7f2497afc9b67c76059767dfb2e4b694a47
|
[
"BSL-1.0"
] | null | null | null |
examples/profiling/primitive_instrumentation.cpp
|
rhecto1/phylanx
|
524eb7f2497afc9b67c76059767dfb2e4b694a47
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2018 Parsa Amini
// Copyright (c) 2018 Hartmut Kaiser
// Copyright (c) 2018 Shahrzad Shirzad
//
// 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)
#include <phylanx/phylanx.hpp>
#include <hpx/hpx_init.hpp>
#include <hpx/include/agas.hpp>
#include <cstdint>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <hpx/program_options.hpp>
///////////////////////////////////////////////////////////////////////////////
char const* const fib_code = R"(block(
define(fib_test, iterations,
block(
define(x, 1.0),
define(z, 0.0),
define(y, 1.0),
cout(x),
cout(y),
define(temp,0.0),
define(step, 2),
while(
step < iterations,
block(
store(z, x + y),
store(temp, y),
store(y, z),
store(x, temp),
cout(z),
store(step, step + 1)
)
)
)
),
fib_test
))";
///////////////////////////////////////////////////////////////////////////////
int hpx_main(hpx::program_options::variables_map& vm)
{
// Compile the given code
phylanx::execution_tree::compiler::function_list snippets;
auto const& code = phylanx::execution_tree::compile(
"fib", phylanx::ast::generate_ast(fib_code), snippets);
// Enable collection of performance data for all existing primitives
auto existing_primitive_instances = phylanx::util::enable_measurements();
auto const fibonacci = code.run();
// Fibonacci arguments
auto num_iterations = vm["num_iterations"].as<std::int64_t>();
// Evaluate Fibonacci using the read data
fibonacci(num_iterations);
// CSV Header
std::cout << "primitive_instance,display_name,count,time,eval_directs\n";
// Print performance data
for (auto const& entry :
phylanx::util::retrieve_counter_data(existing_primitive_instances))
{
std::cout << "\"" << entry.first << "\",\""
<< phylanx::execution_tree::compiler::primitive_display_name(
entry.first)
<< "\"";
for (auto const& counter_value : entry.second)
{
std::cout << "," << counter_value;
}
std::cout << std::endl;
}
return hpx::finalize();
}
int main(int argc, char* argv[])
{
// Command-line handling
hpx::program_options::options_description desc(
"usage: primitive_instrumentation [options]");
desc.add_options()
("num_iterations,n",
hpx::program_options::value<std::int64_t>()->default_value(10),
"number of iterations (default: 10)");
return hpx::init(desc, argc, argv);
}
| 29.138614
| 80
| 0.545362
|
rhecto1
|
25e4b5938abbf299ec0c5b11f33fc4daaca7ad92
| 260
|
cpp
|
C++
|
src/cpu/insts/Jnb.cpp
|
ammubhave/emu
|
ff9501719f3cc53207a8931d85c19d24c86dccdc
|
[
"MIT"
] | null | null | null |
src/cpu/insts/Jnb.cpp
|
ammubhave/emu
|
ff9501719f3cc53207a8931d85c19d24c86dccdc
|
[
"MIT"
] | null | null | null |
src/cpu/insts/Jnb.cpp
|
ammubhave/emu
|
ff9501719f3cc53207a8931d85c19d24c86dccdc
|
[
"MIT"
] | null | null | null |
#include "gen/Jnb.h"
#include "cpu/Cpu.h"
#include "cpu/insts/Util.h"
namespace emu::cpu::insts {
template <typename Op1>
void Jnb<Op1>::execute(Cpu& cpu) {
Jcc(cpu, op1_, [&]() { return !CF; });
}
} // namespace emu::cpu::insts
#include "gen/Jnb.cpp"
| 16.25
| 40
| 0.630769
|
ammubhave
|
25e528d4f4c3222df65af774f958cfcc5078435b
| 955
|
hpp
|
C++
|
shared/include/req_file_helpers.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 13
|
2019-03-25T09:40:12.000Z
|
2022-03-13T16:12:39.000Z
|
shared/include/req_file_helpers.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 110
|
2018-10-16T09:05:43.000Z
|
2022-03-16T23:32:28.000Z
|
shared/include/req_file_helpers.hpp
|
SleepKiller/swbfii-shaderpatch
|
b49ce3349d4dd09b19237ff4766652166ba1ffd4
|
[
"MIT"
] | 1
|
2020-02-06T20:32:50.000Z
|
2020-02-06T20:32:50.000Z
|
#pragma once
#include "small_function.hpp"
#include <filesystem>
#include <string>
#include <string_view>
#include <vector>
namespace sp {
auto parse_req_file(const std::filesystem::path& filepath,
std::string_view platform = "pc")
-> std::vector<std::pair<std::string, std::vector<std::string>>>;
void emit_req_file(const std::filesystem::path& filepath,
const std::vector<std::pair<std::string, std::vector<std::string>>>& key_sections);
void parse_files_req_file(const std::filesystem::path& filepath,
Small_function<void(std::string entry) noexcept> callback);
template<typename SequenceContainer>
inline void parse_files_req_file(const std::filesystem::path& filepath,
SequenceContainer& container)
{
parse_files_req_file(
filepath, [&](std::string entry) noexcept {
container.emplace_back(std::move(entry));
});
}
}
| 28.939394
| 102
| 0.66178
|
SleepKiller
|
25e689abd7027ed8b9992ce185f8a21d61141482
| 1,854
|
cpp
|
C++
|
libs/file/test/test_file.cpp
|
sabel83/just
|
cfe90c1997a000cd88481f5ea9f21a75130a2170
|
[
"BSL-1.0"
] | 6
|
2016-05-21T17:15:17.000Z
|
2018-04-24T13:03:16.000Z
|
libs/file/test/test_file.cpp
|
sabel83/just
|
cfe90c1997a000cd88481f5ea9f21a75130a2170
|
[
"BSL-1.0"
] | null | null | null |
libs/file/test/test_file.cpp
|
sabel83/just
|
cfe90c1997a000cd88481f5ea9f21a75130a2170
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2016.
// 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)
#include <just/file.hpp>
#include <just/temp.hpp>
#include <just/test.hpp>
using namespace just;
namespace
{
std::string load_file(const std::string& filename_)
{
std::vector<char> s1;
just::file::read(filename_, s1);
const std::vector<char> s2 = just::file::read(filename_);
const std::string s3 = just::file::read<std::string>(filename_);
JUST_ASSERT_EQUAL_CONTAINER(s1, s2);
JUST_ASSERT_EQUAL_CONTAINER(s2, s3);
return s3;
}
class read_back_tester
{
public:
void operator()(const std::string& s_) const
{
const std::string filename = _tmp.path() + "/test.txt";
just::file::write(filename, s_);
JUST_ASSERT_EQUAL(s_, load_file(filename));
}
private:
just::temp::directory _tmp;
};
}
JUST_TEST_CASE(test_throws_when_fails_to_create_file)
{
try
{
just::file::write("/proc/asd", "");
JUST_ASSERT(!"The above should have thrown");
}
catch (const just::file::error&)
{
// ignore
}
}
JUST_TEST_CASE(test_read_back_content)
{
read_back_tester test;
test("");
test("hello world");
test("hello\nworld");
test("hello\rworld");
test("hello\r\nworld");
}
JUST_TEST_CASE(test_throws_when_fails_to_open_file_for_read)
{
try
{
just::file::read("/proc/asd");
JUST_ASSERT(!"The above should have thrown");
}
catch (const just::file::error&)
{
// ignore
}
}
JUST_TEST_CASE(test_throws_when_fails_to_open_file_for_write)
{
try
{
just::file::write("/proc/cpuinfo/asd", "");
JUST_ASSERT(!"The above should have thrown");
}
catch (const just::file::error&)
{
// ignore
}
}
| 19.515789
| 68
| 0.65534
|
sabel83
|
25f438ca798ef4a0e3e06805444bf5f438796120
| 948
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_TributeTerminal_Base_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_TributeTerminal_Base_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_TributeTerminal_Base_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_TributeTerminal_Base_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass TributeTerminal_Base.TributeTerminal_Base_C
// 0x0000 (0x0E10 - 0x0E10)
class ATributeTerminal_Base_C : public AStructureItemContainerBaseBP_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass TributeTerminal_Base.TributeTerminal_Base_C");
return ptr;
}
void BPOnDemolish(class APlayerController** ForPC, class AActor** DamageCauser);
void BPPostLoadedFromSaveGame();
void UserConstructionScript();
void ExecuteUbergraph_TributeTerminal_Base(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 22.571429
| 110
| 0.665612
|
2bite
|
25f668a08167d717905198f842e1b149ffcfa341
| 66,900
|
cpp
|
C++
|
lemu/tests/lconst_test.cpp
|
jsg831/livehd
|
6a3fb84a8db2bdc3460bb391f82a796fef83d13b
|
[
"BSD-3-Clause"
] | 115
|
2019-09-28T13:39:41.000Z
|
2022-03-24T11:08:53.000Z
|
lemu/tests/lconst_test.cpp
|
jsg831/livehd
|
6a3fb84a8db2bdc3460bb391f82a796fef83d13b
|
[
"BSD-3-Clause"
] | 113
|
2019-10-08T23:51:29.000Z
|
2021-12-12T06:47:38.000Z
|
lemu/tests/lconst_test.cpp
|
jsg831/livehd
|
6a3fb84a8db2bdc3460bb391f82a796fef83d13b
|
[
"BSD-3-Clause"
] | 44
|
2019-09-28T07:53:21.000Z
|
2022-02-13T23:21:12.000Z
|
#include "lconst.hpp"
#include <cassert>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <vector>
#include "fmt/format.h"
#include "gtest/gtest.h"
#include "lbench.hpp"
#include "lrand.hpp"
#include "mmap_map.hpp"
#include "sint.hpp"
#include "uint.hpp"
/*
uint and sint are the low level (C++ generated) library from simlib.
Lconst must be compatible with uint/sint. The main difference is that
Lconst does not have a "known" at compile time number of bits. As a
result, it uses the slower boost cpp interface.
This unit test checks lvariable and that uint/sint are consistent with
Lconst (still a work in progress)
*/
class Lconst_test : public ::testing::Test {
protected:
UInt<16> a16u;
UInt<16> b16u;
UInt<64> a64u;
UInt<64> b64u;
UInt<80> a80u;
UInt<80> b80u;
UInt<128> a128u;
UInt<128> b128u;
SInt<16> a16s;
SInt<16> b16s;
SInt<64> a64s;
SInt<64> b64s;
SInt<80> a80s;
SInt<80> b80s;
SInt<128> a128s;
SInt<128> b128s;
Lconst l_a16u;
Lconst l_b16u;
Lconst l_a64u;
Lconst l_b64u;
Lconst l_a80u;
Lconst l_b80u;
Lconst l_a128u;
Lconst l_b128u;
Lconst l_a16s;
Lconst l_b16s;
Lconst l_a64s;
Lconst l_b64s;
Lconst l_a80s;
Lconst l_b80s;
Lconst l_a128s;
Lconst l_b128s;
public:
void TearDown() override {
mmap_lib::str::nuke();
}
void SetUp() override {
mmap_lib::str::setup();
a16u = UInt<16>(0xcafe);
b16u = UInt<16>(0xbebe);
a64u = UInt<64>(0xe2bd5b4ff8b30fc8);
b64u = UInt<64>(0x2fc353e33c6938a7);
a80u = UInt<80>("0x987426c1f7cd7d4d693a");
b80u = UInt<80>("0x563a0757a07b7bd27485");
a128u = UInt<128>("0xe903646a697fcaa344d2b2aa95e47b5d");
b128u = UInt<128>("0x56fa570ecb04adca42405f12bf28b822");
a16s = SInt<16>(0x6dba);
b16s = SInt<16>(0xccb2);
a64s = SInt<64>(0x71088d1c4a5c4a02);
b64s = SInt<64>(0xdefaa415d9062302);
a80s = SInt<80>("0x381c1fe6bca6875922fe");
b80s = SInt<80>("0xefbe8ae0d38ab7f36dda");
a128s = SInt<128>("0x6e0939370acc19daec06e9c13db50674");
b128s = SInt<128>("0xbeb828fdbac591dba8e38eeb433f563d");
l_a16u = Lconst::from_pyrope("0xcafe");
l_b16u = Lconst::from_pyrope("0xbebe");
l_a64u = Lconst::from_pyrope("0xe2bd5b4ff8b30fc8");
l_b64u = Lconst::from_pyrope("0x2fc353e33c6938a7");
l_a80u = Lconst::from_pyrope("0x987426c1f7cd7d4d693a");
l_b80u = Lconst::from_pyrope("0x563a0757a07b7bd27485");
l_a128u = Lconst::from_pyrope("0xe903646a697fcaa344d2b2aa95e47b5d");
l_b128u = Lconst::from_pyrope("0x56fa570ecb04adca42405f12bf28b822");
l_a16s = Lconst::from_pyrope("0x6dba");
l_b16s = Lconst::from_pyrope("0xccb2");
l_a64s = Lconst::from_pyrope("0x71088d1c4a5c4a02");
l_b64s = Lconst::from_pyrope("0xdefaa415d9062302");
l_a80s = Lconst::from_pyrope("0x381c1fe6bca6875922fe");
l_b80s = Lconst::from_pyrope("0xefbe8ae0d38ab7f36dda");
l_a128s = Lconst::from_pyrope("0x6e0939370acc19daec06e9c13db50674");
l_b128s = Lconst::from_pyrope("0xbeb828fdbac591dba8e38eeb433f563d");
};
};
template <int N>
void print_method(const UInt<N> v) {
fmt::print("{} bits:{}\n", v.to_string(), N);
}
TEST_F(Lconst_test, to_from_pyrope) {
auto v = Lconst::from_pyrope("0sb11111111111111111111111111111111111111111111110");
EXPECT_EQ(v.to_i(), -2);
EXPECT_EQ(v.to_pyrope(), "-2");
}
TEST_F(Lconst_test, lvar_sizes) {
auto l1 = Lconst::from_pyrope("-1"); // 0xFF or -1
fmt::print("l1:{} bits:{}\n", l1.to_pyrope(), l1.get_bits());
EXPECT_EQ(Lconst::from_pyrope("false"), l1.eq_op(Lconst::from_pyrope("0xFF")));
EXPECT_FALSE(l1.eq_op(Lconst::from_pyrope("-1")).is_known_false());
EXPECT_TRUE(l1.eq_op(Lconst::from_pyrope("-1")).is_known_true());
EXPECT_TRUE(l1.eq_op(Lconst::from_pyrope("0xFFFFFFF")).is_known_false());
EXPECT_FALSE(l1.eq_op(Lconst::from_pyrope("0xFFFFFFF")).is_known_true());
EXPECT_EQ(l1.get_bits(), 1);
auto s1 = l1 + Lconst::from_pyrope("1");
fmt::print("s1:{} bits:{}\n", s1.to_pyrope(), s1.get_bits());
EXPECT_EQ(s1.eq_op(Lconst::from_pyrope("0x0")).is_known_false(), false);
EXPECT_EQ(s1.get_bits(), 1);
auto s2 = l1 + Lconst::from_pyrope("-1");
fmt::print("s2:{} bits:{}\n", s2.to_pyrope(), s2.get_bits());
EXPECT_FALSE(s2.eq_op(Lconst::from_pyrope("-2")).is_known_false());
EXPECT_EQ(s2.get_bits(), 2);
auto s4 = l1 + Lconst::from_pyrope("0x1F");
fmt::print("s4:{} bits:{}\n", s4.to_pyrope(), s4.get_bits());
EXPECT_FALSE(s4.eq_op(Lconst::from_pyrope("0x1E")).is_known_false());
EXPECT_EQ(s4.get_bits(), 6);
}
TEST_F(Lconst_test, uint_comparison_operators) {
EXPECT_TRUE(a16u == a16u);
EXPECT_TRUE(a16u != b16u);
EXPECT_TRUE(b16u < a16u);
EXPECT_TRUE(b16u <= a16u);
EXPECT_TRUE(a16u <= a16u);
EXPECT_TRUE(a16u >= a16u);
EXPECT_TRUE(a16u > b16u);
EXPECT_TRUE(a64u == a64u);
EXPECT_TRUE(a64u != b64u);
EXPECT_TRUE(b64u < a64u);
EXPECT_TRUE(b64u <= a64u);
EXPECT_TRUE(a64u <= a64u);
EXPECT_TRUE(a64u >= a64u);
EXPECT_TRUE(a64u > b64u);
EXPECT_TRUE(a80u == a80u);
EXPECT_TRUE(a80u != b80u);
EXPECT_TRUE(b80u < a80u);
EXPECT_TRUE(b80u <= a80u);
EXPECT_TRUE(a80u <= a80u);
EXPECT_TRUE(a80u >= a80u);
EXPECT_TRUE(a80u > b80u);
EXPECT_TRUE(a128u == a128u);
EXPECT_TRUE(a128u != b128u);
EXPECT_TRUE(b128u < a128u);
EXPECT_TRUE(b128u <= a128u);
EXPECT_TRUE(a128u <= a128u);
EXPECT_TRUE(a128u >= a128u);
EXPECT_TRUE(a128u > b128u);
EXPECT_TRUE(l_a16u == l_a16u);
EXPECT_TRUE(l_a16u != l_b16u);
EXPECT_TRUE(l_b16u < l_a16u);
EXPECT_TRUE(l_b16u <= l_a16u);
EXPECT_TRUE(l_a16u <= l_a16u);
EXPECT_TRUE(l_a16u >= l_a16u);
EXPECT_TRUE(l_a16u > l_b16u);
EXPECT_TRUE(l_a64u == l_a64u);
EXPECT_TRUE(l_a64u != l_b64u);
EXPECT_TRUE(l_b64u < l_a64u);
EXPECT_TRUE(l_b64u <= l_a64u);
EXPECT_TRUE(l_a64u <= l_a64u);
EXPECT_TRUE(l_a64u >= l_a64u);
EXPECT_TRUE(l_a64u > l_b64u);
EXPECT_TRUE(l_a80u == l_a80u);
EXPECT_TRUE(l_a80u != l_b80u);
EXPECT_TRUE(l_b80u < l_a80u);
EXPECT_TRUE(l_b80u <= l_a80u);
EXPECT_TRUE(l_a80u <= l_a80u);
EXPECT_TRUE(l_a80u >= l_a80u);
EXPECT_TRUE(l_a80u > l_b80u);
EXPECT_TRUE(l_a128u == l_a128u);
EXPECT_TRUE(l_a128u != l_b128u);
EXPECT_TRUE(l_b128u < l_a128u);
EXPECT_TRUE(l_b128u <= l_a128u);
EXPECT_TRUE(l_a128u <= l_a128u);
EXPECT_TRUE(l_a128u >= l_a128u);
EXPECT_TRUE(l_a128u > l_b128u);
}
TEST_F(Lconst_test, uint_constructors) {
EXPECT_TRUE(a16u == UInt<16>("0xcafe"));
EXPECT_TRUE(a16u == UInt<16>(a16u));
EXPECT_TRUE(a64u == UInt<64>(a64u));
EXPECT_TRUE(a80u == UInt<80>(a80u));
EXPECT_TRUE(a128u == UInt<128>(a128u));
EXPECT_TRUE(a16u == UInt<16>(0xfcafe));
EXPECT_TRUE(UInt<128>(0x1) == UInt<128>("0x1"));
EXPECT_TRUE(a80u == UInt<80>(std::array<uint64_t, 2>({0x9874, 0x26c1f7cd7d4d693a})));
EXPECT_TRUE(a128u == UInt<128>(std::array<uint64_t, 2>({0xe903646a697fcaa3, 0x44d2b2aa95e47b5d})));
}
TEST_F(Lconst_test, uint_pad_operator) {
EXPECT_TRUE(a16u == a16u.pad<16>());
EXPECT_TRUE(a16u.pad<64>() == UInt<64>(0xcafe));
EXPECT_TRUE(a64u.pad<200>() == a64u.pad<200>());
EXPECT_TRUE(a64u.pad<200>() != b64u.pad<200>());
}
TEST_F(Lconst_test, uint_cat_operator) {
EXPECT_TRUE(a16u.cat(b16u) == UInt<32>(0xcafebebe));
EXPECT_TRUE(a16u.cat(a64u) == UInt<80>("0xcafee2bd5b4ff8b30fc8"));
EXPECT_TRUE(a64u.cat(a16u) == UInt<80>("0xe2bd5b4ff8b30fc8cafe"));
EXPECT_TRUE(a16u.cat(a80u) == UInt<96>("0xcafe987426c1f7cd7d4d693a"));
EXPECT_TRUE(a80u.cat(a16u) == UInt<96>("0x987426c1f7cd7d4d693acafe"));
EXPECT_TRUE(a16u.cat(a128u) == UInt<144>("0xcafee903646a697fcaa344d2b2aa95e47b5d"));
EXPECT_TRUE(a128u.cat(a16u) == UInt<144>("0xe903646a697fcaa344d2b2aa95e47b5dcafe"));
EXPECT_TRUE(a80u.cat(a128u) == UInt<208>("0x987426c1f7cd7d4d693ae903646a697fcaa344d2b2aa95e47b5d"));
EXPECT_TRUE(a128u.cat(a80u) == UInt<208>("0xe903646a697fcaa344d2b2aa95e47b5d987426c1f7cd7d4d693a"));
EXPECT_TRUE(a128u.cat(b128u) == UInt<256>("0xe903646a697fcaa344d2b2aa95e47b5d56fa570ecb04adca42405f12bf28b822"));
}
TEST_F(Lconst_test, uint_add_operator) {
EXPECT_TRUE(a16u + b16u == UInt<17>(0x189bc));
for (int i = 0; i < 100; ++i) {
// get 2 random 64+48 bit number
__int128 t1 = rand();
__int128 t2 = rand();
t1 <<= rand() % 48;
t2 <<= rand() % 48;
t1 += rand();
t2 += rand();
UInt<112> v1(std::array<uint64_t, 2>({(uint64_t)(t1 >> 64), (uint64_t)t1}));
UInt<112> v2(std::array<uint64_t, 2>({(uint64_t)(t2 >> 64), (uint64_t)t2}));
auto v3a = v1 + v2;
auto t3 = t1 + t2;
UInt<113> v3b(std::array<uint64_t, 2>({(uint64_t)(t3 >> 64), (uint64_t)t3}));
EXPECT_EQ(v3a, v3b);
}
for (int i = 0; i < 100; ++i) {
// get 2 random 64+48 bit number
__int128 t1 = rand();
__int128 t2 = rand();
t1 <<= rand() % 48;
t2 <<= rand() % 48;
t1 += rand();
t2 += rand();
UInt<128 + 32> v1(std::array<uint64_t, 3>({0, (uint64_t)(t1 >> 64), (uint64_t)t1}));
UInt<112> v2(std::array<uint64_t, 2>({(uint64_t)(t2 >> 64), (uint64_t)t2}));
auto v3a = v1 + v2;
auto t3 = t1 + t2;
UInt<113> v3b(std::array<uint64_t, 2>({(uint64_t)(t3 >> 64), (uint64_t)t3}));
EXPECT_EQ(v3a, v3b);
}
EXPECT_TRUE(a64u + b64u == UInt<65>("0x11280af33351c486f"));
EXPECT_TRUE(a80u + b80u == UInt<81>("0xeeae2e199848f91fddbf"));
EXPECT_TRUE(a128u + b128u == UInt<129>("0x13ffdbb793484786d871311bd550d337f"));
EXPECT_TRUE(l_a64u + l_b64u == Lconst::from_pyrope("0x11280af33351c486f"));
EXPECT_TRUE(l_a80u + l_b80u == Lconst::from_pyrope("0xeeae2e199848f91fddbf"));
EXPECT_TRUE(l_a128u + l_b128u == Lconst::from_pyrope("0x13ffdbb793484786d871311bd550d337f"));
}
TEST_F(Lconst_test, uint_addw_operator) {
EXPECT_TRUE(a16u.addw(b16u) == UInt<16>(0x89bc));
EXPECT_TRUE(a64u.addw(b64u) == UInt<64>("0x1280af33351c486f"));
EXPECT_TRUE(a80u.addw(b80u) == UInt<80>("0xeeae2e199848f91fddbf"));
EXPECT_TRUE(a128u.addw(b128u) == UInt<128>("0x3ffdbb793484786d871311bd550d337f"));
}
TEST_F(Lconst_test, uint_sub_operator) {
EXPECT_TRUE(a16u - b16u == SInt<17>(0xc40));
EXPECT_TRUE(a64u - b64u == SInt<65>("0xb2fa076cbc49d721"));
EXPECT_TRUE(a80u - b80u == SInt<81>("0x423a1f6a5752017af4b5"));
EXPECT_TRUE(a128u - b128u == SInt<129>("0x92090d5b9e7b1cd902925397d6bbc33b"));
}
TEST_F(Lconst_test, uint_negate_operator) {
EXPECT_TRUE(-a16u == SInt<17>(0x13502));
EXPECT_TRUE(-a64u == SInt<65>("0x11d42a4b0074cf038"));
EXPECT_TRUE(-a80u == SInt<81>("0x1678bd93e083282b296c6"));
EXPECT_TRUE(-a128u == SInt<129>("0x116fc9b959680355cbb2d4d556a1b84a3"));
EXPECT_TRUE((-(-a16u)) == SInt<18>(a16u.pad<18>()));
EXPECT_TRUE((-(-a64u)) == SInt<66>(a64u.pad<66>()));
EXPECT_TRUE((-(-a80u)) == SInt<82>(a80u.pad<82>()));
EXPECT_TRUE((-(-a128u)) == SInt<130>(a128u.pad<130>()));
}
TEST_F(Lconst_test, uint_mult_operator) {
EXPECT_TRUE(a16u * b16u == UInt<32>(0x973f2c84));
EXPECT_TRUE(a64u * b64u == UInt<128>("0x2a4dc44ce497c914d9d3df0ec14b0b78"));
EXPECT_TRUE(a80u * b80u == UInt<160>("0x335993b54d4bc81d37835773f77fa4765c79f322"));
EXPECT_TRUE(a128u * b128u == UInt<256>("0x4f2b00496d758f68469327504061b9045f77243f5cfda64ce9fb69abca8b3a5a"));
}
TEST_F(Lconst_test, uint_div_operator) {
EXPECT_TRUE(a16u / b16u == UInt<16>(1));
EXPECT_TRUE(a64u / b64u == UInt<64>(4));
}
TEST_F(Lconst_test, uint_mod_operator) {
EXPECT_TRUE(a16u % b16u == UInt<16>(0xc40));
EXPECT_TRUE(a64u % b64u == UInt<64>(0x23b00bc3070e2d2c));
}
TEST_F(Lconst_test, uint_not_operator) {
EXPECT_TRUE(~a16u == UInt<16>(0x3501));
EXPECT_TRUE(~a64u == UInt<64>(0x1d42a4b0074cf037));
EXPECT_TRUE(~a80u == UInt<80>("0x678bd93e083282b296c5"));
EXPECT_TRUE(~a128u == UInt<128>("0x16fc9b959680355cbb2d4d556a1b84a2"));
}
TEST_F(Lconst_test, uint_and_operator) {
EXPECT_TRUE((a16u & b16u) == UInt<16>(0x8abe));
EXPECT_TRUE((a64u & b64u) == UInt<64>(0x2281534338210880));
EXPECT_TRUE((a80u & b80u) == UInt<80>("0x10300641a04979406000"));
EXPECT_TRUE((a128u & b128u) == UInt<128>("0x4002440a490488824040120295203800"));
}
TEST_F(Lconst_test, uint_or_operator) {
EXPECT_TRUE((a16u | b16u) == UInt<16>(0xfefe));
EXPECT_TRUE((a64u | b64u) == UInt<64>(0xefff5beffcfb3fef));
EXPECT_TRUE((a80u | b80u) == UInt<80>("0xde7e27d7f7ff7fdf7dbf"));
EXPECT_TRUE((a128u | b128u) == UInt<128>("0xfffb776eeb7fefeb46d2ffbabfecfb7f"));
}
TEST_F(Lconst_test, uint_xor_operator) {
EXPECT_TRUE((a16u ^ b16u) == UInt<16>(0x7440));
EXPECT_TRUE((a64u ^ b64u) == UInt<64>(0xcd7e08acc4da376f));
EXPECT_TRUE((a80u ^ b80u) == UInt<80>("0xce4e219657b6069f1dbf"));
EXPECT_TRUE((a128u ^ b128u) == UInt<128>("0xbff93364a27b67690692edb82accc37f"));
}
TEST_F(Lconst_test, uint_andr_operator) {
EXPECT_TRUE((a16u.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<16>(0)).andr()) == UInt<1>(1));
EXPECT_TRUE((a64u.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<64>(0)).andr()) == UInt<1>(1));
EXPECT_TRUE((a80u.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<80>(0)).andr()) == UInt<1>(1));
EXPECT_TRUE((a128u.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<128>(0)).andr()) == UInt<1>(1));
}
TEST_F(Lconst_test, uint_orr_operator) {
EXPECT_TRUE((a16u.orr()) == UInt<1>(0x1));
EXPECT_TRUE((UInt<16>(0).andr()) == UInt<1>(0));
EXPECT_TRUE((a64u.orr()) == UInt<1>(0x1));
EXPECT_TRUE((UInt<64>(0).andr()) == UInt<1>(0));
EXPECT_TRUE((a80u.orr()) == UInt<1>(0x1));
EXPECT_TRUE((UInt<80>(0).andr()) == UInt<1>(0));
EXPECT_TRUE((a128u.orr()) == UInt<1>(0x1));
EXPECT_TRUE((UInt<128>(0).andr()) == UInt<1>(0));
}
TEST_F(Lconst_test, uint_xorr_operator) {
EXPECT_TRUE((a16u.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((b16u.xorr()) == UInt<1>(0x0));
EXPECT_TRUE((a64u.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((b64u.xorr()) == UInt<1>(0x0));
EXPECT_TRUE((a80u.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((b80u.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((a128u.xorr()) == UInt<1>(0x0));
EXPECT_TRUE((b128u.xorr()) == UInt<1>(0x1));
}
TEST_F(Lconst_test, uint_bits_operator) {
EXPECT_TRUE((a16u.bits<11, 4>()) == UInt<8>(0xaf));
EXPECT_TRUE((a64u.bits<47, 24>()) == UInt<24>(0x5b4ff8));
EXPECT_TRUE((a80u.bits<79, 64>()) == UInt<16>(0x9874));
EXPECT_TRUE((a80u.bits<71, 56>()) == UInt<16>(0x7426));
EXPECT_TRUE((a128u.bits<111, 96>()) == UInt<16>(0x646a));
EXPECT_TRUE((a128u.bits<71, 56>()) == UInt<16>(0xa344));
}
TEST_F(Lconst_test, uint_head_operator) {
EXPECT_TRUE((a16u.head<8>()) == UInt<8>(0xca));
EXPECT_TRUE((a64u.head<64>()) == a64u);
EXPECT_TRUE((a64u.head<16>()) == UInt<16>(0xe2bd));
EXPECT_TRUE((a80u.head<24>()) == UInt<24>(0x987426));
EXPECT_TRUE((a128u.head<32>()) == UInt<32>(0xe903646a));
}
TEST_F(Lconst_test, uint_tail_operator) {
EXPECT_TRUE((a16u.tail<8>()) == UInt<8>(0xfe));
EXPECT_TRUE((a64u.tail<0>()) == a64u);
EXPECT_TRUE((a64u.tail<16>()) == UInt<48>(0x5b4ff8b30fc8));
EXPECT_TRUE((a80u.tail<8>()) == UInt<72>("0x7426c1f7cd7d4d693a"));
EXPECT_TRUE((a128u.tail<32>()) == UInt<96>("0x697fcaa344d2b2aa95e47b5d"));
}
TEST_F(Lconst_test, uint_static_shifts) {
EXPECT_TRUE(a16u.shl<0>() == a16u);
EXPECT_TRUE(a16u.shl<4>() == UInt<20>(0xcafe0));
EXPECT_TRUE(a64u.shl<8>() == UInt<72>("0xe2bd5b4ff8b30fc800"));
EXPECT_TRUE(a80u.shl<60>() == UInt<140>("0x987426c1f7cd7d4d693a000000000000000"));
EXPECT_TRUE(a128u.shl<72>() == UInt<200>("0xe903646a697fcaa344d2b2aa95e47b5d000000000000000000"));
EXPECT_TRUE(a16u.shlw<0>() == a16u);
EXPECT_TRUE(a16u.shlw<4>() == UInt<16>(0xafe0));
EXPECT_TRUE(a64u.shlw<8>() == UInt<64>("0xbd5b4ff8b30fc800"));
EXPECT_TRUE(a80u.shlw<60>() == UInt<80>("0xd693a000000000000000"));
EXPECT_TRUE(a128u.shlw<72>() == UInt<128>("0xd2b2aa95e47b5d000000000000000000"));
EXPECT_TRUE(a16u.shr<0>() == a16u);
EXPECT_TRUE(a16u.shr<8>() == UInt<8>(0xca));
EXPECT_TRUE(a64u.shr<16>() == UInt<48>(0xe2bd5b4ff8b3));
EXPECT_TRUE(a80u.shr<24>() == UInt<56>(0x987426c1f7cd7d));
EXPECT_TRUE(a128u.shr<48>() == UInt<80>("0xe903646a697fcaa344d2"));
}
TEST_F(Lconst_test, uint_dynamic_shifts) {
EXPECT_TRUE((a16u << UInt<1>(0)) == UInt<17>(0xcafe));
EXPECT_TRUE((a16u << UInt<4>(4)) == UInt<31>(0xcafe0));
EXPECT_TRUE((a64u << UInt<4>(8)) == UInt<79>("0xe2bd5b4ff8b30fc800"));
EXPECT_TRUE((a80u << UInt<5>(12)) == UInt<111>("0x987426c1f7cd7d4d693a000"));
EXPECT_TRUE((a128u << UInt<6>(16)) == UInt<191>("0xe903646a697fcaa344d2b2aa95e47b5d0000"));
EXPECT_TRUE((a16u.dshlw(UInt<1>(0))) == a16u);
EXPECT_TRUE((a16u.dshlw(UInt<4>(4))) == UInt<16>(0xafe0));
EXPECT_TRUE((a64u.dshlw(UInt<4>(8))) == UInt<64>("0xbd5b4ff8b30fc800"));
EXPECT_TRUE((a80u.dshlw(UInt<6>(60))) == UInt<80>("0xd693a000000000000000"));
EXPECT_TRUE((a128u.dshlw(UInt<7>(72))) == UInt<128>("0xd2b2aa95e47b5d000000000000000000"));
EXPECT_TRUE((a16u >> UInt<1>(0)) == UInt<16>(0xcafe));
EXPECT_TRUE((a16u >> UInt<4>(4)) == UInt<16>(0x0caf));
EXPECT_TRUE((a64u >> UInt<4>(8)) == UInt<64>("0xe2bd5b4ff8b30f"));
EXPECT_TRUE((a80u >> UInt<5>(12)) == UInt<80>("0x987426c1f7cd7d4d6"));
EXPECT_TRUE((a128u >> UInt<6>(16)) == UInt<128>("0xe903646a697fcaa344d2b2aa95e4"));
}
TEST_F(Lconst_test, uint_conversion) {
EXPECT_TRUE(a16u.asUInt() == a16u);
EXPECT_TRUE(a16u.asSInt() == SInt<16>("0xcafe"));
EXPECT_TRUE(a16u.cvt() == SInt<17>(0xcafe));
}
TEST_F(Lconst_test, sint_comparison_operators) {
EXPECT_TRUE(a16s == a16s);
EXPECT_TRUE(a16s != b16s);
EXPECT_TRUE(b16s < a16s);
EXPECT_TRUE(b16s <= a16s);
EXPECT_TRUE(a16s <= a16s);
EXPECT_TRUE(a16s >= a16s);
EXPECT_TRUE(a16s > b16s);
EXPECT_TRUE(a64s == a64s);
EXPECT_TRUE(a64s != b64s);
EXPECT_TRUE(b64s < a64s);
EXPECT_TRUE(b64s <= a64s);
EXPECT_TRUE(a64s <= a64s);
EXPECT_TRUE(a64s >= a64s);
EXPECT_TRUE(a64s > b64s);
EXPECT_TRUE(a80s == a80s);
EXPECT_TRUE(a80s != b80s);
EXPECT_TRUE(b80s < a80s);
EXPECT_TRUE(b80s <= a80s);
EXPECT_TRUE(a80s <= a80s);
EXPECT_TRUE(a80s >= a80s);
EXPECT_TRUE(a80s > b80s);
EXPECT_TRUE(a128s == a128s);
EXPECT_TRUE(a128s != b128s);
EXPECT_TRUE(b128s < a128s);
EXPECT_TRUE(b128s <= a128s);
EXPECT_TRUE(a128s <= a128s);
EXPECT_TRUE(a128s >= a128s);
EXPECT_TRUE(a128s > b128s);
}
TEST_F(Lconst_test, sint_constructors) {
EXPECT_TRUE(b16s == SInt<16>(0xccb2));
EXPECT_TRUE(b16s == SInt<16>(b16s));
EXPECT_TRUE(b64s == SInt<64>(b64s));
EXPECT_TRUE(b80s == SInt<80>(b80s));
EXPECT_TRUE(b128s == SInt<128>(b128s));
EXPECT_TRUE(a80s == SInt<80>(std::array<uint64_t, 2>({0x381c, 0x1fe6bca6875922fe})));
EXPECT_TRUE(a128s == SInt<128>(std::array<uint64_t, 2>({0x6e0939370acc19da, 0xec06e9c13db50674})));
}
TEST_F(Lconst_test, sint_pad_operator) {
EXPECT_TRUE(a16s == a16s.pad<16>());
EXPECT_TRUE(a16s.pad<64>() == SInt<64>(0x6dba));
EXPECT_TRUE(a64s.pad<200>() == a64s.pad<100>().pad<200>());
EXPECT_TRUE(a64u.pad<200>() != b64u.pad<200>());
EXPECT_TRUE(b16s.pad<64>() == SInt<64>(0xffffffffffffccb2));
}
TEST_F(Lconst_test, sint_cat_operator) {
EXPECT_TRUE(a16s.cat(b16s) == SInt<32>("0x6dbaccb2"));
EXPECT_TRUE(b16s.cat(b64s) == SInt<80>("0xccb2defaa415d9062302"));
EXPECT_TRUE(b64s.cat(b16s) == SInt<80>("0xdefaa415d9062302ccb2"));
EXPECT_TRUE(b16s.cat(b80s) == SInt<96>("0xccb2efbe8ae0d38ab7f36dda"));
EXPECT_TRUE(b80s.cat(b16s) == SInt<96>("0xefbe8ae0d38ab7f36ddaccb2"));
EXPECT_TRUE(b16s.cat(b128s) == SInt<144>("0xccb2beb828fdbac591dba8e38eeb433f563d"));
EXPECT_TRUE(b128s.cat(b16s) == SInt<144>("0xbeb828fdbac591dba8e38eeb433f563dccb2"));
EXPECT_TRUE(b80s.cat(b128s) == SInt<208>("0xefbe8ae0d38ab7f36ddabeb828fdbac591dba8e38eeb433f563d"));
EXPECT_TRUE(b128s.cat(b80s) == SInt<208>("0xbeb828fdbac591dba8e38eeb433f563defbe8ae0d38ab7f36dda"));
EXPECT_TRUE(b128s.cat(b128s) == SInt<256>("0xbeb828fdbac591dba8e38eeb433f563dbeb828fdbac591dba8e38eeb433f563d"));
}
TEST_F(Lconst_test, sint_add_operator) {
EXPECT_TRUE(a16s + b16s == SInt<17>(0x3a6c));
EXPECT_TRUE(b16s + b16s == SInt<17>(0x19964));
EXPECT_TRUE(a64s + b64s == SInt<65>("0x5003313223626d04"));
EXPECT_TRUE(b64s + b64s == SInt<65>("0x1bdf5482bb20c4604"));
EXPECT_TRUE(a80s + b80s == SInt<81>("0x27daaac790313f4c90d8"));
EXPECT_TRUE(b80s + b80s == SInt<81>("0x1df7d15c1a7156fe6dbb4"));
EXPECT_TRUE(a128s + b128s == SInt<129>("0x2cc16234c591abb694ea78ac80f45cb1"));
EXPECT_TRUE(b128s + b128s == SInt<129>("0x17d7051fb758b23b751c71dd6867eac7a"));
EXPECT_TRUE(SInt<64>(1) + SInt<64>(-1) == SInt<65>(0));
EXPECT_TRUE(SInt<64>(-1) + SInt<64>(-1) == SInt<65>(-2));
}
TEST_F(Lconst_test, sint_addw_operator) {
EXPECT_TRUE(a16s.addw(b16s) == SInt<16>(0x3a6c));
EXPECT_TRUE(a64s.addw(b64s) == SInt<64>("0x5003313223626d04"));
EXPECT_TRUE(a80s.addw(b80s) == SInt<80>("0x27daaac790313f4c90d8"));
EXPECT_TRUE(a128s.addw(b128s) == SInt<128>("0x2cc16234c591abb694ea78ac80f45cb1"));
EXPECT_TRUE(SInt<64>(1).addw(SInt<64>(-1)) == SInt<64>(0));
EXPECT_TRUE(SInt<64>(-1).addw(SInt<64>(-1)) == SInt<64>(-2));
}
TEST_F(Lconst_test, sint_sub_operator) {
EXPECT_TRUE(a16s - b16s == SInt<17>(0xa108));
EXPECT_TRUE(b16s - a16s == SInt<17>(0x15ef8));
EXPECT_TRUE(b16s - SInt<16>(0) == b16s.pad<17>());
EXPECT_TRUE(a64s - b64s == SInt<65>("0x920de90671562700"));
EXPECT_TRUE(b64s - a64s == SInt<65>("0x16df216f98ea9d900"));
EXPECT_TRUE(b64s - SInt<64>(0) == b64s.pad<65>());
EXPECT_TRUE(a80s - b80s == SInt<81>("0x485d9505e91bcf65b524"));
EXPECT_TRUE(b80s - a80s == SInt<81>("0x1b7a26afa16e4309a4adc"));
EXPECT_TRUE(b80s - SInt<80>(0) == b80s.pad<81>());
EXPECT_TRUE(a128s - b128s == SInt<129>("0xaf511039500687ff43235ad5fa75b037"));
EXPECT_TRUE(b128s - a128s == SInt<129>("0x150aeefc6aff97800bcdca52a058a4fc9"));
EXPECT_TRUE(b128s - SInt<128>(0) == b128s.pad<129>());
}
TEST_F(Lconst_test, sint_negate_operator) {
EXPECT_TRUE(-a16s == SInt<17>(0x19246));
EXPECT_TRUE(-a64s == SInt<65>("0x18ef772e3b5a3b5fe"));
EXPECT_TRUE(-a80s == SInt<81>("0x1c7e3e019435978a6dd02"));
EXPECT_TRUE(-a128s == SInt<129>("0x191f6c6c8f533e62513f9163ec24af98c"));
EXPECT_TRUE((-(-a16s)) == SInt<18>(a16s.pad<18>()));
EXPECT_TRUE((-(-a64s)) == SInt<66>(a64s.pad<66>()));
EXPECT_TRUE((-(-a80s)) == SInt<82>(a80s.pad<82>()));
EXPECT_TRUE((-(-a128s)) == SInt<130>(a128s.pad<130>()));
EXPECT_TRUE(-b16s == SInt<17>(0x334e));
EXPECT_TRUE(-b64s == SInt<65>("0x21055bea26f9dcfe"));
EXPECT_TRUE(-b80s == SInt<81>("0x1041751f2c75480c9226"));
EXPECT_TRUE(-b128s == SInt<129>("0x4147d702453a6e24571c7114bcc0a9c3"));
EXPECT_TRUE((-(-b16s)) == SInt<18>(b16s.pad<18>()));
EXPECT_TRUE((-(-b64s)) == SInt<66>(b64s.pad<66>()));
EXPECT_TRUE((-(-b80s)) == SInt<82>(b80s.pad<82>()));
EXPECT_TRUE((-(-b128s)) == SInt<130>(b128s.pad<130>()));
}
TEST_F(Lconst_test, sint_mult_operator) {
EXPECT_TRUE(a16s * b16s == SInt<32>(0xea028354));
EXPECT_TRUE(a64s * b64s == SInt<128>("0xf16b880f2bad048691fd4b72a0e2da04"));
EXPECT_TRUE(a80s * b80s == SInt<160>("0xfc6fe531cae4d5f834f4831b7dc6f5fbfee7f24c"));
EXPECT_TRUE(a128s * b128s == SInt<256>("0xe3f0c77f6f1ce87a5d5735256c8addf7a2a5210cf49a1af0917e727f76d981a4"));
EXPECT_TRUE(b16s * b16s == SInt<32>(0xa482bc4));
EXPECT_TRUE(b64s * b64s == SInt<128>("0x044261cf16323e9d07bfb5d30ce18c04"));
EXPECT_TRUE(b80s * b80s == SInt<160>("0x1083f6094f8beff28a26e6d6335b98f66ff5da4"));
EXPECT_TRUE(b128s * b128s == SInt<256>("0x10a58f581efee2a4d90812cc128d304f3a498bebb936e0afcbcc36cd7d130a89"));
EXPECT_TRUE(SInt<16>(-1) * SInt<16>(-1) == SInt<32>(1));
EXPECT_TRUE(SInt<80>(-1) * SInt<80>(-1) == SInt<160>(1));
EXPECT_TRUE(SInt<128>(-1) * SInt<128>(-1) == SInt<256>(1));
EXPECT_TRUE(SInt<512>(-1) * SInt<512>(-1) == SInt<1024>(1));
}
TEST_F(Lconst_test, sint_div_operator) {
EXPECT_TRUE(a16s / b16s == SInt<17>(0x1fffe));
EXPECT_TRUE(a64s / b64s == SInt<65>("0x1fffffffffffffffd"));
EXPECT_TRUE(a64s / a16s == SInt<65>("0x107b710ae332f"));
EXPECT_TRUE(b64s / b16s == SInt<65>("0xa4c48cb11e2b"));
}
TEST_F(Lconst_test, sint_mod_operator) {
EXPECT_TRUE(a16s % b16s == SInt<16>(0x71e));
EXPECT_TRUE(a64s % b64s == SInt<64>(0xdf8795dd56eb308));
EXPECT_TRUE(a64s % a16s == SInt<16>(0x16dc));
EXPECT_TRUE(b64s % b16s == SInt<16>(0xe51c));
}
TEST_F(Lconst_test, sint_not_operator) {
EXPECT_TRUE(~a16s == UInt<16>(0x9245));
EXPECT_TRUE(~a64s == UInt<64>(0x8ef772e3b5a3b5fd));
EXPECT_TRUE(~a80s == UInt<80>("0xc7e3e019435978a6dd01"));
EXPECT_TRUE(~a128s == UInt<128>("0x91f6c6c8f533e62513f9163ec24af98b"));
}
TEST_F(Lconst_test, sint_and_operator) {
EXPECT_TRUE((a16s & b16s) == UInt<16>(0x4cb2));
EXPECT_TRUE((a64s & b64s) == UInt<64>(0x5008841448040202L));
EXPECT_TRUE((a80s & b80s) == UInt<80>("0x281c0ae09082875120da"));
EXPECT_TRUE((a128s & b128s) == UInt<128>("0x2e0828350ac411daa80288c101350634"));
}
TEST_F(Lconst_test, sint_or_operator) {
EXPECT_TRUE((a16s | b16s) == UInt<16>(0xedba));
EXPECT_TRUE((a64s | b64s) == UInt<64>(0xfffaad1ddb5e6b02));
EXPECT_TRUE((a80s | b80s) == UInt<80>("0xffbe9fe6ffaeb7fb6ffe"));
EXPECT_TRUE((a128s | b128s) == UInt<128>("0xfeb939ffbacd99dbece7efeb7fbf567d"));
}
TEST_F(Lconst_test, sint_xor_operator) {
EXPECT_TRUE((a16s ^ b16s) == UInt<16>(0xa108));
EXPECT_TRUE((a64s ^ b64s) == UInt<64>(0xaff22909935a6900));
EXPECT_TRUE((a80s ^ b80s) == UInt<80>("0xd7a295066f2c30aa4f24"));
EXPECT_TRUE((a128s ^ b128s) == UInt<128>("0xd0b111cab009880144e5672a7e8a5049"));
}
TEST_F(Lconst_test, sint_andr_operator) {
EXPECT_TRUE((a16s.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<16>(0)).asSInt().andr()) == UInt<1>(1));
EXPECT_TRUE((a64s.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<64>(0)).asSInt().andr()) == UInt<1>(1));
EXPECT_TRUE((a80s.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<80>(0)).asSInt().andr()) == UInt<1>(1));
EXPECT_TRUE((a128s.andr()) == UInt<1>(0x0));
EXPECT_TRUE(((~UInt<128>(0)).asSInt().andr()) == UInt<1>(1));
}
TEST_F(Lconst_test, sint_orr_operator) {
EXPECT_TRUE((a16s.orr()) == UInt<1>(0x1));
EXPECT_TRUE((SInt<16>(0).andr()) == UInt<1>(0));
EXPECT_TRUE((a64s.orr()) == UInt<1>(0x1));
EXPECT_TRUE((SInt<64>(0).andr()) == UInt<1>(0));
EXPECT_TRUE((a80s.orr()) == UInt<1>(0x1));
EXPECT_TRUE((SInt<80>(0).andr()) == UInt<1>(0));
EXPECT_TRUE((a128s.orr()) == UInt<1>(0x1));
EXPECT_TRUE((SInt<128>(0).andr()) == UInt<1>(0));
}
TEST_F(Lconst_test, sint_xorr_operator) {
EXPECT_TRUE((a16s.xorr()) == UInt<1>(0x0));
EXPECT_TRUE((b16s.xorr()) == UInt<1>(0x0));
EXPECT_TRUE((a64s.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((b64s.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((a80s.xorr()) == UInt<1>(0x0));
EXPECT_TRUE((b80s.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((a128s.xorr()) == UInt<1>(0x1));
EXPECT_TRUE((b128s.xorr()) == UInt<1>(0x1));
}
TEST_F(Lconst_test, sint_bits_operator) {
EXPECT_TRUE((a16s.bits<11, 4>()) == UInt<8>(0xdb));
EXPECT_TRUE((a64s.bits<47, 24>()) == UInt<24>(0x8d1c4a));
EXPECT_TRUE((a80s.bits<79, 64>()) == UInt<16>(0x381c));
EXPECT_TRUE((a80s.bits<71, 56>()) == UInt<16>(0x1c1f));
EXPECT_TRUE((a128s.bits<111, 96>()) == UInt<16>(0x3937));
EXPECT_TRUE((a128s.bits<71, 56>()) == UInt<16>(0xdaec));
}
TEST_F(Lconst_test, sint_head_operator) {
EXPECT_TRUE((a16s.head<8>()) == UInt<8>(0x6d));
EXPECT_TRUE((a64s.head<64>()) == a64s.asUInt());
EXPECT_TRUE((a64s.head<16>()) == UInt<16>(0x7108));
EXPECT_TRUE((a80s.head<24>()) == UInt<24>(0x381c1f));
EXPECT_TRUE((a128s.head<32>()) == UInt<32>(0x6e093937));
EXPECT_TRUE((b16s.head<8>()) == UInt<8>(0xcc));
EXPECT_TRUE((b64s.head<16>()) == UInt<16>(0xdefa));
EXPECT_TRUE((b80s.head<24>()) == UInt<24>(0xefbe8a));
EXPECT_TRUE((b128s.head<32>()) == UInt<32>(0xbeb828fd));
}
TEST_F(Lconst_test, sint_tail_operator) {
EXPECT_TRUE((a16s.tail<8>()) == UInt<8>(0xba));
EXPECT_TRUE((a64s.tail<0>()) == a64s.asUInt());
EXPECT_TRUE((a64s.tail<16>()) == UInt<48>(0x8d1c4a5c4a02));
EXPECT_TRUE((a80s.tail<8>()) == UInt<72>("0x1c1fe6bca6875922fe"));
EXPECT_TRUE((a128s.tail<32>()) == UInt<96>("0x0acc19daec06e9c13db50674"));
}
TEST_F(Lconst_test, sint_static_shifts) {
EXPECT_TRUE(a16s.shl<0>() == a16s);
EXPECT_TRUE(a16s.shl<4>() == SInt<20>(0x6dba0));
EXPECT_TRUE(a64s.shl<8>() == SInt<72>("0x71088d1c4a5c4a0200"));
EXPECT_TRUE(a80s.shl<60>() == SInt<140>("0x381c1fe6bca6875922fe000000000000000"));
EXPECT_TRUE(a128s.shl<72>() == SInt<200>("0x6e0939370acc19daec06e9c13db50674000000000000000000"));
EXPECT_TRUE(a16s.shlw<0>() == a16s);
EXPECT_TRUE(a16s.shlw<4>() == SInt<16>(0xdba0));
EXPECT_TRUE(a64s.shlw<8>() == SInt<64>("0x088d1c4a5c4a0200"));
EXPECT_TRUE(a80s.shlw<60>() == SInt<80>("0x922fe000000000000000"));
EXPECT_TRUE(a128s.shlw<72>() == SInt<128>("0x06e9c13db50674000000000000000000"));
EXPECT_TRUE(a16s.shr<0>() == a16s);
EXPECT_TRUE(a16s.shr<8>() == SInt<8>(0x6d));
EXPECT_TRUE(a64s.shr<16>() == SInt<48>(0x71088d1c4a5c));
EXPECT_TRUE(a80s.shr<24>() == SInt<56>(0x381c1fe6bca687));
EXPECT_TRUE(a128s.shr<48>() == SInt<80>("0x6e0939370acc19daec06"));
}
TEST_F(Lconst_test, sint_dynamic_shifts) {
EXPECT_TRUE((a16s << UInt<1>(0)) == SInt<17>(0x6dba));
EXPECT_TRUE((a16s << UInt<4>(4)) == SInt<31>(0x6dba0));
EXPECT_TRUE((a64s << UInt<4>(8)) == SInt<79>("0x71088d1c4a5c4a0200"));
EXPECT_TRUE((a80s << UInt<5>(12)) == SInt<111>("0x381c1fe6bca6875922fe000"));
EXPECT_TRUE((a128s << UInt<6>(16)) == SInt<191>("0x6e0939370acc19daec06e9c13db506740000"));
EXPECT_TRUE((b16s << UInt<1>(0)) == SInt<17>(0x1ccb2));
EXPECT_TRUE((b16s << UInt<4>(4)) == SInt<31>(0x7ffccb20));
EXPECT_TRUE((b64s << UInt<4>(8)) == SInt<79>("0x7fdefaa415d906230200"));
EXPECT_TRUE((b80s << UInt<5>(12)) == SInt<111>("0x7ffffefbe8ae0d38ab7f36dda000"));
EXPECT_TRUE((b128s << UInt<6>(16)) == SInt<191>("0x7fffffffffffbeb828fdbac591dba8e38eeb433f563d0000"));
EXPECT_TRUE((a16s.dshlw(UInt<1>(0))) == SInt<16>(0x6dba));
EXPECT_TRUE((a16s.dshlw(UInt<4>(4))) == SInt<16>(0xdba0));
EXPECT_TRUE((a64s.dshlw(UInt<4>(8))) == SInt<64>("0x088d1c4a5c4a0200"));
EXPECT_TRUE((a80s.dshlw(UInt<5>(12))) == SInt<80>("0xc1fe6bca6875922fe000"));
EXPECT_TRUE((a128s.dshlw(UInt<6>(16))) == SInt<128>("0x39370acc19daec06e9c13db506740000"));
EXPECT_TRUE((b16s.dshlw(UInt<1>(0))) == SInt<16>(0xccb2));
EXPECT_TRUE((b16s.dshlw(UInt<4>(4))) == SInt<16>(0xcb20));
EXPECT_TRUE((b64s.dshlw(UInt<4>(8))) == SInt<64>("0xfaa415d906230200"));
EXPECT_TRUE((b80s.dshlw(UInt<6>(60))) == SInt<80>("0x36dda000000000000000"));
EXPECT_TRUE((b128s.dshlw(UInt<7>(72))) == SInt<128>("0xe38eeb433f563d000000000000000000"));
EXPECT_TRUE((a16s >> UInt<1>(0)) == SInt<16>(0x6dba));
EXPECT_TRUE((a16s >> UInt<4>(4)) == SInt<16>(0x06db));
EXPECT_TRUE((a64s >> UInt<4>(8)) == SInt<64>("0x71088d1c4a5c4a"));
EXPECT_TRUE((a80s >> UInt<5>(12)) == SInt<80>("0x381c1fe6bca687592"));
EXPECT_TRUE((a128s >> UInt<6>(16)) == SInt<128>("0x6e0939370acc19daec06e9c13db5"));
EXPECT_TRUE((b16s >> UInt<1>(0)) == SInt<16>(0xccb2));
EXPECT_TRUE((b16s >> UInt<4>(4)) == SInt<16>(0xfccb));
EXPECT_TRUE((b64s >> UInt<4>(8)) == SInt<64>("0xffdefaa415d90623"));
EXPECT_TRUE((b80s >> UInt<5>(12)) == SInt<80>("0xfffefbe8ae0d38ab7f36"));
EXPECT_TRUE((b128s >> UInt<6>(16)) == SInt<128>("0xffffbeb828fdbac591dba8e38eeb433f"));
}
TEST_F(Lconst_test, sint_conversion) {
EXPECT_TRUE(a16s.asUInt() == UInt<16>("0x6dba"));
EXPECT_TRUE(a16s.asSInt() == a16s);
EXPECT_TRUE(a16s.cvt() == SInt<16>(0x6dba));
}
TEST_F(Lconst_test, mixed_add_operator) {
EXPECT_TRUE(a16u + b16s == SInt<17>(0x97b0));
EXPECT_TRUE(a64u + b64s == SInt<65>("0xc1b7ff65d1b932ca"));
EXPECT_TRUE(a80u + b80s == SInt<81>("0x8832b1a2cb583540d714"));
EXPECT_TRUE(a128u + b128s == SInt<129>("0xa7bb8d6824455c7eedb64195d923d19a"));
EXPECT_TRUE(b16s + a16u == SInt<17>(0x97b0));
EXPECT_TRUE(b64s + a64u == SInt<65>("0xc1b7ff65d1b932ca"));
EXPECT_TRUE(b80s + a80u == SInt<81>("0x8832b1a2cb583540d714"));
EXPECT_TRUE(b128s + a128u == SInt<129>("0xa7bb8d6824455c7eedb64195d923d19a"));
}
TEST_F(Lconst_test, mixed_sub_operator) {
EXPECT_TRUE(a16u - b16s == SInt<17>(0xfe4c));
EXPECT_TRUE(a64u - b64s == SInt<65>("0x103c2b73a1facecc6"));
EXPECT_TRUE(a80u - b80s == SInt<81>("0xa8b59be12442c559fb60"));
EXPECT_TRUE(a128u - b128s == SInt<129>("0x12a4b3b6caeba38c79bef23bf52a52520"));
EXPECT_TRUE(b16s - a16u == SInt<17>(0x101b4));
EXPECT_TRUE(b64s - a64u == SInt<65>("0xfc3d48c5e053133a"));
EXPECT_TRUE(b80s - a80u == SInt<81>("0x1574a641edbbd3aa604a0"));
EXPECT_TRUE(b128s - a128u == SInt<129>("0xd5b4c4935145c7386410dc40ad5adae0"));
}
TEST_F(Lconst_test, mixed_mul_operator) {
EXPECT_TRUE(a16u * b16s == SInt<32>(0xd7518c9c));
EXPECT_TRUE(a64u * b64s == SInt<128>("0xe2c0d81f3550c17f8cc2ad9b533e7790"));
EXPECT_TRUE(a80u * b80s == SInt<160>("0xf651c2566302169937ff4a396485514e01c74d64"));
EXPECT_TRUE(a128u * b128s == SInt<256>("0xc494bfdc37540a963a9a7ad576771522f488399b3bc2e87c8c1164e32bc5a329"));
EXPECT_TRUE(b16s * a16u == SInt<32>(0xd7518c9c));
EXPECT_TRUE(b64s * a64u == SInt<128>("0xe2c0d81f3550c17f8cc2ad9b533e7790"));
EXPECT_TRUE(b80s * a80u == SInt<160>("0xf651c2566302169937ff4a396485514e01c74d64"));
EXPECT_TRUE(b128s * a128u == SInt<256>("0xc494bfdc37540a963a9a7ad576771522f488399b3bc2e87c8c1164e32bc5a329"));
}
TEST_F(Lconst_test, Trivial) {
Lbench bench("lemu.LCONST_trivial");
constexpr auto v_10 = 10_uint;
constexpr auto v_10b = 0xa_uint;
static_assert(v_10 == v_10b, "same at compile time");
UInt<4> a16u_10(0xa);
EXPECT_EQ(a16u_10, v_10b);
print_method(v_10);
print_method(v_10b);
UInt<1> a1u(0x1);
print_method(a1u);
print_method(a16u);
fmt::print("UInt<1> has sizeof {}\n", sizeof(a1u));
fmt::print("UInt<16> has sizeof {}\n", sizeof(a16u));
fmt::print("UInt<64> has sizeof {}\n", sizeof(a64u));
fmt::print("UInt<80> has sizeof {}\n", sizeof(a80u));
fmt::print("UInt<128> has sizeof {}\n", sizeof(a128u));
EXPECT_EQ(a16u.cat(b16u), UInt<32>(0xcafebebe));
EXPECT_EQ(a16u.cat(a64u), UInt<80>("0xcafee2bd5b4ff8b30fc8"));
EXPECT_EQ(a64u.cat(a16u), UInt<80>("0xe2bd5b4ff8b30fc8cafe"));
EXPECT_EQ(a16u.cat(a80u), UInt<96>("0xcafe987426c1f7cd7d4d693a"));
EXPECT_EQ(a80u.cat(a16u), UInt<96>("0x987426c1f7cd7d4d693acafe"));
EXPECT_EQ(a16u.cat(a128u), UInt<144>("0xcafee903646a697fcaa344d2b2aa95e47b5d"));
EXPECT_EQ(a128u.cat(a16u), UInt<144>("0xe903646a697fcaa344d2b2aa95e47b5dcafe"));
EXPECT_EQ(a80u.cat(a128u), UInt<208>("0x987426c1f7cd7d4d693ae903646a697fcaa344d2b2aa95e47b5d"));
EXPECT_EQ(a128u.cat(a80u), UInt<208>("0xe903646a697fcaa344d2b2aa95e47b5d987426c1f7cd7d4d693a"));
EXPECT_EQ(a128u.cat(b128u), UInt<256>("0xe903646a697fcaa344d2b2aa95e47b5d56fa570ecb04adca42405f12bf28b822"));
#if 0
auto base_ptr = data.data();
auto& big_int_ref = *base_ptr;
auto x = reinterpret_cast<big_int<Len> *>(base_ptr + i);
auto y = reinterpret_cast<big_int<Len> *>(base_ptr + i + Len);
#endif
{
auto a = 0x10_uint;
auto b = 0x20_uint;
auto c = a + b;
EXPECT_EQ(c, 0x30_uint);
}
{
auto a = 0x10_uint;
auto b = 0x2_uint;
auto c = a + b;
EXPECT_EQ(c, 0x12_uint);
}
}
TEST_F(Lconst_test, Storage) {
Lbench b("lemu.LCONST_storage");
uint64_t data = 3;
auto val16_ptr = reinterpret_cast<UInt<16> *>(&data);
auto &val16 = *val16_ptr;
auto val8_ptr = reinterpret_cast<UInt<8> *>(&data);
auto &val8 = *val8_ptr;
EXPECT_EQ(sizeof(val8), 1);
EXPECT_EQ(sizeof(val16), 8);
print_method(val8);
print_method(val16);
EXPECT_EQ(val8, 0x03_uint);
EXPECT_EQ(val16, 0x0003_uint);
auto val7_ptr = reinterpret_cast<UInt<7> *>(&data);
auto &val7 = *val7_ptr;
auto val18_ptr = reinterpret_cast<UInt<18> *>(&data);
auto &val18 = *val18_ptr;
print_method(val7);
print_method(val18);
// FIXME: EXPECT_EQ(0x1f58d11f58d11f58d1_uint, 076543210765432107654321_uint);
print_method(012345_uint);
print_method(0x9876543210987654321_uint);
print_method(076543210765432107654321_uint);
fmt::print("verilog: {}\n", (076543210765432107654321_uint).to_verilog());
mmap_lib::map<uint32_t, mmap_lib::str> map;
map.set(12345, mmap_lib::str((0x12345_uint).to_string()));
EXPECT_TRUE(map.has(12345));
auto v = map.get(12345);
EXPECT_EQ(v, "0x12345");
}
TEST_F(Lconst_test, used_bits) {
auto a = 0x010_uint;
print_method(a);
fmt::print("a used bits:{}\n", a.bit_length());
auto b = 0x010_uint; // runtime or compile time
print_method(b);
fmt::print("b used bits:{}\n", b.bit_length());
uint64_t v = 0x10;
auto uint_ptr = reinterpret_cast<UInt<8> *>(&v);
auto & u = *uint_ptr;
fmt::print("u used bits:{}\n", u.bit_length());
}
TEST_F(Lconst_test, boost) {
auto a = 0x0000010_uint;
auto b = 0x0100030_uint;
auto c = a * b;
using boost::multiprecision::cpp_int;
cpp_int b_a("0x010");
cpp_int b_b(b.to_string_hex());
cpp_int b_c = b_a * b_b;
std::vector<unsigned char> v;
export_bits(b_c, std::back_inserter(v), 8);
cpp_int b_c_recover;
import_bits(b_c_recover, v.begin(), v.end());
EXPECT_EQ(b_c.str(), b_c_recover.str());
cpp_int c_x(c.to_string_hex());
EXPECT_EQ(c_x.str(), b_c_recover.str());
}
TEST_F(Lconst_test, trivial_vals) {
Lconst p_1(1);
Lconst p_2(2);
Lconst n_1 = p_1 - p_2;
EXPECT_EQ(p_1.to_i(), 1);
EXPECT_EQ(p_2.to_i(), 2);
EXPECT_EQ(n_1.to_i(), -1);
EXPECT_EQ(Lconst::from_pyrope("-2").to_i(), -2);
EXPECT_EQ(Lconst::from_pyrope("0").to_i(), 0);
EXPECT_EQ(Lconst::from_pyrope("1").to_i(), 1);
EXPECT_EQ(Lconst::from_pyrope("3278").to_i(), 3278);
EXPECT_EQ(Lconst::from_pyrope("-13278").to_i(), -13278);
EXPECT_EQ(Lconst::from_pyrope("-2").to_pyrope(), "-2");
EXPECT_EQ(Lconst::from_pyrope("0").to_pyrope(), "0");
EXPECT_EQ(Lconst::from_pyrope("1").to_pyrope(), "1");
}
TEST_F(Lconst_test, hexa_check) {
//auto v1 = Lconst::from_pyrope("0xdbd7b0ac8a3a5dcb7ada8e8a30ea6dc54ebe6bc7a37d2d8b2cd2a");
auto v1 = Lconst::from_pyrope("0x64a02e47a5ceca6e50ccbded70bbc7ca56e644d5ee1eb447ea14e33d53a6e5d");
mmap_lib::str str("0x64a02e47a5ceca6e50ccbded70bbc7ca56e644d5ee1eb447ea14e33d53a6e5d");
auto s1 = v1.serialize();
auto v2 = Lconst::unserialize(s1);
#if 0
fmt::print("or:");
for(auto i=0u;i<s1.size();++i) {
fmt::print(":{}", (int)s1[i]);
}
fmt::print("\n");
fmt::print("v1:{}\n", v1.to_pyrope());
fmt::print("v2:{}\n", v2.to_pyrope());
#endif
EXPECT_EQ(v1,v2);
EXPECT_EQ(v1.to_pyrope(),str);
EXPECT_EQ(v2.to_pyrope(),str);
}
TEST_F(Lconst_test, hexa_check_long) {
Lbench b("lemu.LCONST_const_attr");
unlink("lgdb_attr/c_map");
mmap_lib::map<uint32_t, mmap_lib::str> c_map("lgdb_attr","c_map");
Lrand<size_t> rnd;
const size_t n_const = rnd.between(200, 3000);
std::vector<mmap_lib::str> rnd_list;
Lrand_range<int> num_digits(1, 200);
Lrand_range<char> hex1_digits('0', '9');
Lrand_range<char> hex2_digits('a', 'f');
Lrand_range<char> hex3_digits('A', 'F');
Lrand<bool> flip;
rnd_list.resize(n_const);
for (auto i = 0u; i < n_const; ++i) {
rnd_list[i] = "0x";
for (auto j = num_digits.any(); j > 0; --j) {
if (flip.any())
rnd_list[i] = rnd_list[i].append(hex1_digits.any());
else if (flip.any())
rnd_list[i] = rnd_list[i].append(hex2_digits.any());
else
rnd_list[i] = rnd_list[i].append(hex3_digits.any());
}
c_map.set(i, Lconst::from_pyrope(rnd_list[i]).serialize());
auto v1 = Lconst::from_pyrope(rnd_list[i]);
auto v2 = Lconst::unserialize(v1.serialize());
//fmt::print("raw:{}\n",rnd_list[i]);
//fmt::print("1 :{}\n",v1.to_pyrope());
//fmt::print("2 :{}\n",v2.to_pyrope());
//v1.dump();
//v2.dump();
EXPECT_EQ(v1, v2);
}
for (auto i = 0u; i < n_const; ++i) {
{ // CHECK that mmap works
auto v1 = Lconst::unserialize(c_map.get(i));
auto v2 = Lconst::from_pyrope(rnd_list[i]);
//fmt::print("raw:{}\n",rnd_list[i]);
//fmt::print(" :{}\n",v1.to_pyrope());
//fmt::print(" :{}\n",v2.to_pyrope());
EXPECT_EQ(v1, v2);
}
boost::multiprecision::cpp_int c(rnd_list[i].to_s()); // read hexa
std::stringstream ss;
ss << std::hex << c;
{ // CHECK that to/from pyrope is consistent
auto v1 = Lconst::from_pyrope(rnd_list[i]);
auto v2 = Lconst::from_pyrope(v1.to_pyrope());
EXPECT_EQ(v1,v2);
if (c>63 && rnd_list[i][2] != '0') { // no short pyrope syntax, no 0x0... which will be shorter
EXPECT_EQ(v1.to_pyrope(), rnd_list[i].to_lower());
}
}
auto a = Lconst::from_pyrope(rnd_list[i]);
EXPECT_EQ(a.get_raw_num(), c);
}
}
TEST_F(Lconst_test, dec_check) {
boost::multiprecision::cpp_int b10("10");
auto p10 = Lconst::from_pyrope("10");
EXPECT_EQ(p10.get_raw_num(), b10);
auto p123 = Lconst::from_pyrope("123");
boost::multiprecision::cpp_int b123("123");
EXPECT_EQ(p123.get_raw_num(), b123);
Lrand<size_t> rnd;
const size_t n_const = rnd.between(200, 3000);
std::vector<std::string> rnd_list;
Lrand_range<int> num_digits(1, 200);
Lrand_range<char> hex1_digits('0', '9');
Lrand_range<char> hex2_digits('1', '9');
Lrand<bool> flip;
std::vector<bool> negative;
rnd_list.resize(n_const);
negative.resize(n_const);
for (auto i = 0u; i < n_const; ++i) {
if (flip.any()) {
rnd_list[i].append(1, '-');
negative[i] = true;
}
rnd_list[i].append(1, hex2_digits.any());
for (auto j = num_digits.any(); j > 0; --j) {
rnd_list[i].append(1, hex1_digits.any());
}
}
for (auto i = 0u; i < n_const; ++i) {
boost::multiprecision::cpp_int c(rnd_list[i]);
mmap_lib::str padded;
bool digit_found=false;
for (const auto ch : rnd_list[i]) {
if (flip.any() && digit_found)
padded = padded.append('_');
padded = padded.append(ch);
if (std::isdigit(ch))
digit_found = true;
}
auto a1 = Lconst::from_pyrope(mmap_lib::str(rnd_list[i]));
EXPECT_EQ(a1.get_raw_num(), c);
auto a2 = Lconst::from_pyrope(padded);
#if 0
if (a2.get_raw_num() != c) {
fmt::print("PADDED:{}\n", padded);
a2.dump();
a1.dump();
}
#endif
EXPECT_EQ(a2.get_raw_num(), c);
auto fmt_a = a1.to_pyrope();
auto b = Lconst::from_pyrope(fmt_a);
#if 0
fmt::print("orig:{}\n",rnd_list[i]);
fmt::print(" a1:{}\n",a1.to_pyrope());
fmt::print(" a2:{}\n",a2.to_pyrope());
fmt::print("padd:{}\n",padded);
fmt::print(" b:{}\n",b.to_pyrope());
#endif
EXPECT_EQ(b.get_raw_num(), c);
}
}
TEST_F(Lconst_test, string) {
auto a = Lconst::from_pyrope("cadena");
auto b = Lconst::from_pyrope("'cadena'");
EXPECT_EQ(a.to_pyrope(), "'cadena'");
EXPECT_EQ(b.to_pyrope(), "'cadena'");
EXPECT_EQ(Lconst::from_string("a longer chain of text").to_pyrope(), mmap_lib::str("'a longer chain of text'"));
EXPECT_EQ(Lconst::from_pyrope("a longer chain of text").to_pyrope(), mmap_lib::str("'a longer chain of text'"));
EXPECT_EQ(Lconst::from_pyrope("'a longer chain of text'").to_pyrope(), mmap_lib::str("'a longer chain of text'"));
EXPECT_EQ(Lconst::from_string("'a longer chain of text'").to_pyrope(), mmap_lib::str("'a longer chain of text'"));
EXPECT_EQ(Lconst::from_pyrope("\'a longer chain of text").to_pyrope(), mmap_lib::str("'\'a longer chain of text'"));
EXPECT_EQ(Lconst::from_pyrope("").to_pyrope(), mmap_lib::str("0"));
EXPECT_EQ(Lconst::from_pyrope("''").to_pyrope(), mmap_lib::str("''"));
EXPECT_EQ(Lconst::from_string("''").to_pyrope(), mmap_lib::str("''"));
EXPECT_EQ(Lconst::from_string("''''").to_pyrope(), mmap_lib::str("''''")); // Lconst::from_pyrope("''''") raises an exception
EXPECT_EQ(Lconst::from_pyrope("__longer chain of text").to_pyrope(), mmap_lib::str("'__longer chain of text'"));
EXPECT_EQ(Lconst::from_pyrope("_").to_pyrope(), mmap_lib::str("'_'"));
EXPECT_EQ(Lconst::from_pyrope("a").to_pyrope(), mmap_lib::str("'a'"));
EXPECT_TRUE(Lconst::from_pyrope("_").is_string());
EXPECT_FALSE(Lconst::from_pyrope("0").is_string());
EXPECT_EQ(Lconst::from_pyrope("0").get_raw_num(), 0);
}
TEST_F(Lconst_test, false_true) {
EXPECT_TRUE(Lconst::from_pyrope("string").is_known_true());
EXPECT_TRUE(Lconst::from_pyrope("true").is_known_true());
EXPECT_TRUE(Lconst::from_pyrope("3").is_known_true());
EXPECT_TRUE(Lconst::from_pyrope("").is_known_false()); // empty string is false
EXPECT_FALSE(Lconst::from_pyrope("string").is_known_false());
EXPECT_FALSE(Lconst::from_pyrope("true").is_known_false());
EXPECT_FALSE(Lconst::from_pyrope("3").is_known_false());
EXPECT_FALSE(Lconst::from_pyrope("").is_known_true()); // empty string is false
EXPECT_FALSE(Lconst::from_pyrope("false").is_known_true());
EXPECT_FALSE(Lconst::from_pyrope("0x0000").is_known_true());
EXPECT_FALSE(Lconst::from_pyrope("0sb0000").is_known_true());
EXPECT_FALSE(Lconst::from_pyrope("0b0000").is_known_true());
EXPECT_FALSE(Lconst::from_pyrope("0000").is_known_true());
EXPECT_FALSE(Lconst::from_pyrope("0").is_known_true());
EXPECT_TRUE(Lconst::from_pyrope("false").is_known_false());
EXPECT_TRUE(Lconst::from_pyrope("0x0000").is_known_false());
EXPECT_TRUE(Lconst::from_pyrope("0sb0000").is_known_false());
EXPECT_TRUE(Lconst::from_pyrope("0b0000").is_known_false());
EXPECT_TRUE(Lconst::from_pyrope("0000").is_known_false());
EXPECT_TRUE(Lconst::from_pyrope("0").is_known_false());
// with unknowns
EXPECT_FALSE(Lconst::from_pyrope("0b?").is_known_false());
EXPECT_FALSE(Lconst::from_pyrope("0b?").is_known_true());
EXPECT_FALSE(Lconst::from_pyrope("0sb??000??").is_known_false());
EXPECT_FALSE(Lconst::from_pyrope("0sb?0?0??").is_known_true());
EXPECT_FALSE(Lconst::from_pyrope("0sb??000??").is_known_false());
EXPECT_FALSE(Lconst::from_pyrope("0sb?0?0??").is_known_true());
}
TEST_F(Lconst_test, binary) {
auto c = Lconst::from_pyrope("0b01__?10__?_1");
Lconst a = Lconst::from_pyrope("0b1100");
Lconst b = Lconst::from_pyrope("12");
Lconst b2 = Lconst::from_pyrope("12");
a.dump();
b.dump();
EXPECT_TRUE(a == b); // explicit sign (12s vs 12u) does not change this
EXPECT_TRUE(a == b2); // explicit sign (12s vs 12u) does not change this
EXPECT_EQ(a, b); // different explicit bits
EXPECT_EQ(a, b2); // different explicit bits
EXPECT_FALSE(a.eq_op(b).is_known_false());
EXPECT_FALSE(a.eq_op(b2).is_known_false());
EXPECT_TRUE(a.eq_op(b).is_known_true());
EXPECT_TRUE(a.eq_op(b2).is_known_true());
EXPECT_EQ(c.to_verilog(), "7'sb01?10?1");
EXPECT_EQ(c.to_pyrope(), "0b001?_10?1");
auto d = Lconst::from_pyrope("0b____1_1x1_");
EXPECT_EQ(d.to_pyrope(), "0b0000_11?1");
EXPECT_EQ(d.to_verilog(), "5'sb011?1");
EXPECT_EQ(d.to_binary(), "011?1");
auto e = Lconst::from_pyrope("_-__0b1_");
EXPECT_EQ(e.to_pyrope(), "'_-__0b1_'");
EXPECT_EQ(e.to_verilog(), "\"_-__0b1_\"");
auto e1 = Lconst::from_pyrope("-0b11_");
EXPECT_EQ(e1.to_pyrope(), "-3");
EXPECT_EQ(e1.to_verilog(), "3'sh5"); // 3'sb101
auto f = Lconst::from_pyrope("0b1_0100");
EXPECT_EQ(f.to_pyrope(), "20");
EXPECT_EQ(f.to_verilog(), "6'sh14");
EXPECT_EQ(f.to_binary(), "010100");
Lconst g = Lconst::from_pyrope("0bxxxx_xxxx_");
EXPECT_EQ(g.to_pyrope(), "0b0000_????_????");
EXPECT_EQ(g.to_verilog(), "9'sb0????????");
EXPECT_EQ(g.to_binary(), "0????????");
Lconst h = Lconst::from_pyrope("0b0??___???_??___?");
EXPECT_EQ(h, g);
Lconst g1 = Lconst::from_pyrope("0sb1xx_xxxx_");
EXPECT_EQ(g1.to_pyrope(), "0sb11??_????");
Lconst g2 = Lconst::from_pyrope("0bxxx_xxxx_");
EXPECT_EQ(g2, Lconst::from_pyrope("0b0_0_0_0_0_0_0__???__????")); // positive, add zeroes at will
EXPECT_EQ(g2.to_pyrope(), "0b0???_????");
EXPECT_EQ(g2.to_verilog() ,"8'sb0???????");
EXPECT_EQ(g2.to_binary() , "0???????"); // 0 as MSB because it is a positive number
Lconst g3 = Lconst::from_pyrope("0sb0xxx_xxxx_");
EXPECT_EQ(g3.to_pyrope() , "0b0???_????");
EXPECT_EQ(g3.to_verilog(), "8'sb0???????");
EXPECT_EQ(g3.to_binary() , "0???????");
Lconst g4 = Lconst::from_pyrope("0sb11111xxxx_xxxx_");
g4.dump();
fmt::print("pyrope :{}\n", g4.to_pyrope());
fmt::print("verilog:{}\n", g4.to_verilog());
EXPECT_EQ(g4.to_pyrope(), "0sb1111_????_????");
EXPECT_EQ(g4.to_verilog(), "9'sb1????????");
EXPECT_EQ(g4.to_binary() , "1????????");
Lconst j = Lconst::from_pyrope("-17");
EXPECT_EQ(j.to_pyrope(), "-17"); // small constant
EXPECT_EQ(j.to_verilog(), "6'sh2f"); // neg values use binary (could be patched)
EXPECT_EQ(j.to_binary(), "101111");
{
Lconst k = Lconst::from_pyrope("17");
EXPECT_EQ(k.to_pyrope(), "17");
EXPECT_EQ(k.to_verilog(), "6'sh11");
EXPECT_EQ(k.to_binary(), "010001");
}
{
Lconst k = Lconst::from_pyrope("255");
EXPECT_EQ(k.to_pyrope(), "0xff");
EXPECT_EQ(k.to_verilog(), "9'shff");
EXPECT_EQ(k.to_binary(), "011111111");
}
{
Lconst k = Lconst::from_pyrope("0sb111111");
EXPECT_EQ(k.to_pyrope(), "-1");
EXPECT_EQ(k.to_verilog(), "1'sh1"); // hex positives
EXPECT_EQ(k.to_binary(), "1");
}
}
TEST_F(Lconst_test, serialize) {
mmap_lib::map<uint32_t, Lconst::Container> map;
Lconst a(255);
Lconst b = Lconst::from_pyrope("0xFF");
Lconst c = Lconst::from_pyrope("0x1234567890abcdef1234567890abcdef");
map.set(1, a.serialize());
map.set(2, b.serialize());
map.set(3, c.serialize());
auto s_a = Lconst::unserialize(map.get(1));
auto s_b = Lconst::unserialize(map.get(2));
auto s_c = Lconst::unserialize(map.get(3));
b.dump();
s_b.dump();
fmt::print(" a:{}\n", a.to_pyrope());
fmt::print("s_a:{}\n", s_a.to_pyrope());
fmt::print(" b:{}\n", b.to_pyrope());
fmt::print("s_b:{}\n", s_b.to_pyrope());
fmt::print(" c:{}\n", c.to_pyrope());
fmt::print("s_c:{}\n", s_c.to_pyrope());
EXPECT_EQ(a, s_a);
EXPECT_EQ(b, s_b);
EXPECT_EQ(c, s_c);
}
TEST_F(Lconst_test, serialize2a) {
{
unlink("tmp_lemu/const");
mmap_lib::map<uint32_t, Lconst::Container> map("tmp_lemu", "const");
Lconst a(255);
Lconst b = Lconst::from_pyrope("0xFF");
Lconst c = Lconst::from_pyrope("0x1234567890abcdef1234567890abcdef");
map.set(1, a.serialize());
map.set(2, b.serialize());
map.set(3, c.serialize());
}
{
mmap_lib::map<uint32_t, Lconst::Container> map("tmp_lemu", "const");
auto s_a = Lconst::unserialize(map.get(1));
auto s_b = Lconst::unserialize(map.get(2));
auto s_c = Lconst::unserialize(map.get(3));
Lconst a(255);
Lconst b = Lconst::from_pyrope("0xFF");
Lconst c = Lconst::from_pyrope("0x1234567890abcdef1234567890abcdef");
b.dump();
s_b.dump();
fmt::print(" a:{}\n", a.to_pyrope());
fmt::print("s_a:{}\n", s_a.to_pyrope());
fmt::print(" b:{}\n", b.to_pyrope());
fmt::print("s_b:{}\n", s_b.to_pyrope());
fmt::print(" c:{}\n", c.to_pyrope());
fmt::print("s_c:{}\n", s_c.to_pyrope());
EXPECT_EQ(a, s_a);
EXPECT_EQ(b, s_b);
EXPECT_EQ(c, s_c);
}
}
TEST_F(Lconst_test, zerocase) {
Lconst nothing;
EXPECT_EQ(nothing.get_bits(), 0);
EXPECT_EQ(Lconst(0).get_bits(), 1);
EXPECT_EQ(Lconst::from_pyrope("0x0").get_bits(), 1);
EXPECT_EQ(Lconst::from_pyrope("0").get_bits(), 1);
EXPECT_EQ(Lconst::from_pyrope("0b0").get_bits(), 1);
EXPECT_EQ(Lconst::from_pyrope("0b?").get_bits(), 2);
}
TEST_F(Lconst_test, cpp_int_vs_lconst) {
using boost::multiprecision::cpp_int;
cpp_int a(-1);
cpp_int b = Lconst::from_pyrope("0xFF").get_raw_num();
cpp_int c_and = a & b;
cpp_int d_and = a & a;
auto a_not = a;
a_not = ~a;
auto b_not = b;
b_not = ~b;
fmt::print("{} s:{} p:{}\n", a.str(), a.sign(), a_not.str());
fmt::print("{} s:{} p:{}\n", b.str(), b.sign(), b_not.str());
auto c_and_not = c_and;
auto d_and_not = d_and;
c_and_not = ~c_and;
d_and_not = ~d_and;
fmt::print("{} = {} & {} s:{} ~:{}\n", c_and.str(), a.str(), b.str(), c_and.sign(), c_and_not.str());
fmt::print("{} = {} & {} s:{} ~:{}\n", d_and.str(), a.str(), a.str(), c_and.sign(), d_and_not.str());
cpp_int c_or = a | b;
cpp_int d_or = a | a;
auto c_or_not = c_or;
auto d_or_not = d_or;
c_or_not = ~c_or;
d_or_not = ~d_or;
fmt::print("{} = {} | {} s:{} ~:{}\n", c_or.str(), a.str(), b.str(), c_or.sign(), c_or_not.str());
fmt::print("{} = {} | {} s:{} ~:{}\n", d_or.str(), a.str(), a.str(), c_or.sign(), d_or_not.str());
Lconst l_a = Lconst::from_pyrope("-1");
Lconst l_b = Lconst::from_pyrope("0xFF");
Lconst l_c_and = l_a.and_op(l_b);
Lconst l_d_and = l_a.and_op(l_a);
EXPECT_EQ(l_c_and.to_i(), c_and.convert_to<int>());
EXPECT_EQ(l_d_and.to_i(), d_and.convert_to<int>());
Lconst l_c_or = l_a.or_op(l_b);
Lconst l_d_or = l_a.or_op(l_a);
EXPECT_EQ(l_c_or.to_i(), c_or.convert_to<int>());
EXPECT_EQ(l_d_or.to_i(), d_or.convert_to<int>());
// Same/diff are not the same
cpp_int c_eq = a == b;
cpp_int d_eq = a == a;
fmt::print("{} = {} == {} s:{}\n", c_eq.str(), a.str(), b.str(), c_eq.sign());
fmt::print("{} = {} == {} s:{}\n", d_eq.str(), a.str(), a.str(), c_eq.sign());
Lconst l_c_eq = l_a.eq_op(l_b);
Lconst l_d_eq = l_a.eq_op(l_a);
EXPECT_EQ(c_eq, 0);
EXPECT_NE(d_eq, 0);
EXPECT_EQ(l_c_eq, 0);
EXPECT_NE(l_d_eq, 0);
EXPECT_EQ(l_d_eq, -1);
}
TEST_F(Lconst_test, lconst_add) {
{
auto a = Lconst::from_pyrope("0xF0") + Lconst::from_pyrope("0x0E");
EXPECT_EQ(a.to_i(), 254);
EXPECT_EQ(a.get_bits(), 9);
}
{
auto a = Lconst::from_pyrope("0xFF") + Lconst::from_pyrope("-1");
EXPECT_EQ(a.to_i(), 254);
EXPECT_EQ(a.get_bits(), 9);
}
{
auto a = Lconst::from_pyrope("0xFF") + Lconst::from_pyrope("-1");
EXPECT_EQ(a.to_i(), 254);
EXPECT_EQ(a.get_bits(), 9);
}
{
auto a = Lconst::from_pyrope("1") + Lconst::from_pyrope("-1");
EXPECT_EQ(a.to_i(), 0);
EXPECT_EQ(a.get_bits(), 1);
}
{
auto a = Lconst::from_pyrope("0b0?") + Lconst::from_pyrope("1");
EXPECT_FALSE(a.is_i());
EXPECT_EQ(a, Lconst::from_pyrope("0b??"));
EXPECT_EQ(a.to_pyrope(), "0b00??");
EXPECT_EQ(a.get_bits(), 3);
}
}
TEST_F(Lconst_test, lconst_get_bits) {
Lconst cadena = Lconst::from_pyrope("cadena"); // c=0x63, a=0x61, d=0x64, e=0x65, n=0x6E
EXPECT_EQ(cadena.get_mask_op() , Lconst::from_pyrope("cadena"));
EXPECT_EQ(cadena.get_mask_op(Lconst(-1)) , Lconst::from_pyrope("cadena"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFFFFFFFFFFFFULL)), Lconst::from_pyrope("cadena"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFFFFFFFFFF00ULL)), Lconst::from_pyrope("adena"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFFFFFFFF00FFULL)), Lconst::from_pyrope("cdena"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFFFFFF0000FFULL)), Lconst::from_pyrope("cena"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFFULL)), Lconst::from_pyrope("c"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFF00ULL)), Lconst::from_pyrope("a"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFF0000ULL)), Lconst::from_pyrope("d"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFF000000ULL)), Lconst::from_pyrope("e"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFF00000000ULL)), Lconst::from_pyrope("n"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFF0000000000ULL)), Lconst::from_pyrope("a"));
EXPECT_EQ(cadena.get_mask_op(Lconst(0xFF000000000000ULL)), Lconst::from_pyrope(""));
EXPECT_EQ(Lconst::from_pyrope("0xFFF").get_mask_op(Lconst::from_pyrope("-1")), Lconst::from_pyrope("0xFFF"));
EXPECT_EQ(Lconst::from_pyrope("0xfeef").get_mask_op(Lconst::from_pyrope("-1")), Lconst::from_pyrope("0xfeef"));
// a =0b1111_1110_1110_1111 mask=11111.111110
// out=0b 1111_1110_1110_111
EXPECT_EQ(Lconst::from_pyrope("0xfeef").get_mask_op(Lconst::from_pyrope("-2")), Lconst::from_pyrope("0x7F77"));
EXPECT_EQ(Lconst::from_pyrope("0xfeef").get_mask_op(Lconst::from_pyrope("-3")), Lconst::from_pyrope("0x7F77"));
// a =0b1111_1110_1110_1[11]1 mask=11111.111001
// out= 0b1111_1110_1110_11
//
// out = {foo[1],foo[3],foo[5]}
// out = getmask(foo,0b1_1010)
//
// out = getmask(foo,-1) // convert to unsign
//
// tmp = bar@[1,2,54] // get_mask(bar, (1<<1) | (1<<2) | (1<<54))
auto val1 = Lconst::from_pyrope("0xfeee").get_mask_op(Lconst::from_pyrope("-2"));
auto val2 = Lconst::from_pyrope("0xfeee").get_mask_op(Lconst::from_pyrope("-3"));
fmt::print("val1:{} val2:{}\n", val1.to_pyrope(), val2.to_pyrope());
EXPECT_EQ(Lconst::from_pyrope("0b1011_0110").get_mask_op(Lconst::from_pyrope("-2")), Lconst::from_pyrope("0b1011_011")); // -2 (1111..110) drop bit 0
EXPECT_EQ(Lconst::from_pyrope("0b1011_0110").get_mask_op(Lconst::from_pyrope("-3")), Lconst::from_pyrope("0b1011_010")); // -3 (1111..101) drop bit 1
auto v1 = Lconst::from_pyrope("-23").get_mask_op(Lconst::from_pyrope("-1"));
auto v2 = Lconst::from_pyrope("-23").get_mask_op();
auto v3 = Lconst::from_pyrope("41");
EXPECT_EQ(v1, v2);
EXPECT_EQ(v2, v3);
auto v4 = Lconst::from_pyrope("-23").get_mask_op(Lconst::from_pyrope("0xFFF"));
EXPECT_EQ(v4, Lconst::from_pyrope("0xfe9"));
EXPECT_EQ(Lconst(-2).get_mask_op(Lconst(0xF)), Lconst::from_pyrope("0xe"));
EXPECT_EQ(Lconst(-2).get_mask_op(Lconst(0xFF)), Lconst::from_pyrope("0xFe"));
EXPECT_EQ(Lconst(-2).get_mask_op(Lconst(0xF0F)), Lconst::from_pyrope("0xFe"));
EXPECT_EQ(Lconst::from_pyrope("0b0?0").get_mask_op(Lconst::from_pyrope("1")), Lconst::from_pyrope("0"));
EXPECT_EQ(Lconst::from_pyrope("0b0?0").get_mask_op(Lconst::from_pyrope("2")), Lconst::from_pyrope("0b?"));
EXPECT_EQ(Lconst::from_pyrope("0b0?0").get_mask_op(Lconst::from_pyrope("4")), Lconst::from_pyrope("0"));
EXPECT_EQ(Lconst::from_pyrope("0b?0?0").get_mask_op(Lconst::from_pyrope("0x7")), Lconst::from_pyrope("0b0?0"));
EXPECT_EQ(Lconst::from_pyrope("0b?0?0").get_mask_op(Lconst::from_pyrope("0xFF")), Lconst::from_pyrope("0b0?0?0"));
EXPECT_EQ(Lconst::from_pyrope("0xfeef").get_mask_op(Lconst::from_pyrope("1")), Lconst::from_pyrope("1"));
EXPECT_EQ(Lconst::from_pyrope("-1").get_mask_op(Lconst::from_pyrope("0x3")), Lconst::from_pyrope("0b11"));
EXPECT_EQ(Lconst::from_pyrope("-1").get_mask_op(Lconst::from_pyrope("0")), Lconst::from_pyrope("0"));
EXPECT_EQ(Lconst::from_pyrope("-123123").get_mask_op(Lconst::from_pyrope("1")), Lconst::from_pyrope("1")); // 0b....1 & 0x1 == 1
EXPECT_EQ(Lconst::from_pyrope("0xfeef").get_mask_op(Lconst::from_pyrope("0xFF")), Lconst::from_pyrope("0xEF"));
}
TEST_F(Lconst_test, lconst_set_bits) {
{
auto tmp1 = Lconst::from_pyrope("0xfeef").get_mask_op(Lconst::from_pyrope("0xFF")); // 0xEF
auto tmp2 = Lconst::from_pyrope("0xfe0F").set_mask_op(Lconst::from_pyrope("0xFF"), tmp1); // 0xfeef
EXPECT_EQ(tmp1, Lconst(0xef));
EXPECT_EQ(tmp2, Lconst(0xfeef));
}
auto src = Lconst::from_pyrope("0xFFF");
EXPECT_EQ(src.set_mask_op(Lconst::from_pyrope("0x0F0"), Lconst(0xabc)) , Lconst::from_pyrope("0xfcf"));
EXPECT_EQ(src.set_mask_op(Lconst::from_pyrope("0x0F0"), Lconst(0x3abc)), Lconst::from_pyrope("0xfcf"));
EXPECT_EQ(src.set_mask_op(Lconst::from_pyrope("0x0FF"), Lconst(0xabc)) , Lconst::from_pyrope("0xfbc"));
EXPECT_EQ(src.set_mask_op(Lconst::from_pyrope("0xF0F"), Lconst(0xabc)) , Lconst::from_pyrope("0xbFc"));
EXPECT_EQ(src.set_mask_op(Lconst::from_pyrope("0xF0F"), Lconst(0xa)) , Lconst::from_pyrope("0x0Fa"));
// base is 0
// mask is 111..11_0_1111 (-17)
// value is 0b1_1111_1110_1111
// res is 0b11_1111_1100_1111
EXPECT_EQ(Lconst( 0).set_mask_op(Lconst::from_pyrope("-17"), Lconst(0x1FEF)), Lconst(0x3FCF));
// base is 1_0000
// mask is 111..11_0_1111 (-17)
// value is 0b1_1111_1110_1111
// res is 0b11_1111_1101_1111
Lconst( 0x10).set_mask_op(Lconst::from_pyrope("-17"), Lconst(0x1FEF)).dump();
EXPECT_EQ(Lconst( 0x10).set_mask_op(Lconst::from_pyrope("-17"), Lconst(0x1FEF)), Lconst(0x3FDF));
// out[0:300] = xxxx
// out[2:3] = bar // out = set_mask(out, 0b01100, bar)
src.set_mask_op(Lconst::from_pyrope("-1"), Lconst(0x3abcd)).dump();
EXPECT_EQ(src.set_mask_op(Lconst::from_pyrope("-1"), Lconst(0x3abc)), Lconst(0x3abc));
EXPECT_EQ(src.set_mask_op(Lconst::from_pyrope("-1"), Lconst(0xa)), Lconst(0xa));
// base is xxxx_010x
// mask is 111..1111_0001 (-15)
// value is 0b1_1011_1100_110 1
// res is 0b1101_1110_0110_0101
Lconst(0x14).set_mask_op(Lconst::from_pyrope("-15"), Lconst(0x1bcd)).dump();
EXPECT_EQ(Lconst(0x14).set_mask_op(Lconst::from_pyrope("-15"), Lconst(0x1bcd)), Lconst(0xde65));
#if 0
// FIXME: This should work
// base is 111..1110_0100 (-28)
// mask is 111..1111_0001 (-15)
// value is 0b1_1011_1100_110 1
// res is 0b1101_1110_0110_0101
Lconst(-28).set_mask_op(Lconst::from_pyrope("-15"), Lconst(0x1bcd)).dump();
EXPECT_EQ(Lconst(-28).set_mask_op(Lconst::from_pyrope("-15"), Lconst(0x1bcd)), Lconst(0xde65));
// base is 111..1111_1110 (-2)
// mask is 111..1111_0001 (-15)
// value is 0b1_1011_1100_110 1
// res is 0b1101_1110_0110_1110
Lconst(-2).set_mask_op(Lconst::from_pyrope("-15"), Lconst(0x1bcd)).dump();
EXPECT_EQ(Lconst(-2).set_mask_op(Lconst::from_pyrope("-15"), Lconst(0x1bcd)), Lconst(0xde6d));
#endif
}
TEST_F(Lconst_test, lconst_sign) {
{
auto neg1 = Lconst::from_pyrope("-123");
auto pos1 = Lconst::from_pyrope("43");
auto pos2 = pos1.mult_op(Lconst::from_pyrope("0b?"));
auto neg2 = Lconst(-1).mult_op(Lconst::from_pyrope("0b?")); // neg * pos -> neg
auto pos3 = neg2.mult_op(neg1);
auto neg3 = pos3.mult_op(neg2);
EXPECT_TRUE(!pos1.is_negative());
EXPECT_TRUE(!pos2.is_negative());
EXPECT_TRUE(!pos3.is_negative());
EXPECT_TRUE( neg1.is_negative());
EXPECT_TRUE( neg2.is_negative());
EXPECT_TRUE( neg3.is_negative());
}
{
EXPECT_EQ(Lconst::from_pyrope(-123), Lconst::from_pyrope("0sb1111110000101"));
//"0sb1111110000101"
//"0sb00000000??0??"
auto pos1 = Lconst(-123).and_op(Lconst::from_pyrope("0b??0??"));
EXPECT_TRUE(!pos1.is_negative());
auto zero = pos1.rsh_op(2).and_op(1);
fmt::print("zero:{}\n",zero.to_pyrope());
EXPECT_EQ(zero, Lconst::from_pyrope("0b?"));
}
{
auto neg1 = Lconst(-123).div_op(Lconst::from_pyrope("0b??0??"));
auto neg2 = Lconst::from_pyrope("0b??0??").div_op(-2);
auto pos1 = Lconst( 47).div_op(Lconst::from_pyrope("0b?0?"));
auto pos2 = Lconst::from_pyrope("0b??0??").div_op( 3);
EXPECT_TRUE(!pos1.is_negative());
EXPECT_TRUE(!pos2.is_negative());
EXPECT_TRUE( neg1.is_negative());
EXPECT_TRUE( neg2.is_negative());
auto pos3 = neg1.div_op(3122000); // 0
EXPECT_TRUE(!pos3.is_negative());
auto zero = Lconst::from_pyrope("0b????").div_op(16); // 0
EXPECT_EQ(zero, Lconst(0));
}
}
TEST_F(Lconst_test, lconst_sext) {
Lconst c_255(255);
EXPECT_EQ(Lconst(-3).sext_op(1), Lconst( 1)); // 0sb01 == 1
for(auto i=0u;i<8;++i) {
EXPECT_EQ(c_255.sext_op(i), Lconst(-1));
}
for(auto i=8u;i<16;++i) {
EXPECT_EQ(c_255.sext_op(i), c_255);
}
EXPECT_EQ(Lconst::from_pyrope("0b10101").sext_op(0), Lconst(-1 ));
EXPECT_EQ(Lconst::from_pyrope("0b10101").sext_op(1), Lconst::from_pyrope("0b1" ));
EXPECT_EQ(Lconst::from_pyrope("0b10101").sext_op(2), Lconst(-3 )); // 0sb101 == -3
EXPECT_EQ(Lconst::from_pyrope("0b10101").sext_op(3), Lconst::from_pyrope("0b0101")); // 0sb101 == -3
EXPECT_EQ(Lconst::from_pyrope("0b10101").sext_op(4), Lconst(-11 )); // 0sb10101 == -11
EXPECT_EQ(Lconst(-3).sext_op(0), Lconst(-1)); // 0sb1 == -1
EXPECT_EQ(Lconst(-3).sext_op(1), Lconst( 1)); // 0sb01 == 1
EXPECT_EQ(Lconst(-3).sext_op(2), Lconst(-3)); // 0sb101 == -3
EXPECT_EQ(Lconst(-3).sext_op(3), Lconst(-3)); // 0sb1101 == -3
EXPECT_EQ(Lconst(-3).sext_op(4), Lconst(-3)); // 0sb11101 == -3
EXPECT_EQ(Lconst::from_pyrope("0b10111").sext_op(3), Lconst(7)); // 0sb0111 == 7
EXPECT_EQ(Lconst::from_pyrope("0b10111").sext_op(2), Lconst(-1)); // 0sb111 == -1
}
Lconst bit_implies(Lconst tmp1, Lconst tmp2){
return ((tmp1.not_op()).or_op(tmp2));
}
TEST_F(Lconst_test, get_set_mask_equivalence) {
#if 0
Lrand<size_t> rnd;
for(int i = 0; i < 36; i++){ //dozens of random size_t for testing
Lconst a(rnd.any());
Lconst b(rnd.any());
Lconst c(rnd.any());
Lconst X(rnd.any());
Lconst Y(rnd.any());
// 1- get_mask(get_mask(X,a),b)) == get_mask(X, set_mask(a=a,val=-1,mask=b))
// EXPECT_EQ((X.get_mask_op(a)).get_mask_op(b), X.get_mask_op(a.set_mask_op(b, Lconst(-1)))); fails, set_mask neg value assertion
// 2- get_mask(0,b) == 0
EXPECT_EQ(Lconst(0).get_mask_op(b), Lconst(0));
// 3- get_mask(-1,b) && b>0 == b
EXPECT_EQ(Lconst(-1).get_mask_op(b), b); //fails, works with masks of all 1's
// 4- get_mask(a,-1) && a>0 == a
EXPECT_EQ(a.get_mask_op(Lconst(-1)), a);
// 5- get_mask(a,0) == 0
EXPECT_EQ(a.get_mask_op(Lconst(0)), Lconst(0));
// 6- set_mask(a=0,val=X,mask=b) == get_mask(X,b)
EXPECT_EQ(Lconst(0).set_mask_op(b, X), X.get_mask_op(b)); //works with masks of all 1's, fails otherwise
// 7- set_mask(a=X,val=Y,mask=-1) == Y
EXPECT_EQ(X.set_mask_op(Lconst(-1), Y), Y);
// 8- set_mask(a=X,val=Y,mask=0) == X
EXPECT_EQ(X.set_mask_op(Lconst(0), Y), X);
// 9- Since set_mask(a=X,val=-1,mask=b) == X | b
//EXPECT_EQ(X.set_mask_op(b, Lconst(-1)), X.or_op(b)); fails, set_mask neg value assertion
// 9.1- get_mask(or(X,b),c) && b bit_implies c == get_mask(set_mask(a=X,val=-1,mask=b),c) -> get_mask(-1,c) (if c>0 -> c)
auto tmp1 = ((X.or_op(b)).get_mask_op(c)).and_op(b);
EXPECT_EQ(bit_implies(tmp1, c), c);
// 10- Since set_mask(a=X,val=0,mask=b) == X & b
EXPECT_EQ(X.set_mask_op(b, Lconst(0)), X.and_op(b));
// 10.1- get_mask(and(X,b),c) && b bit_implies c == get_mask(set_mask(a=X,val=0,mask=b),c) -> get_mask(0,c) -> c
tmp1 = ((X.and_op(b)).get_mask_op(c)).and_op(b);
EXPECT_EQ(bit_implies(tmp1, c), c);
// 11- get_mask(set_mask(a=Y,val=X,mask=a),b) && a bit_implies b -> get_mask(X,b)
tmp1 = ((Y.set_mask_op(a, X)).get_mask_op(b)).and_op(a);
EXPECT_EQ(bit_implies(tmp1, b), X.get_mask_op(b));
// 12- get_mask(set_mask(a=Y,val=X,mask=a),b) && ~a bit_implies b -> get_mask(Y,b)
tmp1 = ((Y.set_mask_op(a, X)).get_mask_op(b)).and_op(a.not_op());
EXPECT_EQ(bit_implies(tmp1, b), Y.get_mask_op(b));
// 13- set_mask(a=get_mask(Y,a),val=X,mask=b) && popcount(a) < popcount(b) -> get_mask(X,b)
tmp1 = (Y.get_mask_op(a)).set_mask_op(b, X);
// 14- eq(get_mask(X,b), c) and b bit_implies c == ror(get_mask(X,b))
}
#endif
}
TEST_F(Lconst_test, debug_console) {
auto a = UInt<130>("0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); // 129 ones
auto b = UInt<130>("0x100000000000000000000000000000001"); // 1, 127 zeroes, 1 one
auto res = a+b;
std::cout << res << "\n";
}
| 37.968218
| 151
| 0.659955
|
jsg831
|
25f671b1e42af154aa02b73a0b0d06059df26724
| 8,439
|
cpp
|
C++
|
case-studies/PoDoFo/podofo/cib/podofo/doc/PdfSignOutputDevice.h.cpp
|
satya-das/cib
|
369333ea58b0530b8789a340e21096ba7d159d0e
|
[
"MIT"
] | 30
|
2018-03-05T17:35:29.000Z
|
2022-03-17T18:59:34.000Z
|
case-studies/PoDoFo/podofo/cib/podofo/doc/PdfSignOutputDevice.h.cpp
|
satya-das/cib
|
369333ea58b0530b8789a340e21096ba7d159d0e
|
[
"MIT"
] | 2
|
2016-05-26T04:47:13.000Z
|
2019-02-15T05:17:43.000Z
|
case-studies/PoDoFo/podofo/cib/podofo/doc/PdfSignOutputDevice.h.cpp
|
satya-das/cib
|
369333ea58b0530b8789a340e21096ba7d159d0e
|
[
"MIT"
] | 5
|
2019-02-15T05:09:22.000Z
|
2021-04-14T12:10:16.000Z
|
#include "podofo/base/PdfData.h"
#include "podofo/base/PdfOutputDevice.h"
#include "podofo/doc/PdfSignOutputDevice.h"
#include "__zz_cib_CibPoDoFo-class-down-cast.h"
#include "__zz_cib_CibPoDoFo-delegate-helper.h"
#include "__zz_cib_CibPoDoFo-generic.h"
#include "__zz_cib_CibPoDoFo-ids.h"
#include "__zz_cib_CibPoDoFo-type-converters.h"
#include "__zz_cib_CibPoDoFo-mtable-helper.h"
#include "__zz_cib_CibPoDoFo-proxy-mgr.h"
namespace __zz_cib_ {
using namespace ::PoDoFo;
template <>
struct __zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice> : public ::PoDoFo::PdfSignOutputDevice {
using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>;
using __zz_cib_AbiType = __zz_cib_Delegatee*;
using ::PoDoFo::PdfSignOutputDevice::PdfSignOutputDevice;
static __zz_cib_AbiType __zz_cib_decl __zz_cib_Copy_0(const __zz_cib_Delegatee* __zz_cib_obj) {
return new __zz_cib_Delegatee(*__zz_cib_obj);
}
static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_1(__zz_cib_AbiType_t<::PoDoFo::PdfOutputDevice*> pRealDevice) {
return new __zz_cib_Delegatee( __zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfOutputDevice*>(pRealDevice));
}
static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_2(__zz_cib_AbiType_t<const char*> pszFilename) {
return new __zz_cib_Delegatee( __zz_cib_::__zz_cib_FromAbiType<const char*>(pszFilename));
}
static void __zz_cib_decl __zz_cib_Delete_3(__zz_cib_Delegatee* __zz_cib_obj) {
delete __zz_cib_obj;
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetSignatureSize_4(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<size_t> lSignatureSize) {
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::SetSignatureSize(
__zz_cib_::__zz_cib_FromAbiType<size_t>(lSignatureSize)
);
}
static __zz_cib_AbiType_t<size_t> __zz_cib_decl GetSignatureSize_5(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<size_t>(
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::GetSignatureSize()
);
}
static __zz_cib_AbiType_t<const ::PoDoFo::PdfData*> __zz_cib_decl GetSignatureBeacon_6(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<const ::PoDoFo::PdfData*>(
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::GetSignatureBeacon()
);
}
static __zz_cib_AbiType_t<bool> __zz_cib_decl HasSignaturePosition_7(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<bool>(
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::HasSignaturePosition()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl AdjustByteRange_8(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::AdjustByteRange();
}
static __zz_cib_AbiType_t<size_t> __zz_cib_decl ReadForSignature_9(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<char*> pBuffer, __zz_cib_AbiType_t<size_t> lLen) {
return __zz_cib_ToAbiType<size_t>(
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::ReadForSignature(
__zz_cib_::__zz_cib_FromAbiType<char*>(pBuffer),
__zz_cib_::__zz_cib_FromAbiType<size_t>(lLen)
)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetSignature_10(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfData&> sigData) {
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::SetSignature(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfData&>(sigData)
);
}
static __zz_cib_AbiType_t<size_t> __zz_cib_decl GetLength_11(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<size_t>(
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::GetLength()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Print_12(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const char*> pszFormat) {
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::Print(
__zz_cib_::__zz_cib_FromAbiType<const char*>(pszFormat)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Write_13(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const char*> pBuffer, __zz_cib_AbiType_t<size_t> lLen) {
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::Write(
__zz_cib_::__zz_cib_FromAbiType<const char*>(pBuffer),
__zz_cib_::__zz_cib_FromAbiType<size_t>(lLen)
);
}
static __zz_cib_AbiType_t<size_t> __zz_cib_decl Read_14(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<char*> pBuffer, __zz_cib_AbiType_t<size_t> lLen) {
return __zz_cib_ToAbiType<size_t>(
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::Read(
__zz_cib_::__zz_cib_FromAbiType<char*>(pBuffer),
__zz_cib_::__zz_cib_FromAbiType<size_t>(lLen)
)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Seek_15(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<size_t> offset) {
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::Seek(
__zz_cib_::__zz_cib_FromAbiType<size_t>(offset)
);
}
static __zz_cib_AbiType_t<size_t> __zz_cib_decl Tell_16(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<size_t>(
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::Tell()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Flush_17(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfSignOutputDevice::Flush();
}
static ::PoDoFo::PdfOutputDevice* __zz_cib_decl __zz_cib_CastTo__zz_cib_Class386(::PoDoFo::PdfSignOutputDevice* __zz_cib_obj) {
return __zz_cib_obj;
}
static ::PoDoFo::PdfSignOutputDevice* __zz_cib_decl __zz_cib_CastFrom__zz_cib_Class386(::PoDoFo::PdfOutputDevice* __zz_cib_obj) {
return __zz_cib_DownCast<::PoDoFo::PdfSignOutputDevice*>(__zz_cib_obj);
}
};
}
namespace __zz_cib_ {
namespace __zz_cib_Class333 {
using namespace ::PoDoFo;
namespace __zz_cib_Class471 {
const __zz_cib_MethodTable* __zz_cib_GetMethodTable() {
static const __zz_cib_MTableEntry methodArray[] = {
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::__zz_cib_Copy_0),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::__zz_cib_New_1),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::__zz_cib_New_2),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::__zz_cib_Delete_3),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::SetSignatureSize_4),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::GetSignatureSize_5),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::GetSignatureBeacon_6),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::HasSignaturePosition_7),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::AdjustByteRange_8),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::ReadForSignature_9),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::SetSignature_10),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::GetLength_11),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::Print_12),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::Write_13),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::Read_14),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::Seek_15),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::Tell_16),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::Flush_17),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::__zz_cib_CastTo__zz_cib_Class386),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfSignOutputDevice>::__zz_cib_CastFrom__zz_cib_Class386)
};
static const __zz_cib_MethodTable methodTable = { methodArray, 20 };
return &methodTable;
}
}}}
| 57.408163
| 172
| 0.792748
|
satya-das
|
25fe59ddff0adb240ab78ee57e5b7a8b7427c200
| 40,960
|
cpp
|
C++
|
src/modules/processes/PixelMath/PixelMathInterface.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
src/modules/processes/PixelMath/PixelMathInterface.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
src/modules/processes/PixelMath/PixelMathInterface.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
// ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 2.4.9
// ----------------------------------------------------------------------------
// Standard PixelMath Process Module Version 1.8.1
// ----------------------------------------------------------------------------
// PixelMathInterface.cpp - Released 2021-05-05T15:38:07Z
// ----------------------------------------------------------------------------
// This file is part of the standard PixelMath PixInsight module.
//
// Copyright (c) 2003-2021 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (https://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ----------------------------------------------------------------------------
#include "ExpressionEditorDialog.h"
#include "ImageCache.h"
#include "PixelMathInterface.h"
#include "PixelMathProcess.h"
#include <pcl/ErrorHandler.h>
#include <pcl/MessageBox.h>
#define AUTO_ID "<Auto>"
#define EDITOR_MIN_WIDTH 600
#define EDITOR_MIN_HEIGHT 150
namespace pcl
{
// ----------------------------------------------------------------------------
PixelMathInterface* ThePixelMathInterface = nullptr;
// ----------------------------------------------------------------------------
PixelMathInterface::PixelMathInterface()
: m_instance( ThePixelMathProcess )
{
ThePixelMathInterface = this;
// The auto save geometry feature is of no good to interfaces that include
// both auto-expanding controls (e.g. CodeEditor) and collapsible sections
// (e.g. SectionBar).
DisableAutoSaveGeometry();
}
// ----------------------------------------------------------------------------
PixelMathInterface::~PixelMathInterface()
{
if ( GUI != nullptr )
delete GUI, GUI = nullptr;
}
// ----------------------------------------------------------------------------
IsoString PixelMathInterface::Id() const
{
return "PixelMath";
}
// ----------------------------------------------------------------------------
MetaProcess* PixelMathInterface::Process() const
{
return ThePixelMathProcess;
}
// ----------------------------------------------------------------------------
String PixelMathInterface::IconImageSVGFile() const
{
return "@module_icons_dir/PixelMath.svg";
}
// ----------------------------------------------------------------------------
InterfaceFeatures PixelMathInterface::Features() const
{
return InterfaceFeature::Default | InterfaceFeature::ApplyGlobalButton;
}
// ----------------------------------------------------------------------------
void PixelMathInterface::ApplyInstance() const
{
const_cast<PixelMathInterface*>( this )->ExportSourceCode();
m_instance.LaunchOnCurrentView();
}
// ----------------------------------------------------------------------------
void PixelMathInterface::ApplyInstanceGlobal() const
{
const_cast<PixelMathInterface*>( this )->ExportSourceCode();
m_instance.LaunchGlobal();
}
// ----------------------------------------------------------------------------
void PixelMathInterface::ResetInstance()
{
PixelMathInstance defaultInstance( ThePixelMathProcess );
ImportProcess( defaultInstance );
}
// ----------------------------------------------------------------------------
bool PixelMathInterface::Launch( const MetaProcess& P, const ProcessImplementation*, bool& dynamic, unsigned& /*flags*/ )
{
if ( GUI == nullptr )
{
GUI = new GUIData( *this );
SetWindowTitle( "PixelMath" );
ImportSourceCode();
UpdateControls();
}
dynamic = false;
return &P == ThePixelMathProcess;
}
// ----------------------------------------------------------------------------
ProcessImplementation* PixelMathInterface::NewProcess() const
{
const_cast<PixelMathInterface*>( this )->ExportSourceCode();
return new PixelMathInstance( m_instance );
}
// ----------------------------------------------------------------------------
bool PixelMathInterface::ValidateProcess( const ProcessImplementation& p, String& whyNot ) const
{
if ( dynamic_cast<const PixelMathInstance*>( &p ) != nullptr )
return true;
whyNot = "Not a PixelMath instance.";
return false;
}
// ----------------------------------------------------------------------------
bool PixelMathInterface::RequiresInstanceValidation() const
{
return true;
}
// ----------------------------------------------------------------------------
bool PixelMathInterface::ImportProcess( const ProcessImplementation& p )
{
m_instance.Assign( p );
ImportSourceCode();
UpdateControls();
return true;
}
// ----------------------------------------------------------------------------
/*
* We use image notifications to keep the image cache consistent when images
* are modified, renamed or deleted.
*/
bool PixelMathInterface::WantsImageNotifications() const
{
return true;
}
void PixelMathInterface::ImageUpdated( const View& view )
{
if ( !TheImageCache->IsEmpty() )
if ( view.IsMainView() )
TheImageCache->InvalidateImage( view.Id() );
}
void PixelMathInterface::ImageRenamed( const View& view )
{
/*
* ### TODO - CRITICAL
*
* We should have a notification where we can know the old and new image
* identifiers in the same function call. We cannot rely on View references in
* this case because we can have nested generators, hence cached images
* generated from generated images ... and so on.
*
* We have a serious limitation here because we cannot invalidate cache items
* for renamed images. For example, suppose that I execute:
*
* generator( A )
*
* Then I rename A -> B. The cached images for A (now B) cannot be invalidated
* because they cannot be tracked by this function. Now I have a different
* image C, which I rename C -> A. The cached images for the old A (now B) will
* be used as if they had been generated for C (now A) - not nice, although
* very unlikely to happen, fortunately.
*/
// if ( !TheImageCache->IsEmpty() )
// if ( view.IsMainView() )
// TheImageCache->InvalidateImage( view.Id() );
}
void PixelMathInterface::ImageDeleted( const View& view )
{
if ( !TheImageCache->IsEmpty() )
if ( view.IsMainView() )
TheImageCache->InvalidateImage( view.Id() );
}
// ----------------------------------------------------------------------------
void PixelMathInterface::UpdateControls()
{
if ( m_instance.p_useSingleExpression )
{
if ( GUI->Editors_TabBox.CurrentPageIndex() == 1 || GUI->Editors_TabBox.CurrentPageIndex() == 2 )
GUI->Editors_TabBox.SetCurrentPageIndex( 0 );
GUI->Editors_TabBox.SetPageLabel( 0, "RGB/K" );
GUI->Editors_TabBox.SetPageIcon( 0, ScaledResource( ":/toolbar/image-display-rgb.png" ) );
GUI->Editors_TabBox.DisablePage( 1 );
GUI->Editors_TabBox.DisablePage( 2 );
}
else
{
GUI->Editors_TabBox.SetPageLabel( 0, "R/K" );
GUI->Editors_TabBox.SetPageIcon( 0, ScaledResource( ":/toolbar/image-display-red.png" ) );
GUI->Editors_TabBox.EnablePage( 1 );
GUI->Editors_TabBox.EnablePage( 2 );
}
GUI->UseSingleExpression_CheckBox.SetChecked( m_instance.p_useSingleExpression );
GUI->GenerateOutput_CheckBox.SetChecked( m_instance.p_generateOutput );
GUI->CacheGeneratedImages_CheckBox.SetChecked( m_instance.p_cacheGeneratedImages );
GUI->SingleThreaded_CheckBox.SetChecked( m_instance.p_singleThreaded );
GUI->Optimization_CheckBox.SetChecked( m_instance.p_optimization );
GUI->Use64BitWorkingImage_CheckBox.Enable( m_instance.p_generateOutput );
GUI->Use64BitWorkingImage_CheckBox.SetChecked( m_instance.p_use64BitWorkingImage );
GUI->Rescale_CheckBox.Enable( m_instance.p_generateOutput );
GUI->Rescale_CheckBox.SetChecked( m_instance.p_rescaleResult );
GUI->RescaleLower_NumericEdit.Enable( m_instance.p_generateOutput && m_instance.p_rescaleResult );
GUI->RescaleLower_NumericEdit.SetValue( m_instance.p_rescaleLower );
GUI->RescaleUpper_NumericEdit.Enable( m_instance.p_generateOutput && m_instance.p_rescaleResult );
GUI->RescaleUpper_NumericEdit.SetValue( m_instance.p_rescaleUpper );
GUI->ReplaceTarget_RadioButton.Enable( m_instance.p_generateOutput );
GUI->ReplaceTarget_RadioButton.SetChecked( !m_instance.p_createNewImage );
GUI->CreateNewImage_RadioButton.Enable( m_instance.p_generateOutput );
GUI->CreateNewImage_RadioButton.SetChecked( m_instance.p_createNewImage );
GUI->ImageId_Label.Enable( m_instance.p_generateOutput && m_instance.p_createNewImage );
GUI->ImageId_Edit.Enable( m_instance.p_generateOutput && m_instance.p_createNewImage );
GUI->ImageId_Edit.SetText( m_instance.p_newImageId.IsEmpty() ? AUTO_ID : m_instance.p_newImageId );
GUI->ImageId_Button.Enable( m_instance.p_generateOutput && m_instance.p_createNewImage );
GUI->Width_Label.Enable( m_instance.p_createNewImage );
GUI->Width_SpinBox.Enable( m_instance.p_createNewImage );
GUI->Width_SpinBox.SetValue( m_instance.p_newImageWidth );
GUI->Height_Label.Enable( m_instance.p_createNewImage );
GUI->Height_SpinBox.Enable( m_instance.p_createNewImage );
GUI->Height_SpinBox.SetValue( m_instance.p_newImageHeight );
GUI->ColorSpace_Label.Enable( m_instance.p_createNewImage );
GUI->ColorSpace_ComboBox.Enable( m_instance.p_createNewImage );
GUI->ColorSpace_ComboBox.SetCurrentItem( m_instance.p_newImageColorSpace );
GUI->CreateAlpha_CheckBox.Enable( m_instance.p_createNewImage );
GUI->CreateAlpha_CheckBox.SetChecked( m_instance.p_newImageAlpha );
GUI->SampleFormat_Label.Enable( m_instance.p_generateOutput && m_instance.p_createNewImage );
GUI->SampleFormat_ComboBox.Enable( m_instance.p_generateOutput && m_instance.p_createNewImage );
GUI->SampleFormat_ComboBox.SetCurrentItem( m_instance.p_newImageSampleFormat );
}
// ----------------------------------------------------------------------------
void PixelMathInterface::ImportSourceCode()
{
String x0 = m_instance.p_expression[0].Trimmed();
String x1 = m_instance.p_expression[1].Trimmed();
String x2 = m_instance.p_expression[2].Trimmed();
String x3 = m_instance.p_expression[3].Trimmed();
String x4 = m_instance.p_symbols.Trimmed();
if ( !x0.IsEmpty() )
x0 << '\n';
if ( !x1.IsEmpty() )
x1 << '\n';
if ( !x2.IsEmpty() )
x2 << '\n';
if ( !x3.IsEmpty() )
x3 << '\n';
if ( !x4.IsEmpty() )
x4 << '\n';
GUI->RK_CodeEditor.SetText( x0 );
GUI->G_CodeEditor.SetText( x1 );
GUI->B_CodeEditor.SetText( x2 );
GUI->A_CodeEditor.SetText( x3 );
GUI->Symbols_CodeEditor.SetText( x4 );
MakeSummary();
GUI->RK_CodeEditor.SetCursorPosition( 0, 0 );
GUI->G_CodeEditor.SetCursorPosition( 0, 0 );
GUI->B_CodeEditor.SetCursorPosition( 0, 0 );
GUI->A_CodeEditor.SetCursorPosition( 0, 0 );
GUI->Symbols_CodeEditor.SetCursorPosition( 0, 0 );
GUI->Summary_CodeEditor.SetCursorPosition( 0, 0 );
}
// ----------------------------------------------------------------------------
void PixelMathInterface::ExportSourceCode()
{
m_instance.p_expression[0] = GUI->RK_CodeEditor.Text().Trimmed();
m_instance.p_expression[1] = GUI->G_CodeEditor.Text().Trimmed();
m_instance.p_expression[2] = GUI->B_CodeEditor.Text().Trimmed();
m_instance.p_expression[3] = GUI->A_CodeEditor.Text().Trimmed();
m_instance.p_symbols = GUI->Symbols_CodeEditor.Text().Trimmed();
}
// ----------------------------------------------------------------------------
void PixelMathInterface::MakeSummary()
{
String x0 = GUI->RK_CodeEditor.Text().Trimmed();
String x1 = GUI->G_CodeEditor.Text().Trimmed();
String x2 = GUI->B_CodeEditor.Text().Trimmed();
String x3 = GUI->A_CodeEditor.Text().Trimmed();
String x4 = GUI->Symbols_CodeEditor.Text().Trimmed();
StringList textBlocks;
if ( !x0.IsEmpty() )
textBlocks << (String( m_instance.p_useSingleExpression ? "// RGB/K:" : "// R:" ) << '\n' << x0);
if ( !m_instance.p_useSingleExpression )
{
if ( !x1.IsEmpty() )
textBlocks << (String( "// G:\n" ) << x1);
if ( !x2.IsEmpty() )
textBlocks << (String( "// B:\n" ) << x2);
if ( !x3.IsEmpty() )
textBlocks << (String( "// A:\n" ) << x3);
}
if ( !x4.IsEmpty() )
textBlocks << (String( "// Symbols:\n" ) << x4);
GUI->Summary_CodeEditor.SetText( String().ToSeparated( textBlocks, "\n\n" ) << '\n' );
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_PageSelected( TabBox& sender, int pageIndex )
{
if ( pageIndex == 5 )
MakeSummary();
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_ToggleSection( SectionBar& sender, Control& section, bool start )
{
if ( start )
GUI->Editors_TabBox.SetFixedHeight();
else
{
GUI->Editors_TabBox.SetScaledMinHeight( EDITOR_MIN_HEIGHT );
GUI->Editors_TabBox.SetMaxHeight( int_max );
if ( GUI->Editors_TabBox.IsVisible() )
SetVariableHeight();
else
SetFixedHeight();
}
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_EditCompleted( Edit& sender )
{
if ( sender == GUI->ImageId_Edit )
{
try
{
String text = sender.Text().Trimmed();
if ( !text.IsEmpty() && text != AUTO_ID && !text.IsValidIdentifier() )
throw Error( "Invalid identifier: " + text );
m_instance.p_newImageId = (text != AUTO_ID) ? text : String();
text = m_instance.p_newImageId.IsEmpty() ? AUTO_ID : m_instance.p_newImageId;
sender.SetText( text );
}
ERROR_CLEANUP(
sender.SetText( m_instance.p_newImageId );
sender.SelectAll();
sender.Focus();
return;
)
}
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_EditGetFocus( Control& sender )
{
if ( sender == GUI->ImageId_Edit )
if ( GUI->ImageId_Edit.Text() == AUTO_ID )
GUI->ImageId_Edit.Clear();
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_ButtonClick( Button& sender, bool checked )
{
if ( sender == GUI->ExpressionEditor_Button )
{
static ExpressionEditorDialog* dialog = nullptr;
if ( dialog == nullptr )
dialog = new ExpressionEditorDialog;
ExportSourceCode();
if ( dialog->Execute( m_instance ) )
{
ImportSourceCode();
UpdateControls();
}
}
else if ( sender == GUI->UseSingleExpression_CheckBox )
{
m_instance.p_useSingleExpression = checked;
MakeSummary();
UpdateControls();
}
else if ( sender == GUI->Use64BitWorkingImage_CheckBox )
{
m_instance.p_use64BitWorkingImage = checked;
}
else if ( sender == GUI->GenerateOutput_CheckBox )
{
m_instance.p_generateOutput = checked;
UpdateControls();
}
else if ( sender == GUI->CacheGeneratedImages_CheckBox )
{
m_instance.p_cacheGeneratedImages = checked;
}
else if ( sender == GUI->SingleThreaded_CheckBox )
{
m_instance.p_singleThreaded = checked;
}
else if ( sender == GUI->Optimization_CheckBox )
{
m_instance.p_optimization = checked;
}
else if ( sender == GUI->Rescale_CheckBox )
{
m_instance.p_rescaleResult = checked;
UpdateControls();
}
else if ( sender == GUI->ReplaceTarget_RadioButton )
{
m_instance.p_createNewImage = false;
UpdateControls();
}
else if ( sender == GUI->CreateNewImage_RadioButton )
{
m_instance.p_createNewImage = true;
UpdateControls();
}
else if ( sender == GUI->CreateAlpha_CheckBox )
{
m_instance.p_newImageAlpha = checked;
}
else if ( sender == GUI->ImageId_Button )
{
m_instance.p_newImageId.Clear();
GUI->ImageId_Edit.SetText( AUTO_ID );
}
else if ( sender == GUI->ClearGeneratedImages_Button )
{
size_type count, size;
String text;
if ( TheImageCache->ClearImages( count, size ) )
text << String( count ) << " cached image(s) removed, "
<< File::SizeAsString( size ) << " freed up.";
else
text << "The image cache is empty.";
MessageBox( "<p style=\"white-space: pre;\">" + text + "</p>", "PixelMath",
StdIcon::Information,
StdButton::Ok ).Execute();
}
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_NumericEditValueUpdated( NumericEdit& sender, double value )
{
if ( sender == GUI->RescaleLower_NumericEdit )
m_instance.p_rescaleLower = value;
else if ( sender == GUI->RescaleUpper_NumericEdit )
m_instance.p_rescaleUpper = value;
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_SpinBoxValueUpdated( SpinBox& sender, int value )
{
if ( sender == GUI->Width_SpinBox )
m_instance.p_newImageWidth = value;
else if ( sender == GUI->Height_SpinBox )
m_instance.p_newImageHeight = value;
UpdateControls();
}
// ----------------------------------------------------------------------------
void PixelMathInterface::e_ComboBoxItemSelected( ComboBox& sender, int itemIndex )
{
if ( sender == GUI->SampleFormat_ComboBox )
m_instance.p_newImageSampleFormat = itemIndex;
else if ( sender == GUI->ColorSpace_ComboBox )
m_instance.p_newImageColorSpace = itemIndex;
}
// ----------------------------------------------------------------------------
PixelMathInterface::GUIData::GUIData( PixelMathInterface& w )
{
pcl::Font fnt = w.Font();
int labelWidth1 = fnt.Width( String( "Sample format:" ) + 'T' );
int comboWidth1 = fnt.Width( String( 'M', 25 ) );
int ui4 = w.LogicalPixelsToPhysical( 4 );
//
Expression_SectionBar.SetTitle( "Expressions" );
Expression_SectionBar.SetSection( Expression_Control );
Expression_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&PixelMathInterface::e_ToggleSection, w );
//
RK_CodeEditor.SetFilePath( "rk.pmath" ); // enable syntax highlighting, PixelMath language
RK_CodeEditor.LineNumbersControl().SetVisible( false );
RK_Sizer.Add( RK_CodeEditor.LineNumbersControl() );
RK_Sizer.Add( RK_CodeEditor );
RK_Control.SetSizer( RK_Sizer );
G_CodeEditor.SetFilePath( "g.pmath" );
G_CodeEditor.LineNumbersControl().SetVisible( false );
G_Sizer.Add( G_CodeEditor.LineNumbersControl() );
G_Sizer.Add( G_CodeEditor );
G_Control.SetSizer( G_Sizer );
B_CodeEditor.SetFilePath( "b.pmath" );
B_CodeEditor.LineNumbersControl().SetVisible( false );
B_Sizer.Add( B_CodeEditor.LineNumbersControl() );
B_Sizer.Add( B_CodeEditor );
B_Control.SetSizer( B_Sizer );
A_CodeEditor.SetFilePath( "a.pmath" );
A_CodeEditor.LineNumbersControl().SetVisible( false );
A_Sizer.Add( A_CodeEditor.LineNumbersControl() );
A_Sizer.Add( A_CodeEditor );
A_Control.SetSizer( A_Sizer );
Symbols_CodeEditor.SetFilePath( "symbols.pmath" );
Symbols_CodeEditor.LineNumbersControl().SetVisible( false );
Symbols_Sizer.Add( Symbols_CodeEditor.LineNumbersControl() );
Symbols_Sizer.Add( Symbols_CodeEditor );
Symbols_Control.SetSizer( Symbols_Sizer );
Summary_CodeEditor.SetFilePath( "summary.pmath" );
Summary_CodeEditor.SetReadOnly();
Summary_CodeEditor.LineNumbersControl().SetVisible( false );
Summary_Sizer.Add( Summary_CodeEditor.LineNumbersControl() );
Summary_Sizer.Add( Summary_CodeEditor );
Summary_Control.SetSizer( Summary_Sizer );
Editors_TabBox.SetScaledMinSize( EDITOR_MIN_WIDTH, EDITOR_MIN_HEIGHT );
Editors_TabBox.AddPage( RK_Control, "RGB/K" );
Editors_TabBox.AddPage( G_Control, "G" );
Editors_TabBox.AddPage( B_Control, "B" );
Editors_TabBox.AddPage( A_Control, "A" );
Editors_TabBox.AddPage( Symbols_Control, "Symbols" );
Editors_TabBox.AddPage( Summary_Control, "Summary" );
Editors_TabBox.SetPageIcon( 0, w.ScaledResource( ":/toolbar/image-display-red.png" ) );
Editors_TabBox.SetPageIcon( 1, w.ScaledResource( ":/toolbar/image-display-green.png" ) );
Editors_TabBox.SetPageIcon( 2, w.ScaledResource( ":/toolbar/image-display-blue.png" ) );
Editors_TabBox.SetPageIcon( 3, w.ScaledResource( ":/toolbar/image-display-alpha.png" ) );
Editors_TabBox.SetPageIcon( 4, w.ScaledResource( ":/icons/table.png" ) );
Editors_TabBox.SetPageIcon( 5, w.ScaledResource( ":/icons/document-text.png" ) );
Editors_TabBox.OnPageSelected( (TabBox::page_event_handler)&PixelMathInterface::e_PageSelected, w );
//
UseSingleExpression_CheckBox.SetText( "Use a single RGB/K expression" );
UseSingleExpression_CheckBox.SetToolTip(
"<p>Apply a single expression to the red, green and blue channels of RGB color images. "
"The same expression will also be applied to the gray channel of grayscale images.</p>" );
UseSingleExpression_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
UseSingleExpression_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
UseSingleExpression_Sizer.Add( UseSingleExpression_CheckBox );
UseSingleExpression_Sizer.AddStretch();
//
ExpressionEditor_Button.SetText( "Expression Editor" );
ExpressionEditor_Button.SetToolTip( "<p>Open the PixelMath Expression Editor dialog.</p>" );
ExpressionEditor_Button.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
ExpressionEditor_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
ExpressionEditor_Sizer.Add( ExpressionEditor_Button );
ExpressionEditor_Sizer.AddStretch();
//
Expression_Sizer.SetSpacing( 4 );
Expression_Sizer.Add( Editors_TabBox );
Expression_Sizer.Add( UseSingleExpression_Sizer );
Expression_Sizer.Add( ExpressionEditor_Sizer );
Expression_Control.SetSizer( Expression_Sizer );
//
Destination_SectionBar.SetTitle( "Destination" );
Destination_SectionBar.SetSection( Destination_Control );
Destination_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&PixelMathInterface::e_ToggleSection, w );
//
GenerateOutput_CheckBox.SetText( "Generate output" );
GenerateOutput_CheckBox.SetToolTip( "<p>When this option is selected, PixelMath expressions will be evaluated and their "
"results will generate output pixels, either in a newly created image (if the <i>create new image</i> option is selected), "
"or to replace the target image (if <i>replace target image</i> is selected). This is the normal PixelMath working mode.</p>"
"<p>If this option is disabled, PixelMath expressions will be evaluated but their results will be discarded. No output will "
"be generated, and hence PixelMath will behave as a no-op process: the target image won't be modified when the process "
"is executed in a view context, and no new image will be created as a result of global execution. This working mode is "
"useful when PixelMath is being used exclusively for evaluation of global variables as a side-effect of expression "
"evaluation.</p>" );
GenerateOutput_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
GenerateOutput_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
GenerateOutput_Sizer.Add( GenerateOutput_CheckBox );
GenerateOutput_Sizer.AddStretch();
//
CacheGeneratedImages_CheckBox.SetText( "Cache generated images" );
CacheGeneratedImages_CheckBox.SetToolTip(
"<p>Preserve generated images before and after PixelMath execution. This option is useful to speed up "
"calculations when PixelMath expressions using generators are being executed repeatedly (for example, "
"on a preview to fine tune expressions by trial/error work). Note that this uses memory resources, which "
"may become significant, especially after many executions of PixelMath expressions with varying "
"generator function parameters.</p>"
"<p>If this option is disabled, existing generated images will be destroyed before and after PixelMath "
"execution, so they'll have to be recalculated in successive executions of the same expressions.</p>" );
CacheGeneratedImages_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
CacheGeneratedImages_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
CacheGeneratedImages_Sizer.Add( CacheGeneratedImages_CheckBox );
CacheGeneratedImages_Sizer.AddStretch();
//
SingleThreaded_CheckBox.SetText( "Single threaded" );
SingleThreaded_CheckBox.SetToolTip( "<p>Enable this option to force PixelMath to use a single execution thread, irrespective of "
"current global parallel execution settings. Single-threaded execution is necessary for some applications that are "
"incompatible with multithreaded implementations. A good example is calculation of integral images. In an integral image, "
"each pixel at coordinates {x,y} is the sum of all pixels at coordinates {i <= x, j <= y} in the source image. "
"This task cannot be parallelized, and hence requires enabling this option to be implemented with PixelMath.</p>" );
SingleThreaded_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
SingleThreaded_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
SingleThreaded_Sizer.Add( SingleThreaded_CheckBox );
SingleThreaded_Sizer.AddStretch();
//
Optimization_CheckBox.SetText( "Code optimization" );
Optimization_CheckBox.SetToolTip( "<p>Enable code optimization to implement faster conditional functions and logical operators. "
"Code optimization works by minimizing execution of unnecessary subexpressions, which can lead to a significant increase in "
"the execution speed of iif() and iswitch() inline conditional functions, as well as logical operators (through short-circuit "
"evaluation), among other critical PixelMath language constructs. This option is enabled by default, and should only be "
"disabled by developers for verification and debugging purposes.</p>" );
Optimization_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
Optimization_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
Optimization_Sizer.Add( Optimization_CheckBox );
Optimization_Sizer.AddStretch();
//
Use64BitWorkingImage_CheckBox.SetText( "Use 64-bit working images" );
Use64BitWorkingImage_CheckBox.SetToolTip(
"<p>If this option is selected, PixelMath will use 64-bit floating point working images to "
"accumulate and store all intermediate results.</p>"
"<p>When this option is disabled, PixelMath uses 32-bit floating point working images.</p>" );
Use64BitWorkingImage_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
Use64BitWorkingImage_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
Use64BitWorkingImage_Sizer.Add( Use64BitWorkingImage_CheckBox );
Use64BitWorkingImage_Sizer.AddStretch();
//
Rescale_CheckBox.SetText( "Rescale result" );
Rescale_CheckBox.SetToolTip( "<p>When this option is selected, PixelMath will rescale the final resulting "
"image to the specified output range (see the <i>lower range</i> and <i>upper range</i> parameters below).</p>"
"<p>If this option is disabled (default state), the final image will be truncated, if necessary, to fit "
"in the normalized [0,1] range.</p>"
"<p>You can disable both rescaling and truncation by creating a PixelMath process icon and editing its "
"instance source code. If you set both 'rescale' and 'truncate' instance properties to false, the resulting "
"image will be left intact upon PixelMath execution termination.</p>"
"<p><b>Warning: Platform stability is not guaranteed if out-of-range pixel sample values propagate after "
"process execution.</b></p>" );
Rescale_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
Rescale_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
Rescale_Sizer.Add( Rescale_CheckBox );
Rescale_Sizer.AddStretch();
//
RescaleLower_NumericEdit.label.SetText( "Lower bound:" );
RescaleLower_NumericEdit.label.SetFixedWidth( labelWidth1 );
RescaleLower_NumericEdit.sizer.AddStretch();
RescaleLower_NumericEdit.SetReal();
RescaleLower_NumericEdit.SetRange( 0, 1 );
RescaleLower_NumericEdit.SetPrecision( Abs( ThePMRescaleLowerBoundParameter->Precision() ) );
RescaleLower_NumericEdit.SetToolTip( "<p>When the <i>rescale result</i> option is enabled, this is the lower bound "
"of the output rescaling range.</p>" );
RescaleLower_NumericEdit.OnValueUpdated( (NumericEdit::value_event_handler)&PixelMathInterface::e_NumericEditValueUpdated, w );
//
RescaleUpper_NumericEdit.label.SetText( "Upper bound:" );
RescaleUpper_NumericEdit.label.SetFixedWidth( labelWidth1 );
RescaleUpper_NumericEdit.sizer.AddStretch();
RescaleUpper_NumericEdit.SetReal();
RescaleUpper_NumericEdit.SetRange( 0, 1 );
RescaleUpper_NumericEdit.SetPrecision( Abs( ThePMRescaleUpperBoundParameter->Precision() ) );
RescaleUpper_NumericEdit.SetToolTip( "<p>When the <i>rescale result</i> option is enabled, this is the upper bound "
"of the output rescaling range.</p>" );
RescaleUpper_NumericEdit.OnValueUpdated( (NumericEdit::value_event_handler)&PixelMathInterface::e_NumericEditValueUpdated, w );
//
ReplaceTarget_RadioButton.SetText( "Replace target image" );
ReplaceTarget_RadioButton.SetToolTip( "<p>Replace the target image with the result of PixelMath execution.</p>" );
ReplaceTarget_RadioButton.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
ReplaceTarget_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
ReplaceTarget_Sizer.Add( ReplaceTarget_RadioButton );
ReplaceTarget_Sizer.AddStretch();
//
CreateNewImage_RadioButton.SetText( "Create new image" );
CreateNewImage_RadioButton.SetToolTip( "<p>Send the PixelMath result to a newly created image window.</p>"
"<p>If you select this option, the geometry, color space and data format of the output image can either be specified "
"by this PixelMath instance (see the <i>width</i>, <i>height</i>, <i>color space</i> and <i>sample format</i> "
"parameters below), or taken from the target image this PixelMath instance is executed on. In the former case, "
"PixelMath can be executed in the global context because none of its parameters depend on an existing image. In the "
"latter case, PixelMath can only be applied to an image.</p>"
"<p>When PixelMath is executed globally, the working image has all of its pixel samples initially set to zero.</p>" );
CreateNewImage_RadioButton.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
CreateNewImage_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
CreateNewImage_Sizer.Add( CreateNewImage_RadioButton );
CreateNewImage_Sizer.AddStretch();
//
ImageId_Label.SetText( "Image Id:" );
ImageId_Label.SetMinWidth( labelWidth1 );
ImageId_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
ImageId_Edit.SetToolTip( "<p>When the <i>create new image</i> option is enabled, this is the identifier of the newly "
"created output image. If it is left blank (or with its default <Auto> value), the platform will assign an automatic "
"image identifier.</p>" );
ImageId_Edit.OnGetFocus( (Control::event_handler)&PixelMathInterface::e_EditGetFocus, w );
ImageId_Edit.OnEditCompleted( (Edit::edit_event_handler)&PixelMathInterface::e_EditCompleted, w );
ImageId_Button.SetIcon( w.ScaledResource( ":/icons/clear.png" ) );
ImageId_Button.SetScaledFixedSize( 20, 20 );
ImageId_Button.SetToolTip( "<p>Clear the image identifier</p>" );
ImageId_Button.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
ImageId_Sizer.SetSpacing( 4 );
ImageId_Sizer.Add( ImageId_Label );
ImageId_Sizer.Add( ImageId_Edit, 100 );
ImageId_Sizer.Add( ImageId_Button );
//
const char* widthToolTip = "<p>Width in pixels of the output image, when the <i>create new image</i> option is selected.</p>";
Width_Label.SetText( "Image width:" );
Width_Label.SetMinWidth( labelWidth1 );
Width_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
Width_Label.SetToolTip( widthToolTip );
Width_SpinBox.SetRange( 0, int_max );
Width_SpinBox.SetMinimumValueText( "<As target>" );
Width_SpinBox.SetToolTip( widthToolTip );
Width_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&PixelMathInterface::e_SpinBoxValueUpdated, w );
Width_Sizer.SetSpacing( 4 );
Width_Sizer.Add( Width_Label );
Width_Sizer.Add( Width_SpinBox );
Width_Sizer.AddStretch();
//
const char* heightToolTip = "<p>Height in pixels of the output image, when the <i>create new image</i> option is selected.</p>";
Height_Label.SetText( "Image height:" );
Height_Label.SetMinWidth( labelWidth1 );
Height_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
Height_Label.SetToolTip( heightToolTip );
Height_SpinBox.SetRange( 0, int_max );
Height_SpinBox.SetMinimumValueText( "<As target>" );
Height_SpinBox.SetToolTip( heightToolTip );
Height_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&PixelMathInterface::e_SpinBoxValueUpdated, w );
Height_Sizer.SetSpacing( 4 );
Height_Sizer.Add( Height_Label );
Height_Sizer.Add( Height_SpinBox );
Height_Sizer.AddStretch();
//
const char* colorSpaceToolTip = "<p>Color space of the output image, when the <i>create new image</i> option is selected.</p>";
ColorSpace_Label.SetText( "Color space:" );
ColorSpace_Label.SetMinWidth( labelWidth1 );
ColorSpace_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
ColorSpace_Label.SetToolTip( colorSpaceToolTip );
ColorSpace_ComboBox.AddItem( "<Same as target>" );
ColorSpace_ComboBox.AddItem( "RGB Color" );
ColorSpace_ComboBox.AddItem( "Grayscale" );
ColorSpace_ComboBox.SetMinWidth( comboWidth1 );
ColorSpace_ComboBox.SetToolTip( colorSpaceToolTip );
ColorSpace_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&PixelMathInterface::e_ComboBoxItemSelected, w );
ColorSpace_Sizer.SetSpacing( 4 );
ColorSpace_Sizer.Add( ColorSpace_Label );
ColorSpace_Sizer.Add( ColorSpace_ComboBox );
ColorSpace_Sizer.AddStretch();
//
CreateAlpha_CheckBox.SetText( "Alpha channel" );
CreateAlpha_CheckBox.SetToolTip( "<p>Create an alpha channel in the output image, when the <i>create new image</i> option is "
"selected. This option should be enabled when an alpha channel PixelMath expression has been defined and the process is "
"being executed on the global context. Otherwise the alpha channel expression will be ignored.</p>" );
CreateAlpha_CheckBox.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
CreateAlpha_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 );
CreateAlpha_Sizer.Add( CreateAlpha_CheckBox );
CreateAlpha_Sizer.AddStretch();
//
const char* sampleFormatToolTip = "<p>Pixel sample format of the output image, when the <i>create new image</i> option is selected.</p>";
SampleFormat_Label.SetText( "Sample format:" );
SampleFormat_Label.SetMinWidth( labelWidth1 );
SampleFormat_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter );
SampleFormat_Label.SetToolTip( sampleFormatToolTip );
SampleFormat_ComboBox.AddItem( "<Same as target>" );
SampleFormat_ComboBox.AddItem( "8-bit unsigned integer" );
SampleFormat_ComboBox.AddItem( "16-bit unsigned integer" );
SampleFormat_ComboBox.AddItem( "32-bit unsigned integer" );
SampleFormat_ComboBox.AddItem( "32-bit IEEE 754 floating point" );
SampleFormat_ComboBox.AddItem( "64-bit IEEE 754 floating point" );
SampleFormat_ComboBox.SetMinWidth( comboWidth1 );
SampleFormat_ComboBox.SetToolTip( sampleFormatToolTip );
SampleFormat_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&PixelMathInterface::e_ComboBoxItemSelected, w );
SampleFormat_Sizer.SetSpacing( 4 );
SampleFormat_Sizer.Add( SampleFormat_Label );
SampleFormat_Sizer.Add( SampleFormat_ComboBox );
SampleFormat_Sizer.AddStretch();
//
DestinationLeft_Sizer.SetSpacing( 4 );
DestinationLeft_Sizer.Add( GenerateOutput_Sizer );
DestinationLeft_Sizer.Add( CacheGeneratedImages_Sizer );
DestinationLeft_Sizer.Add( SingleThreaded_Sizer );
DestinationLeft_Sizer.Add( Optimization_Sizer );
DestinationLeft_Sizer.Add( Use64BitWorkingImage_Sizer );
DestinationLeft_Sizer.Add( Rescale_Sizer );
DestinationLeft_Sizer.Add( RescaleLower_NumericEdit );
DestinationLeft_Sizer.Add( RescaleUpper_NumericEdit );
DestinationLeft_Sizer.Add( ReplaceTarget_Sizer );
DestinationLeft_Sizer.Add( CreateNewImage_Sizer );
DestinationLeft_Sizer.Add( ImageId_Sizer );
DestinationLeft_Sizer.Add( Width_Sizer );
DestinationLeft_Sizer.Add( Height_Sizer );
DestinationLeft_Sizer.Add( ColorSpace_Sizer );
DestinationLeft_Sizer.Add( CreateAlpha_Sizer );
DestinationLeft_Sizer.Add( SampleFormat_Sizer );
//
ClearGeneratedImages_Button.SetText( "Clear Image Cache" );
ClearGeneratedImages_Button.SetToolTip( "<p>Destroy all cached images that have been created by generators "
"in previously executed PixelMath expressions.</p>" );
ClearGeneratedImages_Button.OnClick( (Button::click_event_handler)&PixelMathInterface::e_ButtonClick, w );
//
DestinationRight_Sizer.SetSpacing( 4 );
DestinationRight_Sizer.Add( ClearGeneratedImages_Button );
DestinationRight_Sizer.AddStretch();
//
Destination_Sizer.SetSpacing( 16 );
Destination_Sizer.Add( DestinationLeft_Sizer, 100 );
Destination_Sizer.Add( DestinationRight_Sizer );
Destination_Control.SetSizer( Destination_Sizer );
//
Global_Sizer.SetMargin( 8 );
Global_Sizer.SetSpacing( 8 );
Global_Sizer.Add( Expression_SectionBar );
Global_Sizer.Add( Expression_Control, 100 );
Global_Sizer.Add( Destination_SectionBar );
Global_Sizer.Add( Destination_Control );
w.SetSizer( Global_Sizer );
Destination_Control.Hide();
w.EnsureLayoutUpdated();
w.AdjustToContents();
w.SetMinSize();
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF PixelMathInterface.cpp - Released 2021-05-05T15:38:07Z
| 40.394477
| 140
| 0.679858
|
fmeschia
|
d30093b03fff2c442567370546d8f79044540cd9
| 10,991
|
cpp
|
C++
|
impl/gamelib/level.cpp
|
runvs/Alakajam14
|
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
|
[
"CC0-1.0"
] | null | null | null |
impl/gamelib/level.cpp
|
runvs/Alakajam14
|
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
|
[
"CC0-1.0"
] | null | null | null |
impl/gamelib/level.cpp
|
runvs/Alakajam14
|
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
|
[
"CC0-1.0"
] | null | null | null |
#include "level.hpp"
#include "dialog/dialog_serializer.hpp"
#include "enemies/enemy_serialization.hpp"
#include "game_interface.hpp"
#include "game_properties.hpp"
#include "guile.hpp"
#include "nlohmann.hpp"
#include "pathfinder/pathfinder.hpp"
#include "strutils.hpp"
#include "tilemap/node_layer.hpp"
#include "tilemap/tile_layer.hpp"
#include "tilemap/tile_node.hpp"
#include "tilemap/tileson_loader.hpp"
Level::Level(std::string const& fileName)
: m_fileName { fileName }
{
}
void Level::doCreate()
{
jt::tilemap::TilesonLoader loader { m_fileName };
m_tileLayerGround1 = std::make_shared<jt::tilemap::TileLayer>(
loader.loadTilesFromLayer("ground1", getGame()->gfx().textureManager()));
m_tileLayerGround1->setScreenSizeHint(jt::Vector2f { 400, 300 });
m_tileLayerOverlay = std::make_shared<jt::tilemap::TileLayer>(
loader.loadTilesFromLayer("overlay", getGame()->gfx().textureManager()));
m_tileLayerOverlay->setScreenSizeHint(jt::Vector2f { 400, 300 });
m_tileLayerUnderlay = std::make_shared<jt::tilemap::TileLayer>(
loader.loadTilesFromLayer("underlay", getGame()->gfx().textureManager()));
m_tileLayerUnderlay->setScreenSizeHint(jt::Vector2f { 400, 300 });
m_tileLayerUnderunderlay = std::make_shared<jt::tilemap::TileLayer>(
loader.loadTilesFromLayer("underunderlay", getGame()->gfx().textureManager()));
m_tileLayerUnderunderlay->setScreenSizeHint(jt::Vector2f { 400, 300 });
m_tileLayerOveroverlay = std::make_shared<jt::tilemap::TileLayer>(
loader.loadTilesFromLayer("overoverlay", getGame()->gfx().textureManager()));
m_tileLayerOveroverlay->setScreenSizeHint(jt::Vector2f { 400, 300 });
m_nodeLayer = std::make_shared<jt::tilemap::NodeLayer>(
loader.loadNodesFromLayer("ground1", getGame()->gfx().textureManager()));
m_tileCollisions = loader.loadCollisionsFromLayer("ground1");
auto const levelColliderCountInitial = m_tileCollisions.getRects().size();
m_tileCollisions.refineColliders(16.0f);
auto const levelColliderCountOptimized = m_tileCollisions.getRects().size();
getGame()->logger().debug(
"Level colliders initial: " + std::to_string(levelColliderCountInitial)
+ " and optimized: " + std::to_string(levelColliderCountOptimized),
{ "level" });
m_objects = loader.loadObjectsFromLayer("objects");
loadObjectPositions(m_objects);
}
void Level::loadObjectPositions(std::vector<jt::tilemap::InfoRect>& objects)
{
for (auto const& o : objects) {
if (o.name == "player_spawn") {
m_playerSpawn = o.position;
} else if (o.type == "stairs") {
m_stairsPosition = o.position;
} else if (o.type == "key") {
m_keyPosition = o.position;
} else if (o.type == "dest") {
m_stairsDest = o.position;
}
}
}
void Level::doUpdate(float elapsed)
{
m_tileLayerUnderlay->update(elapsed);
m_tileLayerUnderunderlay->update(elapsed);
m_tileLayerGround1->update(elapsed);
m_tileLayerOverlay->update(elapsed);
m_tileLayerOveroverlay->update(elapsed);
}
void Level::drawLowerLayers()
{
m_tileLayerUnderunderlay->draw(getGame()->gfx().target());
m_tileLayerUnderlay->draw(getGame()->gfx().target());
m_tileLayerGround1->draw(getGame()->gfx().target());
m_tileLayerOverlay->draw(getGame()->gfx().target());
}
void Level::drawUpperLayers() { m_tileLayerOveroverlay->draw(getGame()->gfx().target()); }
std::shared_ptr<jt::pathfinder::NodeInterface> Level::getTileAtPosition(
jt::Vector2f const& actorPosInFloat)
{
m_nodeLayer->reset();
auto const actorPosInInt
= jt::Vector2u { static_cast<unsigned int>(actorPosInFloat.x / GP::TileSizeInPixel()),
static_cast<unsigned int>(actorPosInFloat.y / GP::TileSizeInPixel()) };
return m_nodeLayer->getTileAt(actorPosInInt)->getNode();
}
void Level::drawTileNodeOverlay()
{
for (auto const& t : m_nodeLayer->getAllTiles()) {
if (t->getBlocked()) {
continue;
}
t->getDrawable()->draw(getGame()->gfx().target());
}
}
void Level::updateTileNodes(float const elapsed)
{
for (auto const& t : m_nodeLayer->getAllTiles()) {
t->getDrawable()->update(elapsed);
}
}
jt::Vector2f Level::getPlayerSpawn() const { return m_playerSpawn; }
std::vector<jt::tilemap::InfoRect> Level::getInfoRects() { return m_objects; }
std::vector<jt::tilemap::InfoRect> Level::getGuilesInfo()
{
std::vector<jt::tilemap::InfoRect> guileInfo;
for (auto const& o : m_objects) {
if (o.type == "guile") {
guileInfo.push_back(o);
}
}
return guileInfo;
}
std::vector<jt::tilemap::InfoRect> Level::getEnemiesInfo()
{
std::vector<jt::tilemap::InfoRect> enemiesInfo;
for (auto const& o : m_objects) {
if (strutil::contains(o.name, "enemy")) {
enemiesInfo.push_back(o);
}
}
return enemiesInfo;
}
std::vector<jt::tilemap::InfoRect> Level::getLootInfo()
{
std::vector<jt::tilemap::InfoRect> lootInfo;
for (auto const& o : m_objects) {
if (strutil::contains(o.name, "loot")) {
lootInfo.push_back(o);
}
}
return lootInfo;
}
jt::Vector2f Level::getKeysPosition() const { return m_keyPosition; }
jt::Vector2f Level::getStairsPosition() const { return m_stairsPosition; }
jt::Vector2f Level::getDestPosition() const { return m_stairsDest; }
std::vector<std::shared_ptr<jt::pathfinder::NodeInterface>> Level::calculatePath(
jt::Vector2f const& startPos, jt::Vector2f const& endPos)
{
auto const tileForStart = getTileAtPosition(startPos);
auto const tileForEnd = getTileAtPosition(endPos);
return jt::pathfinder::calculatePath(tileForStart, tileForEnd);
}
std::vector<std::shared_ptr<jt::Box2DObject>> Level::createColliders(
std::shared_ptr<jt::Box2DWorldInterface> world)
{
std::vector<std::shared_ptr<jt::Box2DObject>> colliders;
b2BodyDef bodyDef;
bodyDef.fixedRotation = true;
bodyDef.type = b2_staticBody;
b2FixtureDef fixtureDef;
fixtureDef.filter.categoryBits = GP::PhysicsCollisionCategoryWalls();
fixtureDef.filter.maskBits = GP::PhysicsCollisionCategoryPlayer()
| GP::PhysicsCollisionCategoryPlayerShots() | GP::PhysicsCollisionCategoryEnemies()
| GP::PhysicsCollisionCategoryEnemyShots() | GP::PhysicsCollisionCategoryExperienceOrbs();
for (auto const& r : m_tileCollisions.getRects()) {
bodyDef.position.Set(r.left + r.width / 2.0f, r.top + r.height / 2.0f);
b2PolygonShape boxCollider {};
boxCollider.SetAsBox(r.width / 2.0f, r.height / 2.0f);
fixtureDef.shape = &boxCollider;
auto collider = std::make_shared<jt::Box2DObject>(world, &bodyDef);
collider->getB2Body()->CreateFixture(&fixtureDef);
colliders.push_back(collider);
}
return colliders;
}
b2BodyDef getEnemyDefinition(jt::Vector2f const& position)
{
b2BodyDef bodyDef;
bodyDef.fixedRotation = true;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(position.x, position.y);
bodyDef.linearDamping = 16.0f;
return bodyDef;
}
EnemyInfo loadEnemyInfoCrystalSmall()
{
std::ifstream f { "assets/enemy_crystal_small.json" };
nlohmann::json j;
f >> j;
EnemyInfo ei = j.get<EnemyInfo>();
return ei;
}
EnemyInfo loadEnemyInfoCrystalMedium()
{
std::ifstream f { "assets/enemy_crystal_medium.json" };
nlohmann::json j;
f >> j;
EnemyInfo ei = j.get<EnemyInfo>();
return ei;
}
EnemyInfo loadEnemyInfoCrystalLarge()
{
std::ifstream f { "assets/enemy_crystal_large.json" };
nlohmann::json j;
f >> j;
EnemyInfo ei = j.get<EnemyInfo>();
return ei;
}
EnemyInfo loadEnemyInfoCrystalBoss()
{
std::ifstream f { "assets/enemy_crystal_boss.json" };
nlohmann::json j;
f >> j;
EnemyInfo ei = j.get<EnemyInfo>();
return ei;
}
std::shared_ptr<Enemy> loadSingleEnemySmallCrystal(
jt::Vector2f const& position, std::shared_ptr<jt::Box2DWorldInterface> world)
{
b2BodyDef bodyDef = getEnemyDefinition(position);
return std::make_shared<Enemy>(world, &bodyDef, loadEnemyInfoCrystalSmall());
}
std::shared_ptr<Enemy> loadSingleEnemyMediumCrystal(
jt::Vector2f const& position, std::shared_ptr<jt::Box2DWorldInterface> world)
{
b2BodyDef bodyDef = getEnemyDefinition(position);
return std::make_shared<Enemy>(world, &bodyDef, loadEnemyInfoCrystalMedium());
}
std::shared_ptr<Enemy> loadSingleEnemyLargeCrystal(
jt::Vector2f const& position, std::shared_ptr<jt::Box2DWorldInterface> world)
{
b2BodyDef bodyDef = getEnemyDefinition(position);
return std::make_shared<Enemy>(world, &bodyDef, loadEnemyInfoCrystalLarge());
}
std::shared_ptr<Enemy> loadSingleEnemyBoss(
jt::Vector2f const& position, std::shared_ptr<jt::Box2DWorldInterface> world)
{
b2BodyDef bodyDef = getEnemyDefinition(position);
return std::make_shared<Enemy>(world, &bodyDef, loadEnemyInfoCrystalBoss());
}
std::shared_ptr<Enemy> loadSingleEnemy(
jt::tilemap::InfoRect const& info, std::shared_ptr<jt::Box2DWorldInterface> world)
{
auto const position = info.position;
auto const type = info.properties.strings.at("enemyType");
if (type == "crystal_small") {
return loadSingleEnemySmallCrystal(position, world);
}
if (type == "crystal_medium") {
return loadSingleEnemyMediumCrystal(position, world);
}
if (type == "crystal_large") {
return loadSingleEnemyLargeCrystal(position, world);
}
if (type == "boss") {
return loadSingleEnemyBoss(position, world);
}
throw std::invalid_argument { "Enemy type " + type + " not supported" };
}
std::vector<std::shared_ptr<Enemy>> Level::createEnemies(
std::shared_ptr<jt::Box2DWorldInterface> world)
{
std::vector<std::shared_ptr<Enemy>> enemies {};
for (auto const& enemyInfo : getEnemiesInfo()) {
enemies.emplace_back(loadSingleEnemy(enemyInfo, world));
}
return enemies;
}
std::shared_ptr<Guile> loadSingleGuile(
std::shared_ptr<jt::Box2DWorldInterface> world, std::weak_ptr<TargetInterface> target)
{
b2BodyDef bodyDef;
bodyDef.fixedRotation = true;
bodyDef.type = b2_kinematicBody;
return std::make_shared<Guile>(world, &bodyDef, target);
}
DialogInfo loadDialog(std::string const& fileName)
{
std::ifstream f { fileName };
nlohmann::json j;
f >> j;
return j.get<DialogInfo>();
}
std::vector<std::shared_ptr<Guile>> Level::createGuiles(
std::shared_ptr<jt::Box2DWorldInterface> world, std::weak_ptr<TargetInterface> target)
{
std::vector<std::shared_ptr<Guile>> guiles;
for (auto const& guileInfo : getGuilesInfo()) {
auto guile = loadSingleGuile(world, target);
guile->setPosition(guileInfo.position);
guile->setDialog(loadDialog(guileInfo.properties.strings.at("dialog")));
guiles.push_back(guile);
}
return guiles;
}
| 33.714724
| 98
| 0.689564
|
runvs
|
d3034982b3ad966046d0cf3dfc55ca84f55a7413
| 874
|
cpp
|
C++
|
Codeforces/1005A_Tanya and Stairways.cpp
|
lieahau/Online-Judge-Solution
|
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
|
[
"MIT"
] | 1
|
2020-04-13T11:12:19.000Z
|
2020-04-13T11:12:19.000Z
|
Codeforces/1005A_Tanya and Stairways.cpp
|
lieahau/Online-Judge-Solution
|
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
|
[
"MIT"
] | null | null | null |
Codeforces/1005A_Tanya and Stairways.cpp
|
lieahau/Online-Judge-Solution
|
26d81d1783cbdd9294455f00b77fb3dbaedd0c01
|
[
"MIT"
] | null | null | null |
/*
People who don't work hard
don't have the right
to be envious of the people with talent.
People fail because
they don't understand
the hard work necessary to be successful.
*/
#include <bits/stdc++.h>
using namespace std;
int n, arr[1007], total;
vector<int> ans;
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &arr[i]);
if(arr[i] == 1) total++;
}
if(total == 1)
ans.push_back(arr[n-1]);
else
{
for(int i = 1; i < n; i++)
{
if(arr[i] == 1)
ans.push_back(arr[i-1]);
}
ans.push_back(arr[n-1]);
}
printf("%d\n", total);
for(int i = 0; i < total; i++)
{
if(i) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
return 0;
}
| 18.595745
| 46
| 0.44508
|
lieahau
|
d305fcafcaf30719fa92302b617b05d4bd433503
| 2,620
|
hpp
|
C++
|
hpx/util/logging/detail/raw_doc/namespace_concepts.hpp
|
Titzi90/hpx
|
150fb0de1cfe40c26a722918097199147957b45c
|
[
"BSL-1.0"
] | null | null | null |
hpx/util/logging/detail/raw_doc/namespace_concepts.hpp
|
Titzi90/hpx
|
150fb0de1cfe40c26a722918097199147957b45c
|
[
"BSL-1.0"
] | null | null | null |
hpx/util/logging/detail/raw_doc/namespace_concepts.hpp
|
Titzi90/hpx
|
150fb0de1cfe40c26a722918097199147957b45c
|
[
"BSL-1.0"
] | null | null | null |
// Boost Logging library
//
// Author: John Torjo, www.torjo.com
//
// Copyright (C) 2007 John Torjo (see www.torjo.com for email)
//
// 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)
//
// See http://www.boost.org for updates, documentation, and revision history.
// See http://www.torjo.com/log2/ for more details
namespace hpx { namespace util { namespace logging {
/**
@page namespace_concepts Concepts as namespaces
- @ref namespace_general
- @ref namespace_process
- @ref namespace_manipulator
- @ref namespace_write
This library uses a few concepts.
Take filter, for instance. It's a very simple concept - it tells you if "it's enabled".
Each concept can be implemented in several ways. To make it easier for you, <b>each concept is a namespace</b>.
In the given namespace, you'll find possible implementations of that concept. Of course, to those implementations, you can add your own ;)
\n\n
@section namespace_general General concepts
- filter - available filter implementations
- level - in case you want to use Log Levels
- writer - %writer objects; they do the actual write of the message
- scenario - in case you want to easily specify the logger and filter class(es), based on your application's needs
\n\n
@section namespace_process Logging (Processing) the message
(for more info, see logger class)
- gather - gathering the message
- writer - %writer objects; they do the actual write of the message
- gather::ostream_like - (related to gathering the message) allows gathering the message using the cool operator<< (@ref workflow_2a)
\n\n
@section namespace_manipulator Manipulator concepts
- manipulator - what a manipulator is: a formatter or a destination
- formatter - available formatters
- destination - available destinations
- tag - available tags
- formatter::tag - available tag formatters
\n\n
@section namespace_write Writing concepts
- format_and_write - contains the logic for formatting and writing to destinations
- msg_route - contains the logic for routing the message to the formatters and destinations
- op_equal - implements operator==, in order to compare formatters and/or destinations. Useful when you want to
erase formatters/destinations from a logger.
- optimize - (related to gathering the message) optimizes holding the message, as it's formatted. Formatting can modify the message.
Implementations from this namespace allow optimizing the medium so that modifying the message is as fast as possible
*/
}}}
| 38.529412
| 138
| 0.758397
|
Titzi90
|
d309e838dfc29a7bcf2726c9b022b3a176384e5e
| 1,058
|
cpp
|
C++
|
Mesh.cpp
|
refik-karic/ZSharp
|
643d4d7603e91d5b9150bf8ddfed8b1eab930b92
|
[
"MIT"
] | null | null | null |
Mesh.cpp
|
refik-karic/ZSharp
|
643d4d7603e91d5b9150bf8ddfed8b1eab930b92
|
[
"MIT"
] | null | null | null |
Mesh.cpp
|
refik-karic/ZSharp
|
643d4d7603e91d5b9150bf8ddfed8b1eab930b92
|
[
"MIT"
] | null | null | null |
#include "Mesh.h"
#include "UtilMath.h"
#include <cstring>
namespace ZSharp {
Mesh::Mesh() {
}
Mesh::Mesh(size_t numVerts, size_t stride, size_t numTriangleFaces) :
mStride(stride) {
mVertTable.Resize(numVerts);
mTriangleFaceTable.Resize(numTriangleFaces);
}
Mesh::Mesh(const Mesh& copy) {
*this = copy;
}
void Mesh::Resize(size_t vertexLength, size_t stride, size_t faceTableLength) {
mVertTable.Resize(vertexLength);
mTriangleFaceTable.Resize(faceTableLength);
mStride = stride;
}
void Mesh::SetData(const float* vertData, size_t index, size_t numVerts) {
memcpy(mVertTable.GetData() + index, vertData, numVerts);
}
void Mesh::SetTriangle(const Triangle& triangle, size_t index) {
mTriangleFaceTable[index] = triangle;
}
Array<float>& Mesh::GetVertTable() {
return mVertTable;
}
const Array<float>& Mesh::GetVertTable() const {
return mVertTable;
}
Array<Triangle>& Mesh::GetTriangleFaceTable() {
return mTriangleFaceTable;
}
const Array<Triangle>& Mesh::GetTriangleFaceTable() const {
return mTriangleFaceTable;
}
}
| 20.346154
| 79
| 0.73913
|
refik-karic
|
d30f89346ef520782d61df00a575e065f5245433
| 708
|
hpp
|
C++
|
lib/libcpp/Solvers/Solvers/model.hpp
|
beckerrh/simfemsrc
|
d857eb6f6f8627412d4f9d89a871834c756537db
|
[
"MIT"
] | null | null | null |
lib/libcpp/Solvers/Solvers/model.hpp
|
beckerrh/simfemsrc
|
d857eb6f6f8627412d4f9d89a871834c756537db
|
[
"MIT"
] | 1
|
2019-01-31T10:59:11.000Z
|
2019-01-31T10:59:11.000Z
|
lib/libcpp/Solvers/Solvers/model.hpp
|
beckerrh/simfemsrc
|
d857eb6f6f8627412d4f9d89a871834c756537db
|
[
"MIT"
] | null | null | null |
#ifndef __Solvers_Model_hpp
#define __Solvers_Model_hpp
#include "modelinterface.hpp"
/*--------------------------------------------------------------------------*/
namespace solvers
{
class Model : public ModelInterface
{
protected:
public:
~Model();
Model();
Model( const Model& model);
Model& operator=( const Model& model);
std::string getClassName() const;
std::string getInfo() const;
// void residualCell(solvers::PdePartData::vec& floc, const solvers::FemDatas& fems)const;
// void matrixCell(solvers::PdePartData::mat& mat, const solvers::FemDatas& fems)const;
};
}
/*--------------------------------------------------------------------------*/
#endif
| 26.222222
| 94
| 0.539548
|
beckerrh
|
d312f66bffa4fdefcc24ceff1d7ef11d29d6b6c5
| 3,363
|
cpp
|
C++
|
Photon Engine/Model.cpp
|
DeryabinIvan/Photon-Engine
|
b256486b4a6d92a5dce49b07e53c318b89aa3e71
|
[
"MIT"
] | 1
|
2018-07-06T12:30:33.000Z
|
2018-07-06T12:30:33.000Z
|
Photon Engine/Model.cpp
|
DeryabinIvan/Photon-Engine
|
b256486b4a6d92a5dce49b07e53c318b89aa3e71
|
[
"MIT"
] | 3
|
2021-06-17T18:08:26.000Z
|
2021-09-07T07:48:15.000Z
|
Photon Engine/Model.cpp
|
DeryabinIvan/Photon-Engine
|
b256486b4a6d92a5dce49b07e53c318b89aa3e71
|
[
"MIT"
] | null | null | null |
#include "Model.h"
#include "GLEW/glew.h"
#include "GLM/glm.hpp"
#include "GLM/gtc/matrix_transform.hpp"
namespace ph_engine {
Model::Model(){
}
Model::~Model(){
//TODO: AssImp unload
}
void Model::draw(ShaderProgram& program) {
for (int i = 0; i < meshes.size(); i++)
meshes[i].draw(program);
}
void Model::loadModel(string path) {
Assimp::Importer import;
const aiScene* scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals);
if (!scene || scene->mFlags&AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cerr << "Model load error: " << import.GetErrorString() << std::endl;
return;
}
dir = path.substr(0, path.find_last_of('/'));
processNode(scene->mRootNode, scene);
#ifdef _DEBUG
std::cout << "Loaded textures:" << std::endl;
for (unsigned int j = 0; j < textures_loaded.size(); j++) {
std::cout << textures_loaded[j] << std::endl;
}
#endif
}
void Model::processNode(aiNode* node, const aiScene* scene) {
for (unsigned int i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
Mesh current = processMesh(mesh, scene);
if (mesh->mMaterialIndex) {
aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
string diffusePath, specularPath;
diffusePath = getTexturePath(material, aiTextureType_DIFFUSE);
specularPath = getTexturePath(material, aiTextureType_SPECULAR);
//meshes.back().loadTextures(diffusePath, specularPath);
current.loadTexture(Texture::TEXTURE_TYPE::DIFFUSE, diffusePath, 0);
current.loadTexture(Texture::TEXTURE_TYPE::SPECULAR, specularPath, 1);
}
meshes.push_back(current);
}
for (unsigned int i = 0; i < node->mNumChildren; i++)
processNode(node->mChildren[i], scene);
}
Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene) {
vector<Mesh::Vertex> verticies;
vector<int> indices;
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
Mesh::Vertex vertex;
glm::vec3 tmp;
tmp.x = mesh->mVertices[i].x;
tmp.y = mesh->mVertices[i].y;
tmp.z = mesh->mVertices[i].z;
vertex.position = tmp;
tmp.x = mesh->mNormals[i].x;
tmp.y = mesh->mNormals[i].y;
tmp.z = mesh->mNormals[i].z;
vertex.normal = tmp;
if (mesh->mTextureCoords[0]) {
glm::vec2 vec;
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.texCoord = vec;
} else {
vertex.texCoord = glm::vec2(0.f);
}
verticies.push_back(vertex);
}
for (unsigned int i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
return Mesh(verticies, indices);
}
string Model::getTexturePath(aiMaterial* mat, aiTextureType type) {
aiString path;
mat->GetTexture(type, 0, &path);
bool skip = false;
for (unsigned int j = 0; j < textures_loaded.size(); j++) {
if (std::strcmp(textures_loaded[j].c_str(), path.C_Str()) == 0) {
skip = true;
break;
}
}
if (!skip && path.length) {
string texturepath = dir + '/' + path.C_Str();
textures_loaded.push_back(texturepath);
return texturepath;
}
return string();
}
}
| 27.120968
| 114
| 0.626524
|
DeryabinIvan
|
d3190296515cab5c7d33357ca523486066171216
| 140
|
cpp
|
C++
|
inputs/condition.cpp
|
sparklingyo/compilers-final-project
|
2538756af945750f552529856a22623716b13d44
|
[
"MIT"
] | null | null | null |
inputs/condition.cpp
|
sparklingyo/compilers-final-project
|
2538756af945750f552529856a22623716b13d44
|
[
"MIT"
] | null | null | null |
inputs/condition.cpp
|
sparklingyo/compilers-final-project
|
2538756af945750f552529856a22623716b13d44
|
[
"MIT"
] | 2
|
2019-12-15T00:17:07.000Z
|
2020-08-14T19:35:12.000Z
|
int main(){
int a = 1;
int b = 2;
int c;
if (b > a) {
c = b;
}
else {
c = a;
}
return c;
}
| 10
| 16
| 0.285714
|
sparklingyo
|
d31b24145fe86a102e259aae1e9cb57bd9505097
| 558
|
cpp
|
C++
|
src/NovelRT/Experimental/Graphics/GraphicsPipelineResource.cpp
|
Exadon/NovelRT
|
82000a25fd53157b26a6e6d6c71cbee0ebaa241b
|
[
"MIT"
] | 167
|
2019-02-12T14:12:04.000Z
|
2022-03-25T17:14:24.000Z
|
src/NovelRT/Experimental/Graphics/GraphicsPipelineResource.cpp
|
BanalityOfSeeking/NovelRT
|
bbbe54f719acdc2fcee4604ee90fb43ff975aee9
|
[
"MIT"
] | 270
|
2019-02-14T20:33:05.000Z
|
2022-03-08T02:28:20.000Z
|
src/NovelRT/Experimental/Graphics/GraphicsPipelineResource.cpp
|
BanalityOfSeeking/NovelRT
|
bbbe54f719acdc2fcee4604ee90fb43ff975aee9
|
[
"MIT"
] | 56
|
2019-08-22T15:57:00.000Z
|
2022-03-03T19:52:18.000Z
|
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root
// for more information.
#include <NovelRT/Experimental/Graphics/Graphics.h>
namespace NovelRT::Experimental::Graphics
{
GraphicsPipelineResourceKind Graphics::GraphicsPipelineResource::GetKind() const noexcept
{
return _kind;
}
ShaderProgramVisibility GraphicsPipelineResource::GetShaderProgramVisibility() const noexcept
{
return _visibility;
}
} // namespace NovelRT::Experimental::Graphics
| 29.368421
| 119
| 0.752688
|
Exadon
|
d31b38df9d8fbd911dabf899e296e3fab6878048
| 426
|
cpp
|
C++
|
RiverAttack/Drawer.cpp
|
leonardola/RiverAttack
|
511e8e8888b0fd96fa26a01289bd811a39dc5a8b
|
[
"MIT"
] | null | null | null |
RiverAttack/Drawer.cpp
|
leonardola/RiverAttack
|
511e8e8888b0fd96fa26a01289bd811a39dc5a8b
|
[
"MIT"
] | null | null | null |
RiverAttack/Drawer.cpp
|
leonardola/RiverAttack
|
511e8e8888b0fd96fa26a01289bd811a39dc5a8b
|
[
"MIT"
] | null | null | null |
#include "Drawer.h"
Drawer::Drawer(int windowHeight, int windowWidth){
this->windowHeight = windowHeight;
this->startingPosition = -windowHeight/2;
this->mapBlocks[0]->get
}
void Drawer::createBaseMap(int windowHeight, int windowWidth){
for(int i = 0; i < 10; i++){
this->mapBlocks[i] = new Blocks(windowHeight,windowWidth);
}
}
Drawer::~Drawer(void){
}
void Drawer::drawMap(int inicialPosition){
}
| 12.171429
| 62
| 0.690141
|
leonardola
|
d31c21a47cca852d64579392e987ccfc18690fb7
| 55
|
cpp
|
C++
|
modules/electron/system-part1/src/export_socket_hal.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | 1
|
2019-02-24T07:13:51.000Z
|
2019-02-24T07:13:51.000Z
|
modules/electron/system-part1/src/export_socket_hal.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | 1
|
2018-05-29T19:27:53.000Z
|
2018-05-29T19:27:53.000Z
|
modules/electron/system-part1/src/export_socket_hal.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | null | null | null |
#define DYNALIB_EXPORT
#include "hal_dynalib_socket.h"
| 18.333333
| 31
| 0.836364
|
zsoltmazlo
|
d3268f371126b8a9b4ef6bffc7bcaca84e8f82f1
| 1,162
|
cpp
|
C++
|
binary search/firstAndLastPosition.cpp
|
Gooner1886/DSA-101
|
44092e10ad39bebbf7da93e897927106d5a45ae7
|
[
"MIT"
] | 20
|
2022-01-04T19:36:14.000Z
|
2022-03-21T15:35:09.000Z
|
binary search/firstAndLastPosition.cpp
|
Gooner1886/DSA-101
|
44092e10ad39bebbf7da93e897927106d5a45ae7
|
[
"MIT"
] | null | null | null |
binary search/firstAndLastPosition.cpp
|
Gooner1886/DSA-101
|
44092e10ad39bebbf7da93e897927106d5a45ae7
|
[
"MIT"
] | null | null | null |
// Leetcode - 34 - Find First and Last Position of Element in Sorted Array
vector<int> searchRange(vector<int> &nums, int target)
{
vector<int> result(2);
result[0] = findStartIndex(nums, target);
result[1] = findEndIndex(nums, target);
return result;
}
int findStartIndex(vector<int> &nums, int target)
{
int index = -1;
int start = 0;
int end = nums.size() - 1;
while (start <= end)
{
int mid = (start + (end - start) / 2);
if (nums[mid] >= target)
{
end = mid - 1;
}
else
{
start = mid + 1;
}
if (nums[mid] == target)
{
index = mid;
}
}
return index;
}
int findEndIndex(vector<int> &nums, int target)
{
int index = -1;
int start = 0;
int end = nums.size() - 1;
while (start <= end)
{
int mid = (start + (end - start) / 2);
if (nums[mid] <= target)
{
start = mid + 1;
}
else
{
end = mid - 1;
}
if (nums[mid] == target)
{
index = mid;
}
}
return index;
}
| 20.385965
| 74
| 0.457831
|
Gooner1886
|
d330e85084822b6f1fa5573c84a797a247a3989b
| 1,223
|
cpp
|
C++
|
src/game/Asteroid.cpp
|
MuniuDev/SpaceRush
|
5a32ae5ca0ddcc3682a63ef0c0f3c534b921ce36
|
[
"MIT"
] | null | null | null |
src/game/Asteroid.cpp
|
MuniuDev/SpaceRush
|
5a32ae5ca0ddcc3682a63ef0c0f3c534b921ce36
|
[
"MIT"
] | null | null | null |
src/game/Asteroid.cpp
|
MuniuDev/SpaceRush
|
5a32ae5ca0ddcc3682a63ef0c0f3c534b921ce36
|
[
"MIT"
] | null | null | null |
#include "game/Asteroid.hpp"
#include "rendering/MeshFactory.hpp"
#include <cmath>
static const float kScale = 0.3f;
static const float kAsteroidMass = 10.0f;
Asteroid::Asteroid(const glm::vec3& pos, const glm::vec3& scale,
const glm::vec3& speed, const glm::vec3& rotSpeed) {
m_pos = pos;
m_speed = speed;
m_rotSpeed = rotSpeed;
m_scale = scale * kScale;
}
Asteroid::~Asteroid() { MeshFactory::GetInstance().OnRelease(m_mesh); }
void Asteroid::Init() {
m_mesh = MeshFactory::GetInstance().LoadMesh("res/Asteroid/", "asteroid.fbx",
true);
glm::vec3 size = m_scale * kAsteroidMass;
float mass = glm::abs(size.x * size.y * size.z);
InitPhysics(std::unique_ptr<btCollisionShape>(
new btBoxShape(btVector3(m_scale.x, m_scale.y, m_scale.z))),
ASTEROID, mass);
}
void Asteroid::Update(float dt) { PhysicsNode::Update(dt); }
void Asteroid::Draw() { m_mesh->Draw(); }
glm::mat4 Asteroid::GetTransformation() const {
glm::mat4 scale = glm::scale(glm::mat4(1.0f), m_scale);
glm::mat4 trans = glm::translate(glm::mat4(1.0f), m_pos);
glm::mat4 rot = glm::mat4_cast(m_rot);
return trans * rot * scale;
}
| 29.829268
| 79
| 0.639411
|
MuniuDev
|
d337ac107753f37fce256b12433bf43743028f81
| 53,642
|
cpp
|
C++
|
apps/hubo-ik-gui.cpp
|
mxgrey/protoHuboGUI
|
3384c5e40c544bd472199da9cd6e90e28321a77f
|
[
"BSD-2-Clause"
] | null | null | null |
apps/hubo-ik-gui.cpp
|
mxgrey/protoHuboGUI
|
3384c5e40c544bd472199da9cd6e90e28321a77f
|
[
"BSD-2-Clause"
] | null | null | null |
apps/hubo-ik-gui.cpp
|
mxgrey/protoHuboGUI
|
3384c5e40c544bd472199da9cd6e90e28321a77f
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <mxgrey@gatech.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include <dart/dart.h>
#include <osgDart/osgDart.h>
#include <HuboPath/Operator.hpp>
#include <osg/Timer>
using namespace dart::dynamics;
using namespace dart::simulation;
class RelaxedPosture : public dart::optimizer::Function
{
public:
RelaxedPosture(const Eigen::VectorXd& idealPosture,
const Eigen::VectorXd& lower, const Eigen::VectorXd& upper,
const Eigen::VectorXd& weights, bool enforceIdeal = false)
: enforceIdealPosture(enforceIdeal),
mIdeal(idealPosture),
mLower(lower),
mUpper(upper),
mWeights(weights)
{
int dofs = mIdeal.size();
if(mLower.size() != dofs || mWeights.size() != dofs || mUpper.size() != dofs)
{
dterr << "[RelaxedPose::RelaxedPose] Dimension mismatch:\n"
<< " ideal: " << mIdeal.size() << "\n"
<< " lower: " << mLower.size() << "\n"
<< " upper: " << mUpper.size() << "\n"
<< " weights: " << mWeights.size() << "\n";
}
mResultVector.setZero(dofs);
}
double eval(const Eigen::VectorXd& _x) override
{
computeResultVector(_x);
return 0.5 * mResultVector.dot(mResultVector);
}
void evalGradient(const Eigen::VectorXd& _x,
Eigen::Map<Eigen::VectorXd> _grad) override
{
computeResultVector(_x);
_grad.setZero();
int smaller = std::min(mResultVector.size(), _grad.size());
for(int i=0; i < smaller; ++i)
_grad[i] = mResultVector[i];
}
void computeResultVector(const Eigen::VectorXd& _x)
{
mResultVector.setZero();
if(enforceIdealPosture)
{
for(int i=0; i < _x.size(); ++i)
{
if(mIdeal.size() <= i)
break;
mResultVector[i] = mWeights[i]*(_x[i] - mIdeal[i]);
}
}
else
{
for(int i=0; i < _x.size(); ++i)
{
if(mIdeal.size() <= i)
break;
if(_x[i] < mLower[i])
mResultVector[i] = mWeights[i]*(_x[i] - mLower[i]);
else if(mUpper[i] < _x[i])
mResultVector[i] = mWeights[i]*(_x[i] - mUpper[i]);
}
}
}
bool enforceIdealPosture;
protected:
Eigen::VectorXd mResultVector;
Eigen::VectorXd mIdeal;
Eigen::VectorXd mLower;
Eigen::VectorXd mUpper;
Eigen::VectorXd mWeights;
};
static inline bool checkDist(Eigen::Vector3d& p, double a, double b)
{
double d = p.norm();
double dmax = a+b;
double dmin = fabs(a-b);
if (d > dmax)
{
p *= dmax/d;
return false;
}
else if (d < dmin)
{
p *= dmin/d;
return false;
}
else
{
return true;
}
}
static inline void clamp_sincos(double& sincos, bool& valid)
{
if (sincos < -1)
{
valid = false;
sincos = -1;
}
else if (sincos > 1)
{
valid = false;
sincos = 1;
}
}
static inline Eigen::Vector3d flipEuler3Axis(const Eigen::Vector3d& u)
{
Eigen::Vector3d v;
v[0] = u[0] - M_PI;
v[1] = M_PI - u[1];
v[2] = u[2] - M_PI;
return v;
}
/// The HuboArmIK is based on the derivation of Hubo's arm IK by Matt Zucker.
class HuboArmIK : public InverseKinematics::Analytical
{
public:
HuboArmIK(InverseKinematics* _ik, const std::string& baseLinkName)
: Analytical(_ik, "HuboArmIK_"+baseLinkName, Analytical::Properties()),
configured(false),
mBaseLinkName(baseLinkName)
{
// Do nothing
}
std::unique_ptr<dart::dynamics::InverseKinematics::GradientMethod> clone(InverseKinematics* _newIK) const override
{
return std::unique_ptr<GradientMethod>(new HuboArmIK(_newIK, mBaseLinkName));
}
const std::vector<Solution>& computeSolutions(
const Eigen::Isometry3d& _desiredBodyTf)
{
mSolutions.clear();
mSolutions.reserve(8);
if(!configured)
{
configure();
if(!configured)
{
dtwarn << "[HuboArmIK::computeSolutions] This analytical IK was not able "
<< "to configure properly, so it will not be able to compute "
<< "solutions\n";
return mSolutions;
}
}
const BodyNodePtr& base = mBaseLink.lock();
if(nullptr == base || nullptr == mWristEnd)
{
dterr << "[HuboArmIK::computeSolutions] Attempting to perform an IK on a "
<< "limb that no longer exists!\n";
assert(false);
return mSolutions;
}
const size_t SP = 0;
const size_t SR = 1;
const size_t SY = 2;
const size_t EP = 3;
const size_t WY = 4;
const size_t WP = 5;
const SkeletonPtr& skel = base->getSkeleton();
Eigen::Isometry3d B =
base->getParentBodyNode()->getWorldTransform().inverse()
* _desiredBodyTf * mWristEnd->getTransform(mIK->getNode());
Eigen::Isometry3d shoulder_from_wrist = shoulderTf.inverse() * B;
Eigen::Vector3d p = shoulder_from_wrist.inverse().translation();
const double a2 = L5*L5 + L4*L4;
const double b2 = L3*L3 + L4*L4;
const double a = sqrt(a2);
const double b = sqrt(b2);
const double alpha = atan2(L5, L4);
const double beta = atan2(L3, L4);
bool startValid = checkDist(p, a, b);
double c2 = p.dot(p);
double x = p.x();
double y = p.y();
double z = p.z();
for(size_t i = 0; i < 8; ++i)
{
const int flipEP = alterantives(i,0);
const int incWY = alterantives(i,1);
const int flipShoulder = alterantives(i,2);
Eigen::Vector6d testQ;
bool isValid = startValid;
double cosGamma = (a2 + b2 - c2) / (2*a*b);
clamp_sincos(cosGamma, isValid);
double gamma = flipEP * acos( cosGamma );
double theta3 = alpha + beta + gamma - 2*M_PI;
testQ(EP) = theta3;
double c3 = cos(theta3);
double s3 = sin(theta3);
double numer = -y;
double denom = (-L4*c3 - L3*s3 + L4);
double s2, theta2;
if(std::abs(denom) < zeroSize)
{
isValid = false;
const double& prevWY = skel->getPosition(mDofs[WY]);
theta2 = incWY ? prevWY : M_PI - prevWY;
s2 = sin(theta2);
}
else
{
s2 = numer / denom;
clamp_sincos(s2, isValid);
theta2 = incWY ? M_PI - asin(s2) : asin(s2);
}
testQ(WY) = theta2;
double c2 = cos(theta2);
double r = L4*c2 - L4*c2*c3 - L3*s3*c2;
double q = -L4*s3 + L3*c3 + L5;
double det = -(q*q + r*r);
if(std::abs(det) < zeroSize)
isValid = false;
double k = det < 0 ? -1 : 1;
double ks1 = k*( q*x - r*z );
double kc1 = k*(-r*x - q*z );
double theta1 = atan2(ks1, kc1);
testQ(WP) = theta1;
Eigen::Quaterniond Rlower =
Eigen::Quaterniond(Eigen::AngleAxisd(testQ(EP), Eigen::Vector3d::UnitY())) *
Eigen::Quaterniond(Eigen::AngleAxisd(testQ(WY), Eigen::Vector3d::UnitZ())) *
Eigen::Quaterniond(Eigen::AngleAxisd(testQ(WP), Eigen::Vector3d::UnitY()));
Eigen::Matrix3d Rupper = B.rotation() * Rlower.inverse().matrix();
Eigen::Vector3d euler = Rupper.eulerAngles(1, 0, 2);
if(flipShoulder)
euler = flipEuler3Axis(euler);
testQ(SP) = euler[0];
testQ(SR) = euler[1];
testQ(SY) = euler[2];
for(size_t j=0; j < 6; ++j)
{
testQ[j] = dart::math::wrapToPi(testQ[j]);
if(std::abs(testQ[j]) < zeroSize)
testQ[j] = 0.0;
}
int validity = isValid? VALID : OUT_OF_REACH;
mSolutions.push_back(Solution(testQ, validity));
}
checkSolutionJointLimits();
return mSolutions;
}
const std::vector<size_t>& getDofs() const override
{
if(!configured)
configure();
return mDofs;
}
const double zeroSize = 1e-8;
protected:
void configure() const
{
configured = false;
mBaseLink = mIK->getNode()->getSkeleton()->getBodyNode(mBaseLinkName);
BodyNode* base = mBaseLink.lock();
if(nullptr == base)
{
dterr << "[HuboArmIK::configure] base link is a nullptr\n";
assert(false);
return;
}
const SkeletonPtr& skel = base->getSkeleton();
const BodyNodePtr& pelvis = skel->getBodyNode("Body_TSY");
if(nullptr == pelvis)
{
dterr << "[HuboArmIK::configure] Could not find Hubo's pelvis "
<< "(Body_TSY)\n";
assert(false);
return;
}
Eigen::Vector6d saved_q;
DegreeOfFreedom* dofs[6];
BodyNode* bn = base;
for(size_t i=0; i < 6; ++i)
{
Joint* joint = bn->getParentJoint();
if(joint->getNumDofs() != 1)
{
dterr << "[HuboArmIK::configure] Invalid number of DOFs ("
<< joint->getNumDofs() << ") in the Joint [" << joint->getName()
<< "]\n";
assert(false);
return;
}
dofs[i] = joint->getDof(0);
saved_q[i] = dofs[i]->getPosition();
dofs[i]->setPosition(0.0);
bn = bn->getChildBodyNode(0);
}
BodyNode* elbow = dofs[3]->getChildBodyNode();
L3 = std::abs(elbow->getTransform(dofs[2]->getParentBodyNode()).translation()[2]);
L4 = std::abs(elbow->getTransform(dofs[3]->getParentBodyNode()).translation()[0]);
BodyNode* wrist = dofs[5]->getChildBodyNode();
Eigen::Isometry3d wrist_tf = wrist->getTransform(elbow);
L5 = std::abs(wrist_tf.translation()[2]);
shoulderTf = Eigen::Isometry3d::Identity();
shoulderTf.translate(dofs[3]->getParentBodyNode()->getTransform(pelvis)
.translation()[0] * Eigen::Vector3d::UnitX());
shoulderTf.translate(dofs[2]->getParentBodyNode()->getTransform(pelvis)
.translation()[1] * Eigen::Vector3d::UnitY());
shoulderTf.translate(dofs[2]->getParentBodyNode()->getTransform(pelvis)
.translation()[2] * Eigen::Vector3d::UnitZ());
mWristEnd = dofs[5]->getChildBodyNode();
alterantives <<
1, 1, 1,
1, 1, 0,
1, 0, 1,
1, 0, 0,
-1, 1, 1,
-1, 1, 0,
-1, 0, 1,
-1, 0, 0;
for(size_t i=0; i < 6; ++i)
{
dofs[i]->setPosition(saved_q[i]);
mDofs.push_back(dofs[i]->getIndexInSkeleton());
}
configured = true;
}
mutable bool configured;
mutable Eigen::Isometry3d shoulderTf;
mutable Eigen::Isometry3d wristTfInv;
mutable Eigen::Isometry3d mNodeOffsetTfInv;
mutable double L3, L4, L5;
mutable Eigen::Matrix<int, 8, 3> alterantives;
mutable std::vector<size_t> mDofs;
std::string mBaseLinkName;
mutable WeakBodyNodePtr mBaseLink;
mutable JacobianNode* mWristEnd;
};
class HuboLegIK : public InverseKinematics::Analytical
{
public:
/// baseLink should be Body_LHY or Body_RHY
HuboLegIK(InverseKinematics* _ik, const std::string& baseLinkName)
: Analytical(_ik, "HuboLegIK_"+baseLinkName, Analytical::Properties()),
configured(false),
mBaseLinkName(baseLinkName)
{
// Do nothing
}
std::unique_ptr<GradientMethod> clone(InverseKinematics* _newIK) const override
{
return std::unique_ptr<GradientMethod>(new HuboLegIK(_newIK, mBaseLinkName));
}
const std::vector<Solution>& computeSolutions(
const Eigen::Isometry3d& _desiredBodyTf) override
{
mSolutions.clear();
mSolutions.reserve(8);
if(!configured)
{
configure();
if(!configured)
{
dtwarn << "[HuboLegIK::computeSolutions] This analytical IK was not able "
<< "to configure properly, so it will not be able to compute "
<< "solutions\n";
return mSolutions;
}
}
const BodyNodePtr& base = mBaseLink.lock();
if(nullptr == base)
{
dterr << "[HuboLegIK::computeSolutions] Attempting to perform IK on a "
<< "limb that no longer exists!\n";
assert(false);
return mSolutions;
}
double nx, ny, sx, sy, ax, ay, az, px, py, pz;
double q1, q2, q3, q4, q5, q6;
double S2, S4, S6;
double C2, C4, C5, C6;
double C45, psi, q345;
std::complex<double> radical;
std::complex<double> sqrt_radical;
Eigen::Isometry3d B, Binv;
Eigen::Vector6d testQ;
B = (base->getParentBodyNode()->getWorldTransform() * waist).inverse()
* _desiredBodyTf * footTfInv;
Binv = B.inverse();
nx = Binv(0,0); sx = Binv(0,1); ax = Binv(0,2); px = Binv(0,3);
ny = Binv(1,0); sy = Binv(1,1); ay = Binv(1,2); py = Binv(1,3);
az = Binv(2,2); pz = Binv(2,3);
for(size_t i=0; i < 8; ++i)
{
bool isValid = true;
C4 = ((px+L6)*(px+L6) - L4*L4 - L5*L5 + py*py + pz*pz)/(2*L4*L5);
radical = 1-C4*C4;
sqrt_radical = std::sqrt(radical);
if(sqrt_radical.imag() != 0)
isValid = false;
q4 = atan2(alternatives(i,0)*sqrt_radical.real(), C4);
S4 = sin(q4);
psi = atan2(S4*L4, C4*L4+L5);
radical = (px+L6)*(px+L6) + py*py;
sqrt_radical = std::sqrt(radical);
if(sqrt_radical.imag() != 0)
isValid = false;
q5 = dart::math::wrapToPi(atan2(-pz, alternatives(i,1)*sqrt_radical.real())-psi);
q6 = atan2(py, -(px+L6));
C45 = cos(q4+q5);
C5 = cos(q5);
if( C45*L4 + C5*L5 < 0 )
q6 = dart::math::wrapToPi(q6+M_PI);
S6 = sin(q6);
C6 = cos(q6);
S2 = C6*ay + S6*ax;
radical = 1-S2*S2;
sqrt_radical = std::sqrt(radical);
if(sqrt_radical.imag() != 0)
isValid = false;
q2 = atan2(S2, alternatives(i,2)*sqrt_radical.real());
q1 = atan2(C6*sy + S6*sx, C6*ny + S6*nx);
C2 = cos(q2);
if( C2 < 0 )
q1 = dart::math::wrapToPi(q1+M_PI);
q345 = atan2(-az/C2, -(C6*ax - S6*ay)/C2);
q3 = dart::math::wrapToPi(q345 - q4 - q5);
testQ[0]=q1; testQ[1]=q2; testQ[2]=q3; testQ[3]=q4; testQ[4]=q5; testQ[5]=q6;
for(int k=0; k<testQ.size(); ++k)
if( fabs(testQ[k]) < zeroSize )
testQ[k] = 0;
int validity = isValid? VALID : OUT_OF_REACH;
mSolutions.push_back(Solution(testQ, validity));
}
checkSolutionJointLimits();
return mSolutions;
}
const std::vector<size_t>& getDofs() const override
{
if(!configured)
configure();
return mDofs;
}
const double zeroSize = 1e-8;
protected:
void configure() const
{
configured = false;
mBaseLink = mIK->getNode()->getSkeleton()->getBodyNode(mBaseLinkName);
BodyNode* base = mBaseLink.lock();
if(nullptr == base)
{
dterr << "[HuboLegIK::configure] base link is a nullptr\n";
assert(false);
return;
}
const SkeletonPtr& skel = mIK->getNode()->getSkeleton();
BodyNode* pelvis = skel->getBodyNode("Body_TSY");
if(nullptr == pelvis)
{
dterr << "[HuboLegIK::configure] Could not find Hubo's pelvis "
<< "(Body_TSY)\n";
assert(false);
return;
}
Eigen::Vector6d saved_q;
DegreeOfFreedom* dofs[6];
BodyNode* bn = base;
for(size_t i=0; i < 6; ++i)
{
Joint* joint = bn->getParentJoint();
if(joint->getNumDofs() != 1)
{
dterr << "[HuboLegIK::configure] Invalid number of DOFs ("
<< joint->getNumDofs() << ") in the Joint [" << joint->getName()
<< "]\n";
assert(false);
return;
}
dofs[i] = joint->getDof(0);
saved_q[i] = dofs[i]->getPosition();
dofs[i]->setPosition(0.0);
if(bn->getNumChildBodyNodes() > 0)
bn = bn->getChildBodyNode(0);
}
L4 = std::abs(dofs[3]->getChildBodyNode()->
getRelativeTransform().translation()[2]);
L5 = std::abs(dofs[4]->getChildBodyNode()->
getRelativeTransform().translation()[2]);
// This offset will be taken care of with footTfInv
L6 = 0.0;
hipRotation = Eigen::Isometry3d::Identity();
hipRotation.rotate(Eigen::AngleAxisd(90*M_PI/180.0,
Eigen::Vector3d::UnitZ()));
waist = dofs[2]->getChildBodyNode()->getTransform(
dofs[0]->getParentBodyNode()) * hipRotation;
footTfInv = Eigen::Isometry3d::Identity();
footTfInv.rotate(Eigen::AngleAxisd(-90*M_PI/180.0,
Eigen::Vector3d::UnitY()));
footTfInv = footTfInv * mIK->getNode()->getTransform(dofs[5]->getChildBodyNode());
footTfInv = footTfInv.inverse();
alternatives <<
1, 1, 1,
1, 1, -1,
1, -1, 1,
1, -1, -1,
-1, 1, 1,
-1, 1, -1,
-1, -1, 1,
-1, -1, -1;
for(size_t i=0; i < 6; ++i)
{
dofs[i]->setPosition(saved_q[i]);
mDofs.push_back(dofs[i]->getIndexInSkeleton());
}
configured = true;
}
mutable double L4, L5, L6;
mutable Eigen::Isometry3d waist;
mutable Eigen::Isometry3d hipRotation;
mutable Eigen::Isometry3d footTfInv;
mutable Eigen::Matrix<int, 8, 3> alternatives;
mutable std::vector<size_t> mDofs;
mutable bool configured;
std::string mBaseLinkName;
mutable WeakBodyNodePtr mBaseLink;
};
class TeleoperationWorld : public osgDart::WorldNode
{
public:
enum MoveEnum_t
{
MOVE_Q = 0,
MOVE_W,
MOVE_E,
MOVE_A,
MOVE_S,
MOVE_D,
MOVE_F,
MOVE_Z,
NUM_MOVE
};
void setupClone(SkeletonPtr& cloneHubo, const Eigen::Vector4d& color)
{
cloneHubo = mHubo->clone();
for(size_t i=0; i < cloneHubo->getNumBodyNodes(); ++i)
{
BodyNode* bn = cloneHubo->getBodyNode(i);
for(size_t j=0; j < bn->getNumVisualizationShapes(); ++j)
{
ShapePtr shape = bn->getVisualizationShape(j);
bn->removeVisualizationShape(shape);
if(MeshShapePtr mesh = std::dynamic_pointer_cast<MeshShape>(shape))
{
MeshShapePtr newMesh = std::make_shared<MeshShape>(
mesh->getScale(), mesh->getMesh(), mesh->getMeshPath(), nullptr);
newMesh->setColor(color);
newMesh->setColorMode(MeshShape::SHAPE_COLOR);
bn->addVisualizationShape(newMesh);
}
}
}
cloneHubo->resetPositions();
mWorld->addSkeleton(cloneHubo);
mWorld->getConstraintSolver()->getCollisionDetector()->removeSkeleton(cloneHubo);
}
void refreshActualHubo()
{
const IndexArray& indexMap = mOperator.getIndexMap();
mOperator.update(0, false);
for(size_t j=6; j < mHubo->getNumDofs(); ++j)
{
if(indexMap[j-6] == InvalidIndex)
{
std::cout << "InvalidIndex (" << j << ") " << mHubo->getDof(j)->getName() << std::endl;
continue;
}
mActualHubo->setPosition(j, mOperator.joints[indexMap[j-6]].position);
}
JacobianNode* anchor;
JacobianNode* hook;
// Use this when Hubo is dangling from the hoist
anchor = mHubo->getBodyNode("Body_Torso");
hook = mActualHubo->getBodyNode("Body_Torso");
// TODO: Use this when Hubo is on the ground instead of dangling
// if(mHubo->getEndEffector(2)->getSupport()->isActive())
// {
// anchor = mHubo->getEndEffector("l_foot");
// hook = mActualHubo->getEndEffector("l_foot");
// }
// else
// {
// anchor = mHubo->getEndEffector("r_foot");
// hook = mActualHubo->getEndEffector("r_foot");
// }
FreeJoint* root = static_cast<FreeJoint*>(mActualHubo->getJoint(0));
Eigen::Isometry3d tf = anchor->getTransform() * root->getChildBodyNode()->getTransform(hook);
tf = root->getTransformFromParentBodyNode().inverse() * tf * root->getTransformFromParentBodyNode();
root->setPositionsStatic(FreeJoint::convertToPositions(tf));
}
void hideHubo(const SkeletonPtr& hubo, bool hide=true)
{
for(size_t i=0; i < hubo->getNumBodyNodes(); ++i)
{
BodyNode* bn = hubo->getBodyNode(i);
for(size_t j=0; j < bn->getNumVisualizationShapes(); ++j)
bn->getVisualizationShape(j)->setHidden(hide);
}
}
void toggleEndpointVisibility()
{
mViewEndpoint = !mViewEndpoint;
hideHubo(mHubo, mViewEndpoint);
if(mTrajectoryValid)
{
hideHubo(mEndpointHubo, !mViewEndpoint);
hideHubo(mFailedHubo, true);
}
else
{
hideHubo(mFailedHubo, !mViewEndpoint);
hideHubo(mEndpointHubo, true);
}
}
void resetPositions()
{
solve = false;
for(size_t i=6; i<mHubo->getNumDofs(); ++i)
{
mHubo->getDof(i)->setPosition(0.0);
}
}
void resumeSolving()
{
solve = true;
}
#define ADD_ADJACENT_PAIR( X, Y ) adjacentPairs.push_back(std::pair<std::string,std::string>( "Body_" #X , "Body_" #Y ));
void disableAdjacentPairs(const SkeletonPtr& hubo)
{
dart::collision::CollisionDetector* detector =
mWorld->getConstraintSolver()->getCollisionDetector();
std::vector<std::pair<std::string, std::string>> adjacentPairs;
ADD_ADJACENT_PAIR(LHY, LHP);
ADD_ADJACENT_PAIR(LKP, LAR);
ADD_ADJACENT_PAIR(RHY, RHP);
ADD_ADJACENT_PAIR(RKP, RAR);
ADD_ADJACENT_PAIR(LSP, LSY);
ADD_ADJACENT_PAIR(RSP, RSY);
for(size_t i=0; i < adjacentPairs.size(); ++i)
{
detector->disablePair(hubo->getBodyNode(adjacentPairs[i].first),
hubo->getBodyNode(adjacentPairs[i].second));
}
}
TeleoperationWorld(WorldPtr _world, SkeletonPtr _robot)
: osgDart::WorldNode(_world),
mHubo(_robot),
iter(0),
mOperator(0),
l_foot(_robot->getEndEffector("l_foot")),
r_foot(_robot->getEndEffector("r_foot")),
l_hand(_robot->getEndEffector("l_hand")),
r_hand(_robot->getEndEffector("r_hand"))
{
setupClone(mActualHubo, Eigen::Vector4d(0.0, 0.67, 0.66, 0.4));
setupClone(mEndpointHubo, Eigen::Vector4d(0.1, 0.1, 0.8, 0.8));
setupClone(mFailedHubo, Eigen::Vector4d(0.8, 0.1, 0.1, 0.8));
hideHubo(mEndpointHubo);
hideHubo(mFailedHubo);
mViewEndpoint = false;
disableAdjacentPairs(mHubo);
mMoveComponents.resize(NUM_MOVE, false);
mAnyMovement = false;
mAmplifyMovement = false;
mPlayTrajectory = false;
mTrajectoryStep = 0;
HuboCan::HuboDescription desc;
desc.parseFile("/opt/hubo/devices/DrcHubo.dd");
mOperator.load_description(desc);
std::vector<std::string> indexNames;
for(size_t i=6; i<mHubo->getNumDofs(); ++i)
{
DegreeOfFreedom* dof = mHubo->getDof(i);
mOperatorIndices.push_back(i);
indexNames.push_back(dof->getName());
}
mOperator.setJointIndices(indexNames);
solve = true;
mLoadedTrajectory = false;
}
void setMovement(const std::vector<bool>& moveComponents)
{
mMoveComponents = moveComponents;
mAnyMovement = false;
for(bool move : mMoveComponents)
{
if(move)
{
mAnyMovement = true;
break;
}
}
}
void playTrajectory()
{
processTrajectory();
mTrajectoryStep = 0;
if(mTrajectoryValid)
{
mPlayTrajectory = true;
}
else
{
toggleEndpointVisibility();
mPlayTrajectory = false;
}
}
void loadWaypoint()
{
mLoadedTrajectory = false;
std::string filename = "/home/grey/projects/protoHuboGUI/trajectory.dat";
std::vector<Eigen::VectorXd> raw_trajectory;
std::ifstream file;
file.open(filename);
if(file.is_open())
{
raw_trajectory.push_back(Eigen::VectorXd(mHubo->getNumDofs()));
Eigen::VectorXd& q = raw_trajectory.back();
for(size_t i=0; i < mHubo->getNumDofs(); ++i)
file >> q[i];
}
else
{
std::cerr << "Could not open file: " << filename << std::endl;
return;
}
raw_trajectory[0].head<6>() = mHubo->getPositions().head<6>();
solve = false;
mHubo->setPositions(raw_trajectory[0]);
}
void loadTrajectory()
{
mLoadedTrajectory = true;
std::string filename = "/home/grey/projects/protoHuboGUI/trajectory.dat";
std::vector<Eigen::VectorXd> raw_trajectory;
std::ifstream file;
file.open(filename);
if(file.is_open())
{
while(!file.eof())
{
raw_trajectory.push_back(Eigen::VectorXd(mHubo->getNumDofs()));
Eigen::VectorXd& q = raw_trajectory.back();
for(size_t i=0; i < mHubo->getNumDofs(); ++i)
file >> q[i];
}
// TODO: Figure out how to avoid needing this
raw_trajectory.pop_back();
}
file.close();
mOperator.setInterpolationMode(HUBO_PATH_RAW);
mOperator.clearWaypoints();
for(size_t i=0; i < raw_trajectory.size(); ++i)
{
mHubo->setPositions(raw_trajectory[i]);
mOperator.addWaypoint(mHubo->getPositions(mOperatorIndices));
}
HuboPath::Trajectory traj = mOperator.getCurrentTrajectory();
std::cout << "Loaded trajectory with " << traj.size() - 1
<< " waypoints" << std::endl;
if(!traj.check_limits())
mTrajectoryValid = false;
mTrajectory.clear();
for(size_t i=0; i < traj.size(); ++i)
{
Eigen::VectorXd q(mHubo->getNumDofs());
for(size_t j=0; j < 6; ++j)
q[j] = mHubo->getDof(j)->getPosition();
const IndexArray& indexMap = mOperator.getIndexMap();
for(size_t j=6; j < mHubo->getNumDofs(); ++j)
q[j] = traj[i].references[indexMap[j-6]];
mTrajectory.push_back(q);
}
checkTrajectoryCollisions();
mTrajectoryStep = 0;
if(mTrajectoryValid)
{
mPlayTrajectory = true;
}
else
{
toggleEndpointVisibility();
mPlayTrajectory = false;
}
}
void runTrajectory()
{
if(!mLoadedTrajectory)
processTrajectory();
if(mTrajectoryValid)
mOperator.sendNewTrajectory();
mTrajectoryStep = 0;
if(mTrajectoryValid)
{
mPlayTrajectory = true;
}
else
{
toggleEndpointVisibility();
mPlayTrajectory = false;
}
}
void checkTrajectoryCollisions()
{
Eigen::VectorXd originalPositions = mHubo->getPositions();
std::cout << "Checking for collisions" << std::endl;
mTrajectoryValid = true;
for(size_t i=0; i < mTrajectory.size(); ++i)
{
mHubo->setPositions(mTrajectory[i]);
dart::collision::CollisionDetector* detector =
mWorld->getConstraintSolver()->getCollisionDetector();
detector->detectCollision(true, true);
for(size_t k=0; k < detector->getNumContacts(); ++k)
{
const dart::collision::Contact& contact = detector->getContact(k);
if(contact.bodyNode1.lock()->getSkeleton() == mHubo
&& contact.bodyNode2.lock()->getSkeleton() == mHubo)
{
std::cerr << "Collision between '"
<< contact.bodyNode1.lock()->getName() << "' and '"
<< contact.bodyNode2.lock()->getName() << "'" << std::endl;
mTrajectoryValid = false;
}
}
if(!mTrajectoryValid)
{
std::cerr << "Trajectory invalid!" << std::endl;
if(i+1 < mTrajectory.size())
mTrajectory.erase(mTrajectory.begin()+i+1, mTrajectory.end());
break;
}
}
mHubo->setPositions(originalPositions);
if(mTrajectoryValid)
std::cout << "Trajectory is valid" << std::endl;
if(!mTrajectory.empty())
{
mEndpointHubo->setPositions(mTrajectory.back());
mFailedHubo->setPositions(mTrajectory.back());
}
}
void processTrajectory()
{
mLoadedTrajectory = false;
mOperator.setInterpolationMode(HUBO_PATH_SPLINE);
mOperator.clearWaypoints();
mOperator.addWaypoint(mHubo->getPositions(mOperatorIndices));
HuboPath::Trajectory traj = mOperator.getCurrentTrajectory();
traj.interpolate();
std::cout << "Raw traj size: " << traj.size() << std::endl;
size_t length = traj.size();
mTrajectory.clear();
for(size_t i=0; i < length; ++i)
{
Eigen::VectorXd q(mHubo->getNumDofs());
for(size_t j=0; j < 6; ++j)
q[j] = mHubo->getDof(j)->getPosition();
const IndexArray& indexMap = mOperator.getIndexMap();
for(size_t j=6; j < mHubo->getNumDofs(); ++j)
q[j] = traj[i].references[indexMap[j-6]];
mTrajectory.push_back(q);
}
checkTrajectoryCollisions();
}
void customPreRefresh() override
{
if(mPlayTrajectory)
{
refreshActualHubo();
double freq = mOperator.get_description().params.frequency;
if(0 == mTrajectoryStep)
{
std::cout << "Starting to play the trajectory ("
<< (double)(mTrajectory.size())/freq << "s)" << std::endl;
mTimer.setStartTick();
}
double time = mTimer.time_s();
mTrajectoryStep = ceil(time*freq);
if(mTrajectory.size() <= mTrajectoryStep)
{
std::cout << "finished playing trajectory" << std::endl;
mPlayTrajectory = false;
mTrajectoryStep = 0;
mHubo->setPositions(mTrajectory.back());
return;
}
mHubo->setPositions(mTrajectory[mTrajectoryStep]);
if(0 == mTrajectoryStep)
++mTrajectoryStep;
return;
}
if(mAnyMovement)
{
mLoadedTrajectory = false;
Eigen::Isometry3d old_tf = mHubo->getBodyNode(0)->getWorldTransform();
Eigen::Isometry3d new_tf = Eigen::Isometry3d::Identity();
Eigen::Vector3d forward = old_tf.linear().col(0);
forward[2] = 0.0;
if(forward.norm() > 1e-10)
forward.normalize();
else
forward.setZero();
Eigen::Vector3d left = old_tf.linear().col(1);
left[2] = 0.0;
if(left.norm() > 1e-10)
left.normalize();
else
left.setZero();
const Eigen::Vector3d& up = Eigen::Vector3d::UnitZ();
double linearStep = 0.01;
double elevationStep = 0.2*linearStep;
double rotationalStep = 2.0*M_PI/180.0;
if(mAmplifyMovement)
{
linearStep *= 2.0;
elevationStep *= 2.0;
rotationalStep *= 2.0;
}
if(mMoveComponents[MOVE_W])
new_tf.translate( linearStep*forward);
if(mMoveComponents[MOVE_S])
new_tf.translate(-linearStep*forward);
if(mMoveComponents[MOVE_A])
new_tf.translate( linearStep*left);
if(mMoveComponents[MOVE_D])
new_tf.translate(-linearStep*left);
if(mMoveComponents[MOVE_F])
new_tf.translate( elevationStep*up);
if(mMoveComponents[MOVE_Z])
new_tf.translate(-elevationStep*up);
if(mMoveComponents[MOVE_Q])
new_tf.rotate(Eigen::AngleAxisd( rotationalStep, up));
if(mMoveComponents[MOVE_E])
new_tf.rotate(Eigen::AngleAxisd(-rotationalStep, up));
new_tf.pretranslate(old_tf.translation());
new_tf.rotate(old_tf.rotation());
mHubo->getJoint(0)->setPositions(FreeJoint::convertToPositions(new_tf));
}
if(!mLoadedTrajectory)
{
if(solve)
mHubo->getIK(true)->solve();
}
refreshActualHubo();
}
bool mAmplifyMovement;
protected:
bool mLoadedTrajectory;
SkeletonPtr mHubo;
size_t iter;
SkeletonPtr mActualHubo;
SkeletonPtr mEndpointHubo;
SkeletonPtr mFailedHubo;
bool mViewEndpoint;
HuboPath::Operator mOperator;
std::vector<size_t> mOperatorIndices;
EndEffectorPtr l_foot;
EndEffectorPtr r_foot;
EndEffectorPtr l_hand;
EndEffectorPtr r_hand;
std::vector<IK::Analytical::Solution> mSolutions;
Eigen::VectorXd grad;
// Order: q, w, e, a, s, d
std::vector<bool> mMoveComponents;
bool mAnyMovement;
bool mPlayTrajectory;
size_t mTrajectoryStep;
bool mTrajectoryValid;
std::vector<Eigen::VectorXd> mTrajectory;
osg::Timer mTimer;
bool solve;
};
class InputHandler : public osgGA::GUIEventHandler
{
public:
InputHandler(osgDart::Viewer* viewer, TeleoperationWorld* teleop,
const SkeletonPtr& hubo, const WorldPtr& world)
: mViewer(viewer),
mTeleop(teleop),
mHubo(hubo),
mWorld(world)
{
initialize();
}
void initialize()
{
mRestConfig = mHubo->getPositions();
for(size_t i=0; i < mHubo->getNumEndEffectors(); ++i)
{
const InverseKinematicsPtr ik = mHubo->getEndEffector(i)->getIK();
if(ik)
{
mDefaultBounds.push_back(ik->getErrorMethod().getBounds());
mDefaultTargetTf.push_back(ik->getTarget()->getRelativeTransform());
mConstraintActive.push_back(false);
mEndEffectorIndex.push_back(i);
}
}
mPosture = std::dynamic_pointer_cast<RelaxedPosture>(
mHubo->getIK(true)->getObjective());
mBalance = std::dynamic_pointer_cast<dart::constraint::BalanceConstraint>(
mHubo->getIK(true)->getProblem()->getEqConstraint(1));
mOptimizationKey = 'r';
mMoveComponents.resize(TeleoperationWorld::NUM_MOVE, false);
}
virtual bool handle(const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter&) override
{
if(nullptr == mHubo)
{
return false;
}
if( osgGA::GUIEventAdapter::KEYDOWN == ea.getEventType() )
{
if( ea.getKey() == ' ' )
{
mTeleop->playTrajectory();
return true;
}
if( ea.getKey() == osgGA::GUIEventAdapter::KEY_Return)
{
mTeleop->runTrajectory();
}
if( ea.getKey() == '`' )
{
mTeleop->toggleEndpointVisibility();
return true;
}
if( ea.getKey() == osgGA::GUIEventAdapter::KEY_Tab )
{
mTeleop->loadWaypoint();
return true;
}
if( ea.getKey() == 'p' )
{
for(size_t i=0; i < mHubo->getNumDofs(); ++i)
std::cout << mHubo->getDof(i)->getName() << ": "
<< mHubo->getDof(i)->getPosition() << std::endl;
return true;
}
if( ea.getKey() == 't' )
{
// Reset all the positions except for x, y, and yaw
for(size_t i=0; i < mHubo->getNumDofs(); ++i)
{
if( i < 2 || 4 < i )
mHubo->getDof(i)->setPosition(mRestConfig[i]);
}
return true;
}
if( ea.getKey() == 'T' )
{
mTeleop->loadTrajectory();
return true;
}
if( '1' <= ea.getKey() && ea.getKey() <= '9' )
{
size_t index = ea.getKey() - '1';
if(index < mConstraintActive.size())
{
EndEffector* ee = mHubo->getEndEffector(mEndEffectorIndex[index]);
const InverseKinematicsPtr& ik = ee->getIK();
if(ik && mConstraintActive[index])
{
mConstraintActive[index] = false;
ik->getErrorMethod().setBounds(mDefaultBounds[index]);
ik->getTarget()->setRelativeTransform(mDefaultTargetTf[index]);
mWorld->removeSimpleFrame(ik->getTarget());
}
else if(ik)
{
mConstraintActive[index] = true;
// Use the standard default bounds instead of our custom default
// bounds
ik->getErrorMethod().setBounds();
ik->getTarget()->setTransform(ee->getTransform());
mWorld->addSimpleFrame(ik->getTarget());
}
}
return true;
}
if( 'x' == ea.getKey() )
{
EndEffector* ee = mHubo->getEndEffector("l_foot");
ee->getSupport()->setActive(!ee->getSupport()->isActive());
return true;
}
if( 'c' == ea.getKey() )
{
EndEffector* ee = mHubo->getEndEffector("r_foot");
ee->getSupport()->setActive(!ee->getSupport()->isActive());
return true;
}
if( '0' == ea.getKey() )
{
std::cout << "Resetting positions" << std::endl;
mTeleop->resetPositions();
return true;
}
if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_L)
mTeleop->mAmplifyMovement = true;
switch(ea.getKey())
{
case 'w': case 'W': mMoveComponents[TeleoperationWorld::MOVE_W] = true; break;
case 'a': case 'A': mMoveComponents[TeleoperationWorld::MOVE_A] = true; break;
case 's': case 'S': mMoveComponents[TeleoperationWorld::MOVE_S] = true; break;
case 'd': case 'D': mMoveComponents[TeleoperationWorld::MOVE_D] = true; break;
case 'q': case 'Q': mMoveComponents[TeleoperationWorld::MOVE_Q] = true; break;
case 'e': case 'E': mMoveComponents[TeleoperationWorld::MOVE_E] = true; break;
case 'f': case 'F': mMoveComponents[TeleoperationWorld::MOVE_F] = true; break;
case 'z': case 'Z': mMoveComponents[TeleoperationWorld::MOVE_Z] = true; break;
}
switch(ea.getKey())
{
case 'w': case 'a': case 's': case 'd': case 'q': case 'e': case 'f': case 'z':
case 'W': case 'A': case 'S': case 'D': case 'Q': case 'E': case 'F': case 'Z':
{
mTeleop->setMovement(mMoveComponents);
return true;
}
}
if(mOptimizationKey == ea.getKey())
{
mTeleop->resumeSolving();
if(mPosture)
mPosture->enforceIdealPosture = true;
if(mBalance)
mBalance->setErrorMethod(dart::constraint::BalanceConstraint::OPTIMIZE_BALANCE);
return true;
}
}
if( osgGA::GUIEventAdapter::KEYUP == ea.getEventType() )
{
if(ea.getKey() == mOptimizationKey)
{
if(mPosture)
mPosture->enforceIdealPosture = false;
if(mBalance)
mBalance->setErrorMethod(dart::constraint::BalanceConstraint::FROM_CENTROID);
return true;
}
if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_L)
mTeleop->mAmplifyMovement = false;
switch(ea.getKey())
{
case 'w': case 'W': mMoveComponents[TeleoperationWorld::MOVE_W] = false; break;
case 'a': case 'A': mMoveComponents[TeleoperationWorld::MOVE_A] = false; break;
case 's': case 'S': mMoveComponents[TeleoperationWorld::MOVE_S] = false; break;
case 'd': case 'D': mMoveComponents[TeleoperationWorld::MOVE_D] = false; break;
case 'q': case 'Q': mMoveComponents[TeleoperationWorld::MOVE_Q] = false; break;
case 'e': case 'E': mMoveComponents[TeleoperationWorld::MOVE_E] = false; break;
case 'f': case 'F': mMoveComponents[TeleoperationWorld::MOVE_F] = false; break;
case 'z': case 'Z': mMoveComponents[TeleoperationWorld::MOVE_Z] = false; break;
}
switch(ea.getKey())
{
case 'w': case 'a': case 's': case 'd': case 'q': case'e': case 'f': case 'z':
case 'W': case 'A': case 'S': case 'D': case 'Q': case 'E': case 'F': case 'Z':
{
mTeleop->setMovement(mMoveComponents);
return true;
}
}
}
return false;
}
protected:
osgDart::Viewer* mViewer;
TeleoperationWorld* mTeleop;
SkeletonPtr mHubo;
WorldPtr mWorld;
Eigen::VectorXd mRestConfig;
std::vector<bool> mConstraintActive;
std::vector<size_t> mEndEffectorIndex;
std::vector< std::pair<Eigen::Vector6d, Eigen::Vector6d> > mDefaultBounds;
Eigen::aligned_vector<Eigen::Isometry3d> mDefaultTargetTf;
std::shared_ptr<RelaxedPosture> mPosture;
std::shared_ptr<dart::constraint::BalanceConstraint> mBalance;
char mOptimizationKey;
std::vector<bool> mMoveComponents;
};
SkeletonPtr createGround()
{
// Create a Skeleton to represent the ground
SkeletonPtr ground = Skeleton::create("ground");
Eigen::Isometry3d tf(Eigen::Isometry3d::Identity());
double thickness = 0.01;
tf.translation() = Eigen::Vector3d(0,0,-thickness/2.0);
WeldJoint::Properties joint;
joint.mT_ParentBodyToJoint = tf;
ground->createJointAndBodyNodePair<WeldJoint>(nullptr, joint);
ShapePtr groundShape =
std::make_shared<BoxShape>(Eigen::Vector3d(10,10,thickness));
groundShape->setColor(dart::Color::Blue(0.2));
ground->getBodyNode(0)->addVisualizationShape(groundShape);
ground->getBodyNode(0)->addCollisionShape(groundShape);
return ground;
}
SkeletonPtr createHubo()
{
dart::utils::DartLoader loader;
loader.addPackageDirectory("drchubo", DART_DATA_PATH"/urdf/drchubo");
SkeletonPtr hubo =
loader.parseSkeleton(DART_DATA_PATH"/urdf/drchubo/drchubo.urdf");
hubo->enableSelfCollision();
for(size_t i = 0; i < hubo->getNumBodyNodes(); ++i)
{
BodyNode* bn = hubo->getBodyNode(i);
if(bn->getName().substr(0, 7) == "Body_LF"
|| bn->getName().substr(0, 7) == "Body_RF"
|| bn->getName().substr(0, 7) == "Body_NK")
{
bn->remove();
--i;
}
}
return hubo;
}
void setStartupConfiguration(const SkeletonPtr& hubo)
{
hubo->getDof("LHP")->setPosition(-45.0*M_PI/180.0);
hubo->getDof("LKP")->setPosition( 90.0*M_PI/180.0);
hubo->getDof("LAP")->setPosition(-45.0*M_PI/180.0);
hubo->getDof("RHP")->setPosition(-45.0*M_PI/180.0);
hubo->getDof("RKP")->setPosition( 90.0*M_PI/180.0);
hubo->getDof("RAP")->setPosition(-45.0*M_PI/180.0);
hubo->getDof("LSP")->setPosition( 30.0*M_PI/180.0);
hubo->getDof("LEP")->setPosition(-120.0*M_PI/180.0);
hubo->getDof("RSP")->setPosition( 30.0*M_PI/180.0);
hubo->getDof("REP")->setPosition(-120.0*M_PI/180.0);
hubo->getDof("LSY")->setPositionLowerLimit(-90.0*M_PI/180.0);
hubo->getDof("LSY")->setPositionUpperLimit( 90.0*M_PI/180.0);
hubo->getDof("LWY")->setPositionLowerLimit(-90.0*M_PI/180.0);
hubo->getDof("LWY")->setPositionUpperLimit( 90.0*M_PI/180.0);
hubo->getDof("RSY")->setPositionLowerLimit(-90.0*M_PI/180.0);
hubo->getDof("RSY")->setPositionUpperLimit( 90.0*M_PI/180.0);
hubo->getDof("RWY")->setPositionLowerLimit(-90.0*M_PI/180.0);
hubo->getDof("RWY")->setPositionUpperLimit( 90.0*M_PI/180.0);
}
void setupEndEffectors(const SkeletonPtr& hubo)
{
Eigen::VectorXd rootjoint_weights = Eigen::VectorXd::Ones(7);
rootjoint_weights = 0.01*rootjoint_weights;
double extra_error_clamp = 0.1;
Eigen::Vector3d linearBounds =
Eigen::Vector3d::Constant(std::numeric_limits<double>::infinity());
Eigen::Vector3d angularBounds =
Eigen::Vector3d::Constant(std::numeric_limits<double>::infinity());
Eigen::Isometry3d tf_hand(Eigen::Isometry3d::Identity());
tf_hand.translate(Eigen::Vector3d(0.0, 0.0, -0.09));
EndEffector* l_hand = hubo->getBodyNode("Body_LWR")->
createEndEffector("l_hand");
l_hand->setDefaultRelativeTransform(tf_hand, true);
osgDart::InteractiveFramePtr lh_target(new osgDart::InteractiveFrame(
Frame::World(), "lh_target"));
l_hand->getIK(true)->setTarget(lh_target);
l_hand->getIK()->useWholeBody();
l_hand->getIK()->setGradientMethod<HuboArmIK>("Body_LSP");
l_hand->getIK()->getAnalytical()->setExtraDofUtilization(
IK::Analytical::PRE_ANALYTICAL);
l_hand->getIK()->getAnalytical()->setExtraErrorLengthClamp(extra_error_clamp);
l_hand->getIK()->getGradientMethod().setComponentWeights(rootjoint_weights);
l_hand->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
l_hand->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
EndEffector* r_hand = hubo->getBodyNode("Body_RWR")->
createEndEffector("r_hand");
r_hand->setDefaultRelativeTransform(tf_hand, true);
osgDart::InteractiveFramePtr rh_target(new osgDart::InteractiveFrame(
Frame::World(), "rh_target"));
r_hand->getIK(true)->setTarget(rh_target);
r_hand->getIK()->useWholeBody();
r_hand->getIK()->setGradientMethod<HuboArmIK>("Body_RSP");
r_hand->getIK()->getAnalytical()->setExtraDofUtilization(
IK::Analytical::PRE_ANALYTICAL);
r_hand->getIK()->getAnalytical()->setExtraErrorLengthClamp(extra_error_clamp);
r_hand->getIK()->getGradientMethod().setComponentWeights(rootjoint_weights);
r_hand->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
r_hand->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
dart::math::SupportGeometry foot_support;
foot_support.push_back(Eigen::Vector3d(-0.08, 0.05, 0.0));
foot_support.push_back(Eigen::Vector3d(-0.18, 0.05, 0.0));
foot_support.push_back(Eigen::Vector3d(-0.18, -0.05, 0.0));
foot_support.push_back(Eigen::Vector3d(-0.08, -0.05, 0.0));
Eigen::Isometry3d tf_foot(Eigen::Isometry3d::Identity());
double ground_dist = 0.01;
tf_foot.translation() = Eigen::Vector3d(0.14, 0.0, -0.136+ground_dist);
linearBounds[2] = 1e-8;
Eigen::Vector3d ground_offset = ground_dist * Eigen::Vector3d::UnitZ();
angularBounds[0] = 1e-8;
angularBounds[1] = 1e-8;
EndEffector* l_foot = hubo->getBodyNode("Body_LAR")->
createEndEffector("l_foot");
l_foot->setDefaultRelativeTransform(tf_foot, true);
osgDart::InteractiveFramePtr lf_target(new osgDart::InteractiveFrame(
Frame::World(), "lf_target"));
l_foot->getIK(true)->setTarget(lf_target);
l_foot->getIK()->setHierarchyLevel(1);
l_foot->getIK()->getErrorMethod().setLinearBounds(
-linearBounds + ground_offset, linearBounds + ground_offset);
l_foot->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
l_foot->getIK()->setGradientMethod<HuboLegIK>("Body_LHY");
l_foot->getSupport(true)->setGeometry(foot_support);
l_foot->getSupport()->setActive();
EndEffector* r_foot = hubo->getBodyNode("Body_RAR")->
createEndEffector("r_foot");
r_foot->setDefaultRelativeTransform(tf_foot, true);
osgDart::InteractiveFramePtr rf_target(new osgDart::InteractiveFrame(
Frame::World(), "rf_target"));
r_foot->getIK(true)->setTarget(rf_target);
r_foot->getIK()->setHierarchyLevel(1);
r_foot->getIK()->getErrorMethod().setLinearBounds(
-linearBounds + ground_offset, linearBounds + ground_offset);
r_foot->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
r_foot->getIK()->setGradientMethod<HuboLegIK>("Body_RHY");
r_foot->getSupport(true)->setGeometry(foot_support);
r_foot->getSupport()->setActive();
dart::math::SupportGeometry peg_support;
peg_support.push_back(Eigen::Vector3d::Zero());
linearBounds = Eigen::Vector3d::Constant(std::numeric_limits<double>::infinity());
angularBounds = linearBounds;
Eigen::Isometry3d tf_peg(Eigen::Isometry3d::Identity());
tf_peg.translation() = Eigen::Vector3d(0.0, 0.0, 0.09);
EndEffector* l_peg = hubo->getBodyNode("Body_LWP")->createEndEffector("l_peg");
l_peg->setDefaultRelativeTransform(tf_peg, true);
osgDart::InteractiveFramePtr lp_target(new osgDart::InteractiveFrame(
Frame::World(), "lp_target"));
l_peg->getIK(true)->setTarget(lp_target);
l_peg->getIK()->setGradientMethod<HuboArmIK>("Body_LSP");
l_peg->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
l_peg->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
l_peg->getSupport(true)->setGeometry(peg_support);
EndEffector* r_peg = hubo->getBodyNode("Body_RWP")->createEndEffector("r_peg");
r_peg->setDefaultRelativeTransform(tf_peg, true);
osgDart::InteractiveFramePtr rp_target(new osgDart::InteractiveFrame(
Frame::World(), "rp_target"));
r_peg->getIK(true)->setTarget(rp_target);
r_peg->getIK()->setGradientMethod<HuboArmIK>("Body_RSP");
r_peg->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
r_peg->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
r_peg->getSupport(true)->setGeometry(peg_support);
double heightChange = -r_foot->getWorldTransform().translation()[2]+ground_dist;
hubo->getDof("rootJoint_pos_z")->setPosition(heightChange);
l_foot->getIK()->getTarget()->setTransform(l_foot->getTransform());
r_foot->getIK()->getTarget()->setTransform(r_foot->getTransform());
}
void enableDragAndDrops(osgDart::Viewer& viewer, const SkeletonPtr& hubo)
{
// Turn on drag-and-drop for the whole Skeleton
for(size_t i=0; i < hubo->getNumBodyNodes(); ++i)
viewer.enableDragAndDrop(hubo->getBodyNode(i), false, false);
for(size_t i=0; i < hubo->getNumEndEffectors(); ++i)
{
EndEffector* ee = hubo->getEndEffector(i);
if(!ee->getIK())
continue;
// Check whether the target is an interactive frame, and add it if it is
if(const auto& frame = std::dynamic_pointer_cast<osgDart::InteractiveFrame>(
ee->getIK()->getTarget()))
viewer.enableDragAndDrop(frame.get());
}
}
void setupWholeBodySolver(const SkeletonPtr& hubo)
{
std::shared_ptr<dart::optimizer::GradientDescentSolver> solver =
std::dynamic_pointer_cast<dart::optimizer::GradientDescentSolver>(
hubo->getIK(true)->getSolver());
size_t nDofs = hubo->getNumDofs();
double default_weight = 0.01;
Eigen::VectorXd weights = default_weight * Eigen::VectorXd::Ones(nDofs);
weights[2] = 0.0;
weights[3] = 0.0;
weights[4] = 0.0;
Eigen::VectorXd lower_posture = Eigen::VectorXd::Constant(nDofs,
-std::numeric_limits<double>::infinity());
lower_posture[0] = -0.35;
lower_posture[1] = -0.35;
lower_posture[5] = 0.55;
Eigen::VectorXd upper_posture = Eigen::VectorXd::Constant(nDofs,
std::numeric_limits<double>::infinity());
upper_posture[0] = 0.35;
upper_posture[1] = 0.50;
upper_posture[5] = 0.95;
std::shared_ptr<RelaxedPosture> objective = std::make_shared<RelaxedPosture>(
hubo->getPositions(), lower_posture, upper_posture, weights);
hubo->getIK()->setObjective(objective);
std::shared_ptr<dart::constraint::BalanceConstraint> balance =
std::make_shared<dart::constraint::BalanceConstraint>(hubo->getIK());
hubo->getIK()->getProblem()->addEqConstraint(balance);
balance->setErrorMethod(dart::constraint::BalanceConstraint::FROM_CENTROID);
balance->setBalanceMethod(dart::constraint::BalanceConstraint::SHIFT_SUPPORT);
solver->setNumMaxIterations(5);
}
int main()
{
dart::simulation::WorldPtr world(new dart::simulation::World);
const SkeletonPtr& hubo = createHubo();
setStartupConfiguration(hubo);
setupEndEffectors(hubo);
world->addSkeleton(hubo);
setupWholeBodySolver(hubo);
osg::ref_ptr<TeleoperationWorld> node = new TeleoperationWorld(world, hubo);
osgDart::Viewer viewer;
viewer.allowSimulation(false);
viewer.addWorldNode(node);
enableDragAndDrops(viewer, hubo);
viewer.addEventHandler(new InputHandler(&viewer, node, hubo, world));
// double display_elevation = 0.05;
// viewer.addAttachment(new osgDart::SupportPolygonVisual(
// hubo, display_elevation));
std::cout << viewer.getInstructions() << std::endl;
std::cout << "Alt + Click: Try to translate a body without changing its orientation\n"
<< "Ctrl + Click: Try to rotate a body without changing its translation\n"
<< "Shift + Click: Move a body using only its parent joint\n"
<< "1 -> 4: Toggle the interactive target of an EndEffector\n"
<< "W A S D: Move the robot around the scene\n"
<< "Q E: Rotate the robot counter-clockwise and clockwise\n"
<< "F Z: Shift the robot's elevation up and down\n"
<< "X C: Toggle support on the left and right foot\n"
<< "R: Optimize the robot's posture\n"
<< "T: Reset the robot to its relaxed posture\n\n"
<< " The green polygon is the support polygon of the robot, and the blue/red ball is\n"
<< " the robot's center of mass. The green ball is the centroid of the polygon.\n\n"
<< "Note that this is purely kinematic. Physical simulation is not allowed in this app.\n"
<< std::endl;
// Set up the window
viewer.setUpViewInWindow(0, 0, 1280, 960);
// Set up the default viewing position
viewer.getCameraManipulator()->setHomePosition(osg::Vec3( 5.34, 3.00, 1.91),
osg::Vec3( 0.00, 0.00, 0.50),
osg::Vec3(-0.20, -0.08, 0.98));
// Reset the camera manipulator so that it starts in the new viewing position
viewer.setCameraManipulator(viewer.getCameraManipulator());
viewer.run();
}
| 28.367002
| 121
| 0.618023
|
mxgrey
|
d33a33240d8a178417fd46bada7263e30639b3bd
| 12,320
|
cpp
|
C++
|
OldCode/CameraController - GenlCam.cpp
|
merfii/Slurry
|
92b23ea2b764252fc90c2af741debdffb9a96106
|
[
"MIT"
] | 4
|
2019-12-04T02:56:35.000Z
|
2022-01-05T14:14:37.000Z
|
OldCode/CameraController - GenlCam.cpp
|
merfii/Slurry
|
92b23ea2b764252fc90c2af741debdffb9a96106
|
[
"MIT"
] | null | null | null |
OldCode/CameraController - GenlCam.cpp
|
merfii/Slurry
|
92b23ea2b764252fc90c2af741debdffb9a96106
|
[
"MIT"
] | 2
|
2018-11-06T03:54:00.000Z
|
2018-12-06T12:13:30.000Z
|
#pragma execution_character_set("utf-8")
#include "GlobalShared.h"
#include "CameraController.h"
//Settings for using Basler GigE cameras.
#include <pylon/PylonIncludes.h>
//#include <pylon/PylonGUI.h>
#include <pylon/gige/BaslerGigEInstantCamera.h>
#include <pylon/gige/BaslerGigEDeviceInfo.h>
typedef Pylon::CBaslerGigEInstantCamera Camera_t;
typedef Pylon::CBaslerGigEImageEventHandler ImageEventHandler_t; // Or use Camera_t::ImageEventHandler_t
typedef Pylon::CBaslerGigEGrabResultPtr GrabResultPtr_t; // Or use Camera_t::GrabResultPtr_t
using namespace Basler_GigECameraParams;
using namespace Pylon;
//using namespace GenApi;
class CameraControllerImpl final: public CameraController
{
public:
~CameraControllerImpl();
static CameraController* getInstance();
virtual int PollingDevices(bool printout) override;
virtual bool LoadConfiguration() override;
virtual void StartGrabbing() override;
virtual void CloseCameras() override;
virtual void SetModeContinue() override;
virtual void SetModeSoftTrig() override;
virtual void ExecuteSoftTrig() override;
virtual void GetFramePacket(FramePacket &fp) override;
virtual int GetCameraOpened() const override;
protected:
CameraControllerImpl();
private:
void doLoadGigECamera();
void doLoadUsbCamera();
void configChunk();
void configExposure();
QVector<String_t> idlist;
CBaslerGigEInstantCamera *camGrayA, *camGrayB, *camColorA, *camColorB;
// CInstantCamera *cameras[4];
// CGrabResultPtr ptrGrabResults[4];
int nCameraOpened;
};
class ImageEventHandler : public CImageEventHandler
{
public:
ImageEventHandler(int chlIdx)
{
m_channelIdx = chlIdx;
}
virtual void OnImageGrabbed(CInstantCamera& camera, const CGrabResultPtr& ptrGrabResult)
{
CameraController::FramePacket fp;
fp.buffer = static_cast<uchar*>(ptrGrabResult->GetBuffer());
fp.height = ptrGrabResult->GetHeight();
fp.width = ptrGrabResult->GetWidth();
fp.size = ptrGrabResult->GetImageSize();
ptrGrabResult->GetStride(fp.stride);
if (PayloadType_ChunkData == ptrGrabResult->GetPayloadType())
{
fp.timestamp = ptrGrabResult->GetTimeStamp();
fp.framecount = ptrGrabResult->GetFrameNumber();
}else
{
fp.timestamp = 0;
fp.framecount = 0;
}
fp.channIdx = m_channelIdx;
/**************************************************/
//跨线程?
emit process(fp);
// GlobalShared::algorithm->process(fp);
/**************************************************/
}
private:
int m_channelIdx;
};
CameraControllerImpl::CameraControllerImpl()
{
PylonInitialize();
idlist.resize(4);
camColorA = camColorB = nullptr;
camGrayA = camGrayB = nullptr;
nCameraOpened = 0;
}
CameraControllerImpl::~CameraControllerImpl()
{
CloseCameras();
PylonTerminate();
}
void CameraControllerImpl::CloseCameras()
{
if (nCameraOpened == 0)
return;
if (camColorA&& camColorA->IsOpen())
{
camColorA->Close();
camColorA->DestroyDevice();
}
if (camColorB&& camColorB->IsOpen())
{
camColorB->Close();
camColorB->DestroyDevice();
}
if (camGrayA&& camGrayA->IsOpen())
{
camGrayA->Close();
camGrayA->DestroyDevice();
}
if (camGrayB&& camGrayB->IsOpen())
{
camGrayB->Close();
camGrayB->DestroyDevice();
}
camColorA = camColorB = nullptr;
camGrayA = camGrayB = nullptr;
nCameraOpened = 0;
}
int CameraControllerImpl::PollingDevices(bool printout)
{
DeviceInfoList_t lstDevices;
DeviceInfoList_t filter;
CTlFactory& TlFactory = CTlFactory::GetInstance();
CloseCameras();
idlist.clear();
//filter.push_back( CDeviceInfo().SetDeviceClass());
TlFactory.EnumerateDevices(lstDevices);
DeviceInfoList_t::const_iterator it;
GlobalShared::PrintLog(QStringLiteral("正在查找相机..."));
for (it = lstDevices.begin(); it != lstDevices.end(); ++it)
{
if (printout)
{
qDebug() << "DeviceClass:\t" << it->GetDeviceClass();
qDebug() << "DeviceFactory:\t" << it->GetDeviceFactory();
qDebug() << "DeviceVersion:\t" << it->GetDeviceVersion();
qDebug() << "FullName:\t" << it->GetFullName();
qDebug() << "FriendlyName:\t" << it->GetFriendlyName();
qDebug() << "ModelName:\t" << it->GetModelName();
qDebug() << "VendorName:\t" << it->GetVendorName();
qDebug() << "SerialNumber:\t" << it->GetSerialNumber();
qDebug() << "UserDefinedName:\t" << it->GetUserDefinedName();
qDebug() << endl;
}
idlist.push_back(it->GetSerialNumber());
}
GlobalShared::PrintLog(QString("已找到相机 %1 个").arg(idlist.size()));
return idlist.size();
}
void CameraControllerImpl::doLoadGigECamera()
{
QString camId;
CDeviceInfo dinfo;
int idx;
camId = GlobalShared::Setting::GetString(QString("CameraControl/ID/") + "GrayA");
idx = 0;
foreach(const String_t &id, idlist)
{
if (id == camId)
{
//dinfo.SetDeviceClass(BaslerGigEDeviceClass);
dinfo.SetSerialNumber(id);
//dinfo.SetFullName(name);
camGrayA = new CBaslerGigEInstantCamera(CTlFactory::GetInstance().CreateDevice(dinfo));
cameras[idx] = static_cast<CInstantCamera*>(camGrayA);
cameraOpened++;
qDebug() << "Using device " << cameras[idx]->GetDeviceInfo().GetModelName() << id;
break;
}
}
camId = GlobalShared::Setting::GetString(QString("CameraControl/ID/") + "GrayB");
idx = 1;
foreach(const String_t &id, idlist)
{
if (id == camId)
{
//dinfo.SetDeviceClass(BaslerGigEDeviceClass);
dinfo.SetSerialNumber(id);
//dinfo.SetFullName(name);
camGrayB = new CBaslerGigEInstantCamera(CTlFactory::GetInstance().CreateDevice(dinfo));
cameras[idx] = static_cast<CInstantCamera*>(camGrayB);
cameraOpened++;
qDebug() << "Using device " << cameras[idx]->GetDeviceInfo().GetModelName() << id;
break;
}
}
//camera.RegisterConfiguration( new CConfigurationEventPrinter, RegistrationMode_Append, Cleanup_Delete); // Camera use.
}
void CameraControllerImpl::doLoadUsbCamera()
{
QString camId;
CDeviceInfo dinfo;
int idx;
camId = GlobalShared::Setting::GetString(QString("CameraControl/ID/") + "ColorA");
idx = 2;
foreach(const String_t &id, idlist)
{
if (id == camId)
{
//dinfo.SetDeviceClass(BaslerGigEDeviceClass);
dinfo.SetSerialNumber(id);
//dinfo.SetFullName(name);
camColorA = new CBaslerUsbInstantCamera(CTlFactory::GetInstance().CreateDevice(dinfo));
cameras[idx] = static_cast<CInstantCamera*>(camColorA);
cameraOpened++;
qDebug() << "Using device " << cameras[idx]->GetDeviceInfo().GetModelName() << id;
break;
}
}
camId = GlobalShared::Setting::GetString(QString("CameraControl/ID/") + "ColorB");
idx = 3;
foreach(const String_t &id, idlist)
{
if (id == camId)
{
//dinfo.SetDeviceClass(BaslerGigEDeviceClass);
dinfo.SetSerialNumber(id);
//dinfo.SetUserDefinedName("GrayA");
camColorB = new CBaslerUsbInstantCamera(CTlFactory::GetInstance().CreateDevice(dinfo));
cameras[idx] = static_cast<CInstantCamera*>(camColorB);
cameraOpened++;
qDebug() << "Using device " << cameras[idx]->GetDeviceInfo().GetModelName() << id;
break;
}
}
}
bool CameraControllerImpl::LoadConfiguration()
{
try
{
doLoadGigECamera();
doLoadUsbCamera();
for (int i = 0; i < 4; i++)
{
if (nullptr == cameras[i])
continue;
cameras[i]->Open();
cameras[i]->RegisterImageEventHandler(new ImageEventHandler(i), RegistrationMode_Append, Cleanup_Delete);
}
SetModeSoftTrig();
configChunk();
configExposure();
}
catch (const GenericException &e)
{
// Error handling.
qDebug() << e.GetDescription() << endl;
return false;
}
return true;
}
void CameraControllerImpl::StartGrabbing()
{
try
{
for (int i = 0; i < 4; i++)
{
if (cameras[i] && cameras[i]->IsOpen())
{
cameras[i]->StartGrabbing(GrabStrategy_LatestImageOnly, GrabLoop_ProvidedByInstantCamera);
cameras[i]->ExecuteSoftwareTrigger();
}
}
}catch (const GenericException &e)
{
// Error handling.
qDebug() << e.GetDescription() << endl;
}
//(*it)->StartGrabbing(GrabStrategy_LatestImageOnly, GrabLoop_ProvidedByUser);
//camera.WaitForFrameTriggerReady( 500, TimeoutHandling_ThrowException)
}
/*
void CameraControllerImpl::StopGrabbing()
{
for (int i = 0; i < 4; i++)
{
if (cameras[i] && cameras[i]->IsOpen() && cameras[i]->IsGrabbing())
cameras[i]->StopGrabbing();
}
}
*/
void CameraControllerImpl::SetModeContinue()
{
for (int i = 0; i < 4; i++)
{
if (cameras[i] && cameras[i]->IsOpen())
{
INodeMap& nodemap = cameras[i]->GetNodeMap();
CEnumerationPtr triggerSelector(nodemap.GetNode("TriggerSelector"));
CEnumerationPtr triggerMode(nodemap.GetNode("TriggerMode"));
triggerSelector->FromString("FrameStart");
triggerMode->FromString("Off");
}
}
}
void CameraControllerImpl::SetModeSoftTrig()
{
for (int i = 0; i < 4; i++)
{
if (cameras[i] && cameras[i]->IsOpen())
{
INodeMap& nodemap = cameras[i]->GetNodeMap();
CEnumerationPtr triggerSelector(nodemap.GetNode("TriggerSelector"));
CEnumerationPtr triggerMode(nodemap.GetNode("TriggerMode"));
CEnumerationPtr triggerSource(nodemap.GetNode("TriggerSource"));
triggerSelector->FromString("FrameStart");
triggerMode->FromString("On");
triggerSource->FromString("Software");
}
}
}
void CameraControllerImpl::ExecuteSoftTrig()
{
try
{
for (int i = 0; i < 4; i++)
{
if (cameras[i] && cameras[i]->IsOpen())
{
cameras[i]->ExecuteSoftwareTrigger();
}
}
}catch (const GenericException &e)
{
// Error handling.
qDebug() << e.GetDescription() << endl;
}
}
void CameraControllerImpl::configChunk()
{
for (int i = 0; i < 4; i++)
{
if (cameras[i] && cameras[i]->IsOpen())
{
INodeMap& nodemap = cameras[i]->GetNodeMap();
try{
CBooleanPtr chunkModeActive(nodemap.GetNode("ChunkModeActive"));
if (IsWritable(chunkModeActive))
{
chunkModeActive->SetValue(true);
}
CEnumerationPtr chunkSelector(nodemap.GetNode("ChunkSelector"));
if (IsWritable(chunkSelector))
{
chunkSelector->FromString("Timestamp");
}
CBooleanPtr chunkEnable(nodemap.GetNode("ChunkEnable"));
if (IsWritable(chunkEnable))
{
chunkEnable->SetValue(true);
}
if (IsWritable(chunkSelector))
{
chunkSelector->FromString("Framecounter");
}
if (IsWritable(chunkEnable))
{
chunkEnable->SetValue(true);
}
}
catch (const GenericException &e)
{
// Error handling.
qDebug() << e.GetDescription() << endl;
}
}
}
/*
if (GenApi::IsWritable(camera->ChunkModeActive))
{
camera->ChunkModeActive.SetValue(true);
camera->ChunkSelector.SetValue(ChunkSelector_Timestamp);
camera->ChunkEnable.SetValue(true);
camera->ChunkSelector.SetValue(ChunkSelector_Framecounter);
camera->ChunkEnable.SetValue(true);
}
*/
}
static void doConfigExposure(CInstantCamera *camera, int expoTime)
{
if (camera && camera->IsOpen())
{
INodeMap& nodemap = camera->GetNodeMap();
CEnumerationPtr exposureMode(nodemap.GetNode("ExposureMode"));
exposureMode->FromString("Timed");
CFloatPtr exposureTime(nodemap.GetNode("ExposureTime"));
if(IsWritable(exposureTime))
exposureTime->SetValue(expoTime);
CFloatPtr exposureTimeAbs(nodemap.GetNode("ExposureTimeAbs"));
if (IsWritable(exposureTimeAbs))
exposureTimeAbs->SetValue(expoTime);
}
/*
// Set for the timed exposure mode
camera->ExposureMode.SetValue(ExposureMode_Timed);
// Set the exposure time
camera->ExposureTimeAbs.SetValue(30000);
*/
}
void CameraControllerImpl::configExposure()
{
int t = GlobalShared::Setting::GetInt(QStringLiteral("CameraControl/ExposureTime"));
doConfigExposure(cameras[0], t);
doConfigExposure(cameras[1], t);
doConfigExposure(cameras[2], t);
doConfigExposure(cameras[3], t);
}
void CameraControllerImpl::GetFramePacket(FramePacket &fp)
{
/*
//已经使用线程callback的情况下不能再用该函数
RetrieveResult(500, ptrGrabResult, TimeoutHandling_Return))
#ifdef PYLON_WIN_BUILD
// Display the grabbed image.
Pylon::DisplayImage(1, ptrGrabResults[fp.channIdx]);
#endif
fp.eCode = 1;
*/
}
int CameraControllerImpl::GetCameraOpened() const
{
return cameraOpened;
}
CameraController* CameraControllerImpl::getInstance()
{
static CameraControllerImpl m_pinstance;
return &m_pinstance;
}
CameraController::CameraController()
{
}
CameraController::~CameraController()
{
}
CameraController* CameraController::GetInstance()
{
return dynamic_cast<CameraController*>(CameraControllerImpl::getInstance());
}
| 24.109589
| 121
| 0.701786
|
merfii
|
d33f8a44195f340f977f41dd7706425d5f71dfbd
| 9,105
|
cpp
|
C++
|
third_party/openal-soft/alc/bsinc_tables.cpp
|
hporro/grafica_cpp
|
1427bb6e8926b44be474b906e9f52cca77b3df9d
|
[
"MIT"
] | 2
|
2022-03-05T02:46:22.000Z
|
2022-03-05T03:04:20.000Z
|
third_party/openal-soft/alc/bsinc_tables.cpp
|
hporro/grafica_cpp
|
1427bb6e8926b44be474b906e9f52cca77b3df9d
|
[
"MIT"
] | null | null | null |
third_party/openal-soft/alc/bsinc_tables.cpp
|
hporro/grafica_cpp
|
1427bb6e8926b44be474b906e9f52cca77b3df9d
|
[
"MIT"
] | 4
|
2021-09-06T20:44:47.000Z
|
2021-10-04T22:05:12.000Z
|
#include "bsinc_tables.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <limits>
#include <memory>
#include <stdexcept>
#include "math_defs.h"
#include "vector.h"
namespace {
/* The max points includes the doubling for downsampling, so the maximum number
* of base sample points is 24, which is 23rd order.
*/
constexpr int BSincPointsMax{BSINC_POINTS_MAX};
constexpr int BSincPointsHalf{BSincPointsMax / 2};
constexpr int BSincPhaseCount{BSINC_PHASE_COUNT};
constexpr int BSincScaleCount{BSINC_SCALE_COUNT};
/* This is the normalized cardinal sine (sinc) function.
*
* sinc(x) = { 1, x = 0
* { sin(pi x) / (pi x), otherwise.
*/
constexpr double Sinc(const double x)
{
if(!(x > 1e-15 || x < -1e-15))
return 1.0;
return std::sin(al::MathDefs<double>::Pi()*x) / (al::MathDefs<double>::Pi()*x);
}
/* The zero-order modified Bessel function of the first kind, used for the
* Kaiser window.
*
* I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
* = sum_{k=0}^inf ((x / 2)^k / k!)^2
*/
constexpr double BesselI_0(const double x)
{
/* Start at k=1 since k=0 is trivial. */
const double x2{x / 2.0};
double term{1.0};
double sum{1.0};
double last_sum{};
int k{1};
/* Let the integration converge until the term of the sum is no longer
* significant.
*/
do {
const double y{x2 / k};
++k;
last_sum = sum;
term *= y * y;
sum += term;
} while(sum != last_sum);
return sum;
}
/* Calculate a Kaiser window from the given beta value and a normalized k
* [-1, 1].
*
* w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
* { 0, elsewhere.
*
* Where k can be calculated as:
*
* k = i / l, where -l <= i <= l.
*
* or:
*
* k = 2 i / M - 1, where 0 <= i <= M.
*/
constexpr double Kaiser(const double beta, const double k, const double besseli_0_beta)
{
if(!(k >= -1.0 && k <= 1.0))
return 0.0;
return BesselI_0(beta * std::sqrt(1.0 - k*k)) / besseli_0_beta;
}
/* Calculates the (normalized frequency) transition width of the Kaiser window.
* Rejection is in dB.
*/
constexpr double CalcKaiserWidth(const double rejection, const int order)
{
if(rejection > 21.19)
return (rejection - 7.95) / (order * 2.285 * al::MathDefs<double>::Tau());
/* This enforces a minimum rejection of just above 21.18dB */
return 5.79 / (order * al::MathDefs<double>::Tau());
}
/* Calculates the beta value of the Kaiser window. Rejection is in dB. */
constexpr double CalcKaiserBeta(const double rejection)
{
if(rejection > 50.0)
return 0.1102 * (rejection-8.7);
else if(rejection >= 21.0)
return (0.5842 * std::pow(rejection-21.0, 0.4)) + (0.07886 * (rejection-21.0));
return 0.0;
}
struct BSincHeader {
double width;
double beta;
double scaleBase;
double scaleRange;
double besseli_0_beta;
int a[BSINC_SCALE_COUNT];
int total_size;
};
constexpr BSincHeader GenerateBSincHeader(int Rejection, int Order)
{
BSincHeader ret{};
ret.width = CalcKaiserWidth(Rejection, Order);
ret.beta = CalcKaiserBeta(Rejection);
ret.scaleBase = ret.width / 2.0;
ret.scaleRange = 1.0 - ret.scaleBase;
ret.besseli_0_beta = BesselI_0(ret.beta);
int num_points{Order+1};
for(int si{0};si < BSincScaleCount;++si)
{
const double scale{ret.scaleBase + (ret.scaleRange * si / (BSincScaleCount - 1))};
const int a{std::min(static_cast<int>(num_points / 2.0 / scale), num_points)};
const int m{2 * a};
ret.a[si] = a;
ret.total_size += 4 * BSincPhaseCount * ((m+3) & ~3);
}
return ret;
}
/* 11th and 23rd order filters (12 and 24-point respectively) with a 60dB drop
* at nyquist. Each filter will scale up the order when downsampling, to 23rd
* and 47th order respectively.
*/
constexpr BSincHeader bsinc12_hdr{GenerateBSincHeader(60, 11)};
constexpr BSincHeader bsinc24_hdr{GenerateBSincHeader(60, 23)};
/* FIXME: This should be constexpr, but the temporary filter arrays are too
* big. This requires using heap space, which is not allowed in a constexpr
* function (maybe in C++20).
*/
template<size_t total_size>
std::array<float,total_size> GenerateBSincCoeffs(const BSincHeader &hdr)
{
auto filter = std::make_unique<double[][BSincPhaseCount+1][BSincPointsMax]>(BSincScaleCount);
/* Calculate the Kaiser-windowed Sinc filter coefficients for each scale
* and phase index.
*/
for(unsigned int si{0};si < BSincScaleCount;++si)
{
const int m{hdr.a[si] * 2};
const int o{BSincPointsHalf - (m/2)};
const int l{hdr.a[si] - 1};
const int a{hdr.a[si]};
const double scale{hdr.scaleBase + (hdr.scaleRange * si / (BSincScaleCount - 1))};
const double cutoff{scale - (hdr.scaleBase * std::max(0.5, scale) * 2.0)};
/* Do one extra phase index so that the phase delta has a proper target
* for its last index.
*/
for(int pi{0};pi <= BSincPhaseCount;++pi)
{
const double phase{l + (pi/double{BSincPhaseCount})};
for(int i{0};i < m;++i)
{
const double x{i - phase};
filter[si][pi][o+i] = Kaiser(hdr.beta, x/a, hdr.besseli_0_beta) * cutoff *
Sinc(cutoff*x);
}
}
}
auto ret = std::make_unique<std::array<float,total_size>>();
size_t idx{0};
for(unsigned int si{0};si < BSincScaleCount-1;++si)
{
const int m{((hdr.a[si]*2) + 3) & ~3};
const int o{BSincPointsHalf - (m/2)};
for(int pi{0};pi < BSincPhaseCount;++pi)
{
/* Write out the filter. Also calculate and write out the phase and
* scale deltas.
*/
for(int i{0};i < m;++i)
(*ret)[idx++] = static_cast<float>(filter[si][pi][o+i]);
/* Linear interpolation between phases is simplified by pre-
* calculating the delta (b - a) in: x = a + f (b - a)
*/
for(int i{0};i < m;++i)
{
const double phDelta{filter[si][pi+1][o+i] - filter[si][pi][o+i]};
(*ret)[idx++] = static_cast<float>(phDelta);
}
/* Linear interpolation between scales is also simplified.
*
* Given a difference in points between scales, the destination
* points will be 0, thus: x = a + f (-a)
*/
for(int i{0};i < m;++i)
{
const double scDelta{filter[si+1][pi][o+i] - filter[si][pi][o+i]};
(*ret)[idx++] = static_cast<float>(scDelta);
}
/* This last simplification is done to complete the bilinear
* equation for the combination of phase and scale.
*/
for(int i{0};i < m;++i)
{
const double spDelta{(filter[si+1][pi+1][o+i] - filter[si+1][pi][o+i]) -
(filter[si][pi+1][o+i] - filter[si][pi][o+i])};
(*ret)[idx++] = static_cast<float>(spDelta);
}
}
}
{
/* The last scale index doesn't have any scale or scale-phase deltas. */
const unsigned int si{BSincScaleCount - 1};
const int m{((hdr.a[si]*2) + 3) & ~3};
const int o{BSincPointsHalf - (m/2)};
for(int pi{0};pi < BSincPhaseCount;++pi)
{
for(int i{0};i < m;++i)
(*ret)[idx++] = static_cast<float>(filter[si][pi][o+i]);
for(int i{0};i < m;++i)
{
const double phDelta{filter[si][pi+1][o+i] - filter[si][pi][o+i]};
(*ret)[idx++] = static_cast<float>(phDelta);
}
for(int i{0};i < m;++i)
(*ret)[idx++] = 0.0f;
for(int i{0};i < m;++i)
(*ret)[idx++] = 0.0f;
}
}
assert(idx == total_size);
return *ret;
}
/* FIXME: These can't be constexpr due to the calls reaching the compiler's
* step limit.
*/
alignas(16) const auto bsinc12_table = GenerateBSincCoeffs<bsinc12_hdr.total_size>(bsinc12_hdr);
alignas(16) const auto bsinc24_table = GenerateBSincCoeffs<bsinc24_hdr.total_size>(bsinc24_hdr);
constexpr BSincTable GenerateBSincTable(const BSincHeader &hdr, const float *tab)
{
BSincTable ret{};
ret.scaleBase = static_cast<float>(hdr.scaleBase);
ret.scaleRange = static_cast<float>(1.0 / hdr.scaleRange);
for(int i{0};i < BSincScaleCount;++i)
ret.m[i] = static_cast<unsigned int>(((hdr.a[i]*2) + 3) & ~3);
ret.filterOffset[0] = 0;
for(int i{1};i < BSincScaleCount;++i)
ret.filterOffset[i] = ret.filterOffset[i-1] + ret.m[i-1]*4*BSincPhaseCount;
ret.Tab = tab;
return ret;
}
} // namespace
const BSincTable bsinc12{GenerateBSincTable(bsinc12_hdr, &bsinc12_table.front())};
const BSincTable bsinc24{GenerateBSincTable(bsinc24_hdr, &bsinc24_table.front())};
| 31.50519
| 97
| 0.577924
|
hporro
|
d34c7917525df38039e1a69a08689de9bd8e14a8
| 299
|
cpp
|
C++
|
C语言程序设计基础/24.【中学】找出最大素数.cpp
|
xiabee/BIT-CS
|
5d8d8331e6b9588773991a872c259e430ef1eae1
|
[
"Apache-2.0"
] | 63
|
2021-01-10T02:32:17.000Z
|
2022-03-30T04:08:38.000Z
|
C语言程序设计基础/24.【中学】找出最大素数.cpp
|
xiabee/BIT-CS
|
5d8d8331e6b9588773991a872c259e430ef1eae1
|
[
"Apache-2.0"
] | 2
|
2021-06-09T05:38:58.000Z
|
2021-12-14T13:53:54.000Z
|
C语言程序设计基础/24.【中学】找出最大素数.cpp
|
xiabee/BIT-CS
|
5d8d8331e6b9588773991a872c259e430ef1eae1
|
[
"Apache-2.0"
] | 20
|
2021-01-12T11:49:36.000Z
|
2022-03-26T11:04:58.000Z
|
#include <stdio.h>
int is_sushu(int n)
{
int i;
for ( i = 2; i*i <= n; i++)
if (n % i == 0) return 0;
if (i*i > n) return 1;
}
int main()
{
int n;
scanf ("%d", &n);
for (; n >= 0; n--)
{
if ( is_sushu(n) == 1)
{
printf ("The max prime number is %d.\n", n);
break;
}
}
}
| 13.590909
| 47
| 0.448161
|
xiabee
|
d3578be326b1fd5095191108bfe615b4a133cbec
| 842
|
cpp
|
C++
|
AdvancedCpp/StacksAndQueues/src/main.cpp
|
SebastianTirado/Cpp-Learning-Archive
|
fb83379d0cc3f9b2390cef00119464ec946753f4
|
[
"MIT"
] | 19
|
2019-09-15T12:23:51.000Z
|
2020-06-18T08:31:26.000Z
|
AdvancedCpp/StacksAndQueues/src/main.cpp
|
SebastianTirado/Cpp-Learning-Archive
|
fb83379d0cc3f9b2390cef00119464ec946753f4
|
[
"MIT"
] | 15
|
2021-12-07T06:46:03.000Z
|
2022-01-31T07:55:32.000Z
|
AdvancedCpp/StacksAndQueues/src/main.cpp
|
SebastianTirado/Cpp-Learning-Archive
|
fb83379d0cc3f9b2390cef00119464ec946753f4
|
[
"MIT"
] | 13
|
2019-06-29T02:58:27.000Z
|
2020-05-07T08:52:22.000Z
|
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
class Test
{
string name;
public:
explicit Test(string name) : name(name)
{
}
~Test()
{
}
void print() const
{
cout << name << endl;
}
};
int main(int argc, char const *argv[])
{
//LIFO
stack<Test> testStack;
testStack.push(Test("Mike"));
testStack.push(Test("John"));
testStack.push(Test("Sue"));
cout << endl;
Test &test1 = testStack.top();
test1.print();
testStack.pop();
Test &test2 = testStack.top();
test2.print();
//FIFO
queue<Test> testQueue;
testQueue.push(Test("Mike"));
testQueue.push(Test("John"));
testQueue.push(Test("Sue"));
cout << endl;
testQueue.back().print();
while(testQueue.size() > 0)
{
Test &test = testQueue.front();
test.print();
testQueue.pop();
}
return 0;
}
| 12.953846
| 40
| 0.624703
|
SebastianTirado
|
d35c3d9a0a0767dccb5c2102fa6638f166482347
| 6,748
|
cpp
|
C++
|
Source/Ilum/Renderer/RenderPass/Shading/Deferred/MeshPass.cpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | 11
|
2022-01-09T05:32:56.000Z
|
2022-03-28T06:35:16.000Z
|
Source/Ilum/Renderer/RenderPass/Shading/Deferred/MeshPass.cpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | null | null | null |
Source/Ilum/Renderer/RenderPass/Shading/Deferred/MeshPass.cpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | 1
|
2021-11-20T15:39:03.000Z
|
2021-11-20T15:39:03.000Z
|
#include "MeshPass.hpp"
#include "Renderer/Renderer.hpp"
#include <imgui.h>
namespace Ilum::pass
{
MeshPass::MeshPass(bool jitter):
m_jitter(jitter)
{
}
void MeshPass::setupPipeline(PipelineState &state)
{
std::vector<std::string> macros;
if (m_jitter)
{
macros.push_back("USE_JITTER");
}
state.shader.load(std::string(PROJECT_SOURCE_DIR) + "Source/Shaders/Shading/Deferred/Mesh.hlsl", VK_SHADER_STAGE_TASK_BIT_NV, Shader::Type::HLSL, "ASmain");
state.shader.load(std::string(PROJECT_SOURCE_DIR) + "Source/Shaders/Shading/Deferred/Mesh.hlsl", VK_SHADER_STAGE_MESH_BIT_NV, Shader::Type::HLSL, "MSmain", macros);
state.shader.load(std::string(PROJECT_SOURCE_DIR) + "Source/Shaders/Shading/Deferred/Mesh.hlsl", VK_SHADER_STAGE_FRAGMENT_BIT, Shader::Type::HLSL, "PSmain");
state.dynamic_state.dynamic_states = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR};
state.color_blend_attachment_states.resize(4);
state.depth_stencil_state.stencil_test_enable = false;
// Disable blending
for (auto &color_blend_attachment_state : state.color_blend_attachment_states)
{
color_blend_attachment_state.blend_enable = false;
}
state.rasterization_state.polygon_mode = VK_POLYGON_MODE_FILL;
state.descriptor_bindings.bind(0, 0, "PerInstanceBuffer", VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
state.descriptor_bindings.bind(0, 1, "PerMeshletBuffer", VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
state.descriptor_bindings.bind(0, 2, "Camera", VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
state.descriptor_bindings.bind(0, 3, "Vertices", VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
state.descriptor_bindings.bind(0, 5, "CullingBuffer", VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
state.descriptor_bindings.bind(0, 6, "MeshletVertexBuffer", VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
state.descriptor_bindings.bind(0, 7, "MeshletIndexBuffer", VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
state.descriptor_bindings.bind(0, 8, "CountBuffer", VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
state.descriptor_bindings.bind(0, 9, "MaterialBuffer", VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
state.descriptor_bindings.bind(0, 10, "TextureArray", ImageViewType::Native, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
state.descriptor_bindings.bind(0, 11, "TexSampler", Renderer::instance()->getSampler(Renderer::SamplerType::Trilinear_Wrap), VK_DESCRIPTOR_TYPE_SAMPLER);
// GBuffer0: RGB - Albedo, A - metallic
// GBuffer1: RGA - normal, A - linear depth
// GBuffer2: RGB - emissive, A - roughness
// GBuffer3: R - entity id, G - instance id, BA - motion vector
state.declareAttachment("GBuffer0", VK_FORMAT_R8G8B8A8_UNORM, Renderer::instance()->getRenderTargetExtent().width, Renderer::instance()->getRenderTargetExtent().height);
state.declareAttachment("GBuffer1", VK_FORMAT_R16G16B16A16_SFLOAT, Renderer::instance()->getRenderTargetExtent().width, Renderer::instance()->getRenderTargetExtent().height);
state.declareAttachment("GBuffer2", VK_FORMAT_R8G8B8A8_UNORM, Renderer::instance()->getRenderTargetExtent().width, Renderer::instance()->getRenderTargetExtent().height);
state.declareAttachment("GBuffer3", VK_FORMAT_R16G16B16A16_SFLOAT, Renderer::instance()->getRenderTargetExtent().width, Renderer::instance()->getRenderTargetExtent().height);
state.declareAttachment("DepthStencil", VK_FORMAT_D32_SFLOAT_S8_UINT, Renderer::instance()->getRenderTargetExtent().width, Renderer::instance()->getRenderTargetExtent().height);
VkClearColorValue clear_color = {};
clear_color.uint32[3] = static_cast<uint32_t>(entt::null);
clear_color.float32[3] = std::numeric_limits<float>::max();
state.addOutputAttachment("GBuffer0", AttachmentState::Clear_Color);
state.addOutputAttachment("GBuffer1", AttachmentState::Clear_Color);
state.addOutputAttachment("GBuffer2", AttachmentState::Clear_Color);
state.addOutputAttachment("GBuffer3", AttachmentState::Clear_Color);
state.addOutputAttachment("DepthStencil", VkClearDepthStencilValue{1.f, 0u});
}
void MeshPass::resolveResources(ResolveState &resolve)
{
resolve.resolve("PerInstanceBuffer", Renderer::instance()->Render_Buffer.Instance_Buffer);
resolve.resolve("PerMeshletBuffer", Renderer::instance()->Render_Buffer.Meshlet_Buffer);
resolve.resolve("Camera", Renderer::instance()->Render_Buffer.Camera_Buffer);
resolve.resolve("Vertices", Renderer::instance()->Render_Buffer.Static_Vertex_Buffer);
resolve.resolve("CullingBuffer", Renderer::instance()->Render_Buffer.Culling_Buffer);
resolve.resolve("MeshletVertexBuffer", Renderer::instance()->Render_Buffer.Meshlet_Vertex_Buffer);
resolve.resolve("MeshletIndexBuffer", Renderer::instance()->Render_Buffer.Meshlet_Index_Buffer);
resolve.resolve("CountBuffer", Renderer::instance()->Render_Buffer.Count_Buffer);
resolve.resolve("MaterialBuffer", Renderer::instance()->Render_Buffer.Material_Buffer);
}
void MeshPass::render(RenderPassState &state)
{
std::memcpy(&Renderer::instance()->Render_Stats.static_mesh_count.instance_visible, reinterpret_cast<uint32_t *>(Renderer::instance()->Render_Buffer.Count_Buffer.map()) + 3, sizeof(uint32_t));
std::memcpy(&Renderer::instance()->Render_Stats.static_mesh_count.meshlet_visible, reinterpret_cast<uint32_t *>(Renderer::instance()->Render_Buffer.Count_Buffer.map()) + 2, sizeof(uint32_t));
Renderer::instance()->Render_Buffer.Count_Buffer.unmap();
auto &cmd_buffer = state.command_buffer;
VkRenderPassBeginInfo begin_info = {};
begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
begin_info.renderPass = state.pass.render_pass;
begin_info.renderArea = state.pass.render_area;
begin_info.framebuffer = state.pass.frame_buffer;
begin_info.clearValueCount = static_cast<uint32_t>(state.pass.clear_values.size());
begin_info.pClearValues = state.pass.clear_values.data();
vkCmdBeginRenderPass(cmd_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(cmd_buffer, state.pass.bind_point, state.pass.pipeline);
auto &extent = Renderer::instance()->getRenderTargetExtent();
VkViewport viewport = {0, static_cast<float>(extent.height), static_cast<float>(extent.width), -static_cast<float>(extent.height), 0, 1};
VkRect2D scissor = {0, 0, extent.width, extent.height};
vkCmdSetViewport(cmd_buffer, 0, 1, &viewport);
vkCmdSetScissor(cmd_buffer, 0, 1, &scissor);
for (auto &descriptor_set : state.pass.descriptor_sets)
{
vkCmdBindDescriptorSets(cmd_buffer, state.pass.bind_point, state.pass.pipeline_layout, descriptor_set.index(), 1, &descriptor_set.getDescriptorSet(), 0, nullptr);
}
vkCmdDrawMeshTasksNV(cmd_buffer, (Renderer::instance()->Render_Stats.static_mesh_count.meshlet_count + 32 - 1) / 32, 0);
vkCmdEndRenderPass(cmd_buffer);
}
void MeshPass::onImGui()
{
}
} // namespace Ilum::pass
| 52.310078
| 193
| 0.783491
|
Chaf-Libraries
|
d35e146e39b63c0929e92cdc048d3c8d28bbf1a4
| 15,443
|
cc
|
C++
|
trader-desk/chart.cc
|
HitHub1991/-dmbcs-trader-desk
|
365ad5a560564220398ba8ab4b900eb1ca26c8cd
|
[
"FSFAP"
] | 6
|
2020-03-23T12:32:32.000Z
|
2022-01-02T22:17:12.000Z
|
trader-desk/chart.cc
|
HitHub1991/-dmbcs-trader-desk
|
365ad5a560564220398ba8ab4b900eb1ca26c8cd
|
[
"FSFAP"
] | null | null | null |
trader-desk/chart.cc
|
HitHub1991/-dmbcs-trader-desk
|
365ad5a560564220398ba8ab4b900eb1ca26c8cd
|
[
"FSFAP"
] | 1
|
2022-02-27T19:07:50.000Z
|
2022-02-27T19:07:50.000Z
|
/*
* Copyright (c) 2017, 2020 Dale Mellor
*
* This file is part of the trader-desk package.
*
* The trader-desk package is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* The trader-desk package is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
#include <trader-desk/chart.h>
#include <iomanip>
#include <set>
/** \file
*
* Implementation of the \c Chart class. */
namespace DMBCS::Trader_Desk {
Chart::Chart (uint32_t const features_, Preferences& P)
: features (features_)
{
data . changed_signal . connect ([this] { queue_draw (); });
/* Big enough for at least a thumb; we will take up more space if we're
* offered it. */
set_size_request (40, 25);
if (features & Feature::CROSS_HAIRS)
add_events (Gdk::POINTER_MOTION_MASK | Gdk::LEAVE_NOTIFY_MASK
| Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK);
if (features & Feature::ANALYZERS)
analyzer = make_unique<Analyzer_Stack> (data, P);
}
bool Chart::on_motion_notify_event (GdkEventMotion *const motion)
{
if (features & Feature::CROSS_HAIRS)
{
if (analyzer)
analyzer->button_move (motion->x, motion->y);
pointer_x = (int) motion->x;
pointer_y = (int) motion->y;
queue_draw ();
}
return 1;
}
bool Chart::on_leave_notify_event (GdkEventCrossing *const)
{
pointer_x = pointer_y = -1;
queue_draw ();
return 1;
}
bool Chart::on_button_press_event (GdkEventButton *const event)
{
return features & Feature::CROSS_HAIRS
&& analyzer
&& analyzer->button_down (event->x, event->y);
}
bool Chart::on_button_release_event (GdkEventButton *const event)
{
return features & Feature::CROSS_HAIRS
&& analyzer
&& analyzer->button_up (event->x, event->y);
}
/* !! We really want to paint most of the chart into memory, and map it
* to the screen as required. But we need to re-assess all the
* tide-marks on the cursor line whenever the cursor moves. */
bool Chart::on_draw (const Cairo::RefPtr<Cairo::Context>& cairo)
{
/* This object is constructed as we draw the various aspects of the
* chart, and then it is rendered on top of everything else right at
* the end of this method. */
Tide_Mark::List tide_marks;
/*************** Set up the canvas. **************************/
Chart_Context canvas;
{
const Gtk::Allocation allocation {get_allocation ()};
canvas.width = allocation.get_width ();
canvas.height = allocation.get_height ();
}
canvas.left_border = features & (int) Feature::AXIS_LABELS ? 45 : 4;
canvas.bottom_border = features & (int) Feature::AXIS_LABELS ? 40 : 4;
canvas.top_border = 4;
canvas.right_border = 4;
canvas.cairo = cairo;
canvas.pango = Pango::Layout::create (canvas.cairo);
canvas.pango -> set_font_description (Pango::FontDescription ("Sans 7"));
canvas.set_source_rgb (data.unaccurate ? Colour::NO_DATA_REGION
: Colour::CHART_BACKGROUND);
canvas.cairo -> paint ();
canvas.outline = data.extremes;
double const space = 0.05 * (canvas.outline.max_value
- canvas.outline.min_value);
canvas.outline.min_value -= space;
canvas.outline.max_value += space;
if (analyzer)
analyzer->stretch_outline (canvas.outline);
auto cursor_mark
= Tide_Mark::price_marker
(canvas.date (pointer_x),
canvas.outline.contains ({ canvas.date (pointer_x),
canvas.value (pointer_y)})
? Colour::CURSOR_TIDES
: Colour::NO_DISPLAY);
auto current_mark = Tide_Mark::price_marker (canvas.outline.end_time,
Colour::CHART_BACKGROUND);
canvas.cairo->set_line_width (1.0);
/************************ No-data region. *******************************/
{
auto const r = data.prices.empty () ? canvas.outline.end_time
: data.prices.back ().time;
if (r > canvas.outline.start_time)
{
canvas.set_source_rgb (Colour::NO_DATA_REGION);
canvas.move_to ({canvas.outline.start_time,
canvas.outline.min_value});
canvas.line_to ({canvas.outline.start_time,
canvas.outline.max_value});
canvas.line_to ({r, canvas.outline.max_value});
canvas.line_to ({r, canvas.outline.min_value});
canvas.cairo->fill ();
}
}
/*********** Let the analyzers draw themselves. *************/
if (analyzer)
analyzer->graph_draw_hook (canvas,
tide_marks,
data.number_shares,
{cursor_mark, current_mark});
/******** X-axis *******/
if (features & Feature::AXIS_LABELS)
{
canvas.set_source_rgb (Colour::TIME_AXIS);
char buffer [200];
auto const *disc = Date_Axis::discretization;
time_t const t = chrono::system_clock::to_time_t
(data.extremes.end_time);
for (; disc->format; ++disc)
{
/* If the spacing between ticks is less than one pixel,
* move on. */
if (disc->real_interval.count ()
/ double ((data.extremes.end_time
- data.extremes.start_time).count ())
* (canvas.width - canvas.left_border
- canvas.right_border)
< 1.0)
continue;
/* Find the box needed to enclose a label showing the
* current time. */
strftime (buffer, sizeof (buffer),
disc->format,
localtime (&t));
canvas.pango->set_text (buffer);
Pango::Rectangle const rect
= canvas.pango->get_pixel_logical_extents ();
/* If the spacing between ticks is more than the space
* required to display the current date-time, then this is
* the tick spacing we will use. */
if (disc->real_interval.count ()
/ double ((data.extremes.end_time
- data.extremes.start_time).count ())
* (canvas.width - canvas.left_border
- canvas.right_border)
> rect.get_width () + 4)
break;
}
auto show_ticks = [&canvas, this]
(Date_Axis::Discretization const &disc,
uint32_t const &line_offset)
{
char buffer [200];
for (auto i = data.extremes.start_time;
i <= data.extremes.end_time;
i += disc.interval)
{
i = disc.round_down (i);
if (i > data.extremes.start_time)
{
auto i_ = chrono::system_clock::to_time_t (i);
strftime (buffer, sizeof (buffer),
disc.format,
localtime (&i_));
canvas.pango->set_text (buffer);
canvas.move_to ({i, canvas.outline.min_value});
canvas.cairo->rel_move_to (0, line_offset + 1);
canvas.pango->add_to_cairo_context (canvas.cairo);
canvas.cairo->fill ();
}
}
};
if (disc->format)
{
show_ticks (*disc, 0);
if ((disc + 1)->format)
{
show_ticks (*(disc + 1), 11);
if ((disc + 2)->format)
show_ticks (*(disc + 2), 22);
}
}
}
/******** Y-axis ********/
canvas.pango
->set_markup (string {"<span size=\"large\">"}
+ pgettext ("Label", "Position value (pounds)")
+ "</span>");
const Pango::Rectangle extents
= canvas.pango->get_pixel_logical_extents ();
const int font_height = extents.get_height ();
if (features & (int) Feature::AXIS_LABELS)
{
canvas.cairo->save ();
canvas.cairo->rotate (- M_PI / 2.0);
canvas.cairo->move_to (- (canvas.height - extents.get_width ())
/ 2,
1);
canvas.pango->add_to_cairo_context (canvas.cairo);
canvas.set_source_rgb (Colour::PRICE_AXIS);
canvas.cairo->fill ();
canvas.cairo->restore ();
}
if (features & (int) Feature::AXIS_LABELS)
{
double const share_scale = data.number_shares / 100.0;
double inc = 0.01;
for (inc = 0.01;
(inc / share_scale) / (canvas.outline.max_value
- canvas.outline.min_value)
* (canvas.height - canvas.bottom_border
- canvas.top_border)
< font_height * 1.0;
inc *= 10.0) ;
for (double b = inc * (floor (share_scale
* canvas.outline.min_value
/ inc)
+ 1);
b < share_scale * canvas.outline.max_value;
b += inc)
if (b / share_scale > canvas.outline.min_value)
{
ostringstream out;
out << setw (5) << b;
canvas.pango->set_text (out.str ());
Pango::Rectangle const extents
= canvas.pango->get_pixel_logical_extents ();
canvas.move_to ({data.extremes.start_time,
b / share_scale});
canvas.cairo->rel_move_to (- extents.get_width () - 2,
- extents.get_height () / 2);
canvas.pango->add_to_cairo_context (canvas.cairo);
canvas.set_source_rgb (Colour::PRICE_AXIS);
canvas.cairo->fill ();
}
}
if (data.prices.empty ())
{
if (features & Feature::COMPANY_NAME)
canvas.add (canvas.text,
data.company_name,
Colour::COMPANY_NAME_TITLE,
{ canvas.left_border, canvas.top_border });
canvas.render (canvas.text);
return 1;
}
canvas.set_source_rgb (Colour::PRICE_AXIS);
canvas.move_to ({data.extremes.start_time, canvas.outline.max_value});
canvas.line_to ({data.extremes.start_time, canvas.outline.min_value});
canvas.cairo->stroke ();
canvas.set_source_rgb (Colour::TIME_AXIS);
canvas.move_to ({data.extremes.start_time, canvas.outline.min_value});
canvas.line_to ({data.extremes.end_time, canvas.outline.min_value});
canvas.cairo->stroke ();
{
lock_guard<mutex> l {data.prices_mutex};
canvas.draw_time_series (data.prices, Colour::PRICE_GRAPH, 1.0);
tide_marks.emplace_back (current_mark (data.prices.front ().price,
Colour::PRICE_TIDES));
tide_marks.emplace_back (cursor_mark (data.prices.interpolated_value
(canvas.date (pointer_x)),
Colour::PRICE_TIDES));
}
if (features & Feature::CROSS_HAIRS)
tide_marks.emplace_back (cursor_mark (canvas.value (pointer_y),
Colour::CURSOR_TIDES));
/**** Company name ****/
if (features & Feature::COMPANY_NAME)
canvas.add (canvas.text,
data.company_name,
Colour::COMPANY_NAME_TITLE,
canvas.x ({data.extremes.start_time,
canvas.outline.max_value}));
/***** Tide marks. *****/
if (features & Feature::TIDE_MARKS)
{
set <Time_Point> dates_shown;
for (auto const &tide : tide_marks)
if (tide.temporal_colour != Colour::NO_DISPLAY
&& tide.time >= canvas.outline.start_time
&& tide.time <= canvas.outline.end_time)
{
canvas.cairo
->set_source_rgb
(1.0 - 0.5 * (1.0 - tide.value_colour.red),
1.0 - 0.5 * (1.0 - tide.value_colour.green),
1.0 - 0.5 * (1.0 - tide.value_colour.blue));
canvas.move_to ({canvas.outline.start_time, tide.price});
canvas.line_to ({canvas.outline.end_time, tide.price});
canvas.cairo->stroke ();
ostringstream hold;
hold << tide.price;
canvas.add (canvas.text,
hold.str (),
tide.value_colour,
{canvas.x (tide.time) + 20,
canvas.y (tide.price) - 13});
ostringstream hold_2;
hold_2 << data.number_shares * tide.price / 100.0;
canvas.add (canvas.text,
hold_2.str (),
tide.value_colour,
{canvas.x (tide.time) - 60,
canvas.y (tide.price) - 13});
if (dates_shown.insert (tide.time).second)
{
canvas.set_source_rgb (tide.temporal_colour);
canvas.move_to ({tide.time, canvas.outline.max_value});
canvas.line_to ({tide.time, canvas.outline.min_value});
canvas.cairo->stroke ();
struct tm tm;
time_t t = chrono::system_clock::to_time_t (tide.time);
localtime_r (&t, &tm);
char buffer [200];
strftime (buffer, sizeof (buffer), "%Y-%m-%d %H:%M", &tm);
canvas.add (canvas.text,
buffer,
Colour::CURSOR_TIDES,
{canvas.x (tide.time) + 2,
canvas.height - canvas.bottom_border
- 12});
}
}
}
canvas.render (canvas.text);
return 1;
} /* End of on_draw method. */
} /* End of namespace DMBCS::Trader_Desk. */
| 31.907025
| 79
| 0.502364
|
HitHub1991
|
d35ff97428c38b8c54774a3b9d974c990bb83677
| 747
|
hpp
|
C++
|
inc/SceneObjects/Plateau.hpp
|
KPO-2020-2021/zad5_2-delipl
|
b4bd2e673c8b7e92e85aed10919427a6704353ca
|
[
"Unlicense"
] | 1
|
2022-03-08T03:16:48.000Z
|
2022-03-08T03:16:48.000Z
|
inc/SceneObjects/Plateau.hpp
|
KPO-2020-2021/zad5_2-delipl
|
b4bd2e673c8b7e92e85aed10919427a6704353ca
|
[
"Unlicense"
] | null | null | null |
inc/SceneObjects/Plateau.hpp
|
KPO-2020-2021/zad5_2-delipl
|
b4bd2e673c8b7e92e85aed10919427a6704353ca
|
[
"Unlicense"
] | null | null | null |
/**
* @file Plateau.hpp
* @author Delicat Jakub (delicat.kuba@gmail.com)
* @brief File describes obstacle like Plateau class
* @version 0.1
* @date 2021-06-24
*
* @copyright Copyright (c) 2021
*
*/
#ifndef PLATEAU_HPP
#define PLATEAU_HPP
#include "Cuboid.hpp"
/**
* @brief Plateau obstacle
*
*/
class Plateau : public Cuboid
{
public:
/**
* @brief Construct a new Plateau object
*
* @param position of Plateau
* @param width of Plateau
* @param lenght of Plateau
*/
Plateau(const Vector3 &position, const double &width, const double &length) : Cuboid(Vector3({width, length, width}) / 10, position){};
virtual ~Plateau() {}
bool CanLand() const override { return true; }
};
#endif
| 20.189189
| 139
| 0.643909
|
KPO-2020-2021
|
d362c50a81c7d34d9a2aab11c8e989aeb3fc2355
| 1,055
|
cc
|
C++
|
modules/ugdk-core/src/time/timeaccumulator.cc
|
uspgamedev/ugdk
|
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
|
[
"Zlib"
] | 11
|
2015-03-06T13:14:32.000Z
|
2020-06-09T23:34:28.000Z
|
modules/ugdk-core/src/time/timeaccumulator.cc
|
uspgamedev/ugdk
|
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
|
[
"Zlib"
] | 62
|
2015-01-04T05:47:40.000Z
|
2018-06-15T17:00:25.000Z
|
modules/ugdk-core/src/time/timeaccumulator.cc
|
uspgamedev/ugdk
|
95885a70df282a8e8e6e5c72b28a7f2f21bf7e99
|
[
"Zlib"
] | 2
|
2017-04-05T20:35:49.000Z
|
2017-07-30T03:44:02.000Z
|
#include <ugdk/time/timeaccumulator.h>
#include "SDL.h"
#include "SDL_timer.h"
#include <ugdk/time/module.h>
namespace ugdk {
namespace time {
TimeAccumulator::TimeAccumulator(int duration_miliseconds) {
Restart(duration_miliseconds);
}
int TimeAccumulator::TimeLeft() {
return duration_ - (manager().TimeSince(initial_time_) - time_paused_);
}
bool TimeAccumulator::Expired() {
if(when_paused_ == 0)
return TimeLeft() <= 0;
return 0;
}
void TimeAccumulator::Restart() {
Restart(duration_);
}
void TimeAccumulator::Restart(int duration) {
initial_time_ = manager().TimeElapsed();
duration_ = (uint32) duration;
time_paused_ = when_paused_ = 0;
}
void TimeAccumulator::Pause() {
if(when_paused_ == 0)
when_paused_ = manager().TimeElapsed();
}
void TimeAccumulator::Resume() {
if(when_paused_ > 0) {
time_paused_ += manager().TimeSince(when_paused_);
when_paused_ = 0;
}
}
bool TimeAccumulator::IsPaused() {
return when_paused_ > 0;
}
} // namespace time
} // namespace ugdk
| 19.90566
| 75
| 0.686256
|
uspgamedev
|
d3641e25f8c24bf81589940c825c3aa53256ed88
| 2,456
|
cpp
|
C++
|
src/main.cpp
|
TheDoctor314/tetris
|
43875a617e263e8ab727405b7d38a6d11db1510d
|
[
"Unlicense"
] | null | null | null |
src/main.cpp
|
TheDoctor314/tetris
|
43875a617e263e8ab727405b7d38a6d11db1510d
|
[
"Unlicense"
] | null | null | null |
src/main.cpp
|
TheDoctor314/tetris
|
43875a617e263e8ab727405b7d38a6d11db1510d
|
[
"Unlicense"
] | null | null | null |
#include <SFML/Graphics.hpp>
#include <chrono>
#include "game.hpp"
#include "grid.hpp"
#include "input.hpp"
#include "tetromino.hpp"
using namespace tetris;
void draw_grid(const GameGrid &grid, sf::RenderWindow &window,
sf::Shape &shape);
void draw_game_over(sf::RenderWindow &window, sf::Font &font);
template<std::size_t SIZE>
void clear_lines(GameGrid &grid, const std::array<bool, SIZE> lines_to_clear);
int main() {
sf::RenderWindow window(
sf::VideoMode(COLS * CELL_WIDTH * 2, ROWS * CELL_HEIGHT * 2), "Tetris");
window.setVerticalSyncEnabled(true);
auto grid_view =
sf::View(sf::FloatRect(0, 0, COLS * CELL_WIDTH, ROWS * CELL_HEIGHT));
window.setView(grid_view);
sf::RectangleShape shape{sf::Vector2f(CELL_WIDTH, CELL_HEIGHT)};
shape.setOutlineColor(sf::Color::Black);
shape.setOutlineThickness(-1);
sf::Font font;
font.loadFromFile("Roboto-Medium.ttf");
auto previous_time = std::chrono::steady_clock::now();
unsigned lag = 0;
Game game{};
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
using sf::Event;
using sf::Keyboard;
case Event::Closed:
window.close();
break;
case Event::KeyPressed:
switch (event.key.code) {
case Keyboard::Q:
window.close();
break;
case Keyboard::Enter:
game = Game{};
break;
default:
game.handle_key_down(event.key.code);
break;
}
break;
case Event::KeyReleased:
game.handle_key_up(event.key.code);
break;
default:
break;
}
}
auto delta_time = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - previous_time)
.count();
lag += delta_time;
previous_time += std::chrono::microseconds(delta_time);
while (lag > FRAME_DURATION) {
lag -= FRAME_DURATION;
game.update();
}
window.clear();
game.draw(window, shape, font);
window.display();
}
return 0;
}
| 26.408602
| 80
| 0.532166
|
TheDoctor314
|
d36691306ef5b9f2489b71badaa8d37eeeda3678
| 3,749
|
cpp
|
C++
|
cg/src/graph/SceneObjectBuilder.cpp
|
MachSilva/Ds
|
a7da3d4ca3b00b19884bc64d9d7baefea809cb3d
|
[
"Zlib"
] | 2
|
2021-11-23T18:36:51.000Z
|
2021-11-24T19:38:25.000Z
|
cg/src/graph/SceneObjectBuilder.cpp
|
MachSilva/Ds
|
a7da3d4ca3b00b19884bc64d9d7baefea809cb3d
|
[
"Zlib"
] | 1
|
2022-02-12T20:47:59.000Z
|
2022-03-17T02:03:25.000Z
|
cg/src/graph/SceneObjectBuilder.cpp
|
MachSilva/Ds
|
a7da3d4ca3b00b19884bc64d9d7baefea809cb3d
|
[
"Zlib"
] | 1
|
2022-02-12T22:31:50.000Z
|
2022-02-12T22:31:50.000Z
|
//[]---------------------------------------------------------------[]
//| |
//| Copyright (C) 2022 Paulo Pagliosa. |
//| |
//| 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. |
//| |
//[]---------------------------------------------------------------[]
//
// OVERVIEW: SceneObjectBuilder.cpp
// ========
// Source file for scene object builder.
//
// Author: Paulo Pagliosa
// Last revision: 10/02/2022
#include "graph/SceneObjectBuilder.h"
#include "graphics/Assets.h"
namespace cg::graph
{ // begin namespace cg::graph
static inline auto
empty(const char* s)
{
return s == nullptr || *s == 0;
}
/////////////////////////////////////////////////////////////////////
//
// SceneObjectBuilder implementation
// ==================
void
SceneObjectBuilder::setScene(Scene& scene)
{
_scene = &scene;
_objectId = _cameraId = _lightId = _materialId = _primitiveId = 0;
}
SceneObject*
SceneObjectBuilder::createEmptyObject()
{
auto object = SceneObject::New(*_scene);
object->setName("Object %d", ++_objectId);
return object;
}
SceneObject*
SceneObjectBuilder::createCameraObject(float aspect, const char* name)
{
auto object = SceneObject::New(*_scene);
if (!empty(name))
object->setName(name);
else
object->setName("Camera %d", ++_cameraId);
auto camera = new Camera{aspect};
object->addComponent(CameraProxy::New(*camera));
CameraProxy::setCurrent(camera);
return object;
}
SceneObject*
SceneObjectBuilder::createLightObject(Light::Type type, const char* name)
{
auto object = SceneObject::New(*_scene);
if (!empty(name))
object->setName(name);
else
object->setName("Light %d", ++_lightId);
auto light = new Light;
light->setType(type);
object->addComponent(LightProxy::New(*light));;
return object;
}
SceneObject*
SceneObjectBuilder::createPrimitiveObject(const TriangleMesh& mesh,
const std::string& meshName)
{
auto object = SceneObject::New(*_scene);
object->setName("%s %d", meshName.c_str(), ++_primitiveId);
object->addComponent(makePrimitive(mesh, meshName));
return object;
}
Material*
SceneObjectBuilder::createMaterial()
{
auto material = new Material{Color::white};
material->setName("Material %d", ++_materialId);
Assets::materials().emplace(material->name(), material);
return material;
}
} // end namespace cg::graph
| 30.729508
| 73
| 0.552681
|
MachSilva
|
d3687c6c7fbd00aed4d9e1675e8efd823a2eb8d3
| 1,280
|
hpp
|
C++
|
include/MtlMaterial.hpp
|
andreasbank/MtlReader
|
3f3b71dce520eaaab3bebbbf071ad85d6ff66479
|
[
"MIT"
] | null | null | null |
include/MtlMaterial.hpp
|
andreasbank/MtlReader
|
3f3b71dce520eaaab3bebbbf071ad85d6ff66479
|
[
"MIT"
] | null | null | null |
include/MtlMaterial.hpp
|
andreasbank/MtlReader
|
3f3b71dce520eaaab3bebbbf071ad85d6ff66479
|
[
"MIT"
] | null | null | null |
/**
* @copyright 2017 Andreas Bank, andreas.mikael.bank@gmail.com
*/
#ifndef MTLMATERIAL_HPP
#define MTLMATERIAL_HPP
#include <string>
#include "MtlMap.hpp"
class MtlObject;
struct MtlColor {
float red, green, blue;
};
class MtlMaterial {
public:
MtlMaterial(const std::string& matName = std::string());
void printProperties(const std::string& prefix = std::string(),
bool isLast = false);
std::string name; // newmtl (string)
MtlColor ambientColor, diffuseColor, specularColor; // Ka, Kd, Ks (3 * [0 - 1])
MtlColor transformFilter; // Tf (3 * [0 - 1])
int illumination; // illum (0 - 10) (predefined meaning, enum)
float dissolve; // d (0.0 - 1.0)
bool dissolveHalo; // -halo (true if 'd' has '-halo' option, else false)
int specularExponent; // Ns (0 - 1000)
int sharpness; // sharpness (0 - 1000)
float opticalDensity; // Ni (0.001 - 10.0)
MtlMap mapAmbientColor; // map_Ka (options filename)
MtlMap mapDiffuseColor; // map_Kd (options filename)
MtlMap mapSpecularColor; // map_Ks (options filename)
MtlMap mapSpecularExponent; // map_Ns (options filename)
bool mapAntiAliasingTextures; // map_aat (on)
MtlMap decal; // decal (options filename)
MtlMap disposition; //disp (options filename)
};
#endif /* MTLMATERIAL_HPP */
| 29.767442
| 81
| 0.691406
|
andreasbank
|
d36ab9f0209b2d1d352471056ac2b4d9f7d1abe8
| 36
|
cc
|
C++
|
chapter-11/11.3.cc
|
hongmi/cpp-primer-4-exercises
|
98ddb98b41d457a1caa525d246dfb7453be0c8d2
|
[
"MIT"
] | 1
|
2017-04-01T06:57:30.000Z
|
2017-04-01T06:57:30.000Z
|
chapter-11/11.3.cc
|
hongmi/cpp-primer-4-exercises
|
98ddb98b41d457a1caa525d246dfb7453be0c8d2
|
[
"MIT"
] | null | null | null |
chapter-11/11.3.cc
|
hongmi/cpp-primer-4-exercises
|
98ddb98b41d457a1caa525d246dfb7453be0c8d2
|
[
"MIT"
] | null | null | null |
accumulate(vi.begin(), vi.end(), 0)
| 18
| 35
| 0.638889
|
hongmi
|
d36e4ca5f98caa992757e1e17c3db5e5da87c34f
| 2,097
|
cpp
|
C++
|
src/modules/Eluna/GroupHooks.cpp
|
muscnx/Mangos021SD2
|
695bb6a4822bb9173ab8e9077cb6259869ca2f32
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
src/modules/Eluna/GroupHooks.cpp
|
muscnx/Mangos021SD2
|
695bb6a4822bb9173ab8e9077cb6259869ca2f32
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
src/modules/Eluna/GroupHooks.cpp
|
muscnx/Mangos021SD2
|
695bb6a4822bb9173ab8e9077cb6259869ca2f32
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
/*
* Copyright (C) 2010 - 2015 Eluna Lua Engine <http://emudevs.com/>
* This program is free software licensed under GPL version 3
* Please see the included DOCS/LICENSE.md for more information
*/
#ifndef _GROUP_HOOKS_H
#define _GROUP_HOOKS_H
#include "Hooks.h"
#include "HookHelpers.h"
#include "LuaEngine.h"
#include "ElunaBinding.h"
#include "ElunaTemplate.h"
using namespace Hooks;
void Eluna::OnAddMember(Group* group, uint64 guid)
{
if (!GroupEventBindings->HasEvents(GROUP_EVENT_ON_MEMBER_ADD))
return;
LOCK_ELUNA;
Push(group);
Push(guid);
CallAllFunctions(GroupEventBindings, GROUP_EVENT_ON_MEMBER_ADD);
}
void Eluna::OnInviteMember(Group* group, uint64 guid)
{
if (!GroupEventBindings->HasEvents(GROUP_EVENT_ON_MEMBER_INVITE))
return;
LOCK_ELUNA;
Push(group);
Push(guid);
CallAllFunctions(GroupEventBindings, GROUP_EVENT_ON_MEMBER_INVITE);
}
void Eluna::OnRemoveMember(Group* group, uint64 guid, uint8 method)
{
if (!GroupEventBindings->HasEvents(GROUP_EVENT_ON_MEMBER_REMOVE))
return;
LOCK_ELUNA;
Push(group);
Push(guid);
Push(method);
CallAllFunctions(GroupEventBindings, GROUP_EVENT_ON_MEMBER_REMOVE);
}
void Eluna::OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid)
{
if (!GroupEventBindings->HasEvents(GROUP_EVENT_ON_LEADER_CHANGE))
return;
LOCK_ELUNA;
Push(group);
Push(newLeaderGuid);
Push(oldLeaderGuid);
CallAllFunctions(GroupEventBindings, GROUP_EVENT_ON_LEADER_CHANGE);
}
void Eluna::OnDisband(Group* group)
{
if (!GroupEventBindings->HasEvents(GROUP_EVENT_ON_DISBAND))
return;
LOCK_ELUNA;
Push(group);
CallAllFunctions(GroupEventBindings, GROUP_EVENT_ON_DISBAND);
}
void Eluna::OnCreate(Group* group, uint64 leaderGuid, GroupType groupType)
{
if (!GroupEventBindings->HasEvents(GROUP_EVENT_ON_CREATE))
return;
LOCK_ELUNA;
Push(group);
Push(leaderGuid);
Push(groupType);
CallAllFunctions(GroupEventBindings, GROUP_EVENT_ON_CREATE);
}
#endif // _GROUP_HOOKS_H
| 24.103448
| 84
| 0.733429
|
muscnx
|
d3703728ad37a635aefb171635aaf68355ad2b0f
| 275
|
cpp
|
C++
|
Aula08/ex-02-20.cpp
|
cgcosta/scaling-barnacle
|
2477436768ccb75b66feb6c0a837314f1ffa9dd3
|
[
"MIT"
] | null | null | null |
Aula08/ex-02-20.cpp
|
cgcosta/scaling-barnacle
|
2477436768ccb75b66feb6c0a837314f1ffa9dd3
|
[
"MIT"
] | 1
|
2018-04-27T23:42:44.000Z
|
2018-04-27T23:42:44.000Z
|
Aula08/ex-02-20.cpp
|
cgcosta/scaling-barnacle
|
2477436768ccb75b66feb6c0a837314f1ffa9dd3
|
[
"MIT"
] | null | null | null |
/*
Morgana
*/
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Informe um numero: ";
cin >> n;
if (n % 2 == 0) {
cout << "é par" << endl;
} else {
cout << "é ímpar" << endl;
}
return 0;
}
| 7.432432
| 32
| 0.418182
|
cgcosta
|
d37222fc63ef8ccde5fccae209d09bec965ecb16
| 1,365
|
hpp
|
C++
|
source/common/vulkan/vkcAlloc.hpp
|
a-day-old-bagel/at3
|
868cec7672fd109760cae740b1acf26cec5eb85e
|
[
"MIT"
] | null | null | null |
source/common/vulkan/vkcAlloc.hpp
|
a-day-old-bagel/at3
|
868cec7672fd109760cae740b1acf26cec5eb85e
|
[
"MIT"
] | null | null | null |
source/common/vulkan/vkcAlloc.hpp
|
a-day-old-bagel/at3
|
868cec7672fd109760cae740b1acf26cec5eb85e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdint>
#include <cstdlib>
#include "vkcTypes.hpp"
namespace at3::vkc::passthrough {
struct AllocatorState {
size_t *memTypeAllocSizes;
uint32_t totalAllocs;
Common *context;
};
extern AllocatorState state;
//ALLOCATOR INTERFACE / INSTALLATION
void activate(Common *context);
void alloc(Allocation &outAlloc, AllocationCreateInfo createInfo);
void free(Allocation &handle);
size_t allocatedSize(uint32_t memoryType);
uint32_t numAllocs();
}
namespace at3::vkc::pool {
struct OffsetSize {
uint64_t offset;
uint64_t size;
};
struct BlockSpanIndexPair {
uint32_t blockIdx;
uint32_t spanIdx;
};
struct DeviceMemoryBlock {
Allocation mem;
std::vector<OffsetSize> layout;
bool pageReserved;
};
struct MemoryPool {
std::vector<DeviceMemoryBlock> blocks;
};
struct AllocatorState {
Common *context;
std::vector<size_t> memTypeAllocSizes;
uint32_t totalAllocs;
uint32_t pageSize;
VkDeviceSize memoryBlockMinSize;
std::vector<MemoryPool> memPools;
};
extern AllocatorState state;
//ALLOCATOR INTERFACE / INSTALLATION
void activate(Common *context);
void alloc(Allocation &outAlloc, AllocationCreateInfo createInfo);
void free(Allocation &handle);
size_t allocatedSize(uint32_t memoryType);
uint32_t numAllocs();
}
| 19.782609
| 68
| 0.721612
|
a-day-old-bagel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.