hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29906b72b943a99d853b3481ca2dc65ff75332f0 | 1,408 | cpp | C++ | esercizi_prove/esercizi_seconda_intercorso/massimo_sottoarray.cpp | AntonioEmmanuele/asd_homework_esercizi | 7eaad2ae78f0ada90d1c6264cd02a05f26c31941 | [
"Apache-2.0"
] | null | null | null | esercizi_prove/esercizi_seconda_intercorso/massimo_sottoarray.cpp | AntonioEmmanuele/asd_homework_esercizi | 7eaad2ae78f0ada90d1c6264cd02a05f26c31941 | [
"Apache-2.0"
] | null | null | null | esercizi_prove/esercizi_seconda_intercorso/massimo_sottoarray.cpp | AntonioEmmanuele/asd_homework_esercizi | 7eaad2ae78f0ada90d1c6264cd02a05f26c31941 | [
"Apache-2.0"
] | null | null | null | /* https://leetcode.com/problems/maximum-subarray/ */
#include <iostream>
#include<vector>
using namespace std;
//1- sottoproblemi sono i suffissi array[i:] Theta(n)
//2-Guess consiste nell'indovinare per ognni indice se fare la somma o usarlo come punto di partenza
// per una nuova sequenza Theta(1)
// 3-max_sum=maxi(a[i],massimo_corrente+a[i])
//4- Theta(n)-> siccome il problema in i dipende sempre solo da i+1 non ho cicli
int maximum_sum(vector<int> array){
int massimo_corrente=array[0];
int massimo_da_ritornare=array[0];
unsigned int idx;
for(idx=1;idx<array.size();idx++){
//Immaginiamo di avere [-2 1], allora parto da -2 e noto che -2+1 =-1 , 1 è più grande
//quindi l'attuale sequenza maggiore è proprio 1
massimo_corrente=max(array[idx],massimo_corrente+array[idx]);
//Ad esempio [-2 7 -8 1 2 ]
//il massimo da ritornare quando arrivo ad 1 è 7(il massimo corrente è 1 in quanto noto che è maggiore
//della somma -8+7+1)
//la sequenza 1, 2 mi da 3 ma non è comunque da aggiornare
massimo_da_ritornare=max(massimo_da_ritornare,massimo_corrente);
}
return massimo_da_ritornare;
}
int main() {
unsigned int size_of_array,idx;
cin>>size_of_array;
vector<int>array(size_of_array,0);
for(idx=0;idx<size_of_array;idx++)
cin>>array[idx];
cout<<maximum_sum(array)<<endl;
return 0;
}
| 40.228571 | 111 | 0.684659 | [
"vector"
] |
2992cd57a7ce18ff609465a654c319d909d3283b | 9,066 | cpp | C++ | tools/fuzz_torrent.cpp | luluandleilei/libtorrent | 8648de3706efe0d9ab2504793bd0dd8a9566a1d6 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | tools/fuzz_torrent.cpp | luluandleilei/libtorrent | 8648de3706efe0d9ab2504793bd0dd8a9566a1d6 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | tools/fuzz_torrent.cpp | luluandleilei/libtorrent | 8648de3706efe0d9ab2504793bd0dd8a9566a1d6 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2015, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
#include <cstdint>
#include <random>
#include <cinttypes> // for PRId64 et.al.
#include "libtorrent/bdecode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/error_code.hpp"
using lt::bdecode_node;
using std::mt19937;
using std::uniform_int_distribution;
char const* invalid_utf8_sequences[] =
{
"\x80",
"\xbf",
"\xff",
"\xfe",
"\xff\xff\xfe\xfe",
"\xc0\xaf",
"\xe0\x80\xaf",
"\xf0\x80\x80\xaf",
"\xf8\x80\x80\x80\xaf ",
"\xfc\x80\x80\x80\x80\xaf",
"\xc1\xbf",
"\xe0\x9f\xbf",
"\xf0\x8f\xbf\xbf",
"\xf8\x87\xbf\xbf\xbf",
"\xfc\x83\xbf\xbf\xbf\xbf",
"\xc0\x80",
"\xe0\x80\x80",
"\xf0\x80\x80\x80",
"\xf8\x80\x80\x80\x80",
"\xfc\x80\x80\x80\x80\x80",
"\xed\xa0\x80",
"\xed\xad\xbf",
"\xed\xae\x80",
"\xed\xaf\xbf",
"\xed\xb0\x80",
"\xed\xbe\x80",
"\xed\xbf\xbf",
"\xed\xa0\x80\xed\xb0\x80",
"\xed\xa0\x80\xed\xbf\xbf",
"\xed\xad\xbf\xed\xb0\x80",
"\xed\xad\xbf\xed\xbf\xbf",
"\xed\xae\x80\xed\xb0\x80",
"\xed\xae\x80\xed\xbf\xbf",
"\xed\xaf\xbf\xed\xb0\x80",
"\xed\xaf\xbf\xed\xbf\xbf",
};
std::int64_t g_seed;
void print_ascii_number(std::string& output, std::int64_t val)
{
const bool overflow = g_seed == 1;
const bool underflow = g_seed == 2;
const bool negative = g_seed == 3;
const bool double_negative = g_seed == 4;
const bool zero = g_seed == 5;
g_seed -= 5;
char const* numbers = "0123456789";
if (zero)
{
output += '0';
}
else if (underflow)
{
output += '-';
for (int i = 0; i < 100; ++i) output += numbers[rand() % 10];
return;
}
else if (overflow)
{
for (int i = 0; i < 100; ++i) output += numbers[rand() % 10];
return;
}
else
{
if (negative) output += '-';
else if (double_negative) output += "--";
char buf[50];
std::snprintf(buf, sizeof(buf), "%" PRId64 "", val);
output += buf;
}
}
void print_string(std::string& output, std::string str)
{
const bool empty_string = g_seed == 1;
g_seed -= 1;
if (empty_string)
{
print_ascii_number(output, 0);
output += ':';
return;
}
const bool random_string = g_seed > 0 && g_seed <= 1000;
const int str_seed = int(g_seed) - 1;
g_seed -= 1000;
if (random_string)
{
static mt19937 random_engine(str_seed);
uniform_int_distribution<> d(0, 255);
for (int i = 0; i < int(str.size()); ++i)
str[i] = std::uint8_t(d(random_engine));
print_ascii_number(output, str.size());
output += ':';
output += str;
return;
}
const int num_sequences = (sizeof(invalid_utf8_sequences)/sizeof(char const*));
const bool invalid_utf8 = g_seed <= num_sequences && g_seed > 0;
if (invalid_utf8)
str += invalid_utf8_sequences[g_seed-1];
g_seed -= num_sequences;
print_ascii_number(output, str.size());
output += ':';
output += str;
}
void print_terminate(std::string& output)
{
const bool unterminated = g_seed == 1;
g_seed -= 1;
if (!unterminated) output += 'e';
}
void print_int(std::string& output, std::int64_t value)
{
const bool double_int = g_seed == 1;
g_seed -= 1;
if (double_int) output += 'i';
output += 'i';
print_ascii_number(output, value);
print_terminate(output);
}
void print_dict(std::string& output)
{
const bool double_dict = g_seed == 1;
g_seed -= 1;
if (double_dict) output += 'd';
output += 'd';
}
void print_list(std::string& output)
{
const bool double_list = g_seed == 1;
g_seed -= 1;
if (double_list) output += 'l';
output += 'l';
}
void render_arbitrary_item(std::string& out)
{
if (g_seed <= 0) return;
std::string option;
print_int(option, 1337);
if (g_seed <= 0)
{
out += option;
return;
}
option.clear();
print_string(option, "abcdefgh");
if (g_seed <= 0)
{
out += option;
return;
}
option.clear();
print_dict(option);
print_string(option, "abcdefgh");
print_int(option, 1337);
print_terminate(option);
if (g_seed <= 0)
{
out += option;
return;
}
option.clear();
print_list(option);
print_string(option, "abcdefgh");
print_terminate(option);
if (g_seed <= 0)
{
out += option;
return;
}
}
void render_variant(std::string& out, bdecode_node const& e)
{
switch (e.type())
{
case bdecode_node::dict_t:
print_dict(out);
for (int i = 0; i < e.dict_size(); ++i)
{
std::pair<lt::string_view, bdecode_node> item = e.dict_at(i);
const bool duplicate = g_seed == 1;
const bool skipped = g_seed == 2;
g_seed -= 2;
if (duplicate)
{
print_string(out, item.first.to_string());
render_variant(out, item.second);
}
if (!skipped)
{
print_string(out, item.first.to_string());
render_variant(out, item.second);
}
render_arbitrary_item(out);
}
print_terminate(out);
break;
case bdecode_node::list_t:
print_list(out);
for (int i = 0; i < e.list_size(); ++i)
{
const bool duplicate = g_seed == 1;
const bool skipped = g_seed == 2;
g_seed -= 2;
if (duplicate) render_variant(out, e.list_at(i));
render_arbitrary_item(out);
if (!skipped) render_variant(out, e.list_at(i));
}
print_terminate(out);
break;
case bdecode_node::int_t:
print_int(out, e.int_value());
break;
case bdecode_node::string_t:
print_string(out, e.string_value().to_string());
break;
default:
abort();
}
}
int load_file(std::string const& filename, std::vector<char>& v
, lt::error_code& ec, int limit = 8000000)
{
ec.clear();
FILE* f = fopen(filename.c_str(), "rb");
if (f == nullptr)
{
ec.assign(errno, boost::system::system_category());
return -1;
}
int r = fseek(f, 0, SEEK_END);
if (r != 0)
{
ec.assign(errno, boost::system::system_category());
fclose(f);
return -1;
}
long s = ftell(f);
if (s < 0)
{
ec.assign(errno, boost::system::system_category());
fclose(f);
return -1;
}
if (s > limit)
{
fclose(f);
return -2;
}
r = fseek(f, 0, SEEK_SET);
if (r != 0)
{
ec.assign(errno, boost::system::system_category());
fclose(f);
return -1;
}
v.resize(s);
if (s == 0)
{
fclose(f);
return 0;
}
r = int(fread(&v[0], 1, v.size(), f));
if (r < 0)
{
ec.assign(errno, boost::system::system_category());
fclose(f);
return -1;
}
fclose(f);
if (r != s) return -3;
return 0;
}
int main(int argc, char const* argv[])
{
std::vector<char> buf;
lt::error_code ec;
if (argc < 2)
{
std::fprintf(stderr, "usage: fuzz_torrent torrent-file [torrent-file ...]\n");
return 1;
}
--argc;
++argv;
for (;argc > 0; --argc, ++argv)
{
int ret = load_file(*argv, buf, ec);
if (ret < 0)
{
std::fprintf(stderr, "ERROR loading file: %s\n%s\n"
, *argv, ec.message().c_str());
continue;
}
bdecode_node e;
if (buf.empty() || bdecode(&buf[0], &buf[0] + buf.size(), e, ec) != 0)
{
std::fprintf(stderr, "ERROR parsing file: %s\n%s\n"
, *argv, ec.message().c_str());
continue;
}
std::string test_buffer;
int i = 0;
for (i = 0; i < 10000000; ++i)
{
g_seed = i;
test_buffer.clear();
render_variant(test_buffer, e);
lt::error_code ec;
lt::torrent_info t(test_buffer, ec, lt::from_span);
// TODO: add option to save to file unconditionally (to test other clients)
/*
{
std::fprintf(stderr, "saving %d\n", i);
char filename[100];
std::snprintf(filename, sizeof(filename), "torrents/fuzz-%d.torrent", i);
FILE* f = fopen(filename, "wb+");
if (f == 0)
{
std::fprintf(stderr, "ERROR saving file: (%d) %s\n", errno, strerror(errno));
return 1;
}
fwrite(test_buffer.c_str(), test_buffer.size(), 1, f);
fclose(f);
}
*/
if (g_seed > 0) break;
}
std::fprintf(stderr, "tested %d variants of %s\n", i, *argv);
}
return 0;
}
| 21.741007 | 81 | 0.644827 | [
"vector"
] |
2994087e07febc003f69c1b2d0df2c61fcd008e3 | 999 | cpp | C++ | source/14.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/14.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/14.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 14.cpp
// LeetCode
//
// Created by Narikbi on 11.04.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <numeric>
#include <unordered_map>
#include <sstream>
#include <unordered_set>
using namespace std;
string longestCommonPrefix(vector<string> &strs) {
string word;
if (strs.size() <= 0) return word;
for (int i = 1; i <= strs[0].size(); i++) {
string w = strs[0].substr(0, i);
bool match = true;
int j = 1;
for (j = 1; j < strs.size(); j++) {
if (i > strs[j].size() || w != strs[j].substr(0, i)) {
match = false;
break;
}
}
if (!match) {
return word;
}
word = w;
}
return word;
}
| 18.849057 | 66 | 0.520521 | [
"vector"
] |
2998287d73e81a335ea74489c4d0b3434352bbc0 | 18,204 | cc | C++ | src/bringup/bin/virtcon/vc-device.cc | EnderNightLord-ChromeBook/fuchsia-pine64-pinephone | 05e2c059b57b6217089090a0315971d1735ecf57 | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | src/bringup/bin/virtcon/vc-device.cc | EnderNightLord-ChromeBook/fuchsia-pine64-pinephone | 05e2c059b57b6217089090a0315971d1735ecf57 | [
"BSD-3-Clause"
] | null | null | null | src/bringup/bin/virtcon/vc-device.cc | EnderNightLord-ChromeBook/fuchsia-pine64-pinephone | 05e2c059b57b6217089090a0315971d1735ecf57 | [
"BSD-3-Clause"
] | 2 | 2020-10-25T01:13:49.000Z | 2020-10-26T02:32:13.000Z | // Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <assert.h>
#include <fcntl.h>
#include <lib/gfx-font-data/gfx-font-data.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <fbl/auto_lock.h>
#include "vc.h"
// Default height/width (in px) of console before any displays are
// attached, since we need somewhere to put any data that is received.
#define DEFAULT_WIDTH 1024
#define DEFAULT_HEIGHT 768
#define SCROLLBACK_ROWS 1024 // TODO make configurable
#define ABS(val) (((val) >= 0) ? (val) : -(val))
const gfx_font* g_font = &gfx_font_9x16;
const keychar_t* g_keymap = qwerty_map;
static zx_status_t vc_setup(vc_t* vc, const color_scheme_t* color_scheme) {
// calculate how many rows/columns we have
vc->rows = DEFAULT_HEIGHT / vc->charh;
vc->columns = DEFAULT_WIDTH / vc->charw;
vc->scrollback_rows_max = SCROLLBACK_ROWS;
vc->scrollback_rows_count = 0;
vc->scrollback_offset = 0;
// allocate the text buffer
vc->text_buf =
reinterpret_cast<vc_char_t*>(calloc(1, vc->rows * vc->columns * sizeof(vc_char_t)));
if (!vc->text_buf)
return ZX_ERR_NO_MEMORY;
// allocate the scrollback buffer
vc->scrollback_buf = reinterpret_cast<vc_char_t*>(
calloc(1, vc->scrollback_rows_max * vc->columns * sizeof(vc_char_t)));
if (!vc->scrollback_buf) {
free(vc->text_buf);
return ZX_ERR_NO_MEMORY;
}
// set up the default palette
memcpy(&vc->palette, default_palette, sizeof(default_palette));
vc->front_color = color_scheme->front;
vc->back_color = color_scheme->back;
return ZX_OK;
}
bool vc_graphics_enabled(vc_t* vc) { return vc->graphics && vc->graphics->vc_gfx; }
static void vc_invalidate(void* cookie, int x0, int y0, int w, int h) {
vc_t* vc = reinterpret_cast<vc_t*>(cookie);
if (!g_vc_owns_display || !vc->active || !vc_graphics_enabled(vc)) {
return;
}
assert(h >= 0);
int y1 = y0 + h;
assert(y0 <= static_cast<int>(vc->rows));
assert(y1 <= static_cast<int>(vc->rows));
// Clip the y range so that we don't unnecessarily draw characters
// outside the visible range, and so that we don't draw characters into
// the bottom margin.
int visible_y0 = vc->viewport_y;
int visible_y1 = vc->viewport_y + vc_rows(vc);
y0 = MAX(y0, visible_y0);
y1 = MIN(y1, visible_y1);
for (int y = y0; y < y1; y++) {
if (y < 0) {
// Scrollback row.
vc_char_t* row = vc_get_scrollback_line_ptr(vc, y + vc->scrollback_rows_count);
for (int x = x0; x < x0 + w; x++) {
vc_gfx_draw_char(vc->graphics, vc, row[x], x, y - vc->viewport_y,
/* invert= */ false);
}
} else {
// Row in the main console region (non-scrollback).
vc_char_t* row = &vc->text_buf[y * vc->columns];
for (int x = x0; x < x0 + w; x++) {
// Check whether we should display the cursor at this
// position. Note that it's possible that the cursor is
// outside the display area (vc->cursor_x ==
// vc->columns). In that case, we won't display the
// cursor, even if there's a margin. This matches
// gnome-terminal.
bool invert = (!vc->hide_cursor && static_cast<unsigned>(x) == vc->cursor_x &&
static_cast<unsigned>(y) == vc->cursor_y);
vc_gfx_draw_char(vc->graphics, vc, row[x], x, y - vc->viewport_y, invert);
}
}
}
}
// implement tc callbacks:
static inline void vc_invalidate_lines(vc_t* vc, int y, int h) {
if (y < vc->invy0) {
vc->invy0 = y;
}
y += h;
if (y > vc->invy1) {
vc->invy1 = y;
}
}
static void vc_tc_invalidate(void* cookie, int x0, int y0, int w, int h) {
vc_t* vc = reinterpret_cast<vc_t*>(cookie);
vc_invalidate(cookie, x0, y0, w, h);
vc_invalidate_lines(vc, y0, h);
}
static void vc_tc_movecursor(void* cookie, int x, int y) {
vc_t* vc = reinterpret_cast<vc_t*>(cookie);
unsigned old_x = vc->cursor_x;
unsigned old_y = vc->cursor_y;
vc->cursor_x = x;
vc->cursor_y = y;
if (g_vc_owns_display && vc->active && !vc->hide_cursor) {
// Clear the cursor from its old position.
vc_invalidate(cookie, old_x, old_y, 1, 1);
vc_invalidate_lines(vc, old_y, 1);
// Display the cursor in its new position.
vc_invalidate(cookie, vc->cursor_x, vc->cursor_y, 1, 1);
vc_invalidate_lines(vc, vc->cursor_y, 1);
}
}
static void vc_tc_scrollback_buffer_push(vc_t* vc, vc_char_t* src) {
unsigned dest_row;
assert(vc->scrollback_rows_count <= vc->scrollback_rows_max);
if (vc->scrollback_rows_count < vc->scrollback_rows_max) {
// Add a row without dropping any existing rows.
assert(vc->scrollback_offset == 0);
dest_row = vc->scrollback_rows_count++;
} else {
// Add a row and drop an existing row.
assert(vc->scrollback_offset < vc->scrollback_rows_max);
dest_row = vc->scrollback_offset++;
if (vc->scrollback_offset == vc->scrollback_rows_max)
vc->scrollback_offset = 0;
}
vc_char_t* dst = &vc->scrollback_buf[dest_row * vc->columns];
memcpy(dst, src, vc->columns * sizeof(vc_char_t));
}
static void vc_tc_push_scrollback_line(void* cookie, int y) {
vc_t* vc = reinterpret_cast<vc_t*>(cookie);
vc_char_t* src = &vc->text_buf[y * vc->columns];
vc_tc_scrollback_buffer_push(vc, src);
// If we're displaying only the main console region (and no
// scrollback), then keep displaying that (i.e. don't modify
// viewport_y).
if (vc->viewport_y < 0) {
// We are displaying some of the scrollback buffer.
if (vc->viewport_y > -static_cast<int>(vc->scrollback_rows_max)) {
// Scroll the viewport to continue displaying the same point in
// the scrollback buffer.
--vc->viewport_y;
} else {
// We were displaying the line at the top of the scrollback
// buffer, but we dropped that line from the buffer. We could
// leave the display as it was (which is what gnome-terminal
// does) and not scroll the display. However, that causes
// problems. If the user later scrolls down, we won't
// necessarily be able to display the lines below -- we might
// have dropped those too. So, instead, let's scroll the
// display and remove the scrollback line that was lost.
//
// For simplicity, fall back to redrawing everything.
vc_invalidate(vc, 0, -vc->scrollback_rows_max, vc->columns, vc_rows(vc));
vc_render(vc);
}
}
}
static void vc_set_cursor_hidden(vc_t* vc, bool hide) {
if (vc->hide_cursor == hide)
return;
vc->hide_cursor = hide;
if (g_vc_owns_display && vc->active) {
vc_invalidate(vc, vc->cursor_x, vc->cursor_y, 1, 1);
vc_invalidate_lines(vc, vc->cursor_y, 1);
}
}
static void vc_tc_copy_lines(void* cookie, int y_dest, int y_src, int line_count) {
vc_t* vc = reinterpret_cast<vc_t*>(cookie);
if (vc->viewport_y < 0) {
tc_copy_lines(&vc->textcon, y_dest, y_src, line_count);
// The viewport is scrolled. For simplicity, fall back to
// redrawing all of the non-scrollback lines in this case.
int rows = vc_rows(vc);
vc_invalidate(vc, 0, 0, vc->columns, rows);
vc_invalidate_lines(vc, 0, rows);
return;
}
// Remove the cursor from the display before copying the lines on
// screen, otherwise we might be copying a rendering of the cursor to a
// position where the cursor isn't. This must be done before the
// tc_copy_lines() call, otherwise we might render the wrong character.
bool old_hide_cursor = vc->hide_cursor;
if (g_vc_owns_display && vc->active) {
vc_set_cursor_hidden(vc, true);
}
// The next two calls can be done in any order.
tc_copy_lines(&vc->textcon, y_dest, y_src, line_count);
if (g_vc_owns_display && vc->active && vc_graphics_enabled(vc)) {
gfx_copyrect(vc->graphics->vc_gfx, 0, y_src * vc->charh, vc->graphics->vc_gfx->width,
line_count * vc->charh, 0, y_dest * vc->charh);
// Restore the cursor.
vc_set_cursor_hidden(vc, old_hide_cursor);
vc_status_update();
vc_gfx_invalidate_status(vc->graphics);
vc_invalidate_lines(vc, 0, vc_rows(vc));
}
}
static void vc_tc_setparam(void* cookie, int param, uint8_t* arg, size_t arglen) {
vc_t* vc = reinterpret_cast<vc_t*>(cookie);
switch (param) {
case TC_SET_TITLE:
strncpy(vc->title, (char*)arg, sizeof(vc->title));
vc->title[sizeof(vc->title) - 1] = '\0';
vc_status_update();
if (g_vc_owns_display && vc_graphics_enabled(vc)) {
vc_gfx_invalidate_status(vc->graphics);
}
break;
case TC_SHOW_CURSOR:
vc_set_cursor_hidden(vc, false);
break;
case TC_HIDE_CURSOR:
vc_set_cursor_hidden(vc, true);
break;
default:; // nothing
}
}
static void vc_clear_gfx(vc_t* vc) {
// Fill display with background color
if (g_vc_owns_display && vc->active && vc_graphics_enabled(vc)) {
gfx_fillrect(vc->graphics->vc_gfx, 0, 0, vc->graphics->vc_gfx->width,
vc->graphics->vc_gfx->height, palette_to_color(vc, vc->back_color));
}
}
static void vc_reset(vc_t* vc) {
// reset the cursor
vc->cursor_x = 0;
vc->cursor_y = 0;
// reset the viewport position
vc->viewport_y = 0;
tc_init(&vc->textcon, vc->columns, vc_rows(vc), vc->text_buf, vc->front_color, vc->back_color,
vc->cursor_x, vc->cursor_y);
vc->textcon.cookie = vc;
vc->textcon.invalidate = vc_tc_invalidate;
vc->textcon.movecursor = vc_tc_movecursor;
vc->textcon.push_scrollback_line = vc_tc_push_scrollback_line;
vc->textcon.copy_lines = vc_tc_copy_lines;
vc->textcon.setparam = vc_tc_setparam;
// fill textbuffer with blank characters
size_t count = vc->rows * vc->columns;
vc_char_t* ptr = vc->text_buf;
while (count--) {
*ptr++ = vc_char_make(' ', vc->front_color, vc->back_color);
}
vc_clear_gfx(vc);
if (vc_graphics_enabled(vc)) {
vc_gfx_invalidate_all(vc->graphics, vc);
}
}
void vc_status_clear() {
if (g_vc_owns_display && g_active_vc && vc_graphics_enabled(g_active_vc)) {
gfx_fillrect(g_active_vc->graphics->vc_status_bar_gfx, 0, 0,
g_active_vc->graphics->vc_status_bar_gfx->width,
g_active_vc->graphics->vc_status_bar_gfx->height,
default_palette[STATUS_COLOR_BG]);
}
}
void vc_status_commit() {
if (g_vc_owns_display && g_active_vc && vc_graphics_enabled(g_active_vc)) {
vc_gfx_invalidate_status(g_active_vc->graphics);
}
}
void vc_status_write(int x, unsigned color, const char* text) {
char c;
unsigned fg = default_palette[color];
unsigned bg = default_palette[STATUS_COLOR_BG];
vc_t* vc = g_active_vc;
if (!g_active_vc) {
return;
}
if (g_vc_owns_display && vc_graphics_enabled(vc)) {
x *= vc->graphics->vc_font->width;
while ((c = *text++) != 0) {
gfx_putchar(vc->graphics->vc_status_bar_gfx, vc->graphics->vc_font, c, x, 0, fg, bg);
x += vc->graphics->vc_font->width;
}
}
}
void vc_render(vc_t* vc) {
if (g_vc_owns_display && vc->active && vc_graphics_enabled(vc)) {
vc_status_update();
vc_gfx_invalidate_all(vc->graphics, vc);
}
}
void vc_full_repaint(vc_t* vc) {
if (g_vc_owns_display && vc_graphics_enabled(vc)) {
vc_clear_gfx(vc);
int scrollback_lines = vc_get_scrollback_lines(vc);
vc_invalidate(vc, 0, -scrollback_lines, vc->columns, scrollback_lines + vc->rows);
}
}
int vc_get_scrollback_lines(vc_t* vc) { return vc->scrollback_rows_count; }
vc_char_t* vc_get_scrollback_line_ptr(vc_t* vc, unsigned row) {
assert(row < vc->scrollback_rows_count);
row += vc->scrollback_offset;
if (row >= vc->scrollback_rows_max)
row -= vc->scrollback_rows_max;
return &vc->scrollback_buf[row * vc->columns];
}
static void vc_scroll_viewport_abs(vc_t* vc, int vpy) {
vpy = MIN(vpy, 0);
vpy = MAX(vpy, -vc_get_scrollback_lines(vc));
int diff = vpy - vc->viewport_y;
if (diff == 0)
return;
int diff_abs = ABS(diff);
vc->viewport_y = vpy;
int rows = vc_rows(vc);
if (!g_vc_owns_display || !vc->active || !vc_graphics_enabled(vc)) {
return;
}
if (diff_abs >= rows) {
// We are scrolling the viewport by a large delta. Invalidate all
// of the visible area of the console.
vc_invalidate(vc, 0, vpy, vc->columns, rows);
} else {
if (diff > 0) {
gfx_copyrect(vc->graphics->vc_gfx, 0, diff_abs * vc->charh, vc->graphics->vc_gfx->width,
(rows - diff_abs) * vc->charh, 0, 0);
vc_invalidate(vc, 0, vpy + rows - diff_abs, vc->columns, diff_abs);
} else {
gfx_copyrect(vc->graphics->vc_gfx, 0, 0, vc->graphics->vc_gfx->width,
(rows - diff_abs) * vc->charh, 0, diff_abs * vc->charh);
vc_invalidate(vc, 0, vpy, vc->columns, diff_abs);
}
}
vc_render(vc);
}
void vc_scroll_viewport(vc_t* vc, int dir) { vc_scroll_viewport_abs(vc, vc->viewport_y + dir); }
void vc_scroll_viewport_top(vc_t* vc) { vc_scroll_viewport_abs(vc, INT_MIN); }
void vc_scroll_viewport_bottom(vc_t* vc) { vc_scroll_viewport_abs(vc, 0); }
void vc_set_fullscreen(vc_t* vc, bool fullscreen) {
unsigned flags;
if (fullscreen) {
flags = vc->flags | VC_FLAG_FULLSCREEN;
} else {
flags = vc->flags & ~VC_FLAG_FULLSCREEN;
}
if (flags != vc->flags) {
vc->flags = flags;
tc_seth(&vc->textcon, vc_rows(vc));
}
vc_render(vc);
}
const gfx_font* vc_get_font() { return g_font; }
void vc_attach_gfx(vc_t* vc) {
if (vc->graphics == nullptr) {
return;
}
// If the size of the new gfx console doesn't match what we had been
// attached to, we need to allocate new memory and copy the existing
// data over.
unsigned rows = vc->graphics->vc_gfx->height / vc->charh;
unsigned columns = vc->graphics->vc_gfx->width / vc->charw;
if (rows == vc->rows && columns == vc->columns) {
return;
}
// allocate the new buffers
vc_char_t* text_buf = reinterpret_cast<vc_char_t*>(calloc(1, rows * columns * sizeof(vc_char_t)));
vc_char_t* scrollback_buf = reinterpret_cast<vc_char_t*>(
calloc(1, vc->scrollback_rows_max * columns * sizeof(vc_char_t)));
if (text_buf && scrollback_buf) {
// fill new text buffer with blank characters
size_t count = rows * columns;
vc_char_t* ptr = text_buf;
while (count--) {
*ptr++ = vc_char_make(' ', vc->front_color, vc->back_color);
}
// Copy the most recent data from the old console to the new one. There are
// (vc->cursor_y + 1) rows available, and we want (rows - (vc->rows - vc_rows(vc))
// rows. Subtract to get the first row index to copy.
unsigned old_i =
MAX(static_cast<int>((vc->cursor_y + 1) - (rows - (vc->rows - vc_rows(vc)))), 0);
unsigned old_data_start = old_i;
unsigned new_i = 0;
size_t len = (vc->columns < columns ? vc->columns : columns) * sizeof(vc_char_t);
while (new_i < rows && old_i <= vc->cursor_y) {
memcpy(text_buf + columns * (new_i++), vc->text_buf + vc->columns * (old_i++), len);
}
// copy the old scrollback buffer
for (int i = 0; i < SCROLLBACK_ROWS; i++) {
memcpy(scrollback_buf + columns * i, vc->scrollback_buf + vc->columns * i, len);
}
vc_char_t* old_text_buf = vc->text_buf;
unsigned old_columns = vc->columns;
free(vc->scrollback_buf);
vc->text_buf = text_buf;
vc->scrollback_buf = scrollback_buf;
vc->rows = rows;
vc->columns = columns;
// Push any data that fell off of text_buf. Use a temporary buffer of the
// right length to handle going to a wider console. Set it to ' 's before
// pushing, so we don't merge data from old rows.
if (old_data_start) {
vc_char_t buf[columns];
for (unsigned i = 0; i < old_data_start; i++) {
vc_char_t* ptr = buf;
while (ptr < buf + columns) {
*ptr++ = vc_char_make(' ', vc->front_color, vc->back_color);
}
ptr = old_text_buf + i * old_columns;
memcpy(buf, ptr, len);
vc_tc_scrollback_buffer_push(vc, buf);
}
}
free(old_text_buf);
} else {
// If we failed to allocate new buffers, use the old ones as best we can
free(text_buf);
free(scrollback_buf);
vc->rows = MIN(vc->rows, rows);
vc->columns = MIN(vc->columns, columns);
printf("vc: buffer resize failed, reusing old buffers (%dx%d)\n", vc->rows, vc->columns);
}
vc->viewport_y = 0;
if (vc->cursor_x >= vc->columns) {
vc->cursor_x = vc->columns - 1;
}
if (static_cast<int>(vc->cursor_y) >= vc_rows(vc)) {
vc->cursor_y = vc_rows(vc) - 1;
}
tc_init(&vc->textcon, vc->columns, vc_rows(vc), vc->text_buf, vc->front_color, vc->back_color,
vc->cursor_x, vc->cursor_y);
}
zx_status_t vc_alloc(vc_t** out, const color_scheme_t* color_scheme) {
vc_t* vc = reinterpret_cast<vc_t*>(calloc(1, sizeof(vc_t)));
if (!vc) {
return ZX_ERR_NO_MEMORY;
}
vc->fd = -1;
vc->keymap = g_keymap;
vc->font = vc_get_font();
vc->charw = vc->font->width;
vc->charh = vc->font->height;
zx_status_t status = vc_setup(vc, color_scheme);
if (status != ZX_OK) {
free(vc);
return status;
}
vc_attach_to_main_display(vc);
vc_reset(vc);
*out = vc;
return ZX_OK;
}
void vc_free(vc_t* vc) {
if (vc->fd >= 0) {
close(vc->fd);
}
free(vc->text_buf);
free(vc->scrollback_buf);
free(vc);
}
void vc_flush(vc_t* vc) {
if (g_vc_owns_display && vc_graphics_enabled(vc) && vc->invy1 >= 0) {
int rows = vc_rows(vc);
// Adjust for the current viewport position. Convert
// console-relative row numbers to screen-relative row numbers.
int invalidate_y0 = MIN(vc->invy0 - vc->viewport_y, rows);
int invalidate_y1 = MIN(vc->invy1 - vc->viewport_y, rows);
vc_gfx_invalidate(vc->graphics, vc, 0, invalidate_y0, vc->columns,
invalidate_y1 - invalidate_y0);
}
}
void vc_flush_all(vc_t* vc) {
if (g_vc_owns_display && vc_graphics_enabled(vc)) {
vc_gfx_invalidate_all(vc->graphics, vc);
}
}
void vc_device_init(const gfx_font* font, const keychar_t* keymap) {
g_font = font;
g_keymap = keymap;
}
| 32.682226 | 100 | 0.655955 | [
"render"
] |
299c622c32845bbb80324ff080ca211793ced6ee | 6,430 | hpp | C++ | src/external/boost/boost_1_68_0/boost/type_erasure/register_binding.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | src/external/boost/boost_1_68_0/boost/type_erasure/register_binding.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | src/external/boost/boost_1_68_0/boost/type_erasure/register_binding.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | // Boost.TypeErasure library
//
// Copyright 2015 Steven Watanabe
//
// 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)
//
// $Id$
#ifndef BOOST_TYPE_ERASURE_REGISTER_BINDING_HPP_INCLUDED
#define BOOST_TYPE_ERASURE_REGISTER_BINDING_HPP_INCLUDED
#include <boost/type_erasure/detail/check_map.hpp>
#include <boost/type_erasure/detail/get_placeholders.hpp>
#include <boost/type_erasure/detail/rebind_placeholders.hpp>
#include <boost/type_erasure/detail/normalize.hpp>
#include <boost/type_erasure/detail/adapt_to_vtable.hpp>
#include <boost/type_erasure/detail/auto_link.hpp>
#include <boost/type_erasure/static_binding.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/remove_if.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/has_key.hpp>
#include <boost/mpl/insert.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/set.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/back_inserter.hpp>
#include <boost/mpl/for_each.hpp>
#include <vector>
#include <typeinfo>
namespace boost {
namespace type_erasure {
namespace detail {
typedef std::vector<const std::type_info*> key_type;
typedef void (*value_type)();
BOOST_TYPE_ERASURE_DECL void register_function_impl(const key_type& key, value_type fn);
BOOST_TYPE_ERASURE_DECL value_type lookup_function_impl(const key_type& key);
template<class Map>
struct append_to_key_static {
append_to_key_static(key_type* k) : key(k) {}
template<class P>
void operator()(P) {
#ifndef BOOST_TYPE_ERASURE_USE_MP11
key->push_back(&typeid(typename ::boost::mpl::at<Map, P>::type));
#else
key->push_back(&typeid(::boost::mp11::mp_second< ::boost::mp11::mp_map_find<Map, P> >));
#endif
}
key_type* key;
};
// This placeholder exists solely to create a normalized
// representation of a primitive concept. For the moment
// I'm going to be conservative and require a bijection
// between the original placeholders and the normalized
// placeholders. It should be safe to map everything
// to a single placeholder, though, as long as the
// key includes every instance of each placeholder
// as a separate element. i.e. we should be able to
// turn addable<_a, _b> into addable<_, _> and
// addable<_a, _a> into addable<_, _> as well if we always
// add typeids for both arguments to the search key.
template<int N>
struct _ : ::boost::type_erasure::placeholder {};
struct counting_map_appender
{
template<class State, class Key>
struct apply
{
typedef typename ::boost::mpl::insert<
State,
::boost::mpl::pair<
Key,
::boost::type_erasure::detail::_<
::boost::mpl::size<State>::value
>
>
>::type type;
};
};
template<class Map>
struct register_function {
template<class F>
void operator()(F) {
key_type key;
#ifndef BOOST_TYPE_ERASURE_USE_MP11
typedef typename ::boost::type_erasure::detail::get_placeholders<F, ::boost::mpl::set0<> >::type placeholders;
#else
typedef typename ::boost::type_erasure::detail::get_placeholders<F, ::boost::mp11::mp_list<> >::type placeholders;
#endif
typedef typename ::boost::mpl::fold<
placeholders,
::boost::mpl::map0<>,
::boost::type_erasure::detail::counting_map_appender
>::type placeholder_map;
key.push_back(&typeid(typename ::boost::type_erasure::detail::rebind_placeholders<F, placeholder_map>::type));
::boost::mpl::for_each<placeholders>(append_to_key_static<Map>(&key));
value_type fn = reinterpret_cast<value_type>(&::boost::type_erasure::detail::rebind_placeholders<F, Map>::type::value);
::boost::type_erasure::detail::register_function_impl(key, fn);
}
};
}
/**
* Registers a model of a concept to allow downcasting @ref any
* via \dynamic_any_cast.
*/
template<class Concept, class Map>
void register_binding(const static_binding<Map>&)
{
typedef typename ::boost::type_erasure::detail::normalize_concept<
Concept
>::type normalized;
typedef typename ::boost::mpl::transform<normalized,
::boost::type_erasure::detail::maybe_adapt_to_vtable< ::boost::mpl::_1>
>::type actual_concept;
typedef typename ::boost::type_erasure::detail::get_placeholder_normalization_map<
Concept
>::type placeholder_subs;
typedef typename ::boost::type_erasure::detail::add_deductions<Map, placeholder_subs>::type actual_map;
::boost::mpl::for_each<actual_concept>(::boost::type_erasure::detail::register_function<actual_map>());
}
/**
* \overload
*/
template<class Concept, class T>
void register_binding()
{
// Find all placeholders
typedef typename ::boost::type_erasure::detail::normalize_concept_impl<Concept>::type normalized;
typedef typename normalized::first basic;
typedef typename ::boost::mpl::fold<
basic,
#ifndef BOOST_TYPE_ERASURE_USE_MP11
::boost::mpl::set0<>,
#else
::boost::mp11::mp_list<>,
#endif
::boost::type_erasure::detail::get_placeholders< ::boost::mpl::_2, ::boost::mpl::_1>
>::type all_placeholders;
// remove deduced placeholders
typedef typename ::boost::mpl::fold<
typename normalized::second,
::boost::mpl::set0<>,
::boost::mpl::insert< ::boost::mpl::_1, ::boost::mpl::second< ::boost::mpl::_2> >
>::type xtra_deduced;
typedef typename ::boost::mpl::remove_if<
all_placeholders,
::boost::mpl::or_<
::boost::type_erasure::detail::is_deduced< ::boost::mpl::_1>,
::boost::mpl::has_key<xtra_deduced, ::boost::mpl::_1>
>,
::boost::mpl::back_inserter< ::boost::mpl::vector0<> >
>::type unknown_placeholders;
// Bind the single remaining placeholder to T
BOOST_MPL_ASSERT((boost::mpl::equal_to<boost::mpl::size<unknown_placeholders>, boost::mpl::int_<1> >));
register_binding<Concept>(::boost::type_erasure::make_binding<
::boost::mpl::map< ::boost::mpl::pair<typename ::boost::mpl::front<unknown_placeholders>::type, T> > >());
}
}
}
#endif
| 35.32967 | 127 | 0.693935 | [
"vector",
"model",
"transform"
] |
29a177e4ab780d39226ccc8d5173697aebd1283a | 2,636 | cc | C++ | ash/system/phonehub/phone_connected_view.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | ash/system/phonehub/phone_connected_view.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | ash/system/phonehub/phone_connected_view.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/phonehub/phone_connected_view.h"
#include <memory>
#include "ash/style/ash_color_provider.h"
#include "ash/system/phonehub/notification_opt_in_view.h"
#include "ash/system/phonehub/phone_hub_view_ids.h"
#include "ash/system/phonehub/phone_status_view.h"
#include "ash/system/phonehub/quick_actions_view.h"
#include "ash/system/phonehub/task_continuation_view.h"
#include "ash/system/phonehub/ui_constants.h"
#include "ash/system/tray/tray_constants.h"
#include "chromeos/components/phonehub/notification_access_manager.h"
#include "chromeos/components/phonehub/phone_hub_manager.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/separator.h"
#include "ui/views/layout/box_layout.h"
namespace ash {
PhoneConnectedView::PhoneConnectedView(
chromeos::phonehub::PhoneHubManager* phone_hub_manager) {
SetID(PhoneHubViewID::kPhoneConnectedView);
auto setup_layered_view = [](views::View* view) {
view->SetPaintToLayer();
view->layer()->SetFillsBoundsOpaquely(false);
};
auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical,
gfx::Insets(0, kBubbleHorizontalSidePaddingDip)));
layout->SetDefaultFlex(1);
AddChildView(std::make_unique<NotificationOptInView>(
phone_hub_manager->GetNotificationAccessManager()));
setup_layered_view(
AddChildView(std::make_unique<QuickActionsView>(phone_hub_manager)));
auto* phone_model = phone_hub_manager->GetPhoneModel();
if (phone_model) {
setup_layered_view(AddChildView(std::make_unique<TaskContinuationView>(
phone_model, phone_hub_manager->GetUserActionRecorder())));
}
}
PhoneConnectedView::~PhoneConnectedView() = default;
void PhoneConnectedView::ChildPreferredSizeChanged(View* child) {
// Resize the bubble when the child change its size.
PreferredSizeChanged();
}
void PhoneConnectedView::ChildVisibilityChanged(View* child) {
// Resize the bubble when the child change its visibility.
PreferredSizeChanged();
}
const char* PhoneConnectedView::GetClassName() const {
return "PhoneConnectedView";
}
phone_hub_metrics::Screen PhoneConnectedView::GetScreenForMetrics() const {
return phone_hub_metrics::Screen::kPhoneConnected;
}
} // namespace ash
| 33.794872 | 75 | 0.777314 | [
"geometry"
] |
29a2cda4d4415a784d8a7981b5c0eebad43b4afe | 2,373 | cpp | C++ | code/old_FINDER_CN_cost_tf/src/lib/graph.cpp | faraz2023/FINDER | 170255f9a442b11e1a27483fe6eaf2ee61766454 | [
"MIT"
] | 87 | 2020-03-09T01:02:07.000Z | 2022-03-27T10:40:31.000Z | code/old_FINDER_CN_cost_tf/src/lib/graph.cpp | faraz2023/FINDER | 170255f9a442b11e1a27483fe6eaf2ee61766454 | [
"MIT"
] | 24 | 2020-05-27T12:03:02.000Z | 2022-03-23T12:11:09.000Z | code/old_FINDER_CN_cost_tf/src/lib/graph.cpp | faraz2023/FINDER | 170255f9a442b11e1a27483fe6eaf2ee61766454 | [
"MIT"
] | 35 | 2020-06-13T23:52:42.000Z | 2022-03-27T05:21:20.000Z | #include "graph.h"
#include <cassert>
#include <iostream>
#include <random>
#include <iterator>
//#include "stdio.h"
Graph::Graph() : num_nodes(0), num_edges(0)
{
edge_list.clear();
adj_list.clear();
nodes_weight.clear();
total_nodes_weight= 0.0;
}
Graph::Graph(const int _num_nodes, const int _num_edges, const int* edges_from, const int* edges_to,const double* _nodes_weight)
: num_nodes(_num_nodes), num_edges(_num_edges)
{
edge_list.resize(num_edges);
adj_list.resize(num_nodes);
nodes_weight.clear();
total_nodes_weight = 0.0;
for (int i = 0; i < num_nodes; ++i)
{
adj_list[i].clear();
nodes_weight.push_back(_nodes_weight[i]);
total_nodes_weight+=_nodes_weight[i];
}
for (int i = 0; i < num_edges; ++i)
{
int x = edges_from[i], y = edges_to[i];
adj_list[x].push_back(y);
adj_list[y].push_back(x);
edge_list[i] = std::make_pair(edges_from[i], edges_to[i]);
}
// for (int i = 0; i < num_nodes; ++i)
// sort(adj_list[i].begin(),adj_list[i].end());
}
double Graph::getTwoRankNeighborsRatio(std::vector<int> covered)
{
std::set<int> tempSet;
for(int i =0;i< (int)covered.size();++i){
tempSet.insert(covered[i]);
}
double sum = 0;
for(int i =0;i<num_nodes;++i){
if(tempSet.count(i)==0){
for(int j=i+1;j<num_nodes;++j){
if(tempSet.count(j)==0){
std::vector<int> v3;
std::set_intersection(adj_list[i].begin(),adj_list[i].end(),adj_list[j].begin(),adj_list[j].end(),std::inserter(v3,v3.begin()));
if(v3.size()>0){
sum += 1.0;
}
}
}
}
}
return sum;
}
GSet::GSet()
{
graph_pool.clear();
}
void GSet::Clear()
{
graph_pool.clear();
}
void GSet::InsertGraph(int gid, std::shared_ptr<Graph> graph)
{
assert(graph_pool.count(gid) == 0);
graph_pool[gid] = graph;
}
std::shared_ptr<Graph> GSet::Get(int gid)
{
assert(graph_pool.count(gid));
return graph_pool[gid];
}
std::shared_ptr<Graph> GSet::Sample()
{
// printf("graph_pool_size:%d",graph_pool.size());
assert(graph_pool.size());
// printf("graph_pool_size:%d",graph_pool.size());
int gid = rand() % graph_pool.size();
assert(graph_pool[gid]);
return graph_pool[gid];
}
GSet GSetTrain, GSetTest; | 24.71875 | 140 | 0.597977 | [
"vector"
] |
29a4a60cbafa9adc9e14ffadc0db548f075f9cf4 | 1,930 | cpp | C++ | src/Messages/HitFailMessage.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | 1 | 2021-04-28T20:32:57.000Z | 2021-04-28T20:32:57.000Z | src/Messages/HitFailMessage.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | 7 | 2021-08-24T14:09:33.000Z | 2021-08-30T12:47:40.000Z | src/Messages/HitFailMessage.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | null | null | null | #include <Messages/HitFailMessage.hpp>
/// <summary>
/// Constructs a hit fail message
/// </summary>
WhackAStoodentServer::Messages::HitFailMessage::HitFailMessage() :
WhackAStoodentServer::Messages::ASerializableMessage<WhackAStoodentServer::EMessageType::HitFail>()
{
// ...
}
/// <summary>
/// Constructs a hit fail message
/// </summary>
/// <param name="position">Position</param>
WhackAStoodentServer::Messages::HitFailMessage::HitFailMessage(const WhackAStoodentServer::Vector2D<float>& position) :
WhackAStoodentServer::Messages::ASerializableMessage<WhackAStoodentServer::EMessageType::HitFail>(),
position(position)
{
// ...
}
/// <summary>
/// Destroys hit fail message
/// </summary>
WhackAStoodentServer::Messages::HitFailMessage::~HitFailMessage()
{
// ...
}
/// <summary>
/// Gets the position
/// </summary>
/// <returns>Position</returns>
const WhackAStoodentServer::Vector2D<float>& WhackAStoodentServer::Messages::HitFailMessage::GetPosition() const
{
return position;
}
/// <summary>
/// Serializes contents
/// </summary>
/// <param name="result">Result</param>
/// <returns>Serialized contents</returns>
std::vector<std::uint8_t>& WhackAStoodentServer::Messages::HitFailMessage::Serialize(std::vector<std::uint8_t>& result) const
{
WhackAStoodentServer::Messages::ASerializableMessage<WhackAStoodentServer::EMessageType::HitFail>::Serialize(result);
return position.Serialize(result);
}
/// <summary>
/// Deserializes given input
/// </summary>
/// <param name="data">Data to deserialize</param>
/// <returns>Remaining data to deserialize</returns>
nonstd::span<const std::uint8_t> WhackAStoodentServer::Messages::HitFailMessage::Deserialize(nonstd::span<const std::uint8_t> data)
{
nonstd::span<const std::uint8_t> next_bytes(WhackAStoodentServer::Messages::ASerializableMessage<WhackAStoodentServer::EMessageType::HitFail>::Deserialize(data));
return position.Deserialize(next_bytes);
}
| 31.129032 | 163 | 0.752332 | [
"vector"
] |
29a8014895a7280dda8d8856e8338ccfdfcc801a | 2,254 | cc | C++ | chrome/browser/ui/views/extensions/extension_permissions_view.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/extensions/extension_permissions_view.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/extensions/extension_permissions_view.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/extensions/extension_permissions_view.h"
#include "chrome/browser/extensions/install_prompt_permissions.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/chrome_typography.h"
#include "chrome/browser/ui/views/extensions/expandable_container_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/metadata/metadata_impl_macros.h"
ExtensionPermissionsView::ExtensionPermissionsView(int available_width)
: available_width_(available_width) {
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, gfx::Insets(),
ChromeLayoutProvider::Get()->GetDistanceMetric(
views::DISTANCE_RELATED_CONTROL_VERTICAL)));
}
void ExtensionPermissionsView::AddItem(
const base::string16& permission_text,
const base::string16& permission_details) {
auto permission_label = std::make_unique<views::Label>(
permission_text, views::style::CONTEXT_DIALOG_BODY_TEXT,
views::style::STYLE_SECONDARY);
permission_label->SetMultiLine(true);
permission_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
permission_label->SizeToFit(available_width_);
AddChildView(std::move(permission_label));
if (!permission_details.empty()) {
// If we have more details to provide, show them in collapsed form.
std::vector<base::string16> details_container;
details_container.push_back(permission_details);
AddChildView(std::make_unique<ExpandableContainerView>(details_container,
available_width_));
}
}
void ExtensionPermissionsView::AddPermissions(
const extensions::InstallPromptPermissions& permissions) {
for (size_t i = 0; i < permissions.permissions.size(); ++i) {
AddItem(permissions.permissions[i], permissions.details[i]);
}
}
void ExtensionPermissionsView::ChildPreferredSizeChanged(views::View* child) {
PreferredSizeChanged();
}
BEGIN_METADATA(ExtensionPermissionsView, views::View)
END_METADATA
| 40.981818 | 78 | 0.759982 | [
"vector"
] |
29abbcb4ec0a59b63a353a78a0f2debb2dc9dcee | 1,798 | cc | C++ | imm/src/model/ListTagPhotosResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | imm/src/model/ListTagPhotosResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | imm/src/model/ListTagPhotosResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/imm/model/ListTagPhotosResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Imm;
using namespace AlibabaCloud::Imm::Model;
ListTagPhotosResult::ListTagPhotosResult() :
ServiceResult()
{}
ListTagPhotosResult::ListTagPhotosResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListTagPhotosResult::~ListTagPhotosResult()
{}
void ListTagPhotosResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allPhotos = value["Photos"]["PhotosItem"];
for (auto value : allPhotos)
{
PhotosItem photosObject;
if(!value["SrcUri"].isNull())
photosObject.srcUri = value["SrcUri"].asString();
if(!value["TagScore"].isNull())
photosObject.tagScore = std::stof(value["TagScore"].asString());
photos_.push_back(photosObject);
}
if(!value["NextMarker"].isNull())
nextMarker_ = value["NextMarker"].asString();
}
std::vector<ListTagPhotosResult::PhotosItem> ListTagPhotosResult::getPhotos()const
{
return photos_;
}
std::string ListTagPhotosResult::getNextMarker()const
{
return nextMarker_;
}
| 26.441176 | 82 | 0.740267 | [
"vector",
"model"
] |
29ac0209fe99d33b638a25bec4b027f18dfcf794 | 24,172 | hpp | C++ | src/Dialect/ONNX/ShapeInference/ONNXShapeHelper.hpp | bxing-groq/onnx-mlir | 993f296b9275a2c7a9b7e9fa645a569603d09191 | [
"Apache-2.0"
] | null | null | null | src/Dialect/ONNX/ShapeInference/ONNXShapeHelper.hpp | bxing-groq/onnx-mlir | 993f296b9275a2c7a9b7e9fa645a569603d09191 | [
"Apache-2.0"
] | null | null | null | src/Dialect/ONNX/ShapeInference/ONNXShapeHelper.hpp | bxing-groq/onnx-mlir | 993f296b9275a2c7a9b7e9fa645a569603d09191 | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-License-Identifier: Apache-2.0
*/
//===----------------ONNXShapeHelper.hpp - help for shapes----------------=== //
//
// Copyright 2020 The IBM Research Authors.
//
// =============================================================================
//
// This file has the computations to compute the shapes using the new index expr
// approach.
//
//===----------------------------------------------------------------------===//
#pragma once
#include "llvm/ADT/BitVector.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Value.h"
#include "mlir/Support/LogicalResult.h"
#include "src/Dialect/ONNX/IndexExpr.hpp"
#include "src/Dialect/ONNX/ONNXOps.hpp"
using namespace mlir;
// Steps to add a new op XXX:
// 1) Create a new shape inference type inside this file, ONNXShapeHelper.hpp.
// 2) Create new shape inference file, say XXX.cpp and implement.
// 3) Add template instantiation at bottom of ONNXShapeHelper.cpp.
// 4) Add new file name XXX.cpp to ../CMakeLists.txt
// 5) Use the new object in ONNXOps.cpp and ONNXToKrnl lowering for XXX.
//===----------------------------------------------------------------------===//
// ONNX Op Shape Helper
//===----------------------------------------------------------------------===//
using DimsExpr = SmallVector<IndexExpr, 4>;
/// When defining support for a new op, add one such stuct which must
/// minimally compute the outputDims present in the parent class. Computation
/// should be performed using a `computeShape` function. Return success on
/// successful computation of all the IndexExpr. During shape inference, object
/// is built using a null-ptr rewriter; during lowering, the rewriter is nonnull
/// and will be used to generate code.
///
/// By adding here the ability of a ShapeHelper to be created in the
/// IndexExprScope of another ShapeHelper, this enables us to nest ShapeHelper.
/// For example, there is a case where ExpandOp needs to find out specific
/// details of an ShapeOp that provides info to the ExpandOp. We can now invoke
/// the ShapeOp shape helper in the context of the ExpandOp shape helper while
/// having all of the IndexExpr info in the same context and thus be generally
/// usable. Support is here to provide an IndexExprScope, which can be added to
/// any subclasses of ONNXOpShapeHelper when this nesting becomes useful to
/// other ops as well.
template <class OP>
struct ONNXOpShapeHelper {
// Constructor for shape inference. Reuse scope if given, otherwise create one
// now and free it in destructor.
ONNXOpShapeHelper(
OP *newOp, int numResults, IndexExprScope *inScope = nullptr);
// Constructor when code can be generated. Reuse scope if given, otherwise
// create one now and free it in destructor.
ONNXOpShapeHelper(OP *newOp, int numResults, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal,
IndexExprScope *inScope = nullptr);
~ONNXOpShapeHelper() {
if (ownScope)
delete scope;
}
// Every child class is expected to create a computeShape with the following
// signature. This method is responsible to compute at a minimum the output
// dims.
//
// LogicalResult computeShape(<<OpAdaptor>> operandAdaptor);
//
// Use the op to get attributes, and operandAdaptor to get the input/output
// tensors.
// Return output dims for the N-th output.
DimsExpr &dimsForOutput(int n = 0) { return outputsDims[n]; }
// Set the number of outputs.
void setNumberOfOutputs(int n) { outputsDims.resize(n); }
// Data that must be present for every ShapeHelper operation. Op and scope
// are initialized in the constructor, and outputsDims is computed by the
// child's struct `computeShape` function.
OP *op;
IndexExprScope *scope;
protected:
// Function to get a dense value from an attribute.
ArrayValueIndexCapture::GetDenseVal fGetDenseVal;
// Function to load a value from an array.
ArrayValueIndexCapture::LoadVal fLoadVal;
private:
SmallVector<DimsExpr, 1> outputsDims;
bool ownScope;
};
/// Compute a broadcasted shape from the shapes of given operands. Operands must
/// be ranked in advance.
template <class OP>
struct ONNXOpBroadcastedShapeHelper : public ONNXOpShapeHelper<OP> {
ONNXOpBroadcastedShapeHelper(OP *newOp, IndexExprScope *inScope = nullptr,
bool uniBroadcasting = false, bool noBroadcasting = false);
ONNXOpBroadcastedShapeHelper(OP *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal,
IndexExprScope *inScope = nullptr, bool uniBroadcasting = false,
bool noBroadcasting = false);
// computeShape a vector of IndexExprs to represent the output shape. Results
// are stored in 'outputDims'. Used in shape inference and memory allocation
// for the output. Parameters:
// - operands: a list of input tensors.
// - additional operand: one additional input that comes from as a vector
// of IndexExpr (used for example for ONNXExpandOp). Ignored when empty.
LogicalResult computeShape(
ArrayRef<Value> operands, DimsExpr &additionalOperand);
// Compute access indices to load/store value from/to a given 'operand'.
// Used in a loop to access the operand.
// Parameters:
// - operand: operand to access.
// - operandIndex: index of the operand in 'this->inputsDims'.
// - loopAccessExprs: IndexExprs for the loop's IVs.
// - operandAccessExprs: access indices to access the operand.
// This is the output of this function. Use it in subsequent load/stores.
LogicalResult GetAccessExprs(Value operand, unsigned operandIndex,
const SmallVectorImpl<IndexExpr> &outputAccessExprs,
SmallVectorImpl<IndexExpr> &operandAccessExprs);
// A vector of input shapes where dimensions are padded with 1 if necessary,
// so that all inputs have the same rank.
SmallVector<DimsExpr, 4> inputsDims;
// A vector of IndexExprs representing the output shape.
// in upper DimsExpr outputDims;
int64_t outputRank;
protected:
// If unidirectional broadcasting, the other operands are always
// unidirectional broadcastable to the first operand.
bool isUniBroadcasting;
// If isNoBroadcasting is true, the shape of all input is assumed to be same
// This flag is used to test dynamic shape
// There is no impact on static shape
bool isNoBroadcasting;
};
struct ONNXGenericOpBroadcastedShapeHelper
: public ONNXOpBroadcastedShapeHelper<Operation> {
ONNXGenericOpBroadcastedShapeHelper(Operation *newOp,
IndexExprScope *inScope = nullptr, bool uniBroadcasting = false,
bool noBroadcasting = false);
ONNXGenericOpBroadcastedShapeHelper(Operation *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal,
IndexExprScope *inScope = nullptr, bool uniBroadcasting = false,
bool noBroadcasting = false);
};
// Shape for ArgMax
struct ONNXArgMaxOpShapeHelper : public ONNXOpShapeHelper<ONNXArgMaxOp> {
ONNXArgMaxOpShapeHelper(ONNXArgMaxOp *newOp);
ONNXArgMaxOpShapeHelper(ONNXArgMaxOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXArgMaxOpAdaptor operandAdaptor);
};
// Shape for Clip.
struct ONNXClipOpShapeHelper : public ONNXOpShapeHelper<ONNXClipOp> {
ONNXClipOpShapeHelper(ONNXClipOp *newOp);
ONNXClipOpShapeHelper(ONNXClipOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXClipOpAdaptor operandAdaptor);
};
// Shape for concat
struct ONNXConcatOpShapeHelper : public ONNXOpShapeHelper<ONNXConcatOp> {
ONNXConcatOpShapeHelper(ONNXConcatOp *newOp);
ONNXConcatOpShapeHelper(ONNXConcatOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXConcatOpAdaptor operandAdaptor);
};
// Shape for DepthToSpace.
struct ONNXDepthToSpaceOpShapeHelper
: public ONNXOpShapeHelper<ONNXDepthToSpaceOp> {
ONNXDepthToSpaceOpShapeHelper(ONNXDepthToSpaceOp *newOp);
ONNXDepthToSpaceOpShapeHelper(ONNXDepthToSpaceOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXDepthToSpaceOpAdaptor operandAdaptor);
};
// Shape for SliceOp.
struct ONNXSliceOpShapeHelper : public ONNXOpShapeHelper<ONNXSliceOp> {
ONNXSliceOpShapeHelper(ONNXSliceOp *newOp);
ONNXSliceOpShapeHelper(ONNXSliceOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXSliceOpAdaptor operandAdaptor);
// Additional data for SliceOp.
SmallVector<IndexExpr, 4> starts;
SmallVector<IndexExpr, 4> ends;
SmallVector<IndexExpr, 4> steps;
};
// Shape for Tile.
struct ONNXTileOpShapeHelper : public ONNXOpShapeHelper<ONNXTileOp> {
ONNXTileOpShapeHelper(ONNXTileOp *newOp);
ONNXTileOpShapeHelper(ONNXTileOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXTileOpAdaptor operandAdaptor);
};
// Shape for GemmOp. Rank of C is known, and its rank can be 0, 1, or 2. Each
// of the dimensions of C can have 1 (broadcast) or many (same size as position
// requires).
struct ONNXGemmOpShapeHelper : public ONNXOpShapeHelper<ONNXGemmOp> {
ONNXGemmOpShapeHelper(ONNXGemmOp *newOp);
ONNXGemmOpShapeHelper(ONNXGemmOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXGemmOpAdaptor operandAdaptor);
// Additional data for GemmOp: output = a * b.
SmallVector<IndexExpr, 4> aDims; // Dim of A, after applying transpose.
SmallVector<IndexExpr, 4> bDims; // Dim of B, after applying transpose.
SmallVector<IndexExpr, 4> cDims; // Dim of C, padding "1" when broadcast.
bool hasBias; // Whether there is a bias (aka C exists).
int cRank; // Dim of the original C (not padding dims by 1).
};
// Shape for MatMulOp.
struct ONNXMatMulOpShapeHelper : public ONNXOpShapeHelper<ONNXMatMulOp> {
ONNXMatMulOpShapeHelper(ONNXMatMulOp *newOp);
ONNXMatMulOpShapeHelper(ONNXMatMulOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXMatMulOpAdaptor operandAdaptor);
// Additional data for MatMulOp: output = a & b.
SmallVector<IndexExpr, 4> aDims; // Dim of A, after applying padding.
SmallVector<IndexExpr, 4> bDims; // Dim of B, after applying padding.
llvm::BitVector aPadDims; // When true, that dim was padded.
llvm::BitVector bPadDims; // When true, that dim was padded.
};
// Shape for Gather.
struct ONNXGatherOpShapeHelper : public ONNXOpShapeHelper<ONNXGatherOp> {
ONNXGatherOpShapeHelper(ONNXGatherOp *newOp);
ONNXGatherOpShapeHelper(ONNXGatherOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXGatherOpAdaptor operandAdaptor);
// Additional data for GatherOp.
SmallVector<IndexExpr, 4> dataDims; // Dim of data.
SmallVector<IndexExpr, 4> indicesDims; // Dim of indices.
bool positiveConstantIndices; // True when all indices are positive consants.
};
// Shape for SpaceToDepth.
struct ONNXSpaceToDepthOpShapeHelper
: public ONNXOpShapeHelper<ONNXSpaceToDepthOp> {
ONNXSpaceToDepthOpShapeHelper(ONNXSpaceToDepthOp *newOp);
ONNXSpaceToDepthOpShapeHelper(ONNXSpaceToDepthOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXSpaceToDepthOpAdaptor operandAdaptor);
};
// Shape for SplitOp.
struct ONNXSplitOpShapeHelper : public ONNXOpShapeHelper<ONNXSplitOp> {
ONNXSplitOpShapeHelper(ONNXSplitOp *newOp);
ONNXSplitOpShapeHelper(ONNXSplitOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXSplitOpAdaptor operandAdaptor);
};
// Shape for SplitV11Op.
struct ONNXSplitV11OpShapeHelper : public ONNXOpShapeHelper<ONNXSplitV11Op> {
ONNXSplitV11OpShapeHelper(ONNXSplitV11Op *newOp);
ONNXSplitV11OpShapeHelper(ONNXSplitV11Op *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXSplitV11OpAdaptor operandAdaptor);
};
// Shape for TransposeOp.
struct ONNXTransposeOpShapeHelper : public ONNXOpShapeHelper<ONNXTransposeOp> {
ONNXTransposeOpShapeHelper(ONNXTransposeOp *newOp);
ONNXTransposeOpShapeHelper(ONNXTransposeOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXTransposeOpAdaptor operandAdaptor);
};
// Shape for LRN.
struct ONNXLRNOpShapeHelper : public ONNXOpShapeHelper<ONNXLRNOp> {
ONNXLRNOpShapeHelper(ONNXLRNOp *newOp);
ONNXLRNOpShapeHelper(ONNXLRNOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXLRNOpAdaptor operandAdaptor);
};
// Shape for generic pooling/conv ops.
template <typename OP_TYPE, typename OP_ADAPTOR>
struct ONNXGenericPoolShapeHelper : public ONNXOpShapeHelper<OP_TYPE> {
ONNXGenericPoolShapeHelper(OP_TYPE *newOp, bool hasFilter, bool ceilMode)
: ONNXOpShapeHelper<OP_TYPE>(
newOp, newOp->getOperation()->getNumResults()),
hasFilter(hasFilter), ceilMode(ceilMode) {}
ONNXGenericPoolShapeHelper(OP_TYPE *newOp, bool hasFilter, bool ceilMode,
OpBuilder *rewriter, ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal)
: ONNXOpShapeHelper<OP_TYPE>(newOp,
newOp->getOperation()->getNumResults(), rewriter, fGetDenseVal,
fLoadVal),
hasFilter(hasFilter), ceilMode(ceilMode) {}
LogicalResult computeShape(OP_ADAPTOR operandAdaptor, Value filterValue,
Optional<ArrayAttr> kernelShapeOpt, Optional<ArrayAttr> padOpt,
Optional<ArrayAttr> strideOpt, Optional<ArrayAttr> dilationOpt);
// Additional data for Pool operations.
bool hasFilter; // If has filter, it also has CO and optional kernel.
bool ceilMode; // Use ceil or floor for auto_pad=NOTSET policy.
// Values set by Compute.
SmallVector<IndexExpr, 2> kernelShape;
SmallVector<IndexExpr, 4> pads;
SmallVector<int64_t, 2> strides;
SmallVector<int64_t, 2> dilations;
};
// Shape for Conv.
struct ONNXConvOpShapeHelper
: public ONNXGenericPoolShapeHelper<ONNXConvOp, ONNXConvOpAdaptor> {
ONNXConvOpShapeHelper(ONNXConvOp *newOp);
ONNXConvOpShapeHelper(ONNXConvOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXConvOpAdaptor operandAdaptor);
};
// Shape for MaxPoolSingleOut.
struct ONNXMaxPoolSingleOutOpShapeHelper
: public ONNXGenericPoolShapeHelper<ONNXMaxPoolSingleOutOp,
ONNXMaxPoolSingleOutOpAdaptor> {
ONNXMaxPoolSingleOutOpShapeHelper(ONNXMaxPoolSingleOutOp *newOp)
: ONNXGenericPoolShapeHelper<ONNXMaxPoolSingleOutOp,
ONNXMaxPoolSingleOutOpAdaptor>(
newOp, false /*hasFilter*/, newOp->ceil_mode()) {}
ONNXMaxPoolSingleOutOpShapeHelper(ONNXMaxPoolSingleOutOp *newOp,
OpBuilder *rewriter, ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal)
: ONNXGenericPoolShapeHelper<ONNXMaxPoolSingleOutOp,
ONNXMaxPoolSingleOutOpAdaptor>(newOp, false /*hasFilter*/,
newOp->ceil_mode(), rewriter, fGetDenseVal, fLoadVal) {}
LogicalResult computeShape(ONNXMaxPoolSingleOutOpAdaptor operandAdaptor);
};
// Shape for ONNXAveragePoolOp
struct ONNXAveragePoolOpShapeHelper
: public ONNXGenericPoolShapeHelper<ONNXAveragePoolOp,
ONNXAveragePoolOpAdaptor> {
ONNXAveragePoolOpShapeHelper(ONNXAveragePoolOp *newOp)
: ONNXGenericPoolShapeHelper<ONNXAveragePoolOp, ONNXAveragePoolOpAdaptor>(
newOp, false /*hasFilter*/, newOp->ceil_mode()) {}
ONNXAveragePoolOpShapeHelper(ONNXAveragePoolOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal)
: ONNXGenericPoolShapeHelper<ONNXAveragePoolOp, ONNXAveragePoolOpAdaptor>(
newOp, false /*hasFilter*/, newOp->ceil_mode(), rewriter,
fGetDenseVal, fLoadVal) {}
LogicalResult computeShape(ONNXAveragePoolOpAdaptor operandAdaptor);
};
// Shape for Reduction.
struct ONNXReduceSumOpShapeHelper : public ONNXOpShapeHelper<ONNXReduceSumOp> {
ONNXReduceSumOpShapeHelper(ONNXReduceSumOp *newOp);
ONNXReduceSumOpShapeHelper(ONNXReduceSumOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXReduceSumOpAdaptor operandAdaptor);
};
// Shape for ReshapeOp.
struct ONNXReshapeOpShapeHelper : public ONNXOpShapeHelper<ONNXReshapeOp> {
ONNXReshapeOpShapeHelper(ONNXReshapeOp *newOp);
ONNXReshapeOpShapeHelper(ONNXReshapeOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXReshapeOpAdaptor operandAdaptor);
};
// Shape for ONNXReverseSequence.
struct ONNXReverseSequenceOpShapeHelper
: public ONNXOpShapeHelper<ONNXReverseSequenceOp> {
ONNXReverseSequenceOpShapeHelper(
ONNXReverseSequenceOp *newOp, IndexExprScope *inScope = nullptr);
ONNXReverseSequenceOpShapeHelper(ONNXReverseSequenceOp *newOp,
OpBuilder *rewriter, ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal,
IndexExprScope *inScope = nullptr);
LogicalResult Compute(ONNXReverseSequenceOpAdaptor operandAdaptor);
};
// Shape for SqueezeOp.
struct ONNXSqueezeOpShapeHelper : public ONNXOpShapeHelper<ONNXSqueezeOp> {
ONNXSqueezeOpShapeHelper(ONNXSqueezeOp *newOp);
ONNXSqueezeOpShapeHelper(ONNXSqueezeOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXSqueezeOpAdaptor operandAdaptor);
};
// Shape for SqueezeV11Op.
struct ONNXSqueezeV11OpShapeHelper
: public ONNXOpShapeHelper<ONNXSqueezeV11Op> {
ONNXSqueezeV11OpShapeHelper(ONNXSqueezeV11Op *newOp);
ONNXSqueezeV11OpShapeHelper(ONNXSqueezeV11Op *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXSqueezeV11OpAdaptor operandAdaptor);
};
// Shape for UnsqueezeOp.
struct ONNXUnsqueezeOpShapeHelper : public ONNXOpShapeHelper<ONNXUnsqueezeOp> {
ONNXUnsqueezeOpShapeHelper(ONNXUnsqueezeOp *newOp);
ONNXUnsqueezeOpShapeHelper(ONNXUnsqueezeOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXUnsqueezeOpAdaptor operandAdaptor);
};
// Shape for UnsqueezeV11Op.
struct ONNXUnsqueezeV11OpShapeHelper
: public ONNXOpShapeHelper<ONNXUnsqueezeV11Op> {
ONNXUnsqueezeV11OpShapeHelper(ONNXUnsqueezeV11Op *newOp);
ONNXUnsqueezeV11OpShapeHelper(ONNXUnsqueezeV11Op *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXUnsqueezeV11OpAdaptor operandAdaptor);
};
// Shape for ONNXShapeOp.
struct ONNXShapeOpShapeHelper : public ONNXOpShapeHelper<ONNXShapeOp> {
ONNXShapeOpShapeHelper(ONNXShapeOp *newOp, IndexExprScope *inScope = nullptr);
ONNXShapeOpShapeHelper(ONNXShapeOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal,
IndexExprScope *inScope = nullptr);
LogicalResult computeShape(ONNXShapeOpAdaptor operandAdaptor);
// Additional data for ShapeOp.
DimsExpr selectedData;
};
// Shape for PadOp.
struct ONNXPadOpShapeHelper : public ONNXOpShapeHelper<ONNXPadOp> {
ONNXPadOpShapeHelper(ONNXPadOp *newOp);
ONNXPadOpShapeHelper(ONNXPadOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXPadOpAdaptor operandAdaptor);
// Additional data for PadOp.
SmallVector<IndexExpr, 4> pads;
};
// Shape for ONNXExpandOp.
struct ONNXExpandOpShapeHelper
: public ONNXOpBroadcastedShapeHelper<ONNXExpandOp> {
ONNXExpandOpShapeHelper(ONNXExpandOp *newOp);
ONNXExpandOpShapeHelper(ONNXExpandOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXExpandOpAdaptor operandAdaptor);
// Additional data for ExpandOp.
ONNXExpandOp *expandOp;
};
// Shape for OneHotOp.
struct ONNXOneHotOpShapeHelper : public ONNXOpShapeHelper<ONNXOneHotOp> {
ONNXOneHotOpShapeHelper(ONNXOneHotOp *newOp);
ONNXOneHotOpShapeHelper(ONNXOneHotOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXOneHotOpAdaptor operandAdaptor);
// Additional data for ExpandOp.
int64_t axis = -1; // Default value.
IndexExpr depth; // Depth which may/maynot be known at compile time.
};
// Shape for ONNXCompressOp.
struct ONNXCompressOpShapeHelper : public ONNXOpShapeHelper<ONNXCompressOp> {
ONNXCompressOpShapeHelper(ONNXCompressOp *newOp);
ONNXCompressOpShapeHelper(ONNXCompressOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXCompressOpAdaptor operandAdaptor);
// Additional data for CompressOp.
int axis = -1; // Value -1 signify axis was not specified.
};
// Shape for ONNXTopKOp.
struct ONNXTopKOpShapeHelper : public ONNXOpShapeHelper<ONNXTopKOp> {
ONNXTopKOpShapeHelper(ONNXTopKOp *newOp);
ONNXTopKOpShapeHelper(ONNXTopKOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXTopKOpAdaptor operandAdaptor);
};
// Shape for ONNXCategoryMapperOp.
struct ONNXCategoryMapperOpShapeHelper
: public ONNXOpShapeHelper<ONNXCategoryMapperOp> {
ONNXCategoryMapperOpShapeHelper(ONNXCategoryMapperOp *newOp);
ONNXCategoryMapperOpShapeHelper(ONNXCategoryMapperOp *newOp,
OpBuilder *rewriter, ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXCategoryMapperOpAdaptor operandAdaptor);
};
// Shape for ONNXRoiAlignOp
struct ONNXRoiAlignOpShapeHelper : public ONNXOpShapeHelper<ONNXRoiAlignOp> {
ONNXRoiAlignOpShapeHelper(ONNXRoiAlignOp *newOp);
ONNXRoiAlignOpShapeHelper(ONNXRoiAlignOp *newOp, OpBuilder *rewriter,
ArrayValueIndexCapture::GetDenseVal fGetDenseVal,
ArrayValueIndexCapture::LoadVal fLoadVal);
LogicalResult computeShape(ONNXRoiAlignOpAdaptor operandAdaptor);
// Additional data for RoiAlignOp.
SmallVector<IndexExpr, 4> xDims; // Dim of X.
SmallVector<IndexExpr, 1> batchIndicesDims; // Dim of batch_indices.
};
| 43.318996 | 80 | 0.768244 | [
"object",
"shape",
"vector"
] |
29ae158f5c79ffc8b4db399d4ac20456dca47af9 | 3,731 | cc | C++ | proxy/src/onlProxy.cc | WU-ARL/ONLdaemons | d01e84a1fb80065d2e2ab7dca5b6f2c72313760f | [
"Apache-2.0"
] | null | null | null | proxy/src/onlProxy.cc | WU-ARL/ONLdaemons | d01e84a1fb80065d2e2ab7dca5b6f2c72313760f | [
"Apache-2.0"
] | null | null | null | proxy/src/onlProxy.cc | WU-ARL/ONLdaemons | d01e84a1fb80065d2e2ab7dca5b6f2c72313760f | [
"Apache-2.0"
] | null | null | null | /*
* $Source: /project/arl/arlcvs/cvsroot/wu_arl/openNetLab/proxy/onlProxy.cc,v $
* $Author: cgw1 $
* $Date: 2007/03/23 21:05:05 $
* $Revision: 1.9 $
* $Name: $
*
* File: try.c
* Created: 12/29/2004 10:56:15 AM CST
* Author: Fred Kunhns, <fredk@cse.wustl.edu>
* Organization: Applied Research Laboratory,
* Washington University in St. Louis
*
* Description:
*
*/
#include <iostream>
#include <sstream>
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <getopt.h>
#include <wulib/wulog.h>
#include <signal.h>
using namespace std;
#include <wuPP/net.h>
#include <wuPP/addr.h>
#include <wuPP/sock.h>
#include <wuPP/buf.h>
#include <wuPP/msg.h>
#include "control.h"
#include "cmd.h"
#include "nccp.h"
#include "basicConn.h"
#include "streamConn.h"
#include "session.h"
#include "proxy.h"
const int default_port = 7070;
void print_usage(char *prog)
{
std::cout << prog << " --help\n";
std::cout << prog << " [-d] [--addr ip/host] [--port pn] [--proto pr] -l lvl\n";
std::cout << "\t-d: run as a damon, log messages set to syslogd (local0)\n"
<< "\t-l lvl: Default logging level\n"
<< "\t--addr ip/host: default 0.0.0.0 (any interface)\n"
<< "\t--port pn: default is " << default_port << "\n"
<< "\t--proto pr: tcp is the only porotocol currently supported\n\n";
}
int
main(int argc, char **argv)
{
std::string servIP = "0.0.0.0";
in_port_t servPort = default_port;
int connProto = IPPROTO_TCP;
char *prog = argv[0];
wulogFlags_t logFlags = wulog_useLocal | wulog_useTStamp;
wulogLvl_t logLvl = wulogInfo;
int mode = 0;
#define OPT_NOARG 0 /* no argument required */
#define OPT_REQARG 1 /* required argument */
#define OPT_OPTARG 2 /* argument is optional */
static struct option longopts[] =
{{"help", OPT_NOARG, NULL, 'h'},
{"addr", OPT_REQARG, NULL, 1},
{"port", OPT_REQARG, NULL, 2},
{"proto", OPT_REQARG, NULL, 3},
{"lvl", OPT_REQARG, NULL, 'l'},
{NULL, 0, NULL, 0}
};
int c;
while ((c = getopt_long(argc, argv, "hl:d", longopts, NULL)) != -1) {
switch (c) {
case 'd':
logFlags = wulog_useSyslog;
mode = 1;
break;
case 'h':
print_usage(prog);
return 1;
break;
case 'l':
logLvl = wulogName2Lvl(optarg);
if (logLvl == wulogInvLvl) {
std::cerr << "Invalid wulog level specified: " << optarg << "\n";
wulogPrintLvls();
return 1;
}
break;
case 1:
servIP = optarg;
break;
case 2:
servPort = in_port_t(atoi(optarg));
break;
case 3:
struct protoent *pent;
if (isalpha(*optarg))
pent = getprotobyname(optarg);
else
pent = getprotobynumber(strtol(optarg, NULL, 0));
if (pent == NULL) {
std::cerr << "Invalid protocol " << optarg << "\n";
return 1;
}
connProto = int(pent->p_proto);
break;
default:
std::cerr << "Unknown option " << c << "\n";
return 1;
break;
}
}
// {name, has_arg, flag, val}
wulogInit(proxyInfo, modCnt, logLvl, "Proxy", logFlags);
wulogSetLvl(wulogProxy, logLvl);
if (mode)
daemon(0, 0);
wulog(wulogApp, wulogInfo, "Calling proxy manager (%s, %d, %d)\n", servIP.c_str(), (int)servPort, connProto);
Proxy::Manager *proxy = Proxy::Manager::getManager(servIP, servPort, connProto);
proxy->run();
return(0);
}
| 25.554795 | 111 | 0.578397 | [
"vector"
] |
29ae310c2b53e44bc27c75d168f4eb24f3ecfe50 | 13,382 | cpp | C++ | qwebrtcpeerconnection.cpp | strfry/qwebrtc | 8f1a4e2a038b37d6c780477c7945387a478163ac | [
"BSD-3-Clause"
] | 1 | 2021-07-31T12:07:08.000Z | 2021-07-31T12:07:08.000Z | qwebrtcpeerconnection.cpp | strfry/qwebrtc | 8f1a4e2a038b37d6c780477c7945387a478163ac | [
"BSD-3-Clause"
] | null | null | null | qwebrtcpeerconnection.cpp | strfry/qwebrtc | 8f1a4e2a038b37d6c780477c7945387a478163ac | [
"BSD-3-Clause"
] | 2 | 2018-06-15T20:44:34.000Z | 2020-01-08T00:24:12.000Z | #include <memory>
#include "qwebrtcpeerconnection.hpp"
#include "qwebrtcpeerconnection_p.hpp"
#include "qwebrtcmediastream_p.hpp"
#include "qwebrtcdatachannel_p.hpp"
#include "qwebrtctypes_p.hpp"
#include "qwebrtcicecandidate.hpp"
#include <api/peerconnectioninterface.h>
#include <api/datachannelinterface.h>
#include <api/mediaconstraintsinterface.h>
#include <api/jsepicecandidate.h>
#include <QVariantMap>
#include <QDebug>
#include <assert.h>
#include "modules/video_capture/video_capture_factory.h"
void QWebRTCCreateSessionDescriptionObserver_p::OnSuccess(webrtc::SessionDescriptionInterface* desc)
{
invokeHandler(QSharedPointer<QWebRTCSessionDescription_impl>(new QWebRTCSessionDescription_impl(desc)));
}
void QWebRTCCreateSessionDescriptionObserver_p::OnFailure(const std::string& error)
{
qWarning() << "Could not create session description " << QByteArray::fromStdString(error);
invokeHandler(QSharedPointer<QWebRTCSessionDescription>());
}
void QWebRTCCreateSessionDescriptionObserver_p::invokeHandler(const QSharedPointer<QWebRTCSessionDescription>& result)
{
// auto sImpl = impl.lock();
if (m_completionHandler) {
m_completionHandler(result);
}
// if (sImpl) {
// // remove adapter from observer list
// for (auto it = sImpl->m_createObservers.begin(); it!= sImpl->m_createObservers.end(); ++it) {
// if ((*it).get() == this) {
// sImpl->m_createObservers.erase(it);
// return;
// }
// }
// }
}
void QWebRTCSetSessionDescriptionObserver_p::OnSuccess()
{
qDebug() << "description set";
invokeHandler(true);
}
void QWebRTCSetSessionDescriptionObserver_p::OnFailure(const std::string& error)
{
qWarning() << "Could not set session description " << QByteArray::fromStdString(error);
invokeHandler(false);
}
void QWebRTCSetSessionDescriptionObserver_p::invokeHandler(bool success)
{
// auto sImpl = impl.lock();
if (m_completionHandler) {
m_completionHandler(success);
}
// if (sImpl) {
// // remove adapter from observer list
// for (auto it = sImpl->m_setObservers.begin(); it!= sImpl->m_setObservers.end(); ++it) {
// if ((*it).get() == this) {
// sImpl->m_setObservers.erase(it);
// return;
// }
// }
// }
}
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions mapToRTCOfferAnserOptions(const QVariantMap& map)
{
auto result = webrtc::PeerConnectionInterface::RTCOfferAnswerOptions();
if (map.contains("receiveVideo")) {
result.offer_to_receive_video = map["receiveVideo"].toInt();
}
if (map.contains("receiveAudio")) {
result.offer_to_receive_audio = map["receiveAudio"].toInt();
}
if (map.contains("voiceActivityDetection")) {
result.voice_activity_detection = map["voiceActivityDetection"].toBool();
}
if (map.contains("iceRestart")) {
result.ice_restart = map["iceRestart"].toBool();
}
if (map.contains("useRtpMux")) {
result.use_rtp_mux = map["useRtpMux"].toBool();
}
return result;
}
QVariantMap RTCOfferAnserOptionsToMap(const webrtc::PeerConnectionInterface::RTCOfferAnswerOptions& options)
{
QVariantMap result;
result["receiveVideo"] = options.offer_to_receive_video;
result["receiveAudio"] = options.offer_to_receive_audio;
result["voiceActivityDetection"] = options.voice_activity_detection;
result["iceRestart"] = options.ice_restart;
result["useRtpMux"] = options.use_rtp_mux;
return result;
}
void QWebRTCPeerConnection::close()
{
if(m_impl->_conn) {
m_impl->_conn->Close();
}
}
void QWebRTCPeerConnection::createOfferForConstraints(const QVariantMap& constraints,
std::function<void(const QSharedPointer<QWebRTCSessionDescription>&)> completionHandler)
{
auto observer = new rtc::RefCountedObject<QWebRTCCreateSessionDescriptionObserver_p>();
observer->m_completionHandler = completionHandler;
//observer->impl = m_impl;
//m_impl->m_createObservers.append(new rtc::RefCountedObject<QWebRTCCreateSessionDescriptionObserver_p>());
m_impl->_conn->CreateOffer(observer, mapToRTCOfferAnserOptions(constraints));
}
void QWebRTCPeerConnection::createAnswerForConstraints(const QVariantMap& constraints,
std::function<void(const QSharedPointer<QWebRTCSessionDescription>&)> completionHandler)
{
auto observer = new rtc::RefCountedObject<QWebRTCCreateSessionDescriptionObserver_p>();
observer->m_completionHandler = completionHandler;
//observer->impl = m_impl;
//m_impl->m_createObservers.append(new rtc::RefCountedObject<QWebRTCCreateSessionDescriptionObserver_p>());
m_impl->_conn->CreateAnswer(observer, webrtc::PeerConnectionInterface::RTCOfferAnswerOptions());
}
void QWebRTCPeerConnection::addStream(const QSharedPointer<QWebRTCMediaStream>& stream)
{
assert(m_impl);
assert(m_impl->_conn);
if (!stream) {
return;
}
auto streamImpl = qSharedPointerCast<QWebRTCMediaStream_impl>(stream);
m_impl->_conn->AddStream(streamImpl->m_nativeStream);
}
void QWebRTCPeerConnection::removeStream(const QSharedPointer<QWebRTCMediaStream>& stream)
{
assert(m_impl);
assert(m_impl->_conn);
if (!stream) {
return;
}
auto streamImpl = qSharedPointerCast<QWebRTCMediaStream_impl>(stream);
m_impl->_conn->RemoveStream(streamImpl->m_nativeStream);
}
void QWebRTCPeerConnection::setConfiguration()
{
}
void QWebRTCPeerConnection::setLocalDescription(const QSharedPointer<QWebRTCSessionDescription>& description,
std::function<void(bool)> completionHandler)
{
qDebug() << "setting local description";
assert(m_impl);
assert(m_impl->_conn);
if (description->isValid()) {
m_impl->m_localDescription = description;
auto observer = new rtc::RefCountedObject<QWebRTCSetSessionDescriptionObserver_p>();
observer->m_completionHandler = completionHandler;
//observer->impl = m_impl;
observer->m_remoteDescription = false;
observer->m_description = description;
//m_impl->m_setObservers.append(observer);
m_impl->_conn->SetLocalDescription(observer,
qSharedPointerCast<QWebRTCSessionDescription_impl>(description)->getNativeDescription());
} else {
qWarning() << "session description invalid";
}
}
void QWebRTCPeerConnection::setRemoteDescription(const QSharedPointer<QWebRTCSessionDescription>& description,
std::function<void(bool)> completionHandler)
{
qDebug() << "setting remote description";
assert(m_impl);
assert(m_impl->_conn);
if (description->isValid()) {
m_impl->m_remoteDescription = description;
rtc::scoped_refptr<QWebRTCSetSessionDescriptionObserver_p> observer(
new rtc::RefCountedObject<QWebRTCSetSessionDescriptionObserver_p>());
observer->m_completionHandler = completionHandler;
//observer->impl = m_impl;
observer->m_remoteDescription = true;
observer->m_description = description;
//m_impl->m_setObservers.append(observer);
m_impl->_conn->SetRemoteDescription(observer,
qSharedPointerCast<QWebRTCSessionDescription_impl>(description)->getNativeDescription());
} else {
qWarning() << "session description invalid";
}
}
void QWebRTCPeerConnection::addIceCandidate(const QSharedPointer<QWebRTCIceCandidate>& iceCandidate)
{
assert(m_impl);
assert(m_impl->_conn);
if (iceCandidate->isValid()) {
m_impl->_conn->AddIceCandidate(
qSharedPointerCast<QWebRTCIceCandidate_impl>(iceCandidate)->iceCandidate());
} else {
qWarning() << "invalid ICE candidate";
}
}
void QWebRTCPeerConnection::removeIceCandidate(const QSharedPointer<QWebRTCIceCandidate>& iceCandidate)
{
assert(m_impl);
assert(m_impl->_conn);
if (iceCandidate->isValid()) {
m_impl->_conn->AddIceCandidate(
qSharedPointerCast<QWebRTCIceCandidate_impl>(iceCandidate)->iceCandidate());
} else {
qWarning() << "invalid ICE candidate";
}
}
QSharedPointer<QWebRTCDataChannel> QWebRTCPeerConnection::dataChannelForLabel(const QString& label, const QWebRTCDataChannelConfig& config)
{
const webrtc::DataChannelInit nativeInit;
return QSharedPointer<QWebRTCDataChannel_impl>(new QWebRTCDataChannel_impl(m_impl->_conn->CreateDataChannel(label.toStdString(), 0)));
}
QSharedPointer<QWebRTCSessionDescription> QWebRTCPeerConnection::createSessionDescription(QWebRTCSessionDescription::SDPType type,
const QByteArray& sdp)
{
return QSharedPointer<QWebRTCSessionDescription_impl>(new QWebRTCSessionDescription_impl(type, sdp));
}
QSharedPointer<QWebRTCIceCandidate> QWebRTCPeerConnection::createIceCandidate(QByteArray mId, int sdpMLineIndex,
const QByteArray& sdpData)
{
return QSharedPointer<QWebRTCIceCandidate_impl>(new QWebRTCIceCandidate_impl(mId, sdpMLineIndex, sdpData));
}
QSharedPointer<QWebRTCSessionDescription> QWebRTCPeerConnection::currentLocalDescription()
{
if (!m_impl->_conn->current_local_description())
return QSharedPointer<QWebRTCSessionDescription>();
return QSharedPointer<QWebRTCSessionDescription_impl>(new QWebRTCSessionDescription_impl(m_impl->_conn->current_local_description()));
}
QSharedPointer<QWebRTCSessionDescription> QWebRTCPeerConnection::currentRemoteDescription()
{
if (!m_impl->_conn->current_remote_description())
return QSharedPointer<QWebRTCSessionDescription>();
return QSharedPointer<QWebRTCSessionDescription_impl>(new QWebRTCSessionDescription_impl(m_impl->_conn->current_local_description()));
}
QWebRTCPeerConnection::SignalingState QWebRTCPeerConnection::signalingState()
{
return static_cast<QWebRTCPeerConnection::SignalingState>(m_impl->_conn->signaling_state());
}
QWebRTCPeerConnection::IceConnectionState QWebRTCPeerConnection::iceConnectionState()
{
return static_cast<QWebRTCPeerConnection::IceConnectionState>(m_impl->_conn->ice_connection_state());
}
QWebRTCPeerConnection::IceGatheringState QWebRTCPeerConnection::iceGatheringState()
{
return static_cast<QWebRTCPeerConnection::IceGatheringState>(m_impl->_conn->ice_gathering_state());
}
QWebRTCPeerConnection::QWebRTCPeerConnection()
: m_impl(new QWebRTCPeerConnection_impl(this))
{
}
QWebRTCPeerConnection::~QWebRTCPeerConnection()
{
delete m_impl;
}
QWebRTCPeerConnection_impl::QWebRTCPeerConnection_impl(QWebRTCPeerConnection* q_ptr)
: q_ptr(q_ptr)
{
qDebug() << "Creating QWebRTCPeerConnection";
}
QWebRTCPeerConnection_impl::~QWebRTCPeerConnection_impl()
{
qDebug() << "Destroying QWebRTCPeerConnection";
}
void QWebRTCPeerConnection_impl::OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state)
{
qDebug() << "signaling change " << (int) new_state;
q_ptr->signalingChange();
}
void QWebRTCPeerConnection_impl::OnAddStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
auto qStream = QSharedPointer<QWebRTCMediaStream_impl>(new QWebRTCMediaStream_impl(stream));
Q_EMIT q_ptr->streamAdded(qStream);
qDebug() << "Stream added " << QString::fromStdString(stream->id());
}
void QWebRTCPeerConnection_impl::OnRemoveStream(rtc::scoped_refptr<webrtc::MediaStreamInterface> stream)
{
auto qStream = QSharedPointer<QWebRTCMediaStream_impl>(new QWebRTCMediaStream_impl(stream));
Q_EMIT q_ptr->streamRemoved(qStream);
}
void QWebRTCPeerConnection_impl::OnDataChannel(rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel)
{
qDebug() << "New data channel";
Q_EMIT q_ptr->dataChannelReceived(QSharedPointer<QWebRTCDataChannel_impl>(new QWebRTCDataChannel_impl(data_channel)));
}
void QWebRTCPeerConnection_impl::OnRenegotiationNeeded() {
qDebug() << "Negotiation needed";
Q_EMIT q_ptr->renegotiationNeeded();
}
void QWebRTCPeerConnection_impl::OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state)
{
Q_EMIT q_ptr->iceConnectionStateChanged();
}
void QWebRTCPeerConnection_impl::OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state)
{
Q_EMIT q_ptr->iceGatheringChanged();
}
void QWebRTCPeerConnection_impl::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
qDebug() << "Ice candidate ready";
Q_EMIT q_ptr->newIceCandidate(QSharedPointer<QWebRTCIceCandidate_impl>(new QWebRTCIceCandidate_impl(candidate)));
}
void QWebRTCPeerConnection_impl::OnIceCandidatesRemoved(const std::vector<cricket::Candidate>& candidates)
{
std::vector<QSharedPointer<QWebRTCIceCandidate_impl>> can;
for (auto candidate : candidates) {
std::unique_ptr<webrtc::JsepIceCandidate> candidate_wrapper(
new webrtc::JsepIceCandidate(candidate.transport_name(), -1, candidate));
can.push_back(QSharedPointer<QWebRTCIceCandidate_impl>(new QWebRTCIceCandidate_impl(candidate_wrapper.get())));
}
qDebug() << "Ice candidate removed";
}
void QWebRTCPeerConnection_impl::OnIceConnectionReceivingChange(bool receiving)
{
}
void QWebRTCPeerConnection_impl::OnAddTrack(rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver,
const std::vector<rtc::scoped_refptr<webrtc::MediaStreamInterface>>& streams) {
qDebug() << "video track added";
}
| 36.966851 | 139 | 0.745404 | [
"vector"
] |
29afa87ce0a2e715c8702a15d7b6efe88983b31a | 23,539 | cpp | C++ | libnd4j/include/loops/cpu/broadcasting_bool.cpp | achalagarwal/deeplearning4j | 91219603a0ba7bdc34198b3f19fc84d068d2b499 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/loops/cpu/broadcasting_bool.cpp | achalagarwal/deeplearning4j | 91219603a0ba7bdc34198b3f19fc84d068d2b499 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/loops/cpu/broadcasting_bool.cpp | achalagarwal/deeplearning4j | 91219603a0ba7bdc34198b3f19fc84d068d2b499 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author raver119@gmail.com
//
#include <op_boilerplate.h>
#include <loops/broadcasting_bool.h>
#include <loops/legacy_ops.h>
#include <types/types.h>
using namespace simdOps;
namespace functions {
namespace broadcast {
template <typename X, typename Y>
void BroadcastBool<X, Y>::exec(const int opNum,
void *x,
Nd4jLong *xShapeInfo,
void *y,
Nd4jLong *yShapeInfo,
void *z,
Nd4jLong *zShapeInfo,
int *dimension,
int dimensionLength,
Nd4jLong *tadShapeInfo,
Nd4jLong *tadOffset,
Nd4jLong *tadShapeInfoZ,
Nd4jLong *tadOffsetZ) {
DISPATCH_BY_OPNUM_TT(exec, PARAMS(x,
xShapeInfo,
y,
yShapeInfo,
z,
zShapeInfo,
dimension,
dimensionLength,
tadShapeInfo,
tadOffset,
tadShapeInfoZ,
tadOffsetZ), BROADCAST_BOOL_OPS);
}
template <typename X, typename Y>
void BroadcastBool<X, Y>::execInverse(const int opNum,
void *x,
Nd4jLong *xShapeInfo,
void *y,
Nd4jLong *yShapeInfo,
void *z,
Nd4jLong *zShapeInfo,
int *dimension,
int dimensionLength,
Nd4jLong *tadShapeInfo,
Nd4jLong *tadOffset,
Nd4jLong *tadShapeInfoZ,
Nd4jLong *tadOffsetZ) {
DISPATCH_BY_OPNUM_TT(exec, PARAMS(x,
xShapeInfo,
y,
yShapeInfo,
z,
zShapeInfo,
dimension,
dimensionLength,
tadShapeInfo,
tadOffset,
tadShapeInfoZ,
tadOffsetZ), BROADCAST_BOOL_OPS);
}
template <typename X, typename Z>
template<typename OpType>
void BroadcastBool<X, Z>::exec(void *vx,
Nd4jLong *xShapeInfo,
void *vy,
Nd4jLong *yShapeInfo,
void *vz,
Nd4jLong *zShapeInfo,
int *dimension,
int dimensionLength,
Nd4jLong *tadShapeInfo,
Nd4jLong *tadOffset,
Nd4jLong *tadShapeInfoZ,
Nd4jLong *tadOffsetZ) {
auto x = reinterpret_cast<X *>(vx);
auto y = reinterpret_cast<X *>(vy);
auto z = reinterpret_cast<Z *>(vz);
//decompose in to several sub tads after
//moving all dimensions (in sorted order)
//to the back.
//permuted version of the x shape info for setting up the tad problem
auto tadShapeShapeInfo = tadShapeInfo;
auto tadOffsets = tadOffset;
shape::TAD *tad = nullptr;
if (tadShapeInfo == nullptr || tadOffsets == nullptr) {
tad = new shape::TAD();
tad->init(xShapeInfo, dimension, dimensionLength);
tad->createTadOnlyShapeInfo();
tad->createOffsets();
tadShapeShapeInfo = tad->tadOnlyShapeInfo;
tadOffsets = tad->tadOffsets;
}
//int *resultStride = shape::stride(tadShapeShapeInfo);
unsigned int tadLength = shape::length(tadShapeShapeInfo);
unsigned int tads = shape::length(xShapeInfo) / tadLength;
if (tadShapeInfoZ == nullptr) {
tadShapeInfoZ = tadShapeShapeInfo;
tadOffsetZ = tadOffsets;
}
auto lenZ = shape::length(tadShapeInfoZ);
auto lenY = shape::length(yShapeInfo);
int tadsPerThread = tads / TAD_THRESHOLD;
int _threads = nd4j::math::nd4j_max<int>(1, tadsPerThread);
_threads = nd4j::math::nd4j_min<int>(_threads, omp_get_max_threads());
auto xEws = shape::elementWiseStride(tadShapeShapeInfo);
auto yEws = shape::elementWiseStride(yShapeInfo);
auto zEws = shape::elementWiseStride(tadShapeInfoZ);
if (shape::order(tadShapeShapeInfo) == shape::order(yShapeInfo) && shape::order(tadShapeInfoZ) == shape::order(yShapeInfo) && xEws > 0 && yEws > 0 && zEws > 0) {
if (xEws == 1 && yEws == 1 && zEws == 1) {
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oX = x + tadOffsets[i];
auto oZ = z + tadOffsetZ[i];
PRAGMA_OMP_SIMD
for (unsigned int f = 0; f < tadLength; f++)
oZ[f] = OpType::op(oX[f], y[f]);
}
} else {
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oX = x + tadOffsets[i];
auto oZ = z + tadOffsetZ[i];
PRAGMA_OMP_SIMD
for (unsigned int f = 0; f < tadLength; f++)
oZ[f * zEws] = OpType::op(oX[f * xEws], y[f * yEws]);
}
}
} else if(shape::haveSameOffsets(tadShapeShapeInfo, yShapeInfo) && shape::haveSameOffsets(tadShapeShapeInfo, tadShapeInfoZ)) {
uint tadShapeShapeInfoCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oX = x + tadOffsets[i];
// TODO: cover this codebranch with tests
// all this stuff already happens within thread
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto offset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastX);
oZ[offset] = OpType::op(oX[offset], y[offset]);
}
}
}
else if(shape::haveSameOffsets(tadShapeShapeInfo, yShapeInfo)) {
uint tadShapeShapeInfoCast[MAX_RANK];
uint tadShapeInfoZCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
bool canCastZ = nd4j::DataTypeUtils::castShapeInfo(tadShapeInfoZ, tadShapeInfoZCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oX = x + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto offset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastX);
auto zOffset = shape::indexOffset(f, tadShapeInfoZ, tadShapeInfoZCast, lenZ, canCastZ);
oZ[zOffset] = OpType::op(oX[offset], y[offset]);
}
}
}
else if(shape::haveSameOffsets(tadShapeShapeInfo, tadShapeInfoZ)) {
uint tadShapeShapeInfoCast[MAX_RANK];
uint yShapeInfoCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(yShapeInfo, yShapeInfoCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oX = x + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto offset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastX);
auto yOffset = shape::indexOffset(f, yShapeInfo, yShapeInfoCast, lenY, canCastY);
oZ[offset] = OpType::op(oX[offset], y[yOffset]);
}
}
}
else if(shape::haveSameOffsets(yShapeInfo, tadShapeInfoZ)) {
uint tadShapeShapeInfoCast[MAX_RANK];
uint yShapeInfoCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(yShapeInfo, yShapeInfoCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oX = x + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto xOffset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastX);
auto offset = shape::indexOffset(f, yShapeInfo, yShapeInfoCast, lenY, canCastY);
oZ[offset] = OpType::op(oX[xOffset], y[offset]);
}
}
}
else {
uint tadShapeShapeInfoCast[MAX_RANK];
uint tadShapeInfoZCast[MAX_RANK];
uint yShapeInfoCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(yShapeInfo, yShapeInfoCast);
bool canCastZ = nd4j::DataTypeUtils::castShapeInfo(tadShapeInfoZ, tadShapeInfoZCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oX = x + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto xOffset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastX);
auto yOffset = shape::indexOffset(f, yShapeInfo, yShapeInfoCast, lenY, canCastY);
auto zOffset = shape::indexOffset(f, tadShapeInfoZ, tadShapeInfoZCast, lenZ, canCastZ);
oZ[zOffset] = OpType::op(oX[xOffset], y[yOffset]);
}
}
}
if (tad != nullptr)
delete tad;
}
template <typename X, typename Z>
template<typename OpType>
void BroadcastBool<X, Z>::execInverse(void *vx,
Nd4jLong *xShapeInfo,
void *vy,
Nd4jLong *yShapeInfo,
void *vz,
Nd4jLong *zShapeInfo,
int *dimension,
int dimensionLength,
Nd4jLong *tadShapeInfo,
Nd4jLong *tadOffset,
Nd4jLong *tadShapeInfoZ,
Nd4jLong *tadOffsetZ) {
auto x = reinterpret_cast<X *>(vx);
auto y = reinterpret_cast<X *>(vy);
auto z = reinterpret_cast<Z *>(vz);
//decompose in to several sub tads after
//moving all dimensions (in sorted order)
//to the back.
//permuted version of the x shape info for setting up the tad problem
auto tadShapeShapeInfo = tadShapeInfo;
auto tadOffsets = tadOffset;
shape::TAD *tad = nullptr;
if (tadShapeInfo == nullptr || tadOffsets == nullptr) {
tad = new shape::TAD();
tad->init(yShapeInfo, dimension, dimensionLength);
tad->createTadOnlyShapeInfo();
tad->createOffsets();
tadShapeShapeInfo = tad->tadOnlyShapeInfo;
tadOffsets = tad->tadOffsets;
}
//int *resultStride = shape::stride(tadShapeShapeInfo);
unsigned int tadLength = shape::length(tadShapeShapeInfo);
unsigned int tads = shape::length(yShapeInfo) / tadLength;
if (tadShapeInfoZ == nullptr) {
tadShapeInfoZ = tadShapeShapeInfo;
tadOffsetZ = tadOffsets;
}
auto lenZ = shape::length(tadShapeInfoZ);
auto lenX = shape::length(xShapeInfo);
int tadsPerThread = tads / TAD_THRESHOLD;
int _threads = nd4j::math::nd4j_max<int>(1, tadsPerThread);
_threads = nd4j::math::nd4j_min<int>(_threads, omp_get_max_threads());
auto yEws = shape::elementWiseStride(tadShapeShapeInfo);
auto xEws = shape::elementWiseStride(xShapeInfo);
auto zEws = shape::elementWiseStride(tadShapeInfoZ);
if (shape::order(tadShapeShapeInfo) == shape::order(xShapeInfo) && shape::order(tadShapeInfoZ) == shape::order(xShapeInfo) && xEws > 0 && yEws > 0 && zEws > 0) {
if (xEws == 1 && yEws == 1 && zEws == 1) {
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oY = y + tadOffsets[i];
auto oZ = z + tadOffsetZ[i];
PRAGMA_OMP_SIMD
for (unsigned int f = 0; f < tadLength; f++)
oZ[f] = OpType::op(x[f], oY[f]);
}
} else {
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oY = y + tadOffsets[i];
auto oZ = z + tadOffsetZ[i];
PRAGMA_OMP_SIMD
for (uint f = 0; f < tadLength; f++)
oZ[f * zEws] = OpType::op(x[f * xEws], oY[f * yEws]);
}
}
} else if(shape::haveSameOffsets(tadShapeShapeInfo, xShapeInfo) && shape::haveSameOffsets(tadShapeShapeInfo, tadShapeInfoZ)) {
uint tadShapeShapeInfoCast[MAX_RANK];
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oY = y + tadOffsets[i];
auto oZ = z + tadOffsetZ[i];
// TODO: cover this codebranch with tests
// all this stuff already happens within thread
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto offset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastY);
oZ[offset] = OpType::op(x[offset], oY[offset]);
}
}
}
else if(shape::haveSameOffsets(tadShapeShapeInfo, xShapeInfo)) {
uint tadShapeShapeInfoCast[MAX_RANK];
uint tadShapeInfoZCast[MAX_RANK];
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
bool canCastZ = nd4j::DataTypeUtils::castShapeInfo(tadShapeInfoZ, tadShapeInfoZCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oY = y + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto offset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastY);
auto zOffset = shape::indexOffset(f, tadShapeInfoZ, tadShapeInfoZCast, lenZ, canCastZ);
oZ[zOffset] = OpType::op(x[offset], oY[offset]);
}
}
}
else if(shape::haveSameOffsets(tadShapeShapeInfo, tadShapeInfoZ)) {
uint tadShapeShapeInfoCast[MAX_RANK];
uint xShapeInfoCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(xShapeInfo, xShapeInfoCast);
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oY = y + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto offset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastY);
auto xOffset = shape::indexOffset(f, xShapeInfo, xShapeInfoCast, lenX, canCastX);
oZ[offset] = OpType::op(x[xOffset], oY[offset]);
}
}
}
else if(shape::haveSameOffsets(xShapeInfo, tadShapeInfoZ)) {
uint tadShapeShapeInfoCast[MAX_RANK];
uint xShapeInfoCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(xShapeInfo, xShapeInfoCast);
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oY = y + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto yOffset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastY);
auto offset = shape::indexOffset(f, xShapeInfo, xShapeInfoCast, lenX, canCastX);
oZ[offset] = OpType::op(x[offset], oY[yOffset]);
}
}
}
else {
uint xShapeInfoCast[MAX_RANK];
uint tadShapeShapeInfoCast[MAX_RANK];
uint tadShapeInfoZCast[MAX_RANK];
bool canCastX = nd4j::DataTypeUtils::castShapeInfo(xShapeInfo, xShapeInfoCast);
bool canCastY = nd4j::DataTypeUtils::castShapeInfo(tadShapeShapeInfo, tadShapeShapeInfoCast);
bool canCastZ = nd4j::DataTypeUtils::castShapeInfo(tadShapeInfoZ, tadShapeInfoZCast);
PRAGMA_OMP_PARALLEL_FOR_THREADS(_threads)
for (int i = 0; i < tads; i++) {
auto oZ = z + tadOffsetZ[i];
auto oY = y + tadOffsets[i];
PRAGMA_OMP_SIMD
for (int f = 0; f < tadLength; f++) {
auto xOffset = shape::indexOffset(f, xShapeInfo, xShapeInfoCast, lenX, canCastX);
auto yOffset = shape::indexOffset(f, tadShapeShapeInfo, tadShapeShapeInfoCast, tadLength, canCastY);
auto zOffset = shape::indexOffset(f, tadShapeInfoZ, tadShapeInfoZCast, lenZ, canCastZ);
oZ[zOffset] = OpType::op(x[xOffset], oY[yOffset]);
}
}
}
if (tad != nullptr)
delete tad;
}
BUILD_DOUBLE_TEMPLATE(template class ND4J_EXPORT BroadcastBool, , LIBND4J_TYPES, BOOL_TYPES);
}
} | 49.660338 | 177 | 0.453843 | [
"shape"
] |
29b25ebf283665fd4932b16a8fc6dbeda23eb4b2 | 188,015 | cpp | C++ | Code/Framework/AzCore/Tests/Patching.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Framework/AzCore/Tests/Patching.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Framework/AzCore/Tests/Patching.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "FileIOBaseTestTypes.h"
#include <AzCore/Serialization/DataPatch.h>
#include <AzCore/Serialization/DynamicSerializableField.h>
#include <AzCore/Serialization/Utils.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzCore/std/any.h>
using namespace AZ;
namespace UnitTest
{
/**
* Tests generating and applying patching to serialized structures.
* \note There a lots special... \TODO add notes depending on the final solution
*/
namespace Patching
{
// Object that we will store in container and patch in the complex case
class ContainedObjectPersistentId
{
public:
AZ_TYPE_INFO(ContainedObjectPersistentId, "{D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA}")
ContainedObjectPersistentId()
: m_data(0)
, m_persistentId(0)
{}
u64 GetPersistentId() const { return m_persistentId; }
void SetPersistentId(u64 pesistentId) { m_persistentId = pesistentId; }
int m_data;
u64 m_persistentId; ///< Returns the persistent object ID
static u64 GetPersistentIdWrapper(const void* instance)
{
return reinterpret_cast<const ContainedObjectPersistentId*>(instance)->GetPersistentId();
}
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ContainedObjectPersistentId>()->
PersistentId(&ContainedObjectPersistentId::GetPersistentIdWrapper)->
Field("m_data", &ContainedObjectPersistentId::m_data)->
Field("m_persistentId", &ContainedObjectPersistentId::m_persistentId);
}
};
class ContainedObjectDerivedPersistentId
: public ContainedObjectPersistentId
{
public:
AZ_TYPE_INFO(ContainedObjectDerivedPersistentId, "{1c3ba36a-ceee-4118-89e7-807930bf2bec}");
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ContainedObjectDerivedPersistentId, ContainedObjectPersistentId>();
}
};
class ContainedObjectNoPersistentId
{
public:
AZ_CLASS_ALLOCATOR(ContainedObjectNoPersistentId, SystemAllocator, 0);
AZ_TYPE_INFO(ContainedObjectNoPersistentId, "{A9980498-6E7A-42C0-BF9F-DFA48142DDAB}");
ContainedObjectNoPersistentId()
: m_data(0)
{}
ContainedObjectNoPersistentId(int data)
: m_data(data)
{}
int m_data;
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ContainedObjectNoPersistentId>()->
Field("m_data", &ContainedObjectNoPersistentId::m_data);
}
};
class SimpleClassContainingVectorOfInts
{
public:
AZ_TYPE_INFO(SimpleClassContainingVectorOfInts, "{82FE64FA-23DB-40B5-BD1B-9DC145CB86EA}");
AZ_CLASS_ALLOCATOR(SimpleClassContainingVectorOfInts, AZ::SystemAllocator, 0);
virtual ~SimpleClassContainingVectorOfInts() = default;
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<SimpleClassContainingVectorOfInts>()
->Field("id", &SimpleClassContainingVectorOfInts::m_id);
}
AZStd::vector<int> m_id;
};
class CommonPatch
{
public:
AZ_RTTI(CommonPatch, "{81FE64FA-23DB-40B5-BD1B-9DC145CB86EA}");
AZ_CLASS_ALLOCATOR(CommonPatch, AZ::SystemAllocator, 0);
virtual ~CommonPatch() = default;
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<CommonPatch>()
->SerializeWithNoData();
}
};
class ObjectToPatch
: public CommonPatch
{
public:
AZ_RTTI(ObjectToPatch, "{47E5CF10-3FA1-4064-BE7A-70E3143B4025}", CommonPatch);
AZ_CLASS_ALLOCATOR(ObjectToPatch, AZ::SystemAllocator, 0);
ObjectToPatch() = default;
ObjectToPatch(const ObjectToPatch&) = delete;
int m_intValue = 0;
AZStd::vector<ContainedObjectPersistentId> m_objectArray;
AZStd::vector<ContainedObjectDerivedPersistentId> m_derivedObjectArray;
AZStd::unordered_map<u32, AZStd::unique_ptr<ContainedObjectNoPersistentId>> m_objectMap;
AZStd::vector<ContainedObjectNoPersistentId> m_objectArrayNoPersistentId;
AZ::DynamicSerializableField m_dynamicField;
~ObjectToPatch() override
{
m_dynamicField.DestroyData();
}
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectToPatch, CommonPatch>()->
Field("m_dynamicField", &ObjectToPatch::m_dynamicField)->
Field("m_intValue", &ObjectToPatch::m_intValue)->
Field("m_objectArray", &ObjectToPatch::m_objectArray)->
Field("m_derivedObjectArray", &ObjectToPatch::m_derivedObjectArray)->
Field("m_objectMap", &ObjectToPatch::m_objectMap)->
Field("m_objectArrayNoPersistentId", &ObjectToPatch::m_objectArrayNoPersistentId);
}
};
class DifferentObjectToPatch
: public CommonPatch
{
public:
AZ_RTTI(DifferentObjectToPatch, "{2E107ABB-E77A-4188-AC32-4CA8EB3C5BD1}", CommonPatch);
AZ_CLASS_ALLOCATOR(DifferentObjectToPatch, AZ::SystemAllocator, 0);
float m_data;
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<DifferentObjectToPatch, CommonPatch>()->
Field("m_data", &DifferentObjectToPatch::m_data);
}
};
class ObjectsWithGenerics
{
public:
AZ_CLASS_ALLOCATOR(ObjectsWithGenerics, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectsWithGenerics, "{DE1EE15F-3458-40AE-A206-C6C957E2432B}");
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectsWithGenerics>()->
Field("m_string", &ObjectsWithGenerics::m_string);
}
AZStd::string m_string;
};
class ObjectWithPointer
{
public:
AZ_CLASS_ALLOCATOR(ObjectWithPointer, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectWithPointer, "{D1FD3240-A7C5-4EA3-8E55-CD18193162B8}");
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectWithPointer>()
->Field("m_int", &ObjectWithPointer::m_int)
->Field("m_pointerInt", &ObjectWithPointer::m_pointerInt)
;
}
AZ::s32 m_int;
AZ::s32* m_pointerInt = nullptr;
};
class ObjectWithMultiPointers
{
public:
AZ_CLASS_ALLOCATOR(ObjectWithMultiPointers, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectWithMultiPointers, "{EBA25BFA-CFA0-4397-929C-A765BA72DE28}");
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectWithMultiPointers>()
->Field("m_int", &ObjectWithMultiPointers::m_int)
->Field("m_pointerInt", &ObjectWithMultiPointers::m_pointerInt)
->Field("m_pointerFloat", &ObjectWithMultiPointers::m_pointerFloat)
;
}
AZ::s32 m_int;
AZ::s32* m_pointerInt = nullptr;
float* m_pointerFloat = nullptr;
};
static AZStd::string IntToString(int)
{
AZ_Assert(false, "Version 0 Type Converter for ObjectWithNumericFieldV1 should never be called");
return {};
};
// If the version 1 to 2 version converter ran
// A sentinel value of 32.0 is always returned which can be represented exactly
// in floating point(power of 2)
static double IntToDouble(int)
{
return 32.0;
};
struct ObjectWithNumericFieldV1
{
AZ_CLASS_ALLOCATOR(ObjectWithNumericFieldV1, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectWithNumericFieldV1, "{556A83B0-77BC-41D1-B3BC-C1CD0A4F5845}");
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ObjectWithNumericFieldV1>()
->Version(1)
->Field("IntValue", &ObjectWithNumericFieldV1::m_value)
//! Provide a name converter for Version 0 -> 1
//! This should never be called as there is no Version 0 of this class
//! It is here to validate that it is never called
->NameChange(0, 1, "IntValue", "NameValueThatShouldNeverBeSet")
//! Version 0 -> 1 type converter should never be called
->TypeChange("IntValue", 0, 1, AZStd::function<AZStd::string(const int&)>(&IntToString))
;
}
}
int m_value{};
};
struct ObjectWithNumericFieldV2
{
AZ_CLASS_ALLOCATOR(ObjectWithNumericFieldV2, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectWithNumericFieldV2, "{556A83B0-77BC-41D1-B3BC-C1CD0A4F5845}");
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ObjectWithNumericFieldV2>()
->Version(2)
->Field("DoubleValue", &ObjectWithNumericFieldV2::m_value)
//! Provide a name converter for Version 0 -> 1
//! This should never be called as there is no Version 0 of this class
//! It is here to validate that it is never called
->NameChange(0, 1, "IntValue", "NameValueThatShouldNeverBeSet")
//! Version 0 -> 1 type converter should never be called
->TypeChange("IntValue", 0, 1, AZStd::function<AZStd::string(const int&)>(&IntToString))
->NameChange(1, 2, "IntValue", "DoubleValue")
->TypeChange("IntValue", 1, 2, AZStd::function<double(const int&)>(&IntToDouble))
;
}
}
double m_value{};
};
class InnerObjectFieldConverterV1
{
public:
AZ_CLASS_ALLOCATOR(InnerObjectFieldConverterV1, SystemAllocator, 0);
AZ_RTTI(InnerObjectFieldConverterV1, "{28E61B17-F321-4D4E-9F4C-00846C6631DE}");
virtual ~InnerObjectFieldConverterV1() = default;
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<InnerObjectFieldConverterV1>()
->Version(1)
->Field("InnerBaseStringField", &InnerObjectFieldConverterV1::m_stringField)
->Field("InnerBaseStringVector", &InnerObjectFieldConverterV1::m_stringVector)
;
}
}
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are on a class that is a descendant element of the patched class
AZStd::string m_stringField;
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are on a class that is a descendant element of the patched class
AZStd::vector<AZStd::string> m_stringVector;
};
template<typename BaseClass>
class InnerObjectFieldConverterDerivedV1Template
: public BaseClass
{
public:
AZ_CLASS_ALLOCATOR(InnerObjectFieldConverterDerivedV1Template, SystemAllocator, 0);
AZ_RTTI(InnerObjectFieldConverterDerivedV1Template, "{C68BE9B8-33F8-4969-B521-B44F5BA1C0DE}", BaseClass);
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<InnerObjectFieldConverterDerivedV1Template, BaseClass>()
->Version(1)
->Field("InnerDerivedNumericField", &InnerObjectFieldConverterDerivedV1Template::m_objectWithNumericField)
;
}
}
//! ObjectWithNumericFieldV1 uses the normal SerializeContext::ClassBulder for for Serialization.
//! This is to test Field Converters for a patched element serialized in a pointer to the base class
ObjectWithNumericFieldV1 m_objectWithNumericField;
};
using InnerObjectFieldConverterDerivedV1 = InnerObjectFieldConverterDerivedV1Template<InnerObjectFieldConverterV1>;
class ObjectFieldConverterV1
{
public:
AZ_CLASS_ALLOCATOR(ObjectFieldConverterV1, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectFieldConverterV1, "{5722C4E4-25DE-48C5-BC89-0EE9D38DF433}");
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ObjectFieldConverterV1>()
->Version(1)
->Field("RootStringField", &ObjectFieldConverterV1::m_rootStringField)
->Field("RootStringVector", &ObjectFieldConverterV1::m_rootStringVector)
->Field("RootInnerObjectValue", &ObjectFieldConverterV1::m_rootInnerObject)
->Field("RootInnerObjectPointer", &ObjectFieldConverterV1::m_baseInnerObjectPolymorphic)
;
}
}
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::string m_rootStringField;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::vector<AZStd::string> m_rootStringVector;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
InnerObjectFieldConverterV1 m_rootInnerObject{};
InnerObjectFieldConverterV1* m_baseInnerObjectPolymorphic{};
};
class ObjectBaseClass
{
public:
AZ_CLASS_ALLOCATOR(ObjectBaseClass, SystemAllocator, 0);
AZ_RTTI(ObjectBaseClass, "{9CFEC143-9C78-4566-A541-46F9CA6FE66E}");
virtual ~ObjectBaseClass() = default;
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectBaseClass>();
}
};
class ObjectDerivedClass1 : public ObjectBaseClass
{
public:
AZ_CLASS_ALLOCATOR(ObjectDerivedClass1, SystemAllocator, 0);
AZ_RTTI(ObjectDerivedClass1, "{9D6502E8-999D-46B8-AF37-EAAA0D53385A}", ObjectBaseClass);
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectDerivedClass1>();
}
};
class ObjectDerivedClass2 : public ObjectBaseClass
{
public:
AZ_CLASS_ALLOCATOR(ObjectDerivedClass2, SystemAllocator, 0);
AZ_RTTI(ObjectDerivedClass2, "{91D1812E-17A2-4BC3-A9A1-13196BE50803}", ObjectBaseClass);
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectDerivedClass2>();
}
};
class ObjectDerivedClass3 : public ObjectBaseClass
{
public:
AZ_CLASS_ALLOCATOR(ObjectDerivedClass3, SystemAllocator, 0);
AZ_RTTI(ObjectDerivedClass2, "{E80E926B-5750-4E8D-80E0-D06057692847}", ObjectBaseClass);
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectDerivedClass3>();
}
};
static bool ConvertDerivedClass2ToDerivedClass3(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement)
{
classElement.Convert(context, AZ::AzTypeInfo<ObjectDerivedClass3>::Uuid());
return true;
}
class ObjectWithVectorOfBaseClasses
{
public:
AZ_CLASS_ALLOCATOR(ObjectWithVectorOfBaseClasses, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectWithVectorOfBaseClasses, "{BC9D5346-1BC5-41C4-8CF0-7ACD96F7790F}");
static void Reflect(AZ::SerializeContext& sc)
{
sc.Class<ObjectWithVectorOfBaseClasses>()
->Field("m_vectorOfBaseClasses", &ObjectWithVectorOfBaseClasses::m_vectorOfBaseClasses);
}
virtual ~ObjectWithVectorOfBaseClasses()
{
for (auto element : m_vectorOfBaseClasses)
{
delete element;
}
m_vectorOfBaseClasses.clear();
}
AZStd::vector<ObjectBaseClass*> m_vectorOfBaseClasses;
};
}
class PatchingTest
: public AllocatorsTestFixture
{
protected:
void SetUp() override
{
AllocatorsFixture::SetUp();
m_serializeContext = AZStd::make_unique<SerializeContext>();
using namespace Patching;
CommonPatch::Reflect(*m_serializeContext);
ContainedObjectPersistentId::Reflect(*m_serializeContext);
ContainedObjectDerivedPersistentId::Reflect(*m_serializeContext);
ContainedObjectNoPersistentId::Reflect(*m_serializeContext);
ObjectToPatch::Reflect(*m_serializeContext);
DifferentObjectToPatch::Reflect(*m_serializeContext);
ObjectsWithGenerics::Reflect(*m_serializeContext);
ObjectWithPointer::Reflect(*m_serializeContext);
ObjectWithMultiPointers::Reflect(*m_serializeContext);
AZ::DataPatch::Reflect(m_serializeContext.get());
const SerializeContext::ClassData* addressTypeSerializerClassData = m_serializeContext.get()->FindClassData(azrtti_typeid<DataPatch::AddressType>());
AZ_Assert(addressTypeSerializerClassData, "AddressType class not reflected, required to run DataPatch Unit Tests");
m_addressTypeSerializer = static_cast<DataPatchInternal::AddressTypeSerializer*>(addressTypeSerializerClassData->m_serializer.get());
AZ_Assert(m_addressTypeSerializer, "AddressTypeSerializer not provided in class AddressType's reflection, required to run DataPatch Unit Tests");
}
void TearDown() override
{
m_serializeContext.reset();
m_addressTypeSerializer = nullptr;
AllocatorsFixture::TearDown();
}
void LoadPatchFromXML(const AZStd::string_view& xmlSrc, DataPatch& patchDest)
{
AZ::IO::MemoryStream xmlStream(xmlSrc.data(), xmlSrc.size());
Utils::LoadObjectFromStreamInPlace(xmlStream, patchDest, m_serializeContext.get());
}
void LoadPatchFromByteStream(const AZStd::vector<AZ::u8>& byteStreamSrc, DataPatch& patchDest)
{
AZ::IO::MemoryStream streamRead(byteStreamSrc.data(), byteStreamSrc.size());
AZ::Utils::LoadObjectFromStreamInPlace(streamRead, patchDest, m_serializeContext.get());
}
void WritePatchToByteStream(const DataPatch& patchSrc, AZStd::vector<AZ::u8>& byteStreamDest)
{
byteStreamDest.clear();
AZ::IO::ByteContainerStream<AZStd::vector<AZ::u8>> streamWrite(&byteStreamDest);
AZ::Utils::SaveObjectToStream(streamWrite, AZ::DataStream::ST_XML, &patchSrc, m_serializeContext.get());
}
// Template XML that can be formatted for multiple tests
// ObjectToPatch m_intValue override
const char* m_XMLDataPatchV1AddressTypeIntOverrideTemplate = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{BFF7A3F5-9014-4000-92C7-9B2BC7913DA9}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CEA836FC-77E0-5E46-BD0F-2E5A39D845E9}">
<Class name="AZStd::pair" field="element" type="{FED51EB4-F646-51FF-9646-9852CF90F353}">
<Class name="AddressType" field="value1" value="%s" version="1" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="any" field="value2" type="{03924488-C7F4-4D6D-948B-ABC2D1AE2FD3}">
<Class name="int" field="m_data" value="%i" type="{72039442-EB38-4D42-A1AD-CB68F7E0EEF6}"/>
</Class>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Valid address for above XML for easy formatting of tests expected to pass
const char* m_XMLDataPatchV1AddressTypeIntOverrideValidAddress = R"(int({72039442-EB38-4D42-A1AD-CB68F7E0EEF6})::m_intValue%s0%s)";
// ObjectToPatch m_objectArray overrides. Container is size 5. Can format the first address and each element's data and persistent ids
const char* m_XMLDataPatchV1AddressTypeIntVectorOverrideTemplate = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{BFF7A3F5-9014-4000-92C7-9B2BC7913DA9}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CEA836FC-77E0-5E46-BD0F-2E5A39D845E9}">
<Class name="AZStd::pair" field="element" type="{FED51EB4-F646-51FF-9646-9852CF90F353}">
<Class name="AddressType" field="value1" value="%s" version="1" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="any" field="value2" type="{03924488-C7F4-4D6D-948B-ABC2D1AE2FD3}">
<Class name="ContainedObjectPersistentId" field="m_data" type="{D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA}">
<Class name="int" field="m_data" value="%i" type="{72039442-EB38-4D42-A1AD-CB68F7E0EEF6}"/>
<Class name="AZ::u64" field="m_persistentId" value="%i" type="{D6597933-47CD-4FC8-B911-63F3E2B0993A}"/>
</Class>
</Class>
</Class>
<Class name="AZStd::pair" field="element" type="{FED51EB4-F646-51FF-9646-9852CF90F353}">
<Class name="AddressType" field="value1" value="AZStd::vector({861A12B0-BD91-528E-9CEC-505246EE98DE})::m_objectArray%s0%sContainedObjectPersistentId({D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA})#%i%s0%s" version="1" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="any" field="value2" type="{03924488-C7F4-4D6D-948B-ABC2D1AE2FD3}">
<Class name="ContainedObjectPersistentId" field="m_data" type="{D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA}">
<Class name="int" field="m_data" value="%i" type="{72039442-EB38-4D42-A1AD-CB68F7E0EEF6}"/>
<Class name="AZ::u64" field="m_persistentId" value="%i" type="{D6597933-47CD-4FC8-B911-63F3E2B0993A}"/>
</Class>
</Class>
</Class>
<Class name="AZStd::pair" field="element" type="{FED51EB4-F646-51FF-9646-9852CF90F353}">
<Class name="AddressType" field="value1" value="AZStd::vector({861A12B0-BD91-528E-9CEC-505246EE98DE})::m_objectArray%s0%sContainedObjectPersistentId({D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA})#%i%s0%s" version="1" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="any" field="value2" type="{03924488-C7F4-4D6D-948B-ABC2D1AE2FD3}">
<Class name="ContainedObjectPersistentId" field="m_data" type="{D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA}">
<Class name="int" field="m_data" value="%i" type="{72039442-EB38-4D42-A1AD-CB68F7E0EEF6}"/>
<Class name="AZ::u64" field="m_persistentId" value="%i" type="{D6597933-47CD-4FC8-B911-63F3E2B0993A}"/>
</Class>
</Class>
</Class>
<Class name="AZStd::pair" field="element" type="{FED51EB4-F646-51FF-9646-9852CF90F353}">
<Class name="AddressType" field="value1" value="AZStd::vector({861A12B0-BD91-528E-9CEC-505246EE98DE})::m_objectArray%s0%sContainedObjectPersistentId({D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA})#%i%s0%s" version="1" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="any" field="value2" type="{03924488-C7F4-4D6D-948B-ABC2D1AE2FD3}">
<Class name="ContainedObjectPersistentId" field="m_data" type="{D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA}">
<Class name="int" field="m_data" value="%i" type="{72039442-EB38-4D42-A1AD-CB68F7E0EEF6}"/>
<Class name="AZ::u64" field="m_persistentId" value="%i" type="{D6597933-47CD-4FC8-B911-63F3E2B0993A}"/>
</Class>
</Class>
</Class>
<Class name="AZStd::pair" field="element" type="{FED51EB4-F646-51FF-9646-9852CF90F353}">
<Class name="AddressType" field="value1" value="AZStd::vector({861A12B0-BD91-528E-9CEC-505246EE98DE})::m_objectArray%s0%sContainedObjectPersistentId({D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA})#%i%s0%s" version="1" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="any" field="value2" type="{03924488-C7F4-4D6D-948B-ABC2D1AE2FD3}">
<Class name="ContainedObjectPersistentId" field="m_data" type="{D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA}">
<Class name="int" field="m_data" value="%i" type="{72039442-EB38-4D42-A1AD-CB68F7E0EEF6}"/>
<Class name="AZ::u64" field="m_persistentId" value="%i" type="{D6597933-47CD-4FC8-B911-63F3E2B0993A}"/>
</Class>
</Class>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Valid address for above XML for easy formatting of tests expected to pass
const char* m_XMLDataPatchV1AddressTypeIntVectorOverrideValidAddress = R"(AZStd::vector({861A12B0-BD91-528E-9CEC-505246EE98DE})::m_objectArray%s0%sContainedObjectPersistentId({D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA})#%i%s0%s)";
/*
Builds a valid address for m_XMLDataPatchV1AddressTypeIntOverrideTemplate
while allowing formatting of the path and version delimiters
*/
AZStd::string GetValidAddressForXMLDataPatchV1AddressTypeIntXML()
{
return AZStd::string::format(m_XMLDataPatchV1AddressTypeIntOverrideValidAddress,
V1AddressTypeElementVersionDelimiter,
V1AddressTypeElementPathDelimiter);
}
/*
Sets the data value for the int type stored in m_XMLDataPatchV1AddressTypeIntOverrideTemplate's xml stream
Can also optionally set the address, otherwise defaults to a valid address if testAddress is nullptr
*/
AZStd::string BuildXMLDataPatchV1AddressTypeIntXML(const char* testAddress, int intValue)
{
AZStd::string editableAddress;
if (testAddress)
{
editableAddress = testAddress;
}
else
{
editableAddress = GetValidAddressForXMLDataPatchV1AddressTypeIntXML();
}
return AZStd::string::format(m_XMLDataPatchV1AddressTypeIntOverrideTemplate, editableAddress.c_str(), intValue);
}
/*
Sets the data values and persistentId values for the ContainedObjectPersistentId type stored in m_XMLDataPatchV1AddressTypeIntVectorOverrideTemplate's xml stream
Can also optionally set the address of the first element otherwise defaults to a valid address if testAddress is nullptr
The stream contains 5 elements within the vector
*/
AZStd::string BuildXMLDataPatchV1AddressTypeIntVectorXML(const char* testAddress, int dataModifier, int persistentIdModifier)
{
AZStd::string editableAddress;
// Allow customization of our delimiters
const char* versionDelimiter = V1AddressTypeElementVersionDelimiter;
const char* pathDelimiter = V1AddressTypeElementPathDelimiter;
// If a testAddress was supplied then use it.
// Otherwise format with a valid path
if (testAddress)
{
editableAddress = testAddress;
}
else
{
editableAddress = AZStd::string::format(m_XMLDataPatchV1AddressTypeIntVectorOverrideValidAddress,
versionDelimiter,
pathDelimiter,
4 + persistentIdModifier,
versionDelimiter,
pathDelimiter);
}
// Format our xml.
// It is size 5 so we format the data and persistent IDs to match this size.
return AZStd::string::format(m_XMLDataPatchV1AddressTypeIntVectorOverrideTemplate,
editableAddress.c_str(), 4 + dataModifier, 4 + persistentIdModifier,
versionDelimiter, pathDelimiter, 3 + persistentIdModifier, versionDelimiter, pathDelimiter, 3 + dataModifier, 3 + persistentIdModifier,
versionDelimiter, pathDelimiter, 2 + persistentIdModifier, versionDelimiter, pathDelimiter, 2 + dataModifier, 2 + persistentIdModifier,
versionDelimiter, pathDelimiter, 1 + persistentIdModifier, versionDelimiter, pathDelimiter, 1 + dataModifier, 1 + persistentIdModifier,
versionDelimiter, pathDelimiter, 0 + persistentIdModifier, versionDelimiter, pathDelimiter, 0 + dataModifier, 0 + persistentIdModifier);
}
// Store each AddressTypeElement version's delimiters seperately from the class so our tests don't auto update to a new version if these delimiters change in V2+
static constexpr const char* V1AddressTypeElementPathDelimiter = "/";
static constexpr const char* V1AddressTypeElementVersionDelimiter = AZ::DataPatchInternal::AddressTypeElement::VersionDelimiter; // utf-8 for <middledot>
AZStd::unique_ptr<SerializeContext> m_serializeContext;
DataPatchInternal::AddressTypeSerializer* m_addressTypeSerializer;
};
namespace Patching
{
TEST_F(PatchingTest, UberTest)
{
ObjectToPatch sourceObj;
sourceObj.m_intValue = 101;
sourceObj.m_objectArray.push_back();
sourceObj.m_objectArray.push_back();
sourceObj.m_objectArray.push_back();
sourceObj.m_dynamicField.Set(aznew ContainedObjectNoPersistentId(40));
{
// derived
sourceObj.m_derivedObjectArray.push_back();
sourceObj.m_derivedObjectArray.push_back();
sourceObj.m_derivedObjectArray.push_back();
}
// test generic containers with persistent ID
sourceObj.m_objectArray[0].m_persistentId = 1;
sourceObj.m_objectArray[0].m_data = 201;
sourceObj.m_objectArray[1].m_persistentId = 2;
sourceObj.m_objectArray[1].m_data = 202;
sourceObj.m_objectArray[2].m_persistentId = 3;
sourceObj.m_objectArray[2].m_data = 203;
{
// derived
sourceObj.m_derivedObjectArray[0].m_persistentId = 1;
sourceObj.m_derivedObjectArray[0].m_data = 2010;
sourceObj.m_derivedObjectArray[1].m_persistentId = 2;
sourceObj.m_derivedObjectArray[1].m_data = 2020;
sourceObj.m_derivedObjectArray[2].m_persistentId = 3;
sourceObj.m_derivedObjectArray[2].m_data = 2030;
}
ObjectToPatch targetObj;
targetObj.m_intValue = 121;
targetObj.m_objectArray.push_back();
targetObj.m_objectArray.push_back();
targetObj.m_objectArray.push_back();
targetObj.m_objectArray[0].m_persistentId = 1;
targetObj.m_objectArray[0].m_data = 301;
targetObj.m_dynamicField.Set(aznew ContainedObjectNoPersistentId(50));
{
// derived
targetObj.m_derivedObjectArray.push_back();
targetObj.m_derivedObjectArray.push_back();
targetObj.m_derivedObjectArray.push_back();
targetObj.m_derivedObjectArray[0].m_persistentId = 1;
targetObj.m_derivedObjectArray[0].m_data = 3010;
}
// remove element 2
targetObj.m_objectArray[1].m_persistentId = 3;
targetObj.m_objectArray[1].m_data = 303;
{
// derived
targetObj.m_derivedObjectArray[1].m_persistentId = 3;
targetObj.m_derivedObjectArray[1].m_data = 3030;
}
// add new element
targetObj.m_objectArray[2].m_persistentId = 4;
targetObj.m_objectArray[2].m_data = 304;
{
// derived
targetObj.m_derivedObjectArray[2].m_persistentId = 4;
targetObj.m_derivedObjectArray[2].m_data = 3040;
}
// insert lots of objects without persistent id
targetObj.m_objectArrayNoPersistentId.resize(999);
for (size_t i = 0; i < targetObj.m_objectArrayNoPersistentId.size(); ++i)
{
targetObj.m_objectArrayNoPersistentId[i].m_data = static_cast<int>(i);
}
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Compare the generated and original target object
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_intValue, targetObj.m_intValue);
EXPECT_EQ(generatedObj->m_objectArray.size(), targetObj.m_objectArray.size());
EXPECT_EQ(generatedObj->m_objectArray[0].m_data, targetObj.m_objectArray[0].m_data);
EXPECT_EQ(generatedObj->m_objectArray[0].m_persistentId, targetObj.m_objectArray[0].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[1].m_data, targetObj.m_objectArray[1].m_data);
EXPECT_EQ(generatedObj->m_objectArray[1].m_persistentId, targetObj.m_objectArray[1].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[2].m_data, targetObj.m_objectArray[2].m_data);
EXPECT_EQ(generatedObj->m_objectArray[2].m_persistentId, targetObj.m_objectArray[2].m_persistentId);
EXPECT_EQ(50, generatedObj->m_dynamicField.Get<ContainedObjectNoPersistentId>()->m_data);
{
// derived
EXPECT_EQ(generatedObj->m_derivedObjectArray.size(), targetObj.m_derivedObjectArray.size());
EXPECT_EQ(generatedObj->m_derivedObjectArray[0].m_data, targetObj.m_derivedObjectArray[0].m_data);
EXPECT_EQ(generatedObj->m_derivedObjectArray[0].m_persistentId, targetObj.m_derivedObjectArray[0].m_persistentId);
EXPECT_EQ(generatedObj->m_derivedObjectArray[1].m_data, targetObj.m_derivedObjectArray[1].m_data);
EXPECT_EQ(generatedObj->m_derivedObjectArray[1].m_persistentId, targetObj.m_derivedObjectArray[1].m_persistentId);
EXPECT_EQ(generatedObj->m_derivedObjectArray[2].m_data, targetObj.m_derivedObjectArray[2].m_data);
EXPECT_EQ(generatedObj->m_derivedObjectArray[2].m_persistentId, targetObj.m_derivedObjectArray[2].m_persistentId);
}
// test that the relative order of elements without persistent ID is preserved
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId.size(), targetObj.m_objectArrayNoPersistentId.size());
for (size_t i = 0; i < targetObj.m_objectArrayNoPersistentId.size(); ++i)
{
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId[i].m_data, targetObj.m_objectArrayNoPersistentId[i].m_data);
}
// \note do we need to add support for base class patching and recover for root elements with proper casting
generatedObj->m_dynamicField.DestroyData(m_serializeContext.get());
targetObj.m_dynamicField.DestroyData(m_serializeContext.get());
sourceObj.m_dynamicField.DestroyData(m_serializeContext.get());
//delete generatedObj;
}
TEST_F(PatchingTest, PatchArray_RemoveAllObjects_DataPatchAppliesCorrectly)
{
// Init Source with arbitrary Persistent IDs and data
ObjectToPatch sourceObj;
sourceObj.m_objectArray.resize(999);
for (size_t i = 0; i < sourceObj.m_objectArray.size(); ++i)
{
sourceObj.m_objectArray[i].m_persistentId = static_cast<int>(i + 10);
sourceObj.m_objectArray[i].m_data = static_cast<int>(i + 200);
}
// Init empty Target
ObjectToPatch targetObj;
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), targetObj.m_objectArray.size());
EXPECT_TRUE(targetObj.m_objectArray.empty());
EXPECT_TRUE(generatedObj->m_objectArray.empty());
}
TEST_F(PatchingTest, PatchArray_AddObjects_DataPatchAppliesCorrectly)
{
// Init empty Source
ObjectToPatch sourceObj;
// Init Target with arbitrary Persistent IDs and data
ObjectToPatch targetObj;
targetObj.m_objectArray.resize(999);
for (size_t i = 0; i < targetObj.m_objectArray.size(); ++i)
{
targetObj.m_objectArray[i].m_persistentId = static_cast<int>(i + 10);
targetObj.m_objectArray[i].m_data = static_cast<int>(i + 200);
}
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), targetObj.m_objectArray.size());
for (size_t i = 0; i < generatedObj->m_objectArray.size(); ++i)
{
EXPECT_EQ(generatedObj->m_objectArray[i].m_persistentId, targetObj.m_objectArray[i].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[i].m_data, targetObj.m_objectArray[i].m_data);
}
}
TEST_F(PatchingTest, PatchArray_EditAllObjects_DataPatchAppliesCorrectly)
{
// Init Source and Target with arbitrary Persistent IDs (the same) and data (different)
ObjectToPatch sourceObj;
sourceObj.m_objectArray.resize(999);
ObjectToPatch targetObj;
targetObj.m_objectArray.resize(999);
for (size_t i = 0; i < sourceObj.m_objectArray.size(); ++i)
{
sourceObj.m_objectArray[i].m_persistentId = static_cast<int>(i + 10);
sourceObj.m_objectArray[i].m_data = static_cast<int>(i + 200);
// Keep the Persistent IDs the same but change the data
targetObj.m_objectArray[i].m_persistentId = sourceObj.m_objectArray[i].m_persistentId;
targetObj.m_objectArray[i].m_data = sourceObj.m_objectArray[i].m_data + 100;
}
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), targetObj.m_objectArray.size());
for (size_t i = 0; i < generatedObj->m_objectArray.size(); ++i)
{
EXPECT_EQ(generatedObj->m_objectArray[i].m_persistentId, targetObj.m_objectArray[i].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[i].m_data, targetObj.m_objectArray[i].m_data);
}
}
TEST_F(PatchingTest, PatchArray_AddRemoveEdit_DataPatchAppliesCorrectly)
{
// Init Source
ObjectToPatch sourceObj;
sourceObj.m_objectArray.resize(3);
sourceObj.m_objectArray[0].m_persistentId = 1;
sourceObj.m_objectArray[0].m_data = 201;
sourceObj.m_objectArray[1].m_persistentId = 2;
sourceObj.m_objectArray[1].m_data = 202;
sourceObj.m_objectArray[2].m_persistentId = 3;
sourceObj.m_objectArray[2].m_data = 203;
// Init Target
ObjectToPatch targetObj;
targetObj.m_objectArray.resize(4);
// Edit ID 1
targetObj.m_objectArray[0].m_persistentId = 1;
targetObj.m_objectArray[0].m_data = 301;
// Remove ID 2, do not edit ID 3
targetObj.m_objectArray[1].m_persistentId = 3;
targetObj.m_objectArray[1].m_data = 203;
// Add ID 4 and 5
targetObj.m_objectArray[2].m_persistentId = 4;
targetObj.m_objectArray[2].m_data = 304;
targetObj.m_objectArray[3].m_persistentId = 5;
targetObj.m_objectArray[3].m_data = 305;
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), targetObj.m_objectArray.size());
EXPECT_EQ(generatedObj->m_objectArray[0].m_persistentId, targetObj.m_objectArray[0].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[0].m_data, targetObj.m_objectArray[0].m_data);
EXPECT_EQ(generatedObj->m_objectArray[1].m_persistentId, targetObj.m_objectArray[1].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[1].m_data, targetObj.m_objectArray[1].m_data);
EXPECT_EQ(generatedObj->m_objectArray[2].m_persistentId, targetObj.m_objectArray[2].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[2].m_data, targetObj.m_objectArray[2].m_data);
EXPECT_EQ(generatedObj->m_objectArray[3].m_persistentId, targetObj.m_objectArray[3].m_persistentId);
EXPECT_EQ(generatedObj->m_objectArray[3].m_data, targetObj.m_objectArray[3].m_data);
}
TEST_F(PatchingTest, PatchArray_ObjectsHaveNoPersistentId_RemoveAllObjects_DataPatchAppliesCorrectly)
{
// Init Source
ObjectToPatch sourceObj;
sourceObj.m_objectArrayNoPersistentId.resize(999);
for (size_t i = 0; i < sourceObj.m_objectArrayNoPersistentId.size(); ++i)
{
sourceObj.m_objectArrayNoPersistentId[i].m_data = static_cast<int>(i);
}
// Init empty Target
ObjectToPatch targetObj;
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId.size(), targetObj.m_objectArrayNoPersistentId.size());
EXPECT_TRUE(targetObj.m_objectArrayNoPersistentId.empty());
EXPECT_TRUE(generatedObj->m_objectArrayNoPersistentId.empty());
}
TEST_F(PatchingTest, PatchArray_ObjectsHaveNoPersistentId_AddObjects_DataPatchAppliesCorrectly)
{
// Init empty Source
ObjectToPatch sourceObj;
// Init Target
ObjectToPatch targetObj;
targetObj.m_objectArrayNoPersistentId.resize(999);
for (size_t i = 0; i < targetObj.m_objectArrayNoPersistentId.size(); ++i)
{
targetObj.m_objectArrayNoPersistentId[i].m_data = static_cast<int>(i);
}
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_THAT(generatedObj->m_objectArrayNoPersistentId, ::testing::Pointwise(::testing::Truly([](auto arg){ return testing::get<0>(arg).m_data == testing::get<1>(arg).m_data; }), targetObj.m_objectArrayNoPersistentId));
}
TEST_F(PatchingTest, SimpleClassContainingVectorOfInts)
{
SimpleClassContainingVectorOfInts::Reflect(*m_serializeContext.get());
// Init empty Source
SimpleClassContainingVectorOfInts sourceObj;
// Init Target
SimpleClassContainingVectorOfInts targetObj;
targetObj.m_id.resize(20);
for (size_t i = 0; i < targetObj.m_id.size(); ++i)
{
targetObj.m_id[i] = 0;
}
// Create and Apply Patch
DataPatch patch;
EXPECT_TRUE(patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get()));
AZStd::unique_ptr<SimpleClassContainingVectorOfInts> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_THAT(generatedObj->m_id, ::testing::Pointwise(::testing::Truly([](auto arg){ return testing::get<0>(arg) == testing::get<1>(arg); }), targetObj.m_id));
}
TEST_F(PatchingTest, PatchArray_ObjectsHaveNoPersistentId_EditAllObjects_DataPatchAppliesCorrectly)
{
// Init Source
ObjectToPatch sourceObj;
sourceObj.m_objectArrayNoPersistentId.resize(999);
for (size_t i = 0; i < sourceObj.m_objectArrayNoPersistentId.size(); ++i)
{
sourceObj.m_objectArrayNoPersistentId[i].m_data = static_cast<int>(i);
}
// Init Target
ObjectToPatch targetObj;
targetObj.m_objectArrayNoPersistentId.resize(999);
for (size_t i = 0; i < targetObj.m_objectArrayNoPersistentId.size(); ++i)
{
targetObj.m_objectArrayNoPersistentId[i].m_data = static_cast<int>(i + 1);
}
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId.size(), targetObj.m_objectArrayNoPersistentId.size());
for (size_t i = 0; i < targetObj.m_objectArrayNoPersistentId.size(); ++i)
{
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId[i].m_data, targetObj.m_objectArrayNoPersistentId[i].m_data);
}
}
TEST_F(PatchingTest, PatchArray_ObjectsHaveNoPersistentId_RemoveEdit_DataPatchAppliesCorrectly)
{
// Init Source
ObjectToPatch sourceObj;
sourceObj.m_objectArrayNoPersistentId.resize(4);
sourceObj.m_objectArrayNoPersistentId[0].m_data = static_cast<int>(1000);
sourceObj.m_objectArrayNoPersistentId[1].m_data = static_cast<int>(1001);
sourceObj.m_objectArrayNoPersistentId[2].m_data = static_cast<int>(1002);
sourceObj.m_objectArrayNoPersistentId[3].m_data = static_cast<int>(1003);
// Init Target
ObjectToPatch targetObj;
targetObj.m_objectArrayNoPersistentId.resize(2);
targetObj.m_objectArrayNoPersistentId[0].m_data = static_cast<int>(2000);
targetObj.m_objectArrayNoPersistentId[1].m_data = static_cast<int>(2001);
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId.size(), 2);
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId.size(), targetObj.m_objectArrayNoPersistentId.size());
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId[0].m_data, targetObj.m_objectArrayNoPersistentId[0].m_data);
EXPECT_EQ(generatedObj->m_objectArrayNoPersistentId[1].m_data, targetObj.m_objectArrayNoPersistentId[1].m_data);
}
TEST_F(PatchingTest, PatchUnorderedMap_ObjectsHaveNoPersistentId_RemoveAllObjects_DataPatchAppliesCorrectly)
{
// test generic containers without persistent ID (by index)
// Init Source
ObjectToPatch sourceObj;
sourceObj.m_objectMap.emplace(1, aznew ContainedObjectNoPersistentId(401));
sourceObj.m_objectMap.emplace(2, aznew ContainedObjectNoPersistentId(402));
sourceObj.m_objectMap.emplace(3, aznew ContainedObjectNoPersistentId(403));
sourceObj.m_objectMap.emplace(4, aznew ContainedObjectNoPersistentId(404));
// Init empty Target
ObjectToPatch targetObj;
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectMap.size(), targetObj.m_objectMap.size());
EXPECT_TRUE(targetObj.m_objectMap.empty());
EXPECT_TRUE(generatedObj->m_objectMap.empty());
}
TEST_F(PatchingTest, PatchUnorderedMap_ObjectsHaveNoPersistentId_AddObjects_DataPatchAppliesCorrectly)
{
// test generic containers without persistent ID (by index)
// Init empty Source
ObjectToPatch sourceObj;
// Init Target
ObjectToPatch targetObj;
targetObj.m_objectMap.emplace(1, aznew ContainedObjectNoPersistentId(401));
targetObj.m_objectMap.emplace(2, aznew ContainedObjectNoPersistentId(402));
targetObj.m_objectMap.emplace(3, aznew ContainedObjectNoPersistentId(403));
targetObj.m_objectMap.emplace(4, aznew ContainedObjectNoPersistentId(404));
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectMap.size(), targetObj.m_objectMap.size());
EXPECT_EQ(generatedObj->m_objectMap[1]->m_data, targetObj.m_objectMap[1]->m_data);
EXPECT_EQ(generatedObj->m_objectMap[2]->m_data, targetObj.m_objectMap[2]->m_data);
EXPECT_EQ(generatedObj->m_objectMap[3]->m_data, targetObj.m_objectMap[3]->m_data);
EXPECT_EQ(generatedObj->m_objectMap[4]->m_data, targetObj.m_objectMap[4]->m_data);
}
TEST_F(PatchingTest, PatchUnorderedMap_ObjectsHaveNoPersistentId_EditAllObjects_DataPatchAppliesCorrectly)
{
// test generic containers without persistent ID (by index)
// Init Source
ObjectToPatch sourceObj;
sourceObj.m_objectMap.emplace(1, aznew ContainedObjectNoPersistentId(401));
sourceObj.m_objectMap.emplace(2, aznew ContainedObjectNoPersistentId(402));
sourceObj.m_objectMap.emplace(3, aznew ContainedObjectNoPersistentId(403));
sourceObj.m_objectMap.emplace(4, aznew ContainedObjectNoPersistentId(404));
// Init Target
ObjectToPatch targetObj;
targetObj.m_objectMap.emplace(1, aznew ContainedObjectNoPersistentId(501));
targetObj.m_objectMap.emplace(2, aznew ContainedObjectNoPersistentId(502));
targetObj.m_objectMap.emplace(3, aznew ContainedObjectNoPersistentId(503));
targetObj.m_objectMap.emplace(4, aznew ContainedObjectNoPersistentId(504));
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectMap.size(), targetObj.m_objectMap.size());
EXPECT_EQ(generatedObj->m_objectMap[1]->m_data, targetObj.m_objectMap[1]->m_data);
EXPECT_EQ(generatedObj->m_objectMap[2]->m_data, targetObj.m_objectMap[2]->m_data);
EXPECT_EQ(generatedObj->m_objectMap[3]->m_data, targetObj.m_objectMap[3]->m_data);
EXPECT_EQ(generatedObj->m_objectMap[4]->m_data, targetObj.m_objectMap[4]->m_data);
}
TEST_F(PatchingTest, PatchUnorderedMap_ObjectsHaveNoPersistentId_AddRemoveEdit_DataPatchAppliesCorrectly)
{
// test generic containers without persistent ID (by index)
// Init Source
ObjectToPatch sourceObj;
sourceObj.m_objectMap.emplace(1, aznew ContainedObjectNoPersistentId(401));
sourceObj.m_objectMap.emplace(2, aznew ContainedObjectNoPersistentId(402));
sourceObj.m_objectMap.emplace(3, aznew ContainedObjectNoPersistentId(403));
sourceObj.m_objectMap.emplace(4, aznew ContainedObjectNoPersistentId(404));
// Init Target
ObjectToPatch targetObj;
// This will mark the object at index 1 as an edit, objects 2-4 as removed, and 5 as an addition
targetObj.m_objectMap.emplace(1, aznew ContainedObjectNoPersistentId(501));
targetObj.m_objectMap.emplace(5, aznew ContainedObjectNoPersistentId(405));
// Create and Apply Patch
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Test Phase
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectMap.size(), 2);
EXPECT_EQ(generatedObj->m_objectMap.size(), targetObj.m_objectMap.size());
EXPECT_EQ(generatedObj->m_objectMap[1]->m_data, targetObj.m_objectMap[1]->m_data);
EXPECT_EQ(generatedObj->m_objectMap[5]->m_data, targetObj.m_objectMap[5]->m_data);
}
TEST_F(PatchingTest, ReplaceRootElement_DifferentObjects_DataPatchAppliesCorrectly)
{
ObjectToPatch obj1;
DifferentObjectToPatch obj2;
obj1.m_intValue = 99;
obj2.m_data = 3.33f;
DataPatch patch1;
patch1.Create(static_cast<CommonPatch*>(&obj1), static_cast<CommonPatch*>(&obj2), DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get()); // cast to base classes
DifferentObjectToPatch* obj2Generated = patch1.Apply<DifferentObjectToPatch>(&obj1, m_serializeContext.get());
EXPECT_EQ(obj2.m_data, obj2Generated->m_data);
delete obj2Generated;
}
TEST_F(PatchingTest, CompareWithGenerics_DifferentObjects_DataPatchAppliesCorrectly)
{
ObjectsWithGenerics sourceGeneric;
sourceGeneric.m_string = "Hello";
ObjectsWithGenerics targetGeneric;
targetGeneric.m_string = "Ola";
DataPatch genericPatch;
genericPatch.Create(&sourceGeneric, &targetGeneric, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
ObjectsWithGenerics* targerGenericGenerated = genericPatch.Apply(&sourceGeneric, m_serializeContext.get());
EXPECT_EQ(targetGeneric.m_string, targerGenericGenerated->m_string);
delete targerGenericGenerated;
}
TEST_F(PatchingTest, CompareIdentical_DataPatchIsEmpty)
{
ObjectToPatch sourceObj;
ObjectToPatch targetObj;
// Patch without overrides should be empty
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
EXPECT_FALSE(patch.IsData());
}
TEST_F(PatchingTest, CompareIdenticalWithForceOverride_DataPatchHasData)
{
ObjectToPatch sourceObj;
ObjectToPatch targetObj;
DataPatch::AddressType forceOverrideAddress;
forceOverrideAddress.emplace_back(AZ_CRC("m_intValue"));
DataPatch::FlagsMap sourceFlagsMap;
DataPatch::FlagsMap targetFlagsMap;
targetFlagsMap.emplace(forceOverrideAddress, DataPatch::Flag::ForceOverrideSet);
DataPatch patch;
patch.Create(&sourceObj, &targetObj, sourceFlagsMap, targetFlagsMap, m_serializeContext.get());
EXPECT_TRUE(patch.IsData());
}
TEST_F(PatchingTest, ChangeSourceAfterForceOverride_TargetDataUnchanged)
{
ObjectToPatch sourceObj;
ObjectToPatch targetObj;
DataPatch::AddressType forceOverrideAddress;
forceOverrideAddress.emplace_back(AZ_CRC("m_intValue"));
DataPatch::FlagsMap sourceFlagsMap;
DataPatch::FlagsMap targetFlagsMap;
targetFlagsMap.emplace(forceOverrideAddress, DataPatch::Flag::ForceOverrideSet);
DataPatch patch;
patch.Create(&sourceObj, &targetObj, sourceFlagsMap, targetFlagsMap, m_serializeContext.get());
// change source after patch is created
sourceObj.m_intValue = 5;
AZStd::unique_ptr<ObjectToPatch> targetObj2(patch.Apply(&sourceObj, m_serializeContext.get()));
EXPECT_EQ(targetObj.m_intValue, targetObj2->m_intValue);
}
TEST_F(PatchingTest, ForceOverrideAndPreventOverrideBothSet_DataPatchIsEmpty)
{
ObjectToPatch sourceObj;
ObjectToPatch targetObj;
targetObj.m_intValue = 43;
DataPatch::AddressType forceOverrideAddress;
forceOverrideAddress.emplace_back(AZ_CRC("m_intValue"));
DataPatch::FlagsMap sourceFlagsMap;
sourceFlagsMap.emplace(forceOverrideAddress, DataPatch::Flag::PreventOverrideSet);
DataPatch::FlagsMap targetFlagsMap;
targetFlagsMap.emplace(forceOverrideAddress, DataPatch::Flag::ForceOverrideSet);
DataPatch patch;
patch.Create(&sourceObj, &targetObj, sourceFlagsMap, targetFlagsMap, m_serializeContext.get());
EXPECT_FALSE(patch.IsData());
}
TEST_F(PatchingTest, PreventOverrideOnSource_BlocksValueFromPatch)
{
// targetObj is different from sourceObj
ObjectToPatch sourceObj;
ObjectToPatch targetObj;
targetObj.m_intValue = 5;
// create patch from sourceObj -> targetObj
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
// create flags that prevent m_intValue from being patched
DataPatch::AddressType forceOverrideAddress;
forceOverrideAddress.emplace_back(AZ_CRC("m_intValue"));
DataPatch::FlagsMap sourceFlagsMap;
sourceFlagsMap.emplace(forceOverrideAddress, DataPatch::Flag::PreventOverrideSet);
DataPatch::FlagsMap targetFlagsMap;
// m_intValue should be the same as it was in sourceObj
AZStd::unique_ptr<ObjectToPatch> targetObj2(patch.Apply(&sourceObj, m_serializeContext.get(), ObjectStream::FilterDescriptor(), sourceFlagsMap, targetFlagsMap));
EXPECT_EQ(sourceObj.m_intValue, targetObj2->m_intValue);
}
TEST_F(PatchingTest, PreventOverrideOnTarget_DoesntAffectPatching)
{
// targetObj is different from sourceObj
ObjectToPatch sourceObj;
ObjectToPatch targetObj;
targetObj.m_intValue = 5;
// create patch from sourceObj -> targetObj
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
// create flags that prevent m_intValue from being patched, but put them on the target instead of source
DataPatch::AddressType forceOverrideAddress;
forceOverrideAddress.emplace_back(AZ_CRC("m_intValue"));
DataPatch::FlagsMap sourceFlagsMap;
DataPatch::FlagsMap targetFlagsMap;
targetFlagsMap.emplace(forceOverrideAddress, DataPatch::Flag::PreventOverrideSet);
// m_intValue should have been patched
AZStd::unique_ptr<ObjectToPatch> targetObj2(patch.Apply(&sourceObj, m_serializeContext.get(), ObjectStream::FilterDescriptor(), sourceFlagsMap, targetFlagsMap));
EXPECT_EQ(targetObj.m_intValue, targetObj2->m_intValue);
}
TEST_F(PatchingTest, PatchNullptrInSource)
{
ObjectWithPointer sourceObj;
sourceObj.m_int = 7;
ObjectWithPointer targetObj;
targetObj.m_int = 8;
targetObj.m_pointerInt = new AZ::s32(-1);
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
ObjectWithPointer* patchedTargetObj = patch.Apply(&sourceObj, m_serializeContext.get());
EXPECT_EQ(targetObj.m_int, patchedTargetObj->m_int);
EXPECT_NE(nullptr, patchedTargetObj->m_pointerInt);
EXPECT_EQ(*targetObj.m_pointerInt, *patchedTargetObj->m_pointerInt);
delete targetObj.m_pointerInt;
azdestroy(patchedTargetObj->m_pointerInt);
delete patchedTargetObj;
}
TEST_F(PatchingTest, PatchNullptrInTarget)
{
ObjectWithPointer sourceObj;
sourceObj.m_int = 20;
sourceObj.m_pointerInt = new AZ::s32(500);
ObjectWithPointer targetObj;
targetObj.m_int = 23054;
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
ObjectWithPointer* patchedTargetObj = patch.Apply(&sourceObj, m_serializeContext.get());
EXPECT_EQ(targetObj.m_int, patchedTargetObj->m_int);
EXPECT_EQ(nullptr, patchedTargetObj->m_pointerInt);
delete sourceObj.m_pointerInt;
delete patchedTargetObj;
}
// prove that properly deprecated container elements are removed and do not leave nulls behind.
TEST_F(PatchingTest, DeprecatedContainerElements_AreRemoved)
{
ObjectBaseClass::Reflect(*m_serializeContext);
ObjectDerivedClass1::Reflect(*m_serializeContext);
ObjectDerivedClass2::Reflect(*m_serializeContext);
ObjectWithVectorOfBaseClasses::Reflect(*m_serializeContext);
// step 1: Make a patch that includes both classes.
ObjectWithVectorOfBaseClasses sourceObject;
ObjectWithVectorOfBaseClasses targetObject;
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass1());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass1()); // <-- we expect to see this second one, it should not be lost
DataPatch patch;
patch.Create(&sourceObject, &targetObject, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
// step 2: DerivedClass2 no longer exists:
m_serializeContext->EnableRemoveReflection();
ObjectDerivedClass2::Reflect(*m_serializeContext);
m_serializeContext->DisableRemoveReflection();
m_serializeContext->ClassDeprecate("ObjectDerivedClass2", azrtti_typeid<ObjectDerivedClass2>());
// generate a patch which will turn a given source object into the targetObject.
ObjectWithVectorOfBaseClasses* patchedTargetObj = patch.Apply(&sourceObject, m_serializeContext.get());
// at this point, the patched target object should only have ObjectDerivedClass1s on it.
// two of them exactly. There should be no other types and there should be no null holes in it.
EXPECT_EQ(patchedTargetObj->m_vectorOfBaseClasses.size(), 2);
for (auto element : patchedTargetObj->m_vectorOfBaseClasses)
{
EXPECT_EQ(azrtti_typeid(*element), azrtti_typeid<ObjectDerivedClass1>() );
}
delete patchedTargetObj;
}
// prove that unreadable container elements (ie, no deprecation info) generate warnings but also
// do not leave nulls behind.
TEST_F(PatchingTest, UnreadableContainerElements_WithNoDeprecation_GenerateWarning_AreRemoved)
{
ObjectBaseClass::Reflect(*m_serializeContext);
ObjectDerivedClass1::Reflect(*m_serializeContext);
ObjectDerivedClass2::Reflect(*m_serializeContext);
ObjectWithVectorOfBaseClasses::Reflect(*m_serializeContext);
// Make a patch that includes both classes.
ObjectWithVectorOfBaseClasses sourceObject;
ObjectWithVectorOfBaseClasses targetObject;
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass1());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass1()); // <-- we expect to see this second one, it should not be lost
DataPatch patch;
patch.Create(&sourceObject, &targetObject, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
// Remove DerivedClass2 from the serialize context:
m_serializeContext->EnableRemoveReflection();
ObjectDerivedClass2::Reflect(*m_serializeContext);
m_serializeContext->DisableRemoveReflection();
// apply the patch despite it containing deprecated things with no deprecation tag, expect 1 error per unknown instance:
AZ_TEST_START_TRACE_SUPPRESSION;
ObjectWithVectorOfBaseClasses* patchedTargetObj = patch.Apply(&sourceObject, m_serializeContext.get());
AZ_TEST_STOP_TRACE_SUPPRESSION(0);
// at this point, the patched target object should only have ObjectDerivedClass1s on it.
// two of them exactly. There should be no other types and there should be no null holes in it.
EXPECT_EQ(patchedTargetObj->m_vectorOfBaseClasses.size(), 2);
for (auto element : patchedTargetObj->m_vectorOfBaseClasses)
{
EXPECT_EQ(azrtti_typeid(*element), azrtti_typeid<ObjectDerivedClass1>() );
}
delete patchedTargetObj;
}
// note that the entire conversion subsystem is based on loading through an ObjectStream, not a direct patch.
// It is not a real use case to deprecate a class during execution and then expect data patch upgrading to function.
// Instead, deprecated classes always come from data "at rest" such as on disk / network stream, which means
// they come via ObjectStream, which does perform conversion and has its own tests.
// This test is just to ensure that when you do load a patch (Using ObjectStream) and elements in that patch have been
// deprecated, it does not cause unexpected errors.
TEST_F(PatchingTest, UnreadableContainerElements_WithDeprecationConverters_AreConverted)
{
ObjectBaseClass::Reflect(*m_serializeContext);
ObjectDerivedClass1::Reflect(*m_serializeContext);
ObjectDerivedClass2::Reflect(*m_serializeContext);
ObjectDerivedClass3::Reflect(*m_serializeContext);
ObjectWithVectorOfBaseClasses::Reflect(*m_serializeContext);
// step 1: Make a patch that includes deprecated classes.
ObjectWithVectorOfBaseClasses sourceObject;
ObjectWithVectorOfBaseClasses targetObject;
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass1());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass1());
targetObject.m_vectorOfBaseClasses.push_back(new ObjectDerivedClass2());
DataPatch patch;
patch.Create(&sourceObject, &targetObject, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
// save the patch itself to a stream.
AZStd::vector<char> charBuffer;
AZ::IO::ByteContainerStream<AZStd::vector<char> > containerStream(&charBuffer);
bool success = AZ::Utils::SaveObjectToStream(containerStream, AZ::ObjectStream::ST_XML, &patch, m_serializeContext.get());
EXPECT_TRUE(success);
// step 2: DerivedClass2 no longer exists:
m_serializeContext->EnableRemoveReflection();
ObjectDerivedClass2::Reflect(*m_serializeContext);
m_serializeContext->DisableRemoveReflection();
m_serializeContext->ClassDeprecate("Dummy UUID", azrtti_typeid<ObjectDerivedClass2>(), ConvertDerivedClass2ToDerivedClass3);
// load it from the container
DataPatch loadedPatch;
// it should generate no warnings but the deprecated ones should not be there.
success = AZ::Utils::LoadObjectFromBufferInPlace(charBuffer.data(), charBuffer.size(), loadedPatch, m_serializeContext.get());
EXPECT_TRUE(success);
// patch the original source object with the new patch which was loaded:
ObjectWithVectorOfBaseClasses* patchedTargetObj = loadedPatch.Apply(&sourceObject, m_serializeContext.get());
// prove that all deprecated classes were converted and order did not shuffle:
ASSERT_EQ(patchedTargetObj->m_vectorOfBaseClasses.size(), 4);
EXPECT_EQ(azrtti_typeid(patchedTargetObj->m_vectorOfBaseClasses[0]), azrtti_typeid<ObjectDerivedClass1>() );
EXPECT_EQ(azrtti_typeid(patchedTargetObj->m_vectorOfBaseClasses[1]), azrtti_typeid<ObjectDerivedClass3>() );
EXPECT_EQ(azrtti_typeid(patchedTargetObj->m_vectorOfBaseClasses[2]), azrtti_typeid<ObjectDerivedClass1>() );
EXPECT_EQ(azrtti_typeid(patchedTargetObj->m_vectorOfBaseClasses[3]), azrtti_typeid<ObjectDerivedClass3>() );
delete patchedTargetObj;
}
TEST_F(PatchingTest, PatchDistinctNullptrSourceTarget)
{
ObjectWithMultiPointers sourceObj;
sourceObj.m_int = 54;
sourceObj.m_pointerInt = new AZ::s32(500);
ObjectWithMultiPointers targetObj;
targetObj.m_int = -2493;
targetObj.m_pointerFloat = new float(3.14f);
DataPatch patch;
patch.Create(&sourceObj, &targetObj, DataPatch::FlagsMap(), DataPatch::FlagsMap(), m_serializeContext.get());
ObjectWithMultiPointers* patchedTargetObj = patch.Apply(&sourceObj, m_serializeContext.get());
EXPECT_EQ(targetObj.m_int, patchedTargetObj->m_int);
EXPECT_EQ(nullptr, patchedTargetObj->m_pointerInt);
EXPECT_NE(nullptr, patchedTargetObj->m_pointerFloat);
EXPECT_EQ(*targetObj.m_pointerFloat, *patchedTargetObj->m_pointerFloat);
delete sourceObj.m_pointerInt;
delete targetObj.m_pointerFloat;
delete patchedTargetObj->m_pointerInt;
azdestroy(patchedTargetObj->m_pointerFloat);
delete patchedTargetObj;
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidValueOverride_ApplySucceeds_FT)
{
// A Legacy DataPatch containing an int set to 150
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000960000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch and complete conversion
ObjectToPatch sourceObj;
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Verify the patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_intValue, 150);
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidValueOverride_LegacyPatchUsesObjectStreamVersion1_ApplySucceeds_FT)
{
// A Legacy DataPatch containing an int set to 180 and using ObjectStream V1 types for the unordered map, pair, and bytestream.
// Note: Does not use legacy types in the patch themselves (EX: a patched AZStd::string will use it's V3 typeId not V1)
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="1">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{18456A80-63CC-40C5-BF16-6AF94F9A9ECC}">
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000B40000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch and complete conversion
ObjectToPatch sourceObj;
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Verify the patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_intValue, 180);
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidPointerOverride_ApplySucceeds_FT)
{
// A Legacy DataPatch containing a pointer to an int set to 56
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{D1FD3240-A7C5-4EA3-8E55-CD18193162B8}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="F01997AC00000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000380000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch and complete conversion
ObjectWithPointer sourceObj;
AZStd::unique_ptr<ObjectWithPointer> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Verify the patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_TRUE(generatedObj->m_pointerInt);
EXPECT_EQ(*generatedObj->m_pointerInt, 56);
azdestroy(generatedObj->m_pointerInt);
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidPointerOverride_LegacyPatchUsesObjectStreamVersion1_ApplySucceeds_FT)
{
// A Legacy DataPatch containing a pointer to an int set to 74 and using ObjectStream V1 types for the unordered map, pair, and bytestream.
// Note: Does not use legacy types in the patch themselves (EX: a patched AZStd::string will use it's V3 typeId not V1)
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="1">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{D1FD3240-A7C5-4EA3-8E55-CD18193162B8}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{18456A80-63CC-40C5-BF16-6AF94F9A9ECC}">
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="F01997AC00000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF60000004A0000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch and complete conversion
ObjectWithPointer sourceObj;
AZStd::unique_ptr<ObjectWithPointer> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
// Verify the patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_TRUE(generatedObj->m_pointerInt);
EXPECT_EQ(*generatedObj->m_pointerInt, 74);
azdestroy(generatedObj->m_pointerInt);
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidContainerOverride_ApplySucceeds_FT)
{
// A Legacy DataPatch containing a vector of 5 objects with incrementing values and persistent Ids
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000E00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000CC00795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000E000000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000D00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000CB00795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000D000000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000C00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000CA00795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000C000000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000B00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000C900795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000B000000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000A00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000C800795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000A000000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the Patch and complete conversion
ObjectToPatch sourceObj;
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
constexpr int expectedSize = 5;
constexpr int persistentIdOffset = 10;
constexpr int dataOffset = 200;
// Verify the patch applied as expected for each value in the patched array
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), expectedSize);
for (int arrayIndex = 0; arrayIndex < expectedSize; ++arrayIndex)
{
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_persistentId, arrayIndex + persistentIdOffset);
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_data, arrayIndex + dataOffset);
}
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidContainerOverride_LegacyPatchUsesObjectStreamVersion1_ApplySucceeds_FT)
{
// A Legacy DataPatch containing a vector of 5 objects with incrementing values and persistent Ids
// Using ObjectStream V1 types for the unordered map, pair, and bytestream.
// Note: Does not use legacy types in the patch themselves (EX: a patched AZStd::string will use it's V3 typeId not V1)
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="1">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{18456A80-63CC-40C5-BF16-6AF94F9A9ECC}">
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000E00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000CC00795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000E000000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000D00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000CB00795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000D000000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000C00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000CA00795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000C000000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000B00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000C900795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000B000000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000A00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="000000000308D0C4D19C7EFF4F93A5F095F33FC855AA5C335CC94272039442EB384D42A1ADCB68F7E0EEF6000000C800795F998615D659793347CD4FC8B91163F3E2B0993A08000000000000000A000000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch and complete conversion
ObjectToPatch sourceObj;
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
constexpr int expectedSize = 5;
constexpr int persistentIdOffset = 10;
constexpr int dataOffset = 200;
// Verify the patch applied as expected for each value in the patched array
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), expectedSize);
for (int arrayIndex = 0; arrayIndex < expectedSize; ++arrayIndex)
{
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_persistentId, arrayIndex + persistentIdOffset);
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_data, arrayIndex + dataOffset);
}
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidGenericTypeOverride_ApplySucceeds_FT)
{
// A Legacy DataPatch containing a string set to "Hello World"
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{DE1EE15F-3458-40AE-A206-C6C957E2432B}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="57E02DD400000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000033903AAAB3F5C475A669EBCD5FA4DB353C90B48656C6C6F20576F726C640000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch and complete conversion
ObjectsWithGenerics sourceObj;
AZStd::unique_ptr<ObjectsWithGenerics> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
constexpr const char* expectedString = "Hello World";
// Verify the patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_STREQ(generatedObj->m_string.c_str(), expectedString);
}
TEST_F(PatchingTest, Apply_LegacyDataPatchWithValidGenericTypeOverride_LegacyPatchUsesObjectStreamVersion1_ApplySucceeds_FT)
{
// A Legacy DataPatch containing a string set to "Hello World" and using ObjectStream V1 types for the unordered map, pair, and bytestream.
// Note: Does not use legacy types in the patch themselves (EX: a patched AZStd::string will use it's V3 typeId not V1)
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="1">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{DE1EE15F-3458-40AE-A206-C6C957E2432B}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{18456A80-63CC-40C5-BF16-6AF94F9A9ECC}">
<Class name="AZStd::pair" field="element" type="{9F3F5302-3390-407A-A6F7-2E011E3BB686}">
<Class name="AddressType" field="value1" value="57E02DD400000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000033903AAAB3F5C475A669EBCD5FA4DB353C90B48656C6C6F20576F726C640000" type="{6F949CC5-24A4-4229-AC8B-C5E6C70E145E}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch and complete conversion
ObjectsWithGenerics sourceObj;
AZStd::unique_ptr<ObjectsWithGenerics> generatedObj(patch.Apply(&sourceObj, m_serializeContext.get()));
const char* expectedString = "Hello World";
// Verify the patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_STREQ(generatedObj->m_string.c_str(), expectedString);
}
TEST_F(PatchingTest, Apply_LegacyDataPatchAppliedTwice_OnSecondApplyPatchHasBeenConverted_BothPatchAppliesSucceed_FT)
{
// A dataPatch containing an int set to 22
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000160000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
constexpr int expectedValue = 22;
// Load the patch from stream
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch
ObjectToPatch sourceObj;
AZStd::unique_ptr<ObjectToPatch> generatedObjFirstApply(patch.Apply(&sourceObj, m_serializeContext.get()));
// Verify patch applied as expected
EXPECT_TRUE(generatedObjFirstApply);
EXPECT_EQ(generatedObjFirstApply->m_intValue, expectedValue);
// Apply the patch again
AZStd::unique_ptr<ObjectToPatch> generatedObjSecondApply(patch.Apply(&sourceObj, m_serializeContext.get()));
// Verify patch applied successfully the second time
EXPECT_TRUE(generatedObjSecondApply);
EXPECT_EQ(generatedObjSecondApply->m_intValue, expectedValue);
}
TEST_F(PatchingTest, Apply_PatchWrittenToThenReadFromStreamBeforeApply_PatchApplySucceeds_FT)
{
ObjectToPatch source;
ObjectToPatch target;
constexpr int targetArraySize = 999;
constexpr int targetValueScalar = 2;
constexpr int persistentIdOffset = 100;
// Build target array
target.m_objectArray.resize(targetArraySize);
for (size_t arrayIndex = 0; arrayIndex < target.m_objectArray.size(); ++arrayIndex)
{
target.m_objectArray[arrayIndex].m_data = static_cast<int>(arrayIndex * targetValueScalar);
target.m_objectArray[arrayIndex].m_persistentId = static_cast<int>((arrayIndex * targetValueScalar) + persistentIdOffset);
}
// Create patch in memory
DataPatch patch;
patch.Create(&source, &target, AZ::DataPatch::FlagsMap(), AZ::DataPatch::FlagsMap(), m_serializeContext.get());
// Serialize patch into stream
AZStd::vector<AZ::u8> streamBuffer;
WritePatchToByteStream(patch, streamBuffer);
// Load patch from stream
DataPatch loadedPatch;
LoadPatchFromByteStream(streamBuffer, loadedPatch);
// Verify integrity of loaded patch
EXPECT_TRUE(loadedPatch.IsValid() && loadedPatch.IsData());
// Apply the patch
AZStd::unique_ptr<ObjectToPatch> generatedObj(loadedPatch.Apply(&source, m_serializeContext.get()));
// Verify patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), targetArraySize);
for (int arrayIndex = 0; arrayIndex < targetArraySize; ++arrayIndex)
{
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_data, arrayIndex * targetValueScalar);
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_persistentId, (arrayIndex * targetValueScalar) + persistentIdOffset);
}
}
TEST_F(PatchingTest, Apply_LegacyPatchWrittenToThenReadFromStreamBeforeApply_PatchApplySucceeds_FT)
{
// A Legacy DataPatch containing an int set to 57
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000390000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from stream
// Loading the legacy patch will run the converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Serialize partially converted patch to stream
AZStd::vector<AZ::u8> streamBuffer;
WritePatchToByteStream(patch, streamBuffer);
// Load partially converted patch from stream
DataPatch loadedPatch;
LoadPatchFromByteStream(streamBuffer, loadedPatch);
// Verify integrity of loaded patch
EXPECT_TRUE(loadedPatch.IsValid() && loadedPatch.IsData());
// Apply the patch
ObjectToPatch source;
AZStd::unique_ptr<ObjectToPatch> generatedObj(loadedPatch.Apply(&source, m_serializeContext.get()));
// Verify the patch applied as expected
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_intValue, 57);
}
TEST_F(PatchingTest, Apply_LegacyPatchAppliedTwice_AppliedAndWrittenToStream_LoadedFromStreamAndApplied_PatchApplySucceeds_FT)
{
// A Legacy DataPatch containing an int set to 92
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF60000005C0000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
constexpr int expectedValue = 92;
// Load the patch from stream
// Loading the legacy patch will run the converter
// Patch Data will be wrapped in the StreamWrapper type until Apply is called
// Apply provides the remaining class data to complete the conversion
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply provides the remaining class data to complete the conversion
ObjectToPatch source;
AZStd::unique_ptr<ObjectToPatch> generatedObjFirstApply(patch.Apply(&source, m_serializeContext.get()));
EXPECT_TRUE(generatedObjFirstApply);
EXPECT_EQ(generatedObjFirstApply->m_intValue, expectedValue);
// Serialize fully converted patch to stream
AZStd::vector<AZ::u8> streamBuffer;
WritePatchToByteStream(patch, streamBuffer);
// Load fully converted patch from stream
DataPatch loadedPatch;
LoadPatchFromByteStream(streamBuffer, loadedPatch);
// Verify integrity of loaded patch
EXPECT_TRUE(loadedPatch.IsValid() && loadedPatch.IsData());
// Apply the patch
AZStd::unique_ptr<ObjectToPatch> generatedObjSecondApply(loadedPatch.Apply(&source, m_serializeContext.get()));
// Verify the patch applied as expected
EXPECT_TRUE(generatedObjSecondApply);
EXPECT_EQ(generatedObjSecondApply->m_intValue, expectedValue);
}
TEST_F(PatchingTest, LegacyDataPatchConverter_LegacyPatchXMLMissingTargetClassId_ConverterThrowsError_FT)
{
// A Legacy DataPatch containing an int set to 178 but missing its TargetClassId
// This should fail conversion
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000B20000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
DataPatch patch;
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// Verify the expected number of Errors/Asserts occur
// Expected errors: Failed to get data from m_targetClassId field during conversion, found in LegacyDataPatchConverter (DataPatch.cpp)
// Converter failed error found in ObjectStreamImpl::LoadClass (ObjectStream.cpp)
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(legacyPatchXML, patch);
AZ_TEST_STOP_ASSERTTEST(2);
}
TEST_F(PatchingTest, LegacyDataPatchConverter_LegacyPatchXMLMissingAddressType_ConverterThrowsError_FT)
{
// A Legacy DataPatch containing an int set to 154 but missing its AddressType
// This should fail conversion
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF60000009A0000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
DataPatch patch;
// Load the patch from XML
// This triggers the Legacy DataPatch Converter
// Verify the expected number of Errors/Asserts occur on conversion
// Expected errors: Failed to find both first and second values in pair during conversion, found in ConvertByteStreamMapToAnyMap (DataPatch.cpp)
// Converter failed error found in ObjectStreamImpl::LoadClass (ObjectStream.cpp)
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(legacyPatchXML, patch);
AZ_TEST_STOP_ASSERTTEST(2);
}
TEST_F(PatchingTest, LegacyDataPatchConverter_LegacyPatchXMLMissingByteStream_ConverterThrowsError_FT)
{
// A Legacy DataPatch missing its ByteStream data and is expected to fail conversion
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
DataPatch patch;
// Load the patch from XML
// This triggers the Legacy DataPatch Converter
// Verify the expected nummber of Errors/Asserts occur on conversion
// Expected errors: Failed to find both first and second values in pair during conversion, found in ConvertByteStreamMapToAnyMap (DataPatch.cpp)
// Converter failed error found in ObjectStreamImpl::LoadClass (ObjectStream.cpp)
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(legacyPatchXML, patch);
AZ_TEST_STOP_ASSERTTEST(2);
}
TEST_F(PatchingTest, LegacyDataPatchConverter_LegacyPatchXMLMissingAddressTypeAndByteStream_ConverterThrowsError_FT)
{
// A Legacy DataPatch missing both its AddressType and ByteStream and is expected to fail conversion
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
</Class>
</Class>
</Class>
</ObjectStream>
)";
DataPatch patch;
// Load the patch from XML
// This triggers the Legacy DataPatch Converter
// Verify the expected number of Errors/Asserts occur
// Expected errors: Failed to find both first and second values in pair during conversion, found in ConvertByteStreamMapToAnyMap (DataPatch.cpp)
// Converter failed error found in ObjectStreamImpl::LoadClass (ObjectStream.cpp)
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(legacyPatchXML, patch);
AZ_TEST_STOP_ASSERTTEST(2);
}
TEST_F(PatchingTest, Apply_LegacyPatchXMLHasInvalidByteStream_ConverterThrowsError_FT)
{
// A Legacy DataPatch expecting to hold an int but containing an invalid bytestream and is expected to fail conversion
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00FFFFFFFF" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// The invalid bytestream will be stored in a StreamWrapper until Apply
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
ObjectToPatch source;
// Apply the patch and complete conversion
// The stored StreamWrapper will attempt to load and fail
// Verify the expected number of Errors/Asserts occur
// Expected errors: Stream is a newer version than object stream supports, found in ObjectStreamImpl::Start (ObjectStream.cpp)
// Failed to load StreamWrapper during DataPatch Apply, found in DataNodeTree::ApplyToElements (DataPatch.cpp)
AZ_TEST_START_ASSERTTEST;
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&source, m_serializeContext.get()));
AZ_TEST_STOP_ASSERTTEST(2);
}
TEST_F(PatchingTest, Apply_LegacyPatchXMLHasIncorrectAddressType_ApplyFails_FT)
{
// A Legacy DataPatch with an int set to 39 but with an incorrect AddressType
// AddressType to location for an int replaced with AddressType for value in an array structure
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{47E5CF10-3FA1-4064-BE7A-70E3143B4025}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="8C2AFF02000000000A00000000000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000270000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
// The incorrect AddressType will be stored to direct patching for the valid ByteStream
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
ObjectToPatch source;
source.m_intValue = 0;
// Apply the patch, conversion will not complete during this stage
// Since AddressType is invalid, the underlying data will not be requested during apply and will not be fully converted
AZ_TEST_START_TRACE_SUPPRESSION;
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&source, m_serializeContext.get()));
AZ_TEST_STOP_TRACE_SUPPRESSION(0);
// We expect the value 39 to not be patched during apply and m_intValue to remain at 0
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_intValue, 0);
}
TEST_F(PatchingTest, Apply_LegacyPatchXMLHasIncorrectTargetClassId_ApplyFailsAndReturnsNull_FT)
{
// A Legacy DataPatch containing an int set to 203
// TargetClassId set to DataPatch type Id which is incorrect for the type being contained
AZStd::string_view legacyPatchXML = R"(<ObjectStream version="3">
<Class name="DataPatch" type="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}">
<Class name="AZ::Uuid" field="m_targetClassId" value="{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}" type="{E152C105-A133-4D03-BBF8-3D4B2FBA3E2A}"/>
<Class name="AZStd::unordered_map" field="m_patch" type="{CF3B3C65-49C0-5199-B671-E75347EB25C2}">
<Class name="AZStd::pair" field="element" type="{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}">
<Class name="AddressType" field="value1" value="C705B33500000000" type="{90752F2D-CBD3-4EE9-9CDD-447E797C8408}"/>
<Class name="ByteStream" field="value2" value="00000000031C72039442EB384D42A1ADCB68F7E0EEF6000000CB0000" type="{ADFD596B-7177-5519-9752-BC418FE42963}"/>
</Class>
</Class>
</Class>
</ObjectStream>
)";
// Load the patch from XML
// This triggers the Legacy DataPatch converter
DataPatch patch;
LoadPatchFromXML(legacyPatchXML, patch);
// Apply the patch, conversion will not complete during this stage
// Since targetClassId does not match supplied source type Apply is expected to return nullptr
ObjectToPatch source;
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&source, m_serializeContext.get()));
// Verify Apply returned a nullptr
EXPECT_FALSE(generatedObj);
}
TEST_F(PatchingTest, AddressTypeSerializerLoad_AddressTypeIsValid_AddressHasOnlyClassData_LoadSucceeds_FT)
{
const int expectedValue = 52;
AZStd::string patchXML = BuildXMLDataPatchV1AddressTypeIntXML(nullptr, expectedValue);
DataPatch patch;
ObjectToPatch source;
// Verify address deserializes with no errors
AZ_TEST_START_TRACE_SUPPRESSION;
LoadPatchFromXML(patchXML, patch);
AZ_TEST_STOP_TRACE_SUPPRESSION(0);
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&source, m_serializeContext.get()));
// Verify addressed field m_int was patched correctly (verifies integrity of address)
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_intValue, expectedValue);
}
TEST_F(PatchingTest, AddressTypeSerializerLoad_AddressTypeIsValid_AddressHasClassAndIndexData_LoadSucceeds_FT)
{
const size_t expectedContainerSize = 5;
const size_t persistentIdOffset = 10;
const size_t dataOffset = 0;
AZStd::string patchXML = BuildXMLDataPatchV1AddressTypeIntVectorXML(nullptr, dataOffset, persistentIdOffset);
DataPatch patch;
ObjectToPatch source;
// Verify address deserializes with no errors
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(patchXML, patch);
AZ_TEST_STOP_ASSERTTEST(0);
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&source, m_serializeContext.get()));
// Verify integrity of patched object
EXPECT_TRUE(generatedObj);
EXPECT_EQ(generatedObj->m_objectArray.size(), expectedContainerSize);
for (size_t arrayIndex = 0; arrayIndex < expectedContainerSize; ++arrayIndex)
{
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_data, arrayIndex);
EXPECT_EQ(generatedObj->m_objectArray[arrayIndex].m_persistentId, arrayIndex + persistentIdOffset);
}
}
TEST_F(PatchingTest, AddressTypeSerializerLoad_AddressTypeIsInvalid_InvalidElementsInPath_LoadFails_FT)
{
AZStd::string pathWithInvalidElements = GetValidAddressForXMLDataPatchV1AddressTypeIntXML();
pathWithInvalidElements += "not/a/valid/path";
AZStd::string patchXML = BuildXMLDataPatchV1AddressTypeIntXML(pathWithInvalidElements.c_str(), 0);
DataPatch patch;
// Load the patch from XML
// This triggers AddressTypeSerializer::Load
// Expected error: AddressType failed to load due to invalid element in path
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(patchXML, patch);
AZ_TEST_STOP_ASSERTTEST(2);
}
TEST_F(PatchingTest, AddressTypeSerializerLoad_AddressTypeIsInvalid_MissingPathDelimiter_LoadFails_FT)
{
// Build a path from a valid path minus the trailing "/" delimiter
AZStd::string validPath = GetValidAddressForXMLDataPatchV1AddressTypeIntXML();
AZStd::string validPathMissingDelimiter(validPath.c_str(), strlen(validPath.c_str()) - 1);
AZStd::string patchXML = BuildXMLDataPatchV1AddressTypeIntXML(validPathMissingDelimiter.c_str(), 0);
DataPatch patch;
// Load the patch from XML
// This triggers AddressTypeSerializer::Load
// Expected error: AddressType failed to load due to path not containing valid delimiter "/"
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(patchXML, patch);
AZ_TEST_STOP_ASSERTTEST(2);
}
TEST_F(PatchingTest, Apply_AddressTypeIsInvalid_SingleEntryInPatch_ApplyFails_FT)
{
AZStd::string patchXML = BuildXMLDataPatchV1AddressTypeIntXML("not/a/valid/path", 0);
DataPatch patch;
ObjectToPatch source;
// Load the patch from XML
// This triggers AddressTypeSerializer::Load
// Expected errors: AddressType failed to load due to invalid element in path (DataPatch.cpp)
// Apply fails due to patch containing Invalid address during Apply (DataPatch.cpp)
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(patchXML, patch);
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&source, m_serializeContext.get()));
AZ_TEST_STOP_ASSERTTEST(3);
}
TEST_F(PatchingTest, AddressTypeSerializerLoad_AddressTypeIsEmpty_SingleEntryInPatch_ApplySucceeds_FT)
{
// An empty address on a single entry patch denotes that the root element is being patched
// Validate that we succesfully load an emtpy address
AZStd::string patchXML = BuildXMLDataPatchV1AddressTypeIntXML("", 0);
DataPatch patch;
ObjectToPatch source;
// Verify address deserializes with no errors
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(patchXML, patch);
AZ_TEST_STOP_ASSERTTEST(0);
}
TEST_F(PatchingTest, Apply_AddressTypeIsInvalid_MultipleEntriesInPatch_ApplyFails_FT)
{
AZStd::string patchXML = BuildXMLDataPatchV1AddressTypeIntVectorXML("not/a/valid/path", 0, 0);
DataPatch patch;
ObjectToPatch source;
// Load the patch from XML
// This triggers AddressTypeSerializer::Load
// Expected errors: AddressType failed to load due to invalid element in path (DataPatch.cpp)
// Apply fails due to empty AddressType (DataPatch.cpp)
AZ_TEST_START_ASSERTTEST;
LoadPatchFromXML(patchXML, patch);
AZStd::unique_ptr<ObjectToPatch> generatedObj(patch.Apply(&source, m_serializeContext.get()));
AZ_TEST_STOP_ASSERTTEST(3);
}
TEST_F(PatchingTest, AddressTypeElementLoad_PathElementHasValidPathForClassType_LoadIsSuccessful_FT)
{
const char* expectedTypeId = "{D0C4D19C-7EFF-4F93-A5F0-95F33FC855AA}";
const char* expectedAddressElement = "ClassA";
const int expectedVersion = 5000;
DataPatch::AddressTypeElement addressTypeElement =
m_addressTypeSerializer->LoadAddressElementFromPath(AZStd::string::format("somecharacters(%s)::%s%s%i/",
expectedTypeId,
expectedAddressElement,
V1AddressTypeElementVersionDelimiter,
expectedVersion));
EXPECT_TRUE(addressTypeElement.IsValid());
EXPECT_EQ(addressTypeElement.GetElementTypeId(), AZ::Uuid(expectedTypeId));
EXPECT_EQ(addressTypeElement.GetAddressElement(), AZ_CRC(expectedAddressElement));
EXPECT_EQ(addressTypeElement.GetElementVersion(), expectedVersion);
}
TEST_F(PatchingTest, AddressTypeElementLoad_PathElementHasValidPathForIndexType_LoadIsSuccessful_FT)
{
const char* expectedTypeId = "{07DEDB71-0585-5BE6-83FF-1C9029B9E5DB}";
const int expectedAddressElement = 4321;
const int expectedVersion = 2222;
DataPatch::AddressTypeElement addressTypeElement =
m_addressTypeSerializer->LoadAddressElementFromPath(AZStd::string::format("somecharacters(%s)#%i%s%i/",
expectedTypeId,
expectedAddressElement,
V1AddressTypeElementVersionDelimiter,
expectedVersion));
EXPECT_TRUE(addressTypeElement.IsValid());
EXPECT_EQ(addressTypeElement.GetAddressElement(), expectedAddressElement);
EXPECT_EQ(addressTypeElement.GetElementTypeId(), AZ::Uuid(expectedTypeId));
EXPECT_EQ(addressTypeElement.GetElementVersion(), expectedVersion);
}
TEST_F(PatchingTest, AddressTypeElementLoad_PathElementHasValidPathForNoneType_LoadIsSuccessful_FT)
{
const int expectedAddressElement = 9999;
DataPatch::AddressTypeElement addressTypeElement =
m_addressTypeSerializer->LoadAddressElementFromPath(AZStd::string::format("%i/", expectedAddressElement));
EXPECT_TRUE(addressTypeElement.IsValid());
EXPECT_EQ(addressTypeElement.GetAddressElement(), expectedAddressElement);
EXPECT_EQ(addressTypeElement.GetElementTypeId(), AZ::Uuid::CreateNull());
EXPECT_EQ(addressTypeElement.GetElementVersion(), std::numeric_limits<AZ::u32>::max());
}
TEST_F(PatchingTest, AddressTypeElementLoad_PathElementHasInvalidTypeId_LoadFails_FT)
{
AZStd::string pathElementWithInvalidTypeId = AZStd::string::format("somecharacters(invalidTypeId)::classB%s5678%s",
V1AddressTypeElementVersionDelimiter,
V1AddressTypeElementPathDelimiter);
DataPatch::AddressTypeElement addressTypeElement = m_addressTypeSerializer->LoadAddressElementFromPath(pathElementWithInvalidTypeId);
EXPECT_FALSE(addressTypeElement.IsValid());
EXPECT_EQ(addressTypeElement.GetElementTypeId(), AZ::Uuid::CreateNull());
}
TEST_F(PatchingTest, AddressTypeElementLoad_TypeIdMissingParentheses_LoadFails_FT)
{
AZStd::string pathMissingParentheses = AZStd::string::format("somecharacters{3A8D5EC9-D70E-41CB-879C-DEF6A6D6ED03}::classE%s3000%s",
V1AddressTypeElementVersionDelimiter,
V1AddressTypeElementPathDelimiter);
DataPatch::AddressTypeElement addressTypeElement = m_addressTypeSerializer->LoadAddressElementFromPath(pathMissingParentheses);
EXPECT_FALSE(addressTypeElement.IsValid());
}
TEST_F(PatchingTest, AddressTypeElementLoad_TypeIdMissingCurlyBraces_LoadFails_FT)
{
AZStd::string pathMissingCurlyBraces = AZStd::string::format("somecharacters(07DEDB71-0585-5BE6-83FF-1C9029B9E5DB)::classF%s9876%s",
V1AddressTypeElementVersionDelimiter,
V1AddressTypeElementPathDelimiter);
DataPatch::AddressTypeElement addressTypeElement = m_addressTypeSerializer->LoadAddressElementFromPath(pathMissingCurlyBraces);
EXPECT_FALSE(addressTypeElement.IsValid());
}
TEST_F(PatchingTest, AddressTypeElementLoad_ClassTypePathElementMissingColons_LoadFails_FT)
{
AZStd::string pathElementMissingColons = AZStd::string::format("somecharacters({861A12B0-BD91-528E-9CEC-505246EE98DE})classC%s5432%s",
V1AddressTypeElementVersionDelimiter,
V1AddressTypeElementPathDelimiter);
DataPatch::AddressTypeElement addressTypeElement = m_addressTypeSerializer->LoadAddressElementFromPath(pathElementMissingColons);
EXPECT_FALSE(addressTypeElement.IsValid());
}
TEST_F(PatchingTest, AddressTypeElementLoad_IndexTypePathElementMissingPound_LoadFails_FT)
{
AZStd::string pathElementMissingPound = AZStd::string::format("somecharacters({ADFD596B-7177-5519-9752-BC418FE42963})91011%s1122%s",
V1AddressTypeElementVersionDelimiter,
V1AddressTypeElementPathDelimiter);
DataPatch::AddressTypeElement addressTypeElement = m_addressTypeSerializer->LoadAddressElementFromPath(pathElementMissingPound);
EXPECT_FALSE(addressTypeElement.IsValid());
}
TEST_F(PatchingTest, AddressTypeElementLoad_PathElementMissingDotBeforeVersion_LoadFails_FT)
{
AZStd::string pathMissingDot = AZStd::string::format("somecharacters({07DEDB71-0585-5BE6-83FF-1C9029B9E5DB})::classD4000%s",
V1AddressTypeElementPathDelimiter);
DataPatch::AddressTypeElement addressTypeElement = m_addressTypeSerializer->LoadAddressElementFromPath(pathMissingDot);
EXPECT_FALSE(addressTypeElement.IsValid());
}
TEST_F(PatchingTest, DataPatchFieldConverterForVersion1Patch_DoesNotRunVersion0To1Converter_Succeeds)
{
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
const ObjectWithNumericFieldV1 initialObject;
ObjectWithNumericFieldV1 testObject;
testObject.m_value = 3946393;
DataPatch testPatch;
testPatch.Create(&initialObject, &testObject, {}, {}, m_serializeContext.get());
// Unreflect ObjectWithNumericFieldV1 and reflect ObjectWithNumericFieldV2
{
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
ObjectWithNumericFieldV2::Reflect(m_serializeContext.get());
}
ObjectWithNumericFieldV2 initialObjectV2;
ObjectWithNumericFieldV2* patchedObject = testPatch.Apply(&initialObjectV2, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObject);
EXPECT_DOUBLE_EQ(32.0, patchedObject->m_value);
// Clean up ObjectWithNumericFieldV2 patch data;
delete patchedObject;
// Unreflect remaining reflected classes
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV2::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
TEST_F(PatchingTest, ObjectFieldConverter_CreateDataPatchInMemoryCanBeAppliedSuccessfully)
{
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
ObjectFieldConverterV1::Reflect(m_serializeContext.get());
const ObjectFieldConverterV1 initialObject;
ObjectFieldConverterV1 testObject;
// Change the defaults of elements on the ObjectFieldConverterV1 object
testObject.m_rootStringField = "Test1";
testObject.m_rootStringVector.emplace_back("Test2");
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
testObject.m_rootInnerObject.m_stringVector.emplace_back("InnerTest2");
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_stringVector.emplace_back("DerivedTest2");
derivedInnerObject->m_objectWithNumericField.m_value = 1;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
DataPatch testPatch;
testPatch.Create(&initialObject, &testObject, {}, {}, m_serializeContext.get());
ObjectFieldConverterV1* patchedObject = testPatch.Apply(&initialObject, m_serializeContext.get());
EXPECT_EQ(testObject.m_rootStringField, patchedObject->m_rootStringField);
EXPECT_EQ(testObject.m_rootStringVector, patchedObject->m_rootStringVector);
InnerObjectFieldConverterV1& testInnerObject = testObject.m_rootInnerObject;
InnerObjectFieldConverterV1& patchedInnerObject = patchedObject->m_rootInnerObject;
EXPECT_EQ(testInnerObject.m_stringField, patchedInnerObject.m_stringField);
EXPECT_EQ(testInnerObject.m_stringVector, patchedInnerObject.m_stringVector);
auto patchedInnerObjectDerived = azrtti_cast<InnerObjectFieldConverterDerivedV1*>(patchedObject->m_baseInnerObjectPolymorphic);
ASSERT_NE(nullptr, patchedInnerObjectDerived);
EXPECT_EQ(derivedInnerObject->m_stringField, patchedInnerObjectDerived->m_stringField);
EXPECT_EQ(derivedInnerObject->m_stringVector, patchedInnerObjectDerived->m_stringVector);
EXPECT_EQ(derivedInnerObject->m_objectWithNumericField.m_value, patchedInnerObjectDerived->m_objectWithNumericField.m_value);
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObject->m_baseInnerObjectPolymorphic;
delete patchedObject;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
ObjectFieldConverterV1::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
inline namespace NestedMemberFieldChangeConverter
{
class InnerObjectFieldConverterV2
{
public:
AZ_CLASS_ALLOCATOR(InnerObjectFieldConverterV2, SystemAllocator, 0);
AZ_RTTI(InnerObjectFieldConverterV2, "{28E61B17-F321-4D4E-9F4C-00846C6631DE}");
virtual ~InnerObjectFieldConverterV2() = default;
static int64_t StringToInt64(const AZStd::string& value)
{
return static_cast<int64_t>(value.size());
}
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<InnerObjectFieldConverterV2>()
// A class version converter is needed to load an InnerObjectFieldConverterV2 when it is stored directly in patch.
// This occurs when patched element is a pointer to a class. In that case the entire class is serialized out
// Therefore when the DataPatch is loaded, the patch Data will load it's AZStd::any, which goes through the normal
// serialization flow, so if the class stored in the AZStd::any is an old version it needs to run through a Version Converter
->Version(2, &VersionConverter)
->Field("InnerBaseIntField", &InnerObjectFieldConverterV2::m_int64Field)
->TypeChange("InnerBaseStringField", 1, 2, AZStd::function<int64_t(const AZStd::string&)>(&StringToInt64))
->NameChange(1, 2, "InnerBaseStringField", "InnerBaseIntField")
->Field("InnerBaseStringVector", &InnerObjectFieldConverterV2::m_stringVector)
;
}
}
static bool VersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& rootElement)
{
if (rootElement.GetVersion() < 2)
{
AZStd::string stringField;
if (!rootElement.GetChildData(AZ_CRC("InnerBaseStringField"), stringField))
{
AZ_Error("PatchingTest", false, "Unable to retrieve 'InnerBaseStringField' data for %u version of the InnerObjectFieldConverterClass",
rootElement.GetVersion());
return false;
}
rootElement.RemoveElementByName(AZ_CRC("InnerBaseStringField"));
rootElement.AddElementWithData(context, "InnerBaseIntField", static_cast<int64_t>(stringField.size()));
}
return true;
}
int64_t m_int64Field;
AZStd::vector<AZStd::string> m_stringVector;
};
//! InnerObjectFieldConverterDerivedV2 is exactly the same as InnerObjectFieldConverterDerivedV1
//! It is just needed to state that InnerObjectFieldConverterV2 is a base class
using InnerObjectFieldConverterDerivedV1WithV2Base = InnerObjectFieldConverterDerivedV1Template<InnerObjectFieldConverterV2>;
//! ObjectFieldConverterV1WithMemberVersionChange is the same has the ObjectFieldConverterV1 class, it just substitutes out
//! the InnerObjectFieldConverterV1 with InnerObjectFieldConverterV2 that has the same typeid, but newer version
class ObjectFieldConverterV1WithMemberVersionChange
{
using ClassType = ObjectFieldConverterV1WithMemberVersionChange;
public:
AZ_CLASS_ALLOCATOR(ClassType, SystemAllocator, 0);
AZ_TYPE_INFO(ClassType, "{5722C4E4-25DE-48C5-BC89-0EE9D38DF433}");
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ClassType>()
->Version(1)
->Field("RootStringField", &ClassType::m_rootStringField)
->Field("RootStringVector", &ClassType::m_rootStringVector)
->Field("RootInnerObjectValue", &ClassType::m_rootInnerObject)
->Field("RootInnerObjectPointer", &ClassType::m_baseInnerObjectPolymorphic)
;
}
}
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::string m_rootStringField;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::vector<AZStd::string> m_rootStringVector;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
InnerObjectFieldConverterV2 m_rootInnerObject{};
InnerObjectFieldConverterV2* m_baseInnerObjectPolymorphic{};
};
TEST_F(PatchingTest, ObjectFieldConverter_ChangeInnerFieldVersion_FieldConverterRunsSuccessfully)
{
using OriginalObjectField = ObjectFieldConverterV1;
using PatchedObjectField = ObjectFieldConverterV1WithMemberVersionChange;
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
OriginalObjectField testObject;
// Change the defaults of the InnerObjectFieldConverterV2 member and InnerObjectFieldConverterV2 pointer member
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_objectWithNumericField.m_value = 10;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
AZStd::vector<uint8_t> byteBuffer;
// Create DataPatch using ObjectFieldConverterV1
{
DataPatch testPatch;
const OriginalObjectField initialObjectV1;
testPatch.Create(&initialObjectV1, &testObject, {}, {}, m_serializeContext.get());
// Write DataPatch to ByteStream before unreflected Version 1 of the InnerObjectFieldConverterV1 class
AZ::IO::ByteContainerStream<decltype(byteBuffer)> byteStream(&byteBuffer);
WritePatchToByteStream(testPatch, byteBuffer);
}
// Now unreflect the ObjectFieldConverterV1, InnerObjectFieldConverterDerivedV1 and InnerObjectFieldConverterDerivedV1
// and reflect ObjectFieldConverterV1WithMemberVersionChange, InnerObjectFieldConverterV2 and InnerObjectFieldConverterDerivedV1WithV2Base
{
m_serializeContext->EnableRemoveReflection();
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
InnerObjectFieldConverterV2::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1WithV2Base::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
}
// Read DataPatch from ByteStream after reflecting Version 2 of the InnerObjectFieldConverterV2 class
// the reason this is required is the testPatch variable has as part of the patch data AZStd::any
// that wraps a instance of an InnerObjectFieldConverterDerivedV1 stored in an InnerObjectFieldConverterV1 pointer
// The virtual table points to the InnerObjectFieldConverterDerivedV1 class, which in a normal patching scenario
// The Data Patch would be loaded from disk after the new version of the InnerObjectFieldConverterV2 has reflected
// and therefore the patch instance data would be an object of InnerObjectFieldConverterDerivedV1WithV2Base with the
// correct vtable
AZ::DataPatch freshDataPatch;
LoadPatchFromByteStream(byteBuffer, freshDataPatch);
const PatchedObjectField initialObjectV2;
PatchedObjectField *patchedObjectV2 = freshDataPatch.Apply(&initialObjectV2, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObjectV2);
EXPECT_EQ(10, patchedObjectV2->m_rootInnerObject.m_int64Field);
auto patchedDerivedInnerObject = azrtti_cast<InnerObjectFieldConverterDerivedV1WithV2Base*>(patchedObjectV2->m_baseInnerObjectPolymorphic);
ASSERT_NE(nullptr, patchedDerivedInnerObject);
EXPECT_EQ(12, patchedDerivedInnerObject->m_int64Field);
ASSERT_NE(nullptr, patchedDerivedInnerObject);
EXPECT_EQ(10, patchedDerivedInnerObject->m_objectWithNumericField.m_value);
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObjectV2->m_baseInnerObjectPolymorphic;
delete patchedObjectV2;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV2::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1WithV2Base::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
}
inline namespace RootLevelDataSerializerFieldConverter
{
// ObjectFieldConverterReplaceMemberDataSerializerV2, uses the same TypeId as ObjectFieldConverterV1
// for to test the FieldConverter for an IDataSerializer
class ObjectFieldConverterReplaceMemberDataSerializerV2
{
using ClassType = ObjectFieldConverterReplaceMemberDataSerializerV2;
public:
AZ_CLASS_ALLOCATOR(ObjectFieldConverterReplaceMemberDataSerializerV2, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectFieldConverterReplaceMemberDataSerializerV2, "{5722C4E4-25DE-48C5-BC89-0EE9D38DF433}");
static AZ::Uuid ConvertStringToUuid(const AZStd::string& value)
{
return AZ::Uuid::CreateName(value.data());
}
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ClassType>()
->Version(2)
->Field("RootUuidField", &ClassType::m_rootUuidField)
->NameChange(1, 2, "RootStringField", "RootUuidField")
// NOTE!! Type Change is prioritized before Name Change, so it works on the old Field name
->TypeChange("RootStringField", 1, 2, AZStd::function<AZ::Uuid(const AZStd::string&)>(&ClassType::ConvertStringToUuid))
->Field("RootStringVector", &ClassType::m_rootStringVector)
->Field("RootInnerObjectValue", &ClassType::m_rootInnerObject)
->Field("RootInnerObjectPointer", &ClassType::m_baseInnerObjectPolymorphic)
;
}
}
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are directly on the patched class
AZ::Uuid m_rootUuidField{ AZ::Uuid::CreateNull() };
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::vector<AZStd::string> m_rootStringVector;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
InnerObjectFieldConverterV1 m_rootInnerObject{};
InnerObjectFieldConverterV1* m_baseInnerObjectPolymorphic{};
};
// ObjectFieldConverterReplaceMemberDataSerializerV3, uses the same TypeId as ObjectFieldConverterV1
// for to test the FieldConverter that skips a level
class ObjectFieldConverterReplaceMemberDataSerializerV3
{
using ClassType = ObjectFieldConverterReplaceMemberDataSerializerV3;
public:
AZ_CLASS_ALLOCATOR(ObjectFieldConverterReplaceMemberDataSerializerV3, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectFieldConverterReplaceMemberDataSerializerV3, "{5722C4E4-25DE-48C5-BC89-0EE9D38DF433}");
static bool ConvertStringToBool(const AZStd::string& value)
{
return !value.empty();
}
static bool ConvertUuidToBool(const AZ::Uuid& value)
{
return !value.IsNull();
}
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ClassType>()
->Version(3)
->Field("RootBoolField", &ClassType::m_rootBoolField)
->NameChange(2, 3, "RootUuidField", "RootBoolField")
->NameChange(1, 3, "RootStringField", "RootBoolField")
//! NOTE Type Change is prioritized before Name Change, so it works on the old Field name
->TypeChange("RootUuidField", 2, 3, AZStd::function<bool(const AZ::Uuid&)>(&ClassType::ConvertUuidToBool))
->TypeChange("RootStringField", 1, 3, AZStd::function<bool(const AZStd::string&)>(&ClassType::ConvertStringToBool))
->Field("RootStringVector", &ClassType::m_rootStringVector)
->Field("RootInnerObjectValue", &ClassType::m_rootInnerObject)
->Field("RootInnerObjectPointer", &ClassType::m_baseInnerObjectPolymorphic)
;
}
}
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are directly on the patched class
bool m_rootBoolField{};
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::vector<AZStd::string> m_rootStringVector;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
InnerObjectFieldConverterV1 m_rootInnerObject{};
InnerObjectFieldConverterV1* m_baseInnerObjectPolymorphic{};
};
TEST_F(PatchingTest, ObjectFieldConverter_ChangeRootDataSerializerField_ConvertsFromV1ToV2_Successfully)
{
using OriginalObjectField = ObjectFieldConverterV1;
using PatchedObjectField = ObjectFieldConverterReplaceMemberDataSerializerV2;
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
OriginalObjectField testObject;
// Change the defaults of elements on the ObjectFieldConverterV1 object
testObject.m_rootStringField = "Test1";
testObject.m_rootStringVector.emplace_back("Test2");
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
testObject.m_rootInnerObject.m_stringVector.emplace_back("InnerTest2");
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_stringVector.emplace_back("DerivedTest2");
derivedInnerObject->m_objectWithNumericField.m_value = 1;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
// Create DataPatch using ObjectFieldConverterV1
DataPatch testPatch;
const OriginalObjectField initialObjectV1;
testPatch.Create(&initialObjectV1, &testObject, {}, {}, m_serializeContext.get());
// Now unreflect the ObjectFieldConverterV1 and reflect ObjectFieldConverterReplaceMemberDataSerializerV2
{
m_serializeContext->EnableRemoveReflection();
OriginalObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
PatchedObjectField::Reflect(m_serializeContext.get());
}
const PatchedObjectField initialObjectV2;
PatchedObjectField *patchedObjectV2 = testPatch.Apply(&initialObjectV2, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObjectV2);
EXPECT_FALSE(patchedObjectV2->m_rootUuidField.IsNull());
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObjectV2->m_baseInnerObjectPolymorphic;
delete patchedObjectV2;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
TEST_F(PatchingTest, ObjectFieldConverter_ChangeRootDataSerializerField_ConvertsFromV2ToV3_Successfully)
{
using OriginalObjectField = ObjectFieldConverterReplaceMemberDataSerializerV2;
using PatchedObjectField = ObjectFieldConverterReplaceMemberDataSerializerV3;
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
OriginalObjectField testObject;
// Change the defaults of elements on the ObjectFieldConverterV1 object
testObject.m_rootUuidField = AZ::Uuid::CreateString("{10000000-0000-0000-0000-000000000000}");
testObject.m_rootStringVector.emplace_back("Test2");
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
testObject.m_rootInnerObject.m_stringVector.emplace_back("InnerTest2");
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_stringVector.emplace_back("DerivedTest2");
derivedInnerObject->m_objectWithNumericField.m_value = 1;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
// Create DataPatch using ObjectFieldConverterV1
DataPatch testPatch;
const OriginalObjectField initialObjectV1;
testPatch.Create(&initialObjectV1, &testObject, {}, {}, m_serializeContext.get());
// Now unreflect the ObjectFieldConverterV1 and reflect ObjectFieldConverterReplaceMemberDataSerializerV2
{
m_serializeContext->EnableRemoveReflection();
OriginalObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
PatchedObjectField::Reflect(m_serializeContext.get());
}
const PatchedObjectField initialObjectV3;
PatchedObjectField *patchedObjectV3 = testPatch.Apply(&initialObjectV3, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObjectV3);
EXPECT_TRUE(patchedObjectV3->m_rootBoolField);
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObjectV3->m_baseInnerObjectPolymorphic;
delete patchedObjectV3;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
TEST_F(PatchingTest, ObjectFieldConverter_ChangeRootDataSerializerField_ConvertsFromV1ToV3_Successfully)
{
using OriginalObjectField = ObjectFieldConverterV1;
using PatchedObjectField = ObjectFieldConverterReplaceMemberDataSerializerV3;
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
OriginalObjectField testObject;
// Change the defaults of elements on the ObjectFieldConverterV1 object
testObject.m_rootStringField = "StringV1";
testObject.m_rootStringVector.emplace_back("Test2");
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
testObject.m_rootInnerObject.m_stringVector.emplace_back("InnerTest2");
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_stringVector.emplace_back("DerivedTest2");
derivedInnerObject->m_objectWithNumericField.m_value = 1;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
// Create DataPatch using ObjectFieldConverterV1
DataPatch testPatch;
const OriginalObjectField initialObjectV1;
testPatch.Create(&initialObjectV1, &testObject, {}, {}, m_serializeContext.get());
// Now unreflect the ObjectFieldConverterV1 and reflect ObjectFieldConverterReplaceMemberDataSerializerV2
{
m_serializeContext->EnableRemoveReflection();
OriginalObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
PatchedObjectField::Reflect(m_serializeContext.get());
}
const PatchedObjectField initialObjectV3;
PatchedObjectField *patchedObjectV3 = testPatch.Apply(&initialObjectV3, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObjectV3);
EXPECT_TRUE(patchedObjectV3->m_rootBoolField);
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObjectV3->m_baseInnerObjectPolymorphic;
delete patchedObjectV3;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
}
inline namespace RootLevelDataContainerFieldConverter
{
// ObjectFieldConverterReplaceMemberDataConverterV2, uses the same TypeId as ObjectFieldConverterV1
// for to test the FieldConverter for an IDataConverter
class ObjectFieldConverterReplaceMemberDataConverterV2
{
using ClassType = ObjectFieldConverterReplaceMemberDataConverterV2;
public:
AZ_CLASS_ALLOCATOR(ClassType, SystemAllocator, 0);
AZ_TYPE_INFO(ClassType, "{5722C4E4-25DE-48C5-BC89-0EE9D38DF433}");
static AZStd::array<AZStd::string, 5> ConvertStringVectorToStringArray(const AZStd::vector<AZStd::string>& value)
{
AZStd::array<AZStd::string, 5> result;
size_t elementsToCopy = AZStd::min(result.size(), value.size());
for (size_t valueIndex = 0; valueIndex < elementsToCopy; ++valueIndex)
{
result[valueIndex] = value[valueIndex];
}
return result;
}
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
// Because containers are implicitly reflected when used as part of a class reflection
// the ObjectFieldConverterV1 AZStd::vector<AZStd::string> class is not reflected
// if the ObjectFieldConverterV1 did not reflect
serializeContext->RegisterGenericType<AZStd::vector<AZStd::string>>();
serializeContext->Class<ClassType>()
->Version(2)
->Field("RootStringField", &ClassType::m_rootStringField)
->Field("RootStringArray", &ClassType::m_rootStringArray)
->TypeChange("RootStringVector", 1, 2, AZStd::function<AZStd::array<AZStd::string, 5>(const AZStd::vector<AZStd::string>&)>(&ConvertStringVectorToStringArray))
->NameChange(1, 2, "RootStringVector", "RootStringArray")
->Field("RootInnerObjectValue", &ClassType::m_rootInnerObject)
->Field("RootInnerObjectPointer", &ClassType::m_baseInnerObjectPolymorphic)
;
}
}
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::string m_rootStringField;
//! AZStd::array<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::array<AZStd::string, 5> m_rootStringArray;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
InnerObjectFieldConverterV1 m_rootInnerObject{};
InnerObjectFieldConverterV1* m_baseInnerObjectPolymorphic{};
};
// ObjectFieldConverterReplaceMemberDataConverterV3, uses the same TypeId as ObjectFieldConverterV1
// for to test the FieldConverter that skips a level
class ObjectFieldConverterReplaceMemberDataConverterV3
{
using ClassType = ObjectFieldConverterReplaceMemberDataConverterV3;
public:
AZ_CLASS_ALLOCATOR(ClassType, SystemAllocator, 0);
AZ_TYPE_INFO(ClassType, "{5722C4E4-25DE-48C5-BC89-0EE9D38DF433}");
static AZStd::list<AZStd::string> ConvertStringVectorToStringList(const AZStd::vector<AZStd::string>& value)
{
AZStd::list<AZStd::string> result(value.begin(), value.end());
return result;
}
static AZStd::list<AZStd::string> ConvertStringArrayToStringList(const AZStd::array<AZStd::string, 5>& value)
{
AZStd::list<AZStd::string> result(value.begin(), value.end());
return result;
}
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ClassType>()
->Version(3)
->Field("RootStringField", &ClassType::m_rootStringField)
->Field("RootStringList", &ClassType::m_rootStringList)
// The TypeChange and NameChange converters are interleaved purposefully to make sure that the order of declaration
// of the converters doesn't affect the conversion result
->TypeChange("RootStringVector", 1, 3, AZStd::function<AZStd::list<AZStd::string>(const AZStd::vector<AZStd::string>&)>(&ConvertStringVectorToStringList))
->NameChange(1, 3, "RootStringVector", "RootStringList")
->NameChange(2, 3, "RootStringArray", "RootStringList")
->TypeChange("RootStringArray", 2, 3, AZStd::function<AZStd::list<AZStd::string>(const AZStd::array<AZStd::string, 5>&)>(&ConvertStringArrayToStringList))
->Field("RootInnerObjectValue", &ClassType::m_rootInnerObject)
->Field("RootInnerObjectPointer", &ClassType::m_baseInnerObjectPolymorphic)
;
}
}
//! AZStd::string uses IDataSerializer for Serialization.
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::string m_rootStringField;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
AZStd::list<AZStd::string> m_rootStringList;
//! AZStd::vector<AZStd::string> uses IDataContainer for Serialization. The inner AZStd::string class uses IDataSerializer for serialization
//! This is to test Field Converters for patched element that are directly on the patched class
InnerObjectFieldConverterV1 m_rootInnerObject{};
InnerObjectFieldConverterV1* m_baseInnerObjectPolymorphic{};
};
TEST_F(PatchingTest, ObjectFieldConverter_ChangeRootDataContainerField_ConvertsFromV1ToV2_Successfully)
{
using OriginalObjectField = ObjectFieldConverterV1;
using PatchedObjectField = ObjectFieldConverterReplaceMemberDataConverterV2;
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
OriginalObjectField testObject;
// Change the defaults of elements on the ObjectFieldConverterV1 object
testObject.m_rootStringField = "Test1";
testObject.m_rootStringVector.emplace_back("Test2");
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
testObject.m_rootInnerObject.m_stringVector.emplace_back("InnerTest2");
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_stringVector.emplace_back("DerivedTest2");
derivedInnerObject->m_objectWithNumericField.m_value = 1;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
// Create DataPatch using ObjectFieldConverterV1
DataPatch testPatch;
const OriginalObjectField initialObjectV1;
testPatch.Create(&initialObjectV1, &testObject, {}, {}, m_serializeContext.get());
// Now unreflect the ObjectFieldConverterV1 and reflect ObjectFieldConverterReplaceMemberDataSerializerV2
{
m_serializeContext->EnableRemoveReflection();
OriginalObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
PatchedObjectField::Reflect(m_serializeContext.get());
}
const PatchedObjectField initialObjectV2;
PatchedObjectField *patchedObjectV2 = testPatch.Apply(&initialObjectV2, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObjectV2);
EXPECT_EQ("Test2", patchedObjectV2->m_rootStringArray.front());
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObjectV2->m_baseInnerObjectPolymorphic;
delete patchedObjectV2;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
TEST_F(PatchingTest, ObjectFieldConverter_ChangeRootDataContainerField_ConvertsFromV2ToV3_Successfully)
{
using OriginalObjectField = ObjectFieldConverterReplaceMemberDataConverterV2;
using PatchedObjectField = ObjectFieldConverterReplaceMemberDataConverterV3;
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
OriginalObjectField testObject;
// Change the defaults of elements on the ObjectFieldConverterV1 object
testObject.m_rootStringField = "Test1";
testObject.m_rootStringArray[0] = "BigTest";
testObject.m_rootStringArray[3] = "SuperTest";
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
testObject.m_rootInnerObject.m_stringVector.emplace_back("InnerTest2");
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_stringVector.emplace_back("DerivedTest2");
derivedInnerObject->m_objectWithNumericField.m_value = 1;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
// Create DataPatch using ObjectFieldConverterV1
DataPatch testPatch;
const OriginalObjectField initialObjectV1;
testPatch.Create(&initialObjectV1, &testObject, {}, {}, m_serializeContext.get());
// Now unreflect the ObjectFieldConverterV1 and reflect ObjectFieldConverterReplaceMemberDataSerializerV2
{
m_serializeContext->EnableRemoveReflection();
OriginalObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
PatchedObjectField::Reflect(m_serializeContext.get());
}
const PatchedObjectField initialObjectV3;
PatchedObjectField *patchedObjectV3 = testPatch.Apply(&initialObjectV3, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObjectV3);
ASSERT_EQ(2, patchedObjectV3->m_rootStringList.size());
auto patchListIter = patchedObjectV3->m_rootStringList.begin();
EXPECT_EQ("BigTest", *patchListIter++);
EXPECT_EQ("SuperTest", *patchListIter++);
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObjectV3->m_baseInnerObjectPolymorphic;
delete patchedObjectV3;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
TEST_F(PatchingTest, ObjectFieldConverter_ChangeRootDataConverterField_ConvertsFromV1ToV3_Successfully)
{
using OriginalObjectField = ObjectFieldConverterV1;
using PatchedObjectField = ObjectFieldConverterReplaceMemberDataConverterV3;
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
OriginalObjectField::Reflect(m_serializeContext.get());
OriginalObjectField testObject;
// Change the defaults of elements on the ObjectFieldConverterV1 object
testObject.m_rootStringField = "StringV1";
testObject.m_rootStringVector.emplace_back("Test2");
testObject.m_rootInnerObject.m_stringField = "InnerTest1";
testObject.m_rootInnerObject.m_stringVector.emplace_back("InnerTest2");
auto derivedInnerObject = aznew InnerObjectFieldConverterDerivedV1;
derivedInnerObject->m_stringField = "DerivedTest1";
derivedInnerObject->m_stringVector.emplace_back("DerivedTest2");
derivedInnerObject->m_objectWithNumericField.m_value = 1;
testObject.m_baseInnerObjectPolymorphic = derivedInnerObject;
// Create DataPatch using ObjectFieldConverterV1
DataPatch testPatch;
const OriginalObjectField initialObjectV1;
testPatch.Create(&initialObjectV1, &testObject, {}, {}, m_serializeContext.get());
// Now unreflect the ObjectFieldConverterV1 and reflect ObjectFieldConverterReplaceMemberDataSerializerV2
{
m_serializeContext->EnableRemoveReflection();
OriginalObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
PatchedObjectField::Reflect(m_serializeContext.get());
}
const PatchedObjectField initialObjectV3;
PatchedObjectField *patchedObjectV3 = testPatch.Apply(&initialObjectV3, m_serializeContext.get());
ASSERT_NE(nullptr, patchedObjectV3);
ASSERT_EQ(1, patchedObjectV3->m_rootStringList.size());
EXPECT_EQ("Test2", patchedObjectV3->m_rootStringList.front());
// Clean up original ObjectFieldConverterV1 object
delete testObject.m_baseInnerObjectPolymorphic;
// Clean up patched ObjectFieldConverterV1 object
delete patchedObjectV3->m_baseInnerObjectPolymorphic;
delete patchedObjectV3;
m_serializeContext->EnableRemoveReflection();
ObjectWithNumericFieldV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterV1::Reflect(m_serializeContext.get());
InnerObjectFieldConverterDerivedV1::Reflect(m_serializeContext.get());
PatchedObjectField::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
}
struct ObjectWithAnyAndBool
{
AZ_CLASS_ALLOCATOR(ObjectWithAnyAndBool, SystemAllocator, 0);
AZ_TYPE_INFO(ObjectWithAnyAndBool, "{266FD5C6-39AE-482F-99B7-DA2A1AFE1EA9}");
static void Reflect(AZ::ReflectContext* reflectContext)
{
if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext))
{
serializeContext->Class<ObjectWithAnyAndBool>()
->Version(1)
->Field("AnyValue", &ObjectWithAnyAndBool::m_any)
->Field("BoolValue", &ObjectWithAnyAndBool::m_bool);
}
}
AZStd::any m_any;
bool m_bool;
};
TEST_F(PatchingTest, DataPatchingObjectWithAnyPreservesAnyData)
{
ObjectWithAnyAndBool::Reflect(m_serializeContext.get());
ObjectWithAnyAndBool firstObject;
firstObject.m_any = AZStd::make_any<bool>(false);
firstObject.m_bool = false;
ObjectWithAnyAndBool secondObject;
secondObject.m_any = AZStd::make_any<bool>(false);
secondObject.m_bool = true;
DataPatch testPatch;
testPatch.Create(&firstObject, &secondObject, {}, {}, m_serializeContext.get());
ObjectWithAnyAndBool* finalObject = testPatch.Apply(&firstObject, m_serializeContext.get());
ASSERT_FALSE(finalObject->m_any.empty());
delete finalObject;
m_serializeContext->EnableRemoveReflection();
ObjectWithAnyAndBool::Reflect(m_serializeContext.get());
m_serializeContext->DisableRemoveReflection();
}
}
}
| 55.807361 | 302 | 0.626157 | [
"object",
"vector",
"3d"
] |
29bf3047a18761844996e172c2f3de1e4cf6b9a3 | 9,134 | hpp | C++ | viennacl/linalg/lu.hpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | viennacl/linalg/lu.hpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | viennacl/linalg/lu.hpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | #ifndef VIENNACL_LINALG_LU_HPP
#define VIENNACL_LINALG_LU_HPP
/* =========================================================================
Copyright (c) 2010-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/** @file viennacl/linalg/lu.hpp
@brief Implementations of LU factorization for row-major and column-major dense matrices.
*/
#include <algorithm> //for std::min
#include "viennacl/matrix.hpp"
#include "viennacl/matrix_proxy.hpp"
#include "viennacl/linalg/prod.hpp"
#include "viennacl/linalg/direct_solve.hpp"
namespace viennacl
{
namespace linalg
{
/** @brief LU factorization of a row-major dense matrix.
*
* @param A The system matrix, where the LU matrices are directly written to. The implicit unit diagonal of L is not written.
*/
template<typename SCALARTYPE>
void lu_factorize(matrix<SCALARTYPE, viennacl::row_major> & A)
{
typedef matrix<SCALARTYPE, viennacl::row_major> MatrixType;
vcl_size_t max_block_size = 32;
vcl_size_t num_blocks = (A.size2() - 1) / max_block_size + 1;
std::vector<SCALARTYPE> temp_buffer(A.internal_size2() * max_block_size);
// Iterate over panels
for (vcl_size_t panel_id = 0; panel_id < num_blocks; ++panel_id)
{
vcl_size_t row_start = panel_id * max_block_size;
vcl_size_t current_block_size = std::min<vcl_size_t>(A.size1() - row_start, max_block_size);
viennacl::range block_range(row_start, row_start + current_block_size);
viennacl::range remainder_range(row_start + current_block_size, A.size1());
//
// Perform LU factorization on panel:
//
// Read from matrix to buffer:
viennacl::backend::memory_read(A.handle(),
sizeof(SCALARTYPE) * row_start * A.internal_size2(),
sizeof(SCALARTYPE) * current_block_size * A.internal_size2(),
&(temp_buffer[0]));
// Factorize (kij-version):
for (vcl_size_t k=0; k < current_block_size - 1; ++k)
{
for (vcl_size_t i=k+1; i < current_block_size; ++i)
{
temp_buffer[row_start + i * A.internal_size2() + k] /= temp_buffer[row_start + k * A.internal_size2() + k]; // write l_ik
SCALARTYPE l_ik = temp_buffer[row_start + i * A.internal_size2() + k];
for (vcl_size_t j = row_start + k + 1; j < A.size1(); ++j)
temp_buffer[i * A.internal_size2() + j] -= l_ik * temp_buffer[k * A.internal_size2() + j]; // l_ik * a_kj
}
}
// Write back:
viennacl::backend::memory_write(A.handle(),
sizeof(SCALARTYPE) * row_start * A.internal_size2(),
sizeof(SCALARTYPE) * current_block_size * A.internal_size2(),
&(temp_buffer[0]));
if (remainder_range.size() > 0)
{
//
// Compute L_12 = [ (U_11)^{T}^{-1} A_{21}^T ]^T
//
viennacl::matrix_range<MatrixType> U_11(A, block_range, block_range);
viennacl::matrix_range<MatrixType> A_21(A, remainder_range, block_range);
viennacl::linalg::inplace_solve(trans(U_11), trans(A_21), viennacl::linalg::lower_tag());
//
// Update remainder of A
//
viennacl::matrix_range<MatrixType> L_21(A, remainder_range, block_range);
viennacl::matrix_range<MatrixType> U_12(A, block_range, remainder_range);
viennacl::matrix_range<MatrixType> A_22(A, remainder_range, remainder_range);
A_22 -= viennacl::linalg::prod(L_21, U_12);
}
}
}
/** @brief LU factorization of a column-major dense matrix.
*
* @param A The system matrix, where the LU matrices are directly written to. The implicit unit diagonal of L is not written.
*/
template<typename SCALARTYPE>
void lu_factorize(matrix<SCALARTYPE, viennacl::column_major> & A)
{
typedef matrix<SCALARTYPE, viennacl::column_major> MatrixType;
vcl_size_t max_block_size = 32;
vcl_size_t num_blocks = (A.size1() - 1) / max_block_size + 1;
std::vector<SCALARTYPE> temp_buffer(A.internal_size1() * max_block_size);
// Iterate over panels
for (vcl_size_t panel_id = 0; panel_id < num_blocks; ++panel_id)
{
vcl_size_t col_start = panel_id * max_block_size;
vcl_size_t current_block_size = std::min<vcl_size_t>(A.size1() - col_start, max_block_size);
viennacl::range block_range(col_start, col_start + current_block_size);
viennacl::range remainder_range(col_start + current_block_size, A.size1());
//
// Perform LU factorization on panel:
//
// Read from matrix to buffer:
viennacl::backend::memory_read(A.handle(),
sizeof(SCALARTYPE) * col_start * A.internal_size1(),
sizeof(SCALARTYPE) * current_block_size * A.internal_size1(),
&(temp_buffer[0]));
// Factorize (kji-version):
for (vcl_size_t k=0; k < current_block_size; ++k)
{
SCALARTYPE a_kk = temp_buffer[col_start + k + k * A.internal_size1()];
for (vcl_size_t i=col_start+k+1; i < A.size1(); ++i)
temp_buffer[i + k * A.internal_size1()] /= a_kk; // write l_ik
for (vcl_size_t j=k+1; j < current_block_size; ++j)
{
SCALARTYPE a_kj = temp_buffer[col_start + k + j * A.internal_size1()];
for (vcl_size_t i=col_start+k+1; i < A.size1(); ++i)
temp_buffer[i + j * A.internal_size1()] -= temp_buffer[i + k * A.internal_size1()] * a_kj; // l_ik * a_kj
}
}
// Write back:
viennacl::backend::memory_write(A.handle(),
sizeof(SCALARTYPE) * col_start * A.internal_size1(),
sizeof(SCALARTYPE) * current_block_size * A.internal_size1(),
&(temp_buffer[0]));
if (remainder_range.size() > 0)
{
//
// Compute U_12:
//
viennacl::matrix_range<MatrixType> L_11(A, block_range, block_range);
viennacl::matrix_range<MatrixType> A_12(A, block_range, remainder_range);
viennacl::linalg::inplace_solve(L_11, A_12, viennacl::linalg::unit_lower_tag());
//
// Update remainder of A
//
viennacl::matrix_range<MatrixType> L_21(A, remainder_range, block_range);
viennacl::matrix_range<MatrixType> U_12(A, block_range, remainder_range);
viennacl::matrix_range<MatrixType> A_22(A, remainder_range, remainder_range);
A_22 -= viennacl::linalg::prod(L_21, U_12);
}
}
}
//
// Convenience layer:
//
/** @brief LU substitution for the system LU = rhs.
*
* @param A The system matrix, where the LU matrices are directly written to. The implicit unit diagonal of L is not written.
* @param B The matrix of load vectors, where the solution is directly written to
*/
template<typename SCALARTYPE, typename F1, typename F2, unsigned int ALIGNMENT_A, unsigned int ALIGNMENT_B>
void lu_substitute(matrix<SCALARTYPE, F1, ALIGNMENT_A> const & A,
matrix<SCALARTYPE, F2, ALIGNMENT_B> & B)
{
assert(A.size1() == A.size2() && bool("Matrix must be square"));
assert(A.size1() == B.size1() && bool("Matrix must be square"));
inplace_solve(A, B, unit_lower_tag());
inplace_solve(A, B, upper_tag());
}
/** @brief LU substitution for the system LU = rhs.
*
* @param A The system matrix, where the LU matrices are directly written to. The implicit unit diagonal of L is not written.
* @param vec The load vector, where the solution is directly written to
*/
template<typename SCALARTYPE, typename F, unsigned int ALIGNMENT, unsigned int VEC_ALIGNMENT>
void lu_substitute(matrix<SCALARTYPE, F, ALIGNMENT> const & A,
vector<SCALARTYPE, VEC_ALIGNMENT> & vec)
{
assert(A.size1() == A.size2() && bool("Matrix must be square"));
inplace_solve(A, vec, unit_lower_tag());
inplace_solve(A, vec, upper_tag());
}
}
}
#endif
| 40.061404 | 134 | 0.577075 | [
"vector"
] |
29c23353ddeb264ea693f57755b55d4c1b04842f | 3,217 | hpp | C++ | ftp_loader/memory.hpp | ALEHACKsp/ftp_loader | 9e0e6a7230bfd57b02868d8d9b2cafc6f205b864 | [
"Unlicense"
] | 1 | 2022-01-14T20:22:50.000Z | 2022-01-14T20:22:50.000Z | ftp_loader/memory.hpp | ALEHACKsp/ftp_loader | 9e0e6a7230bfd57b02868d8d9b2cafc6f205b864 | [
"Unlicense"
] | null | null | null | ftp_loader/memory.hpp | ALEHACKsp/ftp_loader | 9e0e6a7230bfd57b02868d8d9b2cafc6f205b864 | [
"Unlicense"
] | null | null | null | #pragma once
namespace memory
{
inline bool open_process( std::string path, std::vector<std::string> arguments, PROCESS_INFORMATION& pi )
{
STARTUPINFO si;
{
ZeroMemory( &si, sizeof( si ) );
si.cb = sizeof( si );
}
ZeroMemory( &pi, sizeof( pi ) );
std::string str_path{};
str_path += path;
for ( const auto& arg : arguments )
str_path += (" " + arg);
return CreateProcess( nullptr, str_path.data(), nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi );
}
inline bool is_process_open( const std::vector<std::pair<std::uint32_t, std::string>>& vec_processes, std::string_view str_proc )
{
if ( vec_processes.empty() )
return {};
if ( str_proc.empty() )
return {};
auto target = utils::string::to_lower( str_proc.data() );
for ( const auto& ctx : vec_processes )
{
auto ep = utils::string::to_lower( ctx.second );
if ( target.find( ".exe" ) == std::string::npos )
{
if ( ep.find( target ) == std::string::npos )
continue;
}
else
{
if ( ep != target )
continue;
}
const auto h_process = OpenProcess( PROCESS_VM_READ, false, ctx.first );
if ( h_process != nullptr )
{
CloseHandle( h_process );
return true;
}
}
return {};
}
inline bool kill_process( const std::vector<std::pair<std::uint32_t, std::string>>& vec_processes, std::string_view str_proc )
{
if ( vec_processes.empty() )
return {};
if ( str_proc.empty() )
return {};
auto executed = false;
auto target = utils::string::to_lower( str_proc.data() );
for ( const auto& ctx : vec_processes )
{
auto ep = utils::string::to_lower( ctx.second );
if ( target.find( ".exe" ) == std::string::npos )
{
if ( ep.find( target ) == std::string::npos )
continue;
}
else
{
if ( ep != target )
continue;
}
const auto h_process = OpenProcess( PROCESS_TERMINATE, false, ctx.first );
if ( h_process != nullptr )
{
TerminateProcess( h_process, 9 );
CloseHandle( h_process );
executed = true;
}
}
return executed;
}
inline std::uint32_t get_process_id_by_name( const std::vector<std::pair<std::uint32_t, std::string>>& vec_processes, std::string_view str_proc )
{
if ( vec_processes.empty() )
return {};
if ( str_proc.empty() )
return {};
auto target = utils::string::to_lower( str_proc.data() );
for ( const auto& ctx : vec_processes )
{
auto ep = utils::string::to_lower( ctx.second );
if ( target.find( ".exe" ) == std::string::npos )
{
if ( ep.find( target ) == std::string::npos )
continue;
}
else
{
if ( ep != target )
continue;
}
return ctx.first;
}
return {};
}
inline std::vector<std::pair<std::uint32_t, std::string>> get_process_list()
{
std::vector<std::pair<std::uint32_t, std::string>> vec_list{};
const auto h_handle = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL );
PROCESSENTRY32 m_entry{};
m_entry.dwSize = sizeof( m_entry );
if ( !Process32First( h_handle, &m_entry ) )
return {};
while ( Process32Next( h_handle, &m_entry ) )
vec_list.emplace_back( m_entry.th32ProcessID, m_entry.szExeFile );
CloseHandle( h_handle );
return vec_list;
}
} | 22.496503 | 146 | 0.621697 | [
"vector"
] |
29c4481bb1cd50a612266854133b33a7811f7bb8 | 11,259 | cpp | C++ | aten/src/ATen/native/mkl/SpectralOps.cpp | jsun94/nimble | e5c899a69677818b1becc58100577441e15ede13 | [
"BSD-3-Clause"
] | 206 | 2020-11-28T22:56:38.000Z | 2022-03-27T02:33:04.000Z | aten/src/ATen/native/mkl/SpectralOps.cpp | jsun94/nimble | e5c899a69677818b1becc58100577441e15ede13 | [
"BSD-3-Clause"
] | 19 | 2020-12-09T23:13:14.000Z | 2022-01-24T23:24:08.000Z | aten/src/ATen/native/mkl/SpectralOps.cpp | jsun94/nimble | e5c899a69677818b1becc58100577441e15ede13 | [
"BSD-3-Clause"
] | 28 | 2020-11-29T15:25:12.000Z | 2022-01-20T02:16:27.000Z | #include <ATen/ATen.h>
#include <ATen/NativeFunctions.h>
#include <ATen/native/SpectralOpsUtils.h>
#include <ATen/Config.h>
#if !AT_MKL_ENABLED()
namespace at { namespace native {
Tensor _fft_mkl(const Tensor& input, int64_t signal_ndim,
bool complex_input, bool complex_output,
bool inverse, IntArrayRef checked_signal_sizes,
int64_t normalization, bool onesided,
IntArrayRef output_sizes) {
AT_ERROR("fft: ATen not compiled with MKL support");
}
}}
#else // AT_MKL_ENABLED
#include <ATen/ATen.h>
#include <ATen/Config.h>
#include <ATen/Dispatch.h>
#include <ATen/NativeFunctions.h>
#include <ATen/Parallel.h>
#include <ATen/Utils.h>
#include <algorithm>
#include <vector>
#include <numeric>
#include <cmath>
#include <mkl_dfti.h>
#include <ATen/mkl/Exceptions.h>
#include <ATen/mkl/Descriptors.h>
#include <ATen/mkl/Limits.h>
namespace at { namespace native {
// In real-to-complex transform, MKL FFT only fills half of the values due to
// conjugate symmetry. See native/SpectralUtils.h for more details.
// The following structs are used to fill in the other half with symmetry in
// case of real-to-complex transform with onesided=False flag.
// See NOTE [ Fourier Transform Conjugate Symmetry ] in native/SpectralOpsUtils.h.
template <typename scalar_t>
static inline void _fft_fill_with_conjugate_symmetry_slice(Tensor& output,
int64_t signal_ndim, int64_t size_last_dim,
int64_t start_last_dim_idx, int64_t i, int64_t num) {
scalar_t *data = output.data_ptr<scalar_t>();
// A slice means a slice of last dimension (of size size_last_dim)
// This function iterates through the slices to fill, i.e. to_slice_data
// (basically data_slices[i:i+num]), and keeps track of the slices it reads
// data from, i.e., from_slice_data, using from_slice_indices, a vector
// containing the index of the from_slice_data slice.
// Compute the indices for the first from_slice_data
std::vector<int64_t> from_slice_indices(signal_ndim); // up to before last signal dim
int64_t remainder = i;
// set last signal dim values
int64_t from_slice_offset = 0;
for (int64_t d = signal_ndim - 1; d >= 0; d--) {
int64_t dim_size = output.size(d);
int64_t dim_idx = remainder % dim_size;
remainder = remainder / dim_size;
from_slice_indices[d] = dim_idx;
if (d == 0) {
from_slice_offset += dim_idx * output.stride(d);
} else if (dim_idx != 0) {
from_slice_offset += (dim_size - dim_idx) * output.stride(d);
}
}
// First to_slice_data and from_slice_data
scalar_t *to_slice_data = data + i * size_last_dim * 2;
scalar_t *from_slice_data = data + from_slice_offset;
while (num > 0) {
// Fill to_slice_data from values in from_slice_data
for (int64_t j = start_last_dim_idx; j < size_last_dim; j++) {
// multiply index by 2 because of the last complex dim has size 2
int64_t to_idx = j * 2;
int64_t from_idx = (size_last_dim - j) * 2;
to_slice_data[to_idx] = from_slice_data[from_idx];
to_slice_data[to_idx + 1] = -from_slice_data[from_idx + 1];
}
// Compute the next to_slice_data and from_slice_data slices
to_slice_data += size_last_dim * 2;
for (int64_t d = signal_ndim - 1; d >= 0; d--) {
// Compute the next index at this dimension using conjugate symmetry
// Break out of this loop if nothing carries over
from_slice_indices[d] = (from_slice_indices[d] + 1) % output.size(d);
if (d > 0) {
// At d > 0 nonbatch dim, to get next from_slice_data offset
// 1. if this dim idx becomes 1, will need to add (size - 1) * stride
// 2. otherwise, will need to subtract stride
if (from_slice_indices[d] == 0) {
// Subtract. Carries over to previous dimension
from_slice_data -= output.stride(d);
} else if (from_slice_indices[d] == 1) {
// Dimension index becomes 1
// Doesn't carry over to previous dimension
from_slice_data += (output.size(d) - 1) * output.stride(d);
break;
} else {
// Subtract. Doesn't carry over to previous dimension
from_slice_data -= output.stride(d);
break;
}
} else {
// At d = 0 nonbatch dim, it means that to_slice_data ise now at a the
// beginning of a data sample. It maps to itself by conjugate symmetry.
from_slice_data = to_slice_data;
}
}
num--;
}
}
// input should be a contiguous batched tensor of same size as full (twosided)
// signals, but only contains half (onesided) of the values.
// This function modifies inplace.
static inline void _fft_fill_with_conjugate_symmetry_(Tensor& input,
int64_t signal_ndim, int64_t size_last_dim,
int64_t last_dim_start_slice) {
if (last_dim_start_slice >= size_last_dim) {
return;
}
int64_t num = 1;
for (int64_t d = 0; d < signal_ndim; d++) {
num *= input.size(d);
}
at::parallel_for(0, num, 500, [&](int64_t start, int64_t end) {
AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "_fft_fill_with_conjugate_symmetry", [&] {
_fft_fill_with_conjugate_symmetry_slice<scalar_t>(input, signal_ndim, size_last_dim,
last_dim_start_slice, start, (end - start));
});
});
}
// MKL DFTI
Tensor _fft_mkl(const Tensor& self, int64_t signal_ndim,
bool complex_input, bool complex_output,
bool inverse, IntArrayRef checked_signal_sizes,
int64_t normalization, bool onesided,
IntArrayRef output_sizes) {
int64_t batch = self.size(0);
Tensor input = self;
// real/imag dimension must aligned when viewed as of complex type
if (complex_input) {
bool need_contiguous = input.stride(-1) != 1;
for (int64_t i = 0; !need_contiguous && i <= signal_ndim; i++) {
need_contiguous |= input.stride(i) % 2 != 0;
}
if (need_contiguous) {
input = input.contiguous();
}
}
// check if we can use MKL because MKL_LONG is 32bit on some OS, e.g. Windows
// need to check input and output size and strides
// be careful about complex domain, where the stride needs to be divided by 2
// only need to test upper bound MKL_LONG_MAX as these values are non-negative
if (sizeof(MKL_LONG) < sizeof(int64_t)) {
bool need_contiguous = false;
int64_t inumel = 1 /* istride if we contiguous-fy */, onumel = 1;
int64_t isize, osize, istride, ostride;
for (int64_t i = signal_ndim; i >= 0; i--) {
isize = input.size(i);
osize = output_sizes[i];
istride = complex_input ? input.stride(i) >> 1 : input.stride(i);
ostride = onumel;
TORCH_CHECK(isize <= MKL_LONG_MAX && osize <= MKL_LONG_MAX && ostride <= MKL_LONG_MAX,
"MKL FFT: input signal numel exceeds allowed range [1 ~ ", MKL_LONG_MAX, "]");
if (!need_contiguous && istride > MKL_LONG_MAX) {
// If we didn't plan to contiguous-fy but the `istride` exceeds bound,
// check if we can stride (equal to `inumel`) get back within bound if
// we contiguous-fy. If so, then we need to always check `inumel`
// instead for the remaining iterations. The iterations before this are
// fine as `inumel` is non-decreasing.
need_contiguous = true;
}
TORCH_CHECK(!need_contiguous || inumel <= MKL_LONG_MAX,
"MKL FFT: input signal numel exceeds allowed range [1 ~ ", MKL_LONG_MAX, "]");
inumel *= isize;
onumel *= osize;
}
}
Tensor output = at::empty(output_sizes, input.options());
// precision
DFTI_CONFIG_VALUE prec;
if (input.scalar_type() == ScalarType::Float) {
prec = DFTI_SINGLE;
} else if (input.scalar_type() == ScalarType::Double) {
prec = DFTI_DOUBLE;
} else {
std::ostringstream ss;
ss << "MKL FFT doesn't support tensor of type: "
<< toString(input.scalar_type());
AT_ERROR(ss.str());
}
// signal type
DFTI_CONFIG_VALUE signal_type;
if (!inverse) {
signal_type = complex_input ? DFTI_COMPLEX : DFTI_REAL;
} else {
signal_type = complex_output ? DFTI_COMPLEX : DFTI_REAL;
}
// create descriptor with signal size
std::vector<MKL_LONG> mkl_signal_sizes(checked_signal_sizes.begin(), checked_signal_sizes.end());
DftiDescriptor descriptor;
descriptor.init(prec, signal_type, signal_ndim, mkl_signal_sizes.data());
// out of place FFT
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_PLACEMENT, DFTI_NOT_INPLACE));
// batch mode
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_NUMBER_OF_TRANSFORMS, batch));
auto istrides = input.strides();
auto ostrides = output.strides();
// batch dim stride, i.e., dist between each data
MKL_LONG idist = complex_input ? istrides[0] >> 1 : istrides[0];
MKL_LONG odist = complex_output ? ostrides[0] >> 1 : ostrides[0];
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_INPUT_DISTANCE, idist));
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_OUTPUT_DISTANCE, odist));
// signal strides
// first val is offset, set to zero (ignored)
std::vector<MKL_LONG> mkl_istrides(1 + signal_ndim, 0), mkl_ostrides(1 + signal_ndim, 0);
for (int64_t i = 1; i <= signal_ndim; i++) {
mkl_istrides[i] = complex_input ? istrides[i] >> 1 : istrides[i];
mkl_ostrides[i] = complex_output ? ostrides[i] >> 1 : ostrides[i];
}
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_INPUT_STRIDES, mkl_istrides.data()));
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_OUTPUT_STRIDES, mkl_ostrides.data()));
// if conjugate domain of real is involved, set standard CCE storage type
// this will become default in MKL in future
if (!complex_input || !complex_output) {
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX));
}
// rescale if requested
const auto norm = static_cast<fft_norm_mode>(normalization);
if (norm != fft_norm_mode::none) {
auto signal_numel = at::prod_intlist(checked_signal_sizes);
double double_scale;
if (norm == fft_norm_mode::by_root_n) {
double_scale = 1.0 / std::sqrt(static_cast<double>(signal_numel));
} else {
double_scale = 1.0 / static_cast<double>(signal_numel);
}
MKL_DFTI_CHECK(DftiSetValue(descriptor.get(),
inverse ? DFTI_BACKWARD_SCALE : DFTI_FORWARD_SCALE,
prec == DFTI_DOUBLE ? double_scale : static_cast<float>(double_scale)));
}
// finalize
MKL_DFTI_CHECK(DftiCommitDescriptor(descriptor.get()));
// run
if (!inverse) {
MKL_DFTI_CHECK(DftiComputeForward(descriptor.get(), input.data_ptr(), output.data_ptr()));
} else {
MKL_DFTI_CHECK(DftiComputeBackward(descriptor.get(), input.data_ptr(), output.data_ptr()));
}
// now if needed, fill out the other half using Hermitian symmetry dim
if (!complex_input && complex_output && !onesided) {
auto size_last_signal_dim = checked_signal_sizes[signal_ndim - 1];
auto start_slice = infer_ft_real_to_complex_onesided_size(size_last_signal_dim);
_fft_fill_with_conjugate_symmetry_(output, signal_ndim, size_last_signal_dim, start_slice);
}
return output;
}
}} // namespace at::native
#endif
| 40.210714 | 102 | 0.679723 | [
"vector",
"transform"
] |
29c653ec56ca3759070721cb18989f658585b24c | 36,402 | cpp | C++ | aten/src/ATen/native/sparse/SparseCsrTensorMath.cpp | ashutom/pytorch | 71061b4528ff267eeac2303fa508ace2f1e36798 | [
"Intel"
] | null | null | null | aten/src/ATen/native/sparse/SparseCsrTensorMath.cpp | ashutom/pytorch | 71061b4528ff267eeac2303fa508ace2f1e36798 | [
"Intel"
] | null | null | null | aten/src/ATen/native/sparse/SparseCsrTensorMath.cpp | ashutom/pytorch | 71061b4528ff267eeac2303fa508ace2f1e36798 | [
"Intel"
] | null | null | null | #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
#include <ATen/Dispatch.h>
#include <ATen/ExpandUtils.h>
#include <ATen/Parallel.h>
#include <ATen/SparseCsrTensorUtils.h>
#include <ATen/SparseTensorUtils.h>
#include <ATen/core/Tensor.h>
#include <ATen/mkl/Sparse.h>
#include <ATen/native/BinaryOps.h>
#include <ATen/native/CPUBlas.h>
#include <ATen/native/Resize.h>
#include <ATen/native/mkl/SparseBlasImpl.h>
#include <ATen/native/sparse/SparseBlasImpl.h>
#include <ATen/native/sparse/SparseCsrTensorMath.h>
#include <c10/util/irange.h>
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Functions.h>
#include <ATen/NativeFunctions.h>
#include <ATen/Operators.h>
#else
#include <ATen/ops/_conj_physical_native.h>
#include <ATen/ops/_convert_indices_from_coo_to_csr_native.h>
#include <ATen/ops/_convert_indices_from_csr_to_coo_native.h>
#include <ATen/ops/_sparse_bsr_tensor_unsafe_native.h>
#include <ATen/ops/_sparse_csr_tensor_unsafe_native.h>
#include <ATen/ops/_unique.h>
#include <ATen/ops/abs.h>
#include <ATen/ops/abs_native.h>
#include <ATen/ops/add.h>
#include <ATen/ops/add_native.h>
#include <ATen/ops/addmm.h>
#include <ATen/ops/addmm_native.h>
#include <ATen/ops/angle.h>
#include <ATen/ops/angle_native.h>
#include <ATen/ops/asin.h>
#include <ATen/ops/asin_native.h>
#include <ATen/ops/asinh.h>
#include <ATen/ops/asinh_native.h>
#include <ATen/ops/atan.h>
#include <ATen/ops/atan_native.h>
#include <ATen/ops/atanh.h>
#include <ATen/ops/atanh_native.h>
#include <ATen/ops/ceil.h>
#include <ATen/ops/ceil_native.h>
#include <ATen/ops/conj_physical.h>
#include <ATen/ops/conj_physical_native.h>
#include <ATen/ops/copy_native.h>
#include <ATen/ops/empty.h>
#include <ATen/ops/erf.h>
#include <ATen/ops/erf_native.h>
#include <ATen/ops/erfinv.h>
#include <ATen/ops/erfinv_native.h>
#include <ATen/ops/expm1.h>
#include <ATen/ops/expm1_native.h>
#include <ATen/ops/fill_native.h>
#include <ATen/ops/floor.h>
#include <ATen/ops/floor_native.h>
#include <ATen/ops/isinf.h>
#include <ATen/ops/isinf_native.h>
#include <ATen/ops/isnan.h>
#include <ATen/ops/isnan_native.h>
#include <ATen/ops/isneginf.h>
#include <ATen/ops/isneginf_native.h>
#include <ATen/ops/isposinf.h>
#include <ATen/ops/isposinf_native.h>
#include <ATen/ops/log1p.h>
#include <ATen/ops/log1p_native.h>
#include <ATen/ops/mm_native.h>
#include <ATen/ops/mul_native.h>
#include <ATen/ops/neg.h>
#include <ATen/ops/neg_native.h>
#include <ATen/ops/normal_native.h>
#include <ATen/ops/ones_like.h>
#include <ATen/ops/rad2deg.h>
#include <ATen/ops/rad2deg_native.h>
#include <ATen/ops/resize_as_sparse_native.h>
#include <ATen/ops/result_type.h>
#include <ATen/ops/round.h>
#include <ATen/ops/round_native.h>
#include <ATen/ops/round_ops.h>
#include <ATen/ops/sgn.h>
#include <ATen/ops/sgn_native.h>
#include <ATen/ops/sign.h>
#include <ATen/ops/sign_native.h>
#include <ATen/ops/signbit.h>
#include <ATen/ops/signbit_native.h>
#include <ATen/ops/sin.h>
#include <ATen/ops/sin_native.h>
#include <ATen/ops/sinh.h>
#include <ATen/ops/sinh_native.h>
#include <ATen/ops/sqrt.h>
#include <ATen/ops/sqrt_native.h>
#include <ATen/ops/sparse_mask.h>
#include <ATen/ops/sparse_mask_native.h>
#include <ATen/ops/tan.h>
#include <ATen/ops/tan_native.h>
#include <ATen/ops/tanh.h>
#include <ATen/ops/tanh_native.h>
#include <ATen/ops/tensor.h>
#include <ATen/ops/trunc.h>
#include <ATen/ops/trunc_native.h>
#include <ATen/ops/zero_native.h>
#include <ATen/ops/zeros.h>
#endif
#include <algorithm>
namespace at {
namespace meta {
TORCH_META_FUNC(_convert_indices_from_coo_to_csr)
(const Tensor& self, const int64_t size, const bool out_int32) {
TORCH_CHECK(self.dim() <= 1, "Input is supposed to be a vector");
ScalarType scalar_type = out_int32 ? ScalarType::Int : ScalarType::Long;
c10::TensorOptions options =
TensorOptions().device(self.options().device()).dtype(scalar_type);
set_output(size + 1, options);
}
TORCH_META_FUNC(_convert_indices_from_csr_to_coo)
(const Tensor& crow_indices,
const Tensor& col_indices,
const bool out_int32,
const bool transpose) {
TORCH_CHECK(
crow_indices.dim() == 1, "crow_indices is supposed to be a vector");
TORCH_CHECK(col_indices.dim() == 1, "col_indices is supposed to be a vector");
ScalarType scalar_type = out_int32 ? ScalarType::Int : ScalarType::Long;
c10::TensorOptions options = crow_indices.options().dtype(scalar_type);
set_output(0, {2, col_indices.numel()}, {}, options, {});
}
} // namespace meta
namespace {
constexpr int64_t GRAIN_SIZE = at::internal::GRAIN_SIZE;
template <typename F>
Tensor& unary_op_out(F op_out, const Tensor& self, Tensor& result) {
TORCH_INTERNAL_ASSERT(self.is_sparse_csr());
TORCH_INTERNAL_ASSERT(result.is_sparse_csr());
if (!result.is_same(self)) {
// For the case of (0x0) result tensor, manually resize `result` tensor
// to the size of `self` tensor
if (result.numel() == 0) {
at::native::resize_as_sparse_csr_(result, self);
}
// copy_sparse_csr_ internally checks the sizes of result and self tensors
// Hence no external size check required
at::native::copy_sparse_csr_(result, self);
}
auto self_values = self.values();
auto result_values = result.values();
op_out(self_values, result_values);
return result;
}
template <typename F, typename... Args>
Tensor& unary_op_inplace(Tensor& self, const F& op_inplace, Args&&... args) {
TORCH_INTERNAL_ASSERT(self.is_sparse_csr());
auto self_values = self.values();
(self_values.*op_inplace)(std::forward<Args>(args)...);
return self;
}
template <typename input_t, typename output_t>
void convert_indices_from_csr_to_coo_cpu(
const Tensor& indices,
const Tensor& crow_indices,
const Tensor& col_indices,
const bool transpose = false) {
int64_t nrows = crow_indices.numel() - 1;
if (nrows == 0) {
indices.zero_();
return;
}
auto crow_indices_ = crow_indices.expect_contiguous();
const input_t* crow_indices_data_in = crow_indices_->data_ptr<input_t>();
TORCH_INTERNAL_ASSERT(indices.is_contiguous());
auto row0 = indices.select(0, transpose ? 1 : 0);
auto row1 = indices.select(0, transpose ? 0 : 1);
output_t* data_out = row0.data_ptr<output_t>();
row1.copy_(*col_indices.expect_contiguous());
at::parallel_for(0, nrows, GRAIN_SIZE, [&](int64_t start, int64_t end) {
for (const auto i : c10::irange(start, end)) {
std::fill(
&data_out[crow_indices_data_in[i]],
&data_out[crow_indices_data_in[i + 1]],
static_cast<output_t>(i));
}
});
}
} // end anonymous namespace
namespace native {
using namespace at::sparse_csr;
// certain utiliy functions are usable from sparse COO.
using namespace at::sparse;
namespace {
template <typename F>
inline Tensor get_result_tensor_for_unary_op(F op, const Tensor& input) {
auto values = input.values();
// To handle type promotion for inputs to unary ops,
// we first get the result from the underlined op, and use the result
// to create a sparse CSR tensor, which is used as the input to the out=
// variant
auto result_values = op(values);
auto result = at::native::_sparse_csr_tensor_unsafe(
input.crow_indices().clone(),
input.col_indices().clone(),
result_values,
input.sizes(),
result_values.scalar_type(),
input.layout(),
result_values.device());
return result;
}
} // namespace
static constexpr bool is_mkl_supported() {
#ifdef _MSC_VER
return false;
#elif __APPLE__ || __MACH__
return false;
#else
return true;
#endif
}
// Only accept squares sparse matrices or dense input as a vector
// TODO: Check what happens with MKL, the output error reported with non square
// matrices tends to be high See:
// https://github.com/pytorch/pytorch/issues/58770
bool is_square_or_vec(int64_t dim_i, int64_t dim_j, int64_t dim_k) {
return (dim_i == dim_k && dim_k == dim_j) || (dim_i == dim_j && dim_k == 1);
}
Tensor& normal_sparse_csr_(
Tensor& self,
double mean,
double std,
c10::optional<Generator> gen) {
return unary_op_inplace(self, &Tensor::normal_, mean, std, gen);
}
Tensor& fill_sparse_csr_(Tensor& self, const Scalar& value) {
return unary_op_inplace(self, &TensorBase::fill_, value);
}
Tensor sparse_mask_sparse_csr(
const Tensor& self,
const Tensor& sparse_mask) {
TORCH_CHECK(sparse_mask.is_sparse_csr(), "sparse_mask_sparse_csr expects mask to be sparse csr");
TORCH_CHECK(self.dim() == 2, "sparse_mask_sparse_csr expects self to be 2D");
TORCH_CHECK(sparse_mask.dim() == 2, "sparse_mask_sparse_csr expects mask to be 2D");
// We are computing self.mul(at::ones_like(sparse_mask))
// But mul(dense, sparse_csr) is not implemented yet
if (self.layout() == sparse_mask.layout()) {
// Both inputs are CSR
return self.mul(at::ones_like(sparse_mask));
} else {
return self.sparse_mask(sparse_mask.to_sparse()).to_sparse_csr();
}
}
Tensor mul_scalar_sparse_csr(const Tensor& self, const Scalar& other) {
auto result_values = self.values().mul(other);
return at::native::_sparse_csr_tensor_unsafe(
self.crow_indices().clone(),
self.col_indices().clone(),
result_values,
self.sizes(),
result_values.scalar_type(),
self.layout(),
result_values.device());
}
/* Implementation of Unary Ufuncs, those supported for Sparse CSR Layout
* Only simple funcs, with 0->0 correspondence are currently supported. */
#define CREATE_UNARY_UFUNC_OUT(op_name) \
Tensor& op_name##_sparse_csr_out(const Tensor& self, Tensor& result) { \
return unary_op_out(&at::op_name##_outf, self, result); \
}
#define CREATE_UNARY_UFUNC_FUNCTIONAL(op_name) \
Tensor op_name##_sparse_csr(const Tensor& self) { \
return get_result_tensor_for_unary_op(&at::op_name, self); \
}
#define CREATE_UNARY_UFUNC_INPLACE(op_name) \
Tensor& op_name##_sparse_csr_(Tensor& self) { \
return unary_op_inplace(self, &Tensor::op_name##_); \
}
#define CREATE_UNARY_UFUNC(op_name) \
CREATE_UNARY_UFUNC_OUT(op_name); \
CREATE_UNARY_UFUNC_FUNCTIONAL(op_name); \
CREATE_UNARY_UFUNC_INPLACE(op_name);
#define CREATE_UNARY_UFUNC_NO_INPLACE(op_name) \
CREATE_UNARY_UFUNC_OUT(op_name); \
CREATE_UNARY_UFUNC_FUNCTIONAL(op_name);
// Exhaustive list of the unary ufuncs supported by sparse CSR
CREATE_UNARY_UFUNC(abs);
CREATE_UNARY_UFUNC(asin);
CREATE_UNARY_UFUNC(asinh);
CREATE_UNARY_UFUNC(atan);
CREATE_UNARY_UFUNC(atanh);
CREATE_UNARY_UFUNC(ceil);
CREATE_UNARY_UFUNC(erf);
CREATE_UNARY_UFUNC(erfinv);
CREATE_UNARY_UFUNC(expm1);
CREATE_UNARY_UFUNC(floor);
CREATE_UNARY_UFUNC(log1p);
CREATE_UNARY_UFUNC(neg);
CREATE_UNARY_UFUNC(rad2deg);
CREATE_UNARY_UFUNC(sign);
CREATE_UNARY_UFUNC(sin);
CREATE_UNARY_UFUNC(sinh);
CREATE_UNARY_UFUNC(sgn);
CREATE_UNARY_UFUNC(sqrt);
CREATE_UNARY_UFUNC(tan);
CREATE_UNARY_UFUNC(tanh);
CREATE_UNARY_UFUNC(trunc);
CREATE_UNARY_UFUNC(conj_physical);
CREATE_UNARY_UFUNC_INPLACE(zero);
// With addition of `round.decimals` overload, using CREATE_UNARY_UFUNC leads
// to unresolved overload.
Tensor& round_sparse_csr_out(const Tensor& self, Tensor& result) {
return unary_op_out(&at::_ops::round_out::call, self, result);
}
Tensor round_sparse_csr(const Tensor& self) {
return get_result_tensor_for_unary_op(&at::_ops::round::call, self);
}
Tensor& round_sparse_csr_(Tensor& self) {
TORCH_INTERNAL_ASSERT(self.is_sparse_csr());
self.values().round_();
return self;
}
// angle, isneginf, isposinf and signbit currently don't have an inplace variant
CREATE_UNARY_UFUNC_NO_INPLACE(angle);
CREATE_UNARY_UFUNC_NO_INPLACE(isneginf);
CREATE_UNARY_UFUNC_NO_INPLACE(isposinf);
CREATE_UNARY_UFUNC_NO_INPLACE(signbit);
// isnan and isinf don't have an out variant
CREATE_UNARY_UFUNC_FUNCTIONAL(isnan);
CREATE_UNARY_UFUNC_FUNCTIONAL(isinf);
template <typename scalar_t>
void addmm_out_sparse_csr_native_cpu(
const Tensor& sparse,
const Tensor& dense,
const Tensor& r,
Scalar alpha,
Scalar beta) {
auto dim_i = sparse.size(0);
auto dim_k = dense.size(1);
auto csr = sparse.crow_indices();
auto col_indices = sparse.col_indices();
auto values = sparse.values();
scalar_t cast_alpha = alpha.to<scalar_t>();
r.mul_(beta);
AT_DISPATCH_INDEX_TYPES(
col_indices.scalar_type(), "csr_mm_crow_indices", [&]() {
auto csr_accessor = csr.accessor<index_t, 1>();
auto col_indices_accessor = col_indices.accessor<index_t, 1>();
auto values_accessor = values.accessor<scalar_t, 1>();
scalar_t* dense_ptr = dense.data_ptr<scalar_t>();
scalar_t* r_ptr = r.data_ptr<scalar_t>();
int64_t dense_stride0 = dense.stride(0);
int64_t dense_stride1 = dense.stride(1);
int64_t r_stride0 = r.stride(0);
int64_t r_stride1 = r.stride(1);
at::parallel_for(
0,
dim_i,
internal::GRAIN_SIZE,
[&](int64_t irow_start, int64_t irow_end) {
for (index_t h = irow_start; h < irow_end; ++h) {
index_t i_start = csr_accessor[h];
index_t i_end = csr_accessor[h + 1];
for (index_t i = i_start; i < i_end; i++) {
scalar_t val = values_accessor[i];
index_t col = col_indices_accessor[i];
at::native::cpublas::axpy<scalar_t>(
dim_k,
cast_alpha * val,
dense_ptr + col * dense_stride0,
dense_stride1,
r_ptr + h * r_stride0,
r_stride1);
}
}
});
});
}
// Functions for matrix multiplication.
// result = beta * self + alpha (mat1 @ mat2)
Tensor& addmm_out_sparse_csr_cpu(
const Tensor& self,
const Tensor& mat1,
const Tensor& mat2,
const Scalar& beta,
const Scalar& alpha,
Tensor& result) {
// TODO: remove this, there are no codegenerated checks for devices yet
sparse::impl::_check_is_cpu(self, "self");
sparse::impl::_check_is_cpu(mat1, "mat1");
sparse::impl::_check_is_cpu(mat2, "mat2");
sparse::impl::_check_is_cpu(result, "result");
// All the checks are from addmm_out_cuda_impl (ATen/native/cuda/Blas.cpp) and
// TORCH_META_FUNC(addmm) (ATen/native/LinearAlgebra.cpp)
// TODO: remove code duplication and unify code
sparse::impl::_check_dim(mat1, 2, "mat1");
sparse::impl::_check_dim(mat2, 2, "mat2");
TORCH_CHECK(
mat1.size(1) == mat2.size(0), "mat1 and mat2 shapes cannot be multiplied (",
mat1.size(0), "x", mat1.size(1), " and ", mat2.sizes()[0], "x", mat2.sizes()[1], ")");
c10::MaybeOwned<at::Tensor> self_;
// Don't expand self if this is an in-place operation
if (&result == &self) {
self_ = c10::MaybeOwned<Tensor>::borrowed(self);
} else {
self_ = expand_size(self, {mat1.size(0), mat2.size(1)}, "addmm");
}
TORCH_CHECK(((self_->dim() == 2) &&
(self_->size(0) == mat1.size(0)) &&
(self_->size(1) == mat2.size(1))),
"The input tensor must be a matrix with size ",
mat1.size(0),
"x",
mat2.size(1),
", but got a ",
self_->dim(),
"-D tensor with size ",
self_->size(0),
"x",
self_->size(1));
if (&result != &self) {
if (result.layout() == kStrided) {
at::native::resize_output(result, self_->sizes());
} else {
result.resize_as_sparse_(*self_);
}
result.copy_(*self_);
}
if (result.numel() == 0) {
return result;
}
if (sparse::impl::_is_sparse_and_zero(mat1) || sparse::impl::_is_sparse_and_zero(mat2)) {
// According to docs, when beta==0 values in self should be ignored.
// nans and infs should not propagate
if (beta.toComplexDouble() == 0.) {
result.zero_();
} else {
result.mul_(beta);
}
return result;
}
#if !AT_USE_MKL_SPARSE()
TORCH_CHECK(
(mat1.is_sparse_csr() ||
(mat2.is_sparse_csr() && result.is_sparse_csr())),
false,
"Calling addmm on sparse CPU tensors requires Linux platform. ",
"Please use PyTorch built with MKL on Linux.");
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.layout() == kStrided);
AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(
result.scalar_type(), "addmm_sparse_dense", [&] {
addmm_out_sparse_csr_native_cpu<scalar_t>(
mat1, mat2, result, alpha, beta);
});
#else
sparse::impl::mkl::addmm_out_sparse_csr(mat1, mat2, beta, alpha, result);
#endif
return result;
}
Tensor addmm_sparse_csr_dense(
const Tensor& self,
const SparseCsrTensor& sparse,
const Tensor& dense,
const Scalar& beta,
const Scalar& alpha) {
Tensor r = at::empty({0, 0}, self.options());
at::addmm_out(r, self, sparse, dense, beta, alpha);
return r;
}
Tensor& _sparse_csr_mm_out(
const Tensor& mat1,
const Tensor& mat2,
Tensor& result) {
Tensor zero;
if (result.is_sparse_csr()) {
// TODO: replace with at::zeros when it's implemented for sparse csr
zero = at::empty({mat1.size(0), mat2.size(1)}, mat2.options());
} else {
zero = at::zeros({mat1.size(0), mat2.size(1)}, mat2.options());
}
return at::addmm_out(result, zero, mat1, mat2, 0.0, 1.0);
}
Tensor _sparse_csr_mm(const Tensor& mat1, const Tensor& mat2) {
if (mat1.is_sparse_csr() && mat2.is_sparse_csr()) {
// Return sparse
// TODO: replace with at::zeros when it's implemented for sparse csr
return at::addmm(
at::empty({mat1.size(0), mat2.size(1)}, mat2.options()),
mat1,
mat2,
0.0,
1.0);
}
if (mat1.is_sparse_csr() && mat2.layout() == c10::kStrided) {
// Return dense
return at::addmm(
at::zeros({mat1.size(0), mat2.size(1)}, mat2.options()),
mat1,
mat2,
0.0,
1.0);
}
if (mat1.layout() == c10::kStrided && mat2.is_sparse_csr()) {
// Return dense
return at::addmm(
at::zeros({mat1.size(0), mat2.size(1)}, mat1.options()),
mat1,
mat2,
0.0,
1.0);
}
TORCH_INTERNAL_ASSERT(false, "Shouldn't get here. Please open an issue.");
}
Tensor _sparse_csr_addmm(
const Tensor& t,
const SparseCsrTensor& sparse,
const Tensor& dense,
const Scalar& beta,
const Scalar& alpha) {
// _sparse_addmm forward is functionally equivalent to addmm; it's
// just the backward that is different. This technically does an
// unnecessary redispatch, I was too lazy to make it not do that
return at::addmm(t, sparse, dense, beta, alpha);
}
// Functions for element-wise addition.
Tensor add_sparse_csr(
const Tensor& self,
const Tensor& other,
const Scalar& alpha) {
auto commonDtype = at::result_type(self, other);
alpha_check(commonDtype, alpha);
Tensor result = at::empty({0, 0}, self.options().dtype(commonDtype));
return at::add_out(result, self, other, alpha); // redispatch!
}
Tensor& add_sparse_csr_(
Tensor& self,
const Tensor& other,
const Scalar& alpha) {
return at::add_out(self, self, other, alpha); // redispatch!
}
void add_out_dense_sparse_csr_cpu(
const Tensor& out,
const Tensor& dense,
const SparseCsrTensor& src,
const Scalar& alpha) {
TORCH_INTERNAL_ASSERT(dense.layout() == kStrided);
TORCH_INTERNAL_ASSERT(src.is_sparse_csr());
TORCH_INTERNAL_ASSERT(dense.device() == kCPU);
TORCH_CHECK(
out.is_contiguous(),
"out argument must be contiguous, but got: ",
out.suggest_memory_format());
TORCH_CHECK(
out.device() == kCPU,
"add: expected 'out' to be CPU tensor, but got tensor on device: ",
out.device());
TORCH_CHECK(
src.device() == kCPU,
"add: expected 'other' to be a CPU tensor, but got tensor on device: ",
src.device());
TORCH_CHECK(
dense.sizes().equals(src.sizes()),
"add: expected 'self' and 'other' to have same size, but self has size ",
dense.sizes(),
" while other has size ",
src.sizes(),
" (FYI: op2-sparse addition does not currently support broadcasting)");
auto commonDtype = promoteTypes(dense.scalar_type(), src.scalar_type());
TORCH_CHECK(
canCast(commonDtype, out.scalar_type()),
"Can't convert result type ",
commonDtype,
" to output ",
out.scalar_type(),
" in add operation");
auto src_values = src.values();
resize_output(out, dense.sizes());
Tensor resultBuffer = out;
if (out.scalar_type() != commonDtype) {
resultBuffer = dense.to(commonDtype);
} else if (!is_same_tensor(out, dense)) {
resultBuffer.copy_(dense);
}
if (src._nnz() == 0) {
return;
}
auto valuesBuffer = src_values.to(commonDtype).view({-1, src_values.size(-1)});
resultBuffer = resultBuffer.view({-1, out.size(-2), out.size(-1)});
auto src_crow_indices = src.crow_indices().view({-1, src.crow_indices().size(-1)});
auto src_col_indices = src.col_indices().view({-1, src.col_indices().size(-1)});
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(
kHalf,
kBool,
kBFloat16,
commonDtype,
"add_out_op2_sparse_csr",
[&valuesBuffer,
&resultBuffer,
&alpha,
&src_crow_indices,
&src_col_indices]() {
AT_DISPATCH_INDEX_TYPES(
src_crow_indices.scalar_type(),
"csr_add_out_crow_indices",
[&valuesBuffer,
&resultBuffer,
&alpha,
&src_crow_indices,
&src_col_indices]() {
auto batch_count = resultBuffer.dim() > 2 ? resultBuffer.size(-3) : 1;
auto values_accessor = valuesBuffer.accessor<scalar_t, 2>();
scalar_t* out_ptr = resultBuffer.data_ptr<scalar_t>();
scalar_t cast_value = alpha.to<scalar_t>();
auto crow_indices_accessor =
src_crow_indices.accessor<index_t, 2>();
auto col_indices_accessor =
src_col_indices.accessor<index_t, 2>();
auto out_strides = resultBuffer.strides();
for (const auto batch_idx : c10::irange(batch_count)) {
for (const auto irow : c10::irange(src_crow_indices.size(-1) - 1)) {
index_t start_index = crow_indices_accessor[batch_idx][irow];
index_t end_index = crow_indices_accessor[batch_idx][irow + 1];
for (const auto i : c10::irange(start_index, end_index)) {
auto icol = col_indices_accessor[batch_idx][i];
auto index = batch_idx * out_strides[0] + irow * out_strides[1] + icol * out_strides[2];
out_ptr[index] += cast_value * values_accessor[batch_idx][i];
}
}
}
});
});
if (out.scalar_type() != commonDtype) {
out.copy_(resultBuffer);
}
}
Tensor& add_out_sparse_csr_cpu(
const Tensor& self,
const SparseCsrTensor& other,
const Scalar& alpha,
SparseCsrTensor& out) {
if (self.layout() == kStrided) {
add_out_dense_sparse_csr_cpu(out, self, other, alpha);
} else {
TORCH_CHECK(
self.sizes().equals(other.sizes()),
"torch.add: Expected input tensors to have the same shape, but got tensor `self` with shape ",
self.sizes(),
" and tensor `other` with shape ",
other.sizes());
at::native::resize_as_sparse_csr_(out, self);
sparse::impl::cpu::add_out_sparse_csr(self, other, alpha, out);
}
return out;
}
/*
Reductions on sparse CSR tensors using masked semantics.
- A CSR tensor is a 2D tensor that is specified by a 3-tuple
(crow_indices, col_indices, values).
- To support a reduction operator on a CSR tensor, define:
template <typename scalar_t>
struct Reduction...Op {
inline scalar_t operator()(const scalar_t& a, const scalar_t& b) const {
return a ... b;
}
inline scalar_t identity() const { return ...; }
};
Tensor _sparse_csr_..._cpu(const Tensor& input, IntArrayRef dims_to_sum, bool keepdim, c10::optional<ScalarType> dtype) {
...
result = reduce_sparse_csr_cpu_template<scalar_t>(input_, dims_to_sum, keepdim, Reduction...Op<scalar_t>());
...
return result;
}
and add the following
- func: _sparse_csr_op.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
dispatch:
SparseCsrCUDA: _sparse_csr_..._cpu
to native_functions.yaml
Use ReductionAddOp and _sparse_csr_sum implementation as an example.
- Since a CSR tensor dimensionality is always 2, only reductions
with keepdim=True can be supported.
*/
namespace {
template <typename scalar_t, typename ReductionOp>
Tensor reduce_sparse_csr_dim0_cpu_template(const Tensor& sparse, ReductionOp rop) {
/*
Consider the following sparse tensor:
1 * * * *
* * * 2 *
* * 3 * *
* * * * *
4 * 5 * *
that has CSR representation
crow_indices = [0, 1, 2, 3, 3, 5]
col_indices = [0, 3, 2, 0, 2]
values = [1, 2, 3, 4, 5]
Reduction with dim=0 results:
rop(1,4) * rop(3,5) 2 *
that has CSR representation
new_crow_indices = [0, 3]
new_col_indices = [0, 2, 3]
new_values = [rop(1, 4], rop(3, 5), 2]
In general, the CSR representation data can be computed as follows:
new_col_indices, col_map = col_indices.unique(sorted=True, return_inverse=True)
nnz = new_col_indices.numel()
new_crow_indices = [0, nnz]
new_values.resize(nnz); new_values.fill_(identity)
for i in range(col_indices.numel()):
new_values[col_map[i]] = rop(new_values[col_map[i], values[i])
*/
Tensor col_indices = sparse.col_indices();
Tensor values = sparse.values();
auto numel = values.numel();
Tensor new_col_indices;
Tensor columns_map;
/*
Calling at::_unique constitutes the main bottleneck of this
function. However, it is still about 5x faster than using the
invariant:
csr.sum(dim=0) == csr.transpose(0, 1).sum(dim=1)
*/
std::tie(new_col_indices, columns_map) = at::_unique(col_indices, true, true);
auto nnz = new_col_indices.numel();
Tensor new_crow_indices = at::empty({2}, col_indices.options());
new_crow_indices[0] = 0;
new_crow_indices[1] = nnz;
Tensor new_values = at::empty({nnz}, values.options());
new_values.fill_(rop.identity());
AT_DISPATCH_INDEX_TYPES(col_indices.scalar_type(), "reduce_sparse_csr_dim0_cpu_indices",
[&]() {
index_t* columns_map_ptr = columns_map.data_ptr<index_t>();
scalar_t* values_ptr = values.data_ptr<scalar_t>();
scalar_t* new_values_ptr = new_values.data_ptr<scalar_t>();
// There is no point in parallelizing the following for-loop
// because about 99.3% of the computation time is spent in the
// at::_unique call above.
for (int64_t i=0; i<numel; i++) {
index_t col = columns_map_ptr[i];
scalar_t val = values_ptr[i];
new_values_ptr[col] = rop(new_values_ptr[col], val);
}
});
return at::native::_sparse_csr_tensor_unsafe(new_crow_indices, new_col_indices, new_values,
{1, sparse.size(1)},
new_values.scalar_type(),
sparse.layout(),
new_values.device());
}
template <typename scalar_t, typename ReductionOp>
Tensor reduce_sparse_csr_dim1_cpu_template(const Tensor& sparse, ReductionOp rop) {
/*
Consider the following sparse tensor:
1 * * * *
* * * 2 *
* * 3 * *
* * * * *
4 * 5 * *
that has CSR representation
crow_indices = [0, 1, 2, 3, 3, 5]
col_indices = [0, 3, 2, 0, 2]
values = [1, 2, 3, 4, 5]
Reduction with dim=1 results:
1
2
3
*
rop(4, 5)
that has CSR representation
new_crow_indices = [0, 1, 2, 3, 3, 4]
new_col_indices = [0, 0, 0, 0]
new_values = [1, 2, 3, rop(4, 5)]
In general, the result CSR data can be computed as follows:
new_crow_indices = [0]
for i in range(1, nrows+1):
new_crow_indices[i] = new_crow_indices[i-1] + (crow_indices[i] == crow_indices[i-1])
nnz = new_crow_indices[-1]
new_col_indices = zeros(nnz)
new_values.resize(nnz)
j = -1
for i in range(1, nrows+1):
if crow_indices[i] == crow_indices[i-1]:
continue
j += 1
new_values[j] = rop(values[crow_indices[i] : crow_indices[i-1]])
*/
Tensor crow_indices = sparse.crow_indices();
auto ioptions = crow_indices.options();
Tensor values = sparse.values();
auto nrows = sparse.size(0);
Tensor new_crow_indices = at::empty({crow_indices.numel()}, ioptions);
Tensor new_col_indices = at::empty({}, ioptions);
Tensor new_values = at::empty({}, values.options());
Tensor row_map = at::empty({nrows}, ioptions);
AT_DISPATCH_INDEX_TYPES(crow_indices.scalar_type(), "reduce_sparse_csr_dim1_cpu_indices",
[&]() {
index_t* crow_indices_ptr = crow_indices.data_ptr<index_t>();
index_t* new_crow_indices_ptr = new_crow_indices.data_ptr<index_t>();
index_t* row_map_ptr = row_map.data_ptr<index_t>();
int64_t nnz = 0;
new_crow_indices_ptr[0] = 0;
for(int64_t i=0; i<nrows; i++) {
if (crow_indices_ptr[i] != crow_indices_ptr[i + 1]) {
row_map_ptr[i] = nnz;
nnz++;
}
new_crow_indices_ptr[i + 1] = nnz;
}
new_col_indices.resize_(nnz);
new_col_indices.fill_(index_t(0));
new_values.resize_(nnz);
scalar_t* values_ptr = values.data_ptr<scalar_t>();
scalar_t* new_values_ptr = new_values.data_ptr<scalar_t>();
at::parallel_for(
0,
nrows,
internal::GRAIN_SIZE,
[&](int64_t irow_start, int64_t irow_end) {
index_t i_end = crow_indices_ptr[irow_start];
for (index_t h = irow_start; h < irow_end; ++h) {
index_t i_start = i_end;
i_end = crow_indices_ptr[h+1];
if (i_start != i_end) {
scalar_t res = values_ptr[i_start];
for (index_t i = i_start + 1; i < i_end; i++) {
res = rop(res, values_ptr[i]);
}
new_values_ptr[row_map_ptr[h]] = res;
}
}
});
});
return at::native::_sparse_csr_tensor_unsafe(new_crow_indices, new_col_indices, new_values,
{sparse.size(0), 1},
new_values.scalar_type(),
sparse.layout(),
new_values.device());
}
template <typename scalar_t, typename ReductionOp>
Tensor reduce_sparse_csr_dim01_cpu_template(const Tensor& sparse, ReductionOp rop) {
auto ioptions = sparse.col_indices().options();
Tensor values = sparse.values();
auto numel = values.numel();
auto nnz = std::min<int64_t>(1, numel);
/* TODO: we can likely do about 3x better than parallel_reduce:
In [2]: t=torch.randn(5000, 5000).to_sparse_csr()
In [3]: %timeit torch._sparse_csr_sum(t, dim=(0, 1), keepdim=True)
3.39 ms ± 898 ns per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [4]: %timeit torch.sum(t.values())
1.07 ms ± 291 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
*/
scalar_t* values_ptr = values.data_ptr<scalar_t>();
scalar_t value = at::parallel_reduce(
0,
numel,
internal::GRAIN_SIZE,
rop.identity(),
[&](int64_t i_start, int64_t i_end, scalar_t identity) {
scalar_t res = identity;
for (int64_t i=i_start; i<i_end; i++) {
scalar_t val = values_ptr[i];
res = rop(res, val);
}
return res;
}, rop
);
Tensor new_col_indices = at::zeros({nnz}, ioptions);
Tensor new_crow_indices = at::tensor(ArrayRef<int64_t>{0, nnz}, ioptions);
Tensor new_values;
if (numel > 0) {
new_values = at::empty({1}, values.options());
new_values.fill_(value);
} else {
new_values = at::empty({}, values.options());
}
return at::native::_sparse_csr_tensor_unsafe(new_crow_indices, new_col_indices, new_values,
{1, std::min<int64_t>(1, sparse.size(1))},
new_values.scalar_type(),
sparse.layout(),
new_values.device());
}
template <typename scalar_t, typename ReductionOp>
Tensor reduce_sparse_csr_cpu_template(const Tensor& sparse, std::vector<int64_t> dims, ReductionOp rop) {
if (dims.size() == 1) {
if (dims[0] == 0) {
return reduce_sparse_csr_dim0_cpu_template<scalar_t>(sparse, rop);
} else {
TORCH_INTERNAL_ASSERT(dims[0] == 1);
return reduce_sparse_csr_dim1_cpu_template<scalar_t>(sparse, rop);
}
} else if (dims.size() == 2) {
TORCH_INTERNAL_ASSERT(((dims[0] == 0 && dims[1] == 1) || (dims[0] == 1 && dims[1] == 0)));
return reduce_sparse_csr_dim01_cpu_template<scalar_t>(sparse, rop);
}
TORCH_INTERNAL_ASSERT(dims.size() == 0);
// effective after gh-29137 has been resolved
return sparse.clone();
}
template <typename scalar_t, typename ReductionOp>
Tensor reduce_sparse_csr_cpu_template(const Tensor& sparse, IntArrayRef dims_to_sum, bool keepdim, ReductionOp rop) {
TORCH_INTERNAL_ASSERT(sparse.is_sparse_csr());
TORCH_CHECK(keepdim, "reduction operations on CSR tensors with keepdim=False is unsupported");
TORCH_INTERNAL_ASSERT(sparse.device() == kCPU);
const int64_t input_dim = sparse.dim();
TORCH_INTERNAL_ASSERT(input_dim == 2);
auto dims = dims_to_sum.vec();
maybe_wrap_dims(dims, input_dim);
if (dims.size() == 0) {
// after gh-29137 is resolved, delete this if-block
dims.emplace_back(0);
dims.emplace_back(1);
}
return reduce_sparse_csr_cpu_template<scalar_t>(sparse, dims, rop);
}
template <typename scalar_t>
struct ReductionAddOp {
inline scalar_t operator()(const scalar_t& a, const scalar_t& b) const {
return a + b;
}
inline scalar_t identity() const { return 0; }
};
template <typename scalar_t>
struct ReductionMulOp {
inline scalar_t operator()(const scalar_t& a, const scalar_t& b) const {
return a * b;
}
inline scalar_t identity() const { return 1; }
};
} // namespace
Tensor _sparse_csr_sum_cpu(const Tensor& input, IntArrayRef dims_to_sum, bool keepdim, c10::optional<ScalarType> dtype) {
ScalarType dtype_ = dtype.value_or(input.scalar_type());
Tensor input_ = input.to(dtype_);
Tensor result;
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(
kHalf, kBFloat16, input_.scalar_type(), "_sparse_csr_sum_cpu",
[&] {
result = reduce_sparse_csr_cpu_template<scalar_t>(input_, dims_to_sum, keepdim, ReductionAddOp<scalar_t>());
});
return result;
}
Tensor _sparse_csr_prod_cpu(const Tensor& input, IntArrayRef dims_to_reduce, bool keepdim, c10::optional<ScalarType> dtype) {
ScalarType dtype_ = dtype.value_or(input.scalar_type());
Tensor input_ = input.to(dtype_);
Tensor result;
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(
kHalf, kBFloat16, input_.scalar_type(), "_sparse_csr_prod_cpu",
[&] {
result = reduce_sparse_csr_cpu_template<scalar_t>(input_, dims_to_reduce, keepdim, ReductionMulOp<scalar_t>());
});
return result;
}
} // namespace native
} // namespace at
| 33.4885 | 125 | 0.641696 | [
"shape",
"vector"
] |
29c8d7c5f1d7039f68cdea62e44c291c67e9b38d | 10,867 | hpp | C++ | include/opentxs/core/OTStoragePB.hpp | rfree2/opentxs | 3f61dd0abe2e35b7bc52008517873174b2f9dfa7 | [
"MIT"
] | null | null | null | include/opentxs/core/OTStoragePB.hpp | rfree2/opentxs | 3f61dd0abe2e35b7bc52008517873174b2f9dfa7 | [
"MIT"
] | null | null | null | include/opentxs/core/OTStoragePB.hpp | rfree2/opentxs | 3f61dd0abe2e35b7bc52008517873174b2f9dfa7 | [
"MIT"
] | null | null | null | /************************************************************
*
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* EMAIL:
* fellowtraveler@opentransactions.org
*
* WEBSITE:
* http://www.opentransactions.org/
*
* -----------------------------------------------------
*
* LICENSE:
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL
* was not distributed with this file, You can obtain one
* at http://mozilla.org/MPL/2.0/.
*
* DISCLAIMER:
* 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 Mozilla Public License
* for more details.
*
************************************************************/
#ifndef OPENTXS_CORE_OTSTORAGEPB_HPP
#define OPENTXS_CORE_OTSTORAGEPB_HPP
#include "util/Assert.hpp"
#include <deque>
#include <iostream>
#include <map>
#include <vector>
#if defined(OTDB_PROTOCOL_BUFFERS)
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4267)
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#ifndef __clang__
// -Wuseless-cast does not exist in clang
#pragma GCC diagnostic ignored "-Wuseless-cast"
#endif
#endif
#include "Generics.pb.h"
#include "Markets.pb.h"
#include "Bitcoin.pb.h"
#include "Moneychanger.pb.h"
#ifdef _WIN32
#pragma warning(pop)
#else
#pragma GCC diagnostic pop
#endif
namespace opentxs
{
namespace OTDB
{
// Interface: IStorablePB
//
class IStorablePB : public IStorable
{
public:
virtual ~IStorablePB()
{
}
virtual ::google::protobuf::MessageLite* getPBMessage();
virtual bool onPack(PackedBuffer& theBuffer, Storable& inObj);
virtual bool onUnpack(PackedBuffer& theBuffer, Storable& outObj);
OT_USING_ISTORABLE_HOOKS;
};
// BUFFER for Protocol Buffers.
// Google's protocol buffers serializes to std::strings and streams. How
// conveeeeeenient.
class BufferPB : public PackedBuffer
{
friend class PackerSubclass<BufferPB>;
friend class IStorablePB;
std::string m_buffer;
public:
BufferPB()
: PackedBuffer()
{
}
virtual ~BufferPB()
{
}
virtual bool PackString(std::string& theString);
virtual bool UnpackString(std::string& theString);
virtual bool ReadFromIStream(std::istream& inStream, int64_t lFilesize);
virtual bool WriteToOStream(std::ostream& outStream);
virtual const uint8_t* GetData();
virtual size_t GetSize();
virtual void SetData(const uint8_t* pData, size_t theSize);
std::string& GetBuffer()
{
return m_buffer;
}
};
// Protocol Buffers packer.
//
typedef PackerSubclass<BufferPB> PackerPB;
// Used for subclassing IStorablePB:
//
template <class theBaseType, class theInternalType,
StoredObjectType theObjectType>
class ProtobufSubclass : public theBaseType, public IStorablePB
{
private:
theInternalType __pb_obj;
std::string m_Type;
public:
static Storable* Instantiate()
{
return dynamic_cast<Storable*>(
new ProtobufSubclass<theBaseType, theInternalType, theObjectType>);
}
ProtobufSubclass()
: theBaseType()
, IStorablePB()
, m_Type(StoredObjectTypeStrings[static_cast<int32_t>(theObjectType)])
{
m_Type += "PB";
/*std::cout << m_Type << " -- Constructor" << std::endl;*/ }
ProtobufSubclass(const ProtobufSubclass<theBaseType, theInternalType,
theObjectType>& rhs)
: theBaseType()
, IStorablePB()
, m_Type(StoredObjectTypeStrings[static_cast<int32_t>(theObjectType)])
{
m_Type += "PB";
/*std::cout << m_Type << " -- Copy Constructor" << std::endl; */ rhs
.CopyToObject(*this);
}
ProtobufSubclass<theBaseType, theInternalType, theObjectType>& operator=(
const ProtobufSubclass<theBaseType, theInternalType, theObjectType>&
rhs)
{
rhs.CopyToObject(*this);
return *this;
}
void CopyToObject(ProtobufSubclass<theBaseType, theInternalType,
theObjectType>& theNewStorable) const
{
OTPacker* pPacker = OTPacker::Create(PACK_PROTOCOL_BUFFERS);
const OTDB::Storable* pIntermediate =
dynamic_cast<const OTDB::Storable*>(this);
if (nullptr == pPacker) {
OT_FAIL;
}
PackedBuffer* pBuffer =
pPacker->Pack(*(const_cast<OTDB::Storable*>(pIntermediate)));
if (nullptr == pBuffer) {
OT_FAIL;
}
if (!pPacker->Unpack(*pBuffer, theNewStorable)) {
OT_FAIL;
}
if (nullptr != pPacker) {
delete pPacker;
pPacker = nullptr;
}
if (nullptr != pBuffer) {
delete pBuffer;
pBuffer = nullptr;
}
}
virtual ::google::protobuf::MessageLite* getPBMessage();
// IStorable * clone(void) const
// {return dynamic_cast<IStorable *>(new
// ProtobufSubclass<theBaseType, theInternalType, theObjectType>(*this));}
virtual theBaseType* clone(void) const
{ /*std::cout << "Cloning a " << m_Type << std::endl;*/
return dynamic_cast<theBaseType*>(do_clone());
}
IStorable* do_clone(void) const
{
Storable* pNewStorable =
Storable::Create(theObjectType, PACK_PROTOCOL_BUFFERS);
if (nullptr == pNewStorable) OT_FAIL;
CopyToObject(*(dynamic_cast<
ProtobufSubclass<theBaseType, theInternalType, theObjectType>*>(
pNewStorable)));
return dynamic_cast<IStorable*>(pNewStorable);
}
virtual ~ProtobufSubclass()
{
}
OT_USING_ISTORABLE_HOOKS;
virtual void hookBeforePack(); // <=== Implement this if you subclass.
virtual void hookAfterUnpack(); // <=== Implement this if you subclass.
};
#define DECLARE_PROTOBUF_SUBCLASS(theBaseType, theInternalType, theNewType, \
theObjectType) \
template <> \
void ProtobufSubclass<theBaseType, theInternalType, \
theObjectType>::hookBeforePack(); \
template <> \
void ProtobufSubclass<theBaseType, theInternalType, \
theObjectType>::hookAfterUnpack(); \
typedef ProtobufSubclass<theBaseType, theInternalType, theObjectType> \
theNewType
// THE ACTUAL SUBCLASSES:
DECLARE_PROTOBUF_SUBCLASS(OTDBString, String_InternalPB, StringPB,
STORED_OBJ_STRING);
DECLARE_PROTOBUF_SUBCLASS(Blob, Blob_InternalPB, BlobPB, STORED_OBJ_BLOB);
DECLARE_PROTOBUF_SUBCLASS(StringMap, StringMap_InternalPB, StringMapPB,
STORED_OBJ_STRING_MAP);
DECLARE_PROTOBUF_SUBCLASS(BitcoinAcct, BitcoinAcct_InternalPB, BitcoinAcctPB,
STORED_OBJ_BITCOIN_ACCT);
DECLARE_PROTOBUF_SUBCLASS(BitcoinServer, BitcoinServer_InternalPB,
BitcoinServerPB, STORED_OBJ_BITCOIN_SERVER);
DECLARE_PROTOBUF_SUBCLASS(RippleServer, RippleServer_InternalPB, RippleServerPB,
STORED_OBJ_RIPPLE_SERVER);
DECLARE_PROTOBUF_SUBCLASS(LoomServer, LoomServer_InternalPB, LoomServerPB,
STORED_OBJ_LOOM_SERVER);
DECLARE_PROTOBUF_SUBCLASS(ServerInfo, ServerInfo_InternalPB, ServerInfoPB,
STORED_OBJ_SERVER_INFO);
DECLARE_PROTOBUF_SUBCLASS(ContactAcct, ContactAcct_InternalPB, ContactAcctPB,
STORED_OBJ_CONTACT_ACCT);
DECLARE_PROTOBUF_SUBCLASS(ContactNym, ContactNym_InternalPB, ContactNymPB,
STORED_OBJ_CONTACT_NYM);
DECLARE_PROTOBUF_SUBCLASS(Contact, Contact_InternalPB, ContactPB,
STORED_OBJ_CONTACT);
DECLARE_PROTOBUF_SUBCLASS(AddressBook, AddressBook_InternalPB, AddressBookPB,
STORED_OBJ_ADDRESS_BOOK);
DECLARE_PROTOBUF_SUBCLASS(WalletData, WalletData_InternalPB, WalletDataPB,
STORED_OBJ_WALLET_DATA);
DECLARE_PROTOBUF_SUBCLASS(MarketData, MarketData_InternalPB, MarketDataPB,
STORED_OBJ_MARKET_DATA);
DECLARE_PROTOBUF_SUBCLASS(MarketList, MarketList_InternalPB, MarketListPB,
STORED_OBJ_MARKET_LIST);
DECLARE_PROTOBUF_SUBCLASS(BidData, OfferDataMarket_InternalPB, BidDataPB,
STORED_OBJ_BID_DATA);
DECLARE_PROTOBUF_SUBCLASS(AskData, OfferDataMarket_InternalPB, AskDataPB,
STORED_OBJ_ASK_DATA);
DECLARE_PROTOBUF_SUBCLASS(OfferListMarket, OfferListMarket_InternalPB,
OfferListMarketPB, STORED_OBJ_OFFER_LIST_MARKET);
DECLARE_PROTOBUF_SUBCLASS(TradeDataMarket, TradeDataMarket_InternalPB,
TradeDataMarketPB, STORED_OBJ_TRADE_DATA_MARKET);
DECLARE_PROTOBUF_SUBCLASS(TradeListMarket, TradeListMarket_InternalPB,
TradeListMarketPB, STORED_OBJ_TRADE_LIST_MARKET);
DECLARE_PROTOBUF_SUBCLASS(OfferDataNym, OfferDataNym_InternalPB, OfferDataNymPB,
STORED_OBJ_OFFER_DATA_NYM);
DECLARE_PROTOBUF_SUBCLASS(OfferListNym, OfferListNym_InternalPB, OfferListNymPB,
STORED_OBJ_OFFER_LIST_NYM);
DECLARE_PROTOBUF_SUBCLASS(TradeDataNym, TradeDataNym_InternalPB, TradeDataNymPB,
STORED_OBJ_TRADE_DATA_NYM);
DECLARE_PROTOBUF_SUBCLASS(TradeListNym, TradeListNym_InternalPB, TradeListNymPB,
STORED_OBJ_TRADE_LIST_NYM);
typedef OfferDataMarket_InternalPB BidData_InternalPB;
typedef OfferDataMarket_InternalPB AskData_InternalPB;
// !! ALL OF THESE have to provide implementations for hookBeforePack() and
// hookAfterUnpack().
// In .cpp file:
/*
void SUBCLASS_HERE::hookBeforePack()
{
__pb_obj.set_PROPERTY_NAME_GOES_HERE(PROPERTY_NAME_GOES_HERE);
}
void SUBCLASS_HERE::hookAfterUnpack()
{
PROPERTY_NAME_GOES_HERE = __pb_obj.PROPERTY_NAME_GOES_HERE();
}
*/
} // namespace OTDB
} // namespace opentxs
#endif // defined(OTDB_PROTOCOL_BUFFERS)
#endif // OPENTXS_CORE_OTSTORAGEPB_HPP
| 34.065831 | 80 | 0.648753 | [
"vector"
] |
29c91454a83d0e5167889a4b265569316fc3421d | 8,919 | cpp | C++ | lib/mayaUsd/commands/baseImportCommand.cpp | ika-rporter/maya-usd | 8f216a4fb955fc44c0abda55caa53ed295aaa625 | [
"Apache-2.0"
] | 507 | 2019-07-30T20:05:10.000Z | 2022-03-30T07:38:43.000Z | lib/mayaUsd/commands/baseImportCommand.cpp | ika-rporter/maya-usd | 8f216a4fb955fc44c0abda55caa53ed295aaa625 | [
"Apache-2.0"
] | 1,188 | 2019-07-31T11:27:27.000Z | 2022-03-31T21:06:06.000Z | lib/mayaUsd/commands/baseImportCommand.cpp | ika-rporter/maya-usd | 8f216a4fb955fc44c0abda55caa53ed295aaa625 | [
"Apache-2.0"
] | 165 | 2019-07-30T22:27:57.000Z | 2022-03-25T07:20:23.000Z | //
// Copyright 2016 Pixar
// Copyright 2020 Autodesk
//
// 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 "baseImportCommand.h"
#include <mayaUsd/fileio/jobs/jobArgs.h>
#include <mayaUsd/fileio/jobs/readJob.h>
#include <mayaUsd/utils/util.h>
#include <pxr/pxr.h>
#include <pxr/usd/ar/resolver.h>
#include <maya/MArgList.h>
#include <maya/MSelectionList.h>
#include <maya/MStatus.h>
#include <maya/MSyntax.h>
#include <utility>
PXR_NAMESPACE_USING_DIRECTIVE
namespace MAYAUSD_NS_DEF {
/* static */
MSyntax MayaUSDImportCommand::createSyntax()
{
MSyntax syntax;
// These flags correspond to entries in
// UsdMayaJobImportArgs::GetDefaultDictionary.
syntax.addFlag(
kShadingModeFlag,
UsdMayaJobImportArgsTokens->shadingMode.GetText(),
MSyntax::kString,
MSyntax::kString);
syntax.makeFlagMultiUse(kShadingModeFlag);
syntax.addFlag(
kPreferredMaterialFlag,
UsdMayaJobImportArgsTokens->preferredMaterial.GetText(),
MSyntax::kString);
syntax.addFlag(
kImportInstancesFlag,
UsdMayaJobImportArgsTokens->importInstances.GetText(),
MSyntax::kString);
syntax.addFlag(
kImportUSDZTexturesFlag,
UsdMayaJobImportArgsTokens->importUSDZTextures.GetText(),
MSyntax::kBoolean);
syntax.addFlag(
kImportUSDZTexturesFilePathFlag,
UsdMayaJobImportArgsTokens->importUSDZTexturesFilePath.GetText(),
MSyntax::kString);
syntax.addFlag(kMetadataFlag, UsdMayaJobImportArgsTokens->metadata.GetText(), MSyntax::kString);
syntax.makeFlagMultiUse(kMetadataFlag);
syntax.addFlag(
kApiSchemaFlag, UsdMayaJobImportArgsTokens->apiSchema.GetText(), MSyntax::kString);
syntax.makeFlagMultiUse(kApiSchemaFlag);
syntax.addFlag(
kExcludePrimvarFlag,
UsdMayaJobImportArgsTokens->excludePrimvar.GetText(),
MSyntax::kString);
syntax.makeFlagMultiUse(kExcludePrimvarFlag);
syntax.addFlag(
kUseAsAnimationCacheFlag,
UsdMayaJobImportArgsTokens->useAsAnimationCache.GetText(),
MSyntax::kBoolean);
// Import chasers
syntax.addFlag(
kImportChaserFlag, UsdMayaJobImportArgsTokens->chaser.GetText(), MSyntax::kString);
syntax.makeFlagMultiUse(UsdMayaJobImportArgsTokens->chaser.GetText());
syntax.addFlag(
kImportChaserArgsFlag,
UsdMayaJobImportArgsTokens->chaserArgs.GetText(),
MSyntax::kString,
MSyntax::kString,
MSyntax::kString);
syntax.makeFlagMultiUse(UsdMayaJobImportArgsTokens->chaserArgs.GetText());
// These are additional flags under our control.
syntax.addFlag(kFileFlag, kFileFlagLong, MSyntax::kString);
syntax.addFlag(kParentFlag, kParentFlagLong, MSyntax::kString);
syntax.addFlag(kReadAnimDataFlag, kReadAnimDataFlagLong, MSyntax::kBoolean);
syntax.addFlag(kFrameRangeFlag, kFrameRangeFlagLong, MSyntax::kDouble, MSyntax::kDouble);
syntax.addFlag(kPrimPathFlag, kPrimPathFlagLong, MSyntax::kString);
syntax.addFlag(kVariantFlag, kVariantFlagLong, MSyntax::kString, MSyntax::kString);
syntax.makeFlagMultiUse(kVariantFlag);
syntax.addFlag(kVerboseFlag, kVerboseFlagLong, MSyntax::kNoArg);
syntax.enableQuery(false);
syntax.enableEdit(false);
return syntax;
}
/* static */
void* MayaUSDImportCommand::creator() { return new MayaUSDImportCommand(); }
/* virtual */
std::unique_ptr<UsdMaya_ReadJob> MayaUSDImportCommand::initializeReadJob(
const MayaUsd::ImportData& data,
const UsdMayaJobImportArgs& args)
{
return std::unique_ptr<UsdMaya_ReadJob>(new UsdMaya_ReadJob(data, args));
}
/* virtual */
MStatus MayaUSDImportCommand::doIt(const MArgList& args)
{
MStatus status;
MArgDatabase argData(syntax(), args, &status);
// Check that all flags were valid
if (status != MS::kSuccess) {
return status;
}
// Get dictionary values.
const VtDictionary userArgs = UsdMayaUtil::GetDictionaryFromArgDatabase(
argData, UsdMayaJobImportArgs::GetDefaultDictionary());
std::string mFileName;
if (argData.isFlagSet(kFileFlag)) {
// Get the value
MString tmpVal;
argData.getFlagArgument(kFileFlag, 0, tmpVal);
mFileName = UsdMayaUtil::convert(tmpVal);
// Use the usd resolver for validation (but save the unresolved)
if (ArGetResolver().Resolve(mFileName).empty()
&& !SdfLayer::IsAnonymousLayerIdentifier(mFileName)) {
TF_RUNTIME_ERROR(
"File '%s' does not exist, or could not be resolved. "
"Exiting.",
mFileName.c_str());
return MS::kFailure;
}
TF_STATUS("Importing '%s'", mFileName.c_str());
}
if (mFileName.empty()) {
TF_RUNTIME_ERROR("Empty file specified. Exiting.");
return MS::kFailure;
}
std::string mPrimPath;
if (argData.isFlagSet(kPrimPathFlag)) {
// Get the value
MString tmpVal;
argData.getFlagArgument(kPrimPathFlag, 0, tmpVal);
mPrimPath = UsdMayaUtil::convert(tmpVal);
}
// Add variant (variantSet, variant). Multi-use
SdfVariantSelectionMap mVariants;
unsigned int nbFlags = argData.numberOfFlagUses(kVariantFlag);
for (unsigned int i = 0; i < nbFlags; ++i) {
MArgList tmpArgList;
status = argData.getFlagArgumentList(kVariantFlag, i, tmpArgList);
// Get the value
MString tmpKey = tmpArgList.asString(0, &status);
MString tmpVal = tmpArgList.asString(1, &status);
mVariants.emplace(tmpKey.asChar(), tmpVal.asChar());
}
bool readAnimData = false;
if (argData.isFlagSet(kReadAnimDataFlag)) {
argData.getFlagArgument(kReadAnimDataFlag, 0, readAnimData);
}
GfInterval timeInterval;
if (readAnimData) {
if (argData.isFlagSet(kFrameRangeFlag)) {
double startTime = 1.0;
double endTime = 1.0;
argData.getFlagArgument(kFrameRangeFlag, 0, startTime);
argData.getFlagArgument(kFrameRangeFlag, 1, endTime);
if (endTime < startTime) {
std::swap(startTime, endTime);
}
timeInterval = GfInterval(startTime, endTime);
} else {
timeInterval = GfInterval::GetFullInterval();
}
} else {
timeInterval = GfInterval();
}
UsdMayaJobImportArgs jobArgs = UsdMayaJobImportArgs::CreateFromDictionary(
userArgs,
/* importWithProxyShapes = */ false,
timeInterval);
MayaUsd::ImportData importData(mFileName);
importData.setRootVariantSelections(std::move(mVariants));
importData.setRootPrimPath(mPrimPath);
_readJob = initializeReadJob(importData, jobArgs);
// Add optional command params
if (argData.isFlagSet(kParentFlag)) {
// Get the value
MString tmpVal;
argData.getFlagArgument(kParentFlag, 0, tmpVal);
if (tmpVal.length()) {
MSelectionList selList;
selList.add(tmpVal);
MDagPath dagPath;
status = selList.getDagPath(0, dagPath);
if (status != MS::kSuccess) {
TF_RUNTIME_ERROR("Invalid path '%s' for -parent.", tmpVal.asChar());
return MS::kFailure;
}
_readJob->SetMayaRootDagPath(dagPath);
}
}
// Execute the command
std::vector<MDagPath> addedDagPaths;
bool success = _readJob->Read(&addedDagPaths);
if (success) {
TF_FOR_ALL(iter, addedDagPaths) { appendToResult(iter->fullPathName()); }
}
return (success) ? MS::kSuccess : MS::kFailure;
}
/* virtual */
MStatus MayaUSDImportCommand::redoIt()
{
if (!_readJob) {
return MS::kFailure;
}
bool success = _readJob->Redo();
return (success) ? MS::kSuccess : MS::kFailure;
}
/* virtual */
MStatus MayaUSDImportCommand::undoIt()
{
if (!_readJob) {
return MS::kFailure;
}
bool success = _readJob->Undo();
return (success) ? MS::kSuccess : MS::kFailure;
}
} // namespace MAYAUSD_NS_DEF
| 32.911439 | 101 | 0.650409 | [
"vector"
] |
29cdffa18839c4216e42934a9a1ccedd238d1050 | 9,445 | hpp | C++ | stapl_release/stapl/containers/partitions/splitter.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/containers/partitions/splitter.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/containers/partitions/splitter.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_CONTAINERS_SPLITTER_PARTITION_HPP
#define STAPL_CONTAINERS_SPLITTER_PARTITION_HPP
#include <vector>
#include <algorithm>
#include <stapl/domains/indexed.hpp>
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Partition a one-dimensional domain explicitly into subdomains
/// based on a fixed set of splitter GIDs.
///
/// If the original domain is [0..99] and the set of splitters
/// is {6, 25, 88}, then the resulting subdomains produced will be [0..5],
/// [6..24], [25..87], [88..99].
///
/// @tparam Dom Type of the domain to be partitioned
/// @tparam SplitterType Container that explicitly stores the splitters
//////////////////////////////////////////////////////////////////////
template<typename Dom,
typename SplitterType = std::vector<typename Dom::index_type> >
class splitter_partition
{
typedef SplitterType vec_dom_type;
public:
/// The original domain to partition
typedef Dom view_domain_type;
/// The domain of the partitioner itself (i.e., the domain [0, ..., p-1])
typedef indexed_domain<size_t> domain_type;
/// Type of the subdomains produced by the partition
typedef Dom value_type;
/// Type of the GIDs in the subdomains
typedef typename Dom::index_type gid_type;
/// Type used to describe the i'th subdomain
typedef size_t index_type;
/// Container of splitters
vec_dom_type m_part;
/// Original domain
view_domain_type m_domain;
/// Flag indicating whether or not empty subdomains are allowed
bool m_allow_empties;
//////////////////////////////////////////////////////////////////////
/// @brief Create a partition of a domain based on splitters.
///
/// The container of splitters must be nonempty and sorted. In addition,
/// if allow_empties is not set, there must be no duplicate splitters.
///
/// @param original_dom The original domain to partition.
/// @param vdom A vector of splitters
/// @param allow_empties Flag indicating whether empty domains is allowed.
/// Effectively, the same splitter may not appear twice if allow_empties
/// is false.
//////////////////////////////////////////////////////////////////////
splitter_partition(Dom const& original_dom, vec_dom_type const& vdom,
bool allow_empties = false)
: m_part(vdom), m_domain(original_dom), m_allow_empties(allow_empties)
{
stapl_assert(vdom.size(), "No splitters defined");
if (m_allow_empties)
{
stapl_assert(std::adjacent_find(vdom.begin(),vdom.end(),
std::greater<typename vec_dom_type::value_type>())==vdom.end(),
"Splitter is not sorted");
}
else
{
stapl_assert(std::adjacent_find(vdom.begin(),vdom.end(),
std::greater_equal<typename vec_dom_type::value_type>())==vdom.end(),
"Splitter is not sorted or has duplicates");
}
}
//////////////////////////////////////////////////////////////////////
/// @brief Return the subdomain at a given index. This is the inverse
/// of @ref find.
/// @param idx The index of the subdomain, which should be from 0 to
/// @ref size() - 1.
//////////////////////////////////////////////////////////////////////
value_type operator[](index_type idx) const
{
size_t tempsz=this->size();
stapl_assert(idx<tempsz,"Index out of bounds");
gid_type lower,upper;
if (idx == 0) //first partition
{
lower = m_domain.first();
if (lower == m_part[0])
{
if (m_allow_empties)
return value_type();
else
{
if (m_part.size() > 1)
upper = m_domain.advance(m_part[1], -1);
else
upper = m_domain.last();
}
}
else
upper = m_domain.advance(m_part[0], -1);
}
else if (idx == tempsz-1) //last partition
{
size_t vec_last_ix = m_part.size()-1;
upper = m_domain.last();
lower = m_part[vec_last_ix];
if (m_domain.advance(upper, 1) == lower)
{
if (m_allow_empties)
return value_type();
else
lower = m_part[vec_last_ix-1];
}
}
else //some middle partition
{
index_type temp = idx;
if (!m_allow_empties && m_part[0] == m_domain.first())
++temp;
lower = m_part[temp-1];
upper = m_part[temp];
if (lower == upper)
return value_type();
else
upper = m_domain.advance(m_part[temp], -1);
}
return value_type(lower, upper);
}
//////////////////////////////////////////////////////////////////////
/// @brief Return the number of partitions generated.
//////////////////////////////////////////////////////////////////////
size_t size() const
{
//an extra partition will occur before the first index
if (m_allow_empties)
return m_part.size()+1;
//but that partition and the last partition may be empty
size_t last_ix = m_part.size()-1;
return last_ix
+ (m_part[0] == m_domain.first() ? 0 : 1)
+ (m_part[last_ix] == m_domain.advance(m_domain.last(), 1) ? 0 : 1);
}
protected:
//////////////////////////////////////////////////////////////////////
/// @brief Returns the index of the partition that contains the gid @c g.
/// @param g gid to find
/// @param left Whether we should search left-to-right or right-to-left
/// in the partition list. If left is true, the index is with respect
/// to the first partition. Otherwise, the index is with respect to the
/// last partition, traversing backward.
/// @return The index of the subdomain that contains @c g
//////////////////////////////////////////////////////////////////////
index_type in_domain(gid_type const& g, bool left)
{
if (!m_domain.contains(g))
return index_bounds<index_type>::invalid();
size_t dist;
if (left) {
if (g == m_domain.first()) {
dist = 0;
}
else {
dist = std::distance(m_part.begin(),
std::lower_bound(m_part.begin(), m_part.end(), g));
if (dist < m_part.size() && g == m_part[dist])
++dist;
if (!m_allow_empties && m_part[0] == m_domain.first())
--dist;
}
}
else {
if (g == m_domain.last()) {
dist = this->size()-1;
}
else {
dist = std::distance(m_part.begin(),
std::upper_bound(m_part.begin(), m_part.end(), g));
if (!m_allow_empties && m_part[0] == m_domain.first())
--dist;
}
}
return dist;
}
public:
//////////////////////////////////////////////////////////////////////
/// @brief Get the partition's domain [0, .., p-1].
//////////////////////////////////////////////////////////////////////
domain_type domain() const
{
return domain_type(this->size());
}
//////////////////////////////////////////////////////////////////////
/// @brief Return the original domain that was used to create subdomains.
//////////////////////////////////////////////////////////////////////
value_type const& global_domain() const
{
return m_domain;
}
//////////////////////////////////////////////////////////////////////
/// @brief Returns the index of the partition that contains the gid @c g.
/// @param g gid to find
/// @return The index of the subdomain that contains @c g
//////////////////////////////////////////////////////////////////////
index_type find(gid_type const& g)
{
return in_domain(g,true);
}
//////////////////////////////////////////////////////////////////////
/// @copydoc explicit_partition::contained_in
//////////////////////////////////////////////////////////////////////
template <typename ODom, typename MFG>
std::vector<std::pair<domain_type,bool> >
contained_in(ODom const& dom, MFG x)
{
std::vector<std::pair<domain_type,bool> > doms;
index_type first = in_domain(dom.first(), true);
index_type last = in_domain(dom.last(), false);
value_type tmp_dom = this->operator[](last);
if (tmp_dom.last() == dom.last())
{
if (this->operator[](first).size()>0 &&
dom.first() != this->operator[](first).first())
++first;
if (first <= last) {
doms.push_back(std::make_pair(domain_type(first,last), true));
}
}
else
{ // the last partition is only partially contained
if (this->operator[](first).size()>0 && dom.first()
!= this->operator[](first).first())
++first;
if (first < last) {
doms.push_back(std::make_pair(domain_type(first,last-1), true));
}
if (first <= last) {
if (first == last && tmp_dom.contains(dom.first())&&
tmp_dom.contains(dom.last()))
return doms;
doms.push_back(std::make_pair(domain_type(last,last), false));
}
}
return doms;
}
};
} // stapl namespace
#endif /* STAPL_SPLITTER_PARTITION_HPP */
| 32.457045 | 77 | 0.531498 | [
"vector"
] |
29ce682858f0c616b40767e584c34b5b65f6c5a7 | 12,445 | cpp | C++ | src/IECoreScene/MeshPrimitiveShrinkWrapOp.cpp | ericmehl/cortex | 054839cc709ce153d1bcaaefe7f340ebe641ec82 | [
"BSD-3-Clause"
] | 386 | 2015-01-02T11:10:43.000Z | 2022-03-10T15:12:20.000Z | src/IECoreScene/MeshPrimitiveShrinkWrapOp.cpp | ericmehl/cortex | 054839cc709ce153d1bcaaefe7f340ebe641ec82 | [
"BSD-3-Clause"
] | 484 | 2015-01-09T18:28:06.000Z | 2022-03-31T16:02:04.000Z | src/IECoreScene/MeshPrimitiveShrinkWrapOp.cpp | ericmehl/cortex | 054839cc709ce153d1bcaaefe7f340ebe641ec82 | [
"BSD-3-Clause"
] | 99 | 2015-01-28T23:18:04.000Z | 2022-03-27T00:59:39.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreScene/MeshPrimitiveShrinkWrapOp.h"
#include "IECoreScene/MeshAlgo.h"
#include "IECoreScene/PrimitiveEvaluator.h"
#include "IECore/CompoundObject.h"
#include "IECore/CompoundParameter.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/ObjectParameter.h"
#include "IECore/RunTimeTyped.h"
#include "IECore/VectorOps.h"
#include "IECore/VectorTypedData.h"
#include "boost/format.hpp"
using namespace IECore;
using namespace IECoreScene;
using namespace Imath;
IE_CORE_DEFINERUNTIMETYPED( MeshPrimitiveShrinkWrapOp );
MeshPrimitiveShrinkWrapOp::MeshPrimitiveShrinkWrapOp() : MeshPrimitiveOp( "A MeshPrimitiveOp to shrink-wrap one mesh onto another" )
{
m_targetMeshParameter = new MeshPrimitiveParameter(
"target",
"The target mesh to shrink-wrap onto.",
new MeshPrimitive()
);
IntParameter::PresetsContainer directionPresets;
directionPresets.push_back( IntParameter::Preset( "Inside", Inside ) );
directionPresets.push_back( IntParameter::Preset( "Outside", Outside ) );
directionPresets.push_back( IntParameter::Preset( "Both", Both ) );
m_directionParameter = new IntParameter(
"direction",
"The direction by which rays are cast to find the target mesh.",
Both,
Inside,
Both,
directionPresets,
true
);
IntParameter::PresetsContainer methodPresets;
methodPresets.push_back( IntParameter::Preset( "Normal", Normal ) );
methodPresets.push_back( IntParameter::Preset( "X-axis", XAxis ) );
methodPresets.push_back( IntParameter::Preset( "Y-axis", YAxis ) );
methodPresets.push_back( IntParameter::Preset( "Z-axis", ZAxis ) );
methodPresets.push_back( IntParameter::Preset( "DirectionMesh", DirectionMesh ) );
m_methodParameter = new IntParameter(
"method",
"The method by which find the target mesh.",
Normal,
Normal,
DirectionMesh,
methodPresets,
true
);
m_directionMeshParameter = new MeshPrimitiveParameter(
"directionMesh",
"The direction mesh to use when determining where to cast rays",
new MeshPrimitive()
);
parameters()->addParameter( m_targetMeshParameter );
parameters()->addParameter( m_directionParameter );
parameters()->addParameter( m_methodParameter );
parameters()->addParameter( m_directionMeshParameter );
}
MeshPrimitiveShrinkWrapOp::~MeshPrimitiveShrinkWrapOp()
{
}
MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::targetMeshParameter()
{
return m_targetMeshParameter.get();
}
const MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::targetMeshParameter() const
{
return m_targetMeshParameter.get();
}
IntParameter * MeshPrimitiveShrinkWrapOp::methodParameter()
{
return m_methodParameter.get();
}
const IntParameter * MeshPrimitiveShrinkWrapOp::methodParameter() const
{
return m_methodParameter.get();
}
IntParameter * MeshPrimitiveShrinkWrapOp::directionParameter()
{
return m_directionParameter.get();
}
const IntParameter * MeshPrimitiveShrinkWrapOp::directionParameter() const
{
return m_directionParameter.get();
}
MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::directionMeshParameter()
{
return m_directionMeshParameter.get();
}
const MeshPrimitiveParameter * MeshPrimitiveShrinkWrapOp::directionMeshParameter() const
{
return m_directionMeshParameter.get();
}
struct MeshPrimitiveShrinkWrapOp::ShrinkWrapFn
{
typedef void ReturnType;
PrimitivePtr m_sourceMesh;
const Primitive * m_targetMesh;
const Data * m_directionData;
Direction m_direction;
Method m_method;
ShrinkWrapFn( Primitive * sourceMesh, const Primitive * targetMesh, const Data * directionData, Direction direction, Method method )
: m_sourceMesh( sourceMesh ), m_targetMesh( targetMesh ), m_directionData( directionData ), m_direction( direction ), m_method( method )
{
}
template<typename T>
void operator()( T * vertexData ) const
{
assert( vertexData );
typedef typename T::ValueType::value_type Vec;
assert( m_sourceMesh );
if ( ! m_targetMesh )
{
return;
}
typename T::ValueType &vertices = vertexData->writable();
const T *directionVerticesData = runTimeCast<const T , const Data >( m_directionData );
if ( m_method == DirectionMesh )
{
if ( !directionVerticesData )
{
throw InvalidArgumentException( (boost::format("MeshPrimitiveShrinkWrapOp: Direction mesh has no primitive variable \"P\" of type \"%s\" ") % T::staticTypeName() ).str() );
}
else if ( directionVerticesData->readable().size() != vertices.size() )
{
throw InvalidArgumentException("MeshPrimitiveShrinkWrapOp: Direction mesh has incorrect number of vertices" );
}
}
MeshPrimitivePtr triangulatedSourcePrimitive = MeshAlgo::triangulate( runTimeCast<MeshPrimitive>( m_sourceMesh.get() ) );
PrimitiveEvaluatorPtr sourceEvaluator = nullptr;
PrimitiveEvaluator::ResultPtr sourceResult = nullptr;
if ( m_method == Normal )
{
sourceEvaluator = PrimitiveEvaluator::create( triangulatedSourcePrimitive );
assert( sourceEvaluator );
sourceResult = sourceEvaluator->createResult();
assert( sourceResult );
}
PrimitiveEvaluatorPtr targetEvaluator = PrimitiveEvaluator::create( m_targetMesh );
assert( targetEvaluator );
PrimitiveEvaluator::ResultPtr insideResult = targetEvaluator->createResult();
PrimitiveEvaluator::ResultPtr outsideResult = targetEvaluator->createResult();
assert( insideResult );
assert( outsideResult );
PrimitiveVariableMap::const_iterator it = triangulatedSourcePrimitive->variables.find( "N" );
if (it == m_sourceMesh->variables.end())
{
throw InvalidArgumentException("MeshPrimitiveShrinkWrapOp: MeshPrimitive has no primitive variable \"N\"" );
}
const PrimitiveVariable &nPrimVar = it->second;
typename T::ValueType::size_type vertexId = 0;
for ( typename T::ValueType::iterator pit = vertices.begin(); pit != vertices.end(); ++pit, ++vertexId )
{
Vec &vertexPosition = *pit;
Vec rayDirection;
if ( m_method == Normal )
{
assert( sourceEvaluator );
assert( sourceResult );
sourceEvaluator->closestPoint( vertexPosition, sourceResult.get() );
rayDirection = sourceResult->vectorPrimVar( nPrimVar ).normalized();
}
else if ( m_method == XAxis )
{
rayDirection = Vec( 1.0, 0.0, 0.0 );
}
else if ( m_method == YAxis )
{
rayDirection = Vec( 0.0, 1.0, 0.0 );
}
else if ( m_method == ZAxis )
{
rayDirection = Vec( 0.0, 0.0, 1.0 );
}
else
{
assert( m_method == DirectionMesh );
assert( directionVerticesData );
assert( vertexId < directionVerticesData->readable().size() );
rayDirection = ( directionVerticesData->readable()[ vertexId ] - vertexPosition ).normalized();
}
bool hit = false;
if ( m_direction == Inside )
{
hit = targetEvaluator->intersectionPoint( vertexPosition, -rayDirection, insideResult.get() );
if ( hit )
{
vertexPosition = insideResult->point();
}
}
else if ( m_direction == Outside )
{
hit = targetEvaluator->intersectionPoint( vertexPosition, rayDirection, outsideResult.get() );
if ( hit )
{
vertexPosition = outsideResult->point();
}
}
else
{
assert( m_direction == Both );
bool insideHit = targetEvaluator->intersectionPoint( vertexPosition, -rayDirection, insideResult.get() );
bool outsideHit = targetEvaluator->intersectionPoint( vertexPosition, rayDirection, outsideResult.get() );
/// Choose the closest, or the only, intersection
if ( insideHit && outsideHit )
{
typename Vec::BaseType insideDist = vecDistance2( vertexPosition, Vec( insideResult->point() ) );
typename Vec::BaseType outsideDist = vecDistance2( vertexPosition, Vec( outsideResult->point() ) );
if ( insideDist < outsideDist )
{
vertexPosition = insideResult->point();
}
else
{
vertexPosition = outsideResult->point();
}
}
else if ( insideHit )
{
vertexPosition = insideResult->point();
}
else if ( outsideHit )
{
vertexPosition = outsideResult->point();
}
}
}
}
struct ErrorHandler
{
template<typename T, typename F>
void operator()( const T *data, const F& functor )
{
assert( data );
throw InvalidArgumentException( ( boost::format( "MeshPrimitiveShrinkWrapOp: Invalid data type \"%s\" for primitive variable \"P\"." ) % Object::typeNameFromTypeId( data->typeId() ) ).str() );
}
};
};
void MeshPrimitiveShrinkWrapOp::modifyTypedPrimitive( MeshPrimitive * mesh, const CompoundObject * operands )
{
assert( mesh );
assert( operands );
PrimitiveVariableMap::const_iterator it = mesh->variables.find("P");
if (it == mesh->variables.end())
{
throw InvalidArgumentException("MeshPrimitive has no primitive variable \"P\" in MeshPrimitiveShrinkWrapOp" );
}
const DataPtr verticesData = it->second.data;
if (! mesh->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Mesh with invalid primitive variables given to MeshPrimitiveShrinkWrapOp" );
}
MeshPrimitivePtr target = targetMeshParameter()->getTypedValue< MeshPrimitive >( );
if ( !target )
{
return;
}
if ( ! target->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Target mesh with invalid primitive variables given to MeshPrimitiveShrinkWrapOp" );
}
target = MeshAlgo::triangulate( target.get() );
assert( target );
Direction direction = static_cast<Direction>( m_directionParameter->getNumericValue() );
Method method = static_cast<Method>( m_methodParameter->getNumericValue() );
MeshPrimitivePtr directionMesh = nullptr;
ConstDataPtr directionVerticesData = nullptr;
if ( method == DirectionMesh )
{
directionMesh = directionMeshParameter()->getTypedValue< MeshPrimitive >( );
if ( ! directionMesh )
{
throw InvalidArgumentException( "No direction mesh given to MeshPrimitiveShrinkWrapOp" );
}
if ( ! directionMesh->arePrimitiveVariablesValid() )
{
throw InvalidArgumentException( "Direction mesh with invalid primitive variables given to MeshPrimitiveShrinkWrapOp" );
}
PrimitiveVariableMap::const_iterator it = directionMesh->variables.find("P");
if (it == directionMesh->variables.end())
{
throw InvalidArgumentException("Direction mesh has no primitive variable \"P\" in MeshPrimitiveShrinkWrapOp" );
}
directionVerticesData = it->second.data;
}
ShrinkWrapFn fn( mesh, target.get(), directionVerticesData.get(), direction, method );
despatchTypedData< ShrinkWrapFn, TypeTraits::IsFloatVec3VectorTypedData, ShrinkWrapFn::ErrorHandler >( verticesData.get(), fn );
}
| 32.157623 | 195 | 0.71354 | [
"mesh",
"object"
] |
29ce79bda6cfc8201ee72e6e99373e298adcc6e0 | 1,793 | cc | C++ | mindspore/lite/src/runtime/kernel/arm/fp16/layout_transform_fp16.cc | GuoSuiming/mindspore | 48afc4cfa53d970c0b20eedfb46e039db2a133d5 | [
"Apache-2.0"
] | 55 | 2020-12-17T10:26:06.000Z | 2022-03-28T07:18:26.000Z | mindspore/lite/src/runtime/kernel/arm/fp16/layout_transform_fp16.cc | forwhat461/mindspore | 59a277756eb4faad9ac9afcc7fd526e8277d4994 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/fp16/layout_transform_fp16.cc | forwhat461/mindspore | 59a277756eb4faad9ac9afcc7fd526e8277d4994 | [
"Apache-2.0"
] | 14 | 2021-01-29T02:39:47.000Z | 2022-03-23T05:00:26.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/runtime/kernel/arm/fp16/layout_transform_fp16.h"
#include "nnacl/fp16/pack_fp16.h"
#include "schema/ops_generated.h"
#include "src/common/log_adapter.h"
namespace mindspore::kernel {
LayoutConvertor LayoutTransformFp16(schema::Format src_format, schema::Format dst_format) {
if (src_format == schema::Format::Format_NHWC && dst_format == schema::Format::Format_NC4HW4) {
return PackNHWCToNC4HW4Fp16;
} else if (src_format == schema::Format::Format_NHWC && dst_format == schema::Format::Format_NHWC4) {
return PackNHWCToNHWC4Fp16;
} else if (src_format == schema::Format::Format_NC4HW4 && dst_format == schema::Format::Format_NHWC4) {
return PackNC4HW4ToNHWC4Fp16;
} else if (src_format == schema::Format::Format_NCHW && dst_format == schema::Format::Format_NC4HW4) {
return PackNCHWToNC4HW4Fp16;
} else if (src_format == schema::Format::Format_NC4HW4 && dst_format == schema::Format::Format_NHWC) {
return PackNC4HW4ToNHWCFp16;
} else {
MS_LOG(ERROR) << "Unsupported transform from " << EnumNameFormat(src_format) << " to "
<< EnumNameFormat(dst_format);
return nullptr;
}
}
} // namespace mindspore::kernel
| 44.825 | 105 | 0.730061 | [
"transform"
] |
29d0cc86e181bd9680404114ccc63363dd5bb896 | 4,023 | cpp | C++ | unit/unittest_color.cpp | ysak-y/apl-core-library | f0a99732c530fde9d9fac97c2d008c012594fc51 | [
"Apache-2.0"
] | null | null | null | unit/unittest_color.cpp | ysak-y/apl-core-library | f0a99732c530fde9d9fac97c2d008c012594fc51 | [
"Apache-2.0"
] | null | null | null | unit/unittest_color.cpp | ysak-y/apl-core-library | f0a99732c530fde9d9fac97c2d008c012594fc51 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "testeventloop.h"
#include "apl/common.h"
using namespace apl;
class ColorTest : public MemoryWrapper {};
TEST_F(ColorTest, Grammar)
{
ASSERT_EQ( 0xff0000ff, Color(session, "red") );
ASSERT_EQ( 0x008000ff, Color(session, "green") );
ASSERT_EQ( 0xeeddbbff, Color(session, "#edb"));
ASSERT_EQ( 0x11223344, Color(session, "#1234"));
ASSERT_EQ( 0x123456ff, Color(session, "#123456"));
ASSERT_EQ( 0xfedcba98, Color(session, "#fedcba98"));
ASSERT_EQ( 0x0000ff7f, Color(session, "rgba(blue, 50%)"));
ASSERT_EQ( 0x0080003f, Color(session, "rgb(rgba(green, 50%), 50%)"));
ASSERT_EQ( 0x8040c0ff, Color(session, "rgb(128, 64, 192)"));
ASSERT_EQ( 0xff072040, Color(session, "rgba(255, 7, 32, 25%)"));
ASSERT_EQ( 0xff072040, Color(session, "rgba(255, 7, 32, 0.25)"));
ASSERT_EQ( 0xff072040, Color(session, "rgba(255, 7, 32, .25)"));
ASSERT_EQ( 0xb8860bff, Color(session, "darkgoldenrod"));
}
TEST_F(ColorTest, HSL)
{
ASSERT_EQ( Color::RED, Color(session, "hsl(0, 100%, 50%)"));
ASSERT_EQ( 0xff8000ff, Color(session, "hsl(30, 100%, 50%)"));
ASSERT_EQ( 0xffff00ff, Color(session, "hsl(60, 100%, 50%)"));
ASSERT_EQ( 0x80ff00ff, Color(session, "hsl(90, 100%, 50%)"));
ASSERT_EQ( 0x00ff00ff, Color(session, "hsl(120, 100%, 50%)"));
ASSERT_EQ( 0x00FF80ff, Color(session, "hsl(150, 100%, 50%)"));
ASSERT_EQ( 0x00FFFFff, Color(session, "hsl(180, 100%, 50%)"));
ASSERT_EQ( 0x007fFFff, Color(session, "hsl(210, 100%, 50%)"));
ASSERT_EQ( 0x0000FFff, Color(session, "hsl(240, 100%, 50%)"));
ASSERT_EQ( 0x7f00FFff, Color(session, "hsl(270, 100%, 50%)"));
ASSERT_EQ( 0xFF00FFff, Color(session, "hsl(300, 100%, 50%)"));
ASSERT_EQ( 0xFF0080ff, Color(session, "hsl(330, 100%, 50%)"));
ASSERT_EQ( Color::RED, Color(session, "hsl(360, 100%, 50%)"));
ASSERT_EQ( 0x000000ff, Color(session, "hsl(120, 100%, 0%)"));
ASSERT_EQ( 0x006600ff, Color(session, "hsl(120, 100%, 20%)"));
ASSERT_EQ( 0x00cc00ff, Color(session, "hsl(120, 100%, 40%)"));
ASSERT_EQ( 0x33FF33ff, Color(session, "hsl(120, 100%, 60%)"));
ASSERT_EQ( 0x99FF99ff, Color(session, "hsl(120, 100%, 80%)"));
ASSERT_EQ( 0xFFFFFFff, Color(session, "hsl(120, 100%, 100%)"));
ASSERT_EQ( 0x00ff00ff, Color(session, "hsl(120, 100%, 50%)"));
ASSERT_EQ( 0x19E619ff, Color(session, "hsl(120, 80%, 50%)"));
ASSERT_EQ( 0x33CC33ff, Color(session, "hsl(120, 60%, 50%)"));
ASSERT_EQ( 0x4dB34dff, Color(session, "hsl(120, 40%, 50%)"));
ASSERT_EQ( 0x669966ff, Color(session, "hsl(120, 20%, 50%)"));
ASSERT_EQ( 0x808080ff, Color(session, "hsl(120, 0%, 50%)"));
ASSERT_EQ( 0x80808080, Color(session, "hsl(120, 0, 0.5, 0.5)"));
ASSERT_EQ( 0x80808040, Color(session, "hsla(120, 0, 50%, 25%)"));
}
TEST_F(ColorTest, Basic)
{
auto p = Color(session, "rgb(128, 64, 192, 0.125)");
ASSERT_EQ(128, p.red());
ASSERT_EQ(64, p.green());
ASSERT_EQ(192, p.blue());
ASSERT_EQ(32, p.alpha());
p = Color(session, "#12345678");
ASSERT_EQ(0x12, p.red());
ASSERT_EQ(0x34, p.green());
ASSERT_EQ(0x56, p.blue());
ASSERT_EQ(0x78, p.alpha());
}
const static std::vector<std::string> sErrorTests = {
"rgb(123 ",
"bluz",
"hsl(120, 0, 0, )"
};
TEST_F(ColorTest, Error)
{
for (auto& m : sErrorTests) {
ASSERT_EQ(Color::TRANSPARENT, Color(session, m)) << m;
ASSERT_TRUE(ConsoleMessage()) << m;
}
} | 38.314286 | 76 | 0.638081 | [
"vector"
] |
29d81c6df1f02670850a793fe67353508b7c5e54 | 3,671 | cpp | C++ | clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 409 | 2015-01-03T23:52:34.000Z | 2022-03-09T11:32:18.000Z | clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 410 | 2019-06-06T20:52:32.000Z | 2022-01-18T14:21:48.000Z | clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 374 | 2015-02-02T05:23:26.000Z | 2022-03-31T10:53:25.000Z | // RUN: %check_clang_tidy -std=c++14 %s modernize-return-braced-init-list %t
// FIXME: Fix the checker to work in C++17 mode.
namespace std {
typedef decltype(sizeof(int)) size_t;
// libc++'s implementation
template <class _E>
class initializer_list {
const _E *__begin_;
size_t __size_;
initializer_list(const _E *__b, size_t __s)
: __begin_(__b),
__size_(__s) {}
public:
typedef _E value_type;
typedef const _E &reference;
typedef const _E &const_reference;
typedef size_t size_type;
typedef const _E *iterator;
typedef const _E *const_iterator;
initializer_list() : __begin_(nullptr), __size_(0) {}
size_t size() const { return __size_; }
const _E *begin() const { return __begin_; }
const _E *end() const { return __begin_ + __size_; }
};
template <typename T>
class vector {
public:
vector(T) {}
vector(std::initializer_list<T>) {}
};
}
class Bar {};
Bar b0;
class Foo {
public:
Foo(Bar) {}
explicit Foo(Bar, unsigned int) {}
Foo(unsigned int) {}
};
class Baz {
public:
Foo m() {
Bar bm;
return Foo(bm);
// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: avoid repeating the return type from the declaration; use a braced initializer list instead [modernize-return-braced-init-list]
// CHECK-FIXES: return {bm};
}
};
class Quux : public Foo {
public:
Quux(Bar bar) : Foo(bar) {}
Quux(unsigned, unsigned, unsigned k = 0) : Foo(k) {}
};
Foo f() {
Bar b1;
return Foo(b1);
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
// CHECK-FIXES: return {b1};
}
Foo f2() {
Bar b2;
return {b2};
}
auto f3() {
Bar b3;
return Foo(b3);
}
#define A(b) Foo(b)
Foo f4() {
Bar b4;
return A(b4);
}
Foo f5() {
Bar b5;
return Quux(b5);
}
Foo f6() {
Bar b6;
return Foo(b6, 1);
}
std::vector<int> f7() {
int i7 = 1;
return std::vector<int>(i7);
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
}
Bar f8() {
return {};
}
Bar f9() {
return Bar();
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
}
Bar f10() {
return Bar{};
}
Foo f11(Bar b11) {
return Foo(b11);
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
// CHECK-FIXES: return {b11};
}
Foo f12() {
return f11(Bar());
}
Foo f13() {
return Foo(Bar()); // 13
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
// CHECK-FIXES: return {Bar()}; // 13
}
Foo f14() {
// FIXME: Type narrowing should not occur!
return Foo(-1);
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
// CHECK-FIXES: return {-1};
}
Foo f15() {
return Foo(f10());
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
// CHECK-FIXES: return {f10()};
}
Quux f16() {
return Quux(1, 2);
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
// CHECK-FIXES: return {1, 2};
}
Quux f17() {
return Quux(1, 2, 3);
// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: avoid repeating the return type
// CHECK-FIXES: return {1, 2, 3};
}
template <typename T>
T f19() {
return T();
}
Bar i1 = f19<Bar>();
Baz i2 = f19<Baz>();
template <typename T>
Foo f20(T t) {
return Foo(t);
}
Foo i3 = f20(b0);
template <typename T>
class BazT {
public:
T m() {
Bar b;
return T(b);
}
Foo m2(T t) {
return Foo(t);
}
};
BazT<Foo> bazFoo;
Foo i4 = bazFoo.m();
Foo i5 = bazFoo.m2(b0);
BazT<Quux> bazQuux;
Foo i6 = bazQuux.m();
Foo i7 = bazQuux.m2(b0);
auto v1 = []() { return std::vector<int>({1, 2}); }();
auto v2 = []() -> std::vector<int> { return std::vector<int>({1, 2}); }();
| 18.355 | 176 | 0.614546 | [
"vector"
] |
29df8b1255b299f50f863179f036eaf4ac295e76 | 134,821 | cpp | C++ | framework/generated/generated_vulkan_ascii_consumer.cpp | davidlunarg/gfxreconstruct | 8344c13ea0fcbd38e07b22065d5f5f6ff5999492 | [
"Apache-2.0"
] | null | null | null | framework/generated/generated_vulkan_ascii_consumer.cpp | davidlunarg/gfxreconstruct | 8344c13ea0fcbd38e07b22065d5f5f6ff5999492 | [
"Apache-2.0"
] | null | null | null | framework/generated/generated_vulkan_ascii_consumer.cpp | davidlunarg/gfxreconstruct | 8344c13ea0fcbd38e07b22065d5f5f6ff5999492 | [
"Apache-2.0"
] | null | null | null | /*
** Copyright (c) 2018-2019 Valve Corporation
** Copyright (c) 2018-2019 LunarG, Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*
** This file is generated from the Khronos Vulkan XML API Registry.
**
*/
#include "generated/generated_vulkan_ascii_consumer.h"
#include "util/defines.h"
#include "vulkan/vulkan.h"
GFXRECON_BEGIN_NAMESPACE(gfxrecon)
GFXRECON_BEGIN_NAMESPACE(decode)
void VulkanAsciiConsumer::Process_vkCreateInstance(
VkResult returnValue,
const StructPointerDecoder<Decoded_VkInstanceCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkInstance>& pInstance)
{
fprintf(GetFile(), "%s\n", "vkCreateInstance");
}
void VulkanAsciiConsumer::Process_vkDestroyInstance(
format::HandleId instance,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyInstance");
}
void VulkanAsciiConsumer::Process_vkEnumeratePhysicalDevices(
VkResult returnValue,
format::HandleId instance,
const PointerDecoder<uint32_t>& pPhysicalDeviceCount,
const HandlePointerDecoder<VkPhysicalDevice>& pPhysicalDevices)
{
fprintf(GetFile(), "%s\n", "vkEnumeratePhysicalDevices");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceFeatures(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceFeatures>& pFeatures)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceFeatures");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceFormatProperties(
format::HandleId physicalDevice,
VkFormat format,
const StructPointerDecoder<Decoded_VkFormatProperties>& pFormatProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceFormatProperties");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceImageFormatProperties(
VkResult returnValue,
format::HandleId physicalDevice,
VkFormat format,
VkImageType type,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
const StructPointerDecoder<Decoded_VkImageFormatProperties>& pImageFormatProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceImageFormatProperties");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceProperties(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceProperties>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceProperties");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceQueueFamilyProperties(
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pQueueFamilyPropertyCount,
const StructPointerDecoder<Decoded_VkQueueFamilyProperties>& pQueueFamilyProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceQueueFamilyProperties");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceMemoryProperties(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceMemoryProperties>& pMemoryProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceMemoryProperties");
}
void VulkanAsciiConsumer::Process_vkCreateDevice(
VkResult returnValue,
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkDeviceCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDevice>& pDevice)
{
fprintf(GetFile(), "%s\n", "vkCreateDevice");
}
void VulkanAsciiConsumer::Process_vkDestroyDevice(
format::HandleId device,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyDevice");
}
void VulkanAsciiConsumer::Process_vkGetDeviceQueue(
format::HandleId device,
uint32_t queueFamilyIndex,
uint32_t queueIndex,
const HandlePointerDecoder<VkQueue>& pQueue)
{
fprintf(GetFile(), "%s\n", "vkGetDeviceQueue");
}
void VulkanAsciiConsumer::Process_vkQueueSubmit(
VkResult returnValue,
format::HandleId queue,
uint32_t submitCount,
const StructPointerDecoder<Decoded_VkSubmitInfo>& pSubmits,
format::HandleId fence)
{
fprintf(GetFile(), "%s\n", "vkQueueSubmit");
}
void VulkanAsciiConsumer::Process_vkQueueWaitIdle(
VkResult returnValue,
format::HandleId queue)
{
fprintf(GetFile(), "%s\n", "vkQueueWaitIdle");
}
void VulkanAsciiConsumer::Process_vkDeviceWaitIdle(
VkResult returnValue,
format::HandleId device)
{
fprintf(GetFile(), "%s\n", "vkDeviceWaitIdle");
}
void VulkanAsciiConsumer::Process_vkAllocateMemory(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkMemoryAllocateInfo>& pAllocateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDeviceMemory>& pMemory)
{
fprintf(GetFile(), "%s\n", "vkAllocateMemory");
}
void VulkanAsciiConsumer::Process_vkFreeMemory(
format::HandleId device,
format::HandleId memory,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkFreeMemory");
}
void VulkanAsciiConsumer::Process_vkMapMemory(
VkResult returnValue,
format::HandleId device,
format::HandleId memory,
VkDeviceSize offset,
VkDeviceSize size,
VkMemoryMapFlags flags,
const PointerDecoder<uint64_t>& ppData)
{
fprintf(GetFile(), "%s\n", "vkMapMemory");
}
void VulkanAsciiConsumer::Process_vkUnmapMemory(
format::HandleId device,
format::HandleId memory)
{
fprintf(GetFile(), "%s\n", "vkUnmapMemory");
}
void VulkanAsciiConsumer::Process_vkFlushMappedMemoryRanges(
VkResult returnValue,
format::HandleId device,
uint32_t memoryRangeCount,
const StructPointerDecoder<Decoded_VkMappedMemoryRange>& pMemoryRanges)
{
fprintf(GetFile(), "%s\n", "vkFlushMappedMemoryRanges");
}
void VulkanAsciiConsumer::Process_vkInvalidateMappedMemoryRanges(
VkResult returnValue,
format::HandleId device,
uint32_t memoryRangeCount,
const StructPointerDecoder<Decoded_VkMappedMemoryRange>& pMemoryRanges)
{
fprintf(GetFile(), "%s\n", "vkInvalidateMappedMemoryRanges");
}
void VulkanAsciiConsumer::Process_vkGetDeviceMemoryCommitment(
format::HandleId device,
format::HandleId memory,
const PointerDecoder<VkDeviceSize>& pCommittedMemoryInBytes)
{
fprintf(GetFile(), "%s\n", "vkGetDeviceMemoryCommitment");
}
void VulkanAsciiConsumer::Process_vkBindBufferMemory(
VkResult returnValue,
format::HandleId device,
format::HandleId buffer,
format::HandleId memory,
VkDeviceSize memoryOffset)
{
fprintf(GetFile(), "%s\n", "vkBindBufferMemory");
}
void VulkanAsciiConsumer::Process_vkBindImageMemory(
VkResult returnValue,
format::HandleId device,
format::HandleId image,
format::HandleId memory,
VkDeviceSize memoryOffset)
{
fprintf(GetFile(), "%s\n", "vkBindImageMemory");
}
void VulkanAsciiConsumer::Process_vkGetBufferMemoryRequirements(
format::HandleId device,
format::HandleId buffer,
const StructPointerDecoder<Decoded_VkMemoryRequirements>& pMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetBufferMemoryRequirements");
}
void VulkanAsciiConsumer::Process_vkGetImageMemoryRequirements(
format::HandleId device,
format::HandleId image,
const StructPointerDecoder<Decoded_VkMemoryRequirements>& pMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetImageMemoryRequirements");
}
void VulkanAsciiConsumer::Process_vkGetImageSparseMemoryRequirements(
format::HandleId device,
format::HandleId image,
const PointerDecoder<uint32_t>& pSparseMemoryRequirementCount,
const StructPointerDecoder<Decoded_VkSparseImageMemoryRequirements>& pSparseMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetImageSparseMemoryRequirements");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSparseImageFormatProperties(
format::HandleId physicalDevice,
VkFormat format,
VkImageType type,
VkSampleCountFlagBits samples,
VkImageUsageFlags usage,
VkImageTiling tiling,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkSparseImageFormatProperties>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSparseImageFormatProperties");
}
void VulkanAsciiConsumer::Process_vkQueueBindSparse(
VkResult returnValue,
format::HandleId queue,
uint32_t bindInfoCount,
const StructPointerDecoder<Decoded_VkBindSparseInfo>& pBindInfo,
format::HandleId fence)
{
fprintf(GetFile(), "%s\n", "vkQueueBindSparse");
}
void VulkanAsciiConsumer::Process_vkCreateFence(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkFenceCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkFence>& pFence)
{
fprintf(GetFile(), "%s\n", "vkCreateFence");
}
void VulkanAsciiConsumer::Process_vkDestroyFence(
format::HandleId device,
format::HandleId fence,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyFence");
}
void VulkanAsciiConsumer::Process_vkResetFences(
VkResult returnValue,
format::HandleId device,
uint32_t fenceCount,
const HandlePointerDecoder<VkFence>& pFences)
{
fprintf(GetFile(), "%s\n", "vkResetFences");
}
void VulkanAsciiConsumer::Process_vkGetFenceStatus(
VkResult returnValue,
format::HandleId device,
format::HandleId fence)
{
fprintf(GetFile(), "%s\n", "vkGetFenceStatus");
}
void VulkanAsciiConsumer::Process_vkWaitForFences(
VkResult returnValue,
format::HandleId device,
uint32_t fenceCount,
const HandlePointerDecoder<VkFence>& pFences,
VkBool32 waitAll,
uint64_t timeout)
{
fprintf(GetFile(), "%s\n", "vkWaitForFences");
}
void VulkanAsciiConsumer::Process_vkCreateSemaphore(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkSemaphoreCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSemaphore>& pSemaphore)
{
fprintf(GetFile(), "%s\n", "vkCreateSemaphore");
}
void VulkanAsciiConsumer::Process_vkDestroySemaphore(
format::HandleId device,
format::HandleId semaphore,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroySemaphore");
}
void VulkanAsciiConsumer::Process_vkCreateEvent(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkEventCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkEvent>& pEvent)
{
fprintf(GetFile(), "%s\n", "vkCreateEvent");
}
void VulkanAsciiConsumer::Process_vkDestroyEvent(
format::HandleId device,
format::HandleId event,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyEvent");
}
void VulkanAsciiConsumer::Process_vkGetEventStatus(
VkResult returnValue,
format::HandleId device,
format::HandleId event)
{
fprintf(GetFile(), "%s\n", "vkGetEventStatus");
}
void VulkanAsciiConsumer::Process_vkSetEvent(
VkResult returnValue,
format::HandleId device,
format::HandleId event)
{
fprintf(GetFile(), "%s\n", "vkSetEvent");
}
void VulkanAsciiConsumer::Process_vkResetEvent(
VkResult returnValue,
format::HandleId device,
format::HandleId event)
{
fprintf(GetFile(), "%s\n", "vkResetEvent");
}
void VulkanAsciiConsumer::Process_vkCreateQueryPool(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkQueryPoolCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkQueryPool>& pQueryPool)
{
fprintf(GetFile(), "%s\n", "vkCreateQueryPool");
}
void VulkanAsciiConsumer::Process_vkDestroyQueryPool(
format::HandleId device,
format::HandleId queryPool,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyQueryPool");
}
void VulkanAsciiConsumer::Process_vkGetQueryPoolResults(
VkResult returnValue,
format::HandleId device,
format::HandleId queryPool,
uint32_t firstQuery,
uint32_t queryCount,
size_t dataSize,
const PointerDecoder<uint8_t>& pData,
VkDeviceSize stride,
VkQueryResultFlags flags)
{
fprintf(GetFile(), "%s\n", "vkGetQueryPoolResults");
}
void VulkanAsciiConsumer::Process_vkCreateBuffer(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkBufferCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkBuffer>& pBuffer)
{
fprintf(GetFile(), "%s\n", "vkCreateBuffer");
}
void VulkanAsciiConsumer::Process_vkDestroyBuffer(
format::HandleId device,
format::HandleId buffer,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyBuffer");
}
void VulkanAsciiConsumer::Process_vkCreateBufferView(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkBufferViewCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkBufferView>& pView)
{
fprintf(GetFile(), "%s\n", "vkCreateBufferView");
}
void VulkanAsciiConsumer::Process_vkDestroyBufferView(
format::HandleId device,
format::HandleId bufferView,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyBufferView");
}
void VulkanAsciiConsumer::Process_vkCreateImage(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkImageCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkImage>& pImage)
{
fprintf(GetFile(), "%s\n", "vkCreateImage");
}
void VulkanAsciiConsumer::Process_vkDestroyImage(
format::HandleId device,
format::HandleId image,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyImage");
}
void VulkanAsciiConsumer::Process_vkGetImageSubresourceLayout(
format::HandleId device,
format::HandleId image,
const StructPointerDecoder<Decoded_VkImageSubresource>& pSubresource,
const StructPointerDecoder<Decoded_VkSubresourceLayout>& pLayout)
{
fprintf(GetFile(), "%s\n", "vkGetImageSubresourceLayout");
}
void VulkanAsciiConsumer::Process_vkCreateImageView(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkImageViewCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkImageView>& pView)
{
fprintf(GetFile(), "%s\n", "vkCreateImageView");
}
void VulkanAsciiConsumer::Process_vkDestroyImageView(
format::HandleId device,
format::HandleId imageView,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyImageView");
}
void VulkanAsciiConsumer::Process_vkCreateShaderModule(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkShaderModuleCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkShaderModule>& pShaderModule)
{
fprintf(GetFile(), "%s\n", "vkCreateShaderModule");
}
void VulkanAsciiConsumer::Process_vkDestroyShaderModule(
format::HandleId device,
format::HandleId shaderModule,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyShaderModule");
}
void VulkanAsciiConsumer::Process_vkCreatePipelineCache(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkPipelineCacheCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkPipelineCache>& pPipelineCache)
{
fprintf(GetFile(), "%s\n", "vkCreatePipelineCache");
}
void VulkanAsciiConsumer::Process_vkDestroyPipelineCache(
format::HandleId device,
format::HandleId pipelineCache,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyPipelineCache");
}
void VulkanAsciiConsumer::Process_vkGetPipelineCacheData(
VkResult returnValue,
format::HandleId device,
format::HandleId pipelineCache,
const PointerDecoder<size_t>& pDataSize,
const PointerDecoder<uint8_t>& pData)
{
fprintf(GetFile(), "%s\n", "vkGetPipelineCacheData");
}
void VulkanAsciiConsumer::Process_vkMergePipelineCaches(
VkResult returnValue,
format::HandleId device,
format::HandleId dstCache,
uint32_t srcCacheCount,
const HandlePointerDecoder<VkPipelineCache>& pSrcCaches)
{
fprintf(GetFile(), "%s\n", "vkMergePipelineCaches");
}
void VulkanAsciiConsumer::Process_vkCreateGraphicsPipelines(
VkResult returnValue,
format::HandleId device,
format::HandleId pipelineCache,
uint32_t createInfoCount,
const StructPointerDecoder<Decoded_VkGraphicsPipelineCreateInfo>& pCreateInfos,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkPipeline>& pPipelines)
{
fprintf(GetFile(), "%s\n", "vkCreateGraphicsPipelines");
}
void VulkanAsciiConsumer::Process_vkCreateComputePipelines(
VkResult returnValue,
format::HandleId device,
format::HandleId pipelineCache,
uint32_t createInfoCount,
const StructPointerDecoder<Decoded_VkComputePipelineCreateInfo>& pCreateInfos,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkPipeline>& pPipelines)
{
fprintf(GetFile(), "%s\n", "vkCreateComputePipelines");
}
void VulkanAsciiConsumer::Process_vkDestroyPipeline(
format::HandleId device,
format::HandleId pipeline,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyPipeline");
}
void VulkanAsciiConsumer::Process_vkCreatePipelineLayout(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkPipelineLayoutCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkPipelineLayout>& pPipelineLayout)
{
fprintf(GetFile(), "%s\n", "vkCreatePipelineLayout");
}
void VulkanAsciiConsumer::Process_vkDestroyPipelineLayout(
format::HandleId device,
format::HandleId pipelineLayout,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyPipelineLayout");
}
void VulkanAsciiConsumer::Process_vkCreateSampler(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkSamplerCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSampler>& pSampler)
{
fprintf(GetFile(), "%s\n", "vkCreateSampler");
}
void VulkanAsciiConsumer::Process_vkDestroySampler(
format::HandleId device,
format::HandleId sampler,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroySampler");
}
void VulkanAsciiConsumer::Process_vkCreateDescriptorSetLayout(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDescriptorSetLayoutCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDescriptorSetLayout>& pSetLayout)
{
fprintf(GetFile(), "%s\n", "vkCreateDescriptorSetLayout");
}
void VulkanAsciiConsumer::Process_vkDestroyDescriptorSetLayout(
format::HandleId device,
format::HandleId descriptorSetLayout,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyDescriptorSetLayout");
}
void VulkanAsciiConsumer::Process_vkCreateDescriptorPool(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDescriptorPoolCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDescriptorPool>& pDescriptorPool)
{
fprintf(GetFile(), "%s\n", "vkCreateDescriptorPool");
}
void VulkanAsciiConsumer::Process_vkDestroyDescriptorPool(
format::HandleId device,
format::HandleId descriptorPool,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyDescriptorPool");
}
void VulkanAsciiConsumer::Process_vkResetDescriptorPool(
VkResult returnValue,
format::HandleId device,
format::HandleId descriptorPool,
VkDescriptorPoolResetFlags flags)
{
fprintf(GetFile(), "%s\n", "vkResetDescriptorPool");
}
void VulkanAsciiConsumer::Process_vkAllocateDescriptorSets(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDescriptorSetAllocateInfo>& pAllocateInfo,
const HandlePointerDecoder<VkDescriptorSet>& pDescriptorSets)
{
fprintf(GetFile(), "%s\n", "vkAllocateDescriptorSets");
}
void VulkanAsciiConsumer::Process_vkFreeDescriptorSets(
VkResult returnValue,
format::HandleId device,
format::HandleId descriptorPool,
uint32_t descriptorSetCount,
const HandlePointerDecoder<VkDescriptorSet>& pDescriptorSets)
{
fprintf(GetFile(), "%s\n", "vkFreeDescriptorSets");
}
void VulkanAsciiConsumer::Process_vkUpdateDescriptorSets(
format::HandleId device,
uint32_t descriptorWriteCount,
const StructPointerDecoder<Decoded_VkWriteDescriptorSet>& pDescriptorWrites,
uint32_t descriptorCopyCount,
const StructPointerDecoder<Decoded_VkCopyDescriptorSet>& pDescriptorCopies)
{
fprintf(GetFile(), "%s\n", "vkUpdateDescriptorSets");
}
void VulkanAsciiConsumer::Process_vkCreateFramebuffer(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkFramebufferCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkFramebuffer>& pFramebuffer)
{
fprintf(GetFile(), "%s\n", "vkCreateFramebuffer");
}
void VulkanAsciiConsumer::Process_vkDestroyFramebuffer(
format::HandleId device,
format::HandleId framebuffer,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyFramebuffer");
}
void VulkanAsciiConsumer::Process_vkCreateRenderPass(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkRenderPassCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkRenderPass>& pRenderPass)
{
fprintf(GetFile(), "%s\n", "vkCreateRenderPass");
}
void VulkanAsciiConsumer::Process_vkDestroyRenderPass(
format::HandleId device,
format::HandleId renderPass,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyRenderPass");
}
void VulkanAsciiConsumer::Process_vkGetRenderAreaGranularity(
format::HandleId device,
format::HandleId renderPass,
const StructPointerDecoder<Decoded_VkExtent2D>& pGranularity)
{
fprintf(GetFile(), "%s\n", "vkGetRenderAreaGranularity");
}
void VulkanAsciiConsumer::Process_vkCreateCommandPool(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkCommandPoolCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkCommandPool>& pCommandPool)
{
fprintf(GetFile(), "%s\n", "vkCreateCommandPool");
}
void VulkanAsciiConsumer::Process_vkDestroyCommandPool(
format::HandleId device,
format::HandleId commandPool,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyCommandPool");
}
void VulkanAsciiConsumer::Process_vkResetCommandPool(
VkResult returnValue,
format::HandleId device,
format::HandleId commandPool,
VkCommandPoolResetFlags flags)
{
fprintf(GetFile(), "%s\n", "vkResetCommandPool");
}
void VulkanAsciiConsumer::Process_vkAllocateCommandBuffers(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkCommandBufferAllocateInfo>& pAllocateInfo,
const HandlePointerDecoder<VkCommandBuffer>& pCommandBuffers)
{
fprintf(GetFile(), "%s\n", "vkAllocateCommandBuffers");
}
void VulkanAsciiConsumer::Process_vkFreeCommandBuffers(
format::HandleId device,
format::HandleId commandPool,
uint32_t commandBufferCount,
const HandlePointerDecoder<VkCommandBuffer>& pCommandBuffers)
{
fprintf(GetFile(), "%s\n", "vkFreeCommandBuffers");
}
void VulkanAsciiConsumer::Process_vkBeginCommandBuffer(
VkResult returnValue,
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkCommandBufferBeginInfo>& pBeginInfo)
{
fprintf(GetFile(), "%s\n", "vkBeginCommandBuffer");
}
void VulkanAsciiConsumer::Process_vkEndCommandBuffer(
VkResult returnValue,
format::HandleId commandBuffer)
{
fprintf(GetFile(), "%s\n", "vkEndCommandBuffer");
}
void VulkanAsciiConsumer::Process_vkResetCommandBuffer(
VkResult returnValue,
format::HandleId commandBuffer,
VkCommandBufferResetFlags flags)
{
fprintf(GetFile(), "%s\n", "vkResetCommandBuffer");
}
void VulkanAsciiConsumer::Process_vkCmdBindPipeline(
format::HandleId commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
format::HandleId pipeline)
{
fprintf(GetFile(), "%s\n", "vkCmdBindPipeline");
}
void VulkanAsciiConsumer::Process_vkCmdSetViewport(
format::HandleId commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const StructPointerDecoder<Decoded_VkViewport>& pViewports)
{
fprintf(GetFile(), "%s\n", "vkCmdSetViewport");
}
void VulkanAsciiConsumer::Process_vkCmdSetScissor(
format::HandleId commandBuffer,
uint32_t firstScissor,
uint32_t scissorCount,
const StructPointerDecoder<Decoded_VkRect2D>& pScissors)
{
fprintf(GetFile(), "%s\n", "vkCmdSetScissor");
}
void VulkanAsciiConsumer::Process_vkCmdSetLineWidth(
format::HandleId commandBuffer,
float lineWidth)
{
fprintf(GetFile(), "%s\n", "vkCmdSetLineWidth");
}
void VulkanAsciiConsumer::Process_vkCmdSetDepthBias(
format::HandleId commandBuffer,
float depthBiasConstantFactor,
float depthBiasClamp,
float depthBiasSlopeFactor)
{
fprintf(GetFile(), "%s\n", "vkCmdSetDepthBias");
}
void VulkanAsciiConsumer::Process_vkCmdSetBlendConstants(
format::HandleId commandBuffer,
const PointerDecoder<float>& blendConstants)
{
fprintf(GetFile(), "%s\n", "vkCmdSetBlendConstants");
}
void VulkanAsciiConsumer::Process_vkCmdSetDepthBounds(
format::HandleId commandBuffer,
float minDepthBounds,
float maxDepthBounds)
{
fprintf(GetFile(), "%s\n", "vkCmdSetDepthBounds");
}
void VulkanAsciiConsumer::Process_vkCmdSetStencilCompareMask(
format::HandleId commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t compareMask)
{
fprintf(GetFile(), "%s\n", "vkCmdSetStencilCompareMask");
}
void VulkanAsciiConsumer::Process_vkCmdSetStencilWriteMask(
format::HandleId commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t writeMask)
{
fprintf(GetFile(), "%s\n", "vkCmdSetStencilWriteMask");
}
void VulkanAsciiConsumer::Process_vkCmdSetStencilReference(
format::HandleId commandBuffer,
VkStencilFaceFlags faceMask,
uint32_t reference)
{
fprintf(GetFile(), "%s\n", "vkCmdSetStencilReference");
}
void VulkanAsciiConsumer::Process_vkCmdBindDescriptorSets(
format::HandleId commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
format::HandleId layout,
uint32_t firstSet,
uint32_t descriptorSetCount,
const HandlePointerDecoder<VkDescriptorSet>& pDescriptorSets,
uint32_t dynamicOffsetCount,
const PointerDecoder<uint32_t>& pDynamicOffsets)
{
fprintf(GetFile(), "%s\n", "vkCmdBindDescriptorSets");
}
void VulkanAsciiConsumer::Process_vkCmdBindIndexBuffer(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
VkIndexType indexType)
{
fprintf(GetFile(), "%s\n", "vkCmdBindIndexBuffer");
}
void VulkanAsciiConsumer::Process_vkCmdBindVertexBuffers(
format::HandleId commandBuffer,
uint32_t firstBinding,
uint32_t bindingCount,
const HandlePointerDecoder<VkBuffer>& pBuffers,
const PointerDecoder<VkDeviceSize>& pOffsets)
{
fprintf(GetFile(), "%s\n", "vkCmdBindVertexBuffers");
}
void VulkanAsciiConsumer::Process_vkCmdDraw(
format::HandleId commandBuffer,
uint32_t vertexCount,
uint32_t instanceCount,
uint32_t firstVertex,
uint32_t firstInstance)
{
fprintf(GetFile(), "%s\n", "vkCmdDraw");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndexed(
format::HandleId commandBuffer,
uint32_t indexCount,
uint32_t instanceCount,
uint32_t firstIndex,
int32_t vertexOffset,
uint32_t firstInstance)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndexed");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndirect(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndirect");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndexedIndirect(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndexedIndirect");
}
void VulkanAsciiConsumer::Process_vkCmdDispatch(
format::HandleId commandBuffer,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ)
{
fprintf(GetFile(), "%s\n", "vkCmdDispatch");
}
void VulkanAsciiConsumer::Process_vkCmdDispatchIndirect(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset)
{
fprintf(GetFile(), "%s\n", "vkCmdDispatchIndirect");
}
void VulkanAsciiConsumer::Process_vkCmdCopyBuffer(
format::HandleId commandBuffer,
format::HandleId srcBuffer,
format::HandleId dstBuffer,
uint32_t regionCount,
const StructPointerDecoder<Decoded_VkBufferCopy>& pRegions)
{
fprintf(GetFile(), "%s\n", "vkCmdCopyBuffer");
}
void VulkanAsciiConsumer::Process_vkCmdCopyImage(
format::HandleId commandBuffer,
format::HandleId srcImage,
VkImageLayout srcImageLayout,
format::HandleId dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const StructPointerDecoder<Decoded_VkImageCopy>& pRegions)
{
fprintf(GetFile(), "%s\n", "vkCmdCopyImage");
}
void VulkanAsciiConsumer::Process_vkCmdBlitImage(
format::HandleId commandBuffer,
format::HandleId srcImage,
VkImageLayout srcImageLayout,
format::HandleId dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const StructPointerDecoder<Decoded_VkImageBlit>& pRegions,
VkFilter filter)
{
fprintf(GetFile(), "%s\n", "vkCmdBlitImage");
}
void VulkanAsciiConsumer::Process_vkCmdCopyBufferToImage(
format::HandleId commandBuffer,
format::HandleId srcBuffer,
format::HandleId dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const StructPointerDecoder<Decoded_VkBufferImageCopy>& pRegions)
{
fprintf(GetFile(), "%s\n", "vkCmdCopyBufferToImage");
}
void VulkanAsciiConsumer::Process_vkCmdCopyImageToBuffer(
format::HandleId commandBuffer,
format::HandleId srcImage,
VkImageLayout srcImageLayout,
format::HandleId dstBuffer,
uint32_t regionCount,
const StructPointerDecoder<Decoded_VkBufferImageCopy>& pRegions)
{
fprintf(GetFile(), "%s\n", "vkCmdCopyImageToBuffer");
}
void VulkanAsciiConsumer::Process_vkCmdUpdateBuffer(
format::HandleId commandBuffer,
format::HandleId dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize dataSize,
const PointerDecoder<uint8_t>& pData)
{
fprintf(GetFile(), "%s\n", "vkCmdUpdateBuffer");
}
void VulkanAsciiConsumer::Process_vkCmdFillBuffer(
format::HandleId commandBuffer,
format::HandleId dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize size,
uint32_t data)
{
fprintf(GetFile(), "%s\n", "vkCmdFillBuffer");
}
void VulkanAsciiConsumer::Process_vkCmdClearColorImage(
format::HandleId commandBuffer,
format::HandleId image,
VkImageLayout imageLayout,
const StructPointerDecoder<Decoded_VkClearColorValue>& pColor,
uint32_t rangeCount,
const StructPointerDecoder<Decoded_VkImageSubresourceRange>& pRanges)
{
fprintf(GetFile(), "%s\n", "vkCmdClearColorImage");
}
void VulkanAsciiConsumer::Process_vkCmdClearDepthStencilImage(
format::HandleId commandBuffer,
format::HandleId image,
VkImageLayout imageLayout,
const StructPointerDecoder<Decoded_VkClearDepthStencilValue>& pDepthStencil,
uint32_t rangeCount,
const StructPointerDecoder<Decoded_VkImageSubresourceRange>& pRanges)
{
fprintf(GetFile(), "%s\n", "vkCmdClearDepthStencilImage");
}
void VulkanAsciiConsumer::Process_vkCmdClearAttachments(
format::HandleId commandBuffer,
uint32_t attachmentCount,
const StructPointerDecoder<Decoded_VkClearAttachment>& pAttachments,
uint32_t rectCount,
const StructPointerDecoder<Decoded_VkClearRect>& pRects)
{
fprintf(GetFile(), "%s\n", "vkCmdClearAttachments");
}
void VulkanAsciiConsumer::Process_vkCmdResolveImage(
format::HandleId commandBuffer,
format::HandleId srcImage,
VkImageLayout srcImageLayout,
format::HandleId dstImage,
VkImageLayout dstImageLayout,
uint32_t regionCount,
const StructPointerDecoder<Decoded_VkImageResolve>& pRegions)
{
fprintf(GetFile(), "%s\n", "vkCmdResolveImage");
}
void VulkanAsciiConsumer::Process_vkCmdSetEvent(
format::HandleId commandBuffer,
format::HandleId event,
VkPipelineStageFlags stageMask)
{
fprintf(GetFile(), "%s\n", "vkCmdSetEvent");
}
void VulkanAsciiConsumer::Process_vkCmdResetEvent(
format::HandleId commandBuffer,
format::HandleId event,
VkPipelineStageFlags stageMask)
{
fprintf(GetFile(), "%s\n", "vkCmdResetEvent");
}
void VulkanAsciiConsumer::Process_vkCmdWaitEvents(
format::HandleId commandBuffer,
uint32_t eventCount,
const HandlePointerDecoder<VkEvent>& pEvents,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
uint32_t memoryBarrierCount,
const StructPointerDecoder<Decoded_VkMemoryBarrier>& pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const StructPointerDecoder<Decoded_VkBufferMemoryBarrier>& pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const StructPointerDecoder<Decoded_VkImageMemoryBarrier>& pImageMemoryBarriers)
{
fprintf(GetFile(), "%s\n", "vkCmdWaitEvents");
}
void VulkanAsciiConsumer::Process_vkCmdPipelineBarrier(
format::HandleId commandBuffer,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
VkDependencyFlags dependencyFlags,
uint32_t memoryBarrierCount,
const StructPointerDecoder<Decoded_VkMemoryBarrier>& pMemoryBarriers,
uint32_t bufferMemoryBarrierCount,
const StructPointerDecoder<Decoded_VkBufferMemoryBarrier>& pBufferMemoryBarriers,
uint32_t imageMemoryBarrierCount,
const StructPointerDecoder<Decoded_VkImageMemoryBarrier>& pImageMemoryBarriers)
{
fprintf(GetFile(), "%s\n", "vkCmdPipelineBarrier");
}
void VulkanAsciiConsumer::Process_vkCmdBeginQuery(
format::HandleId commandBuffer,
format::HandleId queryPool,
uint32_t query,
VkQueryControlFlags flags)
{
fprintf(GetFile(), "%s\n", "vkCmdBeginQuery");
}
void VulkanAsciiConsumer::Process_vkCmdEndQuery(
format::HandleId commandBuffer,
format::HandleId queryPool,
uint32_t query)
{
fprintf(GetFile(), "%s\n", "vkCmdEndQuery");
}
void VulkanAsciiConsumer::Process_vkCmdResetQueryPool(
format::HandleId commandBuffer,
format::HandleId queryPool,
uint32_t firstQuery,
uint32_t queryCount)
{
fprintf(GetFile(), "%s\n", "vkCmdResetQueryPool");
}
void VulkanAsciiConsumer::Process_vkCmdWriteTimestamp(
format::HandleId commandBuffer,
VkPipelineStageFlagBits pipelineStage,
format::HandleId queryPool,
uint32_t query)
{
fprintf(GetFile(), "%s\n", "vkCmdWriteTimestamp");
}
void VulkanAsciiConsumer::Process_vkCmdCopyQueryPoolResults(
format::HandleId commandBuffer,
format::HandleId queryPool,
uint32_t firstQuery,
uint32_t queryCount,
format::HandleId dstBuffer,
VkDeviceSize dstOffset,
VkDeviceSize stride,
VkQueryResultFlags flags)
{
fprintf(GetFile(), "%s\n", "vkCmdCopyQueryPoolResults");
}
void VulkanAsciiConsumer::Process_vkCmdPushConstants(
format::HandleId commandBuffer,
format::HandleId layout,
VkShaderStageFlags stageFlags,
uint32_t offset,
uint32_t size,
const PointerDecoder<uint8_t>& pValues)
{
fprintf(GetFile(), "%s\n", "vkCmdPushConstants");
}
void VulkanAsciiConsumer::Process_vkCmdBeginRenderPass(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkRenderPassBeginInfo>& pRenderPassBegin,
VkSubpassContents contents)
{
fprintf(GetFile(), "%s\n", "vkCmdBeginRenderPass");
}
void VulkanAsciiConsumer::Process_vkCmdNextSubpass(
format::HandleId commandBuffer,
VkSubpassContents contents)
{
fprintf(GetFile(), "%s\n", "vkCmdNextSubpass");
}
void VulkanAsciiConsumer::Process_vkCmdEndRenderPass(
format::HandleId commandBuffer)
{
fprintf(GetFile(), "%s\n", "vkCmdEndRenderPass");
}
void VulkanAsciiConsumer::Process_vkCmdExecuteCommands(
format::HandleId commandBuffer,
uint32_t commandBufferCount,
const HandlePointerDecoder<VkCommandBuffer>& pCommandBuffers)
{
fprintf(GetFile(), "%s\n", "vkCmdExecuteCommands");
}
void VulkanAsciiConsumer::Process_vkBindBufferMemory2(
VkResult returnValue,
format::HandleId device,
uint32_t bindInfoCount,
const StructPointerDecoder<Decoded_VkBindBufferMemoryInfo>& pBindInfos)
{
fprintf(GetFile(), "%s\n", "vkBindBufferMemory2");
}
void VulkanAsciiConsumer::Process_vkBindImageMemory2(
VkResult returnValue,
format::HandleId device,
uint32_t bindInfoCount,
const StructPointerDecoder<Decoded_VkBindImageMemoryInfo>& pBindInfos)
{
fprintf(GetFile(), "%s\n", "vkBindImageMemory2");
}
void VulkanAsciiConsumer::Process_vkGetDeviceGroupPeerMemoryFeatures(
format::HandleId device,
uint32_t heapIndex,
uint32_t localDeviceIndex,
uint32_t remoteDeviceIndex,
const PointerDecoder<VkPeerMemoryFeatureFlags>& pPeerMemoryFeatures)
{
fprintf(GetFile(), "%s\n", "vkGetDeviceGroupPeerMemoryFeatures");
}
void VulkanAsciiConsumer::Process_vkCmdSetDeviceMask(
format::HandleId commandBuffer,
uint32_t deviceMask)
{
fprintf(GetFile(), "%s\n", "vkCmdSetDeviceMask");
}
void VulkanAsciiConsumer::Process_vkCmdDispatchBase(
format::HandleId commandBuffer,
uint32_t baseGroupX,
uint32_t baseGroupY,
uint32_t baseGroupZ,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ)
{
fprintf(GetFile(), "%s\n", "vkCmdDispatchBase");
}
void VulkanAsciiConsumer::Process_vkEnumeratePhysicalDeviceGroups(
VkResult returnValue,
format::HandleId instance,
const PointerDecoder<uint32_t>& pPhysicalDeviceGroupCount,
const StructPointerDecoder<Decoded_VkPhysicalDeviceGroupProperties>& pPhysicalDeviceGroupProperties)
{
fprintf(GetFile(), "%s\n", "vkEnumeratePhysicalDeviceGroups");
}
void VulkanAsciiConsumer::Process_vkGetImageMemoryRequirements2(
format::HandleId device,
const StructPointerDecoder<Decoded_VkImageMemoryRequirementsInfo2>& pInfo,
const StructPointerDecoder<Decoded_VkMemoryRequirements2>& pMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetImageMemoryRequirements2");
}
void VulkanAsciiConsumer::Process_vkGetBufferMemoryRequirements2(
format::HandleId device,
const StructPointerDecoder<Decoded_VkBufferMemoryRequirementsInfo2>& pInfo,
const StructPointerDecoder<Decoded_VkMemoryRequirements2>& pMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetBufferMemoryRequirements2");
}
void VulkanAsciiConsumer::Process_vkGetImageSparseMemoryRequirements2(
format::HandleId device,
const StructPointerDecoder<Decoded_VkImageSparseMemoryRequirementsInfo2>& pInfo,
const PointerDecoder<uint32_t>& pSparseMemoryRequirementCount,
const StructPointerDecoder<Decoded_VkSparseImageMemoryRequirements2>& pSparseMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetImageSparseMemoryRequirements2");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceFeatures2(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceFeatures2>& pFeatures)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceFeatures2");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceProperties2(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceProperties2>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceProperties2");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceFormatProperties2(
format::HandleId physicalDevice,
VkFormat format,
const StructPointerDecoder<Decoded_VkFormatProperties2>& pFormatProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceFormatProperties2");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceImageFormatProperties2(
VkResult returnValue,
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceImageFormatInfo2>& pImageFormatInfo,
const StructPointerDecoder<Decoded_VkImageFormatProperties2>& pImageFormatProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceImageFormatProperties2");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceQueueFamilyProperties2(
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pQueueFamilyPropertyCount,
const StructPointerDecoder<Decoded_VkQueueFamilyProperties2>& pQueueFamilyProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceQueueFamilyProperties2");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceMemoryProperties2(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceMemoryProperties2>& pMemoryProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceMemoryProperties2");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSparseImageFormatProperties2(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceSparseImageFormatInfo2>& pFormatInfo,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkSparseImageFormatProperties2>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSparseImageFormatProperties2");
}
void VulkanAsciiConsumer::Process_vkTrimCommandPool(
format::HandleId device,
format::HandleId commandPool,
VkCommandPoolTrimFlags flags)
{
fprintf(GetFile(), "%s\n", "vkTrimCommandPool");
}
void VulkanAsciiConsumer::Process_vkGetDeviceQueue2(
format::HandleId device,
const StructPointerDecoder<Decoded_VkDeviceQueueInfo2>& pQueueInfo,
const HandlePointerDecoder<VkQueue>& pQueue)
{
fprintf(GetFile(), "%s\n", "vkGetDeviceQueue2");
}
void VulkanAsciiConsumer::Process_vkCreateSamplerYcbcrConversion(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkSamplerYcbcrConversionCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSamplerYcbcrConversion>& pYcbcrConversion)
{
fprintf(GetFile(), "%s\n", "vkCreateSamplerYcbcrConversion");
}
void VulkanAsciiConsumer::Process_vkDestroySamplerYcbcrConversion(
format::HandleId device,
format::HandleId ycbcrConversion,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroySamplerYcbcrConversion");
}
void VulkanAsciiConsumer::Process_vkCreateDescriptorUpdateTemplate(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDescriptorUpdateTemplateCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDescriptorUpdateTemplate>& pDescriptorUpdateTemplate)
{
fprintf(GetFile(), "%s\n", "vkCreateDescriptorUpdateTemplate");
}
void VulkanAsciiConsumer::Process_vkDestroyDescriptorUpdateTemplate(
format::HandleId device,
format::HandleId descriptorUpdateTemplate,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyDescriptorUpdateTemplate");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceExternalBufferProperties(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceExternalBufferInfo>& pExternalBufferInfo,
const StructPointerDecoder<Decoded_VkExternalBufferProperties>& pExternalBufferProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceExternalBufferProperties");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceExternalFenceProperties(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceExternalFenceInfo>& pExternalFenceInfo,
const StructPointerDecoder<Decoded_VkExternalFenceProperties>& pExternalFenceProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceExternalFenceProperties");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceExternalSemaphoreProperties(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceExternalSemaphoreInfo>& pExternalSemaphoreInfo,
const StructPointerDecoder<Decoded_VkExternalSemaphoreProperties>& pExternalSemaphoreProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceExternalSemaphoreProperties");
}
void VulkanAsciiConsumer::Process_vkGetDescriptorSetLayoutSupport(
format::HandleId device,
const StructPointerDecoder<Decoded_VkDescriptorSetLayoutCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkDescriptorSetLayoutSupport>& pSupport)
{
fprintf(GetFile(), "%s\n", "vkGetDescriptorSetLayoutSupport");
}
void VulkanAsciiConsumer::Process_vkDestroySurfaceKHR(
format::HandleId instance,
format::HandleId surface,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroySurfaceKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSurfaceSupportKHR(
VkResult returnValue,
format::HandleId physicalDevice,
uint32_t queueFamilyIndex,
format::HandleId surface,
const PointerDecoder<VkBool32>& pSupported)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSurfaceSupportKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId surface,
const StructPointerDecoder<Decoded_VkSurfaceCapabilitiesKHR>& pSurfaceCapabilities)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSurfaceFormatsKHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId surface,
const PointerDecoder<uint32_t>& pSurfaceFormatCount,
const StructPointerDecoder<Decoded_VkSurfaceFormatKHR>& pSurfaceFormats)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSurfaceFormatsKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSurfacePresentModesKHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId surface,
const PointerDecoder<uint32_t>& pPresentModeCount,
const PointerDecoder<VkPresentModeKHR>& pPresentModes)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSurfacePresentModesKHR");
}
void VulkanAsciiConsumer::Process_vkCreateSwapchainKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkSwapchainCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSwapchainKHR>& pSwapchain)
{
fprintf(GetFile(), "%s\n", "vkCreateSwapchainKHR");
}
void VulkanAsciiConsumer::Process_vkDestroySwapchainKHR(
format::HandleId device,
format::HandleId swapchain,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroySwapchainKHR");
}
void VulkanAsciiConsumer::Process_vkGetSwapchainImagesKHR(
VkResult returnValue,
format::HandleId device,
format::HandleId swapchain,
const PointerDecoder<uint32_t>& pSwapchainImageCount,
const HandlePointerDecoder<VkImage>& pSwapchainImages)
{
fprintf(GetFile(), "%s\n", "vkGetSwapchainImagesKHR");
}
void VulkanAsciiConsumer::Process_vkAcquireNextImageKHR(
VkResult returnValue,
format::HandleId device,
format::HandleId swapchain,
uint64_t timeout,
format::HandleId semaphore,
format::HandleId fence,
const PointerDecoder<uint32_t>& pImageIndex)
{
fprintf(GetFile(), "%s\n", "vkAcquireNextImageKHR");
}
void VulkanAsciiConsumer::Process_vkQueuePresentKHR(
VkResult returnValue,
format::HandleId queue,
const StructPointerDecoder<Decoded_VkPresentInfoKHR>& pPresentInfo)
{
fprintf(GetFile(), "%s\n", "vkQueuePresentKHR");
}
void VulkanAsciiConsumer::Process_vkGetDeviceGroupPresentCapabilitiesKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDeviceGroupPresentCapabilitiesKHR>& pDeviceGroupPresentCapabilities)
{
fprintf(GetFile(), "%s\n", "vkGetDeviceGroupPresentCapabilitiesKHR");
}
void VulkanAsciiConsumer::Process_vkGetDeviceGroupSurfacePresentModesKHR(
VkResult returnValue,
format::HandleId device,
format::HandleId surface,
const PointerDecoder<VkDeviceGroupPresentModeFlagsKHR>& pModes)
{
fprintf(GetFile(), "%s\n", "vkGetDeviceGroupSurfacePresentModesKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDevicePresentRectanglesKHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId surface,
const PointerDecoder<uint32_t>& pRectCount,
const StructPointerDecoder<Decoded_VkRect2D>& pRects)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDevicePresentRectanglesKHR");
}
void VulkanAsciiConsumer::Process_vkAcquireNextImage2KHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkAcquireNextImageInfoKHR>& pAcquireInfo,
const PointerDecoder<uint32_t>& pImageIndex)
{
fprintf(GetFile(), "%s\n", "vkAcquireNextImage2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceDisplayPropertiesKHR(
VkResult returnValue,
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkDisplayPropertiesKHR>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceDisplayPropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceDisplayPlanePropertiesKHR(
VkResult returnValue,
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkDisplayPlanePropertiesKHR>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceDisplayPlanePropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkGetDisplayPlaneSupportedDisplaysKHR(
VkResult returnValue,
format::HandleId physicalDevice,
uint32_t planeIndex,
const PointerDecoder<uint32_t>& pDisplayCount,
const HandlePointerDecoder<VkDisplayKHR>& pDisplays)
{
fprintf(GetFile(), "%s\n", "vkGetDisplayPlaneSupportedDisplaysKHR");
}
void VulkanAsciiConsumer::Process_vkGetDisplayModePropertiesKHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId display,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkDisplayModePropertiesKHR>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetDisplayModePropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkCreateDisplayModeKHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId display,
const StructPointerDecoder<Decoded_VkDisplayModeCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDisplayModeKHR>& pMode)
{
fprintf(GetFile(), "%s\n", "vkCreateDisplayModeKHR");
}
void VulkanAsciiConsumer::Process_vkGetDisplayPlaneCapabilitiesKHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId mode,
uint32_t planeIndex,
const StructPointerDecoder<Decoded_VkDisplayPlaneCapabilitiesKHR>& pCapabilities)
{
fprintf(GetFile(), "%s\n", "vkGetDisplayPlaneCapabilitiesKHR");
}
void VulkanAsciiConsumer::Process_vkCreateDisplayPlaneSurfaceKHR(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkDisplaySurfaceCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateDisplayPlaneSurfaceKHR");
}
void VulkanAsciiConsumer::Process_vkCreateSharedSwapchainsKHR(
VkResult returnValue,
format::HandleId device,
uint32_t swapchainCount,
const StructPointerDecoder<Decoded_VkSwapchainCreateInfoKHR>& pCreateInfos,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSwapchainKHR>& pSwapchains)
{
fprintf(GetFile(), "%s\n", "vkCreateSharedSwapchainsKHR");
}
void VulkanAsciiConsumer::Process_vkCreateXlibSurfaceKHR(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkXlibSurfaceCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateXlibSurfaceKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceXlibPresentationSupportKHR(
VkBool32 returnValue,
format::HandleId physicalDevice,
uint32_t queueFamilyIndex,
uint64_t dpy,
size_t visualID)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceXlibPresentationSupportKHR");
}
void VulkanAsciiConsumer::Process_vkCreateXcbSurfaceKHR(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkXcbSurfaceCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateXcbSurfaceKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceXcbPresentationSupportKHR(
VkBool32 returnValue,
format::HandleId physicalDevice,
uint32_t queueFamilyIndex,
uint64_t connection,
uint32_t visual_id)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceXcbPresentationSupportKHR");
}
void VulkanAsciiConsumer::Process_vkCreateWaylandSurfaceKHR(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkWaylandSurfaceCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateWaylandSurfaceKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceWaylandPresentationSupportKHR(
VkBool32 returnValue,
format::HandleId physicalDevice,
uint32_t queueFamilyIndex,
uint64_t display)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceWaylandPresentationSupportKHR");
}
void VulkanAsciiConsumer::Process_vkCreateAndroidSurfaceKHR(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkAndroidSurfaceCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateAndroidSurfaceKHR");
}
void VulkanAsciiConsumer::Process_vkCreateWin32SurfaceKHR(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkWin32SurfaceCreateInfoKHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateWin32SurfaceKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceWin32PresentationSupportKHR(
VkBool32 returnValue,
format::HandleId physicalDevice,
uint32_t queueFamilyIndex)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceWin32PresentationSupportKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceFeatures2KHR(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceFeatures2>& pFeatures)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceFeatures2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceProperties2KHR(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceProperties2>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceFormatProperties2KHR(
format::HandleId physicalDevice,
VkFormat format,
const StructPointerDecoder<Decoded_VkFormatProperties2>& pFormatProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceFormatProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceImageFormatProperties2KHR(
VkResult returnValue,
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceImageFormatInfo2>& pImageFormatInfo,
const StructPointerDecoder<Decoded_VkImageFormatProperties2>& pImageFormatProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceImageFormatProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceQueueFamilyProperties2KHR(
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pQueueFamilyPropertyCount,
const StructPointerDecoder<Decoded_VkQueueFamilyProperties2>& pQueueFamilyProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceQueueFamilyProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceMemoryProperties2KHR(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceMemoryProperties2>& pMemoryProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceMemoryProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSparseImageFormatProperties2KHR(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceSparseImageFormatInfo2>& pFormatInfo,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkSparseImageFormatProperties2>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSparseImageFormatProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetDeviceGroupPeerMemoryFeaturesKHR(
format::HandleId device,
uint32_t heapIndex,
uint32_t localDeviceIndex,
uint32_t remoteDeviceIndex,
const PointerDecoder<VkPeerMemoryFeatureFlags>& pPeerMemoryFeatures)
{
fprintf(GetFile(), "%s\n", "vkGetDeviceGroupPeerMemoryFeaturesKHR");
}
void VulkanAsciiConsumer::Process_vkCmdSetDeviceMaskKHR(
format::HandleId commandBuffer,
uint32_t deviceMask)
{
fprintf(GetFile(), "%s\n", "vkCmdSetDeviceMaskKHR");
}
void VulkanAsciiConsumer::Process_vkCmdDispatchBaseKHR(
format::HandleId commandBuffer,
uint32_t baseGroupX,
uint32_t baseGroupY,
uint32_t baseGroupZ,
uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ)
{
fprintf(GetFile(), "%s\n", "vkCmdDispatchBaseKHR");
}
void VulkanAsciiConsumer::Process_vkTrimCommandPoolKHR(
format::HandleId device,
format::HandleId commandPool,
VkCommandPoolTrimFlags flags)
{
fprintf(GetFile(), "%s\n", "vkTrimCommandPoolKHR");
}
void VulkanAsciiConsumer::Process_vkEnumeratePhysicalDeviceGroupsKHR(
VkResult returnValue,
format::HandleId instance,
const PointerDecoder<uint32_t>& pPhysicalDeviceGroupCount,
const StructPointerDecoder<Decoded_VkPhysicalDeviceGroupProperties>& pPhysicalDeviceGroupProperties)
{
fprintf(GetFile(), "%s\n", "vkEnumeratePhysicalDeviceGroupsKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceExternalBufferPropertiesKHR(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceExternalBufferInfo>& pExternalBufferInfo,
const StructPointerDecoder<Decoded_VkExternalBufferProperties>& pExternalBufferProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceExternalBufferPropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkGetMemoryWin32HandleKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkMemoryGetWin32HandleInfoKHR>& pGetWin32HandleInfo,
const PointerDecoder<uint64_t>& pHandle)
{
fprintf(GetFile(), "%s\n", "vkGetMemoryWin32HandleKHR");
}
void VulkanAsciiConsumer::Process_vkGetMemoryWin32HandlePropertiesKHR(
VkResult returnValue,
format::HandleId device,
VkExternalMemoryHandleTypeFlagBits handleType,
uint64_t handle,
const StructPointerDecoder<Decoded_VkMemoryWin32HandlePropertiesKHR>& pMemoryWin32HandleProperties)
{
fprintf(GetFile(), "%s\n", "vkGetMemoryWin32HandlePropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkGetMemoryFdKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkMemoryGetFdInfoKHR>& pGetFdInfo,
const PointerDecoder<int>& pFd)
{
fprintf(GetFile(), "%s\n", "vkGetMemoryFdKHR");
}
void VulkanAsciiConsumer::Process_vkGetMemoryFdPropertiesKHR(
VkResult returnValue,
format::HandleId device,
VkExternalMemoryHandleTypeFlagBits handleType,
int fd,
const StructPointerDecoder<Decoded_VkMemoryFdPropertiesKHR>& pMemoryFdProperties)
{
fprintf(GetFile(), "%s\n", "vkGetMemoryFdPropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceExternalSemaphoreInfo>& pExternalSemaphoreInfo,
const StructPointerDecoder<Decoded_VkExternalSemaphoreProperties>& pExternalSemaphoreProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkImportSemaphoreWin32HandleKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkImportSemaphoreWin32HandleInfoKHR>& pImportSemaphoreWin32HandleInfo)
{
fprintf(GetFile(), "%s\n", "vkImportSemaphoreWin32HandleKHR");
}
void VulkanAsciiConsumer::Process_vkGetSemaphoreWin32HandleKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkSemaphoreGetWin32HandleInfoKHR>& pGetWin32HandleInfo,
const PointerDecoder<uint64_t>& pHandle)
{
fprintf(GetFile(), "%s\n", "vkGetSemaphoreWin32HandleKHR");
}
void VulkanAsciiConsumer::Process_vkImportSemaphoreFdKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkImportSemaphoreFdInfoKHR>& pImportSemaphoreFdInfo)
{
fprintf(GetFile(), "%s\n", "vkImportSemaphoreFdKHR");
}
void VulkanAsciiConsumer::Process_vkGetSemaphoreFdKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkSemaphoreGetFdInfoKHR>& pGetFdInfo,
const PointerDecoder<int>& pFd)
{
fprintf(GetFile(), "%s\n", "vkGetSemaphoreFdKHR");
}
void VulkanAsciiConsumer::Process_vkCmdPushDescriptorSetKHR(
format::HandleId commandBuffer,
VkPipelineBindPoint pipelineBindPoint,
format::HandleId layout,
uint32_t set,
uint32_t descriptorWriteCount,
const StructPointerDecoder<Decoded_VkWriteDescriptorSet>& pDescriptorWrites)
{
fprintf(GetFile(), "%s\n", "vkCmdPushDescriptorSetKHR");
}
void VulkanAsciiConsumer::Process_vkCreateDescriptorUpdateTemplateKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDescriptorUpdateTemplateCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDescriptorUpdateTemplate>& pDescriptorUpdateTemplate)
{
fprintf(GetFile(), "%s\n", "vkCreateDescriptorUpdateTemplateKHR");
}
void VulkanAsciiConsumer::Process_vkDestroyDescriptorUpdateTemplateKHR(
format::HandleId device,
format::HandleId descriptorUpdateTemplate,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyDescriptorUpdateTemplateKHR");
}
void VulkanAsciiConsumer::Process_vkCreateRenderPass2KHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkRenderPassCreateInfo2KHR>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkRenderPass>& pRenderPass)
{
fprintf(GetFile(), "%s\n", "vkCreateRenderPass2KHR");
}
void VulkanAsciiConsumer::Process_vkCmdBeginRenderPass2KHR(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkRenderPassBeginInfo>& pRenderPassBegin,
const StructPointerDecoder<Decoded_VkSubpassBeginInfoKHR>& pSubpassBeginInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdBeginRenderPass2KHR");
}
void VulkanAsciiConsumer::Process_vkCmdNextSubpass2KHR(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkSubpassBeginInfoKHR>& pSubpassBeginInfo,
const StructPointerDecoder<Decoded_VkSubpassEndInfoKHR>& pSubpassEndInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdNextSubpass2KHR");
}
void VulkanAsciiConsumer::Process_vkCmdEndRenderPass2KHR(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkSubpassEndInfoKHR>& pSubpassEndInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdEndRenderPass2KHR");
}
void VulkanAsciiConsumer::Process_vkGetSwapchainStatusKHR(
VkResult returnValue,
format::HandleId device,
format::HandleId swapchain)
{
fprintf(GetFile(), "%s\n", "vkGetSwapchainStatusKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceExternalFencePropertiesKHR(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceExternalFenceInfo>& pExternalFenceInfo,
const StructPointerDecoder<Decoded_VkExternalFenceProperties>& pExternalFenceProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceExternalFencePropertiesKHR");
}
void VulkanAsciiConsumer::Process_vkImportFenceWin32HandleKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkImportFenceWin32HandleInfoKHR>& pImportFenceWin32HandleInfo)
{
fprintf(GetFile(), "%s\n", "vkImportFenceWin32HandleKHR");
}
void VulkanAsciiConsumer::Process_vkGetFenceWin32HandleKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkFenceGetWin32HandleInfoKHR>& pGetWin32HandleInfo,
const PointerDecoder<uint64_t>& pHandle)
{
fprintf(GetFile(), "%s\n", "vkGetFenceWin32HandleKHR");
}
void VulkanAsciiConsumer::Process_vkImportFenceFdKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkImportFenceFdInfoKHR>& pImportFenceFdInfo)
{
fprintf(GetFile(), "%s\n", "vkImportFenceFdKHR");
}
void VulkanAsciiConsumer::Process_vkGetFenceFdKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkFenceGetFdInfoKHR>& pGetFdInfo,
const PointerDecoder<int>& pFd)
{
fprintf(GetFile(), "%s\n", "vkGetFenceFdKHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSurfaceCapabilities2KHR(
VkResult returnValue,
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceSurfaceInfo2KHR>& pSurfaceInfo,
const StructPointerDecoder<Decoded_VkSurfaceCapabilities2KHR>& pSurfaceCapabilities)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSurfaceCapabilities2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSurfaceFormats2KHR(
VkResult returnValue,
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkPhysicalDeviceSurfaceInfo2KHR>& pSurfaceInfo,
const PointerDecoder<uint32_t>& pSurfaceFormatCount,
const StructPointerDecoder<Decoded_VkSurfaceFormat2KHR>& pSurfaceFormats)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSurfaceFormats2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceDisplayProperties2KHR(
VkResult returnValue,
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkDisplayProperties2KHR>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceDisplayProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceDisplayPlaneProperties2KHR(
VkResult returnValue,
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkDisplayPlaneProperties2KHR>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceDisplayPlaneProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetDisplayModeProperties2KHR(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId display,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkDisplayModeProperties2KHR>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetDisplayModeProperties2KHR");
}
void VulkanAsciiConsumer::Process_vkGetDisplayPlaneCapabilities2KHR(
VkResult returnValue,
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkDisplayPlaneInfo2KHR>& pDisplayPlaneInfo,
const StructPointerDecoder<Decoded_VkDisplayPlaneCapabilities2KHR>& pCapabilities)
{
fprintf(GetFile(), "%s\n", "vkGetDisplayPlaneCapabilities2KHR");
}
void VulkanAsciiConsumer::Process_vkGetImageMemoryRequirements2KHR(
format::HandleId device,
const StructPointerDecoder<Decoded_VkImageMemoryRequirementsInfo2>& pInfo,
const StructPointerDecoder<Decoded_VkMemoryRequirements2>& pMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetImageMemoryRequirements2KHR");
}
void VulkanAsciiConsumer::Process_vkGetBufferMemoryRequirements2KHR(
format::HandleId device,
const StructPointerDecoder<Decoded_VkBufferMemoryRequirementsInfo2>& pInfo,
const StructPointerDecoder<Decoded_VkMemoryRequirements2>& pMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetBufferMemoryRequirements2KHR");
}
void VulkanAsciiConsumer::Process_vkGetImageSparseMemoryRequirements2KHR(
format::HandleId device,
const StructPointerDecoder<Decoded_VkImageSparseMemoryRequirementsInfo2>& pInfo,
const PointerDecoder<uint32_t>& pSparseMemoryRequirementCount,
const StructPointerDecoder<Decoded_VkSparseImageMemoryRequirements2>& pSparseMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetImageSparseMemoryRequirements2KHR");
}
void VulkanAsciiConsumer::Process_vkCreateSamplerYcbcrConversionKHR(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkSamplerYcbcrConversionCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSamplerYcbcrConversion>& pYcbcrConversion)
{
fprintf(GetFile(), "%s\n", "vkCreateSamplerYcbcrConversionKHR");
}
void VulkanAsciiConsumer::Process_vkDestroySamplerYcbcrConversionKHR(
format::HandleId device,
format::HandleId ycbcrConversion,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroySamplerYcbcrConversionKHR");
}
void VulkanAsciiConsumer::Process_vkBindBufferMemory2KHR(
VkResult returnValue,
format::HandleId device,
uint32_t bindInfoCount,
const StructPointerDecoder<Decoded_VkBindBufferMemoryInfo>& pBindInfos)
{
fprintf(GetFile(), "%s\n", "vkBindBufferMemory2KHR");
}
void VulkanAsciiConsumer::Process_vkBindImageMemory2KHR(
VkResult returnValue,
format::HandleId device,
uint32_t bindInfoCount,
const StructPointerDecoder<Decoded_VkBindImageMemoryInfo>& pBindInfos)
{
fprintf(GetFile(), "%s\n", "vkBindImageMemory2KHR");
}
void VulkanAsciiConsumer::Process_vkGetDescriptorSetLayoutSupportKHR(
format::HandleId device,
const StructPointerDecoder<Decoded_VkDescriptorSetLayoutCreateInfo>& pCreateInfo,
const StructPointerDecoder<Decoded_VkDescriptorSetLayoutSupport>& pSupport)
{
fprintf(GetFile(), "%s\n", "vkGetDescriptorSetLayoutSupportKHR");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndirectCountKHR(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
format::HandleId countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndirectCountKHR");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndexedIndirectCountKHR(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
format::HandleId countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndexedIndirectCountKHR");
}
void VulkanAsciiConsumer::Process_vkCreateDebugReportCallbackEXT(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkDebugReportCallbackCreateInfoEXT>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDebugReportCallbackEXT>& pCallback)
{
fprintf(GetFile(), "%s\n", "vkCreateDebugReportCallbackEXT");
}
void VulkanAsciiConsumer::Process_vkDestroyDebugReportCallbackEXT(
format::HandleId instance,
format::HandleId callback,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyDebugReportCallbackEXT");
}
void VulkanAsciiConsumer::Process_vkDebugReportMessageEXT(
format::HandleId instance,
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType,
uint64_t object,
size_t location,
int32_t messageCode,
const StringDecoder& pLayerPrefix,
const StringDecoder& pMessage)
{
fprintf(GetFile(), "%s\n", "vkDebugReportMessageEXT");
}
void VulkanAsciiConsumer::Process_vkDebugMarkerSetObjectTagEXT(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDebugMarkerObjectTagInfoEXT>& pTagInfo)
{
fprintf(GetFile(), "%s\n", "vkDebugMarkerSetObjectTagEXT");
}
void VulkanAsciiConsumer::Process_vkDebugMarkerSetObjectNameEXT(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDebugMarkerObjectNameInfoEXT>& pNameInfo)
{
fprintf(GetFile(), "%s\n", "vkDebugMarkerSetObjectNameEXT");
}
void VulkanAsciiConsumer::Process_vkCmdDebugMarkerBeginEXT(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkDebugMarkerMarkerInfoEXT>& pMarkerInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdDebugMarkerBeginEXT");
}
void VulkanAsciiConsumer::Process_vkCmdDebugMarkerEndEXT(
format::HandleId commandBuffer)
{
fprintf(GetFile(), "%s\n", "vkCmdDebugMarkerEndEXT");
}
void VulkanAsciiConsumer::Process_vkCmdDebugMarkerInsertEXT(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkDebugMarkerMarkerInfoEXT>& pMarkerInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdDebugMarkerInsertEXT");
}
void VulkanAsciiConsumer::Process_vkCmdBindTransformFeedbackBuffersEXT(
format::HandleId commandBuffer,
uint32_t firstBinding,
uint32_t bindingCount,
const HandlePointerDecoder<VkBuffer>& pBuffers,
const PointerDecoder<VkDeviceSize>& pOffsets,
const PointerDecoder<VkDeviceSize>& pSizes)
{
fprintf(GetFile(), "%s\n", "vkCmdBindTransformFeedbackBuffersEXT");
}
void VulkanAsciiConsumer::Process_vkCmdBeginTransformFeedbackEXT(
format::HandleId commandBuffer,
uint32_t firstCounterBuffer,
uint32_t counterBufferCount,
const HandlePointerDecoder<VkBuffer>& pCounterBuffers,
const PointerDecoder<VkDeviceSize>& pCounterBufferOffsets)
{
fprintf(GetFile(), "%s\n", "vkCmdBeginTransformFeedbackEXT");
}
void VulkanAsciiConsumer::Process_vkCmdEndTransformFeedbackEXT(
format::HandleId commandBuffer,
uint32_t firstCounterBuffer,
uint32_t counterBufferCount,
const HandlePointerDecoder<VkBuffer>& pCounterBuffers,
const PointerDecoder<VkDeviceSize>& pCounterBufferOffsets)
{
fprintf(GetFile(), "%s\n", "vkCmdEndTransformFeedbackEXT");
}
void VulkanAsciiConsumer::Process_vkCmdBeginQueryIndexedEXT(
format::HandleId commandBuffer,
format::HandleId queryPool,
uint32_t query,
VkQueryControlFlags flags,
uint32_t index)
{
fprintf(GetFile(), "%s\n", "vkCmdBeginQueryIndexedEXT");
}
void VulkanAsciiConsumer::Process_vkCmdEndQueryIndexedEXT(
format::HandleId commandBuffer,
format::HandleId queryPool,
uint32_t query,
uint32_t index)
{
fprintf(GetFile(), "%s\n", "vkCmdEndQueryIndexedEXT");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndirectByteCountEXT(
format::HandleId commandBuffer,
uint32_t instanceCount,
uint32_t firstInstance,
format::HandleId counterBuffer,
VkDeviceSize counterBufferOffset,
uint32_t counterOffset,
uint32_t vertexStride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndirectByteCountEXT");
}
void VulkanAsciiConsumer::Process_vkGetImageViewHandleNVX(
uint32_t returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkImageViewHandleInfoNVX>& pInfo)
{
fprintf(GetFile(), "%s\n", "vkGetImageViewHandleNVX");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndirectCountAMD(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
format::HandleId countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndirectCountAMD");
}
void VulkanAsciiConsumer::Process_vkCmdDrawIndexedIndirectCountAMD(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
format::HandleId countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawIndexedIndirectCountAMD");
}
void VulkanAsciiConsumer::Process_vkGetShaderInfoAMD(
VkResult returnValue,
format::HandleId device,
format::HandleId pipeline,
VkShaderStageFlagBits shaderStage,
VkShaderInfoTypeAMD infoType,
const PointerDecoder<size_t>& pInfoSize,
const PointerDecoder<uint8_t>& pInfo)
{
fprintf(GetFile(), "%s\n", "vkGetShaderInfoAMD");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceExternalImageFormatPropertiesNV(
VkResult returnValue,
format::HandleId physicalDevice,
VkFormat format,
VkImageType type,
VkImageTiling tiling,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkExternalMemoryHandleTypeFlagsNV externalHandleType,
const StructPointerDecoder<Decoded_VkExternalImageFormatPropertiesNV>& pExternalImageFormatProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceExternalImageFormatPropertiesNV");
}
void VulkanAsciiConsumer::Process_vkGetMemoryWin32HandleNV(
VkResult returnValue,
format::HandleId device,
format::HandleId memory,
VkExternalMemoryHandleTypeFlagsNV handleType,
const PointerDecoder<uint64_t>& pHandle)
{
fprintf(GetFile(), "%s\n", "vkGetMemoryWin32HandleNV");
}
void VulkanAsciiConsumer::Process_vkCreateViSurfaceNN(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkViSurfaceCreateInfoNN>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateViSurfaceNN");
}
void VulkanAsciiConsumer::Process_vkCmdBeginConditionalRenderingEXT(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkConditionalRenderingBeginInfoEXT>& pConditionalRenderingBegin)
{
fprintf(GetFile(), "%s\n", "vkCmdBeginConditionalRenderingEXT");
}
void VulkanAsciiConsumer::Process_vkCmdEndConditionalRenderingEXT(
format::HandleId commandBuffer)
{
fprintf(GetFile(), "%s\n", "vkCmdEndConditionalRenderingEXT");
}
void VulkanAsciiConsumer::Process_vkCmdProcessCommandsNVX(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkCmdProcessCommandsInfoNVX>& pProcessCommandsInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdProcessCommandsNVX");
}
void VulkanAsciiConsumer::Process_vkCmdReserveSpaceForCommandsNVX(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkCmdReserveSpaceForCommandsInfoNVX>& pReserveSpaceInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdReserveSpaceForCommandsNVX");
}
void VulkanAsciiConsumer::Process_vkCreateIndirectCommandsLayoutNVX(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkIndirectCommandsLayoutCreateInfoNVX>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkIndirectCommandsLayoutNVX>& pIndirectCommandsLayout)
{
fprintf(GetFile(), "%s\n", "vkCreateIndirectCommandsLayoutNVX");
}
void VulkanAsciiConsumer::Process_vkDestroyIndirectCommandsLayoutNVX(
format::HandleId device,
format::HandleId indirectCommandsLayout,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyIndirectCommandsLayoutNVX");
}
void VulkanAsciiConsumer::Process_vkCreateObjectTableNVX(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkObjectTableCreateInfoNVX>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkObjectTableNVX>& pObjectTable)
{
fprintf(GetFile(), "%s\n", "vkCreateObjectTableNVX");
}
void VulkanAsciiConsumer::Process_vkDestroyObjectTableNVX(
format::HandleId device,
format::HandleId objectTable,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyObjectTableNVX");
}
void VulkanAsciiConsumer::Process_vkUnregisterObjectsNVX(
VkResult returnValue,
format::HandleId device,
format::HandleId objectTable,
uint32_t objectCount,
const PointerDecoder<VkObjectEntryTypeNVX>& pObjectEntryTypes,
const PointerDecoder<uint32_t>& pObjectIndices)
{
fprintf(GetFile(), "%s\n", "vkUnregisterObjectsNVX");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX(
format::HandleId physicalDevice,
const StructPointerDecoder<Decoded_VkDeviceGeneratedCommandsFeaturesNVX>& pFeatures,
const StructPointerDecoder<Decoded_VkDeviceGeneratedCommandsLimitsNVX>& pLimits)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX");
}
void VulkanAsciiConsumer::Process_vkCmdSetViewportWScalingNV(
format::HandleId commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const StructPointerDecoder<Decoded_VkViewportWScalingNV>& pViewportWScalings)
{
fprintf(GetFile(), "%s\n", "vkCmdSetViewportWScalingNV");
}
void VulkanAsciiConsumer::Process_vkReleaseDisplayEXT(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId display)
{
fprintf(GetFile(), "%s\n", "vkReleaseDisplayEXT");
}
void VulkanAsciiConsumer::Process_vkAcquireXlibDisplayEXT(
VkResult returnValue,
format::HandleId physicalDevice,
uint64_t dpy,
format::HandleId display)
{
fprintf(GetFile(), "%s\n", "vkAcquireXlibDisplayEXT");
}
void VulkanAsciiConsumer::Process_vkGetRandROutputDisplayEXT(
VkResult returnValue,
format::HandleId physicalDevice,
uint64_t dpy,
size_t rrOutput,
const HandlePointerDecoder<VkDisplayKHR>& pDisplay)
{
fprintf(GetFile(), "%s\n", "vkGetRandROutputDisplayEXT");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceSurfaceCapabilities2EXT(
VkResult returnValue,
format::HandleId physicalDevice,
format::HandleId surface,
const StructPointerDecoder<Decoded_VkSurfaceCapabilities2EXT>& pSurfaceCapabilities)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceSurfaceCapabilities2EXT");
}
void VulkanAsciiConsumer::Process_vkDisplayPowerControlEXT(
VkResult returnValue,
format::HandleId device,
format::HandleId display,
const StructPointerDecoder<Decoded_VkDisplayPowerInfoEXT>& pDisplayPowerInfo)
{
fprintf(GetFile(), "%s\n", "vkDisplayPowerControlEXT");
}
void VulkanAsciiConsumer::Process_vkRegisterDeviceEventEXT(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDeviceEventInfoEXT>& pDeviceEventInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkFence>& pFence)
{
fprintf(GetFile(), "%s\n", "vkRegisterDeviceEventEXT");
}
void VulkanAsciiConsumer::Process_vkRegisterDisplayEventEXT(
VkResult returnValue,
format::HandleId device,
format::HandleId display,
const StructPointerDecoder<Decoded_VkDisplayEventInfoEXT>& pDisplayEventInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkFence>& pFence)
{
fprintf(GetFile(), "%s\n", "vkRegisterDisplayEventEXT");
}
void VulkanAsciiConsumer::Process_vkGetSwapchainCounterEXT(
VkResult returnValue,
format::HandleId device,
format::HandleId swapchain,
VkSurfaceCounterFlagBitsEXT counter,
const PointerDecoder<uint64_t>& pCounterValue)
{
fprintf(GetFile(), "%s\n", "vkGetSwapchainCounterEXT");
}
void VulkanAsciiConsumer::Process_vkGetRefreshCycleDurationGOOGLE(
VkResult returnValue,
format::HandleId device,
format::HandleId swapchain,
const StructPointerDecoder<Decoded_VkRefreshCycleDurationGOOGLE>& pDisplayTimingProperties)
{
fprintf(GetFile(), "%s\n", "vkGetRefreshCycleDurationGOOGLE");
}
void VulkanAsciiConsumer::Process_vkGetPastPresentationTimingGOOGLE(
VkResult returnValue,
format::HandleId device,
format::HandleId swapchain,
const PointerDecoder<uint32_t>& pPresentationTimingCount,
const StructPointerDecoder<Decoded_VkPastPresentationTimingGOOGLE>& pPresentationTimings)
{
fprintf(GetFile(), "%s\n", "vkGetPastPresentationTimingGOOGLE");
}
void VulkanAsciiConsumer::Process_vkCmdSetDiscardRectangleEXT(
format::HandleId commandBuffer,
uint32_t firstDiscardRectangle,
uint32_t discardRectangleCount,
const StructPointerDecoder<Decoded_VkRect2D>& pDiscardRectangles)
{
fprintf(GetFile(), "%s\n", "vkCmdSetDiscardRectangleEXT");
}
void VulkanAsciiConsumer::Process_vkSetHdrMetadataEXT(
format::HandleId device,
uint32_t swapchainCount,
const HandlePointerDecoder<VkSwapchainKHR>& pSwapchains,
const StructPointerDecoder<Decoded_VkHdrMetadataEXT>& pMetadata)
{
fprintf(GetFile(), "%s\n", "vkSetHdrMetadataEXT");
}
void VulkanAsciiConsumer::Process_vkCreateIOSSurfaceMVK(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkIOSSurfaceCreateInfoMVK>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateIOSSurfaceMVK");
}
void VulkanAsciiConsumer::Process_vkCreateMacOSSurfaceMVK(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkMacOSSurfaceCreateInfoMVK>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateMacOSSurfaceMVK");
}
void VulkanAsciiConsumer::Process_vkSetDebugUtilsObjectNameEXT(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDebugUtilsObjectNameInfoEXT>& pNameInfo)
{
fprintf(GetFile(), "%s\n", "vkSetDebugUtilsObjectNameEXT");
}
void VulkanAsciiConsumer::Process_vkSetDebugUtilsObjectTagEXT(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkDebugUtilsObjectTagInfoEXT>& pTagInfo)
{
fprintf(GetFile(), "%s\n", "vkSetDebugUtilsObjectTagEXT");
}
void VulkanAsciiConsumer::Process_vkQueueBeginDebugUtilsLabelEXT(
format::HandleId queue,
const StructPointerDecoder<Decoded_VkDebugUtilsLabelEXT>& pLabelInfo)
{
fprintf(GetFile(), "%s\n", "vkQueueBeginDebugUtilsLabelEXT");
}
void VulkanAsciiConsumer::Process_vkQueueEndDebugUtilsLabelEXT(
format::HandleId queue)
{
fprintf(GetFile(), "%s\n", "vkQueueEndDebugUtilsLabelEXT");
}
void VulkanAsciiConsumer::Process_vkQueueInsertDebugUtilsLabelEXT(
format::HandleId queue,
const StructPointerDecoder<Decoded_VkDebugUtilsLabelEXT>& pLabelInfo)
{
fprintf(GetFile(), "%s\n", "vkQueueInsertDebugUtilsLabelEXT");
}
void VulkanAsciiConsumer::Process_vkCmdBeginDebugUtilsLabelEXT(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkDebugUtilsLabelEXT>& pLabelInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdBeginDebugUtilsLabelEXT");
}
void VulkanAsciiConsumer::Process_vkCmdEndDebugUtilsLabelEXT(
format::HandleId commandBuffer)
{
fprintf(GetFile(), "%s\n", "vkCmdEndDebugUtilsLabelEXT");
}
void VulkanAsciiConsumer::Process_vkCmdInsertDebugUtilsLabelEXT(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkDebugUtilsLabelEXT>& pLabelInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdInsertDebugUtilsLabelEXT");
}
void VulkanAsciiConsumer::Process_vkCreateDebugUtilsMessengerEXT(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkDebugUtilsMessengerCreateInfoEXT>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkDebugUtilsMessengerEXT>& pMessenger)
{
fprintf(GetFile(), "%s\n", "vkCreateDebugUtilsMessengerEXT");
}
void VulkanAsciiConsumer::Process_vkDestroyDebugUtilsMessengerEXT(
format::HandleId instance,
format::HandleId messenger,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyDebugUtilsMessengerEXT");
}
void VulkanAsciiConsumer::Process_vkSubmitDebugUtilsMessageEXT(
format::HandleId instance,
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
const StructPointerDecoder<Decoded_VkDebugUtilsMessengerCallbackDataEXT>& pCallbackData)
{
fprintf(GetFile(), "%s\n", "vkSubmitDebugUtilsMessageEXT");
}
void VulkanAsciiConsumer::Process_vkGetAndroidHardwareBufferPropertiesANDROID(
VkResult returnValue,
format::HandleId device,
uint64_t buffer,
const StructPointerDecoder<Decoded_VkAndroidHardwareBufferPropertiesANDROID>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetAndroidHardwareBufferPropertiesANDROID");
}
void VulkanAsciiConsumer::Process_vkGetMemoryAndroidHardwareBufferANDROID(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkMemoryGetAndroidHardwareBufferInfoANDROID>& pInfo,
const PointerDecoder<uint64_t>& pBuffer)
{
fprintf(GetFile(), "%s\n", "vkGetMemoryAndroidHardwareBufferANDROID");
}
void VulkanAsciiConsumer::Process_vkCmdSetSampleLocationsEXT(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkSampleLocationsInfoEXT>& pSampleLocationsInfo)
{
fprintf(GetFile(), "%s\n", "vkCmdSetSampleLocationsEXT");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceMultisamplePropertiesEXT(
format::HandleId physicalDevice,
VkSampleCountFlagBits samples,
const StructPointerDecoder<Decoded_VkMultisamplePropertiesEXT>& pMultisampleProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceMultisamplePropertiesEXT");
}
void VulkanAsciiConsumer::Process_vkGetImageDrmFormatModifierPropertiesEXT(
VkResult returnValue,
format::HandleId device,
format::HandleId image,
const StructPointerDecoder<Decoded_VkImageDrmFormatModifierPropertiesEXT>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetImageDrmFormatModifierPropertiesEXT");
}
void VulkanAsciiConsumer::Process_vkCreateValidationCacheEXT(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkValidationCacheCreateInfoEXT>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkValidationCacheEXT>& pValidationCache)
{
fprintf(GetFile(), "%s\n", "vkCreateValidationCacheEXT");
}
void VulkanAsciiConsumer::Process_vkDestroyValidationCacheEXT(
format::HandleId device,
format::HandleId validationCache,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyValidationCacheEXT");
}
void VulkanAsciiConsumer::Process_vkMergeValidationCachesEXT(
VkResult returnValue,
format::HandleId device,
format::HandleId dstCache,
uint32_t srcCacheCount,
const HandlePointerDecoder<VkValidationCacheEXT>& pSrcCaches)
{
fprintf(GetFile(), "%s\n", "vkMergeValidationCachesEXT");
}
void VulkanAsciiConsumer::Process_vkGetValidationCacheDataEXT(
VkResult returnValue,
format::HandleId device,
format::HandleId validationCache,
const PointerDecoder<size_t>& pDataSize,
const PointerDecoder<uint8_t>& pData)
{
fprintf(GetFile(), "%s\n", "vkGetValidationCacheDataEXT");
}
void VulkanAsciiConsumer::Process_vkCmdBindShadingRateImageNV(
format::HandleId commandBuffer,
format::HandleId imageView,
VkImageLayout imageLayout)
{
fprintf(GetFile(), "%s\n", "vkCmdBindShadingRateImageNV");
}
void VulkanAsciiConsumer::Process_vkCmdSetViewportShadingRatePaletteNV(
format::HandleId commandBuffer,
uint32_t firstViewport,
uint32_t viewportCount,
const StructPointerDecoder<Decoded_VkShadingRatePaletteNV>& pShadingRatePalettes)
{
fprintf(GetFile(), "%s\n", "vkCmdSetViewportShadingRatePaletteNV");
}
void VulkanAsciiConsumer::Process_vkCmdSetCoarseSampleOrderNV(
format::HandleId commandBuffer,
VkCoarseSampleOrderTypeNV sampleOrderType,
uint32_t customSampleOrderCount,
const StructPointerDecoder<Decoded_VkCoarseSampleOrderCustomNV>& pCustomSampleOrders)
{
fprintf(GetFile(), "%s\n", "vkCmdSetCoarseSampleOrderNV");
}
void VulkanAsciiConsumer::Process_vkCreateAccelerationStructureNV(
VkResult returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkAccelerationStructureCreateInfoNV>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkAccelerationStructureNV>& pAccelerationStructure)
{
fprintf(GetFile(), "%s\n", "vkCreateAccelerationStructureNV");
}
void VulkanAsciiConsumer::Process_vkDestroyAccelerationStructureNV(
format::HandleId device,
format::HandleId accelerationStructure,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator)
{
fprintf(GetFile(), "%s\n", "vkDestroyAccelerationStructureNV");
}
void VulkanAsciiConsumer::Process_vkGetAccelerationStructureMemoryRequirementsNV(
format::HandleId device,
const StructPointerDecoder<Decoded_VkAccelerationStructureMemoryRequirementsInfoNV>& pInfo,
const StructPointerDecoder<Decoded_VkMemoryRequirements2KHR>& pMemoryRequirements)
{
fprintf(GetFile(), "%s\n", "vkGetAccelerationStructureMemoryRequirementsNV");
}
void VulkanAsciiConsumer::Process_vkBindAccelerationStructureMemoryNV(
VkResult returnValue,
format::HandleId device,
uint32_t bindInfoCount,
const StructPointerDecoder<Decoded_VkBindAccelerationStructureMemoryInfoNV>& pBindInfos)
{
fprintf(GetFile(), "%s\n", "vkBindAccelerationStructureMemoryNV");
}
void VulkanAsciiConsumer::Process_vkCmdBuildAccelerationStructureNV(
format::HandleId commandBuffer,
const StructPointerDecoder<Decoded_VkAccelerationStructureInfoNV>& pInfo,
format::HandleId instanceData,
VkDeviceSize instanceOffset,
VkBool32 update,
format::HandleId dst,
format::HandleId src,
format::HandleId scratch,
VkDeviceSize scratchOffset)
{
fprintf(GetFile(), "%s\n", "vkCmdBuildAccelerationStructureNV");
}
void VulkanAsciiConsumer::Process_vkCmdCopyAccelerationStructureNV(
format::HandleId commandBuffer,
format::HandleId dst,
format::HandleId src,
VkCopyAccelerationStructureModeNV mode)
{
fprintf(GetFile(), "%s\n", "vkCmdCopyAccelerationStructureNV");
}
void VulkanAsciiConsumer::Process_vkCmdTraceRaysNV(
format::HandleId commandBuffer,
format::HandleId raygenShaderBindingTableBuffer,
VkDeviceSize raygenShaderBindingOffset,
format::HandleId missShaderBindingTableBuffer,
VkDeviceSize missShaderBindingOffset,
VkDeviceSize missShaderBindingStride,
format::HandleId hitShaderBindingTableBuffer,
VkDeviceSize hitShaderBindingOffset,
VkDeviceSize hitShaderBindingStride,
format::HandleId callableShaderBindingTableBuffer,
VkDeviceSize callableShaderBindingOffset,
VkDeviceSize callableShaderBindingStride,
uint32_t width,
uint32_t height,
uint32_t depth)
{
fprintf(GetFile(), "%s\n", "vkCmdTraceRaysNV");
}
void VulkanAsciiConsumer::Process_vkCreateRayTracingPipelinesNV(
VkResult returnValue,
format::HandleId device,
format::HandleId pipelineCache,
uint32_t createInfoCount,
const StructPointerDecoder<Decoded_VkRayTracingPipelineCreateInfoNV>& pCreateInfos,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkPipeline>& pPipelines)
{
fprintf(GetFile(), "%s\n", "vkCreateRayTracingPipelinesNV");
}
void VulkanAsciiConsumer::Process_vkGetRayTracingShaderGroupHandlesNV(
VkResult returnValue,
format::HandleId device,
format::HandleId pipeline,
uint32_t firstGroup,
uint32_t groupCount,
size_t dataSize,
const PointerDecoder<uint8_t>& pData)
{
fprintf(GetFile(), "%s\n", "vkGetRayTracingShaderGroupHandlesNV");
}
void VulkanAsciiConsumer::Process_vkGetAccelerationStructureHandleNV(
VkResult returnValue,
format::HandleId device,
format::HandleId accelerationStructure,
size_t dataSize,
const PointerDecoder<uint8_t>& pData)
{
fprintf(GetFile(), "%s\n", "vkGetAccelerationStructureHandleNV");
}
void VulkanAsciiConsumer::Process_vkCmdWriteAccelerationStructuresPropertiesNV(
format::HandleId commandBuffer,
uint32_t accelerationStructureCount,
const HandlePointerDecoder<VkAccelerationStructureNV>& pAccelerationStructures,
VkQueryType queryType,
format::HandleId queryPool,
uint32_t firstQuery)
{
fprintf(GetFile(), "%s\n", "vkCmdWriteAccelerationStructuresPropertiesNV");
}
void VulkanAsciiConsumer::Process_vkCompileDeferredNV(
VkResult returnValue,
format::HandleId device,
format::HandleId pipeline,
uint32_t shader)
{
fprintf(GetFile(), "%s\n", "vkCompileDeferredNV");
}
void VulkanAsciiConsumer::Process_vkGetMemoryHostPointerPropertiesEXT(
VkResult returnValue,
format::HandleId device,
VkExternalMemoryHandleTypeFlagBits handleType,
uint64_t pHostPointer,
const StructPointerDecoder<Decoded_VkMemoryHostPointerPropertiesEXT>& pMemoryHostPointerProperties)
{
fprintf(GetFile(), "%s\n", "vkGetMemoryHostPointerPropertiesEXT");
}
void VulkanAsciiConsumer::Process_vkCmdWriteBufferMarkerAMD(
format::HandleId commandBuffer,
VkPipelineStageFlagBits pipelineStage,
format::HandleId dstBuffer,
VkDeviceSize dstOffset,
uint32_t marker)
{
fprintf(GetFile(), "%s\n", "vkCmdWriteBufferMarkerAMD");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT(
VkResult returnValue,
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pTimeDomainCount,
const PointerDecoder<VkTimeDomainEXT>& pTimeDomains)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT");
}
void VulkanAsciiConsumer::Process_vkGetCalibratedTimestampsEXT(
VkResult returnValue,
format::HandleId device,
uint32_t timestampCount,
const StructPointerDecoder<Decoded_VkCalibratedTimestampInfoEXT>& pTimestampInfos,
const PointerDecoder<uint64_t>& pTimestamps,
const PointerDecoder<uint64_t>& pMaxDeviation)
{
fprintf(GetFile(), "%s\n", "vkGetCalibratedTimestampsEXT");
}
void VulkanAsciiConsumer::Process_vkCmdDrawMeshTasksNV(
format::HandleId commandBuffer,
uint32_t taskCount,
uint32_t firstTask)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawMeshTasksNV");
}
void VulkanAsciiConsumer::Process_vkCmdDrawMeshTasksIndirectNV(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
uint32_t drawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawMeshTasksIndirectNV");
}
void VulkanAsciiConsumer::Process_vkCmdDrawMeshTasksIndirectCountNV(
format::HandleId commandBuffer,
format::HandleId buffer,
VkDeviceSize offset,
format::HandleId countBuffer,
VkDeviceSize countBufferOffset,
uint32_t maxDrawCount,
uint32_t stride)
{
fprintf(GetFile(), "%s\n", "vkCmdDrawMeshTasksIndirectCountNV");
}
void VulkanAsciiConsumer::Process_vkCmdSetExclusiveScissorNV(
format::HandleId commandBuffer,
uint32_t firstExclusiveScissor,
uint32_t exclusiveScissorCount,
const StructPointerDecoder<Decoded_VkRect2D>& pExclusiveScissors)
{
fprintf(GetFile(), "%s\n", "vkCmdSetExclusiveScissorNV");
}
void VulkanAsciiConsumer::Process_vkCmdSetCheckpointNV(
format::HandleId commandBuffer,
uint64_t pCheckpointMarker)
{
fprintf(GetFile(), "%s\n", "vkCmdSetCheckpointNV");
}
void VulkanAsciiConsumer::Process_vkGetQueueCheckpointDataNV(
format::HandleId queue,
const PointerDecoder<uint32_t>& pCheckpointDataCount,
const StructPointerDecoder<Decoded_VkCheckpointDataNV>& pCheckpointData)
{
fprintf(GetFile(), "%s\n", "vkGetQueueCheckpointDataNV");
}
void VulkanAsciiConsumer::Process_vkCreateImagePipeSurfaceFUCHSIA(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkImagePipeSurfaceCreateInfoFUCHSIA>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateImagePipeSurfaceFUCHSIA");
}
void VulkanAsciiConsumer::Process_vkCreateMetalSurfaceEXT(
VkResult returnValue,
format::HandleId instance,
const StructPointerDecoder<Decoded_VkMetalSurfaceCreateInfoEXT>& pCreateInfo,
const StructPointerDecoder<Decoded_VkAllocationCallbacks>& pAllocator,
const HandlePointerDecoder<VkSurfaceKHR>& pSurface)
{
fprintf(GetFile(), "%s\n", "vkCreateMetalSurfaceEXT");
}
void VulkanAsciiConsumer::Process_vkGetBufferDeviceAddressEXT(
VkDeviceAddress returnValue,
format::HandleId device,
const StructPointerDecoder<Decoded_VkBufferDeviceAddressInfoEXT>& pInfo)
{
fprintf(GetFile(), "%s\n", "vkGetBufferDeviceAddressEXT");
}
void VulkanAsciiConsumer::Process_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV(
VkResult returnValue,
format::HandleId physicalDevice,
const PointerDecoder<uint32_t>& pPropertyCount,
const StructPointerDecoder<Decoded_VkCooperativeMatrixPropertiesNV>& pProperties)
{
fprintf(GetFile(), "%s\n", "vkGetPhysicalDeviceCooperativeMatrixPropertiesNV");
}
GFXRECON_END_NAMESPACE(decode)
GFXRECON_END_NAMESPACE(gfxrecon)
| 43.532774 | 109 | 0.614837 | [
"object"
] |
29dfa058041168344f32cc9d39a22ae72c0028fd | 20,221 | cpp | C++ | hphp/runtime/ext/objprof/ext_heapgraph.cpp | jie-pan/hhvm | 41853383c5b53a69ac2c67f9d3cce5e38c6eafa5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/ext/objprof/ext_heapgraph.cpp | jie-pan/hhvm | 41853383c5b53a69ac2c67f9d3cce5e38c6eafa5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/ext/objprof/ext_heapgraph.cpp | jie-pan/hhvm | 41853383c5b53a69ac2c67f9d3cce5e38c6eafa5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/base/builtin-functions.h"
#include <folly/Format.h>
/*
* Heapgraph Extension
* What is it?
* Set of methods to wrap around HHVM's heap graph implementation
*
* How does it work?
* Create a heap graph in HHVM and uses it as a Resource with a
* set of functions that can operate on it.
*
* How do I use it?
* Call heapgraph_create, and then any of the other heapgraph
* function
*/
#include <array>
#include <set>
#include <unordered_map>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/collections.h"
#include "hphp/runtime/base/memory-manager-defs.h"
#include "hphp/runtime/ext/datetime/ext_datetime.h"
#include "hphp/runtime/ext/simplexml/ext_simplexml.h"
#include "hphp/runtime/ext/std/ext_std_closure.h"
#include "hphp/runtime/vm/class.h"
#include "hphp/runtime/vm/unit.h"
#include "hphp/util/alloc.h"
#include "hphp/runtime/base/heap-graph.h"
#include "hphp/runtime/base/heap-algorithms.h"
#include "hphp/runtime/base/container-functions.h"
#include "hphp/runtime/base/rds.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/runtime/vm/vm-regs.h"
namespace HPHP {
struct PhpStack;
struct CppStack;
namespace {
TRACE_SET_MOD(heapgraph);
///////////////////////////////////////////////////////////////////////////////
const StaticString
s_nodes("nodes"),
s_edges("edges"),
s_roots("roots"),
s_root_nodes("root_nodes"),
s_root_path("root_path"),
s_exact("exact"),
s_format("format"),
// Node description
s_kind("kind"),
s_size("size"),
s_index("index"),
s_class("class"),
s_func("func"),
s_local("local"),
s_prop("prop"),
s_Root("Root"),
s_type("type"),
// Edge description
s_from("from"),
s_to("to"),
s_key("key"),
s_value("value"),
s_offset("offset");
}
///////////////////////////////////////////////////////////////////////////////
// CONTEXT OBJECTS
// Extra information about a HeapGraph::Node.
union CapturedNode {
CapturedNode() {}
CapturedNode(const CapturedNode& other) {
memcpy(this, &other, sizeof other);
}
rds::SPropCache sprop_cache; // only for HPHP::SPropCache
struct {
HeaderKind kind;
const Class* cls;
} heap_object; // only for non-roots
};
// Extra information about a HeapGraph::Ptr
struct CapturedPtr {
enum { Key, Value, Property, Offset } index_kind;
uint32_t index; // location of ptr within it's from node
};
struct HeapGraphContext : SweepableResourceData {
explicit HeapGraphContext(const HeapGraph& hg) : hg(hg) {}
explicit HeapGraphContext(HeapGraph&& hg) : hg(std::move(hg)) {}
~HeapGraphContext() override {}
bool isInvalid() const override {
return false;
}
CLASSNAME_IS("HeapGraphContext")
DECLARE_RESOURCE_ALLOCATION(HeapGraphContext)
// overriding ResourceData
const String& o_getClassNameHook() const override { return classnameof(); }
std::vector<CapturedNode> cnodes;
std::vector<CapturedPtr> cptrs;
const HeapGraph hg;
};
IMPLEMENT_RESOURCE_ALLOCATION(HeapGraphContext)
namespace {
using HeapGraphContextPtr = req::ptr<HeapGraphContext>;
static HeapGraphContextPtr get_valid_heapgraph_context_resource(
const Resource& resource,
const char* func_name
) {
auto hgcontext = dyn_cast_or_null<HeapGraphContext>(resource);
if (hgcontext == nullptr || hgcontext->isInvalid()) {
raise_warning(
"%s(): supplied resource is not a valid HeapGraph Context resource",
func_name + 2
);
return nullptr;
}
return hgcontext;
}
///////////////////////////////////////////////////////////////////////////////
// TRAVERSAL FUNCTIONS
static std::array<const StringData*, 3> edge_kind_strs{};
static const char* edge_kind_cstrs[] = {
"Ptr:Counted", "Ptr:Ambiguous", "Ptr:Weak",
};
const StringData* edgeKindName(HeapGraph::PtrKind kind) {
auto s = edge_kind_strs[(int)kind];
if (!s) {
s = makeStaticString(edge_kind_cstrs[(int)kind]);
edge_kind_strs[(int)kind] = s;
}
return s;
static_assert(HeapGraph::NumPtrKinds == 3, "");
static_assert(HeapGraph::Counted == 0, "");
static_assert(HeapGraph::Ambiguous == 1, "");
static_assert(HeapGraph::Weak == 2, "");
}
// return metadata about this pointer, in the form of a CapturedPtr
CapturedPtr getEdgeInfo(const HeapGraph& g, int ptr) {
// Try to drill down and resolve the edge name
assertx(g.ptrs[ptr].from != -1 && g.ptrs[ptr].to != -1);
auto& edge = g.ptrs[ptr];
auto& from = g.nodes[edge.from];
int prop_offset = edge.offset;
if (!from.is_root) {
auto from_hdr = from.h;
// get the actual ObjectData*. This deals with object kinds that
// have data before the object: AFWH, Native, and Closure. Compute
// prop_offset relative to the inner ObjectData.
const ObjectData* from_obj{nullptr};
if (from_hdr->kind() == HeaderKind::AsyncFuncFrame) {
from_obj = asyncFuncWH(from_hdr);
prop_offset = edge.offset - (uintptr_t(from_obj) - uintptr_t(from_hdr));
} else if (from_hdr->kind() == HeaderKind::NativeData) {
from_obj = Native::obj(static_cast<const NativeNode*>(from_hdr));
prop_offset = edge.offset - (uintptr_t(from_obj) - uintptr_t(from_hdr));
} else if (from_hdr->kind() == HeaderKind::ClosureHdr) {
from_obj = closureObj(from_hdr);
prop_offset = edge.offset - (uintptr_t(from_obj) - uintptr_t(from_hdr));
} else if (from_hdr->kind() == HeaderKind::MemoData) {
from_obj = memoObj(from_hdr);
prop_offset = edge.offset - (uintptr_t(from_obj) - uintptr_t(from_hdr));
} else if (isObjectKind(from_hdr->kind())) {
from_obj = static_cast<const ObjectData*>(from_hdr);
prop_offset = edge.offset;
}
switch (from_hdr->kind()) {
// Known generalized cases that don't really need pointer kind
case HeaderKind::Dict:
case HeaderKind::Keyset: {
if (edge.offset >= sizeof(VanillaDict)) {
using Elm = VanillaDict::Elm;
auto elm_offset = edge.offset - sizeof(VanillaDict);
uint32_t index = elm_offset / sizeof(Elm);
if (index < static_cast<const VanillaDict*>(from_hdr)->iterLimit()) {
auto field = elm_offset - index * sizeof(Elm);
if (field == Elm::keyOff()) {
return {CapturedPtr::Key, index};
}
if (field == Elm::dataOff() + offsetof(TypedValue, m_data)) {
return {CapturedPtr::Value, index};
}
}
}
break;
}
case HeaderKind::Vec: {
if (edge.offset >= sizeof(ArrayData)) {
auto elm_offset = edge.offset - sizeof(ArrayData);
uint32_t index = elm_offset / sizeof(TypedValue);
if (index < static_cast<const ArrayData*>(from_hdr)->size()) {
return {CapturedPtr::Value, index};
}
}
break;
}
case HeaderKind::BespokeVec:
case HeaderKind::BespokeDict:
case HeaderKind::BespokeKeyset:
// TODO(kshaunak): Expose an address -> element API for bespokes.
break;
case HeaderKind::Pair: {
if (edge.offset >= c_Pair::dataOffset()) {
auto elm_offset = edge.offset - c_Pair::dataOffset();
uint32_t index = elm_offset / sizeof(TypedValue);
if (index < 2) {
return {CapturedPtr::Value, index};
}
}
break;
}
case HeaderKind::AwaitAllWH:
case HeaderKind::WaitHandle:
case HeaderKind::ClsMeth:
case HeaderKind::RClsMeth:
break;
// cases that have explicit pointer name
case HeaderKind::AsyncFuncFrame:
case HeaderKind::ClosureHdr:
case HeaderKind::Closure:
// the class of a c_Closure describes the captured variables
case HeaderKind::NativeData:
case HeaderKind::MemoData:
case HeaderKind::Object: {
auto cls = from_obj->getVMClass();
FTRACE(5, "HG: Getting connection name for class {} at {}\n",
from_obj->getClassName().data(), from_obj);
if (prop_offset >= sizeof(ObjectData)) {
uint32_t index = ObjectProps::offset2Idx(
prop_offset - sizeof(ObjectData)
);
if (index < cls->numDeclProperties()) {
return {CapturedPtr::Property, index};
}
} else {
// edge_offset > 0 && prop_offset < 0 means nativedata fields
}
break;
}
case HeaderKind::NativeObject:
case HeaderKind::AsyncFuncWH:
case HeaderKind::Vector:
case HeaderKind::ImmVector:
case HeaderKind::Set:
case HeaderKind::ImmSet:
case HeaderKind::Map:
case HeaderKind::ImmMap:
case HeaderKind::String:
case HeaderKind::Resource:
case HeaderKind::BigMalloc:
case HeaderKind::Cpp:
case HeaderKind::SmallMalloc:
case HeaderKind::Free:
case HeaderKind::Hole:
case HeaderKind::Slab:
case HeaderKind::RFunc:
// just provide raw prop_offset
break;
case HeaderKind::Record: // TODO(T41026982)
raise_error(Strings::RECORD_NOT_SUPPORTED);
}
}
return {CapturedPtr::Offset, uint32_t(prop_offset)};
}
void heapgraphCallback(Array fields, const Variant& callback) {
VMRegAnchor _;
auto params = make_vec_array(fields);
vm_call_user_func(callback, params);
}
void heapgraphCallback(Array fields, Array fields2, const Variant& callback) {
VMRegAnchor _;
auto params = make_vec_array(fields, fields2);
vm_call_user_func(callback, params);
}
static const StringData* header_name_strs[NumHeaderKinds];
Array createPhpNode(HeapGraphContextPtr hgptr, int index) {
const auto& node = hgptr->hg.nodes[index];
const auto& cnode = hgptr->cnodes[index];
const StringData* kind_str;
if (!node.is_root) {
auto k = int(cnode.heap_object.kind);
kind_str = header_name_strs[k];
if (!kind_str) {
kind_str = makeStaticString(header_names[k]);
header_name_strs[k] = kind_str;
}
} else {
kind_str = s_Root.get(); // fake HeaderKind "Root"
}
auto node_arr = make_dict_array(
s_index, VarNR(index),
s_kind, VarNR(kind_str),
s_size, VarNR(int64_t(node.size))
);
if (type_scan::hasNonConservative()) {
auto ty = node.tyindex;
if (ty > type_scan::kIndexUnknownNoPtrs) {
auto type = type_scan::getName(ty);
node_arr.set(s_type,
make_tv<KindOfPersistentString>(makeStaticString(type)));
}
}
if (!node.is_root) {
if (auto cls = cnode.heap_object.cls) {
node_arr.set(s_class, make_tv<KindOfPersistentString>(cls->name()));
}
}
return node_arr;
}
Array createPhpEdge(HeapGraphContextPtr hgptr, int index) {
const auto& ptr = hgptr->hg.ptrs[index];
const auto& cptr = hgptr->cptrs[index];
const auto& cfrom = hgptr->cnodes[ptr.from];
auto ptr_arr = make_dict_array(
s_index, VarNR(index),
s_kind, VarNR(edgeKindName(ptr.ptr_kind)),
s_from, VarNR(ptr.from),
s_to, VarNR(ptr.to)
);
switch (cptr.index_kind) {
case CapturedPtr::Key:
ptr_arr.set(s_key, make_tv<KindOfInt64>(cptr.index));
break;
case CapturedPtr::Value:
ptr_arr.set(s_value, make_tv<KindOfInt64>(cptr.index));
break;
case CapturedPtr::Property: {
auto cls = cfrom.heap_object.cls;
auto slot = cls->propIndexToSlot(cptr.index);
auto& prop = cls->declProperties()[slot];
ptr_arr.set(s_prop, make_tv<KindOfPersistentString>(prop.name));
break;
}
case CapturedPtr::Offset:
if (cptr.index) ptr_arr.set(s_offset, make_tv<KindOfInt64>(cptr.index));
break;
}
return ptr_arr;
}
std::vector<int> toBoundIntVector(const Array& arr, int64_t max) {
std::vector<int> result;
result.reserve(arr.size());
for (ArrayIter iter(arr); iter; ++iter) {
auto index = iter.second().toInt64(); // Cannot re-enter.
if (index < 0 || index >= max) {
continue;
}
result.push_back(index);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Exports
Resource HHVM_FUNCTION(heapgraph_create, void) {
HeapGraph hg = makeHeapGraph();
std::vector<CapturedNode> cnodes;
std::vector<CapturedPtr> cptrs;
// Copy edges into captured edges
// Capturing edges first because after capturing nodes we nullify the header
cptrs.reserve(hg.ptrs.size());
for (int i = 0; i < hg.ptrs.size(); ++i) {
auto new_ptr = getEdgeInfo(hg, i); // edge name
cptrs.push_back(new_ptr);
}
// Copy useful information from heap into cnodes
cnodes.resize(hg.nodes.size());
for (size_t i = 0, n = hg.nodes.size(); i < n; ++i) {
auto& node = hg.nodes[i];
auto& cnode = cnodes[i];
if (!node.is_root) {
auto obj = innerObj(node.h);
cnode.heap_object.kind = node.h->kind();
cnode.heap_object.cls = obj ? obj->getVMClass() : nullptr;
node.h = nullptr;
}
}
auto hgcontext = req::make<HeapGraphContext>(std::move(hg));
std::swap(hgcontext->cnodes, cnodes);
std::swap(hgcontext->cptrs, cptrs);
return Resource(hgcontext);
}
void HHVM_FUNCTION(heapgraph_foreach_node,
const Resource& resource,
const Variant& callback
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr || callback.isNull()) return;
for (int i = 0; i < hgptr->hg.nodes.size(); i++) {
auto phpnode = createPhpNode(hgptr, i);
heapgraphCallback(phpnode, callback);
}
}
void HHVM_FUNCTION(heapgraph_foreach_edge,
const Resource& resource,
const Variant& callback
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr || callback.isNull()) return;
for (int i = 0; i < hgptr->hg.ptrs.size(); i++) {
auto phpedge = createPhpEdge(hgptr, i);
heapgraphCallback(phpedge, callback);
}
}
void HHVM_FUNCTION(heapgraph_foreach_root,
const Resource& resource,
const Variant& callback
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr || callback.isNull()) return;
for (int i = 0, n = hgptr->hg.root_ptrs.size(); i < n; ++i) {
auto phpedge = createPhpEdge(hgptr, hgptr->hg.root_ptrs[i]);
heapgraphCallback(phpedge, callback);
}
}
void HHVM_FUNCTION(heapgraph_foreach_root_node,
const Resource& resource,
const Variant& callback
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr || callback.isNull()) return;
for (auto n : hgptr->hg.root_nodes) {
auto phpnode = createPhpNode(hgptr, n);
heapgraphCallback(phpnode, callback);
}
}
void HHVM_FUNCTION(heapgraph_dfs_nodes,
const Resource& resource,
const Array& roots_arr,
const Array& skips_arr,
const Variant& callback
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr || callback.isNull()) return;
auto max = hgptr->hg.nodes.size();
auto roots = toBoundIntVector(roots_arr, max);
auto skips = toBoundIntVector(skips_arr, max);
dfs_nodes(hgptr->hg, roots, skips, [&](int n) {
auto phpnode = createPhpNode(hgptr, n);
heapgraphCallback(phpnode, callback);
});
}
void HHVM_FUNCTION(heapgraph_dfs_edges,
const Resource& resource,
const Array& roots_arr,
const Array& skips_arr,
const Variant& callback
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr || callback.isNull()) return;
auto max = hgptr->hg.ptrs.size();
auto roots = toBoundIntVector(roots_arr, max);
auto skips = toBoundIntVector(skips_arr, max);
dfs_ptrs(hgptr->hg, roots, skips, [&](int n, int p) {
auto phpnode = createPhpNode(hgptr, n);
auto phpedge = createPhpEdge(hgptr, p);
heapgraphCallback(phpedge, phpnode, callback);
});
}
Array HHVM_FUNCTION(heapgraph_edge, const Resource& resource, int64_t index) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr) return Array::CreateDict();
if (size_t(index) >= hgptr->hg.ptrs.size()) return Array::CreateDict();
return createPhpEdge(hgptr, index);
}
Array HHVM_FUNCTION(heapgraph_node, const Resource& resource, int64_t index) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr) return Array::CreateDict();
if (size_t(index) >= hgptr->hg.nodes.size()) return Array::CreateDict();
return createPhpNode(hgptr, index);
}
Array HHVM_FUNCTION(heapgraph_node_out_edges,
const Resource& resource,
int64_t index
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr) return Array::CreateVec();
if (size_t(index) >= hgptr->hg.nodes.size()) return Array::CreateVec();
size_t num_edges{0};
hgptr->hg.eachOutPtr(index, [&](int) { num_edges++; });
VecInit result(num_edges);
hgptr->hg.eachOutPtr(index, [&](int ptr) {
result.append(createPhpEdge(hgptr, ptr));
});
return result.toArray();
}
Array HHVM_FUNCTION(heapgraph_node_in_edges,
const Resource& resource,
int64_t index
) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr) return Array::CreateVec();
if (size_t(index) >= hgptr->hg.nodes.size()) return Array::CreateVec();
size_t num_edges{0};
hgptr->hg.eachInPtr(index, [&](int) { num_edges++; });
VecInit result(num_edges);
hgptr->hg.eachInPtr(index, [&](int ptr) {
result.append(createPhpEdge(hgptr, ptr));
});
return result.toArray();
}
Array HHVM_FUNCTION(heapgraph_stats, const Resource& resource) {
auto hgptr = get_valid_heapgraph_context_resource(resource, __FUNCTION__);
if (!hgptr) return Array::CreateDict();
auto result = make_dict_array(
s_nodes, VarNR(int64_t(hgptr->hg.nodes.size())),
s_edges, VarNR(int64_t(hgptr->hg.ptrs.size())),
s_roots, VarNR(int64_t(hgptr->hg.root_ptrs.size())),
s_root_nodes, VarNR(int64_t(hgptr->hg.root_nodes.size())),
s_exact, VarNR(type_scan::hasNonConservative() ? 1 : 0)
);
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Extension
}
struct heapgraphExtension final : Extension {
heapgraphExtension() : Extension("heapgraph", "1.0") { }
void moduleInit() override {
HHVM_FALIAS(HH\\heapgraph_create, heapgraph_create);
HHVM_FALIAS(HH\\heapgraph_stats, heapgraph_stats);
HHVM_FALIAS(HH\\heapgraph_foreach_node, heapgraph_foreach_node);
HHVM_FALIAS(HH\\heapgraph_foreach_edge, heapgraph_foreach_edge);
HHVM_FALIAS(HH\\heapgraph_foreach_root, heapgraph_foreach_root);
HHVM_FALIAS(HH\\heapgraph_foreach_root_node, heapgraph_foreach_root_node);
HHVM_FALIAS(HH\\heapgraph_edge, heapgraph_edge);
HHVM_FALIAS(HH\\heapgraph_node, heapgraph_node);
HHVM_FALIAS(HH\\heapgraph_node_out_edges, heapgraph_node_out_edges);
HHVM_FALIAS(HH\\heapgraph_node_in_edges, heapgraph_node_in_edges);
HHVM_FALIAS(HH\\heapgraph_dfs_nodes, heapgraph_dfs_nodes);
HHVM_FALIAS(HH\\heapgraph_dfs_edges, heapgraph_dfs_edges);
loadSystemlib();
}
} s_heapgraph_extension;
///////////////////////////////////////////////////////////////////////////////
}
| 32.561997 | 79 | 0.647149 | [
"object",
"vector"
] |
29e2a06d135d4d74daf0ca6fdc0180b25c0e9fd5 | 9,542 | cpp | C++ | be/src/vec/exec/vsort_node.cpp | 13671653088/incubator-doris | 2ccaa6338c272a953c93aaf9827779f9c8543251 | [
"Apache-2.0"
] | null | null | null | be/src/vec/exec/vsort_node.cpp | 13671653088/incubator-doris | 2ccaa6338c272a953c93aaf9827779f9c8543251 | [
"Apache-2.0"
] | null | null | null | be/src/vec/exec/vsort_node.cpp | 13671653088/incubator-doris | 2ccaa6338c272a953c93aaf9827779f9c8543251 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "vec/exec/vsort_node.h"
#include "exec/sort_exec_exprs.h"
#include "runtime/row_batch.h"
#include "runtime/runtime_state.h"
#include "util/debug_util.h"
#include "vec/core/sort_block.h"
namespace doris::vectorized {
VSortNode::VSortNode(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs)
: ExecNode(pool, tnode, descs),
_offset(tnode.sort_node.__isset.offset ? tnode.sort_node.offset : 0),
_num_rows_skipped(0) {}
Status VSortNode::init(const TPlanNode& tnode, RuntimeState* state) {
RETURN_IF_ERROR(ExecNode::init(tnode, state));
RETURN_IF_ERROR(_vsort_exec_exprs.init(tnode.sort_node.sort_info, _pool));
_is_asc_order = tnode.sort_node.sort_info.is_asc_order;
_nulls_first = tnode.sort_node.sort_info.nulls_first;
return Status::OK();
}
Status VSortNode::prepare(RuntimeState* state) {
SCOPED_TIMER(_runtime_profile->total_time_counter());
_runtime_profile->add_info_string("TOP-N", _limit == -1 ? "false" : "true");
RETURN_IF_ERROR(ExecNode::prepare(state));
SCOPED_SWITCH_TASK_THREAD_LOCAL_MEM_TRACKER(_mem_tracker);
_block_mem_tracker = MemTracker::create_virtual_tracker(-1, "VSortNode:Block", mem_tracker());
RETURN_IF_ERROR(_vsort_exec_exprs.prepare(state, child(0)->row_desc(), _row_descriptor,
expr_mem_tracker()));
return Status::OK();
}
Status VSortNode::open(RuntimeState* state) {
SCOPED_TIMER(_runtime_profile->total_time_counter());
SCOPED_SWITCH_TASK_THREAD_LOCAL_MEM_TRACKER(_mem_tracker);
RETURN_IF_ERROR(ExecNode::open(state));
RETURN_IF_ERROR(_vsort_exec_exprs.open(state));
RETURN_IF_CANCELLED(state);
RETURN_IF_ERROR(state->check_query_state("vsort, while open."));
RETURN_IF_ERROR(child(0)->open(state));
// The child has been opened and the sorter created. Sort the input.
// The final merge is done on-demand as rows are requested in get_next().
RETURN_IF_ERROR(sort_input(state));
// Unless we are inside a subplan expecting to call open()/get_next() on the child
// again, the child can be closed at this point.
// if (!IsInSubplan()) {
// child(0)->close(state);
// }
return Status::OK();
}
Status VSortNode::get_next(RuntimeState* state, RowBatch* row_batch, bool* eos) {
*eos = true;
return Status::NotSupported("Not Implemented VSortNode::get_next scalar");
}
Status VSortNode::get_next(RuntimeState* state, Block* block, bool* eos) {
SCOPED_TIMER(_runtime_profile->total_time_counter());
SCOPED_SWITCH_TASK_THREAD_LOCAL_EXISTED_MEM_TRACKER(_mem_tracker);
auto status = Status::OK();
if (_sorted_blocks.empty()) {
*eos = true;
} else if (_sorted_blocks.size() == 1) {
if (_offset != 0) {
_sorted_blocks[0].skip_num_rows(_offset);
}
block->swap(_sorted_blocks[0]);
*eos = true;
} else {
RETURN_IF_ERROR(merge_sort_read(state, block, eos));
}
reached_limit(block, eos);
return status;
}
Status VSortNode::reset(RuntimeState* state) {
_num_rows_skipped = 0;
return Status::OK();
}
Status VSortNode::close(RuntimeState* state) {
if (is_closed()) {
return Status::OK();
}
_block_mem_tracker->release(_total_mem_usage);
_vsort_exec_exprs.close(state);
ExecNode::close(state);
return Status::OK();
}
void VSortNode::debug_string(int indentation_level, stringstream* out) const {
*out << string(indentation_level * 2, ' ');
*out << "VSortNode(";
for (int i = 0; i < _is_asc_order.size(); ++i) {
*out << (i > 0 ? " " : "") << (_is_asc_order[i] ? "asc" : "desc") << " nulls "
<< (_nulls_first[i] ? "first" : "last");
}
ExecNode::debug_string(indentation_level, out);
*out << ")";
}
Status VSortNode::sort_input(RuntimeState* state) {
bool eos = false;
do {
Block block;
RETURN_IF_ERROR(child(0)->get_next(state, &block, &eos));
auto rows = block.rows();
if (rows != 0) {
RETURN_IF_ERROR(pretreat_block(block));
size_t mem_usage = block.allocated_bytes();
// dispose TOP-N logic
if (_limit != -1) {
// Here is a little opt to reduce the mem uasge, we build a max heap
// to order the block in _block_priority_queue.
// if one block totally greater the heap top of _block_priority_queue
// we can throw the block data directly.
if (_num_rows_in_block < _limit) {
_total_mem_usage += mem_usage;
_sorted_blocks.emplace_back(std::move(block));
_num_rows_in_block += rows;
_block_priority_queue.emplace(_pool->add(
new SortCursorImpl(_sorted_blocks.back(), _sort_description)));
} else {
SortBlockCursor block_cursor(
_pool->add(new SortCursorImpl(block, _sort_description)));
if (!block_cursor.totally_greater(_block_priority_queue.top())) {
_sorted_blocks.emplace_back(std::move(block));
_block_priority_queue.push(block_cursor);
_total_mem_usage += mem_usage;
} else {
continue;
}
}
} else {
// dispose normal sort logic
_total_mem_usage += mem_usage;
_sorted_blocks.emplace_back(std::move(block));
}
_block_mem_tracker->consume(mem_usage);
RETURN_IF_CANCELLED(state);
RETURN_IF_ERROR(state->check_query_state("vsort, while sorting input."));
}
} while (!eos);
build_merge_tree();
return Status::OK();
}
Status VSortNode::pretreat_block(doris::vectorized::Block& block) {
if (_vsort_exec_exprs.need_materialize_tuple()) {
auto output_tuple_expr_ctxs = _vsort_exec_exprs.sort_tuple_slot_expr_ctxs();
std::vector<int> valid_column_ids(output_tuple_expr_ctxs.size());
for (int i = 0; i < output_tuple_expr_ctxs.size(); ++i) {
RETURN_IF_ERROR(output_tuple_expr_ctxs[i]->execute(&block, &valid_column_ids[i]));
}
Block new_block;
for (auto column_id : valid_column_ids) {
new_block.insert(block.get_by_position(column_id));
}
block.swap(new_block);
}
_sort_description.resize(_vsort_exec_exprs.lhs_ordering_expr_ctxs().size());
for (int i = 0; i < _sort_description.size(); i++) {
const auto& ordering_expr = _vsort_exec_exprs.lhs_ordering_expr_ctxs()[i];
RETURN_IF_ERROR(ordering_expr->execute(&block, &_sort_description[i].column_number));
_sort_description[i].direction = _is_asc_order[i] ? 1 : -1;
_sort_description[i].nulls_direction =
_nulls_first[i] ? -_sort_description[i].direction : _sort_description[i].direction;
}
sort_block(block, _sort_description, _offset + _limit);
return Status::OK();
}
void VSortNode::build_merge_tree() {
for (const auto& block : _sorted_blocks) {
_cursors.emplace_back(block, _sort_description);
}
if (_sorted_blocks.size() > 1) {
for (auto& _cursor : _cursors) _priority_queue.push(SortCursor(&_cursor));
}
}
Status VSortNode::merge_sort_read(doris::RuntimeState* state, doris::vectorized::Block* block,
bool* eos) {
size_t num_columns = _sorted_blocks[0].columns();
bool mem_reuse = block->mem_reuse();
MutableColumns merged_columns =
mem_reuse ? block->mutate_columns() : _sorted_blocks[0].clone_empty_columns();
/// Take rows from queue in right order and push to 'merged'.
size_t merged_rows = 0;
while (!_priority_queue.empty()) {
auto current = _priority_queue.top();
_priority_queue.pop();
if (_offset == 0) {
for (size_t i = 0; i < num_columns; ++i)
merged_columns[i]->insert_from(*current->all_columns[i], current->pos);
++merged_rows;
} else {
_offset--;
}
if (!current->isLast()) {
current->next();
_priority_queue.push(current);
}
if (merged_rows == state->batch_size()) break;
}
if (merged_rows == 0) {
*eos = true;
return Status::OK();
}
if (!mem_reuse) {
Block merge_block = _sorted_blocks[0].clone_with_columns(std::move(merged_columns));
merge_block.swap(*block);
}
return Status::OK();
}
} // namespace doris::vectorized
| 36.7 | 99 | 0.635821 | [
"vector"
] |
29e2c0a3ec5b7d7576a2438c00778d840578a3a3 | 5,928 | hpp | C++ | external_codes/boost_multi/multi/detail/types.hpp | eugeneswalker/qmcpack | 352ff27f163bb92e0c232c48bec8ae7951ed9d8c | [
"NCSA"
] | null | null | null | external_codes/boost_multi/multi/detail/types.hpp | eugeneswalker/qmcpack | 352ff27f163bb92e0c232c48bec8ae7951ed9d8c | [
"NCSA"
] | 11 | 2020-05-09T20:57:21.000Z | 2020-06-10T00:00:17.000Z | external_codes/boost_multi/multi/detail/types.hpp | mmorale3/qmcpack | b1a358d8aeb63a96bccabafea5d899afa4520d13 | [
"NCSA"
] | null | null | null | #ifdef COMPILATION_INSTRUCTIONS
$CXXX $CXXFLAGS $0 -o $0$X&&$0$X&&rm $0$X;exit
#endif
// © Alfredo A. Correa 2018-2020
#ifndef MULTI_DETAIL_TYPES_HPP
#define MULTI_DETAIL_TYPES_HPP
//#include "detail.hpp"
#include "index_range.hpp"
#include<tuple> // make_tuple
#include<array>
#include<cassert>
#include<cstddef>
#include<type_traits> // make_signed_t
namespace boost{
namespace multi{
using size_type = std::make_signed_t<std::size_t>;
using index = std::make_signed_t<size_type>;
using difference_type = std::make_signed_t<index>;
using index_range = range<index>;
using index_extension = extension_t<index>;
using dimensionality_type = index;
using iextension = index_extension;
using irange = index_range;
namespace detail{
template<typename, typename>
struct append_to_type_seq{};
template<typename T, typename... Ts, template<typename...> class TT>
struct append_to_type_seq<T, TT<Ts...>>{
using type = TT<Ts..., T>;
};
template<typename T, dimensionality_type N, template<typename...> class TT = std::tuple>
struct repeat{
using type = typename
append_to_type_seq<
T,
typename repeat<T, N-1, TT>::type
>::type;
};
template<typename T, template<typename...> class TT>
struct repeat<T, 0, TT>{
using type = TT<>;
};
template<class T, std::size_t N>
constexpr auto array_size_impl(const std::array<T, N>&)
-> std::integral_constant<std::size_t, N>;
template<class... T>
constexpr auto array_size_impl(const std::tuple<T...>&)
-> std::integral_constant<std::size_t, std::tuple_size<std::tuple<T...>>{}>;
template<class Array>
using array_size = decltype(array_size_impl(std::declval<const Array&>()));
template<class Array>
constexpr auto static_size() -> decltype(array_size<Array>::value){
return array_size<Array>::value;
}
template<class Array>
constexpr auto static_size(Array const&) -> decltype(static_size<Array>()){
return static_size<Array>();
}
//TODO consolidate with tuple_tail defined somewhere else
template<class Tuple>
constexpr auto head(Tuple&& t)
->decltype(std::get<0>(std::forward<Tuple>(t))){
return std::get<0>(std::forward<Tuple>(t));}
template<typename Tuple, std::size_t... Ns>
constexpr auto tail_impl(std::index_sequence<Ns...> , Tuple&& t){
return std::make_tuple(std::get<Ns+1u>(std::forward<Tuple>(t))...);
}
template<class Tuple>
constexpr auto tail(Tuple const& t)
//->decltype(tail_impl(std::make_index_sequence<(static_size<Tuple>())-1>(), t)){
{ return tail_impl(std::make_index_sequence<(static_size<Tuple>())-1>(), t);}
//->decltype(tail_impl(std::make_index_sequence<(std::tuple_size<Tuple>{})-1>(), t)){
// return tail_impl(std::make_index_sequence<(std::tuple_size<Tuple>{})-1>(), t);}
template<typename T, std::size_t N>
constexpr std::array<T, N-1> tail(std::array<T, N> const& a){
std::array<T, N-1> ret;
std::copy(a.begin() + 1, a.end(), ret.begin());
return ret;
}
}
template<typename T, dimensionality_type D>
struct initializer_list{
using type = std::initializer_list<typename initializer_list<T, D-1>::type>;
};
template<typename T>
struct initializer_list<T, 1>{using type = std::initializer_list<T>;};
template<typename T, dimensionality_type D>
using initializer_list_t = typename initializer_list<T, D>::type;
template<dimensionality_type D> using index_extensions = typename detail::repeat<index_extension, D>::type;
//template<dimensionality_type D> using iextensions = index_extensions<D>;
template<dimensionality_type D>
struct iextensions : detail::repeat<index_extension, D>::type{
using base_ = typename detail::repeat<index_extension, D>::type;
static constexpr dimensionality_type dimensionality = D;
using base_::base_;
constexpr base_ const& base() const{return *this;}
friend constexpr decltype(auto) base(iextensions const& s){return s.base();}
private:
template <class T, size_t... Is>
constexpr iextensions(std::array<T, static_cast<std::size_t>(D)> const& arr, std::index_sequence<Is...>) : iextensions{arr[Is]...}{}
};
#if defined(__cpp_deduction_guides) and __cpp_deduction_guides >= 201703
template<class... Args> iextensions(Args...) -> iextensions<sizeof...(Args)>;
#endif
template<dimensionality_type D, class Tuple>
constexpr auto contains(index_extensions<D> const& ie, Tuple const& tp){
// using detail::head;
// using detail::tail;
return contains(head(ie), head(tp)) and contains(tail(ie), tail(tp));
}
}}
#if defined(__cpp_structured_bindings) and __cpp_structured_bindings>=201606
namespace std{ // this is for structured binding
template<boost::multi::dimensionality_type D> struct tuple_size<boost::multi::iextensions<D>> : std::integral_constant<size_t, D> { };
template<size_t N, boost::multi::dimensionality_type D> struct tuple_element<N, boost::multi::iextensions<D>> : tuple_element<N, typename boost::multi::iextensions<D>::base_>{};
}
#endif
#if defined(__INCLUDE_LEVEL__) and not __INCLUDE_LEVEL__
//#include<range/v3/begin_end.hpp>
//#include<range/v3/utility/concepts.hpp>
#include<cassert>
#include<iostream>
#include<numeric> // accumulate
#include<vector>
using std::cout;
namespace multi = boost::multi;
template<class T> T what(T&&) = delete;
int main(){
multi::index_extension x(10);
assert( *begin(x) == 0 );
assert( size(x) == 10 );
assert( x[0] == 0 );
assert( x[1] == 1 );
assert( x[9] == 9 );
auto b = begin(x);
assert( b[0] == x[0] );
assert( b[1] == x[1] );
// static_assert( ranges::forward_iterator< std::decay_t<decltype(b)> > , "!");
assert( std::accumulate( begin(x), end(x), 0) == 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 );
std::iterator_traits<std::decay_t<decltype(begin(x))>>::difference_type d; (void)d;
// for(auto i : x) std::cout << i << std::endl;
{
multi::iextensions<3> ies({{0, 3}, {0, 4}, {0, 5}});
assert( std::get<1>(ies).size() == 4 );
auto [is, js, ks] = ies;
assert( is.size() == 3 );
}
}
#endif
#endif
| 29.939394 | 178 | 0.700574 | [
"vector"
] |
29e2c3c0c4ec5b11e1fff533cf3fd8bd331ffff1 | 46,296 | cpp | C++ | libraries/emitters/src/IREmitter.cpp | awf/ELL | 25c94a1422efc41d5560db11b136f9d8f957ad41 | [
"MIT"
] | 1 | 2020-09-18T04:38:45.000Z | 2020-09-18T04:38:45.000Z | libraries/emitters/src/IREmitter.cpp | awesomemachinelearning/ELL | cb897e3aec148a1e9bd648012b5f53ab9d0dd20c | [
"MIT"
] | null | null | null | libraries/emitters/src/IREmitter.cpp | awesomemachinelearning/ELL | cb897e3aec148a1e9bd648012b5f53ab9d0dd20c | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: IREmitter.cpp (emitters)
// Authors: Umesh Madan
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "IREmitter.h"
#include "IRModuleEmitter.h"
#include "EmitterException.h"
#include "LLVMUtilities.h"
#include <utilities/include/Logger.h>
#include <llvm/IR/InstrTypes.h>
#include <llvm/Support/raw_os_ostream.h>
#include <algorithm>
#include <sstream>
namespace ell
{
namespace emitters
{
using namespace logging;
//
// Helpful utility functions in anonymous namespace
//
namespace
{
void ValidateArguments(LLVMFunction f, const IRValueList& args)
{
llvm::FunctionType* fType = f->getFunctionType();
auto numArgs = args.size();
if (f->isVarArg()) // If the function is a varargs function, don't check the extra varargs parameters
{
numArgs = fType->getNumParams();
}
if (numArgs > args.size())
{
throw EmitterException(EmitterError::badFunctionArguments, "wrong number of arguments for function");
}
for (size_t index = 0; index < numArgs; ++index)
{
auto paramType = fType->getParamType(index);
auto argType = args[index]->getType();
if (paramType == nullptr)
{
throw EmitterException(EmitterError::badFunctionDefinition, "function has null parameter type");
}
if (argType == nullptr)
{
throw EmitterException(EmitterError::badFunctionArguments,
"function being called with null parameter type");
}
if (paramType != argType)
{
std::stringstream buffer;
llvm::raw_os_ostream out(buffer);
out << "Wanted ";
paramType->print(out);
out << ", got ";
argType->print(out);
out.flush();
std::string s = buffer.str();
s += ", mismatched types for function " + std::string(f->getName());
throw EmitterException(EmitterError::badFunctionArguments, s);
}
}
}
}; // namespace
//
// IREmitter implementation
//
IREmitter::IREmitter(IRModuleEmitter& moduleEmitter, llvm::LLVMContext& context) :
_moduleEmitter(moduleEmitter),
_llvmContext(context),
_irBuilder(context)
{}
LLVMType IREmitter::Type(VariableType type) const
{
switch (type)
{
case VariableType::Void:
return GetBaseVariableType(type);
case VariableType::VoidPointer:
// We use BytePointer to avoid LLVM Assertion failed: isValidElementType(EltTy) && "Invalid type for pointer element!",
// file ~\llvm-8\lib\ir\type.cpp, line 632
return GetBaseVariableType(VariableType::Byte)->getPointerTo();
case VariableType::Boolean:
return GetBaseVariableType(type);
case VariableType::Byte:
return GetBaseVariableType(type);
case VariableType::BytePointer:
return GetBaseVariableType(VariableType::Byte)->getPointerTo();
case VariableType::Int16:
return GetBaseVariableType(type);
case VariableType::Int16Pointer:
return GetBaseVariableType(VariableType::Int16)->getPointerTo();
case VariableType::Int32:
return GetBaseVariableType(type);
case VariableType::Int32Pointer:
return GetBaseVariableType(VariableType::Int32)->getPointerTo();
case VariableType::Int64:
return GetBaseVariableType(type);
case VariableType::Int64Pointer:
return GetBaseVariableType(VariableType::Int64)->getPointerTo();
case VariableType::Float:
return GetBaseVariableType(type);
case VariableType::FloatPointer:
return GetBaseVariableType(VariableType::Float)->getPointerTo();
case VariableType::Double:
return GetBaseVariableType(type);
case VariableType::DoublePointer:
return GetBaseVariableType(VariableType::Double)->getPointerTo();
case VariableType::Char8:
return GetBaseVariableType(type);
case VariableType::Char8Pointer:
return GetBaseVariableType(VariableType::Char8)->getPointerTo();
default:
throw EmitterException(EmitterError::valueTypeNotSupported);
}
}
llvm::PointerType* IREmitter::PointerType(VariableType type) { return Type(type)->getPointerTo(); }
llvm::PointerType* IREmitter::PointerType(LLVMType type) { return type->getPointerTo(); }
llvm::ArrayType* IREmitter::ArrayType(VariableType type, size_t size)
{
return llvm::ArrayType::get(Type(type), size);
}
llvm::ArrayType* IREmitter::ArrayType(VariableType type, size_t rows, size_t columns)
{
auto rowType = llvm::ArrayType::get(Type(type), columns);
return llvm::ArrayType::get(rowType, rows);
}
llvm::ArrayType* IREmitter::ArrayType(LLVMType type, size_t size) { return llvm::ArrayType::get(type, size); }
llvm::ArrayType* IREmitter::ArrayType(LLVMType type, size_t rows, size_t columns)
{
auto rowType = llvm::ArrayType::get(type, columns);
return llvm::ArrayType::get(rowType, rows);
}
llvm::VectorType* IREmitter::VectorType(VariableType type, size_t size)
{
return llvm::VectorType::get(Type(type), size);
}
llvm::VectorType* IREmitter::VectorType(LLVMType type, size_t size) { return llvm::VectorType::get(type, size); }
llvm::Constant* IREmitter::Literal(const bool value) { return Integer(VariableType::Byte, value ? 1 : 0); }
llvm::Constant* IREmitter::Literal(const int8_t value) { return Integer(VariableType::Char8, value); }
llvm::Constant* IREmitter::Literal(const uint8_t value) { return Integer(VariableType::Byte, value); }
llvm::Constant* IREmitter::Literal(const short value) { return Integer(VariableType::Int16, value); }
llvm::Constant* IREmitter::Literal(const int value) { return Integer(VariableType::Int32, value); }
llvm::Constant* IREmitter::Literal(const int64_t value) { return Integer(VariableType::Int64, value); }
llvm::Constant* IREmitter::Literal(const float value)
{
return llvm::ConstantFP::get(_llvmContext, llvm::APFloat(value));
}
llvm::Constant* IREmitter::Literal(const double value)
{
return llvm::ConstantFP::get(_llvmContext, llvm::APFloat(value));
}
LLVMValue IREmitter::Literal(const char* pValue)
{
assert(pValue != nullptr);
std::string str(pValue);
return Literal(str);
}
LLVMValue IREmitter::Literal(const std::string& value)
{
LLVMValue literal = _stringLiterals.Get(value);
if (literal == nullptr)
{
literal = _irBuilder.CreateGlobalStringPtr(value);
_stringLiterals.Add(value, literal);
}
return literal;
}
llvm::Constant* IREmitter::Literal(const std::vector<uint8_t>& value)
{
return llvm::ConstantDataArray::get(_llvmContext, value);
}
llvm::Constant* IREmitter::Literal(const std::vector<int8_t>& value)
{
return llvm::ConstantDataArray::get(_llvmContext,
llvm::makeArrayRef(reinterpret_cast<const uint8_t*>(value.data()), value.size()));
}
llvm::Constant* IREmitter::Literal(const std::vector<char>& value)
{
return llvm::ConstantDataArray::get(_llvmContext,
llvm::makeArrayRef(reinterpret_cast<const uint8_t*>(value.data()), value.size()));
}
llvm::Constant* IREmitter::Literal(const std::vector<float>& value)
{
return llvm::ConstantDataArray::get(_llvmContext, value);
}
llvm::Constant* IREmitter::Literal(const std::vector<double>& value)
{
return llvm::ConstantDataArray::get(_llvmContext, value);
}
llvm::Constant* IREmitter::Literal(const std::vector<int16_t>& value)
{
return llvm::ConstantDataArray::get(_llvmContext,
llvm::makeArrayRef(reinterpret_cast<const uint16_t*>(value.data()), value.size()));
}
llvm::Constant* IREmitter::Literal(const std::vector<int>& value)
{
return llvm::ConstantDataArray::get(_llvmContext,
llvm::makeArrayRef(reinterpret_cast<const uint32_t*>(value.data()), value.size()));
}
llvm::Constant* IREmitter::Literal(const std::vector<int64_t>& value)
{
return llvm::ConstantDataArray::get(_llvmContext,
llvm::makeArrayRef(reinterpret_cast<const uint64_t*>(value.data()), value.size()));
}
LLVMValue IREmitter::Literal(const std::string& name, const std::string& value)
{
return _irBuilder.CreateGlobalStringPtr(value, name);
}
llvm::Constant* IREmitter::Zero(VariableType type)
{
switch (type)
{
case VariableType::Byte:
case VariableType::Int16:
case VariableType::Int32:
case VariableType::Int64:
return Integer(type, 0);
case VariableType::Float:
case VariableType::Double:
return Literal(0.0);
default:
break;
}
return nullptr;
}
llvm::Constant* IREmitter::Zero(LLVMType type) { return llvm::Constant::getNullValue(type); }
llvm::Constant* IREmitter::True() { return Literal(true); }
llvm::Constant* IREmitter::False() { return Literal(false); }
llvm::Constant* IREmitter::TrueBit() { return llvm::ConstantInt::getTrue(_llvmContext); }
llvm::Constant* IREmitter::FalseBit() { return llvm::ConstantInt::getFalse(_llvmContext); }
llvm::ConstantPointerNull* IREmitter::NullPointer(llvm::PointerType* pointerType)
{
return llvm::ConstantPointerNull::get(pointerType);
}
//
// Typecast
//
LLVMValue IREmitter::CastValue(LLVMValue pValue, VariableType destinationType)
{
return CastValue(pValue, Type(destinationType));
}
LLVMValue IREmitter::CastValue(LLVMValue pValue, LLVMType destinationType)
{
auto inputType = pValue->getType();
auto bitType = llvm::Type::getInt1Ty(_llvmContext);
// Boolean
if (destinationType == bitType)
{
return CastToConditionalBool(pValue);
}
if (inputType == bitType)
{
if (destinationType->isIntegerTy())
{
return CastInt(pValue, destinationType, false);
}
else if (destinationType->isFloatingPointTy())
{
return CastIntToFloat(pValue, destinationType, false);
}
}
else if (inputType->isIntegerTy())
{
if (destinationType->isIntegerTy())
{
return CastInt(pValue, destinationType, true);
}
else if (destinationType->isFloatingPointTy())
{
return CastIntToFloat(pValue, destinationType, true);
}
}
else if (inputType->isFloatingPointTy())
{
if (destinationType->isIntegerTy())
{
return CastFloatToInt(pValue, destinationType, true);
}
else if (destinationType->isFloatingPointTy())
{
return CastFloat(pValue, destinationType);
}
}
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
LLVMValue IREmitter::CastUnsignedValue(LLVMValue pValue, VariableType destinationType)
{
return CastUnsignedValue(pValue, Type(destinationType));
}
LLVMValue IREmitter::CastUnsignedValue(LLVMValue pValue, LLVMType destinationType)
{
auto inputType = pValue->getType();
if (!inputType->isIntegerTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
if (destinationType->isIntegerTy())
{
return CastInt(pValue, destinationType, false);
}
else if (destinationType->isFloatingPointTy())
{
return CastIntToFloat(pValue, destinationType, false);
}
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
LLVMValue IREmitter::BitCast(LLVMValue pValue, VariableType destinationType)
{
return BitCast(pValue, Type(destinationType));
}
LLVMValue IREmitter::BitCast(LLVMValue pValue, LLVMType destinationType)
{
assert(pValue != nullptr);
auto valueType = pValue->getType();
// We can't do a bit cast if the types don't have the same size
if (!llvm::CastInst::isBitCastable(valueType, destinationType))
{
auto currentBlock = _irBuilder.GetInsertBlock();
assert(currentBlock);
auto dataLayout = currentBlock->getModule()->getDataLayout();
auto size1 = dataLayout.getTypeStoreSizeInBits(valueType);
auto size2 = dataLayout.getTypeStoreSizeInBits(destinationType);
if (size1 != 0 && size2 != 0)
{
// unequal sizes: need to bitcast to an int, truncate, then bitcast to destination type
auto intType1 = llvm::Type::getIntNTy(_llvmContext, size1);
auto intType2 = llvm::Type::getIntNTy(_llvmContext, size2);
auto intValue1 = _irBuilder.CreateBitOrPointerCast(pValue, intType1);
auto resizedIntValue = _irBuilder.CreateZExtOrTrunc(intValue1, intType2);
return _irBuilder.CreateBitOrPointerCast(resizedIntValue, destinationType);
}
else
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
}
else
{
return _irBuilder.CreateBitOrPointerCast(pValue, destinationType);
}
}
LLVMValue IREmitter::CastPointer(LLVMValue pValue, VariableType destinationType)
{
return CastPointer(pValue, Type(destinationType));
}
LLVMValue IREmitter::CastPointer(LLVMValue pValue, LLVMType destinationType)
{
assert(pValue != nullptr);
if (!destinationType->isPointerTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
return _irBuilder.CreatePointerCast(pValue, destinationType);
}
LLVMValue IREmitter::CastIntToPointer(LLVMValue pValue, VariableType destinationType)
{
return CastIntToPointer(pValue, Type(destinationType));
}
LLVMValue IREmitter::CastIntToPointer(LLVMValue pValue, LLVMType destinationType)
{
assert(pValue != nullptr);
if (!destinationType->isPointerTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
return _irBuilder.CreateIntToPtr(pValue, destinationType);
}
LLVMValue IREmitter::CastPointerToInt(LLVMValue pValue, VariableType destinationType)
{
return CastPointerToInt(pValue, Type(destinationType));
}
LLVMValue IREmitter::CastPointerToInt(LLVMValue pValue, LLVMType destinationType)
{
assert(pValue != nullptr);
if (!pValue->getType()->isPointerTy() || !destinationType->isIntOrIntVectorTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
return _irBuilder.CreatePtrToInt(pValue, destinationType);
}
LLVMValue IREmitter::CastIntToFloat(LLVMValue pValue, VariableType destinationType, bool isSigned)
{
return CastIntToFloat(pValue, Type(destinationType), isSigned);
}
LLVMValue IREmitter::CastIntToFloat(LLVMValue pValue, LLVMType destinationType, bool isSigned)
{
assert(pValue != nullptr);
if (!pValue->getType()->isIntOrIntVectorTy() || !destinationType->isFPOrFPVectorTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
if (isSigned)
{
return _irBuilder.CreateSIToFP(pValue, destinationType);
}
else
{
return _irBuilder.CreateUIToFP(pValue, destinationType);
}
}
LLVMValue IREmitter::CastFloatToInt(LLVMValue pValue, VariableType destinationType, bool isSigned)
{
return CastFloatToInt(pValue, Type(destinationType), isSigned);
}
LLVMValue IREmitter::CastFloatToInt(LLVMValue pValue, LLVMType destinationType, bool isSigned)
{
assert(pValue != nullptr);
if (!pValue->getType()->isFPOrFPVectorTy() || !destinationType->isIntOrIntVectorTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
if (isSigned)
{
return _irBuilder.CreateFPToSI(pValue, destinationType);
}
else
{
return _irBuilder.CreateFPToUI(pValue, destinationType);
}
}
LLVMValue IREmitter::CastInt(LLVMValue pValue, VariableType destinationType, bool isSigned)
{
return CastInt(pValue, Type(destinationType), isSigned);
}
LLVMValue IREmitter::CastInt(LLVMValue pValue, LLVMType destinationType, bool isSigned)
{
assert(pValue != nullptr);
if (!pValue->getType()->isIntOrIntVectorTy() || !destinationType->isIntOrIntVectorTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
return _irBuilder.CreateIntCast(pValue, destinationType, isSigned);
}
LLVMValue IREmitter::CastFloat(LLVMValue pValue, VariableType destinationType)
{
return CastFloat(pValue, Type(destinationType));
}
LLVMValue IREmitter::CastFloat(LLVMValue pValue, LLVMType destinationType)
{
assert(pValue != nullptr);
if (!pValue->getType()->isFPOrFPVectorTy() || !destinationType->isFPOrFPVectorTy())
{
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
return _irBuilder.CreateFPCast(pValue, destinationType);
}
LLVMValue IREmitter::CastBoolToByte(LLVMValue pValue)
{
return CastInt(pValue, VariableType::Byte, false);
}
LLVMValue IREmitter::CastToConditionalBool(LLVMValue pValue)
{
auto inputType = pValue->getType();
auto bitType = llvm::Type::getInt1Ty(_llvmContext);
if (inputType == bitType)
{
return pValue;
}
else if (inputType->isIntegerTy())
{
return Comparison(TypedComparison::notEquals, pValue, Zero(inputType));
}
else if (inputType->isFloatingPointTy())
{
return Comparison(TypedComparison::notEqualsFloat, pValue, Zero(inputType));
}
throw EmitterException(EmitterError::castNotSupported, "Bad cast");
}
llvm::ReturnInst* IREmitter::ReturnVoid()
{
return _irBuilder.CreateRetVoid();
}
//
// Return
//
llvm::ReturnInst* IREmitter::Return(LLVMValue pValue)
{
assert(pValue != nullptr);
return _irBuilder.CreateRet(pValue);
}
//
// Native LLVM operations / comparisons
//
LLVMValue IREmitter::UnaryOperator(const UnaryOperatorType type, LLVMValue value, const std::string& variableName)
{
assert(value != nullptr);
switch (type)
{
case UnaryOperatorType::logicalNot:
return _irBuilder.CreateNot(value, variableName);
default:
throw EmitterException(EmitterError::operatorTypeNotSupported, "Unsupported unary operator");
}
}
LLVMValue IREmitter::BinaryOperation(const TypedOperator type, LLVMValue pLeftValue, LLVMValue pRightValue, const std::string& variableName)
{
assert(pLeftValue != nullptr);
assert(pRightValue != nullptr);
switch (type)
{
case TypedOperator::add:
return _irBuilder.CreateAdd(pLeftValue, pRightValue, variableName);
case TypedOperator::subtract:
return _irBuilder.CreateSub(pLeftValue, pRightValue, variableName);
case TypedOperator::multiply:
return _irBuilder.CreateMul(pLeftValue, pRightValue, variableName);
case TypedOperator::divideSigned:
return _irBuilder.CreateSDiv(pLeftValue, pRightValue, variableName);
case TypedOperator::moduloSigned:
return _irBuilder.CreateSRem(pLeftValue, pRightValue, variableName);
case TypedOperator::addFloat:
return _irBuilder.CreateFAdd(pLeftValue, pRightValue, variableName);
case TypedOperator::subtractFloat:
return _irBuilder.CreateFSub(pLeftValue, pRightValue, variableName);
case TypedOperator::multiplyFloat:
return _irBuilder.CreateFMul(pLeftValue, pRightValue, variableName);
case TypedOperator::divideFloat:
return _irBuilder.CreateFDiv(pLeftValue, pRightValue, variableName);
case TypedOperator::logicalAnd:
return _irBuilder.CreateAnd(pLeftValue, pRightValue, variableName);
case TypedOperator::logicalOr:
return _irBuilder.CreateOr(pLeftValue, pRightValue, variableName);
case TypedOperator::logicalXor:
return _irBuilder.CreateXor(pLeftValue, pRightValue, variableName);
case TypedOperator::shiftLeft:
return _irBuilder.CreateShl(pLeftValue, pRightValue, variableName);
case TypedOperator::logicalShiftRight:
return _irBuilder.CreateLShr(pLeftValue, pRightValue, variableName);
case TypedOperator::arithmeticShiftRight:
return _irBuilder.CreateAShr(pLeftValue, pRightValue, variableName);
default:
throw EmitterException(EmitterError::operatorTypeNotSupported);
}
}
LLVMValue IREmitter::Comparison(const TypedComparison type, LLVMValue pLeftValue, LLVMValue pRightValue)
{
assert(pLeftValue != nullptr);
assert(pRightValue != nullptr);
switch (type)
{
case TypedComparison::equals:
return _irBuilder.CreateICmpEQ(pLeftValue, pRightValue);
case TypedComparison::lessThan:
return _irBuilder.CreateICmpSLT(pLeftValue, pRightValue);
case TypedComparison::lessThanOrEquals:
return _irBuilder.CreateICmpSLE(pLeftValue, pRightValue);
case TypedComparison::greaterThan:
return _irBuilder.CreateICmpSGT(pLeftValue, pRightValue);
case TypedComparison::greaterThanOrEquals:
return _irBuilder.CreateICmpSGE(pLeftValue, pRightValue);
case TypedComparison::notEquals:
return _irBuilder.CreateICmpNE(pLeftValue, pRightValue);
case TypedComparison::equalsFloat:
return _irBuilder.CreateFCmpOEQ(pLeftValue, pRightValue);
case TypedComparison::lessThanFloat:
return _irBuilder.CreateFCmpOLT(pLeftValue, pRightValue);
case TypedComparison::lessThanOrEqualsFloat:
return _irBuilder.CreateFCmpOLE(pLeftValue, pRightValue);
case TypedComparison::greaterThanFloat:
return _irBuilder.CreateFCmpOGT(pLeftValue, pRightValue);
case TypedComparison::greaterThanOrEqualsFloat:
return _irBuilder.CreateFCmpOGE(pLeftValue, pRightValue);
case TypedComparison::notEqualsFloat:
return _irBuilder.CreateFCmpONE(pLeftValue, pRightValue);
default:
throw EmitterException(EmitterError::comparisonTypeNotSupported);
}
}
LLVMValue IREmitter::Comparison(LLVMValue pValue, bool testValue)
{
assert(pValue != nullptr);
auto boolValue = CastToConditionalBool(pValue);
return Comparison(TypedComparison::equals, boolValue, testValue ? TrueBit() : FalseBit());
}
LLVMValue IREmitter::IsTrue(LLVMValue pValue)
{
return Comparison(pValue, true);
}
LLVMValue IREmitter::IsFalse(LLVMValue pValue)
{
return Comparison(pValue, false);
}
//
// Select
//
LLVMValue IREmitter::Select(LLVMValue pCmp, LLVMValue pTrueValue, LLVMValue pFalseValue)
{
assert(pCmp != nullptr);
assert(pTrueValue != nullptr);
assert(pFalseValue != nullptr);
auto boolValue = CastToConditionalBool(pCmp);
return _irBuilder.CreateSelect(boolValue, pTrueValue, pFalseValue);
}
//
// Functions
//
LLVMFunction IREmitter::DeclareFunction(llvm::Module* pModule, const std::string& name)
{
assert(pModule != nullptr);
auto functionType = llvm::FunctionType::get(_irBuilder.getVoidTy(), false);
return DeclareFunction(pModule, name, functionType);
}
LLVMFunction IREmitter::DeclareFunction(llvm::Module* pModule, const std::string& name, VariableType returnType)
{
auto functionType = llvm::FunctionType::get(Type(returnType), false);
return DeclareFunction(pModule, name, functionType);
}
LLVMFunction IREmitter::DeclareFunction(llvm::Module* pModule, const std::string& name, VariableType returnType, const VariableTypeList& arguments)
{
auto types = GetLLVMTypes(arguments);
auto functionType = llvm::FunctionType::get(Type(returnType), types, false);
return DeclareFunction(pModule, name, functionType);
}
LLVMFunction IREmitter::DeclareFunction(llvm::Module* pModule, const std::string& name, VariableType returnType, const NamedVariableTypeList& arguments)
{
auto types = BindArgumentTypes(arguments);
auto functionType = llvm::FunctionType::get(Type(returnType), types, false);
LLVMFunction pFunction = DeclareFunction(pModule, name, functionType);
BindArgumentNames(pFunction, arguments);
return pFunction;
}
LLVMFunction IREmitter::DeclareFunction(llvm::Module* pModule, const std::string& name, llvm::FunctionType* type)
{
assert(pModule != nullptr);
return static_cast<LLVMFunction>(pModule->getOrInsertFunction(name, type));
}
LLVMFunction IREmitter::Function(llvm::Module* pModule, const std::string& name, VariableType returnType, llvm::Function::LinkageTypes linkage, const VariableTypeList* pArguments)
{
assert(pModule != nullptr);
llvm::FunctionType* pFunctionType = nullptr;
if (pArguments != nullptr)
{
auto types = GetLLVMTypes(*pArguments);
pFunctionType = llvm::FunctionType::get(Type(returnType), types, false);
}
else
{
pFunctionType = llvm::FunctionType::get(Type(returnType), false);
}
return CreateFunction(pModule, name, linkage, pFunctionType);
}
LLVMFunction IREmitter::Function(llvm::Module* pModule, const std::string& name, VariableType returnType, llvm::Function::LinkageTypes linkage, const NamedVariableTypeList& arguments)
{
assert(pModule != nullptr);
auto types = BindArgumentTypes(arguments);
llvm::FunctionType* pFunctionType = llvm::FunctionType::get(Type(returnType), types, false);
LLVMFunction pFunction = CreateFunction(pModule, name, linkage, pFunctionType);
BindArgumentNames(pFunction, arguments);
return pFunction;
}
LLVMFunction IREmitter::Function(llvm::Module* pModule, const std::string& name, LLVMType returnType, llvm::Function::LinkageTypes linkage, const NamedVariableTypeList& arguments)
{
assert(pModule != nullptr);
auto types = BindArgumentTypes(arguments);
LLVMFunction pFunction = Function(pModule, name, returnType, linkage, types);
BindArgumentNames(pFunction, arguments);
return pFunction;
}
LLVMFunction IREmitter::Function(llvm::Module* pModule, const std::string& name, LLVMType returnType, llvm::Function::LinkageTypes linkage, const std::vector<LLVMType>& argTypes)
{
assert(pModule != nullptr);
auto functionType = llvm::FunctionType::get(returnType, argTypes, false);
return CreateFunction(pModule, name, linkage, functionType);
}
LLVMFunction IREmitter::Function(llvm::Module* pModule, const std::string& name, LLVMType returnType, llvm::Function::LinkageTypes linkage, const NamedLLVMTypeList& arguments)
{
assert(pModule != nullptr);
auto types = BindArgumentTypes(arguments);
LLVMFunction pFunction = Function(pModule, name, returnType, linkage, types);
BindArgumentNames(pFunction, arguments);
return pFunction;
}
LLVMFunction IREmitter::Function(llvm::Module* pModule, const std::string& name, LLVMType returnType, llvm::Function::LinkageTypes linkage, const FunctionArgumentList& arguments)
{
assert(pModule != nullptr);
auto types = BindArgumentTypes(arguments);
LLVMFunction pFunction = Function(pModule, name, returnType, linkage, types);
BindArgumentNames(pFunction, arguments);
return pFunction;
}
//
// Blocks
//
llvm::BasicBlock* IREmitter::Block(LLVMFunction pFunction, const std::string& label)
{
assert(pFunction != nullptr);
return llvm::BasicBlock::Create(_llvmContext, label, pFunction);
}
llvm::BasicBlock* IREmitter::BlockBefore(LLVMFunction pFunction, llvm::BasicBlock* pBlock, const std::string& label)
{
assert(pFunction != nullptr);
assert(pBlock != nullptr);
llvm::BasicBlock* pNewBlock = Block(label);
BlockBefore(pFunction, pBlock, pNewBlock);
return pNewBlock;
}
llvm::BasicBlock* IREmitter::BlockBefore(LLVMFunction pFunction, llvm::BasicBlock* pBlock, llvm::BasicBlock* pNewBlock)
{
assert(pFunction != nullptr);
assert(pBlock != nullptr);
assert(pNewBlock != nullptr);
pFunction->getBasicBlockList().insert(pBlock->getIterator(), pNewBlock);
return pNewBlock;
}
llvm::BasicBlock* IREmitter::BlockAfter(LLVMFunction pFunction, llvm::BasicBlock* pBlock, const std::string& label)
{
assert(pFunction != nullptr);
assert(pBlock != nullptr);
llvm::BasicBlock* pNewBlock = Block(label);
BlockAfter(pFunction, pBlock, pNewBlock);
return pNewBlock;
}
llvm::BasicBlock* IREmitter::BlockAfter(LLVMFunction pFunction, llvm::BasicBlock* pBlock, llvm::BasicBlock* pNewBlock)
{
assert(pFunction != nullptr);
assert(pBlock != nullptr);
assert(pNewBlock != nullptr);
pFunction->getBasicBlockList().insertAfter(pBlock->getIterator(), pNewBlock);
return pNewBlock;
}
llvm::BasicBlock* IREmitter::Block(const std::string& label)
{
return llvm::BasicBlock::Create(_llvmContext, label);
}
void IREmitter::SetCurrentBlock(llvm::BasicBlock* pBlock)
{
// assert(pBlock != nullptr);
if (pBlock != nullptr)
{
_irBuilder.SetInsertPoint(pBlock);
}
}
void IREmitter::SetCurrentInsertPoint(llvm::IRBuilder<>::InsertPoint pos) { _irBuilder.restoreIP(pos); }
void IREmitter::SetCurrentInsertPoint(llvm::Instruction* pos) { _irBuilder.SetInsertPoint(pos); }
//
// Calling functions
//
llvm::CallInst* IREmitter::Call(LLVMFunction pFunction)
{
assert(pFunction != nullptr);
return _irBuilder.CreateCall(pFunction, llvm::None);
}
llvm::CallInst* IREmitter::Call(LLVMFunction pFunction, LLVMValue pArgument)
{
assert(pFunction != nullptr);
return _irBuilder.CreateCall(pFunction, pArgument);
}
llvm::CallInst* IREmitter::Call(LLVMFunction pFunction, const IRValueList& arguments)
{
assert(pFunction != nullptr);
ValidateArguments(pFunction, arguments);
return _irBuilder.CreateCall(pFunction, arguments);
}
// Intrinsics / library functions
llvm::CallInst* IREmitter::MemoryMove(LLVMValue pSource, LLVMValue pDestination, LLVMValue pCountBytes)
{
assert(pSource != nullptr);
assert(pDestination != nullptr);
assert(pCountBytes != nullptr);
return _irBuilder.CreateMemMove(pDestination, 0, pSource, 0, pCountBytes);
}
llvm::CallInst* IREmitter::MemoryCopy(LLVMValue pSource, LLVMValue pDestination, LLVMValue pCountBytes)
{
assert(pSource != nullptr);
assert(pDestination != nullptr);
assert(pCountBytes != nullptr);
return _irBuilder.CreateMemCpy(pDestination, 0, pSource, 0, pCountBytes);
}
llvm::CallInst* IREmitter::MemorySet(LLVMValue pDestination, LLVMValue value, LLVMValue size)
{
assert(pDestination != nullptr);
assert(value != nullptr);
return _irBuilder.CreateMemSet(pDestination, value, size, 0);
}
LLVMFunction IREmitter::GetIntrinsic(llvm::Module* pModule, llvm::Intrinsic::ID id, const VariableTypeList& arguments)
{
assert(pModule != nullptr);
auto types = GetLLVMTypes(arguments);
return llvm::Intrinsic::getDeclaration(pModule, id, types);
}
LLVMFunction IREmitter::GetIntrinsic(llvm::Module* pModule, llvm::Intrinsic::ID id, const LLVMTypeList& arguments)
{
assert(pModule != nullptr);
return llvm::Intrinsic::getDeclaration(pModule, id, arguments);
}
llvm::PHINode* IREmitter::Phi(VariableType type, LLVMValue pLeftValue, llvm::BasicBlock* pLeftBlock, LLVMValue pRightValue, llvm::BasicBlock* pRightBlock)
{
assert(pLeftBlock != nullptr);
assert(pRightBlock != nullptr);
assert(pRightValue != nullptr);
assert(pRightBlock != nullptr);
llvm::PHINode* phi = _irBuilder.CreatePHI(Type(type), 2);
phi->addIncoming(pLeftValue, pLeftBlock);
phi->addIncoming(pRightValue, pRightBlock);
return phi;
}
LLVMValue IREmitter::PointerOffset(LLVMValue pArray, LLVMValue pOffset, const std::string& name)
{
assert(pArray != nullptr);
assert(pOffset != nullptr);
return _irBuilder.CreateGEP(pArray, pOffset, name);
}
LLVMValue IREmitter::DereferenceGlobalPointer(LLVMValue pArray)
{
assert(pArray != nullptr);
LLVMValue derefArguments[1]{ Zero() };
return _irBuilder.CreateGEP(pArray, derefArguments);
}
LLVMValue IREmitter::PointerOffset(llvm::GlobalVariable* pArray, LLVMValue pOffset)
{
assert(pArray != nullptr);
assert(pOffset != nullptr);
LLVMValue derefArguments[2]{ Zero(), pOffset };
return _irBuilder.CreateGEP(pArray, derefArguments);
}
// TODO: rename this to avoid clashes with other PointerOffset()
LLVMValue IREmitter::PointerOffset(llvm::GlobalVariable* pArray, LLVMValue pOffset, LLVMValue pFieldOffset)
{
assert(pArray != nullptr);
assert(pOffset != nullptr);
assert(pFieldOffset != nullptr);
LLVMValue derefArguments[3]{ Zero(), pOffset, pFieldOffset };
return _irBuilder.CreateInBoundsGEP(pArray->getValueType(), pArray, derefArguments);
}
LLVMValue IREmitter::PointerOffset(llvm::AllocaInst* pArray, LLVMValue pOffset, LLVMValue pFieldOffset)
{
assert(pArray != nullptr);
assert(pOffset != nullptr);
assert(pFieldOffset != nullptr);
LLVMValue derefArguments[2]{ pOffset, pFieldOffset };
return _irBuilder.CreateInBoundsGEP(pArray, derefArguments);
}
LLVMValue IREmitter::GetStructFieldPointer(LLVMValue structPtr, size_t fieldIndex)
{
auto structPtrType = llvm::dyn_cast<llvm::PointerType>(structPtr->getType());
assert(structPtrType && "Error: must pass pointer to GetStructFieldPointer");
assert(structPtrType->getElementType()->isStructTy() &&
"Error: must pass pointer to a struct type to GetStructFieldPointer");
return _irBuilder.CreateStructGEP(structPtrType->getElementType(), structPtr, fieldIndex);
}
LLVMValue IREmitter::ExtractStructField(LLVMValue structValue, size_t fieldIndex)
{
assert(structValue->getType()->isStructTy() && "Error: must pass a struct type to ExtractStructField");
return _irBuilder.CreateExtractValue(structValue, { static_cast<unsigned int>(fieldIndex) });
}
llvm::LoadInst* IREmitter::Load(LLVMValue pPointer)
{
assert(pPointer != nullptr);
return _irBuilder.CreateLoad(pPointer);
}
llvm::LoadInst* IREmitter::Load(LLVMValue pPointer, const std::string& name)
{
assert(pPointer != nullptr);
return _irBuilder.CreateLoad(pPointer, name);
}
llvm::StoreInst* IREmitter::Store(LLVMValue pPointer, LLVMValue pValue)
{
assert(pPointer != nullptr);
assert(pValue != nullptr);
return _irBuilder.CreateStore(pValue, pPointer);
}
llvm::AllocaInst* IREmitter::StackAllocate(VariableType type)
{
return _irBuilder.CreateAlloca(Type(type), nullptr);
}
llvm::AllocaInst* IREmitter::StackAllocate(LLVMType type) { return _irBuilder.CreateAlloca(type, nullptr); }
llvm::AllocaInst* IREmitter::StackAllocate(VariableType type, const std::string& name)
{
return _irBuilder.CreateAlloca(Type(type), nullptr, name);
}
llvm::AllocaInst* IREmitter::StackAllocate(LLVMType pType, const std::string& name)
{
assert(pType != nullptr);
return _irBuilder.CreateAlloca(pType, nullptr, name);
}
llvm::AllocaInst* IREmitter::StackAllocate(VariableType type, size_t size)
{
return _irBuilder.CreateAlloca(Type(type), Literal(static_cast<int>(size)));
}
llvm::AllocaInst* IREmitter::StackAllocate(VariableType type, size_t rows, size_t columns)
{
auto rowType = ArrayType(Type(type), columns);
return _irBuilder.CreateAlloca(rowType, Literal(static_cast<int>(rows)));
}
llvm::AllocaInst* IREmitter::StackAllocate(LLVMType type, size_t size)
{
return _irBuilder.CreateAlloca(type, Literal(static_cast<int>(size)));
}
llvm::AllocaInst* IREmitter::StackAllocate(LLVMType type, size_t rows, size_t columns)
{
auto rowType = ArrayType(type, columns);
return _irBuilder.CreateAlloca(rowType, Literal(static_cast<int>(rows)));
}
llvm::BranchInst* IREmitter::Branch(LLVMValue pConditionValue, llvm::BasicBlock* pThenBlock, llvm::BasicBlock* pElseBlock)
{
assert(pConditionValue != nullptr);
assert(pThenBlock != nullptr);
assert(pElseBlock != nullptr);
auto boolValue = CastToConditionalBool(pConditionValue);
return _irBuilder.CreateCondBr(boolValue, pThenBlock, pElseBlock);
}
llvm::BranchInst* IREmitter::Branch(llvm::BasicBlock* pDestination)
{
assert(pDestination != nullptr);
return _irBuilder.CreateBr(pDestination);
}
llvm::StructType* IREmitter::DeclareStruct(const std::string& name, const VariableTypeList& fields)
{
llvm::StructType* type = GetStruct(name);
if (type != nullptr)
{
throw EmitterException(EmitterError::duplicateSymbol);
}
LLVMTypeList llvmFields;
for (const auto& field : fields)
{
llvmFields.push_back(Type(field));
}
return DeclareStruct(name, llvmFields);
}
llvm::StructType* IREmitter::DeclareStruct(const std::string& name, const LLVMTypeList& fields)
{
llvm::StructType* type = GetStruct(name);
if (type != nullptr)
{
throw EmitterException(EmitterError::duplicateSymbol);
}
auto structType = llvm::StructType::create(_llvmContext, fields, name);
_structs[name] = structType;
return structType;
}
llvm::StructType* IREmitter::DeclareStruct(const std::string& name, const NamedVariableTypeList& fields)
{
llvm::StructType* type = GetStruct(name);
if (type != nullptr)
{
throw EmitterException(EmitterError::duplicateSymbol);
}
auto types = BindArgumentTypes(fields);
auto structType = llvm::StructType::create(_llvmContext, types, name);
_structs[name] = structType;
return structType;
}
llvm::StructType* IREmitter::GetAnonymousStructType(const LLVMTypeList& fields, bool packed)
{
return llvm::StructType::get(_llvmContext, fields, packed);
}
llvm::StructType* IREmitter::GetStruct(const std::string& name) { return _structs[name]; }
uint64_t IREmitter::SizeOf(LLVMType type) const
{
return _moduleEmitter.GetTargetDataLayout().getTypeAllocSize(type);
}
uint64_t IREmitter::SizeOf(VariableType type) const
{
return SizeOf(Type(type));
}
LLVMType IREmitter::GetBaseVariableType(VariableType type) const
{
switch (type)
{
case VariableType::Void:
return _irBuilder.getVoidTy();
case VariableType::Boolean:
return _irBuilder.getInt1Ty();
case VariableType::Byte:
return _irBuilder.getInt8Ty();
case VariableType::Int16:
return _irBuilder.getInt16Ty();
case VariableType::Int32:
return _irBuilder.getInt32Ty();
case VariableType::Int64:
return _irBuilder.getInt64Ty();
case VariableType::Float:
return _irBuilder.getFloatTy();
case VariableType::Double:
return _irBuilder.getDoubleTy();
case VariableType::Char8:
return _irBuilder.getInt8Ty();
default:
throw EmitterException(EmitterError::valueTypeNotSupported);
}
}
llvm::Constant* IREmitter::Integer(VariableType type, const size_t value)
{
return llvm::ConstantInt::get(_llvmContext, llvm::APInt(SizeOf(type) * 8, value, true));
}
LLVMTypeList IREmitter::GetLLVMTypes(const VariableTypeList& types)
{
LLVMTypeList llvmTypes;
for (auto t : types)
{
if (t == VariableType::VoidPointer)
{
// LLVM doesn't support VoidPointer
t = VariableType::BytePointer;
}
llvmTypes.push_back(Type(t));
}
return llvmTypes;
}
std::vector<LLVMType> IREmitter::BindArgumentTypes(const NamedVariableTypeList& arguments)
{
std::vector<LLVMType> types;
for (auto pair : arguments)
{
VariableType t = pair.second;
if (t == VariableType::VoidPointer)
{
// LLVM doesn't support VoidPointer
t = VariableType::BytePointer;
}
types.push_back(Type(t));
}
return types;
}
std::vector<LLVMType> IREmitter::BindArgumentTypes(const FunctionArgumentList& args)
{
std::vector<LLVMType> types;
for (auto fa : args)
{
VariableType t = fa.GetType();
if (t == VariableType::VoidPointer)
{
// LLVM doesn't support VoidPointer
t = VariableType::BytePointer;
}
types.push_back(Type(t));
}
return types;
}
std::vector<LLVMType> IREmitter::BindArgumentTypes(const NamedLLVMTypeList& arguments)
{
std::vector<LLVMType> types(arguments.size());
std::transform(arguments.begin(), arguments.end(), types.begin(), [](auto argument) {
return argument.second;
});
return types;
}
LLVMFunction IREmitter::CreateFunction(llvm::Module* pModule, const std::string& name, llvm::Function::LinkageTypes linkage, llvm::FunctionType* pFunctionType)
{
LLVMFunction pFunction = llvm::Function::Create(pFunctionType, linkage, name, pModule);
if (pFunction == nullptr)
{
throw EmitterException(EmitterError::functionNotFound);
}
return pFunction;
}
LLVMValue IREmitter::Zero()
{
if (_pZeroLiteral == nullptr)
{
_pZeroLiteral = Literal(0);
}
return _pZeroLiteral;
}
void DebugDump(llvm::Module* module, const std::string& tag, llvm::raw_ostream* stream)
{
auto& targetStream = stream != nullptr ? *stream : llvm::errs();
module->print(targetStream, nullptr, /*ShouldPreserveUseListOrder*/ false, /*IsForDebug*/ true);
if (!tag.empty())
{
targetStream << " [tag = " << tag << "]";
}
targetStream << '\n';
}
void DebugDump(llvm::Type* type, const std::string& tag, llvm::raw_ostream* stream)
{
auto& targetStream = stream != nullptr ? *stream : llvm::errs();
type->print(targetStream, /*IsForDebug*/ true);
if (!tag.empty())
{
targetStream << " [tag = " << tag << "]";
}
targetStream << '\n';
}
void DebugDump(llvm::Value* value, const std::string& tag, llvm::raw_ostream* stream)
{
auto& targetStream = stream != nullptr ? *stream : llvm::errs();
value->print(targetStream, /*IsForDebug*/ true);
if (!tag.empty())
{
targetStream << " [tag = " << tag << "]";
}
targetStream << '\n';
}
void DebugDump(llvm::Function* function, const std::string& tag, llvm::raw_ostream* stream)
{
auto& targetStream = stream != nullptr ? *stream : llvm::errs();
function->print(targetStream, nullptr, false, /*IsForDebug*/ true);
if (!tag.empty())
{
targetStream << " [tag = " << tag << "]";
}
targetStream << '\n';
}
} // namespace emitters
} // namespace ell
| 36.197029 | 187 | 0.636448 | [
"vector",
"transform"
] |
29e8213080c2ed3257af67b0d85683daa8b90d34 | 7,659 | cpp | C++ | gps/gnss/XtraSystemStatusObserver.cpp | atsuisofu/jouletheifos | 9c386eb0df4ec6a923744472ed853173e17461ea | [
"FTL"
] | 17 | 2018-09-15T16:30:19.000Z | 2021-01-30T06:26:20.000Z | gps/gnss/XtraSystemStatusObserver.cpp | atsuisofu/jouletheifos | 9c386eb0df4ec6a923744472ed853173e17461ea | [
"FTL"
] | 1 | 2020-02-16T06:34:35.000Z | 2021-06-14T15:32:35.000Z | gps/gnss/XtraSystemStatusObserver.cpp | atsuisofu/jouletheifos | 9c386eb0df4ec6a923744472ed853173e17461ea | [
"FTL"
] | 9 | 2018-10-08T03:30:27.000Z | 2022-01-11T00:11:20.000Z | /* Copyright (c) 2017, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation, nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#define LOG_TAG "LocSvc_XtraSystemStatusObs"
#include <sys/stat.h>
#include <sys/un.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <cutils/properties.h>
#include <math.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string>
#include <loc_log.h>
#include <loc_nmea.h>
#include <SystemStatus.h>
#include <vector>
#include <sstream>
#include <XtraSystemStatusObserver.h>
#include <LocAdapterBase.h>
#include <DataItemId.h>
#include <DataItemsFactoryProxy.h>
using namespace loc_core;
#define XTRA_HAL_SOCKET_NAME "/data/vendor/location/xtra/socket_hal_xtra"
bool XtraSystemStatusObserver::updateLockStatus(uint32_t lock) {
stringstream ss;
ss << "gpslock";
ss << " " << lock;
ss << "\n"; // append seperator
return ( sendEvent(ss) );
}
bool XtraSystemStatusObserver::updateConnectionStatus(bool connected, uint32_t type) {
stringstream ss;
ss << "connection";
ss << " " << (connected ? "1" : "0");
ss << " " << (int)type;
ss << "\n"; // append seperator
return ( sendEvent(ss) );
}
bool XtraSystemStatusObserver::updateTac(const string& tac) {
stringstream ss;
ss << "tac";
ss << " " << tac.c_str();
ss << "\n"; // append seperator
return ( sendEvent(ss) );
}
bool XtraSystemStatusObserver::updateMccMnc(const string& mccmnc) {
stringstream ss;
ss << "mncmcc";
ss << " " << mccmnc.c_str();
ss << "\n"; // append seperator
return ( sendEvent(ss) );
}
bool XtraSystemStatusObserver::sendEvent(const stringstream& event) {
int socketFd = createSocket();
if (socketFd < 0) {
LOC_LOGe("XTRA unreachable. sending failed.");
return false;
}
const string& data = event.str();
int remain = data.length();
ssize_t sent = 0;
while (remain > 0 &&
(sent = ::send(socketFd, data.c_str() + (data.length() - remain),
remain, MSG_NOSIGNAL)) > 0) {
remain -= sent;
}
if (sent < 0) {
LOC_LOGe("sending error. reason:%s", strerror(errno));
}
closeSocket(socketFd);
return (remain == 0);
}
int XtraSystemStatusObserver::createSocket() {
int socketFd = -1;
if ((socketFd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
LOC_LOGe("create socket error. reason:%s", strerror(errno));
} else {
const char* socketPath = XTRA_HAL_SOCKET_NAME ;
struct sockaddr_un addr = { .sun_family = AF_UNIX };
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socketPath);
if (::connect(socketFd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
LOC_LOGe("cannot connect to XTRA. reason:%s", strerror(errno));
if (::close(socketFd)) {
LOC_LOGe("close socket error. reason:%s", strerror(errno));
}
socketFd = -1;
}
}
return socketFd;
}
void XtraSystemStatusObserver::closeSocket(const int socketFd) {
if (socketFd >= 0) {
if(::close(socketFd)) {
LOC_LOGe("close socket error. reason:%s", strerror(errno));
}
}
}
void XtraSystemStatusObserver::subscribe(bool yes)
{
// Subscription data list
list<DataItemId> subItemIdList;
subItemIdList.push_back(NETWORKINFO_DATA_ITEM_ID);
subItemIdList.push_back(MCCMNC_DATA_ITEM_ID);
if (yes) {
mSystemStatusObsrvr->subscribe(subItemIdList, this);
list<DataItemId> reqItemIdList;
reqItemIdList.push_back(TAC_DATA_ITEM_ID);
mSystemStatusObsrvr->requestData(reqItemIdList, this);
} else {
mSystemStatusObsrvr->unsubscribe(subItemIdList, this);
}
}
// IDataItemObserver overrides
void XtraSystemStatusObserver::getName(string& name)
{
name = "XtraSystemStatusObserver";
}
void XtraSystemStatusObserver::notify(const list<IDataItemCore*>& dlist)
{
struct handleOsObserverUpdateMsg : public LocMsg {
XtraSystemStatusObserver* mXtraSysStatObj;
list <IDataItemCore*> mDataItemList;
inline handleOsObserverUpdateMsg(XtraSystemStatusObserver* xtraSysStatObs,
const list<IDataItemCore*>& dataItemList) :
mXtraSysStatObj(xtraSysStatObs) {
for (auto eachItem : dataItemList) {
IDataItemCore* dataitem = DataItemsFactoryProxy::createNewDataItem(
eachItem->getId());
if (NULL == dataitem) {
break;
}
// Copy the contents of the data item
dataitem->copy(eachItem);
mDataItemList.push_back(dataitem);
}
}
inline ~handleOsObserverUpdateMsg() {
for (auto each : mDataItemList) {
delete each;
}
}
inline void proc() const {
for (auto each : mDataItemList) {
switch (each->getId())
{
case NETWORKINFO_DATA_ITEM_ID:
{
SystemStatusNetworkInfo* networkInfo =
reinterpret_cast<SystemStatusNetworkInfo*>(each);
mXtraSysStatObj->updateConnectionStatus(networkInfo->mConnected,
networkInfo->mType);
}
break;
case TAC_DATA_ITEM_ID:
{
SystemStatusTac* tac = reinterpret_cast<SystemStatusTac*>(each);
mXtraSysStatObj->updateTac(tac->mValue);
}
break;
case MCCMNC_DATA_ITEM_ID:
{
SystemStatusMccMnc* mccmnc = reinterpret_cast<SystemStatusMccMnc*>(each);
mXtraSysStatObj->updateMccMnc(mccmnc->mValue);
}
break;
default:
break;
}
}
}
};
mMsgTask->sendMsg(new (nothrow) handleOsObserverUpdateMsg(this, dlist));
}
| 32.45339 | 97 | 0.614441 | [
"vector"
] |
29eb94d17d728c5644ac7be2b2fa0d5388e2c210 | 9,293 | cpp | C++ | REDSI_1160929_1161573/boost_1_67_0/libs/math/tools/bessel_derivative_append_negative.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 85 | 2015-02-08T20:36:17.000Z | 2021-11-14T20:38:31.000Z | libs/boost/libs/math/tools/bessel_derivative_append_negative.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/boost/libs/math/tools/bessel_derivative_append_negative.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 27 | 2015-01-28T16:33:30.000Z | 2021-08-12T05:04:39.000Z | // Copyright (c) 2014 Anton Bikineev
// Use, modification and distribution are subject to 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)
//
// Appends negative test cases to the *.ipp files.
// Takes the next parameters:
// -f <file> file where the negative values will be appended;
// -x add minus to existing x values and append result;
// -v, -xv like previous option.
// Usage example:
// ./bessel_derivative_append_negative -f "bessel_y_derivative_large_data.ipp" -x -v -xv
#include <fstream>
#include <utility>
#include <functional>
#include <map>
#include <vector>
#include <iterator>
#include <algorithm>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/math/special_functions/bessel.hpp>
template <class T>
T bessel_j_derivative_bare(T v, T x)
{
return (v / x) * boost::math::cyl_bessel_j(v, x) - boost::math::cyl_bessel_j(v+1, x);
}
template <class T>
T bessel_y_derivative_bare(T v, T x)
{
return (v / x) * boost::math::cyl_neumann(v, x) - boost::math::cyl_neumann(v+1, x);
}
template <class T>
T bessel_i_derivative_bare(T v, T x)
{
return (v / x) * boost::math::cyl_bessel_i(v, x) + boost::math::cyl_bessel_i(v+1, x);
}
template <class T>
T bessel_k_derivative_bare(T v, T x)
{
return (v / x) * boost::math::cyl_bessel_k(v, x) - boost::math::cyl_bessel_k(v+1, x);
}
template <class T>
T sph_bessel_j_derivative_bare(T v, T x)
{
if((v < 0) || (floor(v) != v))
throw std::domain_error("");
if(v == 0)
return -boost::math::sph_bessel(1, x);
return boost::math::sph_bessel(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_bessel(itrunc(v), x);
}
template <class T>
T sph_bessel_y_derivative_bare(T v, T x)
{
if((v < 0) || (floor(v) != v))
throw std::domain_error("");
if(v == 0)
return -boost::math::sph_neumann(1, x);
return boost::math::sph_neumann(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_neumann(itrunc(v), x);
}
namespace opt = boost::program_options;
using FloatType = boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<200u> >;
using Function = FloatType(*)(FloatType, FloatType);
using Lines = std::vector<std::string>;
enum class Negate: char
{
x,
v,
xv
};
namespace
{
const unsigned kSignificand = 50u;
std::map<std::string, Function> kFileMapper = {
{"bessel_j_derivative_data.ipp", ::bessel_j_derivative_bare},
{"bessel_j_derivative_int_data.ipp", ::bessel_j_derivative_bare},
{"bessel_j_derivative_large_data.ipp", ::bessel_j_derivative_bare},
{"bessel_y01_derivative_data.ipp", ::bessel_y_derivative_bare},
{"bessel_yn_derivative_data.ipp", ::bessel_y_derivative_bare},
{"bessel_yv_derivative_data.ipp", ::bessel_y_derivative_bare},
{"bessel_i_derivative_data.ipp", ::bessel_i_derivative_bare},
{"bessel_i_derivative_int_data.ipp", ::bessel_i_derivative_bare},
{"bessel_k_derivative_data.ipp", ::bessel_k_derivative_bare},
{"bessel_k_derivative_int_data.ipp", ::bessel_k_derivative_bare},
{"sph_bessel_derivative_data.ipp", ::sph_bessel_j_derivative_bare},
{"sph_neumann_derivative_data.ipp", ::sph_bessel_y_derivative_bare}
};
Function fp = ::bessel_j_derivative_bare;
Lines getSourcePartOfFile(std::fstream& file)
{
file.seekg(std::ios::beg);
Lines lines;
while (true)
{
auto line = std::string{};
std::getline(file, line);
if (line.find("}};") != std::string::npos)
break;
lines.push_back(line);
}
file.seekg(std::ios::beg);
return lines;
}
std::pair<std::string, std::string::iterator> parseValue(std::string::iterator& iter)
{
using std::isdigit;
auto value = std::string{};
auto iterator = std::string::iterator{};
while (!isdigit(*iter) && *iter != '-')
++iter;
iterator = iter;
while (isdigit(*iter) || *iter == '.' || *iter == 'e' || *iter == '-' || *iter == '+')
{
value.push_back(*iter);
++iter;
}
return {value, iterator};
}
void addMinusToValue(std::string& line, Negate which)
{
using std::isdigit;
auto iter = line.begin();
switch (which)
{
case Negate::x:
{
::parseValue(iter);
auto value_begin = ::parseValue(iter).second;
if (*value_begin != '-')
line.insert(value_begin, '-');
break;
}
case Negate::v:
{
auto value_begin = ::parseValue(iter).second;
if (*value_begin != '-')
line.insert(value_begin, '-');
break;
}
case Negate::xv:
{
auto v_value_begin = ::parseValue(iter).second;
if (*v_value_begin != '-')
line.insert(v_value_begin, '-');
// iterator could get invalid
iter = line.begin();
::parseValue(iter);
auto x_value_begin = ::parseValue(iter).second;
if (*x_value_begin != '-')
line.insert(x_value_begin, '-');
break;
}
}
}
void replaceResultInLine(std::string& line)
{
using std::isdigit;
auto iter = line.begin();
// parse v and x values from line and convert them to FloatType
auto v = FloatType{::parseValue(iter).first};
auto x = FloatType{::parseValue(iter).first};
auto result = fp(v, x).str(kSignificand);
while (!isdigit(*iter) && *iter != '-')
++iter;
const auto where_to_write = iter;
while (isdigit(*iter) || *iter == '.' || *iter == 'e' || *iter == '-' || *iter == '+')
line.erase(iter);
line.insert(where_to_write, result.begin(), result.end());
}
Lines processValues(const Lines& source_lines, Negate which)
{
using std::placeholders::_1;
auto processed_lines = source_lines;
std::for_each(std::begin(processed_lines), std::end(processed_lines), std::bind(&addMinusToValue, _1, which));
std::for_each(std::begin(processed_lines), std::end(processed_lines), &replaceResultInLine);
return processed_lines;
}
void updateTestCount(Lines& source_lines, std::size_t mult)
{
using std::isdigit;
const auto where = std::find_if(std::begin(source_lines), std::end(source_lines),
[](const std::string& str){ return str.find("boost::array") != std::string::npos; });
auto& str = *where;
const auto pos = str.find(">, ") + 3;
auto digits_length = 0;
auto k = pos;
while (isdigit(str[k++]))
++digits_length;
const auto new_value = mult * boost::lexical_cast<std::size_t>(str.substr(pos, digits_length));
str.replace(pos, digits_length, boost::lexical_cast<std::string>(new_value));
}
} // namespace
int main(int argc, char*argv [])
{
auto desc = opt::options_description{"All options"};
desc.add_options()
("help", "produce help message")
("file", opt::value<std::string>()->default_value("bessel_j_derivative_data.ipp"))
("x", "append negative x")
("v", "append negative v")
("xv", "append negative x and v");
opt::variables_map vm;
opt::store(opt::command_line_parser(argc, argv).options(desc)
.style(opt::command_line_style::default_style |
opt::command_line_style::allow_long_disguise)
.run(),vm);
opt::notify(vm);
if (vm.count("help"))
{
std::cout << desc;
return 0;
}
auto filename = vm["file"].as<std::string>();
fp = kFileMapper[filename];
std::fstream file{filename.c_str()};
if (!file.is_open())
return -1;
auto source_part = ::getSourcePartOfFile(file);
source_part.back().push_back(',');
auto cases_lines = Lines{};
for (const auto& str: source_part)
{
if (str.find("SC_") != std::string::npos)
cases_lines.push_back(str);
}
auto new_lines = Lines{};
new_lines.reserve(cases_lines.size());
std::size_t mult = 1;
if (vm.count("x"))
{
std::cout << "process x..." << std::endl;
const auto x_lines = ::processValues(cases_lines, Negate::x);
new_lines.insert(std::end(new_lines), std::begin(x_lines), std::end(x_lines));
++mult;
}
if (vm.count("v"))
{
std::cout << "process v..." << std::endl;
const auto v_lines = ::processValues(cases_lines, Negate::v);
new_lines.insert(std::end(new_lines), std::begin(v_lines), std::end(v_lines));
++mult;
}
if (vm.count("xv"))
{
std::cout << "process xv..." << std::endl;
const auto xv_lines = ::processValues(cases_lines, Negate::xv);
new_lines.insert(std::end(new_lines), std::begin(xv_lines), std::end(xv_lines));
++mult;
}
source_part.insert(std::end(source_part), std::begin(new_lines), std::end(new_lines));
::updateTestCount(source_part, mult);
file.close();
file.open(filename, std::ios::out | std::ios::trunc);
std::for_each(std::begin(source_part), std::end(source_part), [&file](const std::string& str)
{ file << str << std::endl; });
file << " }};";
std::cout << "processed, ok\n";
return 0;
}
| 30.369281 | 114 | 0.61358 | [
"vector"
] |
29ec5d0166563dccbe5fd58d25fdc74b8c84150e | 2,285 | hpp | C++ | include/LIEF/PE/utils.hpp | lkollar/LIEF | 04037644af42c75fbace582bd2eb64c061a197e5 | [
"Apache-2.0"
] | 4 | 2020-09-19T21:23:47.000Z | 2020-10-02T19:17:04.000Z | include/LIEF/PE/utils.hpp | lkollar/LIEF | 04037644af42c75fbace582bd2eb64c061a197e5 | [
"Apache-2.0"
] | 1 | 2020-10-05T15:19:24.000Z | 2020-10-05T15:19:24.000Z | include/LIEF/PE/utils.hpp | lkollar/LIEF | 04037644af42c75fbace582bd2eb64c061a197e5 | [
"Apache-2.0"
] | 1 | 2020-11-06T23:32:07.000Z | 2020-11-06T23:32:07.000Z | /* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIEF_PE_UTILS_H_
#define LIEF_PE_UTILS_H_
#include <list>
#include <string>
#include <locale>
#include <memory>
#include "LIEF/visibility.h"
#include "LIEF/PE/Section.hpp"
#include "LIEF/PE/Import.hpp"
namespace LIEF {
namespace PE {
//! @brief check if the `file` is a PE file
LIEF_API bool is_pe(const std::string& file);
//! @brief check if the raw data is a PE file
LIEF_API bool is_pe(const std::vector<uint8_t>& raw);
//! @brief if the input `file` is a PE one, return `PE32` or `PE32+`
LIEF_API PE_TYPE get_type(const std::string& file);
//! @brief Return `PE32` or `PE32+`
LIEF_API PE_TYPE get_type(const std::vector<uint8_t>& raw);
//! @brief Compute the hash of imported functions
//!
//! Properties of the hash generated:
//! * Order agnostic
//! * Casse agnostic
//! * Ordinal (**in some extent**) agnostic
//!
//! @warning The algorithm used to compute the *imphash* value has some variations compared to Yara, pefile, VT implementation
//!
//! @see https://www.fireeye.com/blog/threat-research/2014/01/tracking-malware-import-hashing.html
LIEF_API std::string get_imphash(const Binary& binary);
//! @brief Take a PE::Import as entry and try to resolve imports
//! by ordinal.
//!
//! The ``strict`` boolean parameter enables to throw an LIEF::not_found exception
//! if the ordinal can't be resolved. Otherwise it skips the entry.
//!
//! @param[in] import Import to resolve
//! @param[in] strict If set to ``true``, throw an exception if the import can't be resolved
//! @param[out] Import The import resolved: PE::ImportEntry::name is set
LIEF_API Import resolve_ordinals(const Import& import, bool strict=false);
}
}
#endif
| 33.115942 | 126 | 0.723414 | [
"vector"
] |
29ecc8ceb802500458d3f29b2d18013620df76f6 | 7,737 | hpp | C++ | src/kre/DisplayDevice.hpp | sweetkristas/Castles | 1d68e74937e89cf5e0f8c9f6bd2bb2252ccc4c1b | [
"MIT"
] | null | null | null | src/kre/DisplayDevice.hpp | sweetkristas/Castles | 1d68e74937e89cf5e0f8c9f6bd2bb2252ccc4c1b | [
"MIT"
] | null | null | null | src/kre/DisplayDevice.hpp | sweetkristas/Castles | 1d68e74937e89cf5e0f8c9f6bd2bb2252ccc4c1b | [
"MIT"
] | null | null | null | /*
Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include <functional>
#include <map>
#include <memory>
#include <string>
#include "DisplayDeviceFwd.hpp"
#include "geometry.hpp"
#include "PixelFormat.hpp"
#include "Renderable.hpp"
#include "StencilSettings.hpp"
#include "variant.hpp"
namespace KRE
{
enum class DisplayDeviceCapabilties {
NPOT_TEXTURES,
BLEND_EQUATION_SEPERATE,
RENDER_TO_TEXTURE,
SHADERS,
UNIFORM_BUFFERS,
};
enum class DisplayDeviceParameters {
MAX_TEXTURE_UNITS,
};
enum class ClearFlags {
COLOR = 1,
DEPTH = 2,
STENCIL = 4,
ALL = 0x7fffffff,
};
inline ClearFlags operator|(ClearFlags l, ClearFlags r)
{
return static_cast<ClearFlags>(static_cast<int>(l) | static_cast<int>(r));
}
inline bool operator&(ClearFlags l, ClearFlags r)
{
return (static_cast<int>(l) & static_cast<int>(r)) != 0;
}
enum class ReadFormat {
DEPTH,
STENCIL,
DEPTH_STENCIL,
RED,
GREEN,
BLUE,
RG,
RGB,
BGR,
RGBA,
BGRA,
RED_INT,
GREEN_INT,
BLUE_INT,
RG_INT,
RGB_INT,
BGR_INT,
RGBA_INT,
BGRA_INT,
};
class DisplayDevice
{
public:
enum DisplayDeviceId {
// Display device is OpenGL 2.1 compatible, using shaders.
DISPLAY_DEVICE_OPENGL,
// Display device is OpenGLES 2.0, using shaders
DISPLAY_DEVICE_OPENGLES,
// Display device is OpenGL 1.1, fixed function pipeline
DISPLAY_DEVICE_OPENGL_FIXED,
// Display device is whatever SDL wants to use
DISPLAY_DEVICE_SDL,
// Display device is Direct3D
DISPLAY_DEVICE_D3D,
};
explicit DisplayDevice(WindowPtr wnd);
virtual ~DisplayDevice();
virtual DisplayDeviceId ID() const = 0;
virtual void setClearColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) const;
virtual void setClearColor(float r, float g, float b, float a) const = 0;
virtual void setClearColor(const Color& color) const = 0;
virtual void clear(ClearFlags clr) = 0;
virtual void swap() = 0;
virtual void init(int width, int height) = 0;
virtual void printDeviceInfo() = 0;
virtual void render(const Renderable* r) const = 0;
virtual void clearTextures() = 0;
static TexturePtr createTexture(const SurfacePtr& surface, TextureType type, int mipmap_levels);
static TexturePtr createTexture(const SurfacePtr& surface, const variant& node);
static TexturePtr createTexture1D(int width, PixelFormat::PF fmt);
static TexturePtr createTexture2D(int width, int height, PixelFormat::PF fmt);
static TexturePtr createTexture3D(int width, int height, int depth, PixelFormat::PF fmt);
static TexturePtr createTextureArray(int count, int width, int height, PixelFormat::PF fmt, TextureType type);
static TexturePtr createTextureArray(const std::vector<SurfacePtr>& surfaces, const variant& node);
virtual CanvasPtr getCanvas() = 0;
virtual ClipScopePtr createClipScope(const rect& r) = 0;
virtual StencilScopePtr createStencilScope(const StencilSettings& settings) = 0;
virtual ScissorPtr getScissor(const rect& r) = 0;
virtual CameraPtr setDefaultCamera(const CameraPtr& cam) = 0;
virtual void loadShadersFromVariant(const variant& node) = 0;
virtual ShaderProgramPtr getShaderProgram(const std::string& name) = 0;
virtual ShaderProgramPtr getShaderProgram(const variant& node) = 0;
virtual ShaderProgramPtr getDefaultShader() = 0;
virtual int queryParameteri(DisplayDeviceParameters param) = 0;
virtual BlendEquationImplBasePtr getBlendEquationImpl() = 0;
virtual EffectPtr createEffect(const variant& node) = 0;
static void blitTexture(const TexturePtr& tex, int dstx, int dsty, int dstw, int dsth, float rotation, int srcx, int srcy, int srcw, int srch);
static RenderTargetPtr renderTargetInstance(int width, int height,
int color_plane_count=1,
bool depth=false,
bool stencil=false,
bool use_multi_sampling=false,
int multi_samples=0);
static RenderTargetPtr renderTargetInstance(const variant& node);
virtual void setViewPort(const rect& vp) = 0;
virtual void setViewPort(int x, int y, int width, int height) = 0;
virtual const rect& getViewPort() const = 0;
template<typename T>
bool readPixels(int x, int y, unsigned width, unsigned height, ReadFormat fmt, AttrFormat type, std::vector<T>& data, int stride) {
data.resize(stride * height / sizeof(T));
return handleReadPixels(x, y, width, height, fmt, type, static_cast<void*>(&data[0]), stride);
}
WindowPtr getParentWindow() const;
static AttributeSetPtr createAttributeSet(bool hardware_hint=false, bool indexed=false, bool instanced=false);
static HardwareAttributePtr createAttributeBuffer(bool hw_backed, AttributeBase* parent);
static DisplayDevicePtr factory(const std::string& type, WindowPtr wnd);
static DisplayDevicePtr getCurrent();
static bool checkForFeature(DisplayDeviceCapabilties cap);
static void registerFactoryFunction(const std::string& type, std::function<DisplayDevicePtr(WindowPtr)>);
private:
std::weak_ptr<Window> parent_;
DisplayDevice();
DisplayDevice(const DisplayDevice&);
virtual AttributeSetPtr handleCreateAttributeSet(bool indexed, bool instanced) = 0;
virtual HardwareAttributePtr handleCreateAttribute(AttributeBase* parent) = 0;
virtual RenderTargetPtr handleCreateRenderTarget(int width, int height,
int color_plane_count,
bool depth,
bool stencil,
bool use_multi_sampling,
int multi_samples) = 0;
virtual RenderTargetPtr handleCreateRenderTarget(const variant& node) = 0;
virtual bool handleReadPixels(int x, int y, unsigned width, unsigned height, ReadFormat fmt, AttrFormat type, void* data, int stride) = 0;
virtual TexturePtr handleCreateTexture(const SurfacePtr& surface, TextureType type, int mipmap_levels) = 0;
virtual TexturePtr handleCreateTexture(const SurfacePtr& surface, const variant& node) = 0;
virtual TexturePtr handleCreateTexture1D(int width, PixelFormat::PF fmt) = 0;
virtual TexturePtr handleCreateTexture2D(int width, int height, PixelFormat::PF fmt) = 0;
virtual TexturePtr handleCreateTexture3D(int width, int height, int depth, PixelFormat::PF fmt) = 0;
virtual TexturePtr handleCreateTextureArray(int count, int width, int height, PixelFormat::PF fmt, TextureType type) = 0;
virtual TexturePtr handleCreateTextureArray(const std::vector<SurfacePtr>& surfaces, const variant& node) = 0;
virtual bool doCheckForFeature(DisplayDeviceCapabilties cap) = 0;
virtual void doBlitTexture(const TexturePtr& tex, int dstx, int dsty, int dstw, int dsth, float rotation, int srcx, int srcy, int srcw, int srch) = 0;
};
template<class T>
struct DisplayDeviceRegistrar
{
DisplayDeviceRegistrar(const std::string& type)
{
// register the class factory function
DisplayDevice::registerFactoryFunction(type, [](WindowPtr wnd) -> DisplayDevicePtr { return DisplayDevicePtr(new T(wnd));});
}
};
}
| 33.493506 | 152 | 0.752876 | [
"geometry",
"render",
"vector"
] |
29ecef5df1f65e58c01ea5e6e6b41400b8bf3cad | 9,516 | cpp | C++ | Engine/source/afx/afxSpellBook.cpp | John3/faustlogic_Torque3D-plus-AFX | 45ea3c81707c944792cd785f87e86bc8085f654a | [
"Unlicense"
] | 13 | 2015-04-13T21:46:01.000Z | 2017-11-20T22:12:04.000Z | Engine/source/afx/afxSpellBook.cpp | John3/faustlogic_Torque3D-plus-AFX | 45ea3c81707c944792cd785f87e86bc8085f654a | [
"Unlicense"
] | 1 | 2015-11-16T23:57:12.000Z | 2015-12-01T03:24:08.000Z | Engine/source/afx/afxSpellBook.cpp | John3/faustlogic_Torque3D-plus-AFX | 45ea3c81707c944792cd785f87e86bc8085f654a | [
"Unlicense"
] | 7 | 2015-04-14T23:27:16.000Z | 2022-03-29T00:45:37.000Z |
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
// Copyright (C) 2015 Faust Logic, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
#include "afx/arcaneFX.h"
#include "console/engineAPI.h"
#include "console/consoleTypes.h"
#include "core/stream/bitStream.h"
#include "T3D/gameBase/gameBase.h"
#include "afx/afxSpellBook.h"
#include "afx/afxMagicSpell.h"
#include "afx/rpg/afxRPGMagicSpell.h"
#include "afx/ui/afxSpellButton.h"
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxSpellBookData
IMPLEMENT_CO_DATABLOCK_V1(afxSpellBookData);
ConsoleDocClass( afxSpellBookData,
"@brief A spellbook datablock.\n\n"
"@ingroup afxMisc\n"
"@ingroup AFX\n"
"@ingroup Datablocks\n"
);
afxSpellBookData::afxSpellBookData()
{
spells_per_page = 12;
pages_per_book = 12;
dMemset(spells, 0, sizeof(spells));
dMemset(rpg_spells, 0, sizeof(rpg_spells));
// marked true if datablock ids need to
// be converted into pointers
do_id_convert = false;
}
#define myOffset(field) Offset(field, afxSpellBookData)
void afxSpellBookData::initPersistFields()
{
addField("spellsPerPage", TypeS8, myOffset(spells_per_page),
"...");
addField("pagesPerBook", TypeS8, myOffset(pages_per_book),
"...");
addField("spells", TYPEID<GameBaseData>(), myOffset(spells), MAX_PAGES_PER_BOOK*MAX_SPELLS_PER_PAGE,
"...");
addField("rpgSpells", TYPEID<GameBaseData>(), myOffset(rpg_spells), MAX_PAGES_PER_BOOK*MAX_SPELLS_PER_PAGE,
"...");
Parent::initPersistFields();
}
bool afxSpellBookData::preload(bool server, String &errorStr)
{
if (!Parent::preload(server, errorStr))
return false;
// Resolve objects transmitted from server
if (!server)
{
if (do_id_convert)
{
for (S32 i = 0; i < pages_per_book*spells_per_page; i++)
{
SimObjectId db_id = (SimObjectId) rpg_spells[i];
if (db_id != 0)
{
// try to convert id to pointer
if (!Sim::findObject(db_id, rpg_spells[i]))
{
Con::errorf(ConsoleLogEntry::General,
"afxSpellBookData::preload() -- bad datablockId: 0x%x (afxRPGMagicSpellData)",
db_id);
}
}
}
do_id_convert = false;
}
}
return true;
}
void afxSpellBookData::packData(BitStream* stream)
{
Parent::packData(stream);
stream->write(spells_per_page);
stream->write(pages_per_book);
for (S32 i = 0; i < pages_per_book*spells_per_page; i++)
writeDatablockID(stream, rpg_spells[i], packed);
}
void afxSpellBookData::unpackData(BitStream* stream)
{
Parent::unpackData(stream);
stream->read(&spells_per_page);
stream->read(&pages_per_book);
do_id_convert = true;
for (S32 i = 0; i < pages_per_book*spells_per_page; i++)
rpg_spells[i] = (afxRPGMagicSpellData*) readDatablockID(stream);
}
DefineEngineMethod(afxSpellBookData, getPageSlotIndex, S32, (Point2I bookSlot),,
"...\n\n"
"@ingroup AFX")
{
return object->getPageSlotIndex(bookSlot.x, bookSlot.y);
}
DefineEngineMethod(afxSpellBookData, getCapacity, S32, (),,
"Get the capacity (total number of spell slots) in a spellbook.\n\n"
"@ingroup AFX")
{
return object->spells_per_page*object->pages_per_book;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxSpellBook
IMPLEMENT_CO_NETOBJECT_V1(afxSpellBook);
ConsoleDocClass( afxSpellBook,
"@brief A spellbook object.\n\n"
"@ingroup afxMisc\n"
"@ingroup AFX\n"
);
afxSpellBook::afxSpellBook()
{
mNetFlags.set(Ghostable | ScopeAlways);
mDataBlock = NULL;
all_spell_cooldown = 1.0f;
}
afxSpellBook::~afxSpellBook()
{
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
void afxSpellBook::initPersistFields()
{
Parent::initPersistFields();
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
void afxSpellBook::processTick(const Move* m)
{
Parent::processTick(m);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
void afxSpellBook::advanceTime(F32 dt)
{
Parent::advanceTime(dt);
if (all_spell_cooldown < 1.0f)
{
all_spell_cooldown += dt/2.0f;
if (all_spell_cooldown > 1.0f)
all_spell_cooldown = 1.0f;
}
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
bool afxSpellBook::onNewDataBlock(GameBaseData* dptr, bool reload)
{
mDataBlock = dynamic_cast<afxSpellBookData*>(dptr);
if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
return false;
scriptOnNewDataBlock();
return true;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
bool afxSpellBook::onAdd()
{
if (!Parent::onAdd())
return(false);
return(true);
}
void afxSpellBook::onRemove()
{
Parent::onRemove();
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
U32 afxSpellBook::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
if (stream->writeFlag(mask & InitialUpdateMask))
{
}
// AllSpellCooldown
if (stream->writeFlag(mask & AllSpellCooldownMask))
{
}
return(retMask);
}
void afxSpellBook::unpackUpdate(NetConnection * con, BitStream * stream)
{
Parent::unpackUpdate(con, stream);
// InitialUpdate
if (stream->readFlag())
{
}
// AllSpellCooldown
if (stream->readFlag())
{
all_spell_cooldown = 0.0f;
}
}
#define SPELL_DATA_NOT_FOUND "\n<just:center><font:Arial:20><color:FF0000>** Spell data not found **\n\n\n\n"
char* afxSpellBook::formatDesc(char* buffer, int len, S32 page, S32 slot) const
{
S32 idx = mDataBlock->getPageSlotIndex(page, slot);
if (idx < 0 || !mDataBlock->rpg_spells[idx])
return SPELL_DATA_NOT_FOUND;
return mDataBlock->rpg_spells[idx]->formatDesc(buffer, len);
}
const char* afxSpellBook::getSpellIcon(S32 page, S32 slot) const
{
S32 idx = mDataBlock->getPageSlotIndex(page, slot);
if (idx < 0 || !mDataBlock->rpg_spells[idx])
return 0;
return mDataBlock->rpg_spells[idx]->icon_name;
}
bool afxSpellBook::isPlaceholder(S32 page, S32 slot) const
{
S32 idx = mDataBlock->getPageSlotIndex(page, slot);
if (idx < 0 || !mDataBlock->rpg_spells[idx])
return false;
return mDataBlock->rpg_spells[idx]->is_placeholder;
}
afxMagicSpellData* afxSpellBook::getSpellData(S32 page, S32 slot)
{
S32 idx = mDataBlock->getPageSlotIndex(page, slot);
if (idx < 0 || !mDataBlock->spells[idx])
return 0;
return mDataBlock->spells[idx];
}
afxRPGMagicSpellData* afxSpellBook::getSpellRPGData(S32 page, S32 slot)
{
S32 idx = mDataBlock->getPageSlotIndex(page, slot);
if (idx < 0 || !mDataBlock->rpg_spells[idx])
return 0;
return mDataBlock->rpg_spells[idx];
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
void afxSpellBook::startAllSpellCooldown()
{
//all_spell_cooldown = 0.0f;
setMaskBits(AllSpellCooldownMask);
}
F32 afxSpellBook::getCooldownFactor(S32 page, S32 slot)
{
return all_spell_cooldown;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
DefineEngineMethod(afxSpellBook, getPageSlotIndex, S32, (Point2I bookSlot),,
"...\n\n"
"@ingroup AFX")
{
return object->getPageSlotIndex(bookSlot.x, bookSlot.y);
}
DefineEngineMethod(afxSpellBook, getSpellData, S32, (Point2I bookSlot),,
"Get spell datablock for spell stored at spellbook index, (page, slot).\n\n"
"@ingroup AFX")
{
afxMagicSpellData* spell_data = object->getSpellData(bookSlot.x, bookSlot.y);
return (spell_data) ? spell_data->getId() : 0;
}
DefineEngineMethod(afxSpellBook, getSpellRPGData, S32, (Point2I bookSlot),,
"Get spell RPG datablock for spell stored at spellbook index, (page, slot).\n\n"
"@ingroup AFX")
{
afxRPGMagicSpellData* spell_data = object->getSpellRPGData(bookSlot.x, bookSlot.y);
return (spell_data) ? spell_data->getId() : 0;
}
DefineEngineMethod(afxSpellBook, startAllSpellCooldown, void, (),,
"...\n\n"
"@ingroup AFX")
{
object->startAllSpellCooldown();
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
| 26.581006 | 114 | 0.620008 | [
"object",
"3d"
] |
29eecfa3bb5df41724c0d469994a0e5a8e575e67 | 39,765 | cxx | C++ | PWGHF/vertexingHF/vHFML/AliAnalysisTaskSEDmesonTree.cxx | raquishp/AliPhysics | 7b50836ec122eaf592f9c384fbd19f86e723135c | [
"BSD-3-Clause"
] | null | null | null | PWGHF/vertexingHF/vHFML/AliAnalysisTaskSEDmesonTree.cxx | raquishp/AliPhysics | 7b50836ec122eaf592f9c384fbd19f86e723135c | [
"BSD-3-Clause"
] | null | null | null | PWGHF/vertexingHF/vHFML/AliAnalysisTaskSEDmesonTree.cxx | raquishp/AliPhysics | 7b50836ec122eaf592f9c384fbd19f86e723135c | [
"BSD-3-Clause"
] | null | null | null | /* Copyright(c) 1998-2020, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
//*************************************************************************
// \class AliAnalysisTaskSEDmesonTree
// \brief Analysis task to produce trees of Lc candidates for ML analyses of non-prompt Lc
// \authors:
// F. Grosa, fabrizio.grosa@cern.ch
/////////////////////////////////////////////////////////////
#include "yaml-cpp/yaml.h"
#include <TRandom3.h>
#include "AliAODRecoDecayHF2Prong.h"
#include "AliAODRecoDecayHF3Prong.h"
#include "AliAODRecoCascadeHF.h"
#include "AliRDHFCutsD0toKpi.h"
#include "AliRDHFCutsDplustoKpipi.h"
#include "AliRDHFCutsDStartoKpipi.h"
#include "AliHFMLVarHandlerD0toKpi.h"
#include "AliHFMLVarHandlerDplustoKpipi.h"
#include "AliHFMLVarHandlerDstartoD0pi.h"
#include "AliHFMLResponseD0toKpi.h"
#include "AliHFMLResponseDplustoKpipi.h"
#include "AliHFMLResponseDstartoD0pi.h"
#include "AliVertexingHFUtils.h"
#include "AliAnalysisUtils.h"
#include "AliAODHandler.h"
#include "AliAODExtension.h"
#include "AliAODMCParticle.h"
#include "AliAnalysisManager.h"
#include "AliMultSelection.h"
#include "AliAnalysisTaskSECharmHadronMLSelector.h"
#include "AliAnalysisTaskSEDmesonTree.h"
/// \cond CLASSIMP
ClassImp(AliAnalysisTaskSEDmesonTree);
/// \endcond
//________________________________________________________________________
AliAnalysisTaskSEDmesonTree::AliAnalysisTaskSEDmesonTree() : AliAnalysisTaskSE()
{
/// Default constructor
}
//________________________________________________________________________
AliAnalysisTaskSEDmesonTree::AliAnalysisTaskSEDmesonTree(const char *name, int decayChannel, AliRDHFCuts *analysisCuts, bool createMLtree) :
AliAnalysisTaskSE(name),
fDecChannel(decayChannel),
fCreateMLtree(createMLtree)
{
/// Standard constructor
SetAnalysisCuts(analysisCuts);
SetDecayChannel(decayChannel);
DefineOutput(1, TList::Class());
switch(fDecChannel){
case kD0toKpi:
DefineOutput(2,AliRDHFCutsD0toKpi::Class()); //Cut object for D0
break;
case kDplustoKpipi:
DefineOutput(2,AliRDHFCutsDplustoKpipi::Class()); //Cut object for Dplus
break;
case kDstartoD0pi:
DefineOutput(2,AliRDHFCutsDStartoKpipi::Class()); //Cut object for D*
break;
}
DefineOutput(3, AliNormalizationCounter::Class());
if (fCreateMLtree)
DefineOutput(4, TTree::Class());
}
//________________________________________________________________________
AliAnalysisTaskSEDmesonTree::~AliAnalysisTaskSEDmesonTree()
{
// Destructor
delete fOutput;
delete fCounter;
delete fListCuts;
delete fRDCuts;
if (fCreateMLtree && fMLhandler)
delete fMLhandler; // it also deletes the TTree
if (fApplyML && fMLResponse)
delete fMLResponse;
}
//________________________________________________________________________
void AliAnalysisTaskSEDmesonTree::LocalInit()
{
// Initialization
switch (fDecChannel)
{
case kD0toKpi:
{
AliRDHFCutsD0toKpi *copycut = new AliRDHFCutsD0toKpi(*(static_cast<AliRDHFCutsD0toKpi *>(fRDCuts)));
PostData(2, copycut);
}
break;
case kDplustoKpipi:
{
AliRDHFCutsDplustoKpipi *copycut = new AliRDHFCutsDplustoKpipi(*(static_cast<AliRDHFCutsDplustoKpipi *>(fRDCuts)));
PostData(2, copycut);
}
break;
case kDstartoD0pi:
{
AliRDHFCutsDStartoKpipi *copycut = new AliRDHFCutsDStartoKpipi(*(static_cast<AliRDHFCutsDStartoKpipi *>(fRDCuts)));
PostData(2, copycut);
}
break;
}
return;
}
//________________________________________________________________________
void AliAnalysisTaskSEDmesonTree::UserCreateOutputObjects()
{
/// Create the output container
//
// Several histograms are more conveniently managed in a TList
fOutput = new TList();
fOutput->SetOwner();
fOutput->SetName("OutputHistos");
fHistNEvents = new TH1F("hNEvents", "number of events ", 16, -0.5, 15.5);
fHistNEvents->GetXaxis()->SetBinLabel(1, "nEventsRead");
fHistNEvents->GetXaxis()->SetBinLabel(2, "nEvents Matched dAOD");
fHistNEvents->GetXaxis()->SetBinLabel(3, "nEvents Mismatched dAOD");
fHistNEvents->GetXaxis()->SetBinLabel(4, "nEventsAnal");
fHistNEvents->GetXaxis()->SetBinLabel(5, "n. passing IsEvSelected");
fHistNEvents->GetXaxis()->SetBinLabel(6, "n. rejected due to trigger");
fHistNEvents->GetXaxis()->SetBinLabel(7, "n. rejected due to not reco vertex");
fHistNEvents->GetXaxis()->SetBinLabel(8, "n. rejected for contr vertex");
fHistNEvents->GetXaxis()->SetBinLabel(9, "n. rejected for vertex out of accept");
fHistNEvents->GetXaxis()->SetBinLabel(10, "n. rejected for pileup events");
fHistNEvents->GetXaxis()->SetBinLabel(11, "no. of out centrality events");
fHistNEvents->GetXaxis()->SetBinLabel(12, "no. of D candidates");
fHistNEvents->GetXaxis()->SetBinLabel(13, "no. of D after filtering cuts");
fHistNEvents->GetXaxis()->SetBinLabel(14, "no. of D after selection cuts");
fHistNEvents->GetXaxis()->SetBinLabel(15, "no. of not on-the-fly rec D");
fHistNEvents->GetXaxis()->SetBinLabel(16, "no. of D rejected by preselect");
fHistNEvents->GetXaxis()->SetNdivisions(1, false);
fHistNEvents->SetMinimum(0);
fOutput->Add(fHistNEvents);
// Sparses for efficiencies (only gen)
if(fReadMC)
CreateEffSparses();
//Counter for Normalization
fCounter = new AliNormalizationCounter("NormalizationCounter");
fCounter->Init();
PostData(3, fCounter);
//Loading of ML models
if(fApplyML) {
if(!fDependOnMLSelector)
{
switch (fDecChannel)
{
case kD0toKpi:
fMLResponse = new AliHFMLResponseD0toKpi("D0toKpiMLResponse", "D0toKpiMLResponse", fConfigPath.data());
break;
case kDplustoKpipi:
fMLResponse = new AliHFMLResponseDplustoKpipi("DplustoKpipiMLResponse", "DplustoKpipiMLResponse", fConfigPath.data());
break;
case kDstartoD0pi:
fMLResponse = new AliHFMLResponseDstartoD0pi("DstartoD0piMLResponse", "DstartoD0piMLResponse", fConfigPath.data());
break;
}
fMLResponse->MLResponseInit();
}
else {
std::string configLocalPath = AliMLModelHandler::ImportFile(fConfigPath.data());
YAML::Node nodeList;
try
{
nodeList = YAML::LoadFile(configLocalPath);
}
catch (std::exception &e)
{
AliFatal(Form("Yaml-ccp error: %s! Exit", e.what()));
}
fPtLimsML = nodeList["BINS"].as<vector<float> >();
for (const auto &model : nodeList["MODELS"])
{
fMLScoreCuts.push_back(model["cut"].as<std::vector<double> >());
fMLOptScoreCuts.push_back(model["cut_opt"].as<std::vector<std::string> >());
}
}
CreateRecoSparses();
}
//Create ML tree
if (fCreateMLtree)
{
OpenFile(4);
switch (fDecChannel)
{
case kD0toKpi:
fMLhandler = new AliHFMLVarHandlerD0toKpi(fPIDopt);
break;
case kDplustoKpipi:
fMLhandler = new AliHFMLVarHandlerDplustoKpipi(fPIDopt);
break;
case kDstartoD0pi:
fMLhandler = new AliHFMLVarHandlerDstartoD0pi(fPIDopt);
break;
}
fMLhandler->SetAddSingleTrackVars(fAddSingleTrackVar);
fMLhandler->SetAddGlobalEventVariables(fAddNtrkl, fAddCentr, fCentEstimator);
if (fReadMC)
{
if (fFillOnlySignal)
fMLhandler->SetFillOnlySignal();
fMLhandler->SetFillBeautyMotherPt();
}
fMLtree = fMLhandler->BuildTree("treeMLD", "treeMLD");
fMLtree->SetMaxVirtualSize(1.e+8);
PostData(4, fMLtree);
}
//Set seed of gRandom
if (fCreateMLtree && fEnableEvtSampling)
gRandom->SetSeed(fSeedSampling);
PostData(1, fOutput);
return;
}
//________________________________________________________________________
void AliAnalysisTaskSEDmesonTree::UserExec(Option_t * /*option*/)
{
if (fCreateMLtree && fEnableEvtSampling && ((fOptionSampling == 0 && gRandom->Rndm() > fFracEvtToKeep) || (fOptionSampling == 1 && gRandom->Rndm() < 1-fFracEvtToKeep)))
{
PostData(1, fOutput);
return;
}
fAOD = dynamic_cast<AliAODEvent *>(InputEvent());
fHistNEvents->Fill(0); // all events
if (fAODProtection >= 0)
{
// Protection against different number of events in the AOD and deltaAOD
// In case of discrepancy the event is rejected.
int matchingAODdeltaAODlevel = AliRDHFCuts::CheckMatchingAODdeltaAODevents();
if (matchingAODdeltaAODlevel < 0 || (matchingAODdeltaAODlevel == 0 && fAODProtection == 1))
{
// AOD/deltaAOD trees have different number of entries || TProcessID do not match while it was required
fHistNEvents->Fill(2);
PostData(1, fOutput);
return;
}
fHistNEvents->Fill(1);
}
TClonesArray *arrayCand = nullptr;
if (!fAOD && AODEvent() && IsStandardAOD())
{
// In case there is an AOD handler writing a standard AOD, use the AOD
// event in memory rather than the input (ESD) event.
fAOD = dynamic_cast<AliAODEvent *>(AODEvent());
// in this case the braches in the deltaAOD (AliAOD.VertexingHF.root)
// have to taken from the AOD event hold by the AliAODExtension
AliAODHandler *aodHandler = dynamic_cast<AliAODHandler *>((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
if (aodHandler->GetExtensions())
{
AliAODExtension *ext = dynamic_cast<AliAODExtension *>(aodHandler->GetExtensions()->FindObject("AliAOD.VertexingHF.root"));
AliAODEvent *aodFromExt = ext->GetAOD();
switch (fDecChannel)
{
case kD0toKpi:
arrayCand = dynamic_cast<TClonesArray *>(aodFromExt->GetList()->FindObject("D0toKpi"));
break;
case kDplustoKpipi:
arrayCand = dynamic_cast<TClonesArray *>(aodFromExt->GetList()->FindObject("Charm3Prong"));
break;
case kDstartoD0pi:
arrayCand = dynamic_cast<TClonesArray *>(aodFromExt->GetList()->FindObject("Dstar"));
break;
}
}
}
else if (fAOD)
{
switch (fDecChannel)
{
case kD0toKpi:
arrayCand = dynamic_cast<TClonesArray *>(fAOD->GetList()->FindObject("D0toKpi"));
break;
case kDplustoKpipi:
arrayCand = dynamic_cast<TClonesArray *>(fAOD->GetList()->FindObject("Charm3Prong"));
break;
case kDstartoD0pi:
arrayCand = dynamic_cast<TClonesArray *>(fAOD->GetList()->FindObject("Dstar"));
break;
}
}
if (!fAOD || !arrayCand)
{
AliError("Candidate branch not found!\n");
PostData(1, fOutput);
return;
}
// fix for temporary bug in ESDfilter
// the AODs with null vertex pointer didn't pass the PhysSel
if (!fAOD->GetPrimaryVertex() || TMath::Abs(fAOD->GetMagneticField()) < 0.001)
{
PostData(1, fOutput);
return;
}
fHistNEvents->Fill(3); // count event
fCounter->StoreEvent(fAOD, fRDCuts, fReadMC);
bool isEvSel = fRDCuts->IsEventSelected(fAOD);
if (fRDCuts->IsEventRejectedDueToTrigger())
fHistNEvents->Fill(5);
if (fRDCuts->IsEventRejectedDueToNotRecoVertex())
fHistNEvents->Fill(6);
if (fRDCuts->IsEventRejectedDueToVertexContributors())
fHistNEvents->Fill(7);
if (fRDCuts->IsEventRejectedDueToZVertexOutsideFiducialRegion())
fHistNEvents->Fill(8);
if (fRDCuts->IsEventRejectedDueToPileup())
fHistNEvents->Fill(9);
if (fRDCuts->IsEventRejectedDueToCentrality())
fHistNEvents->Fill(10);
TClonesArray *arrayMC = nullptr;
AliAODMCHeader *mcHeader = nullptr;
int Ntracklets = AliVertexingHFUtils::GetNumberOfTrackletsInEtaRange(fAOD, -1., 1.);
// load MC particles
if (fReadMC)
{
arrayMC = dynamic_cast<TClonesArray *>(fAOD->GetList()->FindObject(AliAODMCParticle::StdBranchName()));
if (!arrayMC)
{
AliWarning("MC particles branch not found!");
PostData(1, fOutput);
return;
}
// load MC header
mcHeader = dynamic_cast<AliAODMCHeader *>(fAOD->GetList()->FindObject(AliAODMCHeader::StdBranchName()));
if (!mcHeader)
{
AliWarning("MC header branch not found!");
PostData(1, fOutput);
return;
}
// fill MC acceptance histos
FillMCGenAccHistos(arrayMC, mcHeader, Ntracklets);
}
if (!isEvSel)
{
PostData(1, fOutput);
return;
}
fHistNEvents->Fill(4); // accepted event
// check if the train includes the common ML selector for the given charm-hadron species
AliAnalysisTaskSECharmHadronMLSelector *taskMLSelect = nullptr;
std::vector<int> chHadIdx{};
std::vector<std::vector<double> > scoresFromMLSelector{}, scoresFromMLSelectorSecond{};
if(fDependOnMLSelector)
{
taskMLSelect = dynamic_cast<AliAnalysisTaskSECharmHadronMLSelector*>(AliAnalysisManager::GetAnalysisManager()->GetTask(fMLSelectorName.data()));
if(!taskMLSelect)
{
AliFatal("ML Selector not present in train and ML models not compiled!");
return;
}
chHadIdx = taskMLSelect->GetSelectedCandidates();
scoresFromMLSelector = taskMLSelect->GetMLSCores();
scoresFromMLSelectorSecond = taskMLSelect->GetMLSCoresSecond();
}
else
{
for (int iCand = 0; iCand < arrayCand->GetEntriesFast(); iCand++)
chHadIdx.push_back(iCand);
}
// vHF object is needed to call the method that refills the missing info of the candidates
// if they have been deleted in dAOD reconstruction phase
// in order to reduce the size of the file
AliAnalysisVertexingHF vHF = AliAnalysisVertexingHF();
for (size_t iCand = 0; iCand < chHadIdx.size(); iCand++)
{
AliAODRecoDecayHF *dMeson = dynamic_cast<AliAODRecoDecayHF *>(arrayCand->UncheckedAt(chHadIdx[iCand]));
bool unsetVtx = false;
bool recVtx = false;
AliAODVertex *origOwnVtx = nullptr;
int isSelected = IsCandidateSelected(dMeson, &vHF, unsetVtx, recVtx, origOwnVtx);
if (!isSelected)
{
if (unsetVtx)
dMeson->UnsetOwnPrimaryVtx();
if (recVtx)
fRDCuts->CleanOwnPrimaryVtx(dMeson, fAOD, origOwnVtx);
continue;
}
fHistNEvents->Fill(13); // candidate selected
// get MC truth
AliAODMCParticle *partD = nullptr;
int labD = -1;
int pdgCode0 = -999;
int orig = 0;
bool isCandInjected = false;
float ptB = -999.;
int pdgD0Dau[2] = {321, 211};
int pdgDplusDau[3] = {321, 211, 211};
int pdgDstarDau[2] = {421, 211};
if (fReadMC)
{
switch (fDecChannel)
{
case kD0toKpi:
labD = (dynamic_cast<AliAODRecoDecayHF2Prong *>(dMeson))->MatchToMC(fPdgD, arrayMC, 2, pdgD0Dau);
break;
case kDplustoKpipi:
labD = (dynamic_cast<AliAODRecoDecayHF3Prong *>(dMeson))->MatchToMC(fPdgD, arrayMC, 3, pdgDplusDau);
break;
case kDstartoD0pi:
labD = (dynamic_cast<AliAODRecoCascadeHF *>(dMeson))->MatchToMC(fPdgD, 421, pdgDstarDau, pdgD0Dau, arrayMC, false);
break;
}
if (labD >= 0)
{
partD = dynamic_cast<AliAODMCParticle *>(arrayMC->At(labD));
if (fDecChannel == kD0toKpi) // check if signal is reflected
{
int labDau0 = dynamic_cast<AliAODTrack *>(dMeson->GetDaughter(0))->GetLabel();
AliAODMCParticle *dau0 = dynamic_cast<AliAODMCParticle *>(arrayMC->UncheckedAt(TMath::Abs(labDau0)));
pdgCode0 = TMath::Abs(dau0->GetPdgCode());
}
}
else
{
if (fKeepOnlyBkgFromHIJING)
isCandInjected = AliVertexingHFUtils::IsCandidateInjected(dMeson, mcHeader, arrayMC);
}
if (partD)
{
orig = AliVertexingHFUtils::CheckOrigin(arrayMC, partD, true);
ptB = AliVertexingHFUtils::GetBeautyMotherPt(arrayMC, partD);
}
}
// fill tree for ML
AliAODPidHF *pidHF = fRDCuts->GetPidHF();
if (fCreateMLtree)
{
fMLhandler->SetGlobalEventVariables(fAOD);
if (fDecChannel == kD0toKpi)
{
if (isSelected == 1 || isSelected == 3) // D0
{
bool isSignal = false;
bool isBkg = false;
bool isPrompt = false;
bool isFD = false;
bool isRefl = false;
if (fReadMC)
{
if (labD >= 0)
{
if (pdgCode0 == 211)
isRefl = true;
if (orig == 4)
isPrompt = true;
else if (orig == 5)
isFD = true;
if (orig >= 4)
isSignal = true;
}
else
{
if (!isCandInjected)
isBkg = true;
}
fMLhandler->SetBeautyMotherPt(ptB);
}
fMLhandler->SetCandidateType(isSignal, isBkg, isPrompt, isFD, isRefl);
bool okSetVar = fMLhandler->SetVariables(dMeson, fAOD->GetMagneticField(), AliHFMLVarHandlerD0toKpi::kD0, pidHF);
if (okSetVar && !(fReadMC && !isSignal && !isBkg && !isPrompt && !isFD && !isRefl))
fMLhandler->FillTree();
}
if (isSelected >= 2) // D0bar
{
bool isSignal = false;
bool isBkg = false;
bool isPrompt = false;
bool isFD = false;
bool isRefl = false;
if (fReadMC)
{
if (labD >= 0)
{
if (pdgCode0 == 321)
isRefl = true;
if (orig == 4)
isPrompt = true;
else if (orig == 5)
isFD = true;
if (orig >= 4)
isSignal = true;
}
else
{
if (!isCandInjected)
isBkg = true;
}
fMLhandler->SetBeautyMotherPt(ptB);
}
fMLhandler->SetCandidateType(isSignal, isBkg, isPrompt, isFD, isRefl);
bool okSetVar = fMLhandler->SetVariables(dMeson, fAOD->GetMagneticField(), AliHFMLVarHandlerD0toKpi::kD0bar, pidHF);
if (okSetVar && !(fReadMC && !isSignal && !isBkg && !isPrompt && !isFD && !isRefl)) // add tag in tree handler for signal from pileup events?
fMLhandler->FillTree();
}
break;
}
else
{
bool isSignal = false;
bool isBkg = false;
bool isPrompt = false;
bool isFD = false;
bool isRefl = false;
if (fReadMC)
{
if (labD >= 0)
{
if (orig == 4)
isPrompt = true;
else if (orig == 5)
isFD = true;
if (orig >= 4)
isSignal = true;
}
else
{
if (!isCandInjected)
isBkg = true;
}
fMLhandler->SetBeautyMotherPt(ptB);
}
fMLhandler->SetCandidateType(isSignal, isBkg, isPrompt, isFD, isRefl);
bool okSetVar = fMLhandler->SetVariables(dMeson, fAOD->GetMagneticField(), 0, pidHF);
if (okSetVar && !(fReadMC && !isSignal && !isBkg && !isPrompt && !isFD && !isRefl)) // add tag in tree handler for signal from pileup events?
fMLhandler->FillTree();
break;
}
}
if(fApplyML)
{
//variables for ML application
std::vector<double> modelPred = {};
bool isMLsel = false;
double ptCand = dMeson->Pt();
double centrality = -999.;
AliMultSelection *multSelection = dynamic_cast<AliMultSelection*>(fAOD->FindListObject("MultSelection"));
if(multSelection)
centrality = multSelection->GetMultiplicityPercentile(fCentEstimator.data());
if((fDecChannel == kD0toKpi && (isSelected == 1 || isSelected == 3)) || fDecChannel == kDplustoKpipi || fDecChannel == kDstartoD0pi)
{
if(fDependOnMLSelector)
{
std::vector<float>::iterator low = std::lower_bound(fPtLimsML.begin(), fPtLimsML.end(), ptCand);
int bin = low - fPtLimsML.begin() - 1;
if(bin < 0)
bin = 0;
else if(bin > fPtLimsML.size()-2)
bin = fPtLimsML.size()-2;
isMLsel = true;
for(size_t iScore = 0; iScore < scoresFromMLSelector[iCand].size(); iScore++) {
if((fMLOptScoreCuts[bin][iScore] == "upper" && scoresFromMLSelector[iCand][iScore] > fMLScoreCuts[bin][iScore]) ||
(fMLOptScoreCuts[bin][iScore] == "lower" && scoresFromMLSelector[iCand][iScore] < fMLScoreCuts[bin][iScore]))
{
isMLsel = false;
break;
}
}
}
else
isMLsel = fMLResponse->IsSelectedMultiClass(modelPred, dMeson, fAOD->GetMagneticField(), pidHF, 0);
if(isMLsel)
{
double mass = -1.;
switch(fDecChannel)
{
case kD0toKpi:
mass = dynamic_cast<AliAODRecoDecayHF2Prong *>(dMeson)->InvMassD0();
break;
case kDplustoKpipi:
mass = dynamic_cast<AliAODRecoDecayHF3Prong *>(dMeson)->InvMassDplus();
break;
case kDstartoD0pi:
mass = dynamic_cast<AliAODRecoCascadeHF *>(dMeson)->DeltaInvMass();
break;
}
std::vector<double> var4nSparse = {mass, ptCand, ptB, centrality, double(Ntracklets)};
if(fDependOnMLSelector)
var4nSparse.insert(var4nSparse.end(), scoresFromMLSelector[iCand].begin(), scoresFromMLSelector[iCand].end());
else
var4nSparse.insert(var4nSparse.end(), modelPred.begin(), modelPred.end());
if(!fReadMC)
fnSparseReco[0]->Fill(var4nSparse.data());
else
{
if(labD >= 0 && orig == 4)
{
fnSparseReco[1]->Fill(var4nSparse.data());
}
else if(labD >= 0 && orig == 5)
{
fnSparseReco[2]->Fill(var4nSparse.data());
}
else if(labD < 0)
{
fnSparseReco[3]->Fill(var4nSparse.data());
}
}
}
}
if(fDecChannel == kD0toKpi && isSelected >= 2)
{
if(fDependOnMLSelector)
{
std::vector<float>::iterator low = std::lower_bound(fPtLimsML.begin(), fPtLimsML.end(), ptCand);
int bin = low - fPtLimsML.begin() - 1;
if(bin < 0)
bin = 0;
else if(bin > fPtLimsML.size()-2)
bin = fPtLimsML.size()-2;
isMLsel = true;
for(size_t iScore = 0; iScore < scoresFromMLSelectorSecond[iCand].size(); iScore++) {
if((fMLOptScoreCuts[bin][iScore] == "upper" && scoresFromMLSelectorSecond[iCand][iScore] > fMLScoreCuts[bin][iScore]) ||
(fMLOptScoreCuts[bin][iScore] == "lower" && scoresFromMLSelectorSecond[iCand][iScore] < fMLScoreCuts[bin][iScore]))
{
isMLsel = false;
break;
}
}
}
else
isMLsel = fMLResponse->IsSelectedMultiClass(modelPred, dMeson, fAOD->GetMagneticField(), pidHF, 1);
if(isMLsel)
{
double mass = -1.;
switch(fDecChannel)
{
case kD0toKpi:
mass = dynamic_cast<AliAODRecoDecayHF2Prong *>(dMeson)->InvMassD0bar();
break;
}
std::vector<double> var4nSparse = {mass, ptCand, ptB, centrality, double(Ntracklets)};
if(fDependOnMLSelector)
var4nSparse.insert(var4nSparse.end(), scoresFromMLSelectorSecond[iCand].begin(), scoresFromMLSelectorSecond[iCand].end());
else
var4nSparse.insert(var4nSparse.end(), modelPred.begin(), modelPred.end());
if(!fReadMC)
fnSparseReco[0]->Fill(var4nSparse.data());
else
{
if(labD >= 0 && orig == 4)
{
fnSparseReco[1]->Fill(var4nSparse.data());
}
else if(labD >= 0 && orig == 5)
{
fnSparseReco[2]->Fill(var4nSparse.data());
}
else if(labD < 0)
{
fnSparseReco[3]->Fill(var4nSparse.data());
}
}
}
}
}
if (unsetVtx)
dMeson->UnsetOwnPrimaryVtx();
if (recVtx)
fRDCuts->CleanOwnPrimaryVtx(dMeson, fAOD, origOwnVtx);
}
PostData(1, fOutput);
PostData(3, fCounter);
if(fCreateMLtree)
PostData(4, fMLtree);
}
//________________________________________________________________________
int AliAnalysisTaskSEDmesonTree::IsCandidateSelected(AliAODRecoDecayHF *&dMeson, AliAnalysisVertexingHF *vHF, bool &unsetVtx, bool &recVtx, AliAODVertex *&origOwnVtx)
{
if (!dMeson || !vHF)
return 0;
fHistNEvents->Fill(11);
// Preselection to speed up task
TObjArray arrDauTracks(3);
int nDau = 3;
if (fDecChannel == kD0toKpi)
nDau = 2;
for (int iDau = 0; iDau < nDau; iDau++)
{
AliAODTrack *track = vHF->GetProng(fAOD, dMeson, iDau);
arrDauTracks.AddAt(track, iDau);
}
if (!fRDCuts->PreSelect(arrDauTracks))
{
fHistNEvents->Fill(15);
return 0;
}
bool isSelBit = true;
switch (fDecChannel)
{
case kD0toKpi:
isSelBit = dMeson->HasSelectionBit(AliRDHFCuts::kD0toKpiCuts);
if (!isSelBit || !vHF->FillRecoCand(fAOD, dynamic_cast<AliAODRecoDecayHF2Prong *>(dMeson)))
{
fHistNEvents->Fill(14);
return 0;
}
break;
case kDplustoKpipi:
isSelBit = dMeson->HasSelectionBit(AliRDHFCuts::kDplusCuts);
if (!isSelBit || !vHF->FillRecoCand(fAOD, dynamic_cast<AliAODRecoDecayHF3Prong *>(dMeson)))
{
fHistNEvents->Fill(14);
return 0;
}
break;
case kDstartoD0pi:
if (!vHF->FillRecoCasc(fAOD, dynamic_cast<AliAODRecoCascadeHF *>(dMeson), true))
{
fHistNEvents->Fill(14);
return 0;
}
break;
}
fHistNEvents->Fill(12);
unsetVtx = false;
if (!dMeson->GetOwnPrimaryVtx())
{
dMeson->SetOwnPrimaryVtx(dynamic_cast<AliAODVertex *>(fAOD->GetPrimaryVertex()));
unsetVtx = true;
// NOTE: the own primary vertex should be unset, otherwise there is a memory leak
// Pay attention if you use continue inside this loop!!!
}
double ptD = dMeson->Pt();
double yD = dMeson->Y(fPdgD);
if (fCreateMLtree && fEnableCandSampling) // apply sampling in pt
{
double pseudoRand = ptD * 1000. - (long)(ptD * 1000);
if (pseudoRand > fFracCandToKeep && ptD < fMaxCandPtSampling)
{
if (unsetVtx)
dMeson->UnsetOwnPrimaryVtx();
return 0;
}
}
int ptBin = fRDCuts->PtBin(ptD);
if (ptBin < 0)
{
if (unsetVtx)
dMeson->UnsetOwnPrimaryVtx();
return 0;
}
bool isFidAcc = fRDCuts->IsInFiducialAcceptance(ptD, yD);
if (!isFidAcc)
{
if (unsetVtx)
dMeson->UnsetOwnPrimaryVtx();
return 0;
}
int isSelected = fRDCuts->IsSelected(dMeson, AliRDHFCuts::kAll, fAOD);
if (!isSelected)
{
if (unsetVtx)
dMeson->UnsetOwnPrimaryVtx();
return 0;
}
recVtx = false;
origOwnVtx = nullptr;
if (fRDCuts->GetIsPrimaryWithoutDaughters())
{
if (dMeson->GetOwnPrimaryVtx())
origOwnVtx = new AliAODVertex(*dMeson->GetOwnPrimaryVtx());
if (fRDCuts->RecalcOwnPrimaryVtx(dMeson, fAOD))
recVtx = true;
else
fRDCuts->CleanOwnPrimaryVtx(dMeson, fAOD, origOwnVtx);
}
return isSelected;
}
//________________________________________________________________________
void AliAnalysisTaskSEDmesonTree::FillMCGenAccHistos(TClonesArray *arrayMC, AliAODMCHeader *mcHeader, int Ntracklets)
{
/// Fill MC histos for cuts study
/// - at GenLimAccStep and AccStep (if fFillAcceptanceLevel=false)
/// - at AccStep (if fFillAcceptanceLevel=true)
double zMCVertex = mcHeader->GetVtxZ(); //vertex MC
if (TMath::Abs(zMCVertex) <= fRDCuts->GetMaxVtxZ())
{
for (int iPart = 0; iPart < arrayMC->GetEntriesFast(); iPart++)
{
AliAODMCParticle *mcPart = dynamic_cast<AliAODMCParticle *>(arrayMC->At(iPart));
if (TMath::Abs(mcPart->GetPdgCode()) == fPdgD)
{
int orig = AliVertexingHFUtils::CheckOrigin(arrayMC, mcPart, true); //Prompt = 4, FeedDown = 5
bool isParticleFromOutOfBunchPileUpEvent = AliAnalysisUtils::IsParticleFromOutOfBunchPileupCollision(iPart, mcHeader, arrayMC);
int deca = 0;
bool isGoodDecay = false;
int labDau[3] = {-1, -1, -1};
bool isFidAcc = false;
bool isDaugInAcc = false;
int nDau = -1;
switch(fDecChannel)
{
case kD0toKpi:
nDau = 2;
deca = AliVertexingHFUtils::CheckD0Decay(arrayMC, mcPart, labDau);
break;
case kDplustoKpipi:
nDau = 3;
deca = AliVertexingHFUtils::CheckDplusDecay(arrayMC, mcPart, labDau);
break;
case kDstartoD0pi:
nDau = 3;
deca = AliVertexingHFUtils::CheckDstarDecay(arrayMC, mcPart, labDau);
break;
}
if (labDau[0] == -1)
continue; //protection against unfilled array of labels
if (deca > 0)
isGoodDecay = true;
if (isGoodDecay)
{
double pt = mcPart->Pt();
double rapid = mcPart->Y();
isFidAcc = fRDCuts->IsInFiducialAcceptance(pt, rapid);
isDaugInAcc = CheckDaugAcc(arrayMC, nDau, labDau);
if ((fFillAcceptanceLevel && isFidAcc && isDaugInAcc) || (!fFillAcceptanceLevel && TMath::Abs(rapid) < 0.5))
{
if (orig == 4 && !isParticleFromOutOfBunchPileUpEvent)
{
double var4nSparseAcc[knVarForSparseAcc] = {pt, rapid, -999., double(Ntracklets)};
fnSparseMC[0]->Fill(var4nSparseAcc);
}
else if (orig == 5 && !isParticleFromOutOfBunchPileUpEvent)
{
double ptB = AliVertexingHFUtils::GetBeautyMotherPt(arrayMC, mcPart);
double var4nSparseAcc[knVarForSparseAcc] = {pt, rapid, ptB, double(Ntracklets)};
fnSparseMC[1]->Fill(var4nSparseAcc);
}
}
}
}
}
}
}
//________________________________________________________________________
bool AliAnalysisTaskSEDmesonTree::CheckDaugAcc(TClonesArray *arrayMC, int nProng, int *labDau)
{
/// check if the decay products are in the good eta and pt range
for (int iProng = 0; iProng < nProng; iProng++)
{
bool isSoftPion = false;
AliAODMCParticle *mcPartDaughter = dynamic_cast<AliAODMCParticle *>(arrayMC->At(labDau[iProng]));
if (!mcPartDaughter)
return false;
if(fDecChannel == kDstartoD0pi)
{
AliAODMCParticle *mother = dynamic_cast<AliAODMCParticle *>(arrayMC->At(mcPartDaughter->GetMother()));
if(TMath::Abs(mother->GetPdgCode()) == 413)
isSoftPion = true;
}
double eta = mcPartDaughter->Eta();
double pt = mcPartDaughter->Pt();
double minPt = (!isSoftPion) ? 0.1 : 0.06;
if (TMath::Abs(eta) > 0.9 || pt < minPt)
return false;
}
return true;
}
//_________________________________________________________________________
void AliAnalysisTaskSEDmesonTree::CreateEffSparses()
{
/// use sparses to be able to add variables if needed (multiplicity, Zvtx, etc)
int nPtBinsCutObj = fRDCuts->GetNPtBins();
float *ptLims = fRDCuts->GetPtBinLimits();
int nPtBins = (int)ptLims[nPtBinsCutObj];
if (fUseFinPtBinsForSparse)
nPtBins = nPtBins * 10;
int nBinsAcc[knVarForSparseAcc] = {nPtBins, 20, nPtBins, 201};
double xminAcc[knVarForSparseAcc] = {0., -1., 0., -0.5};
double xmaxAcc[knVarForSparseAcc] = {ptLims[nPtBinsCutObj], 1., ptLims[nPtBinsCutObj], 200.5};
TString label[2] = {"fromC", "fromB"};
for (int iHist = 0; iHist < 2; iHist++)
{
TString titleSparse = Form("MC nSparse (%s)- %s", fFillAcceptanceLevel ? "Acc.Step" : "Gen.Acc.Step", label[iHist].Data());
fnSparseMC[iHist] = new THnSparseF(Form("fnSparseAcc_%s", label[iHist].Data()), titleSparse.Data(), knVarForSparseAcc, nBinsAcc, xminAcc, xmaxAcc);
fnSparseMC[iHist]->GetAxis(0)->SetTitle("#it{p}_{T} (GeV/c)");
fnSparseMC[iHist]->GetAxis(1)->SetTitle("#it{y}");
fnSparseMC[iHist]->GetAxis(2)->SetTitle("#it{p}_{T}^{B} (GeV/c)");
fnSparseMC[iHist]->GetAxis(3)->SetTitle("#it{N}_{tracklets}");
fOutput->Add(fnSparseMC[iHist]);
}
}
//_________________________________________________________________________
void AliAnalysisTaskSEDmesonTree::CreateRecoSparses()
{
int nPtBinsCutObj = fRDCuts->GetNPtBins();
float *ptLims = fRDCuts->GetPtBinLimits();
int nPtBins = (int)ptLims[nPtBinsCutObj];
if (fUseFinPtBinsForSparse)
nPtBins = nPtBins * 10;
int nMassBins = 500;
double massMin = -1., massMax = -1.;
double massD = TDatabasePDG::Instance()->GetParticle(fPdgD)->Mass();
std::string massTitle = "";
switch(fDecChannel)
{
case kD0toKpi:
massMin = massD - 0.250;
massMax = massD + 0.250;
massTitle = "#it{M}(K#pi) (GeV/#it{c})";
break;
case kDplustoKpipi:
massMin = massD - 0.250;
massMax = massD + 0.250;
massTitle = "#it{M}(K#pi#pi) (GeV/#it{c})";
break;
case kDstartoD0pi:
massMin = 0.138;
massMax = 0.160;
massTitle = "#it{M}(K#pi#pi) #minus #it{M}(K#pi) (GeV/#it{c})";
break;
}
int nBinsReco[knVarForSparseReco] = {nMassBins, nPtBins, 2*nPtBins, 100, 201, fNMLBins[0], fNMLBins[1], fNMLBins[2]};
double xminReco[knVarForSparseReco] = {massMin, 0., 0., 0., -0.5, fMLOutputMin[0], fMLOutputMin[1], fMLOutputMin[2]};
double xmaxReco[knVarForSparseReco] = {massMax, ptLims[nPtBinsCutObj], 2*ptLims[nPtBinsCutObj], 100., 200.5, fMLOutputMax[0], fMLOutputMax[1], fMLOutputMax[2]};
int nVars = 6;
if(fMultiClass)
nVars = 8;
TString label[4] = {"all", "fromC", "fromB", "bkg"};
for (int iHist = 0; iHist < 4; iHist++)
{
TString titleSparse = Form("Reco nSparse - %s", label[iHist].Data());
fnSparseReco[iHist] = new THnSparseF(Form("fnSparseReco_%s", label[iHist].Data()), titleSparse.Data(), nVars, nBinsReco, xminReco, xmaxReco);
fnSparseReco[iHist]->GetAxis(0)->SetTitle(massTitle.data());
fnSparseReco[iHist]->GetAxis(1)->SetTitle("#it{p}_{T} (GeV/c)");
fnSparseReco[iHist]->GetAxis(2)->SetTitle("#it{p}_{T}^{B} (GeV/c)");
fnSparseReco[iHist]->GetAxis(3)->SetTitle("centrality (%)");
fnSparseReco[iHist]->GetAxis(4)->SetTitle("#it{N}_{tracklets}");
for(int iAx=5; iAx<nVars; iAx++)
fnSparseReco[iHist]->GetAxis(iAx)->SetTitle(Form("ML output %d", iAx-5));
fOutput->Add(fnSparseReco[iHist]);
}
}
| 38.198847 | 172 | 0.54294 | [
"object",
"vector",
"model"
] |
29f1c92455661e765f8aee55c8229ab3e4790122 | 11,976 | cpp | C++ | src/mlpack/tests/main_tests/adaboost_test.cpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2015-01-04T04:20:29.000Z | 2016-07-21T23:30:34.000Z | src/mlpack/tests/main_tests/adaboost_test.cpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2017-01-23T18:39:30.000Z | 2021-07-15T13:58:34.000Z | src/mlpack/tests/main_tests/adaboost_test.cpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2017-01-20T00:54:34.000Z | 2020-05-16T05:34:32.000Z | /**
* @file adaboost_test.cpp
* @author Nikhil Goel
*
* Test mlpackMain() of adaboost_main.cpp.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <string>
#define BINDING_TYPE BINDING_TYPE_TEST
static const std::string testName = "AdaBoost";
#include <mlpack/core.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include "test_helper.hpp"
#include <mlpack/methods/adaboost/adaboost_main.cpp>
#include <boost/test/unit_test.hpp>
#include "../test_tools.hpp"
using namespace mlpack;
struct AdaBoostTestFixture
{
public:
AdaBoostTestFixture()
{
// Cache in the options for this program.
CLI::RestoreSettings(testName);
}
~AdaBoostTestFixture()
{
// Clear the settings.
bindings::tests::CleanMemory();
CLI::ClearSettings();
}
};
BOOST_FIXTURE_TEST_SUITE(AdaBoostMainTest, AdaBoostTestFixture);
/**
* Check that number of output labels and number of input
* points are equal.
*/
BOOST_AUTO_TEST_CASE(AdaBoostOutputDimensionTest)
{
arma::mat trainData;
if (!data::Load("vc2.csv", trainData))
BOOST_FAIL("Unable to load train dataset vc2.csv!");
arma::Row<size_t> labels;
if (!data::Load("vc2_labels.txt", labels))
BOOST_FAIL("Unable to load label dataset vc2_labels.txt!");
arma::mat testData;
if (!data::Load("vc2_test.csv", testData))
BOOST_FAIL("Unable to load test dataset vc2.csv!");
size_t testSize = testData.n_cols;
SetInputParam("training", std::move(trainData));
SetInputParam("labels", std::move(labels));
SetInputParam("test", std::move(testData));
mlpackMain();
// Check that number of predicted labels is equal to the input test points.
BOOST_REQUIRE_EQUAL(CLI::GetParam<arma::Row<size_t>>("output").n_cols,
testSize);
BOOST_REQUIRE_EQUAL(CLI::GetParam<arma::Row<size_t>>("output").n_rows, 1);
}
/**
* Ensure that saved model can be used again.
*/
BOOST_AUTO_TEST_CASE(AdaBoostModelReuseTest)
{
arma::mat trainData;
if (!data::Load("vc2.csv", trainData))
BOOST_FAIL("Unable to load train dataset vc2.csv!");
arma::Row<size_t> labels;
if (!data::Load("vc2_labels.txt", labels))
BOOST_FAIL("Unable to load label dataset vc2_labels.txt!");
arma::mat testData;
if (!data::Load("vc2_test.csv", testData))
BOOST_FAIL("Unable to load test dataset vc2.csv!");
SetInputParam("training", std::move(trainData));
SetInputParam("labels", std::move(labels));
SetInputParam("test", testData);
mlpackMain();
arma::Row<size_t> output;
output = std::move(CLI::GetParam<arma::Row<size_t>>("output"));
CLI::GetSingleton().Parameters()["training"].wasPassed = false;
CLI::GetSingleton().Parameters()["labels"].wasPassed = false;
CLI::GetSingleton().Parameters()["test"].wasPassed = false;
SetInputParam("test", std::move(testData));
SetInputParam("input_model",
CLI::GetParam<AdaBoostModel*>("output_model"));
mlpackMain();
// Check that initial output and output using saved model are same.
CheckMatrices(output, CLI::GetParam<arma::Row<size_t>>("output"));
}
/**
* Test that iterations in adaboost is always non-negative.
*/
BOOST_AUTO_TEST_CASE(AdaBoostItrTest)
{
arma::mat trainData;
if (!data::Load("trainSet.csv", trainData))
BOOST_FAIL("Unable load train dataset trainSet.csv!");
SetInputParam("training", std::move(trainData));
SetInputParam("iterations", (int) -1);
Log::Fatal.ignoreInput = true;
BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
Log::Fatal.ignoreInput = false;
}
/**
* Check that the last dimension of the training set is
* used as labels when labels are not passed specifically
* and results are same from both label and without label models.
*/
BOOST_AUTO_TEST_CASE(AdaBoostWithoutLabelTest)
{
// Train adaboost without providing labels.
arma::mat trainData;
if (!data::Load("trainSet.csv", trainData))
BOOST_FAIL("Unable to load train dataset trainSet.csv!");
// Give labels.
arma::Row<size_t> labels(trainData.n_cols);
for (size_t i = 0; i < trainData.n_cols; ++i)
labels[i] = trainData(trainData.n_rows - 1, i);
arma::mat testData;
if (!data::Load("testSet.csv", testData))
BOOST_FAIL("Unable to load test dataset testSet.csv!");
// Delete the last row containing labels from test dataset.
testData.shed_row(testData.n_rows - 1);
SetInputParam("training", trainData);
SetInputParam("test", testData);
mlpackMain();
CLI::GetSingleton().Parameters()["training"].wasPassed = false;
CLI::GetSingleton().Parameters()["test"].wasPassed = false;
arma::Row<size_t> output;
output = std::move(CLI::GetParam<arma::Row<size_t>>("output"));
bindings::tests::CleanMemory();
trainData.shed_row(trainData.n_rows - 1);
// Now train Adaboost with labels provided.
SetInputParam("training", std::move(trainData));
SetInputParam("test", std::move(testData));
SetInputParam("labels", std::move(labels));
mlpackMain();
// Check that initial output and final output matrix are same.
CheckMatrices(output, CLI::GetParam<arma::Row<size_t>>("output"));
}
/**
* Testing that only one of training data or pre-trained model is passed.
*/
BOOST_AUTO_TEST_CASE(AdaBoostTrainingDataOrModelTest)
{
arma::mat trainData;
if (!data::Load("trainSet.csv", trainData))
BOOST_FAIL("Unable to load train dataset trainSet.csv!");
SetInputParam("training", std::move(trainData));
mlpackMain();
SetInputParam("input_model",
CLI::GetParam<AdaBoostModel*>("output_model"));
Log::Fatal.ignoreInput = true;
BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
Log::Fatal.ignoreInput = false;
}
/**
* Weak learner should be either Decision Stump or Perceptron.
*/
BOOST_AUTO_TEST_CASE(AdaBoostWeakLearnerTest)
{
arma::mat trainData;
if (!data::Load("trainSet.csv", trainData))
BOOST_FAIL("Unable to load train dataset trainSet.csv!");
SetInputParam("training", std::move(trainData));
SetInputParam("weak_learner", std::string("decision tree"));
Log::Fatal.ignoreInput = true;
BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
Log::Fatal.ignoreInput = false;
}
/**
* Different Weak learner should give different outputs.
*/
BOOST_AUTO_TEST_CASE(AdaBoostDiffWeakLearnerOutputTest)
{
arma::mat trainData;
if (!data::Load("vc2.csv", trainData))
BOOST_FAIL("Unable to load train dataset vc2.csv!");
arma::Row<size_t> labels;
if (!data::Load("vc2_labels.txt", labels))
BOOST_FAIL("Unable to load label dataset vc2_labels.txt!");
arma::mat testData;
if (!data::Load("vc2_test.csv", testData))
BOOST_FAIL("Unable to load test dataset vc2.csv!");
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("test", testData);
mlpackMain();
arma::Row<size_t> output;
output = std::move(CLI::GetParam<arma::Row<size_t>>("output"));
bindings::tests::CleanMemory();
CLI::GetSingleton().Parameters()["training"].wasPassed = false;
CLI::GetSingleton().Parameters()["labels"].wasPassed = false;
CLI::GetSingleton().Parameters()["test"].wasPassed = false;
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("test", testData);
SetInputParam("weak_learner", std::string("perceptron"));
mlpackMain();
arma::Row<size_t> outputPerceptron;
outputPerceptron = std::move(CLI::GetParam<arma::Row<size_t>>("output"));
BOOST_REQUIRE_GT(arma::accu(output != outputPerceptron), 1);
}
/**
* Accuracy increases as Number of Iterations increases.
* (Or converges and remains same)
*/
BOOST_AUTO_TEST_CASE(AdaBoostDiffItrTest)
{
arma::mat trainData;
if (!data::Load("vc2.csv", trainData))
BOOST_FAIL("Unable to load train dataset vc2.csv!");
arma::Row<size_t> labels;
if (!data::Load("vc2_labels.txt", labels))
BOOST_FAIL("Unable to load label dataset vc2_labels.txt!");
arma::mat testData;
if (!data::Load("vc2_test.csv", testData))
BOOST_FAIL("Unable to load test dataset vc2.csv!");
arma::Row<size_t> testLabels;
if (!data::Load("vc2_test_labels.txt", testLabels))
BOOST_FAIL("Unable to load labels for vc2__test_labels.txt");
// Iterations = 1
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("weak_learner", std::string("perceptron"));
SetInputParam("iterations", (int) 1);
mlpackMain();
// Calculate accuracy.
arma::Row<size_t> output;
CLI::GetParam<AdaBoostModel*>("output_model")->Classify(testData,
output);
size_t correct = arma::accu(output == testLabels);
double accuracy1 = (double(correct) / double(testLabels.n_elem) * 100);
bindings::tests::CleanMemory();
// Iterations = 10
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("weak_learner", std::string("perceptron"));
SetInputParam("iterations", (int) 10);
mlpackMain();
// Calculate accuracy.
CLI::GetParam<AdaBoostModel*>("output_model")->Classify(testData,
output);
correct = arma::accu(output == testLabels);
double accuracy10 = (double(correct) / double(testLabels.n_elem) * 100);
bindings::tests::CleanMemory();
// Iterations = 100
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("weak_learner", std::string("perceptron"));
SetInputParam("iterations", (int) 100);
mlpackMain();
// Calculate accuracy.
CLI::GetParam<AdaBoostModel*>("output_model")->Classify(testData,
output);
correct = arma::accu(output == testLabels);
double accuracy100 = (double(correct) / double(testLabels.n_elem) * 100);
BOOST_REQUIRE_LE(accuracy1, accuracy10);
BOOST_REQUIRE_LE(accuracy10, accuracy100);
}
/**
* Accuracy increases as tolerance decreases.
* (Execution Time also increases)
*/
BOOST_AUTO_TEST_CASE(AdaBoostDiffTolTest)
{
arma::mat trainData;
if (!data::Load("vc2.csv", trainData))
BOOST_FAIL("Unable to load train dataset vc2.csv!");
arma::Row<size_t> labels;
if (!data::Load("vc2_labels.txt", labels))
BOOST_FAIL("Unable to load label dataset vc2_labels.txt!");
arma::mat testData;
if (!data::Load("vc2_test.csv", testData))
BOOST_FAIL("Unable to load test dataset vc2.csv!");
arma::Row<size_t> testLabels;
if (!data::Load("vc2_test_labels.txt", testLabels))
BOOST_FAIL("Unable to load labels for vc2__test_labels.txt");
// tolerance = 0.001
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("tolerance", (double) 0.001);
mlpackMain();
// Calculate accuracy.
arma::Row<size_t> output;
CLI::GetParam<AdaBoostModel*>("output_model")->Classify(testData,
output);
size_t correct = arma::accu(output == testLabels);
double accuracy1 = (double(correct) / double(testLabels.n_elem) * 100);
bindings::tests::CleanMemory();
// tolerance = 0.01
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("tolerance", (double) 0.01);
mlpackMain();
// Calculate accuracy.
CLI::GetParam<AdaBoostModel*>("output_model")->Classify(testData,
output);
correct = arma::accu(output == testLabels);
double accuracy2 = (double(correct) / double(testLabels.n_elem) * 100);
bindings::tests::CleanMemory();
// tolerance = 0.1
SetInputParam("training", trainData);
SetInputParam("labels", labels);
SetInputParam("tolerance", (double) 0.1);
mlpackMain();
// Calculate accuracy.
CLI::GetParam<AdaBoostModel*>("output_model")->Classify(testData,
output);
correct = arma::accu(output == testLabels);
double accuracy3 = (double(correct) / double(testLabels.n_elem) * 100);
BOOST_REQUIRE_LE(accuracy1, accuracy2);
BOOST_REQUIRE_LE(accuracy2, accuracy3);
}
BOOST_AUTO_TEST_SUITE_END();
| 28.446556 | 78 | 0.703156 | [
"model"
] |
29f3b05f1bd0ba789767400aeb9001ed4a440927 | 11,219 | cpp | C++ | rmf_traffic/src/rmf_traffic/agv/planning/DifferentialDriveMap.cpp | 0to1/rmf_traffic | 0e641f779e9c7e6d69c316e905df5a51a2c124e1 | [
"Apache-2.0"
] | 10 | 2021-04-14T07:01:56.000Z | 2022-02-21T02:26:58.000Z | rmf_traffic/src/rmf_traffic/agv/planning/DifferentialDriveMap.cpp | 0to1/rmf_traffic | 0e641f779e9c7e6d69c316e905df5a51a2c124e1 | [
"Apache-2.0"
] | 63 | 2021-03-10T06:06:13.000Z | 2022-03-25T08:47:07.000Z | rmf_traffic/src/rmf_traffic/agv/planning/DifferentialDriveMap.cpp | 0to1/rmf_traffic | 0e641f779e9c7e6d69c316e905df5a51a2c124e1 | [
"Apache-2.0"
] | 10 | 2021-03-17T02:52:14.000Z | 2022-02-21T02:27:02.000Z | /*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* 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 <rmf_utils/math.hpp>
#include "DifferentialDriveMap.hpp"
#include "../internal_Interpolate.hpp"
namespace rmf_traffic {
namespace agv {
namespace planning {
//==============================================================================
DifferentialDriveMapTypes::RouteInfo::RouteInfo(
rmf_traffic::Time finish_time_,
double finish_yaw_,
std::vector<Route> routes_)
: finish_time(finish_time_),
finish_yaw(finish_yaw_),
routes(std::move(routes_))
{
// Do nothing
}
//==============================================================================
FactoryInfo make_differential_drive_translate_factory(
Eigen::Vector3d start,
Eigen::Vector3d finish,
KinematicLimits limits,
double translation_thresh,
double rotation_thresh,
std::vector<std::string> maps)
{
const auto dummy_start_time = rmf_traffic::Time(rmf_traffic::Duration(0));
Trajectory trajectory;
trajectory.insert(dummy_start_time, start, Eigen::Vector3d::Zero());
internal::interpolate_translation(
trajectory, limits.linear.velocity, limits.linear.acceleration,
dummy_start_time, start, finish, translation_thresh);
const double minimal_cost =
rmf_traffic::time::to_seconds(trajectory.duration());
auto factory =
[start,
finish,
limits,
translation_thresh,
rotation_thresh,
maps = std::move(maps)](
rmf_traffic::Time start_time,
double initial_yaw)
-> DifferentialDriveMapTypes::RouteInfo
{
Trajectory trajectory;
const Eigen::Vector3d pre_start{start.x(), start.y(), initial_yaw};
trajectory.insert(start_time, pre_start, Eigen::Vector3d::Zero());
internal::interpolate_rotation(
trajectory, limits.angular.velocity, limits.angular.acceleration,
start_time, pre_start, start, rotation_thresh);
internal::interpolate_translation(
trajectory, limits.linear.velocity, limits.linear.acceleration,
trajectory.back().time(), start, finish, translation_thresh);
std::vector<Route> routes;
routes.reserve(maps.size());
for (const auto& map : maps)
routes.push_back({map, trajectory});
return {*trajectory.finish_time(), finish[2], routes};
};
auto factory_factory = [factory = std::move(factory)](
std::optional<double>)
-> DifferentialDriveMapTypes::RouteFactory
{
return [factory](
const rmf_traffic::Time start_time,
const double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo
{
return factory(start_time, initial_yaw);
};
};
return {minimal_cost, std::move(factory_factory)};
}
//==============================================================================
std::optional<FactoryInfo> make_rotate_factory(
Eigen::Vector2d position,
std::optional<double> start_yaw,
std::optional<double> finish_yaw,
KinematicLimits limits,
double rotation_thresh,
std::string map)
{
double minimum_cost = 0.0;
if (start_yaw.has_value() && finish_yaw.has_value())
{
const double yaw_dist =
std::abs(rmf_utils::wrap_to_pi(*start_yaw - *finish_yaw));
// If both yaws are known and they are within the rotation threshold of each
// other, then no rotation will be needed.
if (yaw_dist <= rotation_thresh)
return std::nullopt;
// If both yaws are known and a rotation is needed, then let's calculate the
// time required for it.
const auto dummy_start_time = rmf_traffic::Time(rmf_traffic::Duration(0));
Trajectory trajectory;
const Eigen::Vector3d start_p{position.x(), position.y(), * start_yaw};
trajectory.insert(dummy_start_time, start_p, Eigen::Vector3d::Zero());
const Eigen::Vector3d finish_p{position.x(), position.y(), * finish_yaw};
internal::interpolate_rotation(
trajectory, limits.angular.velocity, limits.angular.acceleration,
dummy_start_time, start_p, finish_p, rotation_thresh);
minimum_cost = rmf_traffic::time::to_seconds(trajectory.duration());
}
auto factory =
[p = position,
finish_yaw,
limits = limits.angular,
rotation_thresh,
map = std::move(map)](
rmf_traffic::Time start_time,
double initial_yaw,
std::optional<double> child_yaw)
-> DifferentialDriveMapTypes::RouteInfo
{
Trajectory trajectory;
const Eigen::Vector3d start_p = {p.x(), p.y(), initial_yaw};
trajectory.insert(start_time, start_p, Eigen::Vector3d::Zero());
if (finish_yaw.has_value())
{
const Eigen::Vector3d finish_p = {p.x(), p.y(), *finish_yaw};
internal::interpolate_rotation(
trajectory, limits.velocity, limits.acceleration, start_time,
start_p, finish_p, rotation_thresh);
}
else if (child_yaw.has_value())
{
const Eigen::Vector3d finish_p = {p.x(), p.y(), *child_yaw};
internal::interpolate_rotation(
trajectory, limits.velocity, limits.acceleration, start_time,
start_p, finish_p, rotation_thresh);
}
const auto finish_time = *trajectory.finish_time();
const auto finish_yaw = trajectory.back().position()[2];
return {finish_time, finish_yaw, {{map, std::move(trajectory)}}};
};
auto factory_factory = [factory = std::move(factory)](
std::optional<double> child_yaw)
-> DifferentialDriveMapTypes::RouteFactory
{
return [factory, child_yaw](
const rmf_traffic::Time start_time,
const double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo
{
return factory(start_time, initial_yaw, child_yaw);
};
};
return std::optional<FactoryInfo>({minimum_cost, std::move(factory_factory)});
}
//==============================================================================
DifferentialDriveMapTypes::RouteFactoryFactory
make_hold_factory(
Eigen::Vector2d position,
std::optional<double> yaw_opt,
rmf_traffic::Duration duration,
KinematicLimits limits,
double rotation_thresh,
std::vector<std::string> maps)
{
auto factory =
[p = position,
yaw_opt,
duration,
limits = limits.angular,
rotation_thresh,
maps = std::move(maps)](
rmf_traffic::Time start_time,
double initial_yaw,
std::optional<double> child_yaw)
-> DifferentialDriveMapTypes::RouteInfo
{
rmf_traffic::Trajectory trajectory;
const Eigen::Vector3d start_position{p.x(), p.y(), initial_yaw};
trajectory.insert(start_time, start_position, Eigen::Vector3d::Zero());
Eigen::Vector3d yawed_position = start_position;
if (yaw_opt.has_value())
{
yawed_position = {p.x(), p.y(), *yaw_opt};
internal::interpolate_rotation(
trajectory, limits.velocity, limits.acceleration,
trajectory.back().time(), start_position, yawed_position,
rotation_thresh);
}
else if (child_yaw.has_value())
{
yawed_position = {p.x(), p.y(), *child_yaw};
internal::interpolate_rotation(
trajectory, limits.velocity, limits.acceleration,
trajectory.back().time(), yawed_position, yawed_position,
rotation_thresh);
}
const auto desired_finish_time = start_time + duration;
const auto remaining_duration =
desired_finish_time - *trajectory.finish_time();
if (remaining_duration > std::chrono::nanoseconds(0))
{
trajectory.insert(
desired_finish_time,
yawed_position,
Eigen::Vector3d::Zero());
}
std::vector<Route> routes;
routes.reserve(maps.size());
for (const auto& map : maps)
routes.push_back({map, trajectory});
const auto finish_time = *trajectory.finish_time();
const auto finish_yaw = trajectory.back().position()[2];
return {finish_time, finish_yaw, std::move(routes)};
};
return [factory = std::move(factory)](std::optional<double> child_yaw)
-> DifferentialDriveMapTypes::RouteFactory
{
return [factory, child_yaw](
rmf_traffic::Time start_time,
double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo
{
return factory(start_time, initial_yaw, child_yaw);
};
};
}
//==============================================================================
DifferentialDriveMapTypes::RouteFactoryFactory
make_start_factory(
Eigen::Vector2d position,
std::optional<double> target_yaw,
KinematicLimits limits,
double rotation_thresh,
std::vector<std::string> maps)
{
auto factory =
[p = position,
target_yaw,
maps = std::move(maps),
limits = limits.angular,
rotation_thresh](
Time start_time,
double initial_yaw,
std::optional<double> child_yaw)
-> DifferentialDriveMapTypes::RouteInfo
{
Trajectory trajectory;
const Eigen::Vector3d start_p = {p.x(), p.y(), initial_yaw};
trajectory.insert(start_time, start_p, Eigen::Vector3d::Zero());
if (target_yaw.has_value())
{
const Eigen::Vector3d finish_p = {p.x(), p.y(), *target_yaw};
internal::interpolate_rotation(
trajectory, limits.velocity, limits.acceleration,
start_time, start_p, finish_p, rotation_thresh);
}
else if (child_yaw.has_value())
{
const Eigen::Vector3d finish_p = {p.x(), p.y(), *child_yaw};
internal::interpolate_rotation(
trajectory, limits.velocity, limits.acceleration,
start_time, start_p, finish_p, rotation_thresh);
}
std::vector<Route> routes;
routes.reserve(maps.size());
for (const auto& map : maps)
routes.push_back({map, trajectory});
const auto finish_time = *trajectory.finish_time();
const auto finish_yaw = trajectory.back().position()[2];
return {finish_time, finish_yaw, std::move(routes)};
};
return [factory = std::move(factory)](
std::optional<double> child_yaw)
-> DifferentialDriveMapTypes::RouteFactory
{
return [factory, child_yaw](
const rmf_traffic::Time start_time,
const double initial_yaw) -> DifferentialDriveMapTypes::RouteInfo
{
return factory(start_time, initial_yaw, child_yaw);
};
};
}
//==============================================================================
DifferentialDriveMapTypes::RouteFactoryFactory
make_recycling_factory(DifferentialDriveMapTypes::RouteFactory old_factory)
{
return [old_factory = std::move(old_factory)](auto)
{
return old_factory;
};
}
} // namespace planning
} // namespace agv
} // namespace rmf_traffic
| 32.613372 | 80 | 0.646403 | [
"vector"
] |
29f6e5ae2d65d28dd15058fbd85c96ea643eedba | 1,774 | cpp | C++ | 3rdParty/boost/1.71.0/libs/histogram/test/histogram_serialization_test.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | 3rdParty/boost/1.71.0/libs/histogram/test/histogram_serialization_test.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | 3rdParty/boost/1.71.0/libs/histogram/test/histogram_serialization_test.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // Copyright 2018 Hans Dembinski
//
// 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 <boost/assert.hpp>
#include <boost/core/lightweight_test.hpp>
#include <boost/histogram/axis.hpp>
#include <boost/histogram/axis/ostream.hpp>
#include <boost/histogram/ostream.hpp>
#include <boost/histogram/serialization.hpp>
#include <cmath>
#include <string>
#include "throw_exception.hpp"
#include "utility_histogram.hpp"
#include "utility_serialization.hpp"
using namespace boost::histogram;
template <typename Tag>
void run_tests(const std::string& filename) {
// histogram_serialization
namespace tr = axis::transform;
using def = use_default;
using axis::option::none_t;
auto a =
make(Tag(), axis::regular<double, def, def, none_t>(1, -1, 1, "reg"),
axis::circular<float, def, none_t>(1, 0.0, 1.0, "cir"),
axis::regular<double, tr::log, def, none_t>(1, 1, std::exp(2), "reg-log"),
axis::regular<double, tr::pow, std::vector<int>, axis::option::overflow_t>(
tr::pow(0.5), 1, 1, 100, {1, 2, 3}),
axis::variable<double, def, none_t>({1.5, 2.5}, "var"),
axis::category<int, def, none_t>{3, 1},
axis::integer<int, axis::null_type, none_t>(1, 2));
a(0.5, 0.2, 2, 20, 2.2, 1, 1);
print_xml(filename, a);
auto b = decltype(a)();
BOOST_TEST_NE(a, b);
load_xml(filename, b);
BOOST_TEST_EQ(a, b);
}
int main(int argc, char** argv) {
BOOST_ASSERT(argc == 2);
run_tests<static_tag>(join(argv[1], "histogram_serialization_test_static.xml"));
run_tests<dynamic_tag>(join(argv[1], "histogram_serialization_test_dynamic.xml"));
return boost::report_errors();
}
| 34.784314 | 86 | 0.669109 | [
"vector",
"transform"
] |
29fb6b620789e8f7c4cdf91225fa01b3bd0bede2 | 2,073 | hh | C++ | include/train_logReg_param.hh | sestaton/Augustus | 893e0b21fa90bd57fcd0dff2c1e849e88bb02049 | [
"Artistic-1.0"
] | 178 | 2018-05-25T09:51:13.000Z | 2022-03-30T13:55:58.000Z | include/train_logReg_param.hh | sestaton/Augustus | 893e0b21fa90bd57fcd0dff2c1e849e88bb02049 | [
"Artistic-1.0"
] | 249 | 2018-07-02T07:03:12.000Z | 2022-03-30T00:01:01.000Z | include/train_logReg_param.hh | sestaton/Augustus | 893e0b21fa90bd57fcd0dff2c1e849e88bb02049 | [
"Artistic-1.0"
] | 95 | 2018-08-21T21:33:19.000Z | 2022-03-30T13:56:00.000Z | /*
* train_logReg_param.hh
*
* License: Artistic License, see file LICENSE.TXT or
* https://opensource.org/licenses/artistic-license-1.0
*/
#ifndef _TRAINLOGREG_HH
#define _TRAINLOGREG_HH
// project includes
#include "types.hh"
#include "properties.hh"
// standard C/C++ includes
#include <iostream>
#include <vector>
#include <unordered_map>
#include <gsl/gsl_multimin.h>
using namespace std;
/**
* @brief implementation of logistic regression for training OE and EC
* feature parameters using GSL
*
* @author Lizzy Gerischer
*/
class train_data{
public:
train_data(unordered_map<string, pair<int, vector<double> > > *samples, unordered_map<string,int> *ref_class, int numSp);
vector<pair<int, vector<double> > > *exon_samples;
vector<pair<int, vector<double> > > *intron_samples;
int num_features;
double prob_true_false_exons;
double prob_true_false_introns;
vector<int> exon_feature_idx;
vector<int> intron_feature_idx;
void set_mean_std(vector<pair<int, vector<double> > > *samples, vector<int> feature_idx);
};
double activation_f(const gsl_vector *theta, vector<double> *f);
double get_feature(vector<double> *f, int i);
double cross_entropy_error_f(const gsl_vector *theta, void *features);
void cross_entropy_error_df(const gsl_vector *theta, void *features, gsl_vector *df);
void cross_entropy_error_fdf(const gsl_vector *params, void *features, double *f, gsl_vector *df);
double rob_cross_entropy_error_f(const gsl_vector *theta, void *features);
void rob_cross_entropy_error_df(const gsl_vector *theta, void *features, gsl_vector *df);
void rob_cross_entropy_error_fdf(const gsl_vector *params, void *features, double *f, gsl_vector *df);
void optimize_parameters(train_data *data);
void reference_from_file(unordered_map<string,int> *ref_class);
void trainFeature_from_file();
void train_OEscore_params(int numSpecies);
void sgd(vector<pair<int, vector<double> > > *samples, gsl_vector *theta, int n);
void gsl_minimizer(vector<pair<int, vector<double> > > *samples, gsl_vector *theta, int n);
#endif
| 33.435484 | 123 | 0.763145 | [
"vector"
] |
4b045f8e01455d287ab3c8951110094a6fc22d8c | 32,002 | cc | C++ | lite/backends/opencl/cl_runtime.cc | sryio/Paddle-Lite | 9fbc45f5821488af1329554c11fd8eb7257e1484 | [
"Apache-2.0"
] | 6 | 2020-07-01T02:52:16.000Z | 2021-06-22T12:15:59.000Z | lite/backends/opencl/cl_runtime.cc | sryio/Paddle-Lite | 9fbc45f5821488af1329554c11fd8eb7257e1484 | [
"Apache-2.0"
] | null | null | null | lite/backends/opencl/cl_runtime.cc | sryio/Paddle-Lite | 9fbc45f5821488af1329554c11fd8eb7257e1484 | [
"Apache-2.0"
] | 1 | 2021-07-24T15:30:46.000Z | 2021-07-24T15:30:46.000Z | /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "lite/backends/opencl/cl_runtime.h"
#include <string>
#include <utility>
#include <vector>
#include "lite/backends/opencl/utils/cache.h"
#include "lite/core/target_wrapper.h"
#include "lite/core/version.h"
#include "lite/utils/cp_logging.h"
#include "lite/utils/io.h"
#include "lite/utils/string.h"
namespace paddle {
namespace lite {
CLRuntime* CLRuntime::Global() {
static CLRuntime cl_runtime_;
cl_runtime_.Init();
return &cl_runtime_;
}
void CLRuntime::Flush(const int index) {
if (is_cl_runtime_initialized_ && gpu_type_ == GpuType::ARM_MALI &&
index % opencl_flush_period_ == 0) {
command_queue_->flush();
}
}
CLRuntime::~CLRuntime() {
SaveProgram();
SaveTuned();
#ifdef LITE_WITH_LOG
LOG(INFO) << "is_cl_runtime_initialized_:" << is_cl_runtime_initialized_;
#endif
if (is_cl_runtime_initialized_ == false) {
return;
}
if (command_queue_ != nullptr) {
command_queue_->flush();
command_queue_->finish();
}
// For controlling the destruction order
command_queue_.reset();
context_.reset();
device_.reset();
platform_.reset();
device_info_.clear();
}
bool CLRuntime::Init() {
#ifdef LITE_WITH_LOG
VLOG(6) << "is_cl_runtime_initialized_:" << is_cl_runtime_initialized_;
#endif
if (is_cl_runtime_initialized_) {
return true;
}
bool opencl_lib_found = paddle::lite::CLWrapper::Global()->OpenclLibFound();
#ifdef LITE_WITH_LOG
LOG(INFO) << "opencl_lib_found:" << opencl_lib_found;
#endif
if (opencl_lib_found == false) {
return false;
}
bool dlsym_success = paddle::lite::CLWrapper::Global()->DlsymSuccess();
#ifdef LITE_WITH_LOG
LOG(INFO) << "dlsym_success:" << dlsym_success;
#endif
if (dlsym_success == false) {
return false;
}
bool is_platform_init = InitializePlatform();
#ifdef LITE_WITH_LOG
LOG(INFO) << "is_platform_init:" << is_platform_init;
#endif
if (is_platform_init == false) {
return false;
}
bool is_device_init = InitializeDevice();
#ifdef LITE_WITH_LOG
LOG(INFO) << "is_device_init:" << is_device_init;
#endif
if (is_device_init == false) {
return false;
}
if ((is_platform_init == true) && (is_device_init == true)) {
is_platform_device_init_success_ = true;
context_ = CreateContext();
command_queue_ = CreateCommandQueue(context());
is_cl_runtime_initialized_ = true;
#ifdef LITE_WITH_LOG
LOG(INFO) << "set is_cl_runtime_initialized_ = true";
#endif
}
set_precision();
return is_cl_runtime_initialized_;
}
cl::Platform& CLRuntime::platform() {
CHECK(platform_ != nullptr) << "platform_ is not initialized!";
return *platform_;
}
cl::Context& CLRuntime::context() {
if (context_ == nullptr) {
LOG(FATAL) << "context_ create failed, check whether context create "
"successfully in CreateContext!";
}
return *context_;
}
cl::Device& CLRuntime::device() {
if (device_ == nullptr) {
LOG(FATAL) << "device_ is not initialized!";
}
return *device_;
}
std::map<std::string, std::unique_ptr<cl::Program>>& CLRuntime::program_map() {
return programs_;
}
cl::CommandQueue& CLRuntime::command_queue() {
if (command_queue_ == nullptr) {
LOG(FATAL) << "command_queue_ create failed, check whether command queue "
"create successfully in CreateCommandQueue!";
}
return *command_queue_;
}
cl::Program& CLRuntime::GetProgram(const std::string& file_name,
const std::string& options) {
/* -I +CLRuntime::Global()->cl_path() + "/cl_kernel"*/
std::string build_option = options + " -cl-fast-relaxed-math -cl-mad-enable";
if (build_option.find("CL_DTYPE_") == std::string::npos) {
if (lite_api::CL_PRECISION_FP16 == get_precision()) {
build_option += " -DCL_DTYPE_half ";
} else {
build_option += " -DCL_DTYPE_float -DCL_DTYPE_FLOAT_FORCE ";
}
}
#ifdef LITE_WITH_LOG
VLOG(4) << "precision_: " << CLPrecisionTypeToStr(precision_);
VLOG(4) << "OpenCL build_option: " << build_option;
#endif
STL::stringstream program_key_ss;
program_key_ss << file_name << build_option;
std::string program_key = program_key_ss.str();
// Build flow: cache -> precompiled binary -> source
bool ret = CheckFromCache(program_key);
if (!ret) {
ret = CheckFromPrecompiledBinary(program_key, build_option);
if (!ret) {
ret = CheckFromSource(file_name, program_key, build_option);
}
}
if (ret) {
return *(programs_[program_key]);
} else {
LOG(FATAL) << "GetProgram failed, program_key: " << program_key;
}
}
bool CLRuntime::CheckFromCache(const std::string& program_key) {
auto iter = programs_.find(program_key);
if (iter != programs_.end()) {
#ifdef LITE_WITH_LOG
VLOG(3) << " --- program -> " << program_key
<< " has been built in cache --- ";
#endif
return true;
} else {
return false;
}
}
bool CLRuntime::CheckFromPrecompiledBinary(const std::string& program_key,
const std::string& build_option) {
bool ret = false;
bool delete_bin_flag = false;
auto path_name = GetBinaryPathName();
if (path_name.size() != 2) return ret;
// find binary
std::string bin_file = path_name.at(0) + "/" + path_name.at(1);
auto remove_file = [](const std::string& bin_file) {
if (remove(bin_file.c_str()) != 0) {
LOG(FATAL) << "Cannot delete invalid precomplied OpenCL binary["
<< bin_file << "]!";
} else {
LOG(INFO) << "Invalid precomplied OpenCL binary[" << bin_file
<< "] has been deleted!";
}
};
if (programs_.empty()) {
// check whether binary exist
if (!IsFileExists(bin_file)) {
LOG(WARNING)
<< "There is no precompiled OpenCL binary[" << bin_file
<< "] in the given OpenCL binary path. "
"Also please make sure the storage directory exist "
"and you have Write&Read permission. Jump to build program "
"from source.";
} else {
LOG(INFO) << "Load opencl kernel bin file: " << bin_file;
bool success = Deserialize(bin_file, &programs_precompiled_binary_);
CHECK(success) << "Deserialize failed!";
VLOG(3) << "sn_key: " << sn_key_;
VLOG(3) << "map size: " << programs_precompiled_binary_.size();
for (auto& ins : programs_precompiled_binary_) {
std::string prog_key = ins.first;
VLOG(3) << "\t map key: " << prog_key
<< "\t map value size: " << ins.second[0].size();
}
// check if the binary file is illegal and valid
auto sn_iter = programs_precompiled_binary_.find(sn_key_);
if (sn_iter == programs_precompiled_binary_.end()) {
LOG(WARNING) << "The precompiled OpenCL binary[" << bin_file
<< "] is illegal!";
delete_bin_flag = true;
// Jump to build from source
} else if (host::memcmp(((sn_iter->second)[0]).data(),
GetSN(build_option).data(),
GetSN(build_option).length())) {
std::string sn_str(reinterpret_cast<char*>((sn_iter->second)[0].data()),
(sn_iter->second)[0].size());
LOG(INFO) << "\nSN required: " << GetSN(build_option)
<< "\tsize: " << GetSN(build_option).length()
<< "\nSN in bin file: " << sn_str
<< "\tsize: " << ((sn_iter->second)[0]).size();
LOG(WARNING) << "The precompiled OpenCL binary[" << bin_file
<< "] is invalid!";
delete_bin_flag = true;
// Jump to build from source
} else {
#ifdef LITE_WITH_LOG
VLOG(3) << " --- begin read all precompiled programs from binary --- ";
#endif
// loop all programs of the binary file
cl_int status{CL_SUCCESS};
for (auto& ins : programs_precompiled_binary_) {
std::string prog_key = ins.first;
if (prog_key == sn_key_) continue; // skip sn_key
cl::Program program(
context(), {device()}, ins.second, nullptr, &status);
CL_CHECK_FATAL_SOLID(status);
auto pos_start = prog_key.find_first_of("-D");
std::string options = prog_key.substr(pos_start);
BuildProgram(&program, options);
std::unique_ptr<cl::Program> ptr(new cl::Program(program));
programs_[prog_key] = std::move(ptr);
}
auto it = programs_.find(program_key);
if (it != programs_.end()) {
VLOG(3) << " --- program -> " << program_key
<< " has been built in binary --- ";
gotten_bin_flag_ = true;
ret = true;
} else {
delete_bin_flag = true;
// Jump to build from source
}
}
}
if (delete_bin_flag) {
remove_file(bin_file);
programs_precompiled_binary_.clear();
programs_.clear();
}
} else if (gotten_bin_flag_) {
// This case happened when model has updated. Bin file should be updated
// accordingly.
delete_bin_flag = true;
gotten_bin_flag_ = false;
remove_file(bin_file);
}
return ret;
}
bool CLRuntime::CheckFromSource(const std::string& file_name,
const std::string& program_key,
const std::string& build_option) {
auto ptr = CreateProgramFromSource(context(), file_name);
auto program = ptr.get();
#ifdef LITE_WITH_LOG
VLOG(3) << " --- begin build program from source -> " << program_key
<< " --- ";
#endif
BuildProgram(program, build_option);
// Keep built program binary
if (binary_path_name_.size() == 2) {
cl_int status{CL_SUCCESS};
// 1. Query binary (PTX file) size
size_t bin_size;
status = program->getInfo(CL_PROGRAM_BINARY_SIZES, &bin_size);
CL_CHECK_FATAL_SOLID(status);
// 2. Read binary (PTX file) to memory buffer
cl::Program::Binaries binary;
binary.resize(1);
binary[0].resize(bin_size);
auto buf = binary[0].data();
status = program->getInfo(CL_PROGRAM_BINARIES, &buf);
CL_CHECK_FATAL_SOLID(status);
programs_precompiled_binary_[program_key] = binary;
#ifdef LITE_WITH_LOG
VLOG(3) << " --- binary size: " << bin_size << " ---";
#endif
if (programs_precompiled_binary_.find(sn_key_) ==
programs_precompiled_binary_.end()) {
// add identifier
std::string sn = GetSN(build_option);
std::vector<unsigned char> sn_info(sn.data(), sn.data() + sn.size());
programs_precompiled_binary_[sn_key_] = {sn_info};
}
}
programs_[program_key] = std::move(ptr);
return true;
}
std::unique_ptr<cl::Program> CLRuntime::CreateProgramFromSource(
const cl::Context& context, std::string file_name) {
auto cl_file = opencl_kernels_files.find(file_name);
std::string content(cl_file->second.begin(), cl_file->second.end());
cl::Program::Sources sources;
sources.push_back(content);
auto prog =
std::unique_ptr<cl::Program>(new cl::Program(context, sources, &status_));
#ifdef LITE_WITH_LOG
VLOG(4) << "OpenCL kernel file name: " << file_name;
VLOG(4) << "Program source size: " << content.size();
#endif
CL_CHECK_FATAL_SOLID(status_);
return std::move(prog);
}
bool CLRuntime::BuildProgram(cl::Program* program, const std::string& options) {
status_ = program->build({device()}, options.c_str());
CL_CHECK_ERROR(status_);
if (status_ != CL_SUCCESS) {
if (program->getBuildInfo<CL_PROGRAM_BUILD_STATUS>(device()) ==
CL_BUILD_ERROR) {
std::string log = program->getBuildInfo<CL_PROGRAM_BUILD_LOG>(device());
LOG(FATAL) << "Program build error: " << log;
}
return false;
}
return true;
}
void CLRuntime::SaveProgram() {
if (binary_path_name_.empty()) return;
std::string binary_file =
binary_path_name_.at(0) + "/" + binary_path_name_.at(1);
if (IsFileExists(binary_file)) {
LOG(INFO) << "OpenCL Program existed:" << binary_file;
} else {
bool ret = Serialize(binary_file, programs_precompiled_binary_);
CHECK(ret) << "Serialize failed for opencl binary_file:" << binary_file;
#ifdef LITE_WITH_LOG
if (programs_precompiled_binary_.find(sn_key_) !=
programs_precompiled_binary_.end()) {
std::string sn_str(reinterpret_cast<char*>(
programs_precompiled_binary_[sn_key_][0].data()),
programs_precompiled_binary_[sn_key_][0].size());
LOG(INFO) << "SN stored: " << sn_str;
}
LOG(INFO) << "Programs have been serialized to disk successfully. File: "
<< binary_file;
#endif
}
}
void CLRuntime::SaveTuned() {
if (tuned_path_name_.empty() || auto_tune() == lite_api::CL_TUNE_NONE) return;
std::string tuned_file =
tuned_path_name_.at(0) + "/" + tuned_path_name_.at(1);
if (tuned_file == "/") {
LOG(INFO) << "invalid tuned_file:" << tuned_file;
} else if (IsFileExists(tuned_file)) {
LOG(INFO) << "OpenCL Tuned file existed:" << tuned_file;
} else {
bool ret = Serialize(tuned_file, tuned_lwss_map_);
CHECK(ret) << "Serialize failed for opencl tuned_file:" << tuned_file;
LOG(INFO) << "Tuned file have been serialized to disk successfully: "
<< tuned_file;
}
}
// binary
bool CLRuntime::Serialize(
const std::string file_name,
const std::map<std::string, cl::Program::Binaries>& map_data) {
fbs::opencl::Cache cache{map_data};
std::vector<uint8_t> buffer;
cache.CopyDataToBuffer(&buffer);
WriteFile<uint8_t>(file_name, buffer);
return true;
}
bool CLRuntime::Deserialize(
const std::string file_name,
std::map<std::string, cl::Program::Binaries>* map_ptr) {
std::vector<uint8_t> buffer;
ReadFile<uint8_t>(file_name, &buffer);
fbs::opencl::Cache cache{buffer};
*map_ptr = cache.GetBinaryMap();
return true;
}
// tuned param
bool CLRuntime::Serialize(const std::string file_name,
const std::map<std::string, cl::NDRange>& map_data) {
std::map<std::string, std::vector<int>> map_data_cpy;
for (auto& kv : map_data) {
#ifdef LITE_WITH_LOG
VLOG(3) << std::to_string(static_cast<int>(kv.second[0])) << ","
<< std::to_string(static_cast<int>(kv.second[1])) << ","
<< std::to_string(static_cast<int>(kv.second[2]));
#endif
map_data_cpy.insert(std::pair<std::string, std::vector<int>>(
kv.first,
{static_cast<int>(kv.second[0]),
static_cast<int>(kv.second[1]),
static_cast<int>(kv.second[2])}));
}
fbs::opencl::TuneCache cache{map_data_cpy};
std::vector<int> buffer;
cache.CopyDataToBuffer(&buffer);
WriteFile<int>(file_name, buffer);
return true;
}
bool CLRuntime::Deserialize(const std::string file_name,
std::map<std::string, cl::NDRange>* map_ptr) {
std::vector<int> buffer;
ReadFile<int>(file_name, &buffer);
fbs::opencl::TuneCache cache{buffer};
std::map<std::string, std::vector<int>> tmp_map = cache.GetBinaryMap();
for (auto& kv : tmp_map) {
cl::NDRange range{static_cast<cl::size_type>(kv.second[0]),
static_cast<cl::size_type>(kv.second[1]),
static_cast<cl::size_type>(kv.second[2])};
#ifdef LITE_WITH_LOG
VLOG(3) << std::to_string(kv.second[0]) << ","
<< std::to_string(kv.second[1]) << ","
<< std::to_string(kv.second[2]);
#endif
map_ptr->insert(std::pair<std::string, cl::NDRange>(kv.first, range));
}
return true;
}
std::string CLRuntime::GetSN(const std::string options) {
// Identifier info(Serial Number) for each binary file: lite version,
// build options, platform info, device version, driver version
STL::stringstream sn_ss;
const std::string aarch =
#if defined(__aarch64__)
"android_armv8";
#else
"android_armv7";
#endif
#if defined(_WIN64)
"win64";
#elif defined(_WIN32)
"win32";
#endif
const std::string aarch_info = aarch + "; ";
const std::string lite_version = lite::version() + "; ";
const std::string platform_info =
platform_->getInfo<CL_PLATFORM_NAME>() + ", " +
platform_->getInfo<CL_PLATFORM_PROFILE>() + "; ";
const std::string device_version =
device_->getInfo<CL_DEVICE_VERSION>() + "; ";
const std::string driver_version =
device_->getInfo<CL_DRIVER_VERSION>() + "; ";
const std::string place_holder{"place_holder"};
sn_ss << aarch_info << lite_version << options << platform_info
<< device_version << driver_version << place_holder;
return sn_ss.str();
}
std::unique_ptr<cl::UserEvent> CLRuntime::CreateEvent(
const cl::Context& context) {
auto event =
std::unique_ptr<cl::UserEvent>(new cl::UserEvent(context, &status_));
CL_CHECK_FATAL_SOLID(status_);
return std::move(event);
}
bool CLRuntime::InitializePlatform() {
std::vector<cl::Platform> all_platforms;
status_ = cl::Platform::get(&all_platforms);
// has return status do not exit here when release
CL_CHECK_ERROR(status_);
if (all_platforms.empty()) {
LOG(ERROR) << "No OpenCL platform found!";
return false;
}
platform_ = std::make_shared<cl::Platform>();
*platform_ = all_platforms[0];
const std::string extensions = platform_->getInfo<CL_PLATFORM_EXTENSIONS>();
LOG(INFO) << "Platform extension: " << extensions;
return true;
}
OpenCLVersion CLRuntime::ParseDeviceVersion(const std::string& device_version) {
// OpenCL Device version string format:
// OpenCL<space><major_version.minor_version><space>
// <vendor-specific information>
auto words = Split<std::string>(device_version, std::string{" "});
if (words[1] == "2.1") {
return OpenCLVersion::CL_VER_2_1;
} else if (words[1] == "2.0") {
return OpenCLVersion::CL_VER_2_0;
} else if (words[1] == "1.2") {
return OpenCLVersion::CL_VER_1_2;
} else if (words[1] == "1.1") {
return OpenCLVersion::CL_VER_1_1;
} else if (words[1] == "1.0") {
return OpenCLVersion::CL_VER_1_0;
} else {
LOG(ERROR) << "Do not support OpenCL version: " << words[1];
return OpenCLVersion::CL_VER_UNKNOWN;
}
}
GpuType CLRuntime::ParseGpuTypeFromDeviceName(std::string device_name) {
const std::string kMALI_PATTERN_STR = "Mali";
const std::string kADRENO_PATTERN_STR = "QUALCOMM Adreno(TM)";
const std::string kPOWERVR_PATTERN_STR = "PowerVR";
std::string gpu_type_str = "";
if (device_name == kADRENO_PATTERN_STR) {
gpu_type_str = "adreno gpu";
return GpuType::QUALCOMM_ADRENO;
} else if (device_name.find(kMALI_PATTERN_STR) != std::string::npos) {
gpu_type_str = "mali gpu";
return GpuType::ARM_MALI;
} else if (device_name.find(kPOWERVR_PATTERN_STR) != std::string::npos) {
gpu_type_str = "powerVR gpu";
return GpuType::IMAGINATION_POWERVR;
} else {
gpu_type_str = "others gpu";
return GpuType::UNKNOWN;
}
#ifdef LITE_WITH_LOG
LOG(INFO) << "gpu_type_str:" << gpu_type_str;
#endif
}
bool CLRuntime::InitializeDevice() {
// initialized without valid opencl device
if (device_info_.size() > 0 && device_info_.size() <= 2) {
return false;
}
// initialized with valid opencl device
if (device_info_.size() > 2) {
return true;
}
device_info_["PLACEHOLDER"] = 1;
// ===================== BASIC =====================
// CL_DEVICE_TYPE_GPU
// CL_DEVICE_NAME
// CL_DEVICE_SUPPORT
// CL_DEVICE_MAX_COMPUTE_UNITS
// CL_DEVICE_MAX_CLOCK_FREQUENCY
std::vector<cl::Device> all_devices;
status_ = platform_->getDevices(CL_DEVICE_TYPE_GPU, &all_devices);
// for is_opencl_valid_api . do not exit here...
CL_CHECK_ERROR(status_);
if (all_devices.empty()) {
LOG(ERROR)
<< "No available OpenCL GPU device found!, Try CPU Device instead!";
status_ = platform_->getDevices(CL_DEVICE_TYPE_CPU, &all_devices);
CL_CHECK_ERROR(status_);
if (all_devices.empty()) {
return false;
}
}
device_ = std::make_shared<cl::Device>();
*device_ = all_devices[0];
auto device_name = device_->getInfo<CL_DEVICE_NAME>();
LOG(INFO) << "Using device: " << device_name;
gpu_type_ = ParseGpuTypeFromDeviceName(device_name);
cl_device_type device_type = device_->getInfo<CL_DEVICE_TYPE>();
auto device_type_to_str = [](cl_device_type t) -> std::string {
std::string t_str{""};
switch (t) {
case CL_DEVICE_TYPE_CPU:
t_str = "CPU";
break;
case CL_DEVICE_TYPE_GPU:
t_str = "GPU";
break;
case CL_DEVICE_TYPE_ACCELERATOR:
t_str = "Accelerator";
break;
case CL_DEVICE_TYPE_DEFAULT:
t_str = "Default";
break;
default:
t_str = "Unknown";
}
return t_str;
};
auto device_version = device_->getInfo<CL_DEVICE_VERSION>();
LOG(INFO) << "CL_DEVICE_VERSION:" << device_version;
auto opencl_version = ParseDeviceVersion(device_version);
if (opencl_version == OpenCLVersion::CL_VER_UNKNOWN) {
LOG(ERROR) << "Parse device version[" << device_version << "] failed!";
}
device_info_["CL_DEVICE_VERSION"] = opencl_version;
LOG(INFO) << "device_type:" << device_type_to_str(device_type);
device_info_["CL_DEVICE_TYPE"] = device_type;
auto max_units = device_->getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
LOG(INFO) << "The chosen device has " << max_units << " compute units.";
device_info_["CL_DEVICE_MAX_COMPUTE_UNITS"] = max_units;
auto max_clock_freq = device_->getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>();
LOG(INFO) << "CL_DEVICE_MAX_CLOCK_FREQUENCY:" << max_clock_freq;
device_info_["CL_DEVICE_MAX_CLOCK_FREQUENCY"] = max_clock_freq;
// ===================== MEMORY =====================
// CL_DEVICE_LOCAL_MEM_SIZE
// CL_DEVICE_GLOBAL_MEM_CACHE_SIZE
// CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE
// CL_DEVICE_GLOBAL_MEM_SIZE
auto local_mem_kb =
static_cast<float>(device_->getInfo<CL_DEVICE_LOCAL_MEM_SIZE>()) / 1024;
LOG(INFO) << "The local memory size of the chosen device is " << local_mem_kb
<< " KB.";
device_info_["CL_DEVICE_LOCAL_MEM_SIZE_KB"] = local_mem_kb;
auto global_mem_cache_size_kb =
static_cast<float>(device_->getInfo<CL_DEVICE_GLOBAL_MEM_CACHE_SIZE>()) /
1024;
LOG(INFO) << "CL_DEVICE_GLOBAL_MEM_CACHE_SIZE(KB):"
<< global_mem_cache_size_kb << " KB.";
device_info_["CL_DEVICE_GLOBAL_MEM_CACHE_SIZE_KB"] = global_mem_cache_size_kb;
auto global_mem_cacheline_size_kb =
static_cast<float>(
device_->getInfo<CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE>()) /
1024;
LOG(INFO) << "CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE(KB):"
<< global_mem_cacheline_size_kb << " KB.";
device_info_["CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE_KB"] =
global_mem_cacheline_size_kb;
auto global_mem_size_kb =
static_cast<float>(device_->getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>()) / 1024;
LOG(INFO) << "CL_DEVICE_GLOBAL_MEM_SIZE(KB):" << global_mem_size_kb << " KB.";
device_info_["CL_DEVICE_GLOBAL_MEM_SIZE_KB"] = global_mem_size_kb;
// ===================== WORK_GROUP =====================
// CL_DEVICE_MAX_WORK_GROUP_SIZE
// CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS
// CL_DEVICE_MAX_WORK_ITEM_SIZES
auto max_work_group_size = device_->getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>();
LOG(INFO) << "CL_DEVICE_MAX_WORK_GROUP_SIZE:" << max_work_group_size;
device_info_["CL_DEVICE_MAX_WORK_GROUP_SIZE"] = max_work_group_size;
auto max_dims_num = device_->getInfo<CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS>();
LOG(INFO) << "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS:" << max_dims_num;
device_info_["CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS"] = max_dims_num;
auto max_work_item_sizes = device_->getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>();
for (size_t i = 0; i < max_work_item_sizes.size(); ++i) {
LOG(INFO) << "max_work_item_sizes[" << i << "]:" << max_work_item_sizes[i];
std::string dim_key = "CL_DEVICE_MAX_WORK_ITEM_SIZES_" + std::to_string(i);
device_info_[dim_key] = max_work_item_sizes[i];
}
// ===================== BUFFER =====================
// CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE
auto max_constant_buffer_size_kb =
static_cast<float>(
device_->getInfo<CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE>()) /
1024;
LOG(INFO) << "CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE:"
<< max_constant_buffer_size_kb;
device_info_["CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE"] =
max_constant_buffer_size_kb;
// ===================== IMAGE =====================
// CL_DEVICE_IMAGE_SUPPORT
// CL_DEVICE_IMAGE2D_MAX_HEIGHT
// CL_DEVICE_IMAGE2D_MAX_WIDTH
auto image_support = device_->getInfo<CL_DEVICE_IMAGE_SUPPORT>();
if (image_support) {
LOG(INFO) << "The chosen device supports image processing.";
device_info_["CL_DEVICE_IMAGE_SUPPORT"] = 1;
auto image2d_max_height = device_->getInfo<CL_DEVICE_IMAGE2D_MAX_HEIGHT>();
LOG(INFO) << "CL_DEVICE_IMAGE2D_MAX_HEIGHT:" << image2d_max_height;
device_info_["CL_DEVICE_IMAGE2D_MAX_HEIGHT"] = image2d_max_height;
auto image2d_max_width = device_->getInfo<CL_DEVICE_IMAGE2D_MAX_WIDTH>();
LOG(INFO) << "CL_DEVICE_IMAGE2D_MAX_WIDTH:" << image2d_max_width;
device_info_["CL_DEVICE_IMAGE2D_MAX_WIDTH"] = image2d_max_width;
} else {
LOG(ERROR) << "The chosen device doesn't support image processing!";
device_info_["CL_DEVICE_IMAGE_SUPPORT"] = 0;
return false;
}
// ===================== OTHERS / EXTENSION / VERSION =====================
// CL_DEVICE_EXTENSIONS
// CL_DEVICE_ADDRESS_BITS
auto ext_data = device_->getInfo<CL_DEVICE_EXTENSIONS>();
VLOG(4) << "The extensions supported by this device: " << ext_data;
if (ext_data.find("cl_khr_fp16") != std::string::npos) {
LOG(INFO) << "The chosen device supports the half data type.";
device_info_["CL_DEVICE_EXTENSIONS_FP16"] = 1;
} else {
LOG(INFO) << "The chosen device doesn't support the half data type!";
device_info_["CL_DEVICE_EXTENSIONS_FP16"] = 0;
}
auto address_bits = device_->getInfo<CL_DEVICE_ADDRESS_BITS>();
LOG(INFO) << "CL_DEVICE_ADDRESS_BITS:" << address_bits;
device_info_["CL_DEVICE_ADDRESS_BITS"] = address_bits;
auto driver_version = device_->getInfo<CL_DRIVER_VERSION>();
LOG(INFO) << "CL_DRIVER_VERSION:" << driver_version;
#ifdef LITE_WITH_LOG
VLOG(3) << "device_info_.size():" << device_info_.size();
for (auto i : device_info_) {
VLOG(3) << ">>> " << i.first << " " << i.second;
}
#endif
return true;
}
std::map<std::string, size_t>& CLRuntime::GetDeviceInfo() {
InitializeDevice();
return device_info_;
}
GpuType& CLRuntime::GetGpuType() { return gpu_type_; }
void CLRuntime::GetAdrenoContextProperties(
std::vector<cl_context_properties>* properties,
GPUPerfMode gpu_perf_mode,
GPUPriorityLevel gpu_priority_level) {
if (properties == nullptr) {
LOG(ERROR) << "cl_context_properties is nullptr";
return;
}
properties->reserve(5);
switch (gpu_perf_mode) {
case GPUPerfMode::PERF_LOW:
LOG(INFO) << "GPUPerfMode::PERF_LOW";
properties->push_back(CL_CONTEXT_PERF_MODE_QCOM);
properties->push_back(CL_PERF_MODE_LOW_QCOM);
break;
case GPUPerfMode::PERF_NORMAL:
LOG(INFO) << "GPUPerfMode::PERF_NORMAL";
properties->push_back(CL_CONTEXT_PERF_MODE_QCOM);
properties->push_back(CL_PERF_MODE_NORMAL_QCOM);
break;
case GPUPerfMode::PERF_HIGH:
LOG(INFO) << "GPUPerfMode::PERF_HIGH";
properties->push_back(CL_CONTEXT_PERF_MODE_QCOM);
properties->push_back(CL_PERF_MODE_HIGH_QCOM);
break;
default:
break;
}
switch (gpu_priority_level) {
case GPUPriorityLevel::PRIORITY_LOW:
LOG(INFO) << "GPUPriorityLevel::PRIORITY_LOW";
properties->push_back(CL_CONTEXT_PRIORITY_LEVEL_QCOM);
properties->push_back(CL_PRIORITY_HINT_LOW_QCOM);
break;
case GPUPriorityLevel::PRIORITY_NORMAL:
LOG(INFO) << "GPUPriorityLevel::PRIORITY_NORMAL";
properties->push_back(CL_CONTEXT_PRIORITY_LEVEL_QCOM);
properties->push_back(CL_PRIORITY_HINT_NORMAL_QCOM);
break;
case GPUPriorityLevel::PRIORITY_HIGH:
LOG(INFO) << "GPUPriorityLevel::PRIORITY_HIGH";
properties->push_back(CL_CONTEXT_PRIORITY_LEVEL_QCOM);
properties->push_back(CL_PRIORITY_HINT_HIGH_QCOM);
break;
default:
break;
}
// The properties list should be terminated with 0
properties->push_back(0);
}
uint64_t CLRuntime::GetMaxWorkGroupSize(const cl::Kernel& kernel) {
uint64_t max_workgroup_size = 0;
int ret = kernel.getWorkGroupInfo(
*device_, CL_KERNEL_WORK_GROUP_SIZE, &max_workgroup_size);
if (ret != 0) max_workgroup_size = 0;
return max_workgroup_size;
}
void CLRuntime::set_auto_tune(lite_api::CLTuneMode tune_mode,
const std::string& path,
const std::string& name,
size_t lws_repeats) {
auto_tune_ = tune_mode;
auto device_name = CLRuntime::Global()->device().getInfo<CL_DEVICE_NAME>();
if (device_name.find("Mali-T860") != std::string::npos) {
auto_tune_ = lite_api::CL_TUNE_NONE;
}
lws_repeats_ = lws_repeats;
if (tuned_path_name_.empty()) {
tuned_path_name_.push_back(path);
tuned_path_name_.push_back(name);
}
const std::string tuned_file = path + "/" + name;
LOG(INFO) << "tuned_file.size():" << tuned_file.size()
<< ", tuned_file:" << tuned_file;
if (tuned_file.size() > 2 && IsFileExists(tuned_file) &&
auto_tune() != lite_api::CL_TUNE_NONE) {
LOG(INFO) << "Load tuned file: " << tuned_file;
bool status = Deserialize(tuned_file, &tuned_lwss_map_);
if (!status) {
LOG(ERROR) << "failed to deserialize tuned_file:" << tuned_file;
}
} else {
LOG(INFO) << "Not found tuned file:" << tuned_file;
}
command_queue_ = CreateCommandQueue(context());
}
bool CLRuntime::HasTunedLocalWorkSizeMap(const std::string& key,
cl::NDRange* lws) {
bool has = false;
auto it = tuned_lwss_map_.find(key);
if (it != tuned_lwss_map_.end()) {
*lws = it->second;
has = true;
}
return has;
}
void CLRuntime::SetTunedLocalWorkSizeMap(const std::string& key,
const cl::NDRange lws) {
auto it = tuned_lwss_map_.find(key);
if (it != tuned_lwss_map_.end()) {
auto lws_old = it->second;
LOG(FATAL) << "===> found lws_old with same key, please add more detailed "
"info to key <==="
<< "\n lws_old:" << lws_old[0] << "," << lws_old[1] << ","
<< lws_old[2] << "\n lws_new:" << lws[0] << "," << lws[1] << ","
<< lws[2];
}
tuned_lwss_map_.insert(std::pair<std::string, cl::NDRange>(key, lws));
}
double CLRuntime::GetCommandTime(const cl::Event& event) {
event.wait();
auto start_nanos = event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
auto stop_nanos = event.getProfilingInfo<CL_PROFILING_COMMAND_END>();
return (stop_nanos - start_nanos) / 1000000.0;
}
double CLRuntime::GetQueuedTime(const cl::Event& event) {
event.wait();
return (event.getProfilingInfo<CL_PROFILING_COMMAND_START>() -
event.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>()) /
1000000.0;
}
double CLRuntime::GetSubmitTime(const cl::Event& event) {
event.wait();
return (event.getProfilingInfo<CL_PROFILING_COMMAND_START>() -
event.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>()) /
1000000.0;
}
} // namespace lite
} // namespace paddle
| 34.559395 | 80 | 0.657678 | [
"vector",
"model"
] |
4b0b534d119c562de864a2d65ba30a683e7facb4 | 1,960 | cpp | C++ | src/test/TestConfiguration.cpp | vallant/reta | f9eb515a956ebdb8163beda0cd927dfc64875b62 | [
"MIT"
] | 1 | 2022-01-04T17:20:13.000Z | 2022-01-04T17:20:13.000Z | src/test/TestConfiguration.cpp | vallant/reta | f9eb515a956ebdb8163beda0cd927dfc64875b62 | [
"MIT"
] | null | null | null | src/test/TestConfiguration.cpp | vallant/reta | f9eb515a956ebdb8163beda0cd927dfc64875b62 | [
"MIT"
] | null | null | null | #include "TestConfiguration.h"
void TestConfiguration::applyTo (Plugin* plugin) const
{
plugin->prepare (sampleRate, static_cast<size_t> (blockSize), layout);
for ( const auto& pair : parameters )
plugin->setParameter (pair.name, pair.value);
}
std::vector<TestConfiguration> TestConfiguration::sort (const std::vector<TestConfiguration>& input)
{
auto i = input;
auto sort = [] (const TestConfiguration& lhs, const TestConfiguration& rhs) { return lhs.layout < rhs.layout; };
std::sort (i.begin(), i.end(), sort);
return i;
}
std::vector<TestInfos> TestConfiguration::compare (const std::vector<TestConfiguration>& lhs,
const std::vector<TestConfiguration>& rhs)
{
std::vector<TestInfos> infos;
for ( size_t i = 0; i < lhs.size() && i < rhs.size(); ++i )
infos.push_back (lhs[i].compareTo (rhs[i]));
return infos;
}
std::vector<TestInfo> TestConfiguration::compareTo (const TestConfiguration& other) const
{
std::vector<TestInfo> infos;
infos.push_back (RETA_CREATE_TEST (inputSignal));
infos.push_back (RETA_CREATE_TEST (blockSize));
infos.push_back (RETA_CREATE_TEST_FLOAT (sampleRate));
infos.push_back (RETA_CREATE_TEST (inputSignal));
infos.push_back (layout.compareTo (other.layout));
infos.push_back ({"number of values match", std::to_string (parameters.size()),
std::to_string (other.parameters.size()), parameters.size() == other.parameters.size()});
bool matching = true;
for ( size_t i = 0; i < parameters.size() && i < other.parameters.size(); ++i )
{
matching &= juce::approximatelyEqual (parameters[i].value, other.parameters[i].value);
matching &= parameters[i].name == other.parameters[i].name;
}
infos.push_back ({"parameters match", "true", matching ? "true" : "false", matching});
return infos;
}
| 42.608696 | 117 | 0.643367 | [
"vector"
] |
4b0eba67537d39720cc623b3de7ba8fe57f2f5c1 | 599 | cpp | C++ | Medium/48_Rotate_Image.cpp | ShehabMMohamed/LeetCodeCPP | 684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780 | [
"MIT"
] | 1 | 2021-03-15T10:02:10.000Z | 2021-03-15T10:02:10.000Z | Medium/48_Rotate_Image.cpp | ShehabMMohamed/LeetCodeCPP | 684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780 | [
"MIT"
] | null | null | null | Medium/48_Rotate_Image.cpp | ShehabMMohamed/LeetCodeCPP | 684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780 | [
"MIT"
] | null | null | null | class Solution {
public:
void rotate(vector<vector<int>>& M) {
int N = M.size();
int layers = N/2;
for(int layer=0; layer < layers; layer++) {
int first = layer;
int last = N - 1 - layer;
for(int i = first; i < last; i++) {
int offset = i - first;
int top = M[first][i];
M[first][i] = M[last-offset][first];
M[last-offset][first] = M[last][last-offset];
M[last][last-offset] = M[i][last];
M[i][last] = top;
}
}
}
}; | 31.526316 | 61 | 0.417362 | [
"vector"
] |
4b10186383143ecfc260c28ffcdc176b1dfbb682 | 2,695 | cpp | C++ | todd/src/EnemyGoblin.cpp | madd-games/todd-rpg | c28dd5dbaaa51b0e1ba0c3c85868e366853f9a96 | [
"Unlicense"
] | 1 | 2016-11-14T11:31:23.000Z | 2016-11-14T11:31:23.000Z | todd/src/EnemyGoblin.cpp | madd-games/todd-rpg | c28dd5dbaaa51b0e1ba0c3c85868e366853f9a96 | [
"Unlicense"
] | null | null | null | todd/src/EnemyGoblin.cpp | madd-games/todd-rpg | c28dd5dbaaa51b0e1ba0c3c85868e366853f9a96 | [
"Unlicense"
] | null | null | null | /*
===============================================================================================
Todd RPG
Copyright (c) 2014-2016, Madd Games.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===============================================================================================
*/
/**
* EnemyGoblin.cpp
*/
#include "EnemyGoblin.h"
#include "SpriteSheet.h"
#include "Element.h"
#include "Skill.h"
#include "BattleView.h"
#include <stdlib.h>
#include <time.h>
#include "Item.h"
#include <random>
using namespace std;
EnemyGoblin::EnemyGoblin()
{
spriteSheet = ssGoblin;
level = 3;
name = "Goblin";
hp = maxhp = 30;
element = Element::EARTH;
memset(&stats, 0, sizeof(CharStats));
stats.STR = 0;
stats.DEF = -1;
stats.ACC = 70;
stats.AGI = 5;
memset(resist, 0, sizeof(int)*Element::NUM_ELEMENTS);
resist[Element::EARTH] = 10;
resist[Element::AIR] = -50;
resist[Element::WATER] = -10;
resist[Element::FIRE] = -10;
};
Skill *EnemyGoblin::plan()
{
skillAttack->init(battleView.getRandomAlly());
return skillAttack;
};
int getProb()
{
random_device rd;
default_random_engine e1(rd());
uniform_int_distribution<int> mknum(0, 99);
return mknum(e1);
};
void EnemyGoblin::dropItems(vector<int> &drops)
{
srand(time(NULL));
if (getProb() < 40)
{
drops.push_back(Item::MANA_FRUIT);
};
if (getProb() < 30)
{
drops.push_back(Item::POTION);
};
if (getProb() < 20)
{
drops.push_back(Item::GOBLIN_DUST);
};
};
| 26.165049 | 95 | 0.680148 | [
"vector"
] |
4b121da905d34cfcf1f590511c0a39489faeb9df | 19,096 | cpp | C++ | src/gpu/GrStencilAndCoverTextContext.cpp | Igalia/skia | db873d8677a2d4ecfe38a794a5d868301bdeeabe | [
"BSD-3-Clause"
] | 2 | 2019-05-09T17:06:47.000Z | 2020-07-06T16:14:13.000Z | src/gpu/GrStencilAndCoverTextContext.cpp | Igalia/skia | db873d8677a2d4ecfe38a794a5d868301bdeeabe | [
"BSD-3-Clause"
] | null | null | null | src/gpu/GrStencilAndCoverTextContext.cpp | Igalia/skia | db873d8677a2d4ecfe38a794a5d868301bdeeabe | [
"BSD-3-Clause"
] | 3 | 2015-03-13T14:30:30.000Z | 2020-07-06T16:13:36.000Z | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrStencilAndCoverTextContext.h"
#include "GrBitmapTextContext.h"
#include "GrDrawTarget.h"
#include "GrGpu.h"
#include "GrPath.h"
#include "GrPathRange.h"
#include "SkAutoKern.h"
#include "SkDraw.h"
#include "SkDrawProcs.h"
#include "SkGlyphCache.h"
#include "SkGpuDevice.h"
#include "SkPath.h"
#include "SkTextMapStateProc.h"
#include "SkTextFormatParams.h"
GrStencilAndCoverTextContext::GrStencilAndCoverTextContext(
GrContext* context, const SkDeviceProperties& properties)
: GrTextContext(context, properties)
, fStroke(SkStrokeRec::kFill_InitStyle)
, fQueuedGlyphCount(0)
, fFallbackGlyphsIdx(kGlyphBufferSize) {
}
GrStencilAndCoverTextContext* GrStencilAndCoverTextContext::Create(GrContext* context,
const SkDeviceProperties& props) {
GrStencilAndCoverTextContext* textContext = SkNEW_ARGS(GrStencilAndCoverTextContext,
(context, props));
textContext->fFallbackTextContext = GrBitmapTextContext::Create(context, props);
return textContext;
}
GrStencilAndCoverTextContext::~GrStencilAndCoverTextContext() {
}
bool GrStencilAndCoverTextContext::canDraw(const SkPaint& paint, const SkMatrix& viewMatrix) {
if (paint.getRasterizer()) {
return false;
}
if (paint.getMaskFilter()) {
return false;
}
if (paint.getPathEffect()) {
return false;
}
// No hairlines unless we can map the 1 px width to the object space.
if (paint.getStyle() == SkPaint::kStroke_Style
&& paint.getStrokeWidth() == 0
&& viewMatrix.hasPerspective()) {
return false;
}
// No color bitmap fonts.
SkScalerContext::Rec rec;
SkScalerContext::MakeRec(paint, &fDeviceProperties, NULL, &rec);
return rec.getFormat() != SkMask::kARGB32_Format;
}
void GrStencilAndCoverTextContext::onDrawText(GrRenderTarget* rt,
const GrClip& clip,
const GrPaint& paint,
const SkPaint& skPaint,
const SkMatrix& viewMatrix,
const char text[],
size_t byteLength,
SkScalar x, SkScalar y) {
SkASSERT(byteLength == 0 || text != NULL);
if (text == NULL || byteLength == 0 /*|| fRC->isEmpty()*/) {
return;
}
// This is the slow path, mainly used by Skia unit tests. The other
// backends (8888, gpu, ...) use device-space dependent glyph caches. In
// order to match the glyph positions that the other code paths produce, we
// must also use device-space dependent glyph cache. This has the
// side-effect that the glyph shape outline will be in device-space,
// too. This in turn has the side-effect that NVPR can not stroke the paths,
// as the stroke in NVPR is defined in object-space.
// NOTE: here we have following coincidence that works at the moment:
// - When using the device-space glyphs, the transforms we pass to NVPR
// instanced drawing are the global transforms, and the view transform is
// identity. NVPR can not use non-affine transforms in the instanced
// drawing. This is taken care of by SkDraw::ShouldDrawTextAsPaths since it
// will turn off the use of device-space glyphs when perspective transforms
// are in use.
this->init(rt, clip, paint, skPaint, byteLength, kMaxAccuracy_RenderMode, viewMatrix);
// Transform our starting point.
if (fUsingDeviceSpaceGlyphs) {
SkPoint loc;
fContextInitialMatrix.mapXY(x, y, &loc);
x = loc.fX;
y = loc.fY;
}
SkDrawCacheProc glyphCacheProc = fSkPaint.getDrawCacheProc();
const char* stop = text + byteLength;
// Measure first if needed.
if (fSkPaint.getTextAlign() != SkPaint::kLeft_Align) {
SkFixed stopX = 0;
SkFixed stopY = 0;
const char* textPtr = text;
while (textPtr < stop) {
// We don't need x, y here, since all subpixel variants will have the
// same advance.
const SkGlyph& glyph = glyphCacheProc(fGlyphCache, &textPtr, 0, 0);
stopX += glyph.fAdvanceX;
stopY += glyph.fAdvanceY;
}
SkASSERT(textPtr == stop);
SkScalar alignX = SkFixedToScalar(stopX) * fTextRatio;
SkScalar alignY = SkFixedToScalar(stopY) * fTextRatio;
if (fSkPaint.getTextAlign() == SkPaint::kCenter_Align) {
alignX = SkScalarHalf(alignX);
alignY = SkScalarHalf(alignY);
}
x -= alignX;
y -= alignY;
}
SkAutoKern autokern;
SkFixed fixedSizeRatio = SkScalarToFixed(fTextRatio);
SkFixed fx = SkScalarToFixed(x);
SkFixed fy = SkScalarToFixed(y);
while (text < stop) {
const SkGlyph& glyph = glyphCacheProc(fGlyphCache, &text, 0, 0);
fx += SkFixedMul_portable(autokern.adjust(glyph), fixedSizeRatio);
if (glyph.fWidth) {
this->appendGlyph(glyph, SkPoint::Make(SkFixedToScalar(fx), SkFixedToScalar(fy)));
}
fx += SkFixedMul_portable(glyph.fAdvanceX, fixedSizeRatio);
fy += SkFixedMul_portable(glyph.fAdvanceY, fixedSizeRatio);
}
this->finish();
}
void GrStencilAndCoverTextContext::onDrawPosText(GrRenderTarget* rt,
const GrClip& clip,
const GrPaint& paint,
const SkPaint& skPaint,
const SkMatrix& viewMatrix,
const char text[],
size_t byteLength,
const SkScalar pos[],
int scalarsPerPosition,
const SkPoint& offset) {
SkASSERT(byteLength == 0 || text != NULL);
SkASSERT(1 == scalarsPerPosition || 2 == scalarsPerPosition);
// nothing to draw
if (text == NULL || byteLength == 0/* || fRC->isEmpty()*/) {
return;
}
// This is the fast path. Here we do not bake in the device-transform to
// the glyph outline or the advances. This is because we do not need to
// position the glyphs at all, since the caller has done the positioning.
// The positioning is based on SkPaint::measureText of individual
// glyphs. That already uses glyph cache without device transforms. Device
// transform is not part of SkPaint::measureText API, and thus we use the
// same glyphs as what were measured.
this->init(rt, clip, paint, skPaint, byteLength, kMaxPerformance_RenderMode, viewMatrix);
SkDrawCacheProc glyphCacheProc = fSkPaint.getDrawCacheProc();
const char* stop = text + byteLength;
SkTextMapStateProc tmsProc(SkMatrix::I(), offset, scalarsPerPosition);
SkTextAlignProcScalar alignProc(fSkPaint.getTextAlign());
while (text < stop) {
const SkGlyph& glyph = glyphCacheProc(fGlyphCache, &text, 0, 0);
if (glyph.fWidth) {
SkPoint tmsLoc;
tmsProc(pos, &tmsLoc);
SkPoint loc;
alignProc(tmsLoc, glyph, &loc);
this->appendGlyph(glyph, loc);
}
pos += scalarsPerPosition;
}
this->finish();
}
static GrPathRange* get_gr_glyphs(GrContext* ctx,
const SkTypeface* typeface,
const SkDescriptor* desc,
const SkStrokeRec& stroke) {
static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
GrUniqueKey key;
GrUniqueKey::Builder builder(&key, kDomain, 4);
struct GlyphKey {
uint32_t fChecksum;
uint32_t fTypeface;
uint64_t fStroke;
};
GlyphKey* glyphKey = reinterpret_cast<GlyphKey*>(&builder[0]);
glyphKey->fChecksum = desc ? desc->getChecksum() : 0;
glyphKey->fTypeface = typeface ? typeface->uniqueID() : 0;
glyphKey->fStroke = GrPath::ComputeStrokeKey(stroke);
builder.finish();
SkAutoTUnref<GrPathRange> glyphs(
static_cast<GrPathRange*>(ctx->findAndRefCachedResource(key)));
if (NULL == glyphs || (NULL != desc && !glyphs->isEqualTo(*desc))) {
glyphs.reset(ctx->getGpu()->pathRendering()->createGlyphs(typeface, desc, stroke));
ctx->addResourceToCache(key, glyphs);
}
return glyphs.detach();
}
void GrStencilAndCoverTextContext::init(GrRenderTarget* rt,
const GrClip& clip,
const GrPaint& paint,
const SkPaint& skPaint,
size_t textByteLength,
RenderMode renderMode,
const SkMatrix& viewMatrix) {
GrTextContext::init(rt, clip, paint, skPaint);
fContextInitialMatrix = viewMatrix;
fViewMatrix = viewMatrix;
fLocalMatrix = SkMatrix::I();
const bool otherBackendsWillDrawAsPaths =
SkDraw::ShouldDrawTextAsPaths(skPaint, fContextInitialMatrix);
fUsingDeviceSpaceGlyphs = !otherBackendsWillDrawAsPaths &&
kMaxAccuracy_RenderMode == renderMode &&
SkToBool(fContextInitialMatrix.getType() &
(SkMatrix::kScale_Mask | SkMatrix::kAffine_Mask));
if (fUsingDeviceSpaceGlyphs) {
// SkDraw::ShouldDrawTextAsPaths takes care of perspective transforms.
SkASSERT(!fContextInitialMatrix.hasPerspective());
// The whole shape (including stroke) will be baked into the glyph outlines. Make
// NVPR just fill the baked shapes.
fStroke = SkStrokeRec(SkStrokeRec::kFill_InitStyle);
fTextRatio = fTextInverseRatio = 1.0f;
// Glyphs loaded by GPU path rendering have an inverted y-direction.
SkMatrix m;
m.setScale(1, -1);
fViewMatrix = m;
// Post-flip the initial matrix so we're left with just the flip after
// the paint preConcats the inverse.
m = fContextInitialMatrix;
m.postScale(1, -1);
if (!m.invert(&fLocalMatrix)) {
SkDebugf("Not invertible!\n");
return;
}
fGlyphCache = fSkPaint.detachCache(&fDeviceProperties, &fContextInitialMatrix,
true /*ignoreGamma*/);
fGlyphs = get_gr_glyphs(fContext, fGlyphCache->getScalerContext()->getTypeface(),
&fGlyphCache->getDescriptor(), fStroke);
} else {
// Don't bake strokes into the glyph outlines. We will stroke the glyphs
// using the GPU instead. This is the fast path.
fStroke = SkStrokeRec(fSkPaint);
fSkPaint.setStyle(SkPaint::kFill_Style);
if (fStroke.isHairlineStyle()) {
// Approximate hairline stroke.
SkScalar strokeWidth = SK_Scalar1 /
(SkVector::Make(fContextInitialMatrix.getScaleX(),
fContextInitialMatrix.getSkewY()).length());
fStroke.setStrokeStyle(strokeWidth, false /*strokeAndFill*/);
} else if (fSkPaint.isFakeBoldText() &&
#ifdef SK_USE_FREETYPE_EMBOLDEN
kMaxPerformance_RenderMode == renderMode &&
#endif
SkStrokeRec::kStroke_Style != fStroke.getStyle()) {
// Instead of baking fake bold into the glyph outlines, do it with the GPU stroke.
SkScalar fakeBoldScale = SkScalarInterpFunc(fSkPaint.getTextSize(),
kStdFakeBoldInterpKeys,
kStdFakeBoldInterpValues,
kStdFakeBoldInterpLength);
SkScalar extra = SkScalarMul(fSkPaint.getTextSize(), fakeBoldScale);
fStroke.setStrokeStyle(fStroke.needToApply() ? fStroke.getWidth() + extra : extra,
true /*strokeAndFill*/);
fSkPaint.setFakeBoldText(false);
}
bool canUseRawPaths;
if (otherBackendsWillDrawAsPaths || kMaxPerformance_RenderMode == renderMode) {
// We can draw the glyphs from canonically sized paths.
fTextRatio = fSkPaint.getTextSize() / SkPaint::kCanonicalTextSizeForPaths;
fTextInverseRatio = SkPaint::kCanonicalTextSizeForPaths / fSkPaint.getTextSize();
// Compensate for the glyphs being scaled by fTextRatio.
if (!fStroke.isFillStyle()) {
fStroke.setStrokeStyle(fStroke.getWidth() / fTextRatio,
SkStrokeRec::kStrokeAndFill_Style == fStroke.getStyle());
}
fSkPaint.setLinearText(true);
fSkPaint.setLCDRenderText(false);
fSkPaint.setAutohinted(false);
fSkPaint.setHinting(SkPaint::kNo_Hinting);
fSkPaint.setSubpixelText(true);
fSkPaint.setTextSize(SkIntToScalar(SkPaint::kCanonicalTextSizeForPaths));
canUseRawPaths = SK_Scalar1 == fSkPaint.getTextScaleX() &&
0 == fSkPaint.getTextSkewX() &&
!fSkPaint.isFakeBoldText() &&
!fSkPaint.isVerticalText();
} else {
fTextRatio = fTextInverseRatio = 1.0f;
canUseRawPaths = false;
}
SkMatrix textMatrix;
// Glyphs loaded by GPU path rendering have an inverted y-direction.
textMatrix.setScale(fTextRatio, -fTextRatio);
fViewMatrix.preConcat(textMatrix);
fLocalMatrix = textMatrix;
fGlyphCache = fSkPaint.detachCache(&fDeviceProperties, NULL, true /*ignoreGamma*/);
fGlyphs = canUseRawPaths ?
get_gr_glyphs(fContext, fSkPaint.getTypeface(), NULL, fStroke) :
get_gr_glyphs(fContext, fGlyphCache->getScalerContext()->getTypeface(),
&fGlyphCache->getDescriptor(), fStroke);
}
fStateRestore.set(&fPipelineBuilder);
fPipelineBuilder.setFromPaint(fPaint, fRenderTarget, fClip);
GR_STATIC_CONST_SAME_STENCIL(kStencilPass,
kZero_StencilOp,
kZero_StencilOp,
kNotEqual_StencilFunc,
0xffff,
0x0000,
0xffff);
*fPipelineBuilder.stencil() = kStencilPass;
SkASSERT(0 == fQueuedGlyphCount);
SkASSERT(kGlyphBufferSize == fFallbackGlyphsIdx);
}
bool GrStencilAndCoverTextContext::mapToFallbackContext(SkMatrix* inverse) {
// The current view matrix is flipped because GPU path rendering glyphs have an
// inverted y-direction. Unflip the view matrix for the fallback context. If using
// device-space glyphs, we'll also need to restore the original view matrix since
// we moved that transfomation into our local glyph cache for this scenario. Also
// track the inverse operation so the caller can unmap the paint and glyph positions.
if (fUsingDeviceSpaceGlyphs) {
fViewMatrix = fContextInitialMatrix;
if (!fContextInitialMatrix.invert(inverse)) {
return false;
}
inverse->preScale(1, -1);
} else {
inverse->setScale(1, -1);
const SkMatrix& unflip = *inverse; // unflip is equal to its own inverse.
fViewMatrix.preConcat(unflip);
}
return true;
}
inline void GrStencilAndCoverTextContext::appendGlyph(const SkGlyph& glyph, const SkPoint& pos) {
if (fQueuedGlyphCount >= fFallbackGlyphsIdx) {
SkASSERT(fQueuedGlyphCount == fFallbackGlyphsIdx);
this->flush();
}
// Stick the glyphs we can't draw at the end of the buffer, growing backwards.
int index = (SkMask::kARGB32_Format == glyph.fMaskFormat) ?
--fFallbackGlyphsIdx : fQueuedGlyphCount++;
fGlyphIndices[index] = glyph.getGlyphID();
fGlyphPositions[index].set(fTextInverseRatio * pos.x(), -fTextInverseRatio * pos.y());
}
static const SkScalar* get_xy_scalar_array(const SkPoint* pointArray) {
GR_STATIC_ASSERT(2 * sizeof(SkScalar) == sizeof(SkPoint));
GR_STATIC_ASSERT(0 == offsetof(SkPoint, fX));
return &pointArray[0].fX;
}
void GrStencilAndCoverTextContext::flush() {
if (fQueuedGlyphCount > 0) {
SkAutoTUnref<GrPathProcessor> pp(GrPathProcessor::Create(fPaint.getColor(),
fViewMatrix,
fLocalMatrix));
fDrawTarget->drawPaths(&fPipelineBuilder, pp, fGlyphs,
fGlyphIndices, GrPathRange::kU16_PathIndexType,
get_xy_scalar_array(fGlyphPositions),
GrPathRendering::kTranslate_PathTransformType,
fQueuedGlyphCount, GrPathRendering::kWinding_FillType);
fQueuedGlyphCount = 0;
}
if (fFallbackGlyphsIdx < kGlyphBufferSize) {
int fallbackGlyphCount = kGlyphBufferSize - fFallbackGlyphsIdx;
GrPaint paintFallback(fPaint);
SkPaint skPaintFallback(fSkPaint);
if (!fUsingDeviceSpaceGlyphs) {
fStroke.applyToPaint(&skPaintFallback);
}
skPaintFallback.setTextAlign(SkPaint::kLeft_Align); // Align has already been accounted for.
skPaintFallback.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
SkMatrix inverse;
if (this->mapToFallbackContext(&inverse)) {
inverse.mapPoints(&fGlyphPositions[fFallbackGlyphsIdx], fallbackGlyphCount);
}
fFallbackTextContext->drawPosText(fRenderTarget, fClip, paintFallback, skPaintFallback,
fViewMatrix, (char*)&fGlyphIndices[fFallbackGlyphsIdx],
2 * fallbackGlyphCount,
get_xy_scalar_array(&fGlyphPositions[fFallbackGlyphsIdx]),
2, SkPoint::Make(0, 0));
fFallbackGlyphsIdx = kGlyphBufferSize;
}
}
void GrStencilAndCoverTextContext::finish() {
this->flush();
fGlyphs->unref();
fGlyphs = NULL;
SkGlyphCache::AttachCache(fGlyphCache);
fGlyphCache = NULL;
fPipelineBuilder.stencil()->setDisabled();
fStateRestore.set(NULL);
fViewMatrix = fContextInitialMatrix;
GrTextContext::finish();
}
| 40.372093 | 100 | 0.59646 | [
"object",
"shape",
"transform"
] |
4b14fdcffe3439d512ae07aa7e700c308f9eca1c | 4,457 | cpp | C++ | NatsuLang.AOTCompiler.Cli/Main.cpp | NatsuLang/NatsuLang | 671fa6db9a9e19def90b6b675493a6aba26b5996 | [
"MIT"
] | 52 | 2018-06-15T13:19:39.000Z | 2022-01-13T03:58:45.000Z | NatsuLang.AOTCompiler.Cli/Main.cpp | akemimadoka/NatsuLang | 671fa6db9a9e19def90b6b675493a6aba26b5996 | [
"MIT"
] | 9 | 2017-10-25T07:52:57.000Z | 2018-04-01T10:37:28.000Z | NatsuLang.AOTCompiler.Cli/Main.cpp | ammarfaizi2/NatsuLang | 671fa6db9a9e19def90b6b675493a6aba26b5996 | [
"MIT"
] | 6 | 2019-03-18T15:11:55.000Z | 2022-01-13T03:59:22.000Z | #include <CodeGen.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4141)
#pragma warning(disable : 4146)
#pragma warning(disable : 4244)
#pragma warning(disable : 4267)
#pragma warning(disable : 4291)
#pragma warning(disable : 4624)
#pragma warning(disable : 4996)
#endif // _MSC_VER
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FileSystem.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
using namespace NatsuLib;
using namespace NatsuLang::Compiler;
void PrintException(natLog& logger, std::exception const& e);
void PrintException(natLog& logger, natException const& e)
{
logger.LogErr(u8"捕获到来自函数 {0}({1}:{2})的异常,描述为 {3}"_nv, e.GetSource(), e.GetFile(), e.GetLine(), e.GetDesc());
#ifdef EnableStackWalker
logger.LogErr(u8"调用栈为"_nv);
const auto& stackWalker = e.GetStackWalker();
for (std::size_t i = 0, count = stackWalker.GetFrameCount(); i < count; ++i)
{
const auto& symbol = stackWalker.GetSymbol(i);
#ifdef _WIN32
logger.LogErr(u8"{3}: (0x%p) {4} (地址:0x%p) (文件 {5}:{6} (地址:0x%p))"_nv, symbol.OriginalAddress, reinterpret_cast<const void*>(symbol.SymbolAddress), reinterpret_cast<const void*>(symbol.SourceFileAddress), i, symbol.SymbolName, symbol.SourceFileName, symbol.SourceFileLine);
#else
logger.LogErr(u8"0x%p : {1}"_nv, symbol.OriginalAddress, symbol.SymbolInfo);
#endif
}
#endif
try
{
std::rethrow_if_nested(e);
}
catch (natException& inner)
{
logger.LogErr(u8"由以下异常引起:"_nv);
PrintException(logger, inner);
}
catch (std::exception& inner)
{
logger.LogErr(u8"由以下异常引起:"_nv);
PrintException(logger, inner);
}
}
void PrintException(natLog& logger, std::exception const& e)
{
logger.LogErr(u8"捕获到异常,描述为 {0}"_nv, e.what());
try
{
std::rethrow_if_nested(e);
}
catch (natException& inner)
{
logger.LogErr(u8"由以下异常引起:"_nv);
PrintException(logger, inner);
}
catch (std::exception& inner)
{
logger.LogErr(u8"由以下异常引起:"_nv);
PrintException(logger, inner);
}
}
int main(int argc, char* argv[])
{
natConsole console;
natEventBus event;
natLog logger{ event };
logger.UseDefaultAction(console);
try
{
if (argc >= 2)
{
AotCompiler compiler{ make_ref<natStreamReader<nStrView::UsingStringType>>(make_ref<natFileStream>(u8"DiagIdMap.txt"_nv, true, false)), logger };
std::vector<Uri> sourceFiles, metadataFiles;
auto argIter = argv + 1;
const auto argEnd = argv + argc;
auto includeImported = false;
auto isSourceFile = true;
for (; argIter < argEnd; ++argIter)
{
if (nStrView{ *argIter } == u8"-i"_nv)
{
includeImported = true;
continue;
}
if (nStrView{ *argIter } == u8"-m"_nv)
{
isSourceFile = false;
continue;
}
(isSourceFile ? sourceFiles : metadataFiles).emplace_back(*argIter);
}
if (!sourceFiles.empty())
{
for (const auto& uri : sourceFiles)
{
std::string outputName{ uri.GetPath().cbegin(), uri.GetPath().cend() };
outputName += ".obj";
std::error_code ec;
llvm::raw_fd_ostream output{ outputName, ec, llvm::sys::fs::F_None };
if (ec)
{
logger.LogErr(u8"目标文件无法打开,错误为:{0}"_nv, ec.message());
return EXIT_FAILURE;
}
const auto metadata = make_ref<natFileStream>(uri.GetPath() + u8".meta"_nv, false, true);
compiler.Compile(uri, from(metadataFiles), output);
compiler.CreateMetadata(metadata, includeImported);
}
}
else
{
compiler.LoadMetadata(from(metadataFiles), false);
const auto metadata = make_ref<natFileStream>(u8"MergedMetadata.meta"_nv, false, true);
// 没有源文件时总是输出所有元数据
compiler.CreateMetadata(metadata, true);
logger.LogMsg(u8"合并的元数据已存储到文件 MergedMetadata.meta");
}
}
else
{
console.WriteLine(u8"Aki 版本 0.1\n"
"NatsuLang 的 AOT 编译器\n"
"请将欲编译的源码文件作为第一个命令行参数传入\n"
"若有需要导入的元数据文件请在 -m 开关之后的参数传入\n"
"开关 -i 表示输出的元数据文件将会包含导入的元数据,若无源码文件输入则此开关无效,所有元数据将会合并输出\n"
"例如:\n"
"\t{0} file:///example.nat -m file:///library.meta\n"
"其中 \"file:///example.nat\" 是将要编译的源码文件路径,"
"\"file:///library.meta\" 是将要导入的元数据文件,使用标准 uri 形式表示"_nv, argv[0]);
}
console.ReadLine();
}
catch (natException& e)
{
PrintException(logger, e);
logger.LogErr(u8"编译器由于未处理的不可恢复的异常而中止运行,请按 Enter 退出程序");
console.ReadLine();
return EXIT_FAILURE;
}
catch (std::exception& e)
{
PrintException(logger, e);
logger.LogErr(u8"编译器由于未处理的不可恢复的异常而中止运行,请按 Enter 退出程序");
console.ReadLine();
return EXIT_FAILURE;
}
}
| 24.624309 | 275 | 0.679605 | [
"vector"
] |
4b15798df60ff155c3c7ccecdc20a879e76d6139 | 2,929 | hpp | C++ | drape_frontend/render_group.hpp | imanmoghimiq30/omim | 16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423 | [
"Apache-2.0"
] | 1 | 2021-01-19T08:31:19.000Z | 2021-01-19T08:31:19.000Z | drape_frontend/render_group.hpp | imanmoghimiq30/omim | 16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423 | [
"Apache-2.0"
] | null | null | null | drape_frontend/render_group.hpp | imanmoghimiq30/omim | 16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "drape_frontend/animation/opacity_animation.hpp"
#include "drape_frontend/animation/value_mapping.hpp"
#include "drape_frontend/render_state.hpp"
#include "drape_frontend/tile_utils.hpp"
#include "drape/pointers.hpp"
#include "drape/render_bucket.hpp"
#include <memory>
#include <vector>
#include <string>
class ScreenBase;
namespace dp { class OverlayTree; }
namespace df
{
class BaseRenderGroup
{
public:
BaseRenderGroup(dp::GLState const & state, TileKey const & tileKey)
: m_state(state)
, m_tileKey(tileKey)
{}
virtual ~BaseRenderGroup() {}
void SetRenderParams(ref_ptr<dp::GpuProgram> shader, ref_ptr<dp::GpuProgram> shader3d,
ref_ptr<dp::UniformValuesStorage> generalUniforms);
dp::GLState const & GetState() const { return m_state; }
TileKey const & GetTileKey() const { return m_tileKey; }
dp::UniformValuesStorage const & GetUniforms() const { return m_uniforms; }
virtual void UpdateAnimation();
virtual void Render(ScreenBase const & screen);
protected:
dp::GLState m_state;
ref_ptr<dp::GpuProgram> m_shader;
ref_ptr<dp::GpuProgram> m_shader3d;
dp::UniformValuesStorage m_uniforms;
ref_ptr<dp::UniformValuesStorage> m_generalUniforms;
private:
TileKey m_tileKey;
};
class RenderGroup : public BaseRenderGroup
{
using TBase = BaseRenderGroup;
friend class BatchMergeHelper;
public:
RenderGroup(dp::GLState const & state, TileKey const & tileKey);
~RenderGroup() override;
void Update(ScreenBase const & modelView);
void CollectOverlay(ref_ptr<dp::OverlayTree> tree);
bool HasOverlayHandles() const;
void RemoveOverlay(ref_ptr<dp::OverlayTree> tree);
void Render(ScreenBase const & screen) override;
void AddBucket(drape_ptr<dp::RenderBucket> && bucket);
bool IsEmpty() const { return m_renderBuckets.empty(); }
void DeleteLater() const { m_pendingOnDelete = true; }
bool IsPendingOnDelete() const { return m_pendingOnDelete; }
bool CanBeDeleted() const { return m_canBeDeleted; }
bool UpdateCanBeDeletedStatus(bool canBeDeleted, int currentZoom, ref_ptr<dp::OverlayTree> tree);
bool IsOverlay() const;
bool IsUserMark() const;
private:
std::vector<drape_ptr<dp::RenderBucket>> m_renderBuckets;
mutable bool m_pendingOnDelete;
mutable bool m_canBeDeleted;
private:
friend std::string DebugPrint(RenderGroup const & group);
};
class RenderGroupComparator
{
public:
bool operator()(drape_ptr<RenderGroup> const & l, drape_ptr<RenderGroup> const & r);
bool m_pendingOnDeleteFound = false;
};
class UserMarkRenderGroup : public RenderGroup
{
using TBase = RenderGroup;
public:
UserMarkRenderGroup(dp::GLState const & state, TileKey const & tileKey);
~UserMarkRenderGroup() override {}
void UpdateAnimation() override;
bool IsUserPoint() const;
private:
std::unique_ptr<OpacityAnimation> m_animation;
ValueMapping<float> m_mapping;
};
} // namespace df
| 26.151786 | 99 | 0.750768 | [
"render",
"vector"
] |
4b16226d1ac6a7d9b842c64311ae8159bbd4b0ca | 4,889 | cpp | C++ | taichi/transforms/demote_dense_struct_fors.cpp | inkydragon/taichi | b5f80c2771b578c2a32b9a024a351aafc8ca7a0b | [
"MIT"
] | null | null | null | taichi/transforms/demote_dense_struct_fors.cpp | inkydragon/taichi | b5f80c2771b578c2a32b9a024a351aafc8ca7a0b | [
"MIT"
] | null | null | null | taichi/transforms/demote_dense_struct_fors.cpp | inkydragon/taichi | b5f80c2771b578c2a32b9a024a351aafc8ca7a0b | [
"MIT"
] | null | null | null | #include "taichi/ir/ir.h"
#include "taichi/ir/transforms.h"
#include "taichi/ir/visitors.h"
TLANG_NAMESPACE_BEGIN
VecStatement convert_to_range_for(StructForStmt *struct_for) {
VecStatement ret;
auto lower = ret.push_back<ConstStmt>(TypedConstant(0));
std::vector<SNode *> snodes;
auto snode = struct_for->snode;
int total_bits = 0;
while (snode->type != SNodeType::root) {
snodes.push_back(snode);
total_bits += snode->total_num_bits;
snode = snode->parent;
}
std::reverse(snodes.begin(), snodes.end());
TI_ASSERT(total_bits <= 30);
auto upper_bound = 1 << total_bits;
auto upper = ret.push_back<ConstStmt>(TypedConstant(upper_bound));
auto body = std::move(struct_for->body);
const int num_loop_vars = snodes.back()->num_active_indices;
std::vector<Stmt *> new_loop_vars;
VecStatement body_header;
std::vector<int> physical_indices;
for (int i = 0; i < num_loop_vars; i++) {
new_loop_vars.push_back(body_header.push_back<ConstStmt>(TypedConstant(0)));
physical_indices.push_back(snodes.back()->physical_index_position[i]);
}
auto main_loop_var = body_header.push_back<LoopIndexStmt>(nullptr, 0);
// We will set main_loop_var->loop later.
int offset = total_bits;
Stmt *test = body_header.push_back<ConstStmt>(TypedConstant(-1));
bool has_test = false;
for (int i = 0; i < (int)snodes.size(); i++) {
auto snode = snodes[i];
offset -= snode->total_num_bits;
for (int j = 0; j < (int)physical_indices.size(); j++) {
auto p = physical_indices[j];
auto ext = snode->extractors[p];
Stmt *delta = body_header.push_back<BitExtractStmt>(
main_loop_var, ext.acc_offset + offset,
ext.acc_offset + offset + ext.num_bits);
auto multiplier =
body_header.push_back<ConstStmt>(TypedConstant(1 << (ext.start)));
delta = body_header.push_back<BinaryOpStmt>(BinaryOpType::mul, delta,
multiplier);
new_loop_vars[j] = body_header.push_back<BinaryOpStmt>(
BinaryOpType::add, new_loop_vars[j], delta);
}
}
for (int i = 0; i < (int)snodes.size(); i++) {
auto snode = snodes[i];
for (int j = 0; j < (int)physical_indices.size(); j++) {
auto p = physical_indices[j];
auto num_elements = snode->extractors[p].num_elements
<< snode->extractors[p].start;
if (!bit::is_power_of_two(num_elements)) {
has_test = true;
auto bound =
body_header.push_back<ConstStmt>(TypedConstant(num_elements));
auto cmp = body_header.push_back<BinaryOpStmt>(BinaryOpType::cmp_lt,
new_loop_vars[j], bound);
test = body_header.push_back<BinaryOpStmt>(BinaryOpType::bit_and, test,
cmp);
}
}
}
for (int i = 0; i < num_loop_vars; i++) {
auto alloca = body_header.push_back<AllocaStmt>(DataType::i32);
body_header.push_back<LocalStoreStmt>(alloca, new_loop_vars[i]);
irpass::replace_statements_with(
body.get(),
[&](Stmt *s) {
if (auto loop_index = s->cast<LoopIndexStmt>()) {
return loop_index->loop == struct_for &&
loop_index->index ==
snodes.back()->physical_index_position[i];
}
return false;
},
[&]() { return Stmt::make<LocalLoadStmt>(LocalAddress(alloca, 0)); });
}
if (has_test) {
// Create an If statement
auto if_stmt = Stmt::make_typed<IfStmt>(test);
if_stmt->true_statements = std::move(body);
body = std::make_unique<Block>();
body->insert(std::move(if_stmt));
}
body->insert(std::move(body_header), 0);
auto range_for = Stmt::make<RangeForStmt>(
lower, upper, std::move(body), struct_for->vectorize,
struct_for->parallelize, struct_for->block_dim, false);
main_loop_var->loop = range_for.get();
ret.push_back(std::move(range_for));
// TODO: safe guard range
return ret;
}
namespace irpass {
void demote_dense_struct_fors(IRNode *root) {
auto *block = dynamic_cast<Block *>(root);
std::vector<Stmt *> block_body;
for (int i = 0; i < (int)block->statements.size(); i++) {
block_body.push_back(block->statements[i].get());
}
for (int i = 0; i < (int)block_body.size(); i++) {
auto s_ = block_body[i];
if (auto s = s_->cast<StructForStmt>()) {
auto snode = s->snode;
bool all_dense = true;
while (all_dense && snode->type != SNodeType::root) {
if (snode->type != SNodeType::dense) {
all_dense = false;
}
snode = snode->parent;
}
if (all_dense) {
s->parent->replace_with(s, convert_to_range_for(s), false);
}
}
}
re_id(root);
fix_block_parents(root);
}
} // namespace irpass
TLANG_NAMESPACE_END
| 33.717241 | 80 | 0.619554 | [
"vector"
] |
4b1d07cebc3a856fbe23f6c4d23f658fd0c1abf6 | 2,443 | cpp | C++ | Algorithms/0427.Construct_Quad_Tree.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0427.Construct_Quad_Tree.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0427.Construct_Quad_Tree.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight;
Node() {
val = false;
isLeaf = false;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf) {
val = _val;
isLeaf = _isLeaf;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
class Solution {
public:
int n;
vector<vector<int>> ar;
void g(Node* node , int& cntLeaf , vector<bool>& vals) {
cntLeaf += node->isLeaf;
vals[node->val] = true;
}
void f(Node* node , int x1 , int x2 , int y1 , int y2) {
if(x1 == x2 && y1 == y2) {
node->isLeaf = true;
node->val = ar[x1][y1];
return;
}
int xmid = (x1+x2) >> 1;
int ymid = (y1+y2) >> 1;
int cntLeaf = 0;
vector<bool> vals(2,false);
node->topLeft = new Node();
f(node->topLeft,x1,xmid,y1,ymid);
g(node->topLeft,cntLeaf,vals);
node->topRight = new Node();
f(node->topRight,x1,xmid,ymid+1,y2);
g(node->topRight,cntLeaf,vals);
node->bottomLeft = new Node();
f(node->bottomLeft,xmid+1,x2,y1,ymid);
g(node->bottomLeft,cntLeaf,vals);
node->bottomRight = new Node();
f(node->bottomRight,xmid+1,x2,ymid+1,y2);
g(node->bottomRight,cntLeaf,vals);
if(cntLeaf == 4 && (vals[0] ^ vals[1])) {
int valnew = vals[1];
node->isLeaf = true;
node->val = valnew;
delete node->topLeft;
node->topLeft = NULL;
delete node->topRight;
node->topRight = NULL;
delete node->bottomLeft;
node->bottomLeft = NULL;
delete node->bottomRight;
node->bottomRight = NULL;
}
}
Node* construct(vector<vector<int>>& ar) {
n = ar.size();
this->ar = ar;
Node* root = new Node();
f(root,0,n-1,0,n-1);
return root;
}
}; | 28.406977 | 107 | 0.508801 | [
"vector"
] |
4b1f4f6d59d78d30e270cc868c9541a7f26fc9de | 22,350 | cpp | C++ | toonz/sources/tnztools/rgbpickertool.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 3,710 | 2016-03-26T00:40:48.000Z | 2022-03-31T21:35:12.000Z | toonz/sources/tnztools/rgbpickertool.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 4,246 | 2016-03-26T01:21:45.000Z | 2022-03-31T23:10:47.000Z | toonz/sources/tnztools/rgbpickertool.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 633 | 2016-03-26T00:42:25.000Z | 2022-03-17T02:55:13.000Z |
#include "rgbpickertool.h"
#include "tvectorimage.h"
#include "ttoonzimage.h"
#include "tools/cursors.h"
#include "tcolorstyles.h"
#include "toonz/cleanupcolorstyles.h"
#include "trasterimage.h"
#include "tgl.h"
#include "tenv.h"
#include "tstroke.h"
#include "toonz/palettecontroller.h"
#include "toonz/tpalettehandle.h"
#include "toonz/tscenehandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/stage2.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/preferences.h"
#include "toonzqt/icongenerator.h"
#include "toonzqt/dvdialog.h"
#include "toonzqt/lutcalibrator.h"
#include "tools/toolhandle.h"
#include "tools/stylepicker.h"
#include "tools/toolutils.h"
#include "tools/RGBpicker.h"
#define NORMAL_PICK L"Normal"
#define RECT_PICK L"Rectangular"
#define FREEHAND_PICK L"Freehand"
#define POLYLINE_PICK L"Polyline"
TEnv::StringVar PickVectorType("InknpaintPickVectorType", "Normal");
TEnv::IntVar PickPassive("InknpaintPickPassive", 0);
namespace RGBPicker {
//============================================================
// Pick RGB Tool
//------------------------------------------------------------
class UndoPickRGBM final : public TUndo {
TPaletteP m_palette;
int m_styleId;
int m_styleParamIndex;
TPixel32 m_oldValue, m_newValue;
TXshSimpleLevelP m_level;
bool m_colorAutoApplyEnabled;
public:
UndoPickRGBM(TPalette *palette, int styleId, const TPixel32 newValue,
const TXshSimpleLevelP &level)
: m_palette(palette)
, m_styleId(styleId)
, m_newValue(newValue)
, m_level(level)
, m_colorAutoApplyEnabled(true) {
PaletteController *controller =
TTool::getApplication()->getPaletteController();
m_colorAutoApplyEnabled = controller->isColorAutoApplyEnabled();
m_styleParamIndex = controller->getCurrentPalette()->getStyleParamIndex();
if (m_colorAutoApplyEnabled) {
TColorStyle *cs = m_palette->getStyle(m_styleId);
if (0 <= m_styleParamIndex &&
m_styleParamIndex < cs->getColorParamCount())
m_oldValue = cs->getColorParamValue(m_styleParamIndex);
else
m_oldValue = cs->getMainColor();
} else {
m_oldValue = controller->getColorSample();
}
}
void setColor(const TPixel32 &color) const {
PaletteController *controller =
TTool::getApplication()->getPaletteController();
if (m_colorAutoApplyEnabled) {
TColorStyle *cs = m_palette->getStyle(m_styleId);
if (0 <= m_styleParamIndex &&
m_styleParamIndex < cs->getColorParamCount())
cs->setColorParamValue(m_styleParamIndex, color);
else
cs->setMainColor(color);
cs->invalidateIcon();
controller->getCurrentPalette()->notifyColorStyleChanged();
updateLevel();
} else {
controller->setColorSample(color);
}
TTool::Application *app = TTool::getApplication();
TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
if (level) {
std::vector<TFrameId> fids;
level->getFids(fids);
invalidateIcons(level, fids);
}
}
void undo() const override { setColor(m_oldValue); }
void redo() const override { setColor(m_newValue); }
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override {
return QObject::tr("RGB Picker (R%1, G%2, B%3)")
.arg(QString::number((int)m_newValue.r))
.arg(QString::number((int)m_newValue.g))
.arg(QString::number((int)m_newValue.b));
}
private:
void updateLevel() const {
std::vector<TFrameId> fids;
if (!m_level) return;
m_level->getFids(fids);
unsigned int i;
for (i = 0; i < fids.size(); i++)
IconGenerator::instance()->invalidate(m_level.getPointer(), fids[i]);
IconGenerator::instance()->invalidateSceneIcon();
TTool::getApplication()->getCurrentScene()->notifySceneChanged();
}
};
//----------------------------------------------------------------------------------------------
void setCurrentColor(const TPixel32 &color) {
PaletteController *controller =
TTool::getApplication()->getPaletteController();
TPaletteHandle *ph = controller->getCurrentPalette();
TColorStyle *cs = ph->getStyle();
if (!cs) return;
if (controller->isColorAutoApplyEnabled()) {
TCleanupStyle *ccs = dynamic_cast<TCleanupStyle *>(cs);
if (ccs) ccs->setCanUpdate(true);
int index = ph->getStyleParamIndex();
if (0 <= index && index < cs->getColorParamCount())
cs->setColorParamValue(index, color);
else
cs->setMainColor(color);
cs->invalidateIcon();
ph->notifyColorStyleChanged();
// per le palette animate
int styleIndex = ph->getStyleIndex();
TPalette *palette = ph->getPalette();
if (palette && palette->isKeyframe(styleIndex, palette->getFrame()))
palette->setKeyframe(styleIndex, palette->getFrame());
if (ccs) ccs->setCanUpdate(false);
} else
controller->setColorSample(color);
}
//----------------------------------------------------------------------------------------------
void setCurrentColorWithUndo(const TPixel32 &color) {
TTool::Application *app = TTool::getApplication();
TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
int styleId = ph->getStyleIndex();
TPalette *palette = ph->getPalette();
TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
if (palette)
TUndoManager::manager()->add(
new UndoPickRGBM(palette, styleId, color, level));
setCurrentColor(color);
if (level) {
std::vector<TFrameId> fids;
level->getFids(fids);
invalidateIcons(level, fids);
}
}
} // namespace RGBPicker
using namespace RGBPicker;
//----------------------------------------------------------------------------------------------
RGBPickerTool::RGBPickerTool()
: TTool("T_RGBPicker")
, m_currentStyleId(0)
, m_pickType("Type:")
, m_drawingTrack()
, m_workingTrack()
, m_firstDrawingPos()
, m_firstWorkingPos()
, m_mousePosition()
, m_thick(0.5)
, m_stroke(0)
, m_firstStroke(0)
, m_makePick(false)
, m_firstTime(true)
, m_passivePick("Passive Pick", false)
, m_toolOptionsBox(0)
, m_mousePixelPosition() {
bind(TTool::CommonLevels);
m_prop.bind(m_pickType);
m_pickType.addValue(NORMAL_PICK);
m_pickType.addValue(RECT_PICK);
m_pickType.addValue(FREEHAND_PICK);
m_pickType.addValue(POLYLINE_PICK);
m_pickType.setId("Type");
m_prop.bind(m_passivePick);
m_passivePick.setId("PassivePick");
}
//---------------------------------------------------------
void RGBPickerTool::setToolOptionsBox(RGBPickerToolOptionsBox *toolOptionsBox) {
m_toolOptionsBox.push_back(toolOptionsBox);
}
//---------------------------------------------------------
void RGBPickerTool::updateTranslation() {
m_pickType.setQStringName(tr("Type:"));
m_pickType.setItemUIName(NORMAL_PICK, tr("Normal"));
m_pickType.setItemUIName(RECT_PICK, tr("Rectangular"));
m_pickType.setItemUIName(FREEHAND_PICK, tr("Freehand"));
m_pickType.setItemUIName(POLYLINE_PICK, tr("Polyline"));
m_passivePick.setQStringName(tr("Passive Pick"));
}
//---------------------------------------------------------
// Used to notify and set the currentColor outside the draw() methods:
// using special style there was a conflict between the draw() methods of the
// tool
// and the generation of the icon inside the style editor (makeIcon()) which use
// another glContext
void RGBPickerTool::onImageChanged() {
TTool::Application *app = TTool::getApplication();
TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
if (m_currentStyleId != 0 && m_makePick &&
(m_pickType.getValue() == POLYLINE_PICK ||
m_pickType.getValue() == RECT_PICK)) {
TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
int styleId = ph->getStyleIndex();
TPalette *palette = ph->getPalette();
if (palette)
TUndoManager::manager()->add(
new UndoPickRGBM(palette, styleId, m_currentValue, level));
}
if (m_makePick) {
setCurrentColor(m_currentValue);
if (level) {
std::vector<TFrameId> fids;
level->getFids(fids);
invalidateIcons(level, fids);
}
}
m_makePick = false;
}
void RGBPickerTool::draw() {
double pixelSize2 = getPixelSize() * getPixelSize();
m_thick = sqrt(pixelSize2) / 2.0;
if (m_makePick) {
if (m_currentStyleId != 0) {
// Il pick in modalita' polyline e rectangular deve essere fatto soltanto
// dopo aver cancellato il
//"disegno" della polyline altrimenti alcuni pixels neri delle spezzate
// che la
// compongono vengono presi in considerazione nel calcolo del "colore
// medio"
if (m_pickType.getValue() == POLYLINE_PICK && m_drawingPolyline.empty())
doPolylineFreehandPick();
else if (m_pickType.getValue() == RECT_PICK && m_drawingRect.isEmpty())
pickRect();
else if (m_pickType.getValue() == NORMAL_PICK)
pick();
else if (m_pickType.getValue() == FREEHAND_PICK && m_stroke)
doPolylineFreehandPick();
}
return;
}
if (m_passivePick.getValue() == true) {
passivePick();
}
if (m_pickType.getValue() == RECT_PICK && !m_makePick) {
TPixel color = ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg
? TPixel32::White
: TPixel32::Red;
ToolUtils::drawRect(m_drawingRect, color, 0x3F33, true);
} else if (m_pickType.getValue() == POLYLINE_PICK &&
!m_drawingPolyline.empty()) {
TPixel color = ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg
? TPixel32::White
: TPixel32::Black;
tglColor(color);
tglDrawCircle(m_drawingPolyline[0], 2);
glBegin(GL_LINE_STRIP);
for (UINT i = 0; i < m_drawingPolyline.size(); i++)
tglVertex(m_drawingPolyline[i]);
tglVertex(m_mousePosition);
glEnd();
} else if (m_pickType.getValue() == FREEHAND_PICK &&
!m_drawingTrack.isEmpty()) {
TPixel color = ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg
? TPixel32::White
: TPixel32::Black;
tglColor(color);
m_drawingTrack.drawAllFragments();
}
}
//---------------------------------------------------------
void RGBPickerTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {
TTool::Application *app = TTool::getApplication();
TPaletteHandle *pltHandle = app->getPaletteController()->getCurrentPalette();
m_currentStyleId = pltHandle->getStyleIndex();
if (m_currentStyleId == 0) return;
TColorStyle *colorStyle = pltHandle->getStyle();
if (colorStyle) m_oldValue = colorStyle->getMainColor();
if (m_pickType.getValue() == RECT_PICK) {
m_selectingRect.x0 = e.m_pos.x;
m_selectingRect.y0 = e.m_pos.y;
m_selectingRect.x1 = e.m_pos.x;
m_selectingRect.y1 = e.m_pos.y;
m_drawingRect.x0 = pos.x;
m_drawingRect.y0 = pos.y;
m_drawingRect.x1 = pos.x;
m_drawingRect.y1 = pos.y;
invalidate();
return;
} else if (m_pickType.getValue() == FREEHAND_PICK) {
startFreehand(pos, e.m_pos);
return;
} else if (m_pickType.getValue() == POLYLINE_PICK) {
addPointPolyline(pos, e.m_pos);
return;
} else { // NORMAL_PICK
m_mousePixelPosition = e.m_pos;
m_makePick = true;
invalidate();
}
}
//---------------------------------------------------------
void RGBPickerTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {
if (m_currentStyleId == 0) return;
if (m_pickType.getValue() == RECT_PICK) {
m_selectingRect.x1 = e.m_pos.x;
m_selectingRect.y1 = e.m_pos.y;
m_drawingRect.x1 = pos.x;
m_drawingRect.y1 = pos.y;
invalidate();
return;
} else if (m_pickType.getValue() == FREEHAND_PICK) {
freehandDrag(pos, e.m_pos);
invalidate();
}
}
//---------------------------------------------------------
void RGBPickerTool::leftButtonUp(const TPointD &pos, const TMouseEvent &) {
if (m_currentStyleId == 0) return;
if (m_pickType.getValue() == RECT_PICK) {
m_makePick = true;
m_drawingRect.empty();
}
if (m_pickType.getValue() == FREEHAND_PICK) {
closeFreehand();
m_makePick = true;
}
invalidate();
}
//---------------------------------------------------------
void RGBPickerTool::leftButtonDoubleClick(const TPointD &pos,
const TMouseEvent &e) {
if (m_currentStyleId == 0) return;
if (m_pickType.getValue() == POLYLINE_PICK) {
closePolyline(pos, e.m_pos);
std::vector<TThickPoint> strokePoints;
for (UINT i = 0; i < m_workingPolyline.size() - 1; i++) {
strokePoints.push_back(TThickPoint(m_workingPolyline[i], 1));
strokePoints.push_back(TThickPoint(
0.5 * (m_workingPolyline[i] + m_workingPolyline[i + 1]), 1));
}
strokePoints.push_back(TThickPoint(m_workingPolyline.back(), 1));
m_drawingPolyline.clear();
m_workingPolyline.clear();
m_stroke = new TStroke(strokePoints);
m_makePick = true;
invalidate();
}
}
//---------------------------------------------------------
void RGBPickerTool::mouseMove(const TPointD &pos, const TMouseEvent &e) {
/*--- Pick color passively and display in the tool option bar ---*/
if (m_passivePick.getValue() == true) {
m_mousePixelPosition = e.m_pos;
invalidate();
}
if (m_pickType.getValue() == POLYLINE_PICK && !m_drawingPolyline.empty()) {
m_mousePosition = pos;
invalidate();
}
}
//---------------------------------------------------------
void RGBPickerTool::passivePick() {
TImageP image = TImageP(getImage(false));
if (!image) return;
TRectD area = TRectD(m_mousePixelPosition.x, m_mousePixelPosition.y,
m_mousePixelPosition.x, m_mousePixelPosition.y);
StylePicker picker(image);
if (LutManager::instance()->isValid()) m_viewer->bindFBO();
TPixel32 pix = picker.pickColor(area);
if (LutManager::instance()->isValid()) m_viewer->releaseFBO();
QColor col((int)pix.r, (int)pix.g, (int)pix.b);
PaletteController *controller =
TTool::getApplication()->getPaletteController();
controller->notifyColorPassivePicked(col);
}
//---------------------------------------------------------
void RGBPickerTool::pick() {
TImageP image = TImageP(getImage(false));
TTool::Application *app = TTool::getApplication();
TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
int styleId = ph->getStyleIndex();
TPalette *palette = ph->getPalette();
if (!palette) return;
TRectD area = TRectD(m_mousePixelPosition.x - 1, m_mousePixelPosition.y - 1,
m_mousePixelPosition.x + 1, m_mousePixelPosition.y + 1);
StylePicker picker(image, palette);
if (LutManager::instance()->isValid()) m_viewer->bindFBO();
m_currentValue = picker.pickColor(area);
if (LutManager::instance()->isValid()) m_viewer->releaseFBO();
TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
UndoPickRGBM *cmd = new UndoPickRGBM(palette, styleId, m_currentValue, level);
TUndoManager::manager()->add(cmd);
}
//---------------------------------------------------------
void RGBPickerTool::pickRect() {
TImageP image = TImageP(getImage(false));
TTool::Application *app = TTool::getApplication();
TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
int styleId = ph->getStyleIndex();
TPalette *palette = ph->getPalette();
TRectD area = m_selectingRect;
if (!palette) return;
if (m_selectingRect.x0 > m_selectingRect.x1) {
area.x1 = m_selectingRect.x0;
area.x0 = m_selectingRect.x1;
}
if (m_selectingRect.y0 > m_selectingRect.y1) {
area.y1 = m_selectingRect.y0;
area.y0 = m_selectingRect.y1;
}
m_selectingRect.empty();
if (area.getLx() <= 1 || area.getLy() <= 1) return;
StylePicker picker(image, palette);
if (LutManager::instance()->isValid()) m_viewer->bindFBO();
m_currentValue = picker.pickColor(area);
if (LutManager::instance()->isValid()) m_viewer->releaseFBO();
}
//---------------------------------------------------------
void RGBPickerTool::pickStroke() {
TImageP image = TImageP(getImage(false));
TTool::Application *app = TTool::getApplication();
TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
int styleId = ph->getStyleIndex();
TPalette *palette = ph->getPalette();
if (!palette) return;
StylePicker picker(image, palette);
TStroke *stroke = new TStroke(*m_stroke);
if (LutManager::instance()->isValid()) m_viewer->bindFBO();
m_currentValue = picker.pickColor(stroke);
if (LutManager::instance()->isValid()) m_viewer->releaseFBO();
if (!(m_pickType.getValue() == POLYLINE_PICK)) {
TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
TUndoManager::manager()->add(
new UndoPickRGBM(palette, styleId, m_currentValue, level));
}
}
//---------------------------------------------------------
bool RGBPickerTool::onPropertyChanged(std::string propertyName) {
if (propertyName == m_pickType.getName())
PickVectorType = ::to_string(m_pickType.getValue());
else if (propertyName == m_passivePick.getName())
PickPassive = m_passivePick.getValue();
return true;
}
//---------------------------------------------------------
void RGBPickerTool::onActivate() {
if (m_firstTime) {
m_pickType.setValue(::to_wstring(PickVectorType.getValue()));
m_passivePick.setValue(PickPassive ? 1 : 0);
m_firstTime = false;
}
}
//---------------------------------------------------------
TPropertyGroup *RGBPickerTool::getProperties(int targetType) { return &m_prop; }
//---------------------------------------------------------
int RGBPickerTool::getCursorId() const {
int currentStyleId = getApplication()
->getPaletteController()
->getCurrentPalette()
->getStyleIndex();
if (currentStyleId == 0) return ToolCursor::ForbiddenCursor;
if (ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg)
return ToolCursor::PickerRGBWhite;
else
return ToolCursor::PickerRGB;
}
//---------------------------------------------------------
void RGBPickerTool::doPolylineFreehandPick() {
if (m_stroke && (m_pickType.getValue() == POLYLINE_PICK ||
m_pickType.getValue() == FREEHAND_PICK)) {
pickStroke();
delete m_stroke;
m_stroke = 0;
}
}
//---------------------------------------------------------
//! Viene aggiunto \b pos a \b m_track e disegnato il primo pezzetto del lazzo.
//! Viene inizializzato \b m_firstPos
void RGBPickerTool::startFreehand(const TPointD &drawingPos,
const TPointD &workingPos) {
m_drawingTrack.clear();
m_workingTrack.clear();
m_firstDrawingPos = drawingPos;
m_firstWorkingPos = workingPos;
double pixelSize2 = getPixelSize() * getPixelSize();
m_drawingTrack.add(TThickPoint(drawingPos, m_thick), pixelSize2);
m_workingTrack.add(TThickPoint(workingPos, m_thick), pixelSize2);
#if defined(MACOSX)
// m_viewer->prepareForegroundDrawing();
#endif
}
//---------------------------------------------------------
//! Viene aggiunto \b pos a \b m_track e disegnato un altro pezzetto del lazzo.
void RGBPickerTool::freehandDrag(const TPointD &drawingPos,
const TPointD &workingPos) {
#if defined(MACOSX)
// getViewer()->enableRedraw(false);
#endif
double pixelSize2 = getPixelSize() * getPixelSize();
m_drawingTrack.add(TThickPoint(drawingPos, m_thick), pixelSize2);
m_workingTrack.add(TThickPoint(workingPos, m_thick), pixelSize2);
}
//---------------------------------------------------------
//! Viene chiuso il lazzo (si aggiunge l'ultimo punto ad m_track) e viene creato
//! lo stroke rappresentante il lazzo.
void RGBPickerTool::closeFreehand() {
#if defined(MACOSX)
// getViewer()->enableRedraw(true);
#endif
if (m_drawingTrack.isEmpty() || m_workingTrack.isEmpty()) return;
double pixelSize2 = getPixelSize() * getPixelSize();
m_drawingTrack.add(TThickPoint(m_firstDrawingPos, m_thick), pixelSize2);
m_workingTrack.add(TThickPoint(m_firstWorkingPos, m_thick), pixelSize2);
m_workingTrack.filterPoints();
double error = (30.0 / 11) * sqrt(pixelSize2);
m_stroke = m_workingTrack.makeStroke(error);
m_stroke->setStyle(1);
m_drawingTrack.clear();
m_workingTrack.clear();
}
//---------------------------------------------------------
//! Viene aggiunto un punto al vettore m_polyline.
void RGBPickerTool::addPointPolyline(const TPointD &drawingPos,
const TPointD &workingPos) {
m_mousePosition = drawingPos;
/*---drawingPosは中心からの座標 workingPosは画面左下からの座標---*/
m_drawingPolyline.push_back(drawingPos);
m_workingPolyline.push_back(workingPos);
}
//---------------------------------------------------------
//! Agginge l'ultimo pos a \b m_polyline e chiude la spezzata (aggiunge \b
//! m_polyline.front() alla fine del vettore)
void RGBPickerTool::closePolyline(const TPointD &drawingPos,
const TPointD &workingPos) {
if (m_drawingPolyline.size() <= 1 || m_workingPolyline.size() <= 1) return;
if (m_drawingPolyline.back() != drawingPos)
m_drawingPolyline.push_back(drawingPos);
if (m_workingPolyline.back() != workingPos)
m_workingPolyline.push_back(workingPos);
if (m_drawingPolyline.back() != m_drawingPolyline.front())
m_drawingPolyline.push_back(m_drawingPolyline.front());
if (m_workingPolyline.back() != m_workingPolyline.front())
m_workingPolyline.push_back(m_workingPolyline.front());
}
//---------------------------------------------------------
/*! Flipbook上でPassive Pickを有効にする
*/
void RGBPickerTool::showFlipPickedColor(const TPixel32 &pix) {
if (m_passivePick.getValue()) {
QColor col((int)pix.r, (int)pix.g, (int)pix.b);
PaletteController *controller =
TTool::getApplication()->getPaletteController();
controller->notifyColorPassivePicked(col);
}
}
RGBPickerTool RGBpicktool;
// TTool *getPickRGBMTool() {return &pickRBGMTool;}
| 33.111111 | 96 | 0.625324 | [
"vector"
] |
4b219a2ee8daf5a53714699650307d34203755b8 | 3,889 | cpp | C++ | problems/poj3259.cpp | jeffswt/acm-algorithms | 9611f3a1c0691144fd101b0173fbab82b76e46cc | [
"MIT"
] | 1 | 2021-05-19T14:18:20.000Z | 2021-05-19T14:18:20.000Z | problems/poj3259.cpp | jeffswt/acm-algorithms | 9611f3a1c0691144fd101b0173fbab82b76e46cc | [
"MIT"
] | null | null | null | problems/poj3259.cpp | jeffswt/acm-algorithms | 9611f3a1c0691144fd101b0173fbab82b76e46cc | [
"MIT"
] | null | null | null |
#include <iostream> // C++ I/O
#include <fstream> // File I/O
#include <sstream> // String stream I/O
#include <iomanip> // C++ I/O manipulator
#include <cstdlib> // C library
#include <cstdio> // C I/O
#include <ctime> // C time
#include <cmath> // Math library
#include <cstring> // C strings
#include <vector> // Vector
#include <queue> // Queue
#include <stack> // Stack
#include <map> // Map
#include <set> // Set
#include <algorithm> // Algorithms
using namespace std;
#define memclr(_arr) memset(_arr, 0, sizeof(_arr))
#define reps(_var,_begin,_end,_step) for (int _var = (_begin); \
_var <= (_end); _var += (_step))
#define reps_(_var,_end,_begin,_step) for (int _var = (_end); \
_var >= (_begin); _var -= (_step))
#define rep(_var,_begin,_end) reps(_var, _begin, _end, 1)
#define rep_(_var,_end,_begin) reps_(_var, _end, _begin, 1)
#define minimize(_var,_targ) _var = min(_var, _targ)
#define maximize(_var,_targ) _var = max(_var, _targ)
typedef unsigned long long ull;
typedef long long lli, ll;
typedef double llf;
const int maxn = 1010, maxm = 10010;
const lli infinit = 0x003f3f3f3f3f3f3fll;
class SPFA
{
public:
struct edge
{
int u, v;
lli len;
edge *next;
};
edge epool[maxm], *edges[maxn], *from[maxn];
int n, ecnt;
lli dist[maxn];
int qcnt[maxn], inque[maxn];
void add_edge(int u, int v, lli len)
{
edge *p = &epool[++ecnt];
p->u = u; p->v = v; p->len = len;
p->next = edges[u]; edges[u] = p;
return ;
}
bool eval(int s)
{
#define USE_SLF
#ifdef USE_SLF
deque<int> que;
#else
queue<int> que;
#endif
rep(i, 0, n) {
qcnt[i] = 0;
inque[i] = false;
dist[i] = infinit;
from[i] = 0;
}
dist[s] = 0;
qcnt[s] += 1;
inque[s] = true;
#ifdef USE_SLF
que.push_back(s);
#else
que.push(s);
#endif
while (!que.empty()) {
int p = que.front();
#ifdef USE_SLF
que.pop_front();
#else
que.pop();
#endif
inque[p] = false;
for (edge *ep = edges[p]; ep; ep = ep->next)
if (dist[p] + ep->len < dist[ep->v]) {
dist[ep->v] = dist[p] + ep->len;
from[ep->v] = ep;
if (!inque[ep->v]) {
inque[ep->v] = true;
qcnt[ep->v] += 1;
if (qcnt[ep->v] >= n)
return false;
#ifdef USE_SLF
if (que.empty() || dist[ep->v] > dist[que.front()])
que.push_back(ep->v);
else
que.push_front(ep->v);
#else
que.push(ep->v);
#endif
}
}
}
return true;
}
void init(int n)
{
this->n = n;
ecnt = 0;
rep(i, 1, n)
edges[i] = 0;
return ;
}
} graph;
int T;
int n, m, mM, mW;
int main(int argc, char** argv)
{
scanf("%d", &T);
rep(case_, 1, T) {
scanf("%d%d%d", &n, &mM, &mW);
graph.init(n + 1);
m = mM + mW;
rep(i, 1, mM) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
graph.add_edge(u, v, w);
graph.add_edge(v, u, w);
}
rep(i, 1, mW) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
graph.add_edge(u, v, - w);
}
rep(i, 1, n)
graph.add_edge(n + 1, i, 0);
bool res = !graph.eval(n + 1);
printf("%s\n", res ? "YES" : "NO");
}
return 0;
}
| 26.100671 | 75 | 0.441245 | [
"vector"
] |
4b256b1b8f3cdda42e1907342d46a157402d4811 | 11,076 | cpp | C++ | core/src/index/knowhere/knowhere/index/vector_index/IndexIVF.cpp | ggaaooppeenngg/milvus | 04db47fa664cf3c0eecb894592810c153854794c | [
"Apache-2.0"
] | 1 | 2021-10-30T19:38:06.000Z | 2021-10-30T19:38:06.000Z | core/src/index/knowhere/knowhere/index/vector_index/IndexIVF.cpp | weishuo2/milvus | 2e60bc7361362089caa6ae01899bbc55cf41b4b0 | [
"Apache-2.0"
] | 1 | 2020-04-23T03:56:44.000Z | 2020-04-23T03:56:44.000Z | core/src/index/knowhere/knowhere/index/vector_index/IndexIVF.cpp | weishuo2/milvus | 2e60bc7361362089caa6ae01899bbc55cf41b4b0 | [
"Apache-2.0"
] | 1 | 2020-04-23T14:05:06.000Z | 2020-04-23T14:05:06.000Z | // Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License
#include <faiss/AutoTune.h>
#include <faiss/IVFlib.h>
#include <faiss/IndexFlat.h>
#include <faiss/IndexIVF.h>
#include <faiss/IndexIVFFlat.h>
#include <faiss/IndexIVFPQ.h>
#include <faiss/clone_index.h>
#include <faiss/index_factory.h>
#include <faiss/index_io.h>
#ifdef MILVUS_GPU_VERSION
#include <faiss/gpu/GpuAutoTune.h>
#include <faiss/gpu/GpuCloner.h>
#endif
#include <fiu-local.h>
#include <chrono>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "knowhere/common/Exception.h"
#include "knowhere/common/Log.h"
#include "knowhere/index/vector_index/IndexIVF.h"
#include "knowhere/index/vector_index/adapter/VectorAdapter.h"
#include "knowhere/index/vector_index/helpers/IndexParameter.h"
#ifdef MILVUS_GPU_VERSION
#include "knowhere/index/vector_index/gpu/IndexGPUIVF.h"
#include "knowhere/index/vector_index/helpers/FaissGpuResourceMgr.h"
#endif
namespace milvus {
namespace knowhere {
using stdclock = std::chrono::high_resolution_clock;
BinarySet
IVF::Serialize(const Config& config) {
if (!index_ || !index_->is_trained) {
KNOWHERE_THROW_MSG("index not initialize or trained");
}
std::lock_guard<std::mutex> lk(mutex_);
return SerializeImpl(index_type_);
}
void
IVF::Load(const BinarySet& binary_set) {
std::lock_guard<std::mutex> lk(mutex_);
LoadImpl(binary_set, index_type_);
}
void
IVF::Train(const DatasetPtr& dataset_ptr, const Config& config) {
GETTENSOR(dataset_ptr)
faiss::Index* coarse_quantizer = new faiss::IndexFlatL2(dim);
int64_t nlist = config[IndexParams::nlist].get<int64_t>();
faiss::MetricType metric_type = GetMetricType(config[Metric::TYPE].get<std::string>());
auto index = std::make_shared<faiss::IndexIVFFlat>(coarse_quantizer, dim, nlist, metric_type);
index->train(rows, (float*)p_data);
index_.reset(faiss::clone_index(index.get()));
}
void
IVF::Add(const DatasetPtr& dataset_ptr, const Config& config) {
if (!index_ || !index_->is_trained) {
KNOWHERE_THROW_MSG("index not initialize or trained");
}
std::lock_guard<std::mutex> lk(mutex_);
GETTENSORWITHIDS(dataset_ptr)
index_->add_with_ids(rows, (float*)p_data, p_ids);
}
void
IVF::AddWithoutIds(const DatasetPtr& dataset_ptr, const Config& config) {
if (!index_ || !index_->is_trained) {
KNOWHERE_THROW_MSG("index not initialize or trained");
}
std::lock_guard<std::mutex> lk(mutex_);
GETTENSOR(dataset_ptr)
index_->add(rows, (float*)p_data);
}
DatasetPtr
IVF::Query(const DatasetPtr& dataset_ptr, const Config& config) {
if (!index_ || !index_->is_trained) {
KNOWHERE_THROW_MSG("index not initialize or trained");
}
GETTENSOR(dataset_ptr)
try {
fiu_do_on("IVF.Search.throw_std_exception", throw std::exception());
fiu_do_on("IVF.Search.throw_faiss_exception", throw faiss::FaissException(""));
int64_t k = config[meta::TOPK].get<int64_t>();
auto elems = rows * k;
size_t p_id_size = sizeof(int64_t) * elems;
size_t p_dist_size = sizeof(float) * elems;
auto p_id = (int64_t*)malloc(p_id_size);
auto p_dist = (float*)malloc(p_dist_size);
QueryImpl(rows, (float*)p_data, k, p_dist, p_id, config);
// std::stringstream ss_res_id, ss_res_dist;
// for (int i = 0; i < 10; ++i) {
// printf("%llu", p_id[i]);
// printf("\n");
// printf("%.6f", p_dist[i]);
// printf("\n");
// ss_res_id << p_id[i] << " ";
// ss_res_dist << p_dist[i] << " ";
// }
// std::cout << std::endl << "after search: " << std::endl;
// std::cout << ss_res_id.str() << std::endl;
// std::cout << ss_res_dist.str() << std::endl << std::endl;
auto ret_ds = std::make_shared<Dataset>();
ret_ds->Set(meta::IDS, p_id);
ret_ds->Set(meta::DISTANCE, p_dist);
return ret_ds;
} catch (faiss::FaissException& e) {
KNOWHERE_THROW_MSG(e.what());
} catch (std::exception& e) {
KNOWHERE_THROW_MSG(e.what());
}
}
DatasetPtr
IVF::QueryById(const DatasetPtr& dataset_ptr, const Config& config) {
if (!index_ || !index_->is_trained) {
KNOWHERE_THROW_MSG("index not initialize or trained");
}
auto rows = dataset_ptr->Get<int64_t>(meta::ROWS);
auto p_data = dataset_ptr->Get<const int64_t*>(meta::IDS);
try {
int64_t k = config[meta::TOPK].get<int64_t>();
auto elems = rows * k;
size_t p_id_size = sizeof(int64_t) * elems;
size_t p_dist_size = sizeof(float) * elems;
auto p_id = (int64_t*)malloc(p_id_size);
auto p_dist = (float*)malloc(p_dist_size);
// todo: enable search by id (zhiru)
// auto blacklist = dataset_ptr->Get<faiss::ConcurrentBitsetPtr>("bitset");
auto index_ivf = std::static_pointer_cast<faiss::IndexIVF>(index_);
index_ivf->search_by_id(rows, p_data, k, p_dist, p_id, bitset_);
// std::stringstream ss_res_id, ss_res_dist;
// for (int i = 0; i < 10; ++i) {
// printf("%llu", res_ids[i]);
// printf("\n");
// printf("%.6f", res_dis[i]);
// printf("\n");
// ss_res_id << res_ids[i] << " ";
// ss_res_dist << res_dis[i] << " ";
// }
// std::cout << std::endl << "after search: " << std::endl;
// std::cout << ss_res_id.str() << std::endl;
// std::cout << ss_res_dist.str() << std::endl << std::endl;
auto ret_ds = std::make_shared<Dataset>();
ret_ds->Set(meta::IDS, p_id);
ret_ds->Set(meta::DISTANCE, p_dist);
return ret_ds;
} catch (faiss::FaissException& e) {
KNOWHERE_THROW_MSG(e.what());
} catch (std::exception& e) {
KNOWHERE_THROW_MSG(e.what());
}
}
DatasetPtr
IVF::GetVectorById(const DatasetPtr& dataset_ptr, const Config& config) {
if (!index_ || !index_->is_trained) {
KNOWHERE_THROW_MSG("index not initialize or trained");
}
auto p_data = dataset_ptr->Get<const int64_t*>(meta::IDS);
auto elems = dataset_ptr->Get<int64_t>(meta::DIM);
try {
size_t p_x_size = sizeof(float) * elems;
auto p_x = (float*)malloc(p_x_size);
auto index_ivf = std::static_pointer_cast<faiss::IndexIVF>(index_);
index_ivf->get_vector_by_id(1, p_data, p_x, bitset_);
auto ret_ds = std::make_shared<Dataset>();
ret_ds->Set(meta::TENSOR, p_x);
return ret_ds;
} catch (faiss::FaissException& e) {
KNOWHERE_THROW_MSG(e.what());
} catch (std::exception& e) {
KNOWHERE_THROW_MSG(e.what());
}
}
void
IVF::Seal() {
if (!index_ || !index_->is_trained) {
KNOWHERE_THROW_MSG("index not initialize or trained");
}
SealImpl();
}
VecIndexPtr
IVF::CopyCpuToGpu(const int64_t device_id, const Config& config) {
#ifdef MILVUS_GPU_VERSION
if (auto res = FaissGpuResourceMgr::GetInstance().GetRes(device_id)) {
ResScope rs(res, device_id, false);
auto gpu_index = faiss::gpu::index_cpu_to_gpu(res->faiss_res.get(), device_id, index_.get());
std::shared_ptr<faiss::Index> device_index;
device_index.reset(gpu_index);
return std::make_shared<GPUIVF>(device_index, device_id, res);
} else {
KNOWHERE_THROW_MSG("CopyCpuToGpu Error, can't get gpu_resource");
}
#else
KNOWHERE_THROW_MSG("Calling IVF::CopyCpuToGpu when we are using CPU version");
#endif
}
void
IVF::GenGraph(const float* data, const int64_t k, GraphType& graph, const Config& config) {
int64_t K = k + 1;
auto ntotal = Count();
size_t dim = config[meta::DIM];
auto batch_size = 1000;
auto tail_batch_size = ntotal % batch_size;
auto batch_search_count = ntotal / batch_size;
auto total_search_count = tail_batch_size == 0 ? batch_search_count : batch_search_count + 1;
std::vector<float> res_dis(K * batch_size);
graph.resize(ntotal);
GraphType res_vec(total_search_count);
for (int i = 0; i < total_search_count; ++i) {
auto b_size = (i == (total_search_count - 1)) && tail_batch_size != 0 ? tail_batch_size : batch_size;
auto& res = res_vec[i];
res.resize(K * b_size);
auto xq = data + batch_size * dim * i;
QueryImpl(b_size, (float*)xq, K, res_dis.data(), res.data(), config);
for (int j = 0; j < b_size; ++j) {
auto& node = graph[batch_size * i + j];
node.resize(k);
auto start_pos = j * K + 1;
for (int m = 0, cursor = start_pos; m < k && cursor < start_pos + k; ++m, ++cursor) {
node[m] = res[cursor];
}
}
}
}
std::shared_ptr<faiss::IVFSearchParameters>
IVF::GenParams(const Config& config) {
auto params = std::make_shared<faiss::IVFSearchParameters>();
params->nprobe = config[IndexParams::nprobe];
// params->max_codes = config["max_codes"];
return params;
}
void
IVF::QueryImpl(int64_t n, const float* data, int64_t k, float* distances, int64_t* labels, const Config& config) {
auto params = GenParams(config);
auto ivf_index = dynamic_cast<faiss::IndexIVF*>(index_.get());
ivf_index->nprobe = params->nprobe;
stdclock::time_point before = stdclock::now();
if (params->nprobe > 1 && n <= 4) {
ivf_index->parallel_mode = 1;
} else {
ivf_index->parallel_mode = 0;
}
ivf_index->search(n, (float*)data, k, distances, labels, bitset_);
stdclock::time_point after = stdclock::now();
double search_cost = (std::chrono::duration<double, std::micro>(after - before)).count();
KNOWHERE_LOG_DEBUG << "IVF search cost: " << search_cost
<< ", quantization cost: " << faiss::indexIVF_stats.quantization_time
<< ", data search cost: " << faiss::indexIVF_stats.search_time;
faiss::indexIVF_stats.quantization_time = 0;
faiss::indexIVF_stats.search_time = 0;
}
void
IVF::SealImpl() {
#ifdef MILVUS_GPU_VERSION
faiss::Index* index = index_.get();
auto idx = dynamic_cast<faiss::IndexIVF*>(index);
if (idx != nullptr) {
// To be deleted
KNOWHERE_LOG_DEBUG << "Test before to_readonly: IVF READONLY " << std::boolalpha << idx->is_readonly();
idx->to_readonly();
}
#endif
}
} // namespace knowhere
} // namespace milvus
| 34.397516 | 114 | 0.633622 | [
"vector"
] |
4b291d8c842d8a28d39d97b28493debda452295d | 26,496 | cc | C++ | device/bluetooth/test/fake_central.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | device/bluetooth/test/fake_central.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | device/bluetooth/test/fake_central.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/test/fake_central.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/task/post_task.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_discovery_filter.h"
#include "device/bluetooth/bluetooth_discovery_session_outcome.h"
#include "device/bluetooth/public/cpp/bluetooth_uuid.h"
#include "device/bluetooth/public/mojom/test/fake_bluetooth.mojom.h"
#include "device/bluetooth/test/fake_peripheral.h"
#include "device/bluetooth/test/fake_remote_gatt_characteristic.h"
#include "device/bluetooth/test/fake_remote_gatt_service.h"
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
#include "device/bluetooth/bluetooth_low_energy_scan_filter.h"
#endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
namespace bluetooth {
namespace {
template <typename Optional, typename T = typename Optional::value_type>
T ValueOrDefault(Optional&& opt) {
return std::forward<Optional>(opt).value_or(T{});
}
device::BluetoothDevice::ManufacturerDataMap ToManufacturerDataMap(
base::flat_map<uint8_t, std::vector<uint8_t>>&& map) {
return device::BluetoothDevice::ManufacturerDataMap(
std::make_move_iterator(map.begin()), std::make_move_iterator(map.end()));
}
} // namespace
FakeCentral::FakeCentral(mojom::CentralState state,
mojo::PendingReceiver<mojom::FakeCentral> receiver)
: state_(state), receiver_(this, std::move(receiver)) {}
void FakeCentral::SimulatePreconnectedPeripheral(
const std::string& address,
const std::string& name,
const base::flat_map<uint16_t, std::vector<uint8_t>>& manufacturer_data,
const std::vector<device::BluetoothUUID>& known_service_uuids,
SimulatePreconnectedPeripheralCallback callback) {
FakePeripheral* fake_peripheral = GetFakePeripheral(address);
if (fake_peripheral == nullptr) {
auto fake_peripheral_ptr = std::make_unique<FakePeripheral>(this, address);
fake_peripheral = fake_peripheral_ptr.get();
auto pair = devices_.emplace(address, std::move(fake_peripheral_ptr));
DCHECK(pair.second);
}
fake_peripheral->SetName(name);
fake_peripheral->SetSystemConnected(true);
fake_peripheral->SetManufacturerData(
device::BluetoothDevice::ManufacturerDataMap(manufacturer_data.begin(),
manufacturer_data.end()));
fake_peripheral->SetServiceUUIDs(device::BluetoothDevice::UUIDSet(
known_service_uuids.begin(), known_service_uuids.end()));
std::move(callback).Run();
}
void FakeCentral::SimulateAdvertisementReceived(
mojom::ScanResultPtr scan_result_ptr,
SimulateAdvertisementReceivedCallback callback) {
if (NumDiscoverySessions() == 0) {
std::move(callback).Run();
return;
}
auto* fake_peripheral = GetFakePeripheral(scan_result_ptr->device_address);
const bool is_new_device = fake_peripheral == nullptr;
if (is_new_device) {
auto fake_peripheral_ptr =
std::make_unique<FakePeripheral>(this, scan_result_ptr->device_address);
fake_peripheral = fake_peripheral_ptr.get();
auto pair = devices_.emplace(scan_result_ptr->device_address,
std::move(fake_peripheral_ptr));
DCHECK(pair.second);
}
auto& scan_record = scan_result_ptr->scan_record;
auto uuids = ValueOrDefault(std::move(scan_record->uuids));
auto service_data = ValueOrDefault(std::move(scan_record->service_data));
auto manufacturer_data = ToManufacturerDataMap(
ValueOrDefault(std::move(scan_record->manufacturer_data)));
for (auto& observer : observers_) {
observer.DeviceAdvertisementReceived(
scan_result_ptr->device_address, scan_record->name, scan_record->name,
scan_result_ptr->rssi, scan_record->tx_power->value,
absl::nullopt, /* TODO(crbug.com/588083) Implement appearance */
uuids, service_data, manufacturer_data);
}
fake_peripheral->SetName(std::move(scan_record->name));
fake_peripheral->UpdateAdvertisementData(
scan_result_ptr->rssi, absl::nullopt /* flags */, uuids,
scan_record->tx_power->has_value
? absl::make_optional(scan_record->tx_power->value)
: absl::nullopt,
service_data, manufacturer_data);
if (is_new_device) {
// Call DeviceAdded on observers because it is a newly detected peripheral.
for (auto& observer : observers_) {
observer.DeviceAdded(this, fake_peripheral);
}
} else {
// Call DeviceChanged on observers because it is a device that was detected
// before.
for (auto& observer : observers_) {
observer.DeviceChanged(this, fake_peripheral);
}
}
std::move(callback).Run();
}
void FakeCentral::SetState(mojom::CentralState new_state,
SetStateCallback callback) {
// In real devices, when a powered on adapter is added, we notify that it was
// added and then that it was powered on. When an adapter is removed, we
// notify that it was powered off and then that it was removed. The following
// logic simulates this behavior.
if (new_state == state_) {
std::move(callback).Run();
return;
}
const mojom::CentralState old_state = state_;
state_ = new_state;
auto notify_present_changed = [this]() {
NotifyAdapterPresentChanged(IsPresent());
};
auto notify_powered_changed = [this]() {
NotifyAdapterPoweredChanged(IsPowered());
};
switch (old_state) {
case mojom::CentralState::ABSENT:
notify_present_changed();
if (new_state == mojom::CentralState::POWERED_ON)
notify_powered_changed();
break;
case mojom::CentralState::POWERED_OFF:
if (new_state == mojom::CentralState::ABSENT)
notify_present_changed();
else
notify_powered_changed();
break;
case mojom::CentralState::POWERED_ON:
notify_powered_changed();
if (new_state == mojom::CentralState::ABSENT)
notify_present_changed();
break;
}
std::move(callback).Run();
}
void FakeCentral::SetNextGATTConnectionResponse(
const std::string& address,
uint16_t code,
SetNextGATTConnectionResponseCallback callback) {
FakePeripheral* fake_peripheral = GetFakePeripheral(address);
if (fake_peripheral == nullptr) {
std::move(callback).Run(false);
return;
}
fake_peripheral->SetNextGATTConnectionResponse(code);
std::move(callback).Run(true);
}
void FakeCentral::SetNextGATTDiscoveryResponse(
const std::string& address,
uint16_t code,
SetNextGATTDiscoveryResponseCallback callback) {
FakePeripheral* fake_peripheral = GetFakePeripheral(address);
if (fake_peripheral == nullptr) {
std::move(callback).Run(false);
return;
}
fake_peripheral->SetNextGATTDiscoveryResponse(code);
std::move(callback).Run(true);
}
bool FakeCentral::AllResponsesConsumed() {
return std::all_of(devices_.begin(), devices_.end(), [](const auto& e) {
// static_cast is safe because the parent class's devices_ is only
// populated via this FakeCentral, and only with FakePeripherals.
FakePeripheral* fake_peripheral =
static_cast<FakePeripheral*>(e.second.get());
return fake_peripheral->AllResponsesConsumed();
});
}
void FakeCentral::SimulateGATTDisconnection(
const std::string& address,
SimulateGATTDisconnectionCallback callback) {
FakePeripheral* fake_peripheral = GetFakePeripheral(address);
if (fake_peripheral == nullptr) {
std::move(callback).Run(false);
return;
}
fake_peripheral->SimulateGATTDisconnection();
std::move(callback).Run(true);
}
void FakeCentral::SimulateGATTServicesChanged(
const std::string& address,
SimulateGATTServicesChangedCallback callback) {
FakePeripheral* fake_peripheral = GetFakePeripheral(address);
if (fake_peripheral == nullptr) {
std::move(callback).Run(false);
return;
}
std::move(callback).Run(true);
}
void FakeCentral::AddFakeService(const std::string& peripheral_address,
const device::BluetoothUUID& service_uuid,
AddFakeServiceCallback callback) {
FakePeripheral* fake_peripheral = GetFakePeripheral(peripheral_address);
if (fake_peripheral == nullptr) {
std::move(callback).Run(absl::nullopt);
return;
}
std::move(callback).Run(fake_peripheral->AddFakeService(service_uuid));
}
void FakeCentral::RemoveFakeService(const std::string& identifier,
const std::string& peripheral_address,
RemoveFakeServiceCallback callback) {
FakePeripheral* fake_peripheral = GetFakePeripheral(peripheral_address);
if (!fake_peripheral) {
std::move(callback).Run(false);
return;
}
std::move(callback).Run(fake_peripheral->RemoveFakeService(identifier));
}
void FakeCentral::AddFakeCharacteristic(
const device::BluetoothUUID& characteristic_uuid,
mojom::CharacteristicPropertiesPtr properties,
const std::string& service_id,
const std::string& peripheral_address,
AddFakeCharacteristicCallback callback) {
FakeRemoteGattService* fake_remote_gatt_service =
GetFakeRemoteGattService(peripheral_address, service_id);
if (fake_remote_gatt_service == nullptr) {
std::move(callback).Run(absl::nullopt);
return;
}
std::move(callback).Run(fake_remote_gatt_service->AddFakeCharacteristic(
characteristic_uuid, std::move(properties)));
}
void FakeCentral::RemoveFakeCharacteristic(
const std::string& identifier,
const std::string& service_id,
const std::string& peripheral_address,
RemoveFakeCharacteristicCallback callback) {
FakeRemoteGattService* fake_remote_gatt_service =
GetFakeRemoteGattService(peripheral_address, service_id);
if (fake_remote_gatt_service == nullptr) {
std::move(callback).Run(false);
return;
}
std::move(callback).Run(
fake_remote_gatt_service->RemoveFakeCharacteristic(identifier));
}
void FakeCentral::AddFakeDescriptor(
const device::BluetoothUUID& descriptor_uuid,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
AddFakeDescriptorCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (fake_remote_gatt_characteristic == nullptr) {
std::move(callback).Run(absl::nullopt);
return;
}
std::move(callback).Run(
fake_remote_gatt_characteristic->AddFakeDescriptor(descriptor_uuid));
}
void FakeCentral::RemoveFakeDescriptor(const std::string& descriptor_id,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
RemoveFakeDescriptorCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (!fake_remote_gatt_characteristic) {
std::move(callback).Run(false);
return;
}
std::move(callback).Run(
fake_remote_gatt_characteristic->RemoveFakeDescriptor(descriptor_id));
}
void FakeCentral::SetNextReadCharacteristicResponse(
uint16_t gatt_code,
const absl::optional<std::vector<uint8_t>>& value,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
SetNextReadCharacteristicResponseCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (fake_remote_gatt_characteristic == nullptr) {
std::move(callback).Run(false);
return;
}
fake_remote_gatt_characteristic->SetNextReadResponse(gatt_code, value);
std::move(callback).Run(true);
}
void FakeCentral::SetNextWriteCharacteristicResponse(
uint16_t gatt_code,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
SetNextWriteCharacteristicResponseCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (fake_remote_gatt_characteristic == nullptr) {
std::move(callback).Run(false);
return;
}
fake_remote_gatt_characteristic->SetNextWriteResponse(gatt_code);
std::move(callback).Run(true);
}
void FakeCentral::SetNextSubscribeToNotificationsResponse(
uint16_t gatt_code,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
SetNextSubscribeToNotificationsResponseCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (fake_remote_gatt_characteristic == nullptr) {
std::move(callback).Run(false);
return;
}
fake_remote_gatt_characteristic->SetNextSubscribeToNotificationsResponse(
gatt_code);
std::move(callback).Run(true);
}
void FakeCentral::SetNextUnsubscribeFromNotificationsResponse(
uint16_t gatt_code,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
SetNextUnsubscribeFromNotificationsResponseCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (fake_remote_gatt_characteristic == nullptr) {
std::move(callback).Run(false);
return;
}
fake_remote_gatt_characteristic->SetNextUnsubscribeFromNotificationsResponse(
gatt_code);
std::move(callback).Run(true);
}
void FakeCentral::IsNotifying(const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
IsNotifyingCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (!fake_remote_gatt_characteristic) {
std::move(callback).Run(false, false);
return;
}
std::move(callback).Run(true, fake_remote_gatt_characteristic->IsNotifying());
}
void FakeCentral::GetLastWrittenCharacteristicValue(
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
GetLastWrittenCharacteristicValueCallback callback) {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (fake_remote_gatt_characteristic == nullptr) {
std::move(callback).Run(false, absl::nullopt, mojom::WriteType::kNone);
return;
}
std::move(callback).Run(true,
fake_remote_gatt_characteristic->last_written_value(),
fake_remote_gatt_characteristic->last_write_type());
}
void FakeCentral::SetNextReadDescriptorResponse(
uint16_t gatt_code,
const absl::optional<std::vector<uint8_t>>& value,
const std::string& descriptor_id,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
SetNextReadDescriptorResponseCallback callback) {
FakeRemoteGattDescriptor* fake_remote_gatt_descriptor =
GetFakeRemoteGattDescriptor(peripheral_address, service_id,
characteristic_id, descriptor_id);
if (fake_remote_gatt_descriptor == nullptr) {
std::move(callback).Run(false);
return;
}
fake_remote_gatt_descriptor->SetNextReadResponse(gatt_code, value);
std::move(callback).Run(true);
}
void FakeCentral::SetNextWriteDescriptorResponse(
uint16_t gatt_code,
const std::string& descriptor_id,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
SetNextWriteDescriptorResponseCallback callback) {
FakeRemoteGattDescriptor* fake_remote_gatt_descriptor =
GetFakeRemoteGattDescriptor(peripheral_address, service_id,
characteristic_id, descriptor_id);
if (!fake_remote_gatt_descriptor) {
std::move(callback).Run(false);
return;
}
fake_remote_gatt_descriptor->SetNextWriteResponse(gatt_code);
std::move(callback).Run(true);
}
void FakeCentral::GetLastWrittenDescriptorValue(
const std::string& descriptor_id,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
GetLastWrittenDescriptorValueCallback callback) {
FakeRemoteGattDescriptor* fake_remote_gatt_descriptor =
GetFakeRemoteGattDescriptor(peripheral_address, service_id,
characteristic_id, descriptor_id);
if (!fake_remote_gatt_descriptor) {
std::move(callback).Run(false, absl::nullopt);
return;
}
std::move(callback).Run(true,
fake_remote_gatt_descriptor->last_written_value());
}
void FakeCentral::Initialize(base::OnceClosure callback) {
std::move(callback).Run();
}
std::string FakeCentral::GetAddress() const {
NOTREACHED();
return std::string();
}
std::string FakeCentral::GetName() const {
NOTREACHED();
return std::string();
}
void FakeCentral::SetName(const std::string& name,
base::OnceClosure callback,
ErrorCallback error_callback) {
NOTREACHED();
}
bool FakeCentral::IsInitialized() const {
return true;
}
bool FakeCentral::IsPresent() const {
switch (state_) {
case mojom::CentralState::ABSENT:
return false;
case mojom::CentralState::POWERED_OFF:
case mojom::CentralState::POWERED_ON:
return true;
}
NOTREACHED();
return false;
}
bool FakeCentral::IsPowered() const {
switch (state_) {
case mojom::CentralState::ABSENT:
// SetState() calls IsPowered() to notify observers properly when an adapter
// being removed is simulated, so it should return false.
case mojom::CentralState::POWERED_OFF:
return false;
case mojom::CentralState::POWERED_ON:
return true;
}
NOTREACHED();
return false;
}
void FakeCentral::SetPowered(bool powered,
base::OnceClosure callback,
ErrorCallback error_callback) {
NOTREACHED();
}
bool FakeCentral::IsDiscoverable() const {
NOTREACHED();
return false;
}
void FakeCentral::SetDiscoverable(bool discoverable,
base::OnceClosure callback,
ErrorCallback error_callback) {
NOTREACHED();
}
bool FakeCentral::IsDiscovering() const {
NOTREACHED();
return false;
}
FakeCentral::UUIDList FakeCentral::GetUUIDs() const {
NOTREACHED();
return UUIDList();
}
void FakeCentral::CreateRfcommService(
const device::BluetoothUUID& uuid,
const ServiceOptions& options,
CreateServiceCallback callback,
CreateServiceErrorCallback error_callback) {
NOTREACHED();
}
void FakeCentral::CreateL2capService(
const device::BluetoothUUID& uuid,
const ServiceOptions& options,
CreateServiceCallback callback,
CreateServiceErrorCallback error_callback) {
NOTREACHED();
}
void FakeCentral::RegisterAdvertisement(
std::unique_ptr<device::BluetoothAdvertisement::Data> advertisement_data,
CreateAdvertisementCallback callback,
AdvertisementErrorCallback error_callback) {
NOTREACHED();
}
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
void FakeCentral::SetAdvertisingInterval(
const base::TimeDelta& min,
const base::TimeDelta& max,
base::OnceClosure callback,
AdvertisementErrorCallback error_callback) {
NOTREACHED();
}
void FakeCentral::ResetAdvertising(base::OnceClosure callback,
AdvertisementErrorCallback error_callback) {
NOTREACHED();
}
void FakeCentral::ConnectDevice(
const std::string& address,
const absl::optional<device::BluetoothDevice::AddressType>& address_type,
ConnectDeviceCallback callback,
ErrorCallback error_callback) {
NOTREACHED();
}
#endif
device::BluetoothLocalGattService* FakeCentral::GetGattService(
const std::string& identifier) const {
NOTREACHED();
return nullptr;
}
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
void FakeCentral::SetServiceAllowList(const UUIDList& uuids,
base::OnceClosure callback,
ErrorCallback error_callback) {
NOTREACHED();
}
std::unique_ptr<device::BluetoothLowEnergyScanSession>
FakeCentral::StartLowEnergyScanSession(
std::unique_ptr<device::BluetoothLowEnergyScanFilter> filter,
base::WeakPtr<device::BluetoothLowEnergyScanSession::Delegate> delegate) {
NOTREACHED();
return nullptr;
}
device::BluetoothAdapter::LowEnergyScanSessionHardwareOffloadingStatus
FakeCentral::GetLowEnergyScanSessionHardwareOffloadingStatus() {
return LowEnergyScanSessionHardwareOffloadingStatus::kNotSupported;
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
base::WeakPtr<device::BluetoothAdapter> FakeCentral::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
bool FakeCentral::SetPoweredImpl(bool powered) {
NOTREACHED();
return false;
}
void FakeCentral::UpdateFilter(
std::unique_ptr<device::BluetoothDiscoveryFilter> discovery_filter,
DiscoverySessionResultCallback callback) {
if (!IsPresent()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback), /*is_error=*/true,
device::UMABluetoothDiscoverySessionOutcome::ADAPTER_NOT_PRESENT));
return;
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), /*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::SUCCESS));
}
void FakeCentral::StartScanWithFilter(
std::unique_ptr<device::BluetoothDiscoveryFilter> discovery_filter,
DiscoverySessionResultCallback callback) {
if (!IsPresent()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback), /*is_error=*/true,
device::UMABluetoothDiscoverySessionOutcome::ADAPTER_NOT_PRESENT));
return;
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), /*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::SUCCESS));
}
void FakeCentral::StopScan(DiscoverySessionResultCallback callback) {
if (!IsPresent()) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback), /*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::ADAPTER_NOT_PRESENT));
return;
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback), /*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::ADAPTER_NOT_PRESENT));
}
void FakeCentral::RemovePairingDelegateInternal(
device::BluetoothDevice::PairingDelegate* pairing_delegate) {
NOTREACHED();
}
FakeCentral::~FakeCentral() = default;
FakePeripheral* FakeCentral::GetFakePeripheral(
const std::string& peripheral_address) const {
auto device_iter = devices_.find(peripheral_address);
if (device_iter == devices_.end()) {
return nullptr;
}
// static_cast is safe because the parent class's devices_ is only
// populated via this FakeCentral, and only with FakePeripherals.
return static_cast<FakePeripheral*>(device_iter->second.get());
}
FakeRemoteGattService* FakeCentral::GetFakeRemoteGattService(
const std::string& peripheral_address,
const std::string& service_id) const {
FakePeripheral* fake_peripheral = GetFakePeripheral(peripheral_address);
if (fake_peripheral == nullptr) {
return nullptr;
}
// static_cast is safe because FakePeripheral is only populated with
// FakeRemoteGattServices.
return static_cast<FakeRemoteGattService*>(
fake_peripheral->GetGattService(service_id));
}
FakeRemoteGattCharacteristic* FakeCentral::GetFakeRemoteGattCharacteristic(
const std::string& peripheral_address,
const std::string& service_id,
const std::string& characteristic_id) const {
FakeRemoteGattService* fake_remote_gatt_service =
GetFakeRemoteGattService(peripheral_address, service_id);
if (fake_remote_gatt_service == nullptr) {
return nullptr;
}
// static_cast is safe because FakeRemoteGattService is only populated with
// FakeRemoteGattCharacteristics.
return static_cast<FakeRemoteGattCharacteristic*>(
fake_remote_gatt_service->GetCharacteristic(characteristic_id));
}
FakeRemoteGattDescriptor* FakeCentral::GetFakeRemoteGattDescriptor(
const std::string& peripheral_address,
const std::string& service_id,
const std::string& characteristic_id,
const std::string& descriptor_id) const {
FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic =
GetFakeRemoteGattCharacteristic(peripheral_address, service_id,
characteristic_id);
if (fake_remote_gatt_characteristic == nullptr) {
return nullptr;
}
// static_cast is safe because FakeRemoteGattCharacteristic is only populated
// with FakeRemoteGattDescriptors.
return static_cast<FakeRemoteGattDescriptor*>(
fake_remote_gatt_characteristic->GetDescriptor(descriptor_id));
}
} // namespace bluetooth
| 34.5 | 80 | 0.716599 | [
"vector"
] |
4b33170a9bf4251347f553bc37349558609b6b3b | 9,331 | hpp | C++ | src/ttauri/bezier.hpp | PinkFlufflyLlama/ttauri | 7badcfbe792932ebb912d54d1062d8fc820c40a7 | [
"BSL-1.0"
] | 2 | 2021-09-21T00:07:50.000Z | 2021-09-21T22:28:28.000Z | src/ttauri/bezier.hpp | PinkFlufflyLlama/ttauri | 7badcfbe792932ebb912d54d1062d8fc820c40a7 | [
"BSL-1.0"
] | null | null | null | src/ttauri/bezier.hpp | PinkFlufflyLlama/ttauri | 7badcfbe792932ebb912d54d1062d8fc820c40a7 | [
"BSL-1.0"
] | null | null | null | // Copyright Take Vos 2019-2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "polynomial.hpp"
#include "rapid/numeric_array.hpp"
#include "geometry/point.hpp"
#include <array>
#include <optional>
namespace tt {
// B(t)=(P_{2}-P_{1})t+P_{1}
template<typename T>
constexpr std::array<T, 2> bezierToPolynomial(T P1, T P2) noexcept
{
return {P2 - P1, P1};
}
// B(t)=(P_{1}-2C+P_{2})t^{2}+2(C-P_{1})t+P_{1}
template<typename T>
constexpr std::array<T, 3> bezierToPolynomial(T P1, T C, T P2) noexcept
{
return {P1 - C * 2 + P2, (C - P1) * 2, P1};
}
// B(t)=(-P_{1}+3C_{1}-3C_{2}+P_{2})t^{3}+(3P_{1}-6_{1}+3C_{2})t^{2}+(-3P_{1}+3C_{1})t+P_{1}
template<typename T>
constexpr std::array<T, 4> bezierToPolynomial(T P1, T C1, T C2, T P2) noexcept
{
return {-P1 + C1 * 3 - C2 * 3 + P2, P1 * 3 - C1 * 6 + C2 * 3, P1 * -3 + C1 * 3, P1};
}
template<int D>
constexpr geo::point<D> bezierPointAt(geo::point<D> P1, geo::point<D> P2, float t) noexcept
{
ttlet[a, b] = bezierToPolynomial(static_cast<f32x4>(P1), static_cast<f32x4>(P2));
return geo::point<D>{a * t + b};
}
template<int D>
constexpr geo::point<D> bezierPointAt(geo::point<D> P1, geo::point<D> C, geo::point<D> P2, float t) noexcept
{
ttlet[a, b, c] = bezierToPolynomial(static_cast<f32x4>(P1), static_cast<f32x4>(C), static_cast<f32x4>(P2));
return geo::point<D>{a * t * t + b * t + c};
}
template<int D>
constexpr geo::point<D> bezierPointAt(geo::point<D> P1, geo::point<D> C1, geo::point<D> C2, geo::point<D> P2, float t) noexcept
{
ttlet[a, b, c, d] =
bezierToPolynomial(static_cast<f32x4>(P1), static_cast<f32x4>(C1), static_cast<f32x4>(C2), static_cast<f32x4>(P2));
return geo::point<D>{a * t * t * t + b * t * t + c * t + d};
}
template<int D>
inline geo::vector<D> bezierTangentAt(geo::point<D> P1, geo::point<D> P2, float t) noexcept
{
return P2 - P1;
}
template<int D>
inline geo::vector<D> bezierTangentAt(geo::point<D> P1, geo::point<D> C, geo::point<D> P2, float t) noexcept
{
ttlet P1_ = static_cast<f32x4>(P1);
ttlet C_ = static_cast<f32x4>(C);
ttlet P2_ = static_cast<f32x4>(P2);
return geo::vector<D>{2 * t * (P2_ - 2 * C_ + P1_) + 2 * (C_ - P1_)};
}
template<int D>
inline geo::vector<D> bezierTangentAt(geo::point<D> P1, geo::point<D> C1, geo::point<D> C2, geo::point<D> P2, float t) noexcept
{
ttlet P1_ = static_cast<f32x4>(P1);
ttlet C1_ = static_cast<f32x4>(C1);
ttlet C2_ = static_cast<f32x4>(C2);
ttlet P2_ = static_cast<f32x4>(P2);
return geo::vector<D>{3 * t * t * (P2_ - 3 * C2_ + 3 * C1_ - P1_) + 6 * t * (C2_ - 2 * C1_ + P1_) + 3 * (C1_ - P1_)};
}
inline results<float, 1> bezierFindT(float P1, float P2, float x) noexcept
{
ttlet[a, b] = bezierToPolynomial(P1, P2);
return solvePolynomial(a, b - x);
}
inline results<float, 2> bezierFindT(float P1, float C, float P2, float x) noexcept
{
ttlet[a, b, c] = bezierToPolynomial(P1, C, P2);
return solvePolynomial(a, b, c - x);
}
inline results<float, 3> bezierFindT(float P1, float C1, float C2, float P2, float x) noexcept
{
ttlet[a, b, c, d] = bezierToPolynomial(P1, C1, C2, P2);
return solvePolynomial(a, b, c, d - x);
}
/** Find t on the line P1->P2 which is closest to P.
* Used for finding the shortest distance from a point to a curve.
* The shortest vector from a curve to a point is a normal.
*/
inline results<float, 1> bezierFindTForNormalsIntersectingPoint(point2 P1, point2 P2, point2 P) noexcept
{
auto t_above = dot(P - P1, P2 - P1);
auto t_below = dot(P2 - P1, P2 - P1);
if (t_below == 0.0) {
[[unlikely]] return {};
} else {
return {t_above / t_below};
}
}
/** Find t on the curve P1->C->P2 which is closest to P.
* Used for finding the shortest distance from a point to a curve.
* The shortest vector from a curve to a point is a normal.
*/
inline results<float, 3> bezierFindTForNormalsIntersectingPoint(point2 P1, point2 C, point2 P2, point2 P) noexcept
{
ttlet P1_ = static_cast<f32x4>(P1);
ttlet P2_ = static_cast<f32x4>(P2);
ttlet C_ = static_cast<f32x4>(C);
ttlet p = P - P1;
ttlet p1 = C - P1;
ttlet p2 = vector2{P2_ - (2 * C_) + P1_};
ttlet a = dot(p2, p2);
ttlet b = 3 * dot(p1, p2);
ttlet c = dot(2 * p1, p1) - dot(p2, p);
ttlet d = -dot(p1, p);
return solvePolynomial(a, b, c, d);
}
/*! Find x for y on a bezier curve.
* In a contour, multiple bezier curves are attached to each other
* on the anchor point. We don't want duplicate results when
* passing `y` that is at the same height as an anchor point.
* So we compare with less than to the end-anchor point to remove
* it from the result.
*/
inline results<float, 1> bezierFindX(point2 P1, point2 P2, float y) noexcept
{
if (y < std::min({P1.y(), P2.y()}) || y > std::max({P1.y(), P2.y()})) {
return {};
}
results<float, 1> r;
for (ttlet t : bezierFindT(P1.y(), P2.y(), y)) {
if (t >= 0.0f && t < 1.0f) {
r.add(bezierPointAt(P1, P2, t).x());
}
}
return r;
}
/*! Find x for y on a bezier curve.
* In a contour, multiple bezier curves are attached to each other
* on the anchor point. We don't want duplicate results when
* passing `y` that is at the same height as an anchor point.
* So we compare with less than to the end-anchor point to remove
* it from the result.
*/
inline results<float, 2> bezierFindX(point2 P1, point2 C, point2 P2, float y) noexcept
{
results<float, 2> r{};
if (y < std::min({P1.y(), C.y(), P2.y()}) || y > std::max({P1.y(), C.y(), P2.y()})) {
return r;
}
for (ttlet t : bezierFindT(P1.y(), C.y(), P2.y(), y)) {
if (t >= 0.0f && t <= 1.0f) {
r.add(bezierPointAt(P1, C, P2, t).x());
}
}
return r;
}
/*! Find x for y on a bezier curve.
* In a contour, multiple bezier curves are attached to each other
* on the anchor point. We don't want duplicate results when
* passing `y` that is at the same height as an anchor point.
* So we compare with less than to the end-anchor point to remove
* it from the result.
*/
inline results<float, 3> bezierFindX(point2 P1, point2 C1, point2 C2, point2 P2, float y) noexcept
{
results<float, 3> r{};
if (y < std::min({P1.y(), C1.y(), C2.y(), P2.y()}) || y > std::max({P1.y(), C1.y(), C2.y(), P2.y()})) {
return r;
}
for (ttlet t : bezierFindT(P1.y(), C1.y(), C2.y(), P2.y(), y)) {
if (t >= 0.0f && t <= 1.0f) {
r.add(bezierPointAt(P1, C1, C2, P2, t).x());
}
}
return r;
}
/*! Return the flatness of a curve.
* \return 1.0 when completely flat, < 1.0 when curved.
*/
inline float bezierFlatness(point2 P1, point2 P2) noexcept
{
return 1.0f;
}
/*! Return the flatness of a curve.
* \return 1.0 when completely flat, < 1.0 when curved.
*/
inline float bezierFlatness(point2 P1, point2 C, point2 P2) noexcept
{
ttlet P1P2 = hypot(P2 - P1);
if (P1P2 == 0.0f) {
return 1.0;
}
ttlet P1C1 = hypot(C - P1);
ttlet C1P2 = hypot(P2 - C);
return P1P2 / (P1C1 + C1P2);
}
/*! Return the flatness of a curve.
* \return 1.0 when completely flat, < 1.0 when curved.
*/
inline float bezierFlatness(point2 P1, point2 C1, point2 C2, point2 P2) noexcept
{
ttlet P1P2 = hypot(P2 - P1);
if (P1P2 == 0.0f) {
return 1.0;
}
ttlet P1C1 = hypot(C1 - P1);
ttlet C1C2 = hypot(C2 - C1);
ttlet C2P2 = hypot(P2 - C2);
return P1P2 / (P1C1 + C1C2 + C2P2);
}
inline std::pair<point2, point2> parallelLine(point2 P1, point2 P2, float distance) noexcept
{
ttlet v = P2 - P1;
ttlet n = normal(v);
return {P1 + n * distance, P2 + n * distance};
}
/*! Find the intersect points between two line segments.
*/
inline std::optional<point2> getIntersectionPoint(point2 A1, point2 A2, point2 B1, point2 B2) noexcept
{
// convert points to vectors.
ttlet p = A1;
ttlet r = A2 - A1;
ttlet q = B1;
ttlet s = B2 - B1;
// find t and u in:
// p + t*r == q + us
ttlet crossRS = cross(r, s);
if (crossRS == 0.0f) {
// Parallel, other non, or a range of points intersect.
return {};
} else {
ttlet q_min_p = q - p;
ttlet t = cross(q_min_p, s) / crossRS;
ttlet u = cross(q_min_p, r) / crossRS;
if (t >= 0.0f && t <= 1.0f && u >= 0.0f && u <= 1.0f) {
return bezierPointAt(A1, A2, t);
} else {
// The lines intersect outside of one or both of the segments.
return {};
}
}
}
/*! Find the intersect points between two line segments.
*/
inline std::optional<point2> getExtrapolatedIntersectionPoint(point2 A1, point2 A2, point2 B1, point2 B2) noexcept
{
// convert points to vectors.
ttlet p = A1;
ttlet r = A2 - A1;
ttlet q = B1;
ttlet s = B2 - B1;
// find t and u in:
// p + t*r == q + us
ttlet crossRS = cross(r, s);
if (crossRS == 0.0f) {
// Parallel, other non, or a range of points intersect.
return {};
} else {
ttlet q_min_p = q - p;
ttlet t = cross(q_min_p, s) / crossRS;
return bezierPointAt(A1, A2, t);
}
}
} // namespace tt
| 29.622222 | 127 | 0.601543 | [
"geometry",
"vector"
] |
4b3481dbb398e63bb6bbbcbff32a18333f8cf4ec | 61,941 | hpp | C++ | src/core/thread/mle.hpp | makerdiary/openthread | 7bc5dfdc641851a6e111af382860257859d12cae | [
"BSD-3-Clause"
] | 1 | 2020-02-01T04:33:01.000Z | 2020-02-01T04:33:01.000Z | src/core/thread/mle.hpp | makerdiary/openthread | 7bc5dfdc641851a6e111af382860257859d12cae | [
"BSD-3-Clause"
] | null | null | null | src/core/thread/mle.hpp | makerdiary/openthread | 7bc5dfdc641851a6e111af382860257859d12cae | [
"BSD-3-Clause"
] | 1 | 2019-08-08T22:45:06.000Z | 2019-08-08T22:45:06.000Z | /*
* Copyright (c) 2016, The OpenThread Authors.
* 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. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file includes definitions for MLE functionality required by the Thread Child, Router, and Leader roles.
*/
#ifndef MLE_HPP_
#define MLE_HPP_
#include "openthread-core-config.h"
#include "common/encoding.hpp"
#include "common/locator.hpp"
#include "common/timer.hpp"
#include "mac/mac.hpp"
#include "meshcop/joiner_router.hpp"
#include "net/udp6.hpp"
#include "thread/mle_constants.hpp"
#include "thread/mle_tlvs.hpp"
#include "thread/topology.hpp"
namespace ot {
/**
* @addtogroup core-mle MLE
*
* @brief
* This module includes definitions for the MLE protocol.
*
* @{
*
* @defgroup core-mle-core Core
* @defgroup core-mle-router Router
* @defgroup core-mle-tlvs TLVs
*
* @}
*/
/**
* @namespace ot::Mle
*
* @brief
* This namespace includes definitions for the MLE protocol.
*/
namespace Mle {
/**
* @addtogroup core-mle-core
*
* @brief
* This module includes definitions for MLE functionality required by the Thread Child, Router, and Leader roles.
*
* @{
*
*/
/**
* MLE Attach modes
*
*/
enum AttachMode
{
kAttachAny = 0, ///< Attach to any Thread partition.
kAttachSame1 = 1, ///< Attach to the same Thread partition (attempt 1 when losing connectivity).
kAttachSame2 = 2, ///< Attach to the same Thread partition (attempt 2 when losing connectivity).
kAttachBetter = 3, ///< Attach to a better (i.e. higher weight/partition id) Thread partition.
kAttachSameDowngrade = 4, ///< Attach to the same Thread partition during downgrade process.
};
/**
* This enumeration represents the allocation of the ALOC Space
*
*/
enum AlocAllocation
{
kAloc16Leader = 0xfc00,
kAloc16DhcpAgentStart = 0xfc01,
kAloc16DhcpAgentEnd = 0xfc0f,
kAloc16DhcpAgentMask = 0x000f,
kAloc16ServiceStart = 0xfc10,
kAloc16ServiceEnd = 0xfc2f,
kAloc16CommissionerStart = 0xfc30,
kAloc16CommissionerEnd = 0xfc37,
kAloc16CommissionerMask = 0x0007,
kAloc16NeighborDiscoveryAgentStart = 0xfc40,
kAloc16NeighborDiscoveryAgentEnd = 0xfc4e,
};
/**
* Service IDs
*
*/
enum ServiceID
{
kServiceMinId = 0x00, ///< Minimal Service ID.
kServiceMaxId = 0x0f, ///< Maximal Service ID.
};
/**
* This class implements MLE Header generation and parsing.
*
*/
OT_TOOL_PACKED_BEGIN
class Header
{
public:
/**
* This method initializes the MLE header.
*
*/
void Init(void)
{
mSecuritySuite = k154Security;
mSecurityControl = Mac::Frame::kSecEncMic32;
}
/**
* This method indicates whether or not the TLV appears to be well-formed.
*
* @retval TRUE If the TLV appears to be well-formed.
* @retval FALSE If the TLV does not appear to be well-formed.
*
*/
bool IsValid(void) const
{
return (mSecuritySuite == kNoSecurity) ||
(mSecuritySuite == k154Security &&
mSecurityControl == (Mac::Frame::kKeyIdMode2 | Mac::Frame::kSecEncMic32));
}
/**
* This method returns the MLE header and Command Type length.
*
* @returns The MLE header and Command Type length.
*
*/
uint8_t GetLength(void) const
{
uint8_t rval = sizeof(mSecuritySuite) + sizeof(mCommand);
if (mSecuritySuite == k154Security)
{
rval += sizeof(mSecurityControl) + sizeof(mFrameCounter) + sizeof(mKeySource) + sizeof(mKeyIndex);
}
return rval;
}
enum SecuritySuite
{
k154Security = 0, ///< IEEE 802.15.4-2006 security.
kNoSecurity = 255, ///< No security enabled.
};
/**
* This method returns the Security Suite value.
*
* @returns The Security Suite value.
*
*/
SecuritySuite GetSecuritySuite(void) const { return static_cast<SecuritySuite>(mSecuritySuite); }
/**
* This method sets the Security Suite value.
*
* @param[in] aSecuritySuite The Security Suite value.
*
*/
void SetSecuritySuite(SecuritySuite aSecuritySuite) { mSecuritySuite = static_cast<uint8_t>(aSecuritySuite); }
/**
* This method returns the MLE header length (excluding the Command Type).
*
* @returns The MLE header length (excluding the Command Type).
*
*/
uint8_t GetHeaderLength(void) const
{
return sizeof(mSecurityControl) + sizeof(mFrameCounter) + sizeof(mKeySource) + sizeof(mKeyIndex);
}
/**
* This method returns a pointer to first byte of the MLE header.
*
* @returns A pointer to the first byte of the MLE header.
*
*/
const uint8_t *GetBytes(void) const { return reinterpret_cast<const uint8_t *>(&mSecuritySuite); }
/**
* This method returns the Security Control value.
*
* @returns The Security Control value.
*
*/
uint8_t GetSecurityControl(void) const { return mSecurityControl; }
/**
* This method indicates whether or not the Key ID Mode is set to 2.
*
* @retval TRUE If the Key ID Mode is set to 2.
* @retval FALSE If the Key ID Mode is not set to 2.
*
*/
bool IsKeyIdMode2(void) const { return (mSecurityControl & Mac::Frame::kKeyIdModeMask) == Mac::Frame::kKeyIdMode2; }
/**
* This method sets the Key ID Mode to 2.
*
*/
void SetKeyIdMode2(void)
{
mSecurityControl = (mSecurityControl & ~Mac::Frame::kKeyIdModeMask) | Mac::Frame::kKeyIdMode2;
}
/**
* This method returns the Key ID value.
*
* @returns The Key ID value.
*
*/
uint32_t GetKeyId(void) const { return Encoding::BigEndian::HostSwap32(mKeySource); }
/**
* This method sets the Key ID value.
*
* @param[in] aKeySequence The Key ID value.
*
*/
void SetKeyId(uint32_t aKeySequence)
{
mKeySource = Encoding::BigEndian::HostSwap32(aKeySequence);
mKeyIndex = (aKeySequence & 0x7f) + 1;
}
/**
* This method returns the Frame Counter value.
*
* @returns The Frame Counter value.
*
*/
uint32_t GetFrameCounter(void) const { return Encoding::LittleEndian::HostSwap32(mFrameCounter); }
/**
* This method sets the Frame Counter value.
*
* @param[in] aFrameCounter The Frame Counter value.
*
*/
void SetFrameCounter(uint32_t aFrameCounter) { mFrameCounter = Encoding::LittleEndian::HostSwap32(aFrameCounter); }
/**
* MLE Command Types.
*
*/
enum Command
{
kCommandLinkRequest = 0, ///< Link Reject
kCommandLinkAccept = 1, ///< Link Accept
kCommandLinkAcceptAndRequest = 2, ///< Link Accept and Reject
kCommandLinkReject = 3, ///< Link Reject
kCommandAdvertisement = 4, ///< Advertisement
kCommandUpdate = 5, ///< Update
kCommandUpdateRequest = 6, ///< Update Request
kCommandDataRequest = 7, ///< Data Request
kCommandDataResponse = 8, ///< Data Response
kCommandParentRequest = 9, ///< Parent Request
kCommandParentResponse = 10, ///< Parent Response
kCommandChildIdRequest = 11, ///< Child ID Request
kCommandChildIdResponse = 12, ///< Child ID Response
kCommandChildUpdateRequest = 13, ///< Child Update Request
kCommandChildUpdateResponse = 14, ///< Child Update Response
kCommandAnnounce = 15, ///< Announce
kCommandDiscoveryRequest = 16, ///< Discovery Request
kCommandDiscoveryResponse = 17, ///< Discovery Response
/**
* Applicable/Required only when time synchronization service
* (`OPENTHREAD_CONFIG_ENABLE_TIME_SYNC`) is enabled.
*
*/
kCommandTimeSync = 99, ///< Time Synchronization
};
/**
* This method returns the Command Type value.
*
* @returns The Command Type value.
*
*/
Command GetCommand(void) const
{
if (mSecuritySuite == kNoSecurity)
{
return static_cast<Command>(mSecurityControl);
}
else
{
return static_cast<Command>(mCommand);
}
}
/**
* This method sets the Command Type value.
*
* @param[in] aCommand The Command Type value.
*
*/
void SetCommand(Command aCommand)
{
if (mSecuritySuite == kNoSecurity)
{
mSecurityControl = static_cast<uint8_t>(aCommand);
}
else
{
mCommand = static_cast<uint8_t>(aCommand);
}
}
private:
uint8_t mSecuritySuite;
uint8_t mSecurityControl;
uint32_t mFrameCounter;
uint32_t mKeySource;
uint8_t mKeyIndex;
uint8_t mCommand;
} OT_TOOL_PACKED_END;
/**
* This class implements functionality required for delaying MLE responses.
*
*/
OT_TOOL_PACKED_BEGIN
class DelayedResponseHeader
{
public:
/**
* Default constructor for the object.
*
*/
DelayedResponseHeader(void) { memset(this, 0, sizeof(*this)); };
/**
* This constructor initializes the object with specific values.
*
* @param[in] aSendTime Time when the message shall be sent.
* @param[in] aDestination IPv6 address of the message destination.
*
*/
DelayedResponseHeader(uint32_t aSendTime, const Ip6::Address &aDestination)
{
mSendTime = aSendTime;
mDestination = aDestination;
};
/**
* This method appends delayed response header to the message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the bytes.
* @retval OT_ERROR_NO_BUFS Insufficient available buffers to grow the message.
*
*/
otError AppendTo(Message &aMessage) { return aMessage.Append(this, sizeof(*this)); };
/**
* This method reads delayed response header from the message.
*
* @param[in] aMessage A reference to the message.
*
* @returns The number of bytes read.
*
*/
uint16_t ReadFrom(Message &aMessage)
{
return aMessage.Read(aMessage.GetLength() - sizeof(*this), sizeof(*this), this);
};
/**
* This method removes delayed response header from the message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully removed the header.
*
*/
static otError RemoveFrom(Message &aMessage)
{
return aMessage.SetLength(aMessage.GetLength() - sizeof(DelayedResponseHeader));
};
/**
* This method returns a time when the message shall be sent.
*
* @returns A time when the message shall be sent.
*
*/
uint32_t GetSendTime(void) const { return mSendTime; };
/**
* This method returns a destination of the delayed message.
*
* @returns A destination of the delayed message.
*
*/
const Ip6::Address &GetDestination(void) const { return mDestination; };
/**
* This method checks if the message shall be sent before the given time.
*
* @param[in] aTime A time to compare.
*
* @retval TRUE If the message shall be sent before the given time.
* @retval FALSE Otherwise.
*/
bool IsEarlier(uint32_t aTime) { return (static_cast<int32_t>(aTime - mSendTime) > 0); };
/**
* This method checks if the message shall be sent after the given time.
*
* @param[in] aTime A time to compare.
*
* @retval TRUE If the message shall be sent after the given time.
* @retval FALSE Otherwise.
*/
bool IsLater(uint32_t aTime) { return (static_cast<int32_t>(aTime - mSendTime) < 0); };
private:
Ip6::Address mDestination; ///< IPv6 address of the message destination.
uint32_t mSendTime; ///< Time when the message shall be sent.
} OT_TOOL_PACKED_END;
/**
* This class implements MLE functionality required by the Thread EndDevices, Router, and Leader roles.
*
*/
class Mle : public InstanceLocator
{
public:
/**
* This constructor initializes the MLE object.
*
* @param[in] aInstance A reference to the OpenThread instance.
*
*/
explicit Mle(Instance &aInstance);
/**
* This method enables MLE.
*
* @retval OT_ERROR_NONE Successfully enabled MLE.
* @retval OT_ERROR_ALREADY MLE was already enabled.
*
*/
otError Enable(void);
/**
* This method disables MLE.
*
* @retval OT_ERROR_NONE Successfully disabled MLE.
*
*/
otError Disable(void);
/**
* This method starts the MLE protocol operation.
*
* @param[in] aAnnounceAttach True if attach on the announced thread network with newer active timestamp,
* or False if not.
*
* @retval OT_ERROR_NONE Successfully started the protocol operation.
* @retval OT_ERROR_ALREADY The protocol operation was already started.
*
*/
otError Start(bool aAnnounceAttach);
/**
* This method stops the MLE protocol operation.
*
* @param[in] aClearNetworkDatasets True to clear network datasets, False not.
*
*/
void Stop(bool aClearNetworkDatasets);
/**
* This method restores network information from non-volatile memory.
*
* @retval OT_ERROR_NONE Successfully restore the network information.
* @retval OT_ERROR_NOT_FOUND There is no valid network information stored in non-volatile memory.
*
*/
otError Restore(void);
/**
* This method stores network information into non-volatile memory.
*
* @retval OT_ERROR_NONE Successfully store the network information.
* @retval OT_ERROR_NO_BUFS Could not store the network information due to insufficient memory space.
*
*/
otError Store(void);
/**
* This function pointer is called on receiving an MLE Discovery Response message.
*
* @param[in] aResult A valid pointer to the Discovery Response information or NULL when the Discovery completes.
* @param[in] aContext A pointer to application-specific context.
*
*/
typedef void (*DiscoverHandler)(otActiveScanResult *aResult, void *aContext);
/**
* This method initiates a Thread Discovery.
*
* @param[in] aScanChannels A bit vector indicating which channels to scan.
* @param[in] aPanId The PAN ID filter (set to Broadcast PAN to disable filter).
* @param[in] aJoiner Value of the Joiner Flag in the Discovery Request TLV.
* @param[in] aEnableFiltering Enable filtering out MLE discovery responses that don't match our factory
* assigned EUI64.
* @param[in] aHandler A pointer to a function that is called on receiving an MLE Discovery Response.
* @param[in] aContext A pointer to arbitrary context information.
*
* @retval OT_ERROR_NONE Successfully started a Thread Discovery.
* @retval OT_ERROR_BUSY Thread Discovery is already in progress.
*
*/
otError Discover(const Mac::ChannelMask &aScanChannels,
uint16_t aPanId,
bool aJoiner,
bool aEnableFiltering,
DiscoverHandler aCallback,
void * aContext);
/**
* This method indicates whether or not an MLE Thread Discovery is currently in progress.
*
* @returns true if an MLE Thread Discovery is in progress, false otherwise.
*
*/
bool IsDiscoverInProgress(void) const { return mDiscoverInProgress; }
/**
* This method is called by the MeshForwarder to indicate that discovery is complete.
*
*/
void HandleDiscoverComplete(void);
/**
* This method generates an MLE Announce message.
*
* @param[in] aChannel The channel to use when transmitting.
* @param[in] aOrphanAnnounce To indicate if MLE Announce is sent from an orphan end device.
*
* @retval OT_ERROR_NONE Successfully generated an MLE Announce message.
* @retval OT_ERROR_NO_BUFS Insufficient buffers to generate the MLE Announce message.
*
*/
otError SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce);
/**
* This method causes the Thread interface to detach from the Thread network.
*
* @retval OT_ERROR_NONE Successfully detached from the Thread network.
* @retval OT_ERROR_INVALID_STATE MLE is Disabled.
*
*/
otError BecomeDetached(void);
/**
* This method causes the Thread interface to attempt an MLE attach.
*
* @param[in] aMode Indicates what partitions to attach to.
*
* @retval OT_ERROR_NONE Successfully began the attach process.
* @retval OT_ERROR_INVALID_STATE MLE is Disabled.
* @retval OT_ERROR_BUSY An attach process is in progress.
*
*/
otError BecomeChild(AttachMode aMode);
/**
* This method indicates whether or not the Thread device is attached to a Thread network.
*
* @retval TRUE Attached to a Thread network.
* @retval FALSE Not attached to a Thread network.
*
*/
bool IsAttached(void) const;
/**
* This method returns the current Thread interface state.
*
* @returns The current Thread interface state.
*
*/
otDeviceRole GetRole(void) const { return mRole; }
/**
* This method returns the Device Mode as reported in the Mode TLV.
*
* @returns The Device Mode as reported in the Mode TLV.
*
*/
uint8_t GetDeviceMode(void) const { return mDeviceMode; }
/**
* This method sets the Device Mode as reported in the Mode TLV.
*
* @param[in] aDeviceMode The device mode to set.
*
* @retval OT_ERROR_NONE Successfully set the Mode TLV.
* @retval OT_ERROR_INVALID_ARGS The mode combination specified in @p aMode is invalid.
*
*/
otError SetDeviceMode(uint8_t aDeviceMode);
/**
* This method indicates whether or not the device is rx-on-when-idle.
*
* @returns TRUE if rx-on-when-idle, FALSE otherwise.
*
*/
bool IsRxOnWhenIdle(void) const { return (mDeviceMode & ModeTlv::kModeRxOnWhenIdle) != 0; }
/**
* This method indicates whether or not the device is a Full Thread Device.
*
* @returns TRUE if a Full Thread Device, FALSE otherwise.
*
*/
bool IsFullThreadDevice(void) const { return (mDeviceMode & ModeTlv::kModeFullThreadDevice) != 0; }
/**
* This method indicates whether or not the device uses secure IEEE 802.15.4 Data Request messages.
*
* @returns TRUE if using secure IEEE 802.15.4 Data Request messages, FALSE otherwise.
*
*/
bool IsSecureDataRequest(void) const { return (mDeviceMode & ModeTlv::kModeSecureDataRequest) != 0; }
/**
* This method indicates whether or not the device requests Full Network Data.
*
* @returns TRUE if requests Full Network Data, FALSE otherwise.
*
*/
bool IsFullNetworkData(void) const { return (mDeviceMode & ModeTlv::kModeFullNetworkData) != 0; }
/**
* This method indicates whether or not the device is a Minimal End Device.
*
* @returns TRUE if the device is a Minimal End Device, FALSE otherwise.
*
*/
bool IsMinimalEndDevice(void) const
{
return (mDeviceMode & (ModeTlv::kModeFullThreadDevice | ModeTlv::kModeRxOnWhenIdle)) !=
(ModeTlv::kModeFullThreadDevice | ModeTlv::kModeRxOnWhenIdle);
}
/**
* This method returns a pointer to the Mesh Local Prefix.
*
* @returns A reference to the Mesh Local Prefix.
*
*/
const otMeshLocalPrefix &GetMeshLocalPrefix(void) const
{
return reinterpret_cast<const otMeshLocalPrefix &>(mMeshLocal16.GetAddress());
}
/**
* This method sets the Mesh Local Prefix.
*
* @param[in] aMeshLocalPrefix A reference to the Mesh Local Prefix.
*
*/
void SetMeshLocalPrefix(const otMeshLocalPrefix &aMeshLocalPrefix);
/**
* This method applies the Mesh Local Prefix.
*
* @param[in] aPrefix A reference to the Mesh Local Prefix.
*
*/
void ApplyMeshLocalPrefix(void);
/**
* This method returns a reference to the Thread link-local address.
*
* The Thread link local address is derived using IEEE802.15.4 Extended Address as Interface Identifier.
*
* @returns A reference to the Thread link local address.
*
*/
const Ip6::Address &GetLinkLocalAddress(void) const { return mLinkLocal64.GetAddress(); }
/**
* This method updates the link local address.
*
* Call this method when the IEEE 802.15.4 Extended Address has changed.
*
*/
void UpdateLinkLocalAddress(void);
/**
* This method returns a reference to the link-local all Thread nodes multicast address.
*
* @returns A reference to the link-local all Thread nodes multicast address.
*
*/
const Ip6::Address &GetLinkLocalAllThreadNodesAddress(void) const { return mLinkLocalAllThreadNodes.GetAddress(); }
/**
* This method returns a reference to the realm-local all Thread nodes multicast address.
*
* @returns A reference to the realm-local all Thread nodes multicast address.
*
*/
const Ip6::Address &GetRealmLocalAllThreadNodesAddress(void) const
{
return mRealmLocalAllThreadNodes.GetAddress();
}
/**
* This method returns a pointer to the parent when operating in End Device mode.
*
* @returns A pointer to the parent.
*
*/
Router *GetParent(void);
/**
* This method returns a pointer to the parent candidate or parent.
*
* This method is useful when sending IEEE 802.15.4 Data Request frames while attempting to attach to a new parent.
*
* If attempting to attach to a new parent, this method returns the parent candidate.
* If not attempting to attach, this method returns the parent.
*
*/
Router *GetParentCandidate(void);
/**
* This method indicates whether or not an IPv6 address is an RLOC.
*
* @retval TRUE If @p aAddress is an RLOC.
* @retval FALSE If @p aAddress is not an RLOC.
*
*/
bool IsRoutingLocator(const Ip6::Address &aAddress) const;
/**
* This method indicates whether or not an IPv6 address is an ALOC.
*
* @retval TRUE If @p aAddress is an ALOC.
* @retval FALSE If @p aAddress is not an ALOC.
*
*/
bool IsAnycastLocator(const Ip6::Address &aAddress) const;
/**
* This method indicates whether or not an IPv6 address is a Mesh Local Address.
*
* @retval TRUE If @p aAddress is a Mesh Local Address.
* @retval FALSE If @p aAddress is not a Mesh Local Address.
*
*/
bool IsMeshLocalAddress(const Ip6::Address &aAddress) const;
/**
* This method returns the MLE Timeout value.
*
* @returns The MLE Timeout value in seconds.
*
*/
uint32_t GetTimeout(void) const { return mTimeout; }
/**
* This method sets the MLE Timeout value.
*
* @param[in] aTimeout The Timeout value in seconds.
*
*/
void SetTimeout(uint32_t aTimeout);
/**
* This method returns the RLOC16 assigned to the Thread interface.
*
* @returns The RLOC16 assigned to the Thread interface.
*
*/
uint16_t GetRloc16(void) const;
/**
* This method returns a reference to the RLOC assigned to the Thread interface.
*
* @returns A reference to the RLOC assigned to the Thread interface.
*
*/
const Ip6::Address &GetMeshLocal16(void) const { return mMeshLocal16.GetAddress(); }
/**
* This method returns a reference to the ML-EID assigned to the Thread interface.
*
* @returns A reference to the ML-EID assigned to the Thread interface.
*
*/
const Ip6::Address &GetMeshLocal64(void) const { return mMeshLocal64.GetAddress(); }
/**
* This method returns the Router ID of the Leader.
*
* @returns The Router ID of the Leader.
*
*/
uint8_t GetLeaderId(void) const { return mLeaderData.GetLeaderRouterId(); }
/**
* This method retrieves the Leader's RLOC.
*
* @param[out] aAddress A reference to the Leader's RLOC.
*
* @retval OT_ERROR_NONE Successfully retrieved the Leader's RLOC.
* @retval OT_ERROR_DETACHED The Thread interface is not currently attached to a Thread Partition.
*
*/
otError GetLeaderAddress(Ip6::Address &aAddress) const;
/**
* This method retrieves the Leader's ALOC.
*
* @param[out] aAddress A reference to the Leader's ALOC.
*
* @retval OT_ERROR_NONE Successfully retrieved the Leader's ALOC.
* @retval OT_ERROR_DETACHED The Thread interface is not currently attached to a Thread Partition.
*
*/
otError GetLeaderAloc(Ip6::Address &aAddress) const { return GetAlocAddress(aAddress, kAloc16Leader); }
/**
* This method computes the Commissioner's ALOC.
*
* @param[out] aAddress A reference to the Commissioner's ALOC.
* @param[in] aSessionId Commissioner session id.
*
* @retval OT_ERROR_NONE Successfully retrieved the Commissioner's ALOC.
* @retval OT_ERROR_DETACHED The Thread interface is not currently attached to a Thread Partition.
*
*/
otError GetCommissionerAloc(Ip6::Address &aAddress, uint16_t aSessionId) const
{
return GetAlocAddress(aAddress, GetCommissionerAloc16FromId(aSessionId));
}
#if OPENTHREAD_ENABLE_SERVICE
/**
* This method retrieves the Service ALOC for given Service ID.
*
* @param[in] aServiceID Service ID to get ALOC for.
* @param[out] aAddress A reference to the Service ALOC.
*
* @retval OT_ERROR_NONE Successfully retrieved the Service ALOC.
* @retval OT_ERROR_DETACHED The Thread interface is not currently attached to a Thread Partition.
*
*/
otError GetServiceAloc(uint8_t aServiceId, Ip6::Address &aAddress) const;
#endif
/**
* This method adds Leader's ALOC to its Thread interface.
*
* @retval OT_ERROR_NONE Successfully added the Leader's ALOC.
* @retval OT_ERROR_BUSY The Leader's ALOC address was already added.
* @retval OT_ERROR_INVALID_STATE The device's role is not Leader.
*
*/
otError AddLeaderAloc(void);
/**
* This method returns the most recently received Leader Data TLV.
*
* @returns A reference to the most recently received Leader Data TLV.
*
*/
const LeaderDataTlv &GetLeaderDataTlv(void);
/**
* This method gets the Leader Data.
*
* @param[out] aLeaderData A reference to where the leader data is placed.
*
* @retval OT_ERROR_NONE Successfully retrieved the leader data.
* @retval OT_ERROR_DETACHED Not currently attached.
*
*/
otError GetLeaderData(otLeaderData &aLeaderData);
/**
* This method returns the Child ID portion of an RLOC16.
*
* @param[in] aRloc16 The RLOC16 value.
*
* @returns The Child ID portion of an RLOC16.
*
*/
static uint16_t GetChildId(uint16_t aRloc16) { return aRloc16 & kMaxChildId; }
/**
* This method returns the Router ID portion of an RLOC16.
*
* @param[in] aRloc16 The RLOC16 value.
*
* @returns The Router ID portion of an RLOC16.
*
*/
static uint8_t GetRouterId(uint16_t aRloc16) { return aRloc16 >> kRouterIdOffset; }
/**
* This method returns whether the two RLOC16 have the same Router ID.
*
* @param[in] aRloc16A The first RLOC16 value.
* @param[in] aRloc16B The second RLOC16 value.
*
* @returns true if the two RLOC16 have the same Router ID, false otherwise.
*
*/
static bool RouterIdMatch(uint16_t aRloc16A, uint16_t aRloc16B)
{
return ((aRloc16A >> kRouterIdOffset) == (aRloc16B >> kRouterIdOffset));
}
/**
* This method returns the Service ID corresponding to a Service ALOC16.
*
* @param[in] aAloc16 The Servicer ALOC16 value.
*
* @returns The Service ID corresponding to given ALOC16.
*
*/
static uint8_t GetServiceIdFromAloc(uint16_t aAloc16)
{
return static_cast<uint8_t>(aAloc16 - kAloc16ServiceStart);
}
/**
* This method returns the Service Aloc corresponding to a Service ID.
*
* @param[in] aServiceId The Service ID value.
*
* @returns The Service ALOC16 corresponding to given ID.
*
*/
static uint16_t GetServiceAlocFromId(uint8_t aServiceId)
{
return static_cast<uint16_t>(aServiceId + kAloc16ServiceStart);
}
/**
* This method returns the Commissioner Aloc corresponding to a Commissioner Session ID.
*
* @param[in] aSessionId The Commissioner Session ID value.
*
* @returns The Commissioner ALOC16 corresponding to given ID.
*
*/
static uint16_t GetCommissionerAloc16FromId(uint16_t aSessionId)
{
return static_cast<uint16_t>((aSessionId & kAloc16CommissionerMask) + kAloc16CommissionerStart);
}
/**
* This method returns the RLOC16 of a given Router ID.
*
* @param[in] aRouterId The Router ID value.
*
* @returns The RLOC16 of the given Router ID.
*
*/
static uint16_t GetRloc16(uint8_t aRouterId) { return static_cast<uint16_t>(aRouterId << kRouterIdOffset); }
/**
* This method indicates whether or not @p aRloc16 refers to an active router.
*
* @param[in] aRloc16 The RLOC16 value.
*
* @retval TRUE If @p aRloc16 refers to an active router.
* @retval FALSE If @p aRloc16 does not refer to an active router.
*
*/
static bool IsActiveRouter(uint16_t aRloc16) { return GetChildId(aRloc16) == 0; }
/**
* This method fills the NetworkDataTlv.
*
* @param[out] aTlv The NetworkDataTlv.
* @param[in] aStableOnly TRUE to append stable data, FALSE otherwise.
*
*/
void FillNetworkDataTlv(NetworkDataTlv &aTlv, bool aStableOnly);
/**
* This method returns a reference to the send queue.
*
* @returns A reference to the send queue.
*
*/
const MessageQueue &GetMessageQueue(void) const { return mDelayedResponses; }
/**
* This method frees multicast MLE Data Response from Delayed Message Queue if any.
*
*/
void RemoveDelayedDataResponseMessage(void);
/**
* This method converts a device role into a human-readable string.
*
*/
static const char *RoleToString(otDeviceRole aRole);
/**
* This method gets the MLE counters.
*
* @returns A reference to the MLE counters.
*
*/
const otMleCounters &GetCounters(void) const { return mCounters; }
/**
* This method resets the MLE counters.
*
*/
void ResetCounters(void) { memset(&mCounters, 0, sizeof(mCounters)); }
/**
* This function registers the client callback that is called when processing an MLE Parent Response message.
*
* @param[in] aCallback A pointer to a function that is called to deliver MLE Parent Response data.
* @param[in] aContext A pointer to application-specific context.
*
*/
void RegisterParentResponseStatsCallback(otThreadParentResponseCallback aCallback, void *aContext);
protected:
/**
* States during attach (when searching for a parent).
*
*/
enum AttachState
{
kAttachStateIdle, ///< Not currently searching for a parent.
kAttachStateProcessAnnounce, ///< Waiting to process a received Announce (to switch channel/pan-id).
kAttachStateStart, ///< Starting to look for a parent.
kAttachStateParentRequestRouter, ///< Searching for a Router to attach to.
kAttachStateParentRequestReed, ///< Searching for Routers or REEDs to attach to.
kAttachStateAnnounce, ///< Send Announce messages
kAttachStateChildIdRequest, ///< Sending a Child ID Request message.
};
/**
* States when reattaching network using stored dataset
*
*/
enum ReattachState
{
kReattachStop = 0, ///< Reattach process is disabled or finished
kReattachStart = 1, ///< Start reattach process
kReattachActive = 2, ///< Reattach using stored Active Dataset
kReattachPending = 3, ///< Reattach using stored Pending Dataset
};
enum
{
kMleMaxResponseDelay = 1000u, ///< Maximum delay before responding to a multicast request.
};
/**
* This method allocates a new message buffer for preparing an MLE message.
*
* @returns A pointer to the message or NULL if insufficient message buffers are available.
*
*/
Message *NewMleMessage(void);
/**
* This method sets the device role.
*
* @param[in] aRole A device role.
*
*/
void SetRole(otDeviceRole aRole);
/**
* This method sets the attach state
*
* @param[in] aState An attach state
*
*/
void SetAttachState(AttachState aState);
/**
* This method appends an MLE header to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aCommand The MLE Command Type.
*
* @retval OT_ERROR_NONE Successfully appended the header.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the header.
*
*/
otError AppendHeader(Message &aMessage, Header::Command aCommand);
/**
* This method appends a Source Address TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Source Address TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Source Address TLV.
*
*/
otError AppendSourceAddress(Message &aMessage);
/**
* This method appends a Mode TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aMode The Device Mode value.
*
* @retval OT_ERROR_NONE Successfully appended the Mode TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Mode TLV.
*
*/
otError AppendMode(Message &aMessage, uint8_t aMode);
/**
* This method appends a Timeout TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aTimeout The Timeout value.
*
* @retval OT_ERROR_NONE Successfully appended the Timeout TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Timeout TLV.
*
*/
otError AppendTimeout(Message &aMessage, uint32_t aTimeout);
/**
* This method appends a Challenge TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aChallenge A pointer to the Challenge value.
* @param[in] aChallengeLength The length of the Challenge value in bytes.
*
* @retval OT_ERROR_NONE Successfully appended the Challenge TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Challenge TLV.
*
*/
otError AppendChallenge(Message &aMessage, const uint8_t *aChallenge, uint8_t aChallengeLength);
/**
* This method appends a Response TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aResponse A pointer to the Response value.
* @param[in] aResponseLength The length of the Response value in bytes.
*
* @retval OT_ERROR_NONE Successfully appended the Response TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Response TLV.
*
*/
otError AppendResponse(Message &aMessage, const uint8_t *aResponse, uint8_t aResponseLength);
/**
* This method appends a Link Frame Counter TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Link Frame Counter TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Link Frame Counter TLV.
*
*/
otError AppendLinkFrameCounter(Message &aMessage);
/**
* This method appends an MLE Frame Counter TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Frame Counter TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the MLE Frame Counter TLV.
*
*/
otError AppendMleFrameCounter(Message &aMessage);
/**
* This method appends an Address16 TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aRloc16 The RLOC16 value.
*
* @retval OT_ERROR_NONE Successfully appended the Address16 TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Address16 TLV.
*
*/
otError AppendAddress16(Message &aMessage, uint16_t aRloc16);
/**
* This method appends a Network Data TLV to the message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aStableOnly TRUE to append stable data, FALSE otherwise.
*
* @retval OT_ERROR_NONE Successfully appended the Network Data TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Network Data TLV.
*
*/
otError AppendNetworkData(Message &aMessage, bool aStableOnly);
/**
* This method appends a TLV Request TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aTlvs A pointer to the list of TLV types.
* @param[in] aTlvsLength The number of TLV types in @p aTlvs
*
* @retval OT_ERROR_NONE Successfully appended the TLV Request TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the TLV Request TLV.
*
*/
otError AppendTlvRequest(Message &aMessage, const uint8_t *aTlvs, uint8_t aTlvsLength);
/**
* This method appends a Leader Data TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Leader Data TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Leader Data TLV.
*
*/
otError AppendLeaderData(Message &aMessage);
/**
* This method appends a Scan Mask TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aScanMask The Scan Mask value.
*
* @retval OT_ERROR_NONE Successfully appended the Scan Mask TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Scan Mask TLV.
*
*/
otError AppendScanMask(Message &aMessage, uint8_t aScanMask);
/**
* This method appends a Status TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aStatus The Status value.
*
* @retval OT_ERROR_NONE Successfully appended the Status TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Status TLV.
*
*/
otError AppendStatus(Message &aMessage, StatusTlv::Status aStatus);
/**
* This method appends a Link Margin TLV to a message.
*
* @param[in] aMessage A reference to the message.
* @param[in] aLinkMargin The Link Margin value.
*
* @retval OT_ERROR_NONE Successfully appended the Link Margin TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Link Margin TLV.
*
*/
otError AppendLinkMargin(Message &aMessage, uint8_t aLinkMargin);
/**
* This method appends a Version TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Version TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Version TLV.
*
*/
otError AppendVersion(Message &aMessage);
/**
* This method appends an Address Registration TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Address Registration TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Address Registration TLV.
*
*/
otError AppendAddressRegistration(Message &aMessage);
#if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC
/**
* This method appends a Time Request TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Time Request TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Time Request TLV.
*
*/
otError AppendTimeRequest(Message &aMessage);
/**
* This method appends a Time Parameter TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Time Parameter TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Time Parameter TLV.
*
*/
otError AppendTimeParameter(Message &aMessage);
/**
* This method appends a XTAL Accuracy TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the XTAL Accuracy TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the XTAl Accuracy TLV.
*
*/
otError AppendXtalAccuracy(Message &aMessage);
#endif // OPENTHREAD_CONFIG_ENABLE_TIME_SYNC
/**
* This method appends a Active Timestamp TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Active Timestamp TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Active Timestamp TLV.
*
*/
otError AppendActiveTimestamp(Message &aMessage);
/**
* This method appends a Pending Timestamp TLV to a message.
*
* @param[in] aMessage A reference to the message.
*
* @retval OT_ERROR_NONE Successfully appended the Pending Timestamp TLV.
* @retval OT_ERROR_NO_BUFS Insufficient buffers available to append the Pending Timestamp TLV.
*
*/
otError AppendPendingTimestamp(Message &aMessage);
/**
* This method checks if the destination is reachable.
*
* @param[in] aMeshSource The RLOC16 of the source.
* @param[in] aMeshDest The RLOC16 of the destination.
* @param[in] aIp6Header The IPv6 header of the message.
*
* @retval OT_ERROR_NONE The destination is reachable.
* @retval OT_ERROR_DROP The destination is not reachable and the message should be dropped.
*
*/
otError CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header);
/**
* This method returns a pointer to the neighbor object.
*
* @param[in] aAddress A reference to the MAC address.
*
* @returns A pointer to the neighbor object.
*
*/
Neighbor *GetNeighbor(const Mac::Address &aAddress);
/**
* This method returns a pointer to the neighbor object.
*
* @param[in] aAddress A reference to the MAC short address.
*
* @returns A pointer to the neighbor object.
*
*/
Neighbor *GetNeighbor(Mac::ShortAddress aAddress);
/**
* This method returns a pointer to the neighbor object.
*
* @param[in] aAddress A reference to the MAC extended address.
*
* @returns A pointer to the neighbor object.
*
*/
Neighbor *GetNeighbor(const Mac::ExtAddress &aAddress);
/**
* This method returns a pointer to the neighbor object.
*
* @param[in] aAddress A reference to the IPv6 address.
*
* @returns A pointer to the neighbor object.
*
*/
Neighbor *GetNeighbor(const Ip6::Address &aAddress)
{
OT_UNUSED_VARIABLE(aAddress);
return NULL;
}
/**
* This method returns the next hop towards an RLOC16 destination.
*
* @param[in] aDestination The RLOC16 of the destination.
*
* @returns A RLOC16 of the next hop if a route is known, kInvalidRloc16 otherwise.
*
*/
Mac::ShortAddress GetNextHop(uint16_t aDestination) const;
/**
* This method generates an MLE Data Request message.
*
* @param[in] aDestination A reference to the IPv6 address of the destination.
* @param[in] aTlvs A pointer to requested TLV types.
* @param[in] aTlvsLength The number of TLV types in @p aTlvs.
* @param[in] aDelay Delay in milliseconds before the Data Request message is sent.
*
* @retval OT_ERROR_NONE Successfully generated an MLE Data Request message.
* @retval OT_ERROR_NO_BUFS Insufficient buffers to generate the MLE Data Request message.
*
*/
otError SendDataRequest(const Ip6::Address &aDestination,
const uint8_t * aTlvs,
uint8_t aTlvsLength,
uint16_t aDelay);
/**
* This method generates an MLE Child Update Request message.
*
* @retval OT_ERROR_NONE Successfully generated an MLE Child Update Request message.
* @retval OT_ERROR_NO_BUFS Insufficient buffers to generate the MLE Child Update Request message.
*
*/
otError SendChildUpdateRequest(void);
/**
* This method generates an MLE Child Update Response message.
*
* @param[in] aTlvs A pointer to requested TLV types.
* @param[in] aNumTlvs The number of TLV types in @p aTlvs.
* @param[in] aChallenge The Challenge TLV for the response.
*
* @retval OT_ERROR_NONE Successfully generated an MLE Child Update Response message.
* @retval OT_ERROR_NO_BUFS Insufficient buffers to generate the MLE Child Update Response message.
*
*/
otError SendChildUpdateResponse(const uint8_t *aTlvs, uint8_t aNumTlvs, const ChallengeTlv &aChallenge);
/**
* This method submits an MLE message to the UDP socket.
*
* @param[in] aMessage A reference to the message.
* @param[in] aDestination A reference to the IPv6 address of the destination.
*
* @retval OT_ERROR_NONE Successfully submitted the MLE message.
* @retval OT_ERROR_NO_BUFS Insufficient buffers to form the rest of the MLE message.
*
*/
otError SendMessage(Message &aMessage, const Ip6::Address &aDestination);
/**
* This method sets the RLOC16 assigned to the Thread interface.
*
* @param[in] aRloc16 The RLOC16 to set.
*
*/
void SetRloc16(uint16_t aRloc16);
/**
* This method sets the Device State to Detached.
*
*/
void SetStateDetached(void);
/**
* This method sets the Device State to Child.
*
*/
void SetStateChild(uint16_t aRloc16);
/**
* This method sets the Leader's Partition ID, Weighting, and Router ID values.
*
* @param[in] aPartitionId The Leader's Partition ID value.
* @param[in] aWeighting The Leader's Weighting value.
* @param[in] aLeaderRouterId The Leader's Router ID value.
*
*/
void SetLeaderData(uint32_t aPartitionId, uint8_t aWeighting, uint8_t aLeaderRouterId);
/**
* This method adds a message to the message queue. The queued message will be transmitted after given delay.
*
* @param[in] aMessage The message to transmit after given delay.
* @param[in] aDestination The IPv6 address of the recipient of the message.
* @param[in] aDelay The delay in milliseconds before transmission of the message.
*
* @retval OT_ERROR_NONE Successfully queued the message to transmit after the delay.
* @retval OT_ERROR_NO_BUFS Insufficient buffers to queue the message.
*
*/
otError AddDelayedResponse(Message &aMessage, const Ip6::Address &aDestination, uint16_t aDelay);
/**
* This method prints an MLE log message with an IPv6 address.
*
* @param[in] aLogString The log message string.
* @param[in] aAddress The IPv6 address of the peer.
*
*/
void LogMleMessage(const char *aLogString, const Ip6::Address &aAddress) const;
/**
* This method prints an MLE log message with an IPv6 address and RLOC16.
*
* @param[in] aLogString The log message string.
* @param[in] aAddress The IPv6 address of the peer.
* @param[in] aRloc The RLOC16.
*
*/
void LogMleMessage(const char *aLogString, const Ip6::Address &aAddress, uint16_t aRloc) const;
/**
* This method triggers MLE Announce on previous channel after the Thread device successfully
* attaches and receives the new Active Commissioning Dataset if needed.
*
* MTD would send Announce immediately after attached.
* FTD would delay to send Announce after tried to become Router or decided to stay in REED role.
*
*/
void InformPreviousChannel(void);
/**
* This method indicates whether or not in announce attach process.
*
* @retval true if attaching/attached on the announced parameters, false otherwise.
*
*/
bool IsAnnounceAttach(void) const { return mAlternatePanId != Mac::kPanIdBroadcast; }
#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MLE == 1)
/**
* This method converts an `AttachMode` enumeration value into a human-readable string.
*
* @param[in] aMode An attach mode
*
* @returns A human-readable string corresponding to the attach mode.
*
*/
static const char *AttachModeToString(AttachMode aMode);
/**
* This method converts an `AttachState` enumeration value into a human-readable string.
*
* @param[in] aState An attach state
*
* @returns A human-readable string corresponding to the attach state.
*
*/
static const char *AttachStateToString(AttachState aState);
/**
* This method converts a `ReattachState` enumeration value into a human-readable string.
*
* @param[in] aState A reattach state
*
* @returns A human-readable string corresponding to the reattach state.
*
*/
static const char *ReattachStateToString(ReattachState aState);
#endif
LeaderDataTlv mLeaderData; ///< Last received Leader Data TLV.
bool mRetrieveNewNetworkData; ///< Indicating new Network Data is needed if set.
otDeviceRole mRole; ///< Current Thread role.
Router mParent; ///< Parent information.
uint8_t mDeviceMode; ///< Device mode setting.
AttachState mAttachState; ///< The parent request state.
ReattachState mReattachState; ///< Reattach state
uint16_t mAttachCounter; ///< Attach attempt counter.
uint16_t mAnnounceDelay; ///< Delay in between sending Announce messages during attach.
TimerMilli mAttachTimer; ///< The timer for driving the attach process.
TimerMilli mDelayedResponseTimer; ///< The timer to delay MLE responses.
TimerMilli mMessageTransmissionTimer; ///< The timer for (re-)sending of MLE messages (e.g. Child Update).
uint32_t mLastPartitionId; ///< The partition ID of the previous Thread partition
uint8_t mLastPartitionRouterIdSequence; ///< The router ID sequence from the previous Thread partition
uint8_t mLastPartitionIdTimeout; ///< The time remaining to avoid the previous Thread partition
uint8_t mParentLeaderCost;
private:
enum
{
kMleMessagePriority = Message::kPriorityNet,
kMleHopLimit = 255,
// Parameters related to "periodic parent search" feature (CONFIG_ENABLE_PERIODIC_PARENT_SEARCH).
// All timer intervals are converted to milliseconds.
kParentSearchCheckInterval = (OPENTHREAD_CONFIG_PARENT_SEARCH_CHECK_INTERVAL * 1000u),
kParentSearchBackoffInterval = (OPENTHREAD_CONFIG_PARENT_SEARCH_BACKOFF_INTERVAL * 1000u),
kParentSearchJitterInterval = (15 * 1000u),
kParentSearchRssThreadhold = OPENTHREAD_CONFIG_PARENT_SEARCH_RSS_THRESHOLD,
// Parameters for "attach backoff" feature (CONFIG_ENABLE_ATTACH_BACKOFF) - Intervals are in milliseconds.
kAttachBackoffMinInterval = OPENTHREAD_CONFIG_ATTACH_BACKOFF_MINIMUM_INTERVAL,
kAttachBackoffMaxInterval = OPENTHREAD_CONFIG_ATTACH_BACKOFF_MAXIMUM_INTERVAL,
kAttachBackoffJitter = OPENTHREAD_CONFIG_ATTACH_BACKOFF_JITTER_INTERVAL,
};
enum ParentRequestType
{
kParentRequestTypeRouters, ///< Parent Request to all routers.
kParentRequestTypeRoutersAndReeds, ///< Parent Request to all routers and REEDs.
};
enum ChildUpdateRequestState
{
kChildUpdateRequestNone, ///< No pending or active Child Update Request.
kChildUpdateRequestPending, ///< Pending Child Update Request due to relative OT_CHANGED event.
kChildUpdateRequestActive, ///< Child Update Request has been sent and Child Update Response is expected.
};
enum DataRequestState
{
kDataRequestNone, ///< Not waiting for a Data Response.
kDataRequestActive, ///< Data Request has been sent, Data Response is expected.
};
void GenerateNonce(const Mac::ExtAddress &aMacAddr,
uint32_t aFrameCounter,
uint8_t aSecurityLevel,
uint8_t * aNonce);
static void HandleStateChanged(Notifier::Callback &aCallback, otChangedFlags aFlags);
void HandleStateChanged(otChangedFlags aFlags);
static void HandleAttachTimer(Timer &aTimer);
void HandleAttachTimer(void);
static void HandleDelayedResponseTimer(Timer &aTimer);
void HandleDelayedResponseTimer(void);
static void HandleMessageTransmissionTimer(Timer &aTimer);
void HandleMessageTransmissionTimer(void);
static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo);
void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
void ScheduleMessageTransmissionTimer(void);
otError HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
otError HandleChildIdResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
otError HandleChildUpdateRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
otError HandleChildUpdateResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
otError HandleDataResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
otError HandleParentResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence);
otError HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
otError HandleDiscoveryResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
otError HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo);
void ProcessAnnounce(void);
uint32_t GetAttachStartDelay(void) const;
otError SendParentRequest(ParentRequestType aType);
otError SendChildIdRequest(void);
otError SendOrphanAnnounce(void);
bool PrepareAnnounceState(void);
otError SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce, const Ip6::Address &aDestination);
uint32_t Reattach(void);
bool IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, uint8_t aLinkMargin, ConnectivityTlv &aConnectivityTlv);
void ResetParentCandidate(void);
otError GetAlocAddress(Ip6::Address &aAddress, uint16_t aAloc16) const;
#if OPENTHREAD_ENABLE_SERVICE
/**
* This method scans for network data from the leader and updates IP addresses assigned to this
* interface to make sure that all Service ALOCs (0xfc10-0xfc1f) are properly set.
*/
void UpdateServiceAlocs(void);
#endif
#if OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH
otError InformPreviousParent(void);
#endif
#if OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH
static void HandleParentSearchTimer(Timer &aTimer);
void HandleParentSearchTimer(void);
void StartParentSearchTimer(void);
void UpdateParentSearchState(void);
#endif
MessageQueue mDelayedResponses;
struct
{
uint8_t mChallenge[ChallengeTlv::kMaxSize];
uint8_t mChallengeLength;
} mChildIdRequest;
struct
{
uint8_t mChallenge[ChallengeTlv::kMaxSize];
} mParentRequest;
AttachMode mParentRequestMode;
int8_t mParentPriority;
uint8_t mParentLinkQuality3;
uint8_t mParentLinkQuality2;
uint8_t mParentLinkQuality1;
uint8_t mChildUpdateAttempts;
ChildUpdateRequestState mChildUpdateRequestState;
uint8_t mDataRequestAttempts;
DataRequestState mDataRequestState;
uint8_t mParentLinkMargin;
bool mParentIsSingleton;
bool mReceivedResponseFromParent;
LeaderDataTlv mParentLeaderData;
Router mParentCandidate;
Ip6::UdpSocket mSocket;
uint32_t mTimeout;
DiscoverHandler mDiscoverHandler;
void * mDiscoverContext;
uint16_t mDiscoverCcittIndex;
uint16_t mDiscoverAnsiIndex;
bool mDiscoverInProgress;
bool mDiscoverEnableFiltering;
#if OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH
uint16_t mPreviousParentRloc;
#endif
#if OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH
bool mParentSearchIsInBackoff : 1;
bool mParentSearchBackoffWasCanceled : 1;
bool mParentSearchRecentlyDetached : 1;
uint32_t mParentSearchBackoffCancelTime;
TimerMilli mParentSearchTimer;
#endif
uint8_t mAnnounceChannel;
uint8_t mAlternateChannel;
uint16_t mAlternatePanId;
uint64_t mAlternateTimestamp;
Ip6::NetifUnicastAddress mLeaderAloc;
#if OPENTHREAD_ENABLE_SERVICE
Ip6::NetifUnicastAddress mServiceAlocs[OPENTHREAD_CONFIG_MAX_SERVICE_ALOCS];
#endif
otMleCounters mCounters;
Ip6::NetifUnicastAddress mLinkLocal64;
Ip6::NetifUnicastAddress mMeshLocal64;
Ip6::NetifUnicastAddress mMeshLocal16;
Ip6::NetifMulticastAddress mLinkLocalAllThreadNodes;
Ip6::NetifMulticastAddress mRealmLocalAllThreadNodes;
Notifier::Callback mNotifierCallback;
otThreadParentResponseCallback mParentResponseCb;
void * mParentResponseCbContext;
};
} // namespace Mle
/**
* @}
*
*/
} // namespace ot
#endif // MLE_HPP_
| 33.996158 | 120 | 0.650377 | [
"mesh",
"object",
"vector"
] |
4b367f42e5aab653d21157548d579eadcf2379ed | 2,236 | hpp | C++ | bin/pval_mrc/settings.hpp | jewettaij/visfd | 0c4fcdf9215b76e9cc9f3d2d9def5e50ebe86a93 | [
"MIT"
] | 7 | 2019-06-26T04:32:53.000Z | 2022-03-30T07:12:40.000Z | bin/pval_mrc/settings.hpp | jewettaij/visfd | 0c4fcdf9215b76e9cc9f3d2d9def5e50ebe86a93 | [
"MIT"
] | 14 | 2019-03-02T00:41:53.000Z | 2022-03-18T04:20:12.000Z | bin/pval_mrc/settings.hpp | jewettaij/visfd | 0c4fcdf9215b76e9cc9f3d2d9def5e50ebe86a93 | [
"MIT"
] | 1 | 2022-02-16T13:50:42.000Z | 2022-02-16T13:50:42.000Z | #ifndef _SETTINGS_HPP
#define _SETTINGS_HPP
#define DISABLE_BOOTSTRAPPING
//#define DISABLE_TEMPLATE_MATCHING
#include<vector>
#include<string>
using namespace std;
class Settings {
public:
string in_file_name;
int image_size[3];
string out_file_name;
string in_coords_file_name;
bool rescale01_in;
string mask_file_name;
int mask_select;
bool use_mask_select;
bool randomize_input_image;
long random_seed = -1;
float voxel_width = 0.0; //How many Angstroms per voxel? (if 0 then read from file)
bool voxel_width_divide_by_10 = false; //Use nm instead of Angstroms?
//float sigma; //width of Gaussian blur to apply to image
vector<float> vfSigma; //a list of widths to use for Gaussian blurring
float filter_truncate_threshold; //Filter intensity decay value before giving up
//When the filter strength is less than this value
//we ignore it. For difference-of-gaussian filters
//we choose the gaussian with the wider width. This
//parameter overrides other window-width settings.
//(Setting it to a number < 0 disables it.)
float filter_truncate_ratio; //When averaging/filtering consider nearby
//voxels up to a distance of this many sigma away
//(Setting this to a number < 0 disables it.)
bool precomputed_gaussian_blur; //did the user already use a Gaussian blur?
// Did the user already precompute the volume and number of particles?
float compartment_volume; //the volume of the cell (if known in advance)
float num_particles; //number of particles in this volume (if known)
bool use_min_density; //Are we interested in density minima or maxima?
bool extrema_on_boundary = false; //Consider density minima on image boundaries?
Settings();
void ParseArgs(int argc, char **argv);
private:
void ParseArgs(vector<string>& vArgs);
void ConvertArgvToVectorOfStrings(int argc,
char **argv,
vector<string>& dest);
}; //class Settings
#endif //#ifndef _SETTINGS_HPP
| 34.4 | 86 | 0.65966 | [
"vector"
] |
4b39bdd681feb393519c233f59d26031b795ef7c | 31,343 | cpp | C++ | src/widgets/dialogs/UserInfoPopup.cpp | swills/chatterino2 | a79081f4413e65f8437e937bdcc199a5b73f267d | [
"MIT"
] | 2 | 2018-12-26T15:41:08.000Z | 2021-04-30T11:41:39.000Z | src/widgets/dialogs/UserInfoPopup.cpp | RAnders00/chatterino2 | 8b2c3c7386bc65c770f8678dbb24234b5338f42a | [
"MIT"
] | 22 | 2020-11-17T16:22:49.000Z | 2022-03-31T10:05:34.000Z | src/widgets/dialogs/UserInfoPopup.cpp | RAnders00/chatterino2 | 8b2c3c7386bc65c770f8678dbb24234b5338f42a | [
"MIT"
] | null | null | null | #include "UserInfoPopup.hpp"
#include "Application.hpp"
#include "common/Channel.hpp"
#include "common/NetworkRequest.hpp"
#include "controllers/accounts/AccountController.hpp"
#include "controllers/highlights/HighlightBlacklistUser.hpp"
#include "messages/Message.hpp"
#include "providers/IvrApi.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include "providers/twitch/api/Helix.hpp"
#include "providers/twitch/api/Kraken.hpp"
#include "singletons/Resources.hpp"
#include "singletons/Settings.hpp"
#include "util/LayoutCreator.hpp"
#include "util/PostToThread.hpp"
#include "util/Shortcut.hpp"
#include "util/StreamerMode.hpp"
#include "widgets/Label.hpp"
#include "widgets/helper/ChannelView.hpp"
#include "widgets/helper/EffectLabel.hpp"
#include "widgets/helper/Line.hpp"
#include <QCheckBox>
#include <QDesktopServices>
#include <QNetworkAccessManager>
#include <QNetworkReply>
const QString TEXT_VIEWS("Views: %1");
const QString TEXT_FOLLOWERS("Followers: %1");
const QString TEXT_CREATED("Created: %1");
const QString TEXT_TITLE("%1's Usercard");
#define TEXT_USER_ID "ID: "
#define TEXT_UNAVAILABLE "(not available)"
namespace chatterino {
namespace {
Label *addCopyableLabel(LayoutCreator<QHBoxLayout> box)
{
auto label = box.emplace<Label>();
auto button = box.emplace<Button>();
button->setPixmap(getResources().buttons.copyDark);
button->setScaleIndependantSize(18, 18);
button->setDim(Button::Dim::Lots);
QObject::connect(
button.getElement(), &Button::leftClicked,
[label = label.getElement()] {
auto copyText = label->property("copy-text").toString();
qApp->clipboard()->setText(copyText.isEmpty() ? label->getText()
: copyText);
});
return label.getElement();
};
bool checkMessageUserName(const QString &userName, MessagePtr message)
{
if (message->flags.has(MessageFlag::Whisper))
return false;
bool isSubscription = message->flags.has(MessageFlag::Subscription) &&
message->loginName.isEmpty() &&
message->messageText.split(" ").at(0).compare(
userName, Qt::CaseInsensitive) == 0;
bool isModAction =
message->timeoutUser.compare(userName, Qt::CaseInsensitive) == 0;
bool isSelectedUser =
message->loginName.compare(userName, Qt::CaseInsensitive) == 0;
return (isSubscription || isModAction || isSelectedUser);
}
ChannelPtr filterMessages(const QString &userName, ChannelPtr channel)
{
LimitedQueueSnapshot<MessagePtr> snapshot =
channel->getMessageSnapshot();
ChannelPtr channelPtr(
new Channel(channel->getName(), Channel::Type::None));
for (size_t i = 0; i < snapshot.size(); i++)
{
MessagePtr message = snapshot[i];
if (checkMessageUserName(userName, message))
{
channelPtr->addMessage(message);
}
}
return channelPtr;
};
const auto borderColor = QColor(255, 255, 255, 80);
int calculateTimeoutDuration(TimeoutButton timeout)
{
static const QMap<QString, int> durations{
{"s", 1}, {"m", 60}, {"h", 3600}, {"d", 86400}, {"w", 604800},
};
return timeout.second * durations[timeout.first];
}
} // namespace
#ifdef Q_OS_LINUX
FlagsEnum<BaseWindow::Flags> userInfoPopupFlags{BaseWindow::Dialog,
BaseWindow::EnableCustomFrame};
FlagsEnum<BaseWindow::Flags> userInfoPopupFlagsCloseAutomatically{
BaseWindow::EnableCustomFrame};
#else
FlagsEnum<BaseWindow::Flags> userInfoPopupFlags{BaseWindow::EnableCustomFrame};
FlagsEnum<BaseWindow::Flags> userInfoPopupFlagsCloseAutomatically{
BaseWindow::EnableCustomFrame, BaseWindow::Frameless,
BaseWindow::FramelessDraggable};
#endif
UserInfoPopup::UserInfoPopup(bool closeAutomatically, QWidget *parent)
: BaseWindow(closeAutomatically ? userInfoPopupFlagsCloseAutomatically
: userInfoPopupFlags,
parent)
, hack_(new bool)
{
this->setWindowTitle("Usercard");
this->setStayInScreenRect(true);
if (closeAutomatically)
this->setActionOnFocusLoss(BaseWindow::Delete);
else
this->setAttribute(Qt::WA_DeleteOnClose);
// Close the popup when Escape is pressed
createWindowShortcut(this, "Escape", [this] {
this->deleteLater();
});
auto layout = LayoutCreator<QWidget>(this->getLayoutContainer())
.setLayoutType<QVBoxLayout>();
// first line
auto head = layout.emplace<QHBoxLayout>().withoutMargin();
{
// avatar
auto avatar =
head.emplace<Button>(nullptr).assign(&this->ui_.avatarButton);
avatar->setScaleIndependantSize(100, 100);
avatar->setDim(Button::Dim::None);
QObject::connect(avatar.getElement(), &Button::leftClicked, [this] {
QDesktopServices::openUrl(
QUrl("https://twitch.tv/" + this->userName_.toLower()));
});
auto vbox = head.emplace<QVBoxLayout>();
{
// items on the right
{
auto box = vbox.emplace<QHBoxLayout>()
.withoutMargin()
.withoutSpacing();
this->ui_.nameLabel = addCopyableLabel(box);
this->ui_.nameLabel->setFontStyle(FontStyle::UiMediumBold);
box->addStretch(1);
auto palette = QPalette();
palette.setColor(QPalette::WindowText, QColor("#aaa"));
this->ui_.userIDLabel = addCopyableLabel(box);
this->ui_.userIDLabel->setPalette(palette);
}
// items on the left
vbox.emplace<Label>(TEXT_VIEWS.arg(""))
.assign(&this->ui_.viewCountLabel);
vbox.emplace<Label>(TEXT_FOLLOWERS.arg(""))
.assign(&this->ui_.followerCountLabel);
vbox.emplace<Label>(TEXT_CREATED.arg(""))
.assign(&this->ui_.createdDateLabel);
vbox.emplace<Label>("").assign(&this->ui_.followageLabel);
vbox.emplace<Label>("").assign(&this->ui_.subageLabel);
}
}
layout.emplace<Line>(false);
// second line
auto user = layout.emplace<QHBoxLayout>().withoutMargin();
{
user->addStretch(1);
user.emplace<QCheckBox>("Follow").assign(&this->ui_.follow);
user.emplace<QCheckBox>("Ignore").assign(&this->ui_.ignore);
user.emplace<QCheckBox>("Ignore highlights")
.assign(&this->ui_.ignoreHighlights);
auto usercard = user.emplace<EffectLabel2>(this);
usercard->getLabel().setText("Usercard");
auto refresh = user.emplace<EffectLabel2>(this);
refresh->getLabel().setText("Refresh");
auto mod = user.emplace<Button>(this);
mod->setPixmap(getResources().buttons.mod);
mod->setScaleIndependantSize(30, 30);
auto unmod = user.emplace<Button>(this);
unmod->setPixmap(getResources().buttons.unmod);
unmod->setScaleIndependantSize(30, 30);
auto vip = user.emplace<Button>(this);
vip->setPixmap(getResources().buttons.vip);
vip->setScaleIndependantSize(30, 30);
auto unvip = user.emplace<Button>(this);
unvip->setPixmap(getResources().buttons.unvip);
unvip->setScaleIndependantSize(30, 30);
user->addStretch(1);
QObject::connect(usercard.getElement(), &Button::leftClicked, [this] {
QDesktopServices::openUrl("https://www.twitch.tv/popout/" +
this->channel_->getName() +
"/viewercard/" + this->userName_);
});
QObject::connect(refresh.getElement(), &Button::leftClicked, [this] {
this->updateLatestMessages();
});
QObject::connect(mod.getElement(), &Button::leftClicked, [this] {
this->channel_->sendMessage("/mod " + this->userName_);
});
QObject::connect(unmod.getElement(), &Button::leftClicked, [this] {
this->channel_->sendMessage("/unmod " + this->userName_);
});
QObject::connect(vip.getElement(), &Button::leftClicked, [this] {
this->channel_->sendMessage("/vip " + this->userName_);
});
QObject::connect(unvip.getElement(), &Button::leftClicked, [this] {
this->channel_->sendMessage("/unvip " + this->userName_);
});
// userstate
this->userStateChanged_.connect([this, mod, unmod, vip,
unvip]() mutable {
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
bool visibilityModButtons = false;
if (twitchChannel)
{
bool isMyself =
QString::compare(
getApp()->accounts->twitch.getCurrent()->getUserName(),
this->userName_, Qt::CaseInsensitive) == 0;
visibilityModButtons =
twitchChannel->isBroadcaster() && !isMyself;
}
mod->setVisible(visibilityModButtons);
unmod->setVisible(visibilityModButtons);
vip->setVisible(visibilityModButtons);
unvip->setVisible(visibilityModButtons);
});
}
auto lineMod = layout.emplace<Line>(false);
// third line
auto moderation = layout.emplace<QHBoxLayout>().withoutMargin();
{
auto timeout = moderation.emplace<TimeoutWidget>();
this->userStateChanged_.connect([this, lineMod, timeout]() mutable {
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
bool hasModRights =
twitchChannel ? twitchChannel->hasModRights() : false;
lineMod->setVisible(hasModRights);
timeout->setVisible(hasModRights);
});
timeout->buttonClicked.connect([this](auto item) {
TimeoutWidget::Action action;
int arg;
std::tie(action, arg) = item;
switch (action)
{
case TimeoutWidget::Ban: {
if (this->channel_)
{
this->channel_->sendMessage("/ban " + this->userName_);
}
}
break;
case TimeoutWidget::Unban: {
if (this->channel_)
{
this->channel_->sendMessage("/unban " +
this->userName_);
}
}
break;
case TimeoutWidget::Timeout: {
if (this->channel_)
{
this->channel_->sendMessage("/timeout " +
this->userName_ + " " +
QString::number(arg));
}
}
break;
}
});
}
layout.emplace<Line>(false);
// fourth line (last messages)
auto logs = layout.emplace<QVBoxLayout>().withoutMargin();
{
this->ui_.noMessagesLabel = new Label("No recent messages");
this->ui_.noMessagesLabel->setVisible(false);
this->ui_.latestMessages = new ChannelView(this);
this->ui_.latestMessages->setMinimumSize(400, 275);
this->ui_.latestMessages->setSizePolicy(QSizePolicy::Expanding,
QSizePolicy::Expanding);
logs->addWidget(this->ui_.noMessagesLabel);
logs->addWidget(this->ui_.latestMessages);
logs->setAlignment(this->ui_.noMessagesLabel, Qt::AlignHCenter);
}
this->installEvents();
this->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Policy::Ignored);
}
// remove once https://github.com/pajlada/signals/pull/10 gets merged
UserInfoPopup::~UserInfoPopup()
{
this->refreshConnection_.disconnect();
}
void UserInfoPopup::themeChangedEvent()
{
BaseWindow::themeChangedEvent();
for (auto &&child : this->findChildren<QCheckBox *>())
{
child->setFont(getFonts()->getFont(FontStyle::UiMedium, this->scale()));
}
}
void UserInfoPopup::scaleChangedEvent(float /*scale*/)
{
themeChangedEvent();
QTimer::singleShot(20, this, [this] {
auto geo = this->geometry();
geo.setWidth(10);
geo.setHeight(10);
this->setGeometry(geo);
});
}
void UserInfoPopup::installEvents()
{
std::weak_ptr<bool> hack = this->hack_;
// follow
QObject::connect(
this->ui_.follow, &QCheckBox::stateChanged,
[this](int newState) mutable {
auto currentUser = getApp()->accounts->twitch.getCurrent();
const auto reenableFollowCheckbox = [this] {
this->ui_.follow->setEnabled(true);
};
if (!this->ui_.follow->isEnabled())
{
// We received a state update while the checkbox was disabled
// This can only happen from the "check current follow state" call
// The state has been updated to properly reflect the users current follow state
reenableFollowCheckbox();
return;
}
switch (newState)
{
case Qt::CheckState::Unchecked: {
this->ui_.follow->setEnabled(false);
currentUser->unfollowUser(this->userId_,
reenableFollowCheckbox);
}
break;
case Qt::CheckState::PartiallyChecked: {
// We deliberately ignore this state
}
break;
case Qt::CheckState::Checked: {
this->ui_.follow->setEnabled(false);
currentUser->followUser(this->userId_,
reenableFollowCheckbox);
}
break;
}
});
std::shared_ptr<bool> ignoreNext = std::make_shared<bool>(false);
// ignore
QObject::connect(
this->ui_.ignore, &QCheckBox::stateChanged,
[this, ignoreNext, hack](int) mutable {
if (*ignoreNext)
{
*ignoreNext = false;
return;
}
this->ui_.ignore->setEnabled(false);
auto currentUser = getApp()->accounts->twitch.getCurrent();
if (this->ui_.ignore->isChecked())
{
currentUser->ignoreByID(
this->userId_, this->userName_,
[=](auto result, const auto &message) mutable {
if (hack.lock())
{
if (result == IgnoreResult_Failed)
{
*ignoreNext = true;
this->ui_.ignore->setChecked(false);
}
this->ui_.ignore->setEnabled(true);
}
});
}
else
{
currentUser->unignoreByID(
this->userId_, this->userName_,
[=](auto result, const auto &message) mutable {
if (hack.lock())
{
if (result == UnignoreResult_Failed)
{
*ignoreNext = true;
this->ui_.ignore->setChecked(true);
}
this->ui_.ignore->setEnabled(true);
}
});
}
});
// ignore highlights
QObject::connect(
this->ui_.ignoreHighlights, &QCheckBox::clicked,
[this](bool checked) mutable {
this->ui_.ignoreHighlights->setEnabled(false);
if (checked)
{
getSettings()->blacklistedUsers.insert(
HighlightBlacklistUser{this->userName_, false});
this->ui_.ignoreHighlights->setEnabled(true);
}
else
{
const auto &vector = getSettings()->blacklistedUsers.raw();
for (int i = 0; i < vector.size(); i++)
{
if (this->userName_ == vector[i].getPattern())
{
getSettings()->blacklistedUsers.removeAt(i);
i--;
}
}
if (getSettings()->isBlacklistedUser(this->userName_))
{
this->ui_.ignoreHighlights->setToolTip(
"Name matched by regex");
}
else
{
this->ui_.ignoreHighlights->setEnabled(true);
}
}
});
}
void UserInfoPopup::setData(const QString &name, const ChannelPtr &channel)
{
this->userName_ = name;
this->channel_ = channel;
this->setWindowTitle(TEXT_TITLE.arg(name));
this->ui_.nameLabel->setText(name);
this->ui_.nameLabel->setProperty("copy-text", name);
this->updateUserData();
this->userStateChanged_.invoke();
this->updateLatestMessages();
QTimer::singleShot(1, this, [this] {
this->setStayInScreenRect(true);
});
}
void UserInfoPopup::updateLatestMessages()
{
auto filteredChannel = filterMessages(this->userName_, this->channel_);
this->ui_.latestMessages->setChannel(filteredChannel);
this->ui_.latestMessages->setSourceChannel(this->channel_);
const bool hasMessages = filteredChannel->hasMessages();
this->ui_.latestMessages->setVisible(hasMessages);
this->ui_.noMessagesLabel->setVisible(!hasMessages);
// shrink dialog in case ChannelView goes from visible to hidden
this->adjustSize();
this->refreshConnection_
.disconnect(); // remove once https://github.com/pajlada/signals/pull/10 gets merged
this->refreshConnection_ = this->channel_->messageAppended.connect(
[this, hasMessages](auto message, auto) {
if (!checkMessageUserName(this->userName_, message))
return;
if (hasMessages)
{
// display message in ChannelView
this->ui_.latestMessages->channel()->addMessage(message);
}
else
{
// The ChannelView is currently hidden, so manually refresh
// and display the latest messages
this->updateLatestMessages();
}
});
}
void UserInfoPopup::updateUserData()
{
this->ui_.follow->setEnabled(false);
std::weak_ptr<bool> hack = this->hack_;
auto currentUser = getApp()->accounts->twitch.getCurrent();
const auto onUserFetchFailed = [this, hack] {
if (!hack.lock())
{
return;
}
// this can occur when the account doesn't exist.
this->ui_.followerCountLabel->setText(
TEXT_FOLLOWERS.arg(TEXT_UNAVAILABLE));
this->ui_.viewCountLabel->setText(TEXT_VIEWS.arg(TEXT_UNAVAILABLE));
this->ui_.createdDateLabel->setText(TEXT_CREATED.arg(TEXT_UNAVAILABLE));
this->ui_.nameLabel->setText(this->userName_);
this->ui_.userIDLabel->setText(QString("ID ") +
QString(TEXT_UNAVAILABLE));
this->ui_.userIDLabel->setProperty("copy-text",
QString(TEXT_UNAVAILABLE));
};
const auto onUserFetched = [this, hack,
currentUser](const HelixUser &user) {
if (!hack.lock())
{
return;
}
this->userId_ = user.id;
this->ui_.userIDLabel->setText(TEXT_USER_ID + user.id);
this->ui_.userIDLabel->setProperty("copy-text", user.id);
this->ui_.viewCountLabel->setText(TEXT_VIEWS.arg(user.viewCount));
getKraken()->getUser(
user.id,
[this, hack](const auto &user) {
if (!hack.lock())
{
return;
}
this->ui_.nameLabel->setText(user.displayName);
this->setWindowTitle(TEXT_TITLE.arg(user.displayName));
this->ui_.createdDateLabel->setText(
TEXT_CREATED.arg(user.createdAt.section("T", 0, 0)));
},
[] {
// failure
});
if (isInStreamerMode() &&
getSettings()->streamerModeHideUsercardAvatars)
{
this->ui_.avatarButton->setPixmap(getResources().streamerMode);
}
else
{
this->loadAvatar(user.profileImageUrl);
}
getHelix()->getUserFollowers(
user.id,
[this, hack](const auto &followers) {
if (!hack.lock())
{
return;
}
this->ui_.followerCountLabel->setText(
TEXT_FOLLOWERS.arg(followers.total));
},
[] {
// on failure
});
// get follow state
currentUser->checkFollow(user.id, [this, hack](auto result) {
if (!hack.lock())
{
return;
}
if (result != FollowResult_Failed)
{
this->ui_.follow->setChecked(result == FollowResult_Following);
this->ui_.follow->setEnabled(true);
}
});
// get ignore state
bool isIgnoring = false;
for (const auto &ignoredUser : currentUser->getIgnores())
{
if (user.id == ignoredUser.id)
{
isIgnoring = true;
break;
}
}
// get ignoreHighlights state
bool isIgnoringHighlights = false;
const auto &vector = getSettings()->blacklistedUsers.raw();
for (int i = 0; i < vector.size(); i++)
{
if (this->userName_ == vector[i].getPattern())
{
isIgnoringHighlights = true;
break;
}
}
if (getSettings()->isBlacklistedUser(this->userName_) &&
!isIgnoringHighlights)
{
this->ui_.ignoreHighlights->setToolTip("Name matched by regex");
}
else
{
this->ui_.ignoreHighlights->setEnabled(true);
}
this->ui_.ignore->setEnabled(true);
this->ui_.ignore->setChecked(isIgnoring);
this->ui_.ignoreHighlights->setChecked(isIgnoringHighlights);
// get followage and subage
getIvr()->getSubage(
this->userName_, this->channel_->getName(),
[this, hack](const IvrSubage &subageInfo) {
if (!hack.lock())
{
return;
}
if (!subageInfo.followingSince.isEmpty())
{
QDateTime followedAt = QDateTime::fromString(
subageInfo.followingSince, Qt::ISODate);
QString followingSince = followedAt.toString("yyyy-MM-dd");
this->ui_.followageLabel->setText("❤ Following since " +
followingSince);
}
if (subageInfo.isSubHidden)
{
this->ui_.subageLabel->setText(
"Subscription status hidden");
}
else if (subageInfo.isSubbed)
{
this->ui_.subageLabel->setText(
QString("★ Tier %1 - Subscribed for %2 months")
.arg(subageInfo.subTier)
.arg(subageInfo.totalSubMonths));
}
else if (subageInfo.totalSubMonths)
{
this->ui_.subageLabel->setText(
QString("★ Previously subscribed for %1 months")
.arg(subageInfo.totalSubMonths));
}
},
[] {});
};
getHelix()->getUserByName(this->userName_, onUserFetched,
onUserFetchFailed);
this->ui_.follow->setEnabled(false);
this->ui_.ignore->setEnabled(false);
this->ui_.ignoreHighlights->setEnabled(false);
}
void UserInfoPopup::loadAvatar(const QUrl &url)
{
QNetworkRequest req(url);
static auto manager = new QNetworkAccessManager();
auto *reply = manager->get(req);
QObject::connect(reply, &QNetworkReply::finished, this, [=] {
if (reply->error() == QNetworkReply::NoError)
{
const auto data = reply->readAll();
// might want to cache the avatar image
QPixmap avatar;
avatar.loadFromData(data);
this->ui_.avatarButton->setPixmap(avatar);
}
else
{
this->ui_.avatarButton->setPixmap(QPixmap());
}
});
}
//
// TimeoutWidget
//
UserInfoPopup::TimeoutWidget::TimeoutWidget()
: BaseWidget(nullptr)
{
auto layout = LayoutCreator<TimeoutWidget>(this)
.setLayoutType<QHBoxLayout>()
.withoutMargin();
QColor color1(255, 255, 255, 80);
QColor color2(255, 255, 255, 0);
int buttonWidth = 40;
// int buttonWidth = 24;
int buttonWidth2 = 32;
int buttonHeight = 32;
layout->setSpacing(16);
//auto addButton = [&](Action action, const QString &text,
// const QPixmap &pixmap) {
// auto vbox = layout.emplace<QVBoxLayout>().withoutMargin();
// {
// auto title = vbox.emplace<QHBoxLayout>().withoutMargin();
// title->addStretch(1);
// auto label = title.emplace<Label>(text);
// label->setHasOffset(false);
// label->setStyleSheet("color: #BBB");
// title->addStretch(1);
// auto hbox = vbox.emplace<QHBoxLayout>().withoutMargin();
// hbox->setSpacing(0);
// {
// auto button = hbox.emplace<Button>(nullptr);
// button->setPixmap(pixmap);
// button->setScaleIndependantSize(buttonHeight, buttonHeight);
// button->setBorderColor(QColor(255, 255, 255, 127));
// QObject::connect(
// button.getElement(), &Button::leftClicked, [this, action] {
// this->buttonClicked.invoke(std::make_pair(action, -1));
// });
// }
// }
//};
const auto addLayout = [&](const QString &text) {
auto vbox = layout.emplace<QVBoxLayout>().withoutMargin();
auto title = vbox.emplace<QHBoxLayout>().withoutMargin();
title->addStretch(1);
auto label = title.emplace<Label>(text);
label->setStyleSheet("color: #BBB");
label->setHasOffset(false);
title->addStretch(1);
auto hbox = vbox.emplace<QHBoxLayout>().withoutMargin();
hbox->setSpacing(0);
return hbox;
};
const auto addButton = [&](Action action, const QString &title,
const QPixmap &pixmap) {
auto button = addLayout(title).emplace<Button>(nullptr);
button->setPixmap(pixmap);
button->setScaleIndependantSize(buttonHeight, buttonHeight);
button->setBorderColor(QColor(255, 255, 255, 127));
QObject::connect(
button.getElement(), &Button::leftClicked, [this, action] {
this->buttonClicked.invoke(std::make_pair(action, -1));
});
};
auto addTimeouts = [&](const QString &title) {
auto hbox = addLayout(title);
for (const auto &item : getSettings()->timeoutButtons.getValue())
{
auto a = hbox.emplace<EffectLabel2>();
a->getLabel().setText(QString::number(item.second) + item.first);
a->setScaleIndependantSize(buttonWidth, buttonHeight);
a->setBorderColor(borderColor);
const auto pair =
std::make_pair(Action::Timeout, calculateTimeoutDuration(item));
QObject::connect(a.getElement(), &EffectLabel2::leftClicked,
[this, pair] {
this->buttonClicked.invoke(pair);
});
//auto addTimeouts = [&](const QString &title_,
// const std::vector<std::pair<QString, int>> &items) {
// auto vbox = layout.emplace<QVBoxLayout>().withoutMargin();
// {
// auto title = vbox.emplace<QHBoxLayout>().withoutMargin();
// title->addStretch(1);
// auto label = title.emplace<Label>(title_);
// label->setStyleSheet("color: #BBB");
// label->setHasOffset(false);
// title->addStretch(1);
// auto hbox = vbox.emplace<QHBoxLayout>().withoutMargin();
// hbox->setSpacing(0);
// for (const auto &item : items)
// {
// auto a = hbox.emplace<EffectLabel2>();
// a->getLabel().setText(std::get<0>(item));
// if (std::get<0>(item).length() > 1)
// {
// a->setScaleIndependantSize(buttonWidth2, buttonHeight);
// }
// else
// {
// a->setScaleIndependantSize(buttonWidth, buttonHeight);
// }
// a->setBorderColor(color1);
// QObject::connect(a.getElement(), &EffectLabel2::leftClicked,
// [this, timeout = std::get<1>(item)] {
// this->buttonClicked.invoke(std::make_pair(
// Action::Timeout, timeout));
// });
// }
}
};
addButton(Unban, "Unban", getResources().buttons.unban);
addTimeouts("Timeouts");
addButton(Ban, "Ban", getResources().buttons.ban);
}
void UserInfoPopup::TimeoutWidget::paintEvent(QPaintEvent *)
{
// QPainter painter(this);
// painter.setPen(QColor(255, 255, 255, 63));
// painter.drawLine(0, this->height() / 2, this->width(), this->height()
// / 2);
}
} // namespace chatterino
| 35.137892 | 96 | 0.527008 | [
"geometry",
"vector"
] |
4b3bae4702234a28de72034d506accc66791f65c | 9,295 | cc | C++ | xic/src/cd/cd_master.cc | bernardventer/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 3 | 2020-01-26T14:18:52.000Z | 2020-12-09T20:07:22.000Z | xic/src/cd/cd_master.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | null | null | null | xic/src/cd/cd_master.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 2 | 2020-01-26T14:19:02.000Z | 2021-08-14T16:33:28.000Z |
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* Xic Integrated Circuit Layout and Schematic Editor *
* *
*========================================================================*
$Id:$
*========================================================================*/
#include "cd.h"
#include "cd_types.h"
#include "cd_propnum.h"
#include "cd_celldb.h"
#include "miscutil/pathlist.h"
CDm::~CDm()
{
// name is in CellNameTable, don't delete!
if (mObjRefs & 1)
delete (ptable_t<CDc>*)(mObjRefs & ~1);
if (mUnlinked & 1)
delete (ptable_t<CDc>*)(mUnlinked & ~1);
}
// Delete all the instances, which has the effect of deleting the
// master desc itself. However, if there are instances in the
// mObjRefs list and parent is null, the master desc is not deleted.
//
bool
CDm::clear()
{
if (parent()) {
if (parent()->isImmutable())
// Dont touch this!
return (false);
// This will remove any references, and put the instance in
// the mUnlinked list.
CDc_gen cgen(this);
for (CDc *c = cgen.c_first(); c; c = cgen.c_next()) {
if (!parent()->unlink(c, true))
Errs()->get_error();
}
}
CDc_gen cgen(this, true);
for (CDc *c = cgen.c_first(); c; c = cgen.c_next()) {
unlinkCdesc(c, true);
c->setMaster(0); // don't free this
delete c;
}
if (!hasInstances()) {
unlink(); // unlink from parent
if (celldesc())
unlinkRef();
delete this;
return (true);
}
return (false);
}
void
CDm::linkCdesc(CDc *cd, bool unl_list)
{
if (!cd)
return;
if (unl_list) {
if (mUnlinked & 1) {
ptable_t<CDc> *t = (ptable_t<CDc>*)(mUnlinked & ~1);
t->add(cd);
t = t->check_rehash();
mUnlinked = (unsigned long)t | 1;
}
else {
int cnt = 0;
for (CDc *c = (CDc*)mUnlinked; c; c = c->ptab_next())
cnt++;
if (cnt < ST_MAX_DENS) {
cd->set_ptab_next((CDc*)mUnlinked);
mUnlinked = (unsigned long)cd;
}
else {
ptable_t<CDc> *t = new ptable_t<CDc>;
CDc *c = (CDc*)mUnlinked;
while (c) {
CDc *cx = c;
c = c->ptab_next();
cx->set_ptab_next(0);
t->add(cx);
}
t->add(cd);
t = t->check_rehash();
mUnlinked = (unsigned long)t | 1;
}
}
}
else {
if (mObjRefs & 1) {
ptable_t<CDc> *t = (ptable_t<CDc>*)(mObjRefs & ~1);
t->add(cd);
t = t->check_rehash();
mObjRefs = (unsigned long)t | 1;
}
else {
int cnt = 0;
for (CDc *c = (CDc*)mObjRefs; c; c = c->ptab_next())
cnt++;
if (cnt < ST_MAX_DENS) {
cd->set_ptab_next((CDc*)mObjRefs);
mObjRefs = (unsigned long)cd;
}
else {
ptable_t<CDc> *t = new ptable_t<CDc>;
CDc *c = (CDc*)mObjRefs;
while (c) {
CDc *cx = c;
c = c->ptab_next();
cx->set_ptab_next(0);
t->add(cx);
}
t->add(cd);
t = t->check_rehash();
mObjRefs = (unsigned long)t | 1;
}
}
}
}
void
CDm::unlinkCdesc(CDc *cd, bool unl_list)
{
if (!cd)
return;
if (unl_list) {
if (mUnlinked & 1)
((ptable_t<CDc>*)(mUnlinked & ~1))->remove(cd);
else {
CDc *cp = 0;
for (CDc *c = (CDc*)mUnlinked; c; c = c->ptab_next()) {
if (c == cd) {
if (!cp)
mUnlinked = (unsigned long)c->ptab_next();
else
cp->set_ptab_next(c->ptab_next());
cd->set_ptab_next(0);
break;
}
cp = c;
}
}
}
else {
if (mObjRefs & 1)
((ptable_t<CDc>*)(mObjRefs & ~1))->remove(cd);
else {
CDc *cp = 0;
for (CDc *c = (CDc*)mObjRefs; c; c = c->ptab_next()) {
if (c == cd) {
if (!cp)
mObjRefs = (unsigned long)c->ptab_next();
else
cp->set_ptab_next(c->ptab_next());
cd->set_ptab_next(0);
break;
}
cp = c;
}
}
}
}
// Update the object descriptor BB's, and reinsert object descriptors into
// appropriate bins.
//
bool
CDm::reflect()
{
CDc_gen cgen(this);
for (CDc *cdesc = cgen.c_first(); cdesc; cdesc = cgen.c_next()) {
if (!cdesc->updateBB())
return (false);
}
return (true);
}
int
CDm::listInstance(stringnumlist **l, bool expand)
{
int count = 0;
CDc_gen cgen(this);
for (CDc *c = cgen.c_first(); c; c = cgen.c_next()) {
if (expand) {
if (mSdesc && mSdesc->isElectrical()) {
CDp_range *pr = (CDp_range*)c->prpty(P_RANGE);
count += pr ? pr->width() : 1;
}
else {
CDap ap(c);
count += ap.nx*ap.ny;
}
}
else
count++;
}
if (l)
*l = new stringnumlist(lstring::copy(mName), count, *l);
return (count);
}
// Set the mSdesc pointer if it is null.
//
void
CDm::setSdesc()
{
if (!mSdesc && mParent) {
DisplayMode mode = mParent->displayMode();
if (mode == Physical ||
(mode == Electrical && !CD()->IsNoElectrical())) {
CDs *sd = 0;
CDcbin cbin;
if (OIfailed(CD()->OpenExisting(mName, &cbin))) {
// silently ignore error
Errs()->get_error();
sd = CDcdb()->insertCell(mName, mode);
}
else {
sd = cbin.celldesc(mode);
if (!sd)
sd = CDcdb()->insertCell(mName, mode);
}
linkRef(sd);
}
}
}
void
CDm::setParent(CDs *s)
{
if (s && s->isSymbolic()) {
s = s->owner();
CD()->DbgError("symbolic", "CDm::setParent");
}
mParent = s;
}
void
CDm::setCelldesc(CDs *s)
{
if (s && s->isSymbolic()) {
s = s->owner();
CD()->DbgError("symbolic", "CDm::setCelldesc");
}
mSdesc = s;
}
| 31.615646 | 76 | 0.418612 | [
"object"
] |
4b3c1667e45f21191457e36f8431457d739fe94f | 1,488 | cpp | C++ | HDUOJ/6170/dp.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | HDUOJ/6170/dp.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | HDUOJ/6170/dp.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include <climits>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <functional>
#include <iterator>
#define SIZE 2510
using namespace std;
bool dp[SIZE][SIZE];
int main()
{
ios::sync_with_stdio(false);
int caseNum;
cin >> caseNum;
while (caseNum--)
{
string fst, snd;
cin >> fst >> snd;
int fstLen = fst.length();
int sndLen = snd.length();
memset(dp, false, sizeof(dp));
dp[0][0] = true;
for (int i = 1; i <= sndLen; i++)
{
if (i >= 2 && snd[i - 1] == '*')
{
dp[i][0] = dp[i - 2][0];
}
for (int j = 1; j <= fstLen; j++)
{
if (snd[i - 1] == '.' || fst[j - 1] == snd[i - 1])
{
dp[i][j] = dp[i - 1][j - 1];
}
else if (snd[i - 1] == '*')
{
dp[i][j] = dp[i - 2][j] | dp[i - 1][j];
if ((dp[i - 1][j - 1] || dp[i][j - 1]) && fst[j - 2] == fst[j - 1])
{
dp[i][j] = true;
}
}
}
}
if (dp[sndLen][fstLen])
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
} | 22.545455 | 87 | 0.385753 | [
"vector"
] |
4b3c184bf6b10479104021f760e67f333f721ce7 | 3,606 | cpp | C++ | fdbserver/workloads/MetricLogging.actor.cpp | MasterMann/foundationdb | 8d37ddf1ecbd6e8cfac626fe8b65eb5183139c99 | [
"Apache-2.0"
] | 1 | 2019-04-16T19:51:05.000Z | 2019-04-16T19:51:05.000Z | fdbserver/workloads/MetricLogging.actor.cpp | MasterMann/foundationdb | 8d37ddf1ecbd6e8cfac626fe8b65eb5183139c99 | [
"Apache-2.0"
] | 1 | 2019-03-15T18:05:48.000Z | 2019-03-15T18:05:48.000Z | fdbserver/workloads/MetricLogging.actor.cpp | MasterMann/foundationdb | 8d37ddf1ecbd6e8cfac626fe8b65eb5183139c99 | [
"Apache-2.0"
] | null | null | null | /*
* MetricLogging.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fdbrpc/ContinuousSample.h"
#include "fdbclient/NativeAPI.actor.h"
#include "fdbserver/TesterInterface.actor.h"
#include "flow/TDMetric.actor.h"
#include "fdbserver/workloads/workloads.actor.h"
#include "flow/actorcompiler.h" // This must be the last #include.
struct MetricLoggingWorkload : TestWorkload {
int actorCount, metricCount;
double testDuration;
bool testBool, enabled;
vector<Future<Void>> clients;
PerfIntCounter changes;
std::vector<BoolMetricHandle> boolMetrics;
std::vector<Int64MetricHandle> int64Metrics;
MetricLoggingWorkload(WorkloadContext const& wcx)
: TestWorkload(wcx),
changes("Changes")
{
testDuration = getOption( options, LiteralStringRef("testDuration"), 10.0 );
actorCount = getOption( options, LiteralStringRef("actorCount"), 1 );
metricCount = getOption( options, LiteralStringRef("metricCount"), 1 );
testBool = getOption( options, LiteralStringRef("testBool"), true );
enabled = getOption( options, LiteralStringRef("enabled"), true );
for( int i = 0; i < metricCount; i++ ) {
if( testBool ) {
boolMetrics.push_back(BoolMetricHandle(LiteralStringRef("TestBool"), format("%d", i)));
} else {
int64Metrics.push_back(Int64MetricHandle(LiteralStringRef("TestInt"), format("%d", i)));
}
}
}
virtual std::string description() { return "MetricLogging"; }
virtual Future<Void> setup( Database const& cx ) {
return _setup( this, cx );
}
ACTOR Future<Void> _setup( MetricLoggingWorkload* self, Database cx ) {
wait( delay(2.0) );
for( int i = 0; i < self->metricCount; i++ ) {
if( self->testBool ) {
self->boolMetrics[i]->setConfig(true);
} else {
self->int64Metrics[i]->setConfig(true);
}
}
return Void();
}
virtual Future<Void> start( Database const& cx ) {
for(int c = 0; c < actorCount; c++)
clients.push_back( timeout( MetricLoggingClient( cx, this, clientId, c ), testDuration, Void() ) );
return waitForAll( clients );
}
virtual Future<bool> check( Database const& cx ) {
clients.clear();
return true;
}
virtual void getMetrics( vector<PerfMetric>& m ) {
m.push_back( changes.getMetric() );
m.push_back( PerfMetric( "Changes/sec", changes.getValue() / testDuration, false ) );
}
ACTOR Future<Void> MetricLoggingClient( Database cx, MetricLoggingWorkload *self, int clientId, int actorId ) {
state BinaryWriter writer( Unversioned() );
state uint64_t lastTime = 0;
state double startTime = now();
loop {
for( int i = 0; i < 100; i++ ) {
if( self->testBool ) {
self->boolMetrics[self->changes.getValue() % self->metricCount]->toggle();
} else {
self->int64Metrics[self->changes.getValue() % self->metricCount] = (self->changes.getValue());
}
++self->changes;
}
wait( yield() );
}
}
};
WorkloadFactory<MetricLoggingWorkload> MetricLoggingWorkloadFactory("MetricLogging");
| 32.781818 | 112 | 0.702995 | [
"vector"
] |
4b3d904517e30f758234e757d7475221fd240636 | 14,284 | cc | C++ | net/base/cert_verifier.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | net/base/cert_verifier.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | net/base/cert_verifier.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/cert_verifier.h"
#include "base/compiler_specific.h"
#include "base/lock.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/worker_pool.h"
#include "net/base/net_errors.h"
#include "net/base/x509_certificate.h"
#if defined(USE_NSS)
#include <private/pprthred.h> // PR_DetachThread
#endif
namespace net {
////////////////////////////////////////////////////////////////////////////
// Life of a request:
//
// CertVerifier CertVerifierJob CertVerifierWorker Request
// | (origin loop) (worker loop)
// |
// Verify()
// |---->-------------------<creates>
// |
// |---->----<creates>
// |
// |---->---------------------------------------------------<creates>
// |
// |---->--------------------Start
// | |
// | PostTask
// |
// | <starts verifying>
// |---->-----AddRequest |
// |
// |
// |
// Finish
// |
// PostTask
//
// |
// DoReply
// |----<-----------------------|
// HandleResult
// |
// |---->-----HandleResult
// |
// |------>-----------------------------------Post
//
//
//
// On a cache hit, CertVerifier::Verify() returns synchronously without
// posting a task to a worker thread.
// The number of CachedCertVerifyResult objects that we'll cache.
static const unsigned kMaxCacheEntries = 256;
// The number of seconds for which we'll cache a cache entry.
static const unsigned kTTLSecs = 1800; // 30 minutes.
namespace {
class DefaultTimeService : public CertVerifier::TimeService {
public:
// CertVerifier::TimeService methods:
virtual base::Time Now() { return base::Time::Now(); }
};
} // namespace
CachedCertVerifyResult::CachedCertVerifyResult() : error(ERR_FAILED) {
}
CachedCertVerifyResult::~CachedCertVerifyResult() {}
bool CachedCertVerifyResult::HasExpired(const base::Time current_time) const {
return current_time >= expiry;
}
// Represents the output and result callback of a request.
class CertVerifierRequest {
public:
CertVerifierRequest(CompletionCallback* callback,
CertVerifyResult* verify_result)
: callback_(callback),
verify_result_(verify_result) {
}
// Ensures that the result callback will never be made.
void Cancel() {
callback_ = NULL;
verify_result_ = NULL;
}
// Copies the contents of |verify_result| to the caller's
// CertVerifyResult and calls the callback.
void Post(const CachedCertVerifyResult& verify_result) {
if (callback_) {
*verify_result_ = verify_result.result;
callback_->Run(verify_result.error);
}
delete this;
}
private:
CompletionCallback* callback_;
CertVerifyResult* verify_result_;
};
// CertVerifierWorker runs on a worker thread and takes care of the blocking
// process of performing the certificate verification. Deletes itself
// eventually if Start() succeeds.
class CertVerifierWorker {
public:
CertVerifierWorker(X509Certificate* cert,
const std::string& hostname,
int flags,
CertVerifier* cert_verifier)
: cert_(cert),
hostname_(hostname),
flags_(flags),
origin_loop_(MessageLoop::current()),
cert_verifier_(cert_verifier),
canceled_(false),
error_(ERR_FAILED) {
}
bool Start() {
DCHECK_EQ(MessageLoop::current(), origin_loop_);
return WorkerPool::PostTask(
FROM_HERE, NewRunnableMethod(this, &CertVerifierWorker::Run),
true /* task is slow */);
}
// Cancel is called from the origin loop when the CertVerifier is getting
// deleted.
void Cancel() {
DCHECK_EQ(MessageLoop::current(), origin_loop_);
AutoLock locked(lock_);
canceled_ = true;
}
private:
void Run() {
// Runs on a worker thread.
error_ = cert_->Verify(hostname_, flags_, &verify_result_);
#if defined(USE_NSS)
// Detach the thread from NSPR.
// Calling NSS functions attaches the thread to NSPR, which stores
// the NSPR thread ID in thread-specific data.
// The threads in our thread pool terminate after we have called
// PR_Cleanup. Unless we detach them from NSPR, net_unittests gets
// segfaults on shutdown when the threads' thread-specific data
// destructors run.
PR_DetachThread();
#endif
Finish();
}
// DoReply runs on the origin thread.
void DoReply() {
DCHECK_EQ(MessageLoop::current(), origin_loop_);
{
// We lock here because the worker thread could still be in Finished,
// after the PostTask, but before unlocking |lock_|. If we do not lock in
// this case, we will end up deleting a locked Lock, which can lead to
// memory leaks or worse errors.
AutoLock locked(lock_);
if (!canceled_) {
cert_verifier_->HandleResult(cert_, hostname_, flags_,
error_, verify_result_);
}
}
delete this;
}
void Finish() {
// Runs on the worker thread.
// We assume that the origin loop outlives the CertVerifier. If the
// CertVerifier is deleted, it will call Cancel on us. If it does so
// before the Acquire, we'll delete ourselves and return. If it's trying to
// do so concurrently, then it'll block on the lock and we'll call PostTask
// while the CertVerifier (and therefore the MessageLoop) is still alive.
// If it does so after this function, we assume that the MessageLoop will
// process pending tasks. In which case we'll notice the |canceled_| flag
// in DoReply.
bool canceled;
{
AutoLock locked(lock_);
canceled = canceled_;
if (!canceled) {
origin_loop_->PostTask(
FROM_HERE, NewRunnableMethod(this, &CertVerifierWorker::DoReply));
}
}
if (canceled)
delete this;
}
scoped_refptr<X509Certificate> cert_;
const std::string hostname_;
const int flags_;
MessageLoop* const origin_loop_;
CertVerifier* const cert_verifier_;
// lock_ protects canceled_.
Lock lock_;
// If canceled_ is true,
// * origin_loop_ cannot be accessed by the worker thread,
// * cert_verifier_ cannot be accessed by any thread.
bool canceled_;
int error_;
CertVerifyResult verify_result_;
DISALLOW_COPY_AND_ASSIGN(CertVerifierWorker);
};
// A CertVerifierJob is a one-to-one counterpart of a CertVerifierWorker. It
// lives only on the CertVerifier's origin message loop.
class CertVerifierJob {
public:
explicit CertVerifierJob(CertVerifierWorker* worker) : worker_(worker) {
}
~CertVerifierJob() {
if (worker_)
worker_->Cancel();
}
void AddRequest(CertVerifierRequest* request) {
requests_.push_back(request);
}
void HandleResult(const CachedCertVerifyResult& verify_result) {
worker_ = NULL;
PostAll(verify_result);
}
private:
void PostAll(const CachedCertVerifyResult& verify_result) {
std::vector<CertVerifierRequest*> requests;
requests_.swap(requests);
for (std::vector<CertVerifierRequest*>::iterator
i = requests.begin(); i != requests.end(); i++) {
(*i)->Post(verify_result);
// Post() causes the CertVerifierRequest to delete itself.
}
}
std::vector<CertVerifierRequest*> requests_;
CertVerifierWorker* worker_;
};
CertVerifier::CertVerifier()
: time_service_(new DefaultTimeService),
requests_(0),
cache_hits_(0),
inflight_joins_(0) {
}
CertVerifier::CertVerifier(TimeService* time_service)
: time_service_(time_service),
requests_(0),
cache_hits_(0),
inflight_joins_(0) {
}
CertVerifier::~CertVerifier() {
STLDeleteValues(&inflight_);
}
int CertVerifier::Verify(X509Certificate* cert,
const std::string& hostname,
int flags,
CertVerifyResult* verify_result,
CompletionCallback* callback,
RequestHandle* out_req) {
DCHECK(CalledOnValidThread());
if (!callback || !verify_result || hostname.empty()) {
*out_req = NULL;
return ERR_INVALID_ARGUMENT;
}
requests_++;
const RequestParams key = {cert->fingerprint(), hostname, flags};
// First check the cache.
std::map<RequestParams, CachedCertVerifyResult>::iterator i;
i = cache_.find(key);
if (i != cache_.end()) {
if (!i->second.HasExpired(time_service_->Now())) {
cache_hits_++;
*out_req = NULL;
*verify_result = i->second.result;
return i->second.error;
}
// Cache entry has expired.
cache_.erase(i);
}
// No cache hit. See if an identical request is currently in flight.
CertVerifierJob* job;
std::map<RequestParams, CertVerifierJob*>::const_iterator j;
j = inflight_.find(key);
if (j != inflight_.end()) {
// An identical request is in flight already. We'll just attach our
// callback.
inflight_joins_++;
job = j->second;
} else {
// Need to make a new request.
CertVerifierWorker* worker = new CertVerifierWorker(cert, hostname, flags,
this);
job = new CertVerifierJob(worker);
inflight_.insert(std::make_pair(key, job));
if (!worker->Start()) {
inflight_.erase(key);
delete job;
delete worker;
*out_req = NULL;
return ERR_FAILED; // TODO(wtc): Log an error message.
}
}
CertVerifierRequest* request =
new CertVerifierRequest(callback, verify_result);
job->AddRequest(request);
*out_req = request;
return ERR_IO_PENDING;
}
void CertVerifier::CancelRequest(RequestHandle req) {
DCHECK(CalledOnValidThread());
CertVerifierRequest* request = reinterpret_cast<CertVerifierRequest*>(req);
request->Cancel();
}
void CertVerifier::ClearCache() {
DCHECK(CalledOnValidThread());
cache_.clear();
// Leaves inflight_ alone.
}
size_t CertVerifier::GetCacheSize() const {
DCHECK(CalledOnValidThread());
return cache_.size();
}
// HandleResult is called by CertVerifierWorker on the origin message loop.
// It deletes CertVerifierJob.
void CertVerifier::HandleResult(X509Certificate* cert,
const std::string& hostname,
int flags,
int error,
const CertVerifyResult& verify_result) {
DCHECK(CalledOnValidThread());
const base::Time current_time(time_service_->Now());
CachedCertVerifyResult cached_result;
cached_result.error = error;
cached_result.result = verify_result;
uint32 ttl = kTTLSecs;
cached_result.expiry = current_time + base::TimeDelta::FromSeconds(ttl);
const RequestParams key = {cert->fingerprint(), hostname, flags};
DCHECK_GE(kMaxCacheEntries, 1u);
DCHECK_LE(cache_.size(), kMaxCacheEntries);
if (cache_.size() == kMaxCacheEntries) {
// Need to remove an element of the cache.
std::map<RequestParams, CachedCertVerifyResult>::iterator i, cur;
for (i = cache_.begin(); i != cache_.end(); ) {
cur = i++;
if (cur->second.HasExpired(current_time))
cache_.erase(cur);
}
}
if (cache_.size() == kMaxCacheEntries) {
// If we didn't clear out any expired entries, we just remove the first
// element. Crummy but simple.
cache_.erase(cache_.begin());
}
cache_.insert(std::make_pair(key, cached_result));
std::map<RequestParams, CertVerifierJob*>::iterator j;
j = inflight_.find(key);
if (j == inflight_.end()) {
NOTREACHED();
return;
}
CertVerifierJob* job = j->second;
inflight_.erase(j);
job->HandleResult(cached_result);
delete job;
}
/////////////////////////////////////////////////////////////////////
SingleRequestCertVerifier::SingleRequestCertVerifier(
CertVerifier* cert_verifier)
: cert_verifier_(cert_verifier),
cur_request_(NULL),
cur_request_callback_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(
callback_(this, &SingleRequestCertVerifier::OnVerifyCompletion)) {
DCHECK(cert_verifier_ != NULL);
}
SingleRequestCertVerifier::~SingleRequestCertVerifier() {
if (cur_request_) {
cert_verifier_->CancelRequest(cur_request_);
cur_request_ = NULL;
}
}
int SingleRequestCertVerifier::Verify(X509Certificate* cert,
const std::string& hostname,
int flags,
CertVerifyResult* verify_result,
CompletionCallback* callback) {
// Should not be already in use.
DCHECK(!cur_request_ && !cur_request_callback_);
// Do a synchronous verification.
if (!callback)
return cert->Verify(hostname, flags, verify_result);
CertVerifier::RequestHandle request = NULL;
// We need to be notified of completion before |callback| is called, so that
// we can clear out |cur_request_*|.
int rv = cert_verifier_->Verify(
cert, hostname, flags, verify_result, &callback_, &request);
if (rv == ERR_IO_PENDING) {
// Cleared in OnVerifyCompletion().
cur_request_ = request;
cur_request_callback_ = callback;
}
return rv;
}
void SingleRequestCertVerifier::OnVerifyCompletion(int result) {
DCHECK(cur_request_ && cur_request_callback_);
CompletionCallback* callback = cur_request_callback_;
// Clear the outstanding request information.
cur_request_ = NULL;
cur_request_callback_ = NULL;
// Call the user's original callback.
callback->Run(result);
}
} // namespace net
DISABLE_RUNNABLE_METHOD_REFCOUNT(net::CertVerifierWorker);
| 29.634855 | 79 | 0.619644 | [
"vector"
] |
4b3e23b4a54576ee6b463c1f472b756912a83118 | 6,124 | cpp | C++ | gnstlib/examples/example.cpp | guillermo-navas-palencia/gnstlib | e4ecc2a2e73ad91326c5e7550cd0164985296ea1 | [
"Apache-2.0"
] | null | null | null | gnstlib/examples/example.cpp | guillermo-navas-palencia/gnstlib | e4ecc2a2e73ad91326c5e7550cd0164985296ea1 | [
"Apache-2.0"
] | null | null | null | gnstlib/examples/example.cpp | guillermo-navas-palencia/gnstlib | e4ecc2a2e73ad91326c5e7550cd0164985296ea1 | [
"Apache-2.0"
] | null | null | null | /* Copyright (C) 2017 A. Gil, G. Navas-Palencia, J. Segura and N. M. Temme
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iomanip>
#include <iostream>
#include <gnstlib.hpp>
void basic_functions()
{
int err = 0;
std::cout << "\n-----------------------Basic Functions-----------------------"
<< std::scientific << std::endl;
std::cout << "expm1x(0.01) = " << GNSTLIB::expm1x(0.01) << std::endl;
std::cout << "log1pexp(3.2) = " << GNSTLIB::log1pexp(3.2) << std::endl;
std::cout << "log1mexp(-1.5) = " << GNSTLIB::log1mexp(-1.5, err)
<< "\terr_id = " << err << std::endl;
std::cout << "powm1(0.9, 0.3) = " << GNSTLIB::powm1(0.9, 0.3, err)
<< "\terr_id = " << err << std::endl;
}
void gamma_functions()
{
int err = 0;
double x, y;
std::complex<double> z;
x = 213.2;
y = 216.9;
std::cout << "\n-----------------------Gamma Functions-----------------------"
<< std::scientific << std::endl;
std::cout.precision(16);
std::cout << "gamma(16.4) = " << GNSTLIB::gamma(16.4, err);
std::cout << "\terr_id = " << err << std::endl;
std::cout << "qgamma(213.2,216.9) = " << GNSTLIB::qgamma(x, y, err)
<< "\terr_id = " << err << std::endl;
std::cout << "gammastar(1431.2) = " << GNSTLIB::gammastar(1431.2, err)
<< "\terr_id = " << err << std::endl;
std::cout << "stirling(131.9) = " << GNSTLIB::stirling(131.9, err)
<< "\terr_id = " << err << std::endl;
z = std::complex<double>(0.0, 16.4);
std::cout << "gamma(16.4i) = " << std::setprecision(4) <<
GNSTLIB::gamma(z, err) << "\terr_id = " << err << std::endl;
z = std::complex<double>(6.0, 15.0);
std::cout << "loggamma(6+15i) = " << std::setprecision(4) <<
GNSTLIB::loggamma(z, err) << "\terr_id = " << err << std::endl;
}
void exponential_integral_functions()
{
int err = 0;
std::complex<double> ci, si, z;
z = std::complex<double>(2.0, 10.0);
std::cout << "\n--------------------Exponential Integrals--------------------"
<< std::scientific << std::endl;
std::cout.precision(16);
std::cout << "ei(2.2) = " << GNSTLIB::ei(2.2, err)
<< "\terr_id = " << err << std::endl;
std::cout << "e1(2.2) = " << GNSTLIB::e1(2.2, err)
<< "\terr_id = " << err << std::endl;
std::cout << "li(200000) = " << GNSTLIB::li(200000, err)
<< "\terr_id = " << err << std::endl;
// compute sine and cosine integral
GNSTLIB::sici(z, si, ci, err);
std::cout << "ci(2+10i) = " << std::setprecision(4) << ci
<< "\terr_id = " << err << std::endl;
std::cout << "si(2+10i) = " << std::setprecision(4) << si
<< "\terr_id = " << err << std::endl;
}
void error_functions()
{
int err = 0;
std::complex<double> z;
z = std::complex<double>(3.2, 6.5);
std::cout << "\n-----------------------Error Functions-----------------------"
<< std::scientific << std::endl;
std::cout.precision(16);
std::cout << "erf(3.7) = " << GNSTLIB::erf(3.7, err)
<< "\terr_id = " << err << std::endl;
std::cout << "erfc(3.7) = " << GNSTLIB::erfc(3.7, err)
<< "\terr_id = " << err << std::endl;
std::cout << "fresnelc(55,9) = " << GNSTLIB::fresnelc(55.9, err)
<< "\terr_id = " << err << std::endl;
std::cout << "fresnels(55,9) = " << GNSTLIB::fresnels(55.9, err)
<< "\terr_id = " << err << std::endl;
std::cout << "faddeeva(3.2+6.5i) = " << std::setprecision(4) <<
GNSTLIB::faddeeva(z, err) << "\terr_id = " << err << std::endl;
}
void incomplete_gamma_functions()
{
int err = 0;
std::cout << "\n----Incomplete Gamma and Generalized Exponential Integral----"
<< std::scientific << std::endl;
std::cout.precision(16);
std::cout << "gammainc_p(2.3,8.3) = " << GNSTLIB::gammainc_p(2.3, 8.3, err)
<< "\terr_id = " << err << std::endl;
std::cout << "gammainc_q(2.3,8.3) = " << GNSTLIB::gammainc_q(2.3, 8.3, err)
<< "\terr_id = " << err << std::endl;
std::cout << "expint(120.2, 12.2) = " << GNSTLIB::expint(120.2, 12.2, err)
<< "\terr_id = " << err << std::endl;
}
void vectorized_functions()
{
std::cout << "\n-------------Example vectorized functions: Gamma-------------"
<< std::scientific << std::endl;
std::cout.precision(16);
const int n = 3;
std::vector<double> v = {1.0, 2.3, 4.3};
std::vector<double> r;
GNSTLIB::gamma_vec(v, r, 0);
for (auto& i:r) {
std::cout << "gamma(" << v[&i-&r[0]] << ") = " << i << std::endl;
}
const double varray[] = {1.0, 2.3, 4.3};
double rarray[n];
GNSTLIB::gamma_vec(n, varray, rarray, 1);
for (int i = 0; i < n; i++)
std::cout << "gamma(" << varray[i] << ") = " << rarray[i] << std::endl;
}
int main()
{
std::cout.precision(16);
std::cout << "GNSTLIB version 0.1 - Release October 2017" << std::endl;
std::cout << "==========================================" << std::endl;
basic_functions();
gamma_functions();
exponential_integral_functions();
error_functions();
incomplete_gamma_functions();
vectorized_functions();
} | 32.748663 | 81 | 0.549967 | [
"vector"
] |
4b3fd0ea0f77ecb014b9ae676754479fc0a6d4cb | 2,848 | cc | C++ | src/data/gradient_index_format.cc | hmchen-github/xgboost | af0cf88921f4d80a2a338e40f2620c9579afa100 | [
"Apache-2.0"
] | null | null | null | src/data/gradient_index_format.cc | hmchen-github/xgboost | af0cf88921f4d80a2a338e40f2620c9579afa100 | [
"Apache-2.0"
] | 1 | 2022-02-01T16:14:41.000Z | 2022-02-01T16:14:41.000Z | src/data/gradient_index_format.cc | hmchen-github/xgboost | af0cf88921f4d80a2a338e40f2620c9579afa100 | [
"Apache-2.0"
] | null | null | null | /*!
* Copyright 2021-2022 XGBoost contributors
*/
#include "sparse_page_writer.h"
#include "gradient_index.h"
#include "histogram_cut_format.h"
namespace xgboost {
namespace data {
class GHistIndexRawFormat : public SparsePageFormat<GHistIndexMatrix> {
public:
bool Read(GHistIndexMatrix* page, dmlc::SeekStream* fi) override {
if (!ReadHistogramCuts(&page->cut, fi)) {
return false;
}
// indptr
fi->Read(&page->row_ptr);
// data
std::vector<uint8_t> data;
if (!fi->Read(&data)) {
return false;
}
page->index.Resize(data.size());
std::copy(data.cbegin(), data.cend(), page->index.begin());
// bin type
// Old gcc doesn't support reading from enum.
std::underlying_type_t<common::BinTypeSize> uint_bin_type{0};
if (!fi->Read(&uint_bin_type)) {
return false;
}
common::BinTypeSize size_type =
static_cast<common::BinTypeSize>(uint_bin_type);
page->index.SetBinTypeSize(size_type);
// hit count
if (!fi->Read(&page->hit_count)) {
return false;
}
if (!fi->Read(&page->max_num_bins)) {
return false;
}
if (!fi->Read(&page->base_rowid)) {
return false;
}
bool is_dense = false;
if (!fi->Read(&is_dense)) {
return false;
}
page->SetDense(is_dense);
if (is_dense) {
page->index.SetBinOffset(page->cut.Ptrs());
}
page->ReadColumnPage(fi);
return true;
}
size_t Write(GHistIndexMatrix const &page, dmlc::Stream *fo) override {
size_t bytes = 0;
bytes += WriteHistogramCuts(page.cut, fo);
// indptr
fo->Write(page.row_ptr);
bytes += page.row_ptr.size() * sizeof(decltype(page.row_ptr)::value_type) +
sizeof(uint64_t);
// data
std::vector<uint8_t> data(page.index.begin(), page.index.end());
fo->Write(data);
bytes += data.size() * sizeof(decltype(data)::value_type) + sizeof(uint64_t);
// bin type
std::underlying_type_t<common::BinTypeSize> uint_bin_type =
page.index.GetBinTypeSize();
fo->Write(uint_bin_type);
bytes += sizeof(page.index.GetBinTypeSize());
// hit count
fo->Write(page.hit_count);
bytes +=
page.hit_count.size() * sizeof(decltype(page.hit_count)::value_type) +
sizeof(uint64_t);
// max_bins, base row, is_dense
fo->Write(page.max_num_bins);
bytes += sizeof(page.max_num_bins);
fo->Write(page.base_rowid);
bytes += sizeof(page.base_rowid);
fo->Write(page.IsDense());
bytes += sizeof(page.IsDense());
bytes += page.WriteColumnPage(fo);
return bytes;
}
};
DMLC_REGISTRY_FILE_TAG(gradient_index_format);
XGBOOST_REGISTER_GHIST_INDEX_PAGE_FORMAT(raw)
.describe("Raw GHistIndex binary data format.")
.set_body([]() { return new GHistIndexRawFormat(); });
} // namespace data
} // namespace xgboost
| 28.767677 | 81 | 0.641503 | [
"vector"
] |
4b4132564924d1ac383498efad8091ecfcee46b7 | 4,116 | cc | C++ | 3rdparty/poppler-library/poppler/DateInfo.cc | PDF2CASH/PDF2CASH_Parser | 8cc8255cc4aff92f98e3a089ba50c3eb24c96446 | [
"MIT"
] | null | null | null | 3rdparty/poppler-library/poppler/DateInfo.cc | PDF2CASH/PDF2CASH_Parser | 8cc8255cc4aff92f98e3a089ba50c3eb24c96446 | [
"MIT"
] | null | null | null | 3rdparty/poppler-library/poppler/DateInfo.cc | PDF2CASH/PDF2CASH_Parser | 8cc8255cc4aff92f98e3a089ba50c3eb24c96446 | [
"MIT"
] | null | null | null | //========================================================================
//
// DateInfo.cc
//
// Copyright (C) 2008, 2018 Albert Astals Cid <aacid@kde.org>
// Copyright (C) 2009 Carlos Garcia Campos <carlosgc@gnome.org>
// Copyright (C) 2015 André Guerreiro <aguerreiro1985@gmail.com>
// Copyright (C) 2015 André Esser <bepandre@hotmail.com>
// Copyright (C) 2016 Adrian Johnson <ajohnson@redneon.com>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
//========================================================================
//
// Based on code from pdfinfo.cc
//
// Copyright 1998-2003 Glyph & Cog, LLC
//
//========================================================================
#if defined (_MSC_VER)
#include "../config.h"
#else
#include "../config.h"
#endif
#include "../goo/glibc.h"
#include "DateInfo.h"
#include <stdio.h>
#include <string.h>
/* See PDF Reference 1.3, Section 3.8.2 for PDF Date representation */
GBool parseDateString(const char *dateString, int *year, int *month, int *day, int *hour, int *minute, int *second, char *tz, int *tzHour, int *tzMinute)
{
if ( dateString == nullptr ) return gFalse;
if ( strlen(dateString) < 2 ) return gFalse;
if ( dateString[0] == 'D' && dateString[1] == ':' )
dateString += 2;
*month = 1;
*day = 1;
*hour = 0;
*minute = 0;
*second = 0;
*tz = 0x00;
*tzHour = 0;
*tzMinute = 0;
if ( sscanf( dateString,
"%4d%2d%2d%2d%2d%2d%c%2d%*c%2d",
year, month, day, hour, minute, second,
tz, tzHour, tzMinute ) > 0 ) {
/* Workaround for y2k bug in Distiller 3 stolen from gpdf, hoping that it won't
* be used after y2.2k */
if ( *year < 1930 && strlen (dateString) > 14)
{
int century, years_since_1900;
if ( sscanf( dateString,
"%2d%3d%2d%2d%2d%2d%2d",
¢ury, &years_since_1900, month, day, hour, minute, second) == 7 )
{
*year = century * 100 + years_since_1900;
}
else
{
return gFalse;
}
}
if (*year <= 0) return gFalse;
return gTrue;
}
return gFalse;
}
// Convert time to PDF date string
GooString *timeToDateString(time_t *timet) {
GooString *dateString;
char s[5];
struct tm *gt;
size_t len;
time_t timep = timet ? *timet : time(nullptr);
struct tm t;
gt = gmtime_r (&timep, &t);
dateString = new GooString ("D:");
/* Year YYYY */
len = strftime (s, sizeof(s), "%Y", gt);
dateString->append (s, len);
/* Month MM */
len = strftime (s, sizeof(s), "%m", gt);
dateString->append (s, len);
/* Day DD */
len = strftime (s, sizeof(s), "%d", gt);
dateString->append (s, len);
/* Hour HH */
len = strftime (s, sizeof(s), "%H", gt);
dateString->append (s, len);
/* Minute mm */
len = strftime (s, sizeof(s), "%M", gt);
dateString->append (s, len);
/* Second SS */
len = strftime (s, sizeof(s), "%S", gt);
dateString->append (s, len);
return dateString;
}
// Convert PDF date string to time. Returns -1 if conversion fails.
time_t dateStringToTime(const GooString *dateString) {
int year, mon, day, hour, min, sec, tz_hour, tz_minute;
char tz;
struct tm tm;
time_t time;
if (!parseDateString (dateString->getCString(), &year, &mon, &day, &hour, &min, &sec, &tz, &tz_hour, &tz_minute))
return -1;
tm.tm_year = year - 1900;
tm.tm_mon = mon - 1;
tm.tm_mday = day;
tm.tm_hour = hour;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_wday = -1;
tm.tm_yday = -1;
tm.tm_isdst = -1; /* 0 = DST off, 1 = DST on, -1 = don't know */
/* compute tm_wday and tm_yday and check date */
time = timegm (&tm);
if (time == (time_t)-1)
return time;
time_t offset = (tz_hour*60 + tz_minute)*60;
if (tz == '-')
offset *= -1;
time -= offset;
return time;
}
| 26.554839 | 153 | 0.538387 | [
"3d"
] |
4b45d99d8161f359d84c12eb6153e6b34f692f9c | 18,104 | hpp | C++ | src/items.hpp | assasinwar9/Barony | c67c01de1168db1c5a2edad98b23cfff9f999187 | [
"FTL",
"Zlib",
"MIT"
] | 373 | 2016-06-28T06:56:46.000Z | 2022-03-23T02:32:54.000Z | src/items.hpp | assasinwar9/Barony | c67c01de1168db1c5a2edad98b23cfff9f999187 | [
"FTL",
"Zlib",
"MIT"
] | 361 | 2016-07-06T19:09:25.000Z | 2022-03-26T14:14:19.000Z | src/items.hpp | addictgamer/Barony | c67c01de1168db1c5a2edad98b23cfff9f999187 | [
"FTL",
"Zlib",
"MIT"
] | 129 | 2016-06-29T09:02:49.000Z | 2022-01-23T09:56:06.000Z | /*-------------------------------------------------------------------------------
BARONY
File: items.hpp
Desc: contains names and definitions for items
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#pragma once
#include "main.hpp"
#include "entity.hpp"
// items
typedef enum ItemType
{
WOODEN_SHIELD,
QUARTERSTAFF,
BRONZE_SWORD,
BRONZE_MACE,
BRONZE_AXE,
BRONZE_SHIELD,
SLING,
IRON_SPEAR,
IRON_SWORD,
IRON_MACE,
IRON_AXE,
IRON_SHIELD,
SHORTBOW,
STEEL_HALBERD,
STEEL_SWORD,
STEEL_MACE,
STEEL_AXE,
STEEL_SHIELD,
STEEL_SHIELD_RESISTANCE,
CROSSBOW,
GLOVES,
GLOVES_DEXTERITY,
BRACERS,
BRACERS_CONSTITUTION,
GAUNTLETS,
GAUNTLETS_STRENGTH,
CLOAK,
CLOAK_MAGICREFLECTION,
CLOAK_INVISIBILITY,
CLOAK_PROTECTION,
LEATHER_BOOTS,
LEATHER_BOOTS_SPEED,
IRON_BOOTS,
IRON_BOOTS_WATERWALKING,
STEEL_BOOTS,
STEEL_BOOTS_LEVITATION,
STEEL_BOOTS_FEATHER,
LEATHER_BREASTPIECE,
IRON_BREASTPIECE,
STEEL_BREASTPIECE,
HAT_PHRYGIAN,
HAT_HOOD,
HAT_WIZARD,
HAT_JESTER,
LEATHER_HELM,
IRON_HELM,
STEEL_HELM,
AMULET_SEXCHANGE,
AMULET_LIFESAVING,
AMULET_WATERBREATHING,
AMULET_MAGICREFLECTION,
AMULET_STRANGULATION,
AMULET_POISONRESISTANCE,
POTION_WATER,
POTION_BOOZE,
POTION_JUICE,
POTION_SICKNESS,
POTION_CONFUSION,
POTION_EXTRAHEALING,
POTION_HEALING,
POTION_CUREAILMENT,
POTION_BLINDNESS,
POTION_RESTOREMAGIC,
POTION_INVISIBILITY,
POTION_LEVITATION,
POTION_SPEED,
POTION_ACID,
POTION_PARALYSIS,
SCROLL_MAIL,
SCROLL_IDENTIFY,
SCROLL_LIGHT,
SCROLL_BLANK,
SCROLL_ENCHANTWEAPON,
SCROLL_ENCHANTARMOR,
SCROLL_REMOVECURSE,
SCROLL_FIRE,
SCROLL_FOOD,
SCROLL_MAGICMAPPING,
SCROLL_REPAIR,
SCROLL_DESTROYARMOR,
SCROLL_TELEPORTATION,
SCROLL_SUMMON,
MAGICSTAFF_LIGHT,
MAGICSTAFF_DIGGING,
MAGICSTAFF_LOCKING,
MAGICSTAFF_MAGICMISSILE,
MAGICSTAFF_OPENING,
MAGICSTAFF_SLOW,
MAGICSTAFF_COLD,
MAGICSTAFF_FIRE,
MAGICSTAFF_LIGHTNING,
MAGICSTAFF_SLEEP,
RING_ADORNMENT,
RING_SLOWDIGESTION,
RING_PROTECTION,
RING_WARNING,
RING_STRENGTH,
RING_CONSTITUTION,
RING_INVISIBILITY,
RING_MAGICRESISTANCE,
RING_CONFLICT,
RING_LEVITATION,
RING_REGENERATION,
RING_TELEPORTATION,
SPELLBOOK_FORCEBOLT,
SPELLBOOK_MAGICMISSILE,
SPELLBOOK_COLD,
SPELLBOOK_FIREBALL,
SPELLBOOK_LIGHT,
SPELLBOOK_REMOVECURSE,
SPELLBOOK_LIGHTNING,
SPELLBOOK_IDENTIFY,
SPELLBOOK_MAGICMAPPING,
SPELLBOOK_SLEEP,
SPELLBOOK_CONFUSE,
SPELLBOOK_SLOW,
SPELLBOOK_OPENING,
SPELLBOOK_LOCKING,
SPELLBOOK_LEVITATION,
SPELLBOOK_INVISIBILITY,
SPELLBOOK_TELEPORTATION,
SPELLBOOK_HEALING,
SPELLBOOK_EXTRAHEALING,
SPELLBOOK_CUREAILMENT,
SPELLBOOK_DIG,
GEM_ROCK,
GEM_LUCK,
GEM_GARNET,
GEM_RUBY,
GEM_JACINTH,
GEM_AMBER,
GEM_CITRINE,
GEM_JADE,
GEM_EMERALD,
GEM_SAPPHIRE,
GEM_AQUAMARINE,
GEM_AMETHYST,
GEM_FLUORITE,
GEM_OPAL,
GEM_DIAMOND,
GEM_JETSTONE,
GEM_OBSIDIAN,
GEM_GLASS,
TOOL_PICKAXE,
TOOL_TINOPENER,
TOOL_MIRROR,
TOOL_LOCKPICK,
TOOL_SKELETONKEY,
TOOL_TORCH,
TOOL_LANTERN,
TOOL_BLINDFOLD,
TOOL_TOWEL,
TOOL_GLASSES,
TOOL_BEARTRAP,
FOOD_BREAD,
FOOD_CREAMPIE,
FOOD_CHEESE,
FOOD_APPLE,
FOOD_MEAT,
FOOD_FISH,
FOOD_TIN,
READABLE_BOOK,
SPELL_ITEM,
ARTIFACT_SWORD,
ARTIFACT_MACE,
ARTIFACT_SPEAR,
ARTIFACT_AXE,
ARTIFACT_BOW,
ARTIFACT_BREASTPIECE,
ARTIFACT_HELM,
ARTIFACT_BOOTS,
ARTIFACT_CLOAK,
ARTIFACT_GLOVES,
CRYSTAL_BREASTPIECE,
CRYSTAL_HELM,
CRYSTAL_BOOTS,
CRYSTAL_SHIELD,
CRYSTAL_GLOVES,
VAMPIRE_DOUBLET,
WIZARD_DOUBLET,
HEALER_DOUBLET,
MIRROR_SHIELD,
BRASS_KNUCKLES,
IRON_KNUCKLES,
SPIKED_GAUNTLETS,
FOOD_TOMALLEY,
TOOL_CRYSTALSHARD,
CRYSTAL_SWORD,
CRYSTAL_SPEAR,
CRYSTAL_BATTLEAXE,
CRYSTAL_MACE,
BRONZE_TOMAHAWK,
IRON_DAGGER,
STEEL_CHAKRAM,
CRYSTAL_SHURIKEN,
CLOAK_BLACK,
MAGICSTAFF_STONEBLOOD,
MAGICSTAFF_BLEED,
MAGICSTAFF_SUMMON,
TOOL_BLINDFOLD_FOCUS,
TOOL_BLINDFOLD_TELEPATHY,
SPELLBOOK_SUMMON,
SPELLBOOK_STONEBLOOD,
SPELLBOOK_BLEED,
SPELLBOOK_REFLECT_MAGIC,
SPELLBOOK_ACID_SPRAY,
SPELLBOOK_STEAL_WEAPON,
SPELLBOOK_DRAIN_SOUL,
SPELLBOOK_VAMPIRIC_AURA,
SPELLBOOK_CHARM_MONSTER,
POTION_EMPTY,
ARTIFACT_ORB_BLUE,
ARTIFACT_ORB_RED,
ARTIFACT_ORB_PURPLE,
ARTIFACT_ORB_GREEN,
TUNIC,
HAT_FEZ,
MAGICSTAFF_CHARM,
POTION_POLYMORPH,
FOOD_BLOOD,
CLOAK_BACKPACK,
TOOL_ALEMBIC,
POTION_FIRESTORM,
POTION_ICESTORM,
POTION_THUNDERSTORM,
POTION_STRENGTH,
SUEDE_BOOTS,
SUEDE_GLOVES,
CLOAK_SILVER,
HAT_HOOD_SILVER,
HAT_HOOD_RED,
SILVER_DOUBLET,
SPELLBOOK_REVERT_FORM,
SPELLBOOK_RAT_FORM,
SPELLBOOK_SPIDER_FORM,
SPELLBOOK_TROLL_FORM,
SPELLBOOK_IMP_FORM,
SPELLBOOK_SPRAY_WEB,
SPELLBOOK_POISON,
SPELLBOOK_SPEED,
SPELLBOOK_FEAR,
SPELLBOOK_STRIKE,
SPELLBOOK_DETECT_FOOD,
SPELLBOOK_WEAKNESS,
MASK_SHAMAN,
SPELLBOOK_AMPLIFY_MAGIC,
SPELLBOOK_SHADOW_TAG,
SPELLBOOK_TELEPULL,
SPELLBOOK_DEMON_ILLU,
SPELLBOOK_TROLLS_BLOOD,
SPELLBOOK_SALVAGE,
TOOL_WHIP,
SPELLBOOK_FLUTTER,
SPELLBOOK_DASH,
SPELLBOOK_SELF_POLYMORPH,
SPELLBOOK_9,
SPELLBOOK_10,
MAGICSTAFF_POISON,
TOOL_METAL_SCRAP,
TOOL_MAGIC_SCRAP,
TOOL_TINKERING_KIT,
TOOL_SENTRYBOT,
TOOL_DETONATOR_CHARGE,
TOOL_BOMB,
TOOL_SLEEP_BOMB,
TOOL_FREEZE_BOMB,
TOOL_TELEPORT_BOMB,
TOOL_GYROBOT,
TOOL_SPELLBOT,
TOOL_DECOY,
TOOL_DUMMYBOT,
MACHINIST_APRON,
ENCHANTED_FEATHER,
PUNISHER_HOOD,
SCROLL_CHARGING,
QUIVER_SILVER,
QUIVER_PIERCE,
QUIVER_LIGHTWEIGHT,
QUIVER_FIRE,
QUIVER_KNOCKBACK,
QUIVER_CRYSTAL,
QUIVER_HUNTING,
LONGBOW,
COMPOUND_BOW,
HEAVY_CROSSBOW,
BOOMERANG,
SCROLL_CONJUREARROW
} ItemType;
const int NUMITEMS = 287;
//NOTE: If you change this, make sure to update NUMCATEGORIES in game.h to reflect the total number of categories. Not doing that will make bad things happen.
typedef enum Category
{
WEAPON,
ARMOR,
AMULET,
POTION,
SCROLL,
MAGICSTAFF,
RING,
SPELLBOOK,
GEM,
THROWN,
TOOL,
FOOD,
BOOK,
SPELL_CAT
} Category;
typedef enum Status
{
BROKEN,
DECREPIT,
WORN,
SERVICABLE,
EXCELLENT
} Status;
typedef enum EquipmentType
{
TYPE_NONE,
TYPE_HELM,
TYPE_HAT,
TYPE_BREASTPIECE,
TYPE_BOOTS,
TYPE_SHIELD,
TYPE_GLOVES,
TYPE_CLOAK,
TYPE_RING,
TYPE_AMULET,
TYPE_MASK,
TYPE_SWORD,
TYPE_AXE,
TYPE_SPEAR,
TYPE_MACE,
TYPE_BOW,
TYPE_PROJECTILE,
TYPE_OFFHAND
} EquipmentType;
class SummonProperties
{
//TODO: Store monster stats.
public:
SummonProperties();
~SummonProperties() noexcept;
SummonProperties(const SummonProperties& other) = default;
SummonProperties(SummonProperties&& other) noexcept = default;
SummonProperties& operator=(const SummonProperties& other) = default;
SummonProperties& operator=(SummonProperties&& other) noexcept = default;
protected:
private:
};
// inventory item structure
class Item
{
public:
ItemType type;
Status status;
Sint16 beatitude; // blessedness
Sint16 count; // how many of item
Uint32 appearance; // large random static number
bool identified; // if the item is identified or not
Uint32 uid; // item uid
Sint32 x, y; // slot coordinates in item grid
Uint32 ownerUid; // original owner
Uint32 interactNPCUid; // if NPC is interacting with item
bool forcedPickupByPlayer; // player used interact on NPC with item on floor
bool isDroppable; // if item should drop on death
// weight, category and other generic info reported by function calls
node_t* node;
/*
* Gems use this to store information about what sort of creature they contain.
*/
//SummonProperties *captured_monster;
//I wish there was an easy way to do this.
//As it stands, no item destructor is called , so this would lead to a memory leak.
//And tracking down every time an item gets deleted and calling an item destructor would be quite a doozey.
char* description() const;
char* getName() const;
//General Functions.
Sint32 weaponGetAttack(const Stat* wielder = nullptr) const; //Returns the tohit of the weapon.
Sint32 armorGetAC(const Stat* wielder = nullptr) const;
bool canUnequip(const Stat* wielder = nullptr); //Returns true if the item can be unequipped (not cursed), false if it can't (cursed).
int buyValue(int player) const;
int sellValue(int player) const;
bool usableWhileShapeshifted(const Stat* wielder = nullptr) const;
char* getScrollLabel() const;
void apply(int player, Entity* entity);
void applyLockpickToWall(int player, int x, int y) const;
//Item usage functions.
void applySkeletonKey(int player, Entity& entity);
void applyLockpick(int player, Entity& entity);
void applyOrb(int player, ItemType type, Entity& entity);
void applyEmptyPotion(int player, Entity& entity);
//-----ITEM COMPARISON FUNCTIONS-----
/*
* Returns which weapon hits harder.
*/
static bool isThisABetterWeapon(const Item& newWeapon, const Item* weaponAlreadyHave);
static bool isThisABetterArmor(const Item& newArmor, const Item* armorAlreadyHave); //Also checks shields.
bool shouldItemStack(int player) const;
bool isShield() const;
enum ItemBombPlacement : int
{
BOMB_FLOOR,
BOMB_WALL,
BOMB_CHEST,
BOMB_DOOR
};
enum ItemBombFacingDirection : int
{
BOMB_UP,
BOMB_NORTH,
BOMB_EAST,
BOMB_SOUTH,
BOMB_WEST
};
enum ItemBombTriggerType : int
{
BOMB_TRIGGER_ENEMIES,
BOMB_TELEPORT_RECEIVER,
BOMB_TRIGGER_ALL
};
void applyBomb(Entity* parent, ItemType type, ItemBombPlacement placement, ItemBombFacingDirection dir, Entity* thrown, Entity* onEntity);
void applyTinkeringCreation(Entity* parent, Entity* thrown);
bool unableToEquipDueToSwapWeaponTimer(const int player) const;
bool tinkeringBotIsMaxHealth() const;
bool isTinkeringItemWithThrownLimit() const;
};
extern Uint32 itemuids;
// item generic
class ItemGeneric
{
public:
char* name_identified; // identified item name
char* name_unidentified; // unidentified item name
int index; // world model
int fpindex; // first person model
int variations; // number of model variations
int weight; // weight per item
int value; // value per item
list_t images; // item image filenames (inventory)
list_t surfaces; // item image surfaces (inventory)
Category category; // item category
int level; // item level for random generation
};
extern ItemGeneric items[NUMITEMS];
//----------Item usage functions----------
bool item_PotionWater(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionBooze(Item*& item, Entity* entity, Entity* usedBy, bool shouldConsumeItem = true);
bool item_PotionJuice(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionSickness(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionConfusion(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionCureAilment(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionBlindness(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionHealing(Item*& item, Entity* entity, Entity* usedBy, bool shouldConsumeItem = true);
bool item_PotionExtraHealing(Item*& item, Entity* entity, Entity* usedBy, bool shouldConsumeItem = true);
bool item_PotionRestoreMagic(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionInvisibility(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionLevitation(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionSpeed(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionStrength(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionAcid(Item*& item, Entity* entity, Entity* usedBy);
bool item_PotionUnstableStorm(Item*& item, Entity* entity, Entity* usedBy, Entity* thrownPotion);
bool item_PotionParalysis(Item*& item, Entity* entity, Entity* usedBy);
Entity* item_PotionPolymorph(Item*& item, Entity* entity, Entity* usedBy);
void item_ScrollMail(Item* item, int player);
void item_ScrollIdentify(Item* item, int player);
void item_ScrollLight(Item* item, int player);
void item_ScrollBlank(Item* item, int player);
void item_ScrollEnchantWeapon(Item* item, int player);
void item_ScrollEnchantArmor(Item* item, int player);
void item_ScrollRemoveCurse(Item* item, int player);
bool item_ScrollFire(Item* item, int player); // return true if exploded into fire.
void item_ScrollFood(Item* item, int player);
void item_ScrollConjureArrow(Item* item, int player);
void item_ScrollMagicMapping(Item* item, int player);
void item_ScrollRepair(Item* item, int player);
void item_ScrollDestroyArmor(Item* item, int player);
void item_ScrollTeleportation(Item* item, int player);
void item_ScrollSummon(Item* item, int player);
void item_AmuletSexChange(Item* item, int player);
void item_ToolTowel(Item*& item, int player);
void item_ToolTinOpener(Item* item, int player);
void item_ToolMirror(Item*& item, int player);
void item_ToolBeartrap(Item*& item, int player);
void item_Food(Item*& item, int player);
void item_FoodTin(Item*& item, int player);
void item_FoodAutomaton(Item*& item, int player);
void item_Gem(Item* item, int player);
void item_Spellbook(Item*& item, int player);
//General functions.
Item* newItem(ItemType type, Status status, Sint16 beatitude, Sint16 count, Uint32 appearance, bool identified, list_t* inventory);
Item* uidToItem(Uint32 uid);
ItemType itemCurve(Category cat);
ItemType itemLevelCurve(Category cat, int minLevel, int maxLevel);
Item* newItemFromEntity(const Entity* entity); //Make sure to call free(item).
Entity* dropItemMonster(Item* item, Entity* monster, Stat* monsterStats, Sint16 count = 1);
Item** itemSlot(Stat* myStats, Item* item);
enum Category itemCategory(const Item* item);
Sint32 itemModel(const Item* item);
Sint32 itemModelFirstperson(const Item* item);
SDL_Surface* itemSprite(Item* item);
void consumeItem(Item*& item, int player); //NOTE: Items have to be unequipped before calling this function on them. NOTE: THIS CAN FREE THE ITEM POINTER. Sets item to nullptr if it does.
bool dropItem(Item* item, int player, bool notifyMessage = true); // return true on free'd item
void useItem(Item* item, int player, Entity* usedBy = nullptr);
enum EquipItemResult : int
{
EQUIP_ITEM_FAIL_CANT_UNEQUIP,
EQUIP_ITEM_SUCCESS_NEWITEM,
EQUIP_ITEM_SUCCESS_UPDATE_QTY,
EQUIP_ITEM_SUCCESS_UNEQUIP
};
enum EquipItemSendToServerSlot : int
{
EQUIP_ITEM_SLOT_WEAPON,
EQUIP_ITEM_SLOT_SHIELD,
EQUIP_ITEM_SLOT_MASK,
EQUIP_ITEM_SLOT_HELM,
EQUIP_ITEM_SLOT_GLOVES,
EQUIP_ITEM_SLOT_BOOTS,
EQUIP_ITEM_SLOT_BREASTPLATE,
EQUIP_ITEM_SLOT_CLOAK,
EQUIP_ITEM_SLOT_AMULET,
EQUIP_ITEM_SLOT_RING
};
void playerTryEquipItemAndUpdateServer(const int player, Item* item, bool checkInventorySpaceForPaperDoll);
void clientSendEquipUpdateToServer(EquipItemSendToServerSlot slot, EquipItemResult equipType, int player,
ItemType type, Status status, Sint16 beatitude, int count, Uint32 appearance, bool identified);
void clientUnequipSlotAndUpdateServer(const int player, EquipItemSendToServerSlot slot, Item* item);
EquipItemResult equipItem(Item* item, Item** slot, int player);
Item* itemPickup(int player, Item* item);
bool itemIsEquipped(const Item* item, int player);
bool shouldInvertEquipmentBeatitude(const Stat* wielder);
bool isItemEquippableInShieldSlot(const Item* item);
bool itemIsConsumableByAutomaton(const Item& item);
extern const real_t potionDamageSkillMultipliers[6];
extern const real_t thrownDamageSkillMultipliers[6];
extern std::mt19937 enchantedFeatherScrollSeed;
extern std::vector<int> enchantedFeatherScrollsShuffled;
static const std::vector<int> enchantedFeatherScrollsFixedList =
{
SCROLL_BLANK,
SCROLL_MAIL,
SCROLL_DESTROYARMOR,
SCROLL_DESTROYARMOR,
SCROLL_DESTROYARMOR,
SCROLL_FIRE,
SCROLL_FIRE,
SCROLL_FIRE,
SCROLL_LIGHT,
SCROLL_LIGHT,
SCROLL_SUMMON,
SCROLL_SUMMON,
SCROLL_IDENTIFY,
SCROLL_IDENTIFY,
SCROLL_REMOVECURSE,
SCROLL_CONJUREARROW,
SCROLL_FOOD,
SCROLL_FOOD,
SCROLL_TELEPORTATION,
SCROLL_TELEPORTATION,
SCROLL_CHARGING,
SCROLL_REPAIR,
SCROLL_MAGICMAPPING,
SCROLL_ENCHANTWEAPON,
SCROLL_ENCHANTARMOR
};
static const int ENCHANTED_FEATHER_MAX_DURABILITY = 101;
static const int QUIVER_MAX_AMMO_QTY = 51;
static const int SCRAP_MAX_STACK_QTY = 101;
//-----ITEM COMPARISON FUNCS-----
/*
* Only compares items of the same type.
*/
int itemCompare(const Item* item1, const Item* item2, bool checkAppearance);
/*
* Returns true if potion is harmful to the player.
*/
bool isPotionBad(const Item& potion);
bool isRangedWeapon(const Item& item);
bool isMeleeWeapon(const Item& item);
bool itemIsThrowableTinkerTool(const Item* item);
void createCustomInventory(Stat* stats, int itemLimit);
void copyItem(Item* itemToSet, const Item* itemToCopy);
bool swapMonsterWeaponWithInventoryItem(Entity* my, Stat* myStats, node_t* inventoryNode, bool moveStack, bool overrideCursed);
bool monsterUnequipSlot(Stat* myStats, Item** slot, Item* itemToUnequip);
bool monsterUnequipSlotFromCategory(Stat* myStats, Item** slot, Category cat);
node_t* itemNodeInInventory(const Stat* myStats, ItemType itemToFind, Category cat);
node_t* spellbookNodeInInventory(const Stat* myStats, int spellIDToFind);
node_t* getRangedWeaponItemNodeInInventory(const Stat* myStats, bool includeMagicstaff);
node_t* getMeleeWeaponItemNodeInInventory(const Stat* myStats);
ItemType itemTypeWithinGoldValue(int cat, int minValue, int maxValue);
bool itemSpriteIsQuiverThirdPersonModel(int sprite);
bool itemSpriteIsQuiverBaseThirdPersonModel(int sprite);
bool itemTypeIsQuiver(ItemType type);
bool itemSpriteIsBreastpiece(int sprite);
real_t rangedAttackGetSpeedModifier(const Stat* myStats);
bool rangedWeaponUseQuiverOnAttack(const Stat* myStats);
real_t getArtifactWeaponEffectChance(ItemType type, Stat& wielder, real_t* effectAmount);
void updateHungerMessages(Entity* my, Stat* myStats, Item* eaten);
bool playerCanSpawnMoreTinkeringBots(const Stat* myStats);
int maximumTinkeringBotsCanBeDeployed(const Stat* myStats);
extern bool overrideTinkeringLimit;
extern int decoyBoxRange;
// unique monster item appearance to avoid being dropped on death.
static const int MONSTER_ITEM_UNDROPPABLE_APPEARANCE = 1234567890;
static const int ITEM_TINKERING_APPEARANCE = 987654320;
static const int ITEM_GENERATED_QUIVER_APPEARANCE = 1122334455;
bool loadItemLists(); | 27.639695 | 187 | 0.785075 | [
"vector",
"model"
] |
4b4601889bb698f75663aa0ec14ff4598ab449d8 | 16,696 | cc | C++ | third_party/blink/renderer/platform/loader/cors/cors.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/loader/cors/cors.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/loader/cors/cors.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include <memory>
#include <string>
#include <utility>
#include "net/http/http_util.h"
#include "services/network/public/cpp/cors/cors.h"
#include "services/network/public/cpp/cors/preflight_cache.h"
#include "services/network/public/cpp/request_mode.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/platform/loader/cors/cors_error_string.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
#include "third_party/blink/renderer/platform/network/http_header_map.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/thread_specific.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace blink {
namespace {
base::Optional<std::string> GetHeaderValue(const HTTPHeaderMap& header_map,
const AtomicString& header_name) {
if (header_map.Contains(header_name)) {
return header_map.Get(header_name).Latin1();
}
return base::nullopt;
}
network::cors::PreflightCache& GetPerThreadPreflightCache() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadSpecific<network::cors::PreflightCache>,
cache, ());
return *cache;
}
base::Optional<std::string> GetOptionalHeaderValue(
const HTTPHeaderMap& header_map,
const AtomicString& header_name) {
const AtomicString& result = header_map.Get(header_name);
if (result.IsNull())
return base::nullopt;
return result.Ascii();
}
std::unique_ptr<net::HttpRequestHeaders> CreateNetHttpRequestHeaders(
const HTTPHeaderMap& header_map) {
std::unique_ptr<net::HttpRequestHeaders> request_headers =
std::make_unique<net::HttpRequestHeaders>();
for (HTTPHeaderMap::const_iterator i = header_map.begin(),
end = header_map.end();
i != end; ++i) {
DCHECK(!i->key.IsNull());
DCHECK(!i->value.IsNull());
request_headers->SetHeader(i->key.Ascii(), i->value.Ascii());
}
return request_headers;
}
url::Origin AsUrlOrigin(const SecurityOrigin& origin) {
// "file:" origin is treated like an opaque unique origin when
// allow-file-access-from-files is not specified. Such origin is not
// opaque (i.e., IsOpaque() returns false) but still serializes to
// "null".
return origin.ToString() == "null" ? url::Origin() : origin.ToUrlOrigin();
}
// A parser for the value of the Access-Control-Expose-Headers header.
class HTTPHeaderNameListParser {
STACK_ALLOCATED();
public:
explicit HTTPHeaderNameListParser(const String& value)
: value_(value), pos_(0) {}
// Tries parsing |value_| expecting it to be conforming to the #field-name
// ABNF rule defined in RFC 7230. Returns with the field-name entries stored
// in |output| when successful. Otherwise, returns with |output| kept empty.
//
// |output| must be empty.
void Parse(HTTPHeaderSet& output) {
DCHECK(output.empty());
while (true) {
ConsumeSpaces();
if (pos_ == value_.length() && !output.empty()) {
output.insert(std::string());
return;
}
size_t token_start = pos_;
ConsumeTokenChars();
size_t token_size = pos_ - token_start;
if (token_size == 0) {
output.clear();
return;
}
output.insert(value_.Substring(token_start, token_size).Ascii());
ConsumeSpaces();
if (pos_ == value_.length())
return;
if (value_[pos_] == ',') {
++pos_;
} else {
output.clear();
return;
}
}
}
private:
// Consumes zero or more spaces (SP and HTAB) from value_.
void ConsumeSpaces() {
while (true) {
if (pos_ == value_.length())
return;
UChar c = value_[pos_];
if (c != ' ' && c != '\t')
return;
++pos_;
}
}
// Consumes zero or more tchars from value_.
void ConsumeTokenChars() {
while (true) {
if (pos_ == value_.length())
return;
UChar c = value_[pos_];
if (c > 0x7F || !net::HttpUtil::IsTokenChar(c))
return;
++pos_;
}
}
const String value_;
size_t pos_;
};
} // namespace
namespace cors {
base::Optional<network::CorsErrorStatus> CheckAccess(
const KURL& response_url,
const HTTPHeaderMap& response_header,
network::mojom::CredentialsMode credentials_mode,
const SecurityOrigin& origin) {
return network::cors::CheckAccess(
response_url,
GetHeaderValue(response_header, http_names::kAccessControlAllowOrigin),
GetHeaderValue(response_header,
http_names::kAccessControlAllowCredentials),
credentials_mode, AsUrlOrigin(origin));
}
base::Optional<network::CorsErrorStatus> CheckPreflightAccess(
const KURL& response_url,
const int response_status_code,
const HTTPHeaderMap& response_header,
network::mojom::CredentialsMode actual_credentials_mode,
const SecurityOrigin& origin) {
return network::cors::CheckPreflightAccess(
response_url, response_status_code,
GetHeaderValue(response_header, http_names::kAccessControlAllowOrigin),
GetHeaderValue(response_header,
http_names::kAccessControlAllowCredentials),
actual_credentials_mode, AsUrlOrigin(origin));
}
base::Optional<network::CorsErrorStatus> CheckRedirectLocation(
const KURL& url,
network::mojom::RequestMode request_mode,
const SecurityOrigin* origin,
CorsFlag cors_flag) {
base::Optional<url::Origin> origin_to_pass;
if (origin)
origin_to_pass = AsUrlOrigin(*origin);
// Blink-side implementations rewrite the origin instead of setting the
// tainted flag.
return network::cors::CheckRedirectLocation(
url, request_mode, origin_to_pass, cors_flag == CorsFlag::Set, false);
}
base::Optional<network::CorsErrorStatus> CheckExternalPreflight(
const HTTPHeaderMap& response_header) {
return network::cors::CheckExternalPreflight(
GetHeaderValue(response_header, http_names::kAccessControlAllowExternal));
}
bool IsCorsEnabledRequestMode(network::mojom::RequestMode request_mode) {
return network::cors::IsCorsEnabledRequestMode(request_mode);
}
base::Optional<network::CorsErrorStatus> EnsurePreflightResultAndCacheOnSuccess(
const HTTPHeaderMap& response_header_map,
const String& origin,
const KURL& request_url,
const String& request_method,
const HTTPHeaderMap& request_header_map,
network::mojom::CredentialsMode request_credentials_mode) {
DCHECK(!origin.IsNull());
DCHECK(!request_method.IsNull());
base::Optional<network::mojom::CorsError> error;
std::unique_ptr<network::cors::PreflightResult> result =
network::cors::PreflightResult::Create(
request_credentials_mode,
GetOptionalHeaderValue(response_header_map,
http_names::kAccessControlAllowMethods),
GetOptionalHeaderValue(response_header_map,
http_names::kAccessControlAllowHeaders),
GetOptionalHeaderValue(response_header_map,
http_names::kAccessControlMaxAge),
&error);
if (error)
return network::CorsErrorStatus(*error);
base::Optional<network::CorsErrorStatus> status;
status = result->EnsureAllowedCrossOriginMethod(request_method.Ascii());
if (status)
return status;
// |is_revalidating| is not needed for blink-side CORS.
constexpr bool is_revalidating = false;
status = result->EnsureAllowedCrossOriginHeaders(
*CreateNetHttpRequestHeaders(request_header_map), is_revalidating);
if (status)
return status;
GetPerThreadPreflightCache().AppendEntry(
url::Origin::Create(GURL(origin.Ascii())), request_url,
net::NetworkIsolationKey(), std::move(result));
return base::nullopt;
}
bool CheckIfRequestCanSkipPreflight(
const String& origin,
const KURL& url,
network::mojom::CredentialsMode credentials_mode,
const String& method,
const HTTPHeaderMap& request_header_map) {
DCHECK(!origin.IsNull());
DCHECK(!method.IsNull());
// |is_revalidating| is not needed for blink-side CORS.
constexpr bool is_revalidating = false;
return GetPerThreadPreflightCache().CheckIfRequestCanSkipPreflight(
url::Origin::Create(GURL(origin.Ascii())), url,
net::NetworkIsolationKey(), credentials_mode, method.Ascii(),
*CreateNetHttpRequestHeaders(request_header_map), is_revalidating);
}
// Keep this in sync with the identical function
// network::cors::CorsURLLoader::CalculateResponseTainting.
//
// This is the same as that function except using KURL and SecurityOrigin
// instead of GURL and url::Origin. We can't combine them because converting
// SecurityOrigin to url::Origin loses information about origins that are
// allowed by SecurityPolicy.
//
// This function also doesn't use a |tainted_origin| flag because Blink loaders
// mutate the origin instead of using such a flag.
network::mojom::FetchResponseType CalculateResponseTainting(
const KURL& url,
network::mojom::RequestMode request_mode,
const SecurityOrigin* origin,
const SecurityOrigin* isolated_world_origin,
CorsFlag cors_flag) {
if (url.ProtocolIsData())
return network::mojom::FetchResponseType::kBasic;
if (cors_flag == CorsFlag::Set) {
DCHECK(IsCorsEnabledRequestMode(request_mode));
return network::mojom::FetchResponseType::kCors;
}
if (!origin) {
// This is actually not defined in the fetch spec, but in this case CORS
// is disabled so no one should care this value.
return network::mojom::FetchResponseType::kBasic;
}
if (request_mode == network::mojom::RequestMode::kNoCors) {
bool can_request = origin->CanRequest(url);
if (!can_request && isolated_world_origin)
can_request = isolated_world_origin->CanRequest(url);
if (!can_request)
return network::mojom::FetchResponseType::kOpaque;
}
return network::mojom::FetchResponseType::kBasic;
}
bool CalculateCredentialsFlag(
network::mojom::CredentialsMode credentials_mode,
network::mojom::FetchResponseType response_tainting) {
return network::cors::CalculateCredentialsFlag(credentials_mode,
response_tainting);
}
bool IsCorsSafelistedMethod(const String& method) {
DCHECK(!method.IsNull());
return network::cors::IsCorsSafelistedMethod(method.Latin1());
}
bool IsCorsSafelistedContentType(const String& media_type) {
return network::cors::IsCorsSafelistedContentType(media_type.Latin1());
}
bool IsNoCorsSafelistedHeaderName(const String& name) {
DCHECK(!name.IsNull());
return network::cors::IsNoCorsSafelistedHeaderName(name.Latin1());
}
bool IsPrivilegedNoCorsHeaderName(const String& name) {
DCHECK(!name.IsNull());
return network::cors::IsPrivilegedNoCorsHeaderName(name.Latin1());
}
bool IsNoCorsSafelistedHeader(const String& name, const String& value) {
DCHECK(!name.IsNull());
DCHECK(!value.IsNull());
return network::cors::IsNoCorsSafelistedHeader(name.Latin1(), value.Latin1());
}
Vector<String> CorsUnsafeRequestHeaderNames(const HTTPHeaderMap& headers) {
net::HttpRequestHeaders::HeaderVector in;
for (const auto& entry : headers) {
in.push_back(net::HttpRequestHeaders::HeaderKeyValuePair(
entry.key.Latin1(), entry.value.Latin1()));
}
Vector<String> header_names;
for (const auto& name : network::cors::CorsUnsafeRequestHeaderNames(in))
header_names.push_back(WebString::FromLatin1(name));
return header_names;
}
bool IsForbiddenHeaderName(const String& name) {
return !net::HttpUtil::IsSafeHeader(name.Latin1());
}
bool ContainsOnlyCorsSafelistedHeaders(const HTTPHeaderMap& header_map) {
Vector<String> header_names = CorsUnsafeRequestHeaderNames(header_map);
return header_names.IsEmpty();
}
bool ContainsOnlyCorsSafelistedOrForbiddenHeaders(
const HTTPHeaderMap& headers) {
Vector<String> header_names;
net::HttpRequestHeaders::HeaderVector in;
for (const auto& entry : headers) {
in.push_back(net::HttpRequestHeaders::HeaderKeyValuePair(
entry.key.Latin1(), entry.value.Latin1()));
}
// |is_revalidating| is not needed for blink-side CORS.
constexpr bool is_revalidating = false;
return network::cors::CorsUnsafeNotForbiddenRequestHeaderNames(
in, is_revalidating)
.empty();
}
bool IsOkStatus(int status) {
return network::cors::IsOkStatus(status);
}
bool CalculateCorsFlag(const KURL& url,
const SecurityOrigin* initiator_origin,
const SecurityOrigin* isolated_world_origin,
network::mojom::RequestMode request_mode) {
if (request_mode == network::mojom::RequestMode::kNavigate ||
request_mode == network::mojom::RequestMode::kNoCors) {
return false;
}
// CORS needs a proper origin (including a unique opaque origin). If the
// request doesn't have one, CORS will not work.
DCHECK(initiator_origin);
if (initiator_origin->CanReadContent(url))
return false;
if (isolated_world_origin && isolated_world_origin->CanReadContent(url))
return false;
return true;
}
HTTPHeaderSet ExtractCorsExposedHeaderNamesList(
network::mojom::CredentialsMode credentials_mode,
const ResourceResponse& response) {
// If a response was fetched via a service worker, it will always have
// CorsExposedHeaderNames set from the Access-Control-Expose-Headers header.
// For requests that didn't come from a service worker, just parse the CORS
// header.
if (response.WasFetchedViaServiceWorker()) {
HTTPHeaderSet header_set;
for (const auto& header : response.CorsExposedHeaderNames())
header_set.insert(header.Ascii());
return header_set;
}
HTTPHeaderSet header_set;
HTTPHeaderNameListParser parser(
response.HttpHeaderField(http_names::kAccessControlExposeHeaders));
parser.Parse(header_set);
if (credentials_mode != network::mojom::CredentialsMode::kInclude &&
header_set.find("*") != header_set.end()) {
header_set.clear();
for (const auto& header : response.HttpHeaderFields())
header_set.insert(header.key.Ascii());
}
return header_set;
}
bool IsCorsSafelistedResponseHeader(const String& name) {
// https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name
// TODO(dcheng): Consider using a flat_set here with a transparent comparator.
DEFINE_THREAD_SAFE_STATIC_LOCAL(HTTPHeaderSet,
allowed_cross_origin_response_headers,
({
"cache-control",
"content-language",
"content-length",
"content-type",
"expires",
"last-modified",
"pragma",
}));
return allowed_cross_origin_response_headers.find(name.Ascii()) !=
allowed_cross_origin_response_headers.end();
}
// In the spec, https://fetch.spec.whatwg.org/#ref-for-concept-request-mode,
// No-CORS mode is highly discouraged from using it for new features. Only
// legacy usages for backward compatibility are allowed except for well-designed
// usages over the fetch API.
bool IsNoCorsAllowedContext(mojom::RequestContextType context) {
switch (context) {
case mojom::RequestContextType::AUDIO:
case mojom::RequestContextType::FAVICON:
case mojom::RequestContextType::FETCH:
case mojom::RequestContextType::IMAGE:
case mojom::RequestContextType::OBJECT:
case mojom::RequestContextType::PLUGIN:
case mojom::RequestContextType::SCRIPT:
case mojom::RequestContextType::SHARED_WORKER:
case mojom::RequestContextType::VIDEO:
case mojom::RequestContextType::WORKER:
return true;
default:
return false;
}
}
} // namespace cors
} // namespace blink
| 34.711019 | 80 | 0.702324 | [
"object",
"vector"
] |
4b490a9ab724bc1b1db07b450383b9eb7fbf5f1b | 4,371 | cpp | C++ | src/common/transformations/src/transformations/common_optimizations/split_squeeze_concat_fusion.cpp | artkuli/openvino | eb2fb5bf7df36ae55e3251816999b801ce053335 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/common/transformations/src/transformations/common_optimizations/split_squeeze_concat_fusion.cpp | artkuli/openvino | eb2fb5bf7df36ae55e3251816999b801ce053335 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/common/transformations/src/transformations/common_optimizations/split_squeeze_concat_fusion.cpp | tuxedcat/openvino | 5939cb1b363ebb56b73c2ad95d8899961a084677 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "transformations/common_optimizations/split_squeeze_concat_fusion.hpp"
#include <memory>
#include <ngraph/opsets/opset7.hpp>
#include <ngraph/pattern/op/wrap_type.hpp>
#include <ngraph/rt_info.hpp>
#include <numeric>
#include <vector>
#include "itt.hpp"
ngraph::pass::SplitSqueezeConcatFusion::SplitSqueezeConcatFusion() {
MATCHER_SCOPE(SplitSqueezeConcatFusion);
// Detect only concat, because we don't know how many inputs will go into concat
auto concat_pattern = ngraph::pattern::wrap_type<ngraph::opset7::Concat>();
ngraph::matcher_pass_callback callback = [=](ngraph::pattern::Matcher& m) {
const auto& pattern_to_output = m.get_pattern_value_map();
auto concat = std::dynamic_pointer_cast<ngraph::opset7::Concat>(
pattern_to_output.at(concat_pattern).get_node_shared_ptr());
if (!concat)
return false;
NodeVector nodes_to_delete{concat};
int64_t axis_value = 0;
std::shared_ptr<ngraph::opset7::Split> split;
const auto& concat_inputs = concat->input_values();
if (concat_inputs.empty())
return false;
for (size_t i = 0; i < concat_inputs.size(); i++) {
auto squeeze = std::dynamic_pointer_cast<ngraph::opset7::Squeeze>(concat_inputs[i].get_node_shared_ptr());
if (!squeeze)
return false;
nodes_to_delete.push_back(squeeze);
auto split_to_check =
std::dynamic_pointer_cast<ngraph::opset7::Split>(squeeze->input_value(0).get_node_shared_ptr());
auto squeeze_axes =
std::dynamic_pointer_cast<ngraph::opset7::Constant>(squeeze->input_value(1).get_node_shared_ptr());
if (!squeeze_axes || !split_to_check)
return false;
auto squeeze_axes_vec = squeeze_axes->cast_vector<int64_t>();
if (squeeze_axes_vec.size() != 1)
return false;
if (i == 0) {
axis_value = squeeze_axes_vec[0];
nodes_to_delete.push_back(split_to_check);
split = split_to_check;
} else if (axis_value != squeeze_axes_vec[0] || split_to_check != split) {
return false;
}
auto split_output = squeeze->input_value(0);
if (split_output.get_target_inputs().size() != 1 || split_output.get_index() != i)
return false;
}
if (split->get_num_splits() != concat_inputs.size())
return false;
auto split_axis =
std::dynamic_pointer_cast<ngraph::opset7::Constant>(split->input_value(1).get_node_shared_ptr());
if (!split_axis)
return false;
auto axis_vec = split_axis->cast_vector<int64_t>();
if (axis_vec.size() != 1 || axis_value != axis_vec[0])
return false;
auto input = split->input_value(0);
auto concat_axis = concat->get_axis();
auto rank = input.get_partial_shape().rank();
if (!rank.is_static())
return false;
std::vector<int64_t> order(rank.get_length());
std::iota(order.begin(), order.end(), 0);
order.erase(order.begin() + axis_value);
order.insert(order.begin() + concat_axis, axis_value);
auto transpose_order = ngraph::opset7::Constant::create(element::i64, {(size_t)rank.get_length()}, order);
auto transpose = register_new_node<ngraph::opset7::Transpose>(input, transpose_order);
auto shape_after = ngraph::opset7::Constant::create(element::i64,
{(size_t)rank.get_length() - 1},
concat->get_output_shape(0));
auto reshape = std::make_shared<ngraph::opset7::Reshape>(transpose, shape_after, false);
reshape->set_friendly_name(m.get_match_root()->get_friendly_name());
ngraph::copy_runtime_info(nodes_to_delete, {transpose, reshape});
ngraph::replace_node(m.get_match_root(), reshape);
MATCHER_SCOPE_ENABLE(SplitSqueezeConcatFusion);
return true;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(concat_pattern, matcher_name);
register_matcher(m, callback);
}
| 40.850467 | 118 | 0.620911 | [
"vector"
] |
4b4a37ca6c96fe6c998f55bfd15c258c2d6db028 | 3,442 | hpp | C++ | server/drivers/common.hpp | rsarwar87/koheron-sdk | 02c35bf3c1c29f1029fad18b881dbd193efac5a7 | [
"MIT"
] | 1 | 2020-06-23T16:03:22.000Z | 2020-06-23T16:03:22.000Z | server/drivers/common.hpp | rsarwar87/koheron-sdk | 02c35bf3c1c29f1029fad18b881dbd193efac5a7 | [
"MIT"
] | null | null | null | server/drivers/common.hpp | rsarwar87/koheron-sdk | 02c35bf3c1c29f1029fad18b881dbd193efac5a7 | [
"MIT"
] | null | null | null | /// Common commands for all bitstreams
///
/// (c) Koheron
#ifndef __DRIVERS_COMMON_HPP__
#define __DRIVERS_COMMON_HPP__
#include <cstring>
#include <array>
extern "C" {
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
}
#include <context.hpp>
class Common
{
public:
Common(Context& ctx_)
: ctx(ctx_)
, ctl(ctx.mm.get<mem::control>())
, sts(ctx.mm.get<mem::status>())
{}
uint32_t get_forty_two() {
ctx.log<INFO>("TRACE: calling get forty_two \n");
uint32_t ret = sts.read<reg::forty_two>();
ctx.log<INFO>("TRACE: successfullt retrieved value: %d\n", ret);
return ret;
}
uint64_t get_dna() {
return sts.read<reg::dna, uint64_t>();
}
void set_led(uint32_t value) {
ctl.write<reg::led>(value);
}
uint32_t get_led() {
return ctl.read<reg::led>();
}
void init() {
ip_on_leds();
};
std::string get_instrument_config() {
return CFG_JSON;
}
void ip_on_leds() {
struct ifaddrs* addrs;
getifaddrs(&addrs);
ifaddrs* tmp = addrs;
size_t cnt = get_iplist();
bool found = false;
// Turn all the leds ON
ctl.write<reg::led>(255);
for (size_t i = 0; i < cnt; i++) {
while (tmp) {
// Works only for IPv4 address
if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-align"
struct sockaddr_in* pAddr =
reinterpret_cast<struct sockaddr_in*>(tmp->ifa_addr);
#pragma GCC diagnostic pop
int val = strcmp(tmp->ifa_name, iplist.at(i).c_str());
if (val != 0) {
tmp = tmp->ifa_next;
continue;
}
printf("Interface %s found: %s\n", tmp->ifa_name,
inet_ntoa(pAddr->sin_addr));
uint32_t ip = htonl(pAddr->sin_addr.s_addr);
// Write IP address in FPGA memory
// The 8 Least Significant Bits should be connected to the FPGA
// LEDs
ctl.write_mask<reg::led, 0xFF>(ip);
found = true;
break;
}
tmp = tmp->ifa_next;
}
if (found) break;
}
freeifaddrs(addrs);
}
private:
Context& ctx;
Memory<mem::control>& ctl;
Memory<mem::status>& sts;
std::vector<std::string> iplist;
size_t get_iplist () {
std::string s = exec("find /sys/class/net -type l -not -lname '*virtual*' -printf '%f\n'");
std::string delimiter = "\n";
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
if (token.size() > 2) {
iplist.push_back(token);
}
s.erase(0, pos + delimiter.length());
}
return iplist.size();
}
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
return "";
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
};
#endif // __DRIVERS_COMMON_HPP__
| 25.308824 | 99 | 0.531668 | [
"vector"
] |
4b4f3f6c65f470a6f6747cd3202e65e7d4256b5f | 60,053 | cpp | C++ | level_zero/core/test/unit_tests/sources/cmdlist/test_cmdlist_4.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | level_zero/core/test/unit_tests/sources/cmdlist/test_cmdlist_4.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | level_zero/core/test/unit_tests/sources/cmdlist/test_cmdlist_4.cpp | maleadt/compute-runtime | 5d90e2ab1defd413dc9633fe237a44c2a1298185 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2020-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/test/common/cmd_parse/gen_cmd_parse.h"
#include "shared/test/common/helpers/unit_test_helper.h"
#include "shared/test/common/test_macros/test.h"
#include "level_zero/core/source/image/image_hw.h"
#include "level_zero/core/test/unit_tests/fixtures/device_fixture.h"
#include "level_zero/core/test/unit_tests/fixtures/host_pointer_manager_fixture.h"
#include "level_zero/core/test/unit_tests/fixtures/module_fixture.h"
#include "level_zero/core/test/unit_tests/mocks/mock_cmdlist.h"
#include "level_zero/core/test/unit_tests/mocks/mock_cmdqueue.h"
#include "level_zero/core/test/unit_tests/mocks/mock_module.h"
#include "test_traits_common.h"
namespace L0 {
namespace ult {
using CommandListCreate = Test<DeviceFixture>;
HWTEST2_F(CommandListCreate, givenCopyOnlyCommandListWhenAppendWriteGlobalTimestampCalledThenMiFlushDWWithTimestampEncoded, IsAtLeastSkl) {
using GfxFamily = typename NEO::GfxFamilyMapper<gfxCoreFamily>::GfxFamily;
using MI_FLUSH_DW = typename GfxFamily::MI_FLUSH_DW;
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::create(productFamily, device, NEO::EngineGroupType::Copy, 0u, returnValue));
auto &commandContainer = commandList->commandContainer;
uint64_t timestampAddress = 0xfffffffffff0L;
uint64_t *dstptr = reinterpret_cast<uint64_t *>(timestampAddress);
const auto commandStreamOffset = commandContainer.getCommandStream()->getUsed();
commandList->appendWriteGlobalTimestamp(dstptr, nullptr, 0, nullptr);
GenCmdList cmdList;
ASSERT_TRUE(FamilyType::PARSE::parseCommandBuffer(
cmdList,
ptrOffset(commandContainer.getCommandStream()->getCpuBase(), commandStreamOffset),
commandContainer.getCommandStream()->getUsed() - commandStreamOffset));
auto iterator = findAll<MI_FLUSH_DW *>(cmdList.begin(), cmdList.end());
bool postSyncFound = false;
ASSERT_NE(0u, iterator.size());
for (auto it : iterator) {
auto cmd = genCmdCast<MI_FLUSH_DW *>(*it);
if ((cmd->getPostSyncOperation() == MI_FLUSH_DW::POST_SYNC_OPERATION_WRITE_TIMESTAMP_REGISTER) &&
(cmd->getDestinationAddress() == timestampAddress)) {
postSyncFound = true;
}
}
ASSERT_TRUE(postSyncFound);
}
HWTEST2_F(CommandListCreate, givenCommandListWhenAppendWriteGlobalTimestampCalledThenPipeControlWithTimestampWriteEncoded, IsAtLeastSkl) {
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
using POST_SYNC_OPERATION = typename PIPE_CONTROL::POST_SYNC_OPERATION;
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::create(productFamily, device, NEO::EngineGroupType::RenderCompute, 0u, returnValue));
auto &commandContainer = commandList->commandContainer;
uint64_t timestampAddress = 0x123456785500;
uint64_t *dstptr = reinterpret_cast<uint64_t *>(timestampAddress);
const auto commandStreamOffset = commandContainer.getCommandStream()->getUsed();
commandList->appendWriteGlobalTimestamp(dstptr, nullptr, 0, nullptr);
GenCmdList cmdList;
ASSERT_TRUE(FamilyType::PARSE::parseCommandBuffer(
cmdList,
ptrOffset(commandContainer.getCommandStream()->getCpuBase(), commandStreamOffset),
commandContainer.getCommandStream()->getUsed() - commandStreamOffset));
auto iterator = find<PIPE_CONTROL *>(cmdList.begin(), cmdList.end());
auto cmd = genCmdCast<PIPE_CONTROL *>(*iterator);
EXPECT_TRUE(cmd->getCommandStreamerStallEnable());
EXPECT_FALSE(cmd->getDcFlushEnable());
EXPECT_EQ(timestampAddress, NEO::UnitTestHelper<FamilyType>::getPipeControlPostSyncAddress(*cmd));
EXPECT_EQ(POST_SYNC_OPERATION::POST_SYNC_OPERATION_WRITE_TIMESTAMP, cmd->getPostSyncOperation());
}
HWTEST2_F(CommandListCreate, givenCommandListWhenAppendWriteGlobalTimestampCalledThenTimestampAllocationIsInsideResidencyContainer, IsAtLeastSkl) {
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::create(productFamily, device, NEO::EngineGroupType::RenderCompute, 0u, returnValue));
uint64_t timestampAddress = 0x123456785500;
uint64_t *dstptr = reinterpret_cast<uint64_t *>(timestampAddress);
commandList->appendWriteGlobalTimestamp(dstptr, nullptr, 0, nullptr);
auto &commandContainer = commandList->commandContainer;
auto &residencyContainer = commandContainer.getResidencyContainer();
const bool addressIsInContainer = std::any_of(residencyContainer.begin(), residencyContainer.end(), [timestampAddress](NEO::GraphicsAllocation *alloc) {
return alloc->getGpuAddress() == timestampAddress;
});
EXPECT_TRUE(addressIsInContainer);
}
HWTEST2_F(CommandListCreate, givenImmediateCommandListWhenAppendWriteGlobalTimestampThenReturnsSuccess, IsAtLeastSkl) {
const ze_command_queue_desc_t desc = {};
bool internalEngine = true;
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList0(CommandList::createImmediate(productFamily,
device,
&desc,
internalEngine,
NEO::EngineGroupType::RenderCompute,
returnValue));
ASSERT_NE(nullptr, commandList0);
CommandQueueImp *cmdQueue = reinterpret_cast<CommandQueueImp *>(commandList0->cmdQImmediate);
EXPECT_EQ(cmdQueue->getCsr(), neoDevice->getInternalEngine().commandStreamReceiver);
uint64_t timestampAddress = 0x123456785500;
uint64_t *dstptr = reinterpret_cast<uint64_t *>(timestampAddress);
auto result = commandList0->appendWriteGlobalTimestamp(dstptr, nullptr, 0, nullptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
}
HWTEST2_F(CommandListCreate, givenUseCsrImmediateSubmissionEnabledForCopyImmediateCommandListThenAppendImageCopyRegionReturnsSuccess, IsAtLeastXeHpCore) {
DebugManagerStateRestore restorer;
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(true);
const ze_command_queue_desc_t queueDesc = {};
void *srcPtr = reinterpret_cast<void *>(0x1234);
void *dstPtr = reinterpret_cast<void *>(0x2345);
neoDevice->getRootDeviceEnvironment().getMutableHardwareInfo()->capabilityTable.blitterOperationsSupported = true;
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList0(CommandList::createImmediate(productFamily,
device,
&queueDesc,
false,
NEO::EngineGroupType::Copy,
returnValue));
ASSERT_NE(nullptr, commandList0);
ze_image_desc_t desc = {};
desc.stype = ZE_STRUCTURE_TYPE_IMAGE_DESC;
desc.type = ZE_IMAGE_TYPE_3D;
desc.format.layout = ZE_IMAGE_FORMAT_LAYOUT_8_8_8_8;
desc.format.type = ZE_IMAGE_FORMAT_TYPE_UINT;
desc.width = 11;
desc.height = 13;
desc.depth = 17;
desc.format.x = ZE_IMAGE_FORMAT_SWIZZLE_A;
desc.format.y = ZE_IMAGE_FORMAT_SWIZZLE_0;
desc.format.z = ZE_IMAGE_FORMAT_SWIZZLE_1;
desc.format.w = ZE_IMAGE_FORMAT_SWIZZLE_X;
auto imageHWSrc = std::make_unique<WhiteBox<::L0::ImageCoreFamily<gfxCoreFamily>>>();
auto imageHWDst = std::make_unique<WhiteBox<::L0::ImageCoreFamily<gfxCoreFamily>>>();
imageHWSrc->initialize(device, &desc);
imageHWDst->initialize(device, &desc);
returnValue = commandList0->appendImageCopy(imageHWDst->toHandle(), imageHWSrc->toHandle(), nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
returnValue = commandList0->appendImageCopyFromMemory(imageHWDst->toHandle(), srcPtr, nullptr, nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
returnValue = commandList0->appendImageCopyToMemory(dstPtr, imageHWSrc->toHandle(), nullptr, nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
}
HWTEST2_F(CommandListCreate, givenUseCsrImmediateSubmissionDisabledForCopyImmediateCommandListThenAppendImageCopyRegionReturnsSuccess, IsAtLeastXeHpCore) {
DebugManagerStateRestore restorer;
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(false);
const ze_command_queue_desc_t queueDesc = {};
void *srcPtr = reinterpret_cast<void *>(0x1234);
void *dstPtr = reinterpret_cast<void *>(0x2345);
neoDevice->getRootDeviceEnvironment().getMutableHardwareInfo()->capabilityTable.blitterOperationsSupported = true;
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList0(CommandList::createImmediate(productFamily,
device,
&queueDesc,
false,
NEO::EngineGroupType::Copy,
returnValue));
ASSERT_NE(nullptr, commandList0);
ze_image_desc_t desc = {};
desc.stype = ZE_STRUCTURE_TYPE_IMAGE_DESC;
desc.type = ZE_IMAGE_TYPE_3D;
desc.format.layout = ZE_IMAGE_FORMAT_LAYOUT_8_8_8_8;
desc.format.type = ZE_IMAGE_FORMAT_TYPE_UINT;
desc.width = 11;
desc.height = 13;
desc.depth = 17;
desc.format.x = ZE_IMAGE_FORMAT_SWIZZLE_A;
desc.format.y = ZE_IMAGE_FORMAT_SWIZZLE_0;
desc.format.z = ZE_IMAGE_FORMAT_SWIZZLE_1;
desc.format.w = ZE_IMAGE_FORMAT_SWIZZLE_X;
auto imageHWSrc = std::make_unique<WhiteBox<::L0::ImageCoreFamily<gfxCoreFamily>>>();
auto imageHWDst = std::make_unique<WhiteBox<::L0::ImageCoreFamily<gfxCoreFamily>>>();
imageHWSrc->initialize(device, &desc);
imageHWDst->initialize(device, &desc);
returnValue = commandList0->appendImageCopy(imageHWDst->toHandle(), imageHWSrc->toHandle(), nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
returnValue = commandList0->appendImageCopyFromMemory(imageHWDst->toHandle(), srcPtr, nullptr, nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
returnValue = commandList0->appendImageCopyToMemory(dstPtr, imageHWSrc->toHandle(), nullptr, nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
}
HWTEST_F(CommandListCreate, givenUseCsrImmediateSubmissionEnabledForCopyImmediateCommandListthenAppendMemoryCopyRegionReturnsSuccess) {
DebugManagerStateRestore restorer;
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(true);
void *srcPtr = reinterpret_cast<void *>(0x1234);
void *dstPtr = reinterpret_cast<void *>(0x2345);
uint32_t width = 16;
uint32_t height = 16;
ze_copy_region_t sr = {0U, 0U, 0U, width, height, 0U};
ze_copy_region_t dr = {0U, 0U, 0U, width, height, 0U};
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
auto commandList = CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Copy, returnValue);
auto result = commandList->appendMemoryCopyRegion(dstPtr, &dr, 0, 0, srcPtr, &sr, 0, 0, nullptr, 0, nullptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
commandList->destroy();
}
class CommandListImmediateFlushTaskTests : public DeviceFixture {
public:
void SetUp() {
DeviceFixture::SetUp();
}
void TearDown() {
DeviceFixture::TearDown();
}
DebugManagerStateRestore restorer;
};
using CommandListImmediateFlushTaskComputeTests = Test<CommandListImmediateFlushTaskTests>;
HWTEST2_F(CommandListImmediateFlushTaskComputeTests, givenDG2CommandListIsInititalizedThenByDefaultFlushTaskSubmissionEnabled, IsDG2) {
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
EXPECT_EQ(true, commandList->isFlushTaskSubmissionEnabled);
}
using MatchXeHpc = IsGfxCore<IGFX_XE_HPC_CORE>;
HWTEST2_F(CommandListImmediateFlushTaskComputeTests, givenXeHPCCommandListIsInititalizedThenByDefaultFlushTaskSubmissionEnabled, MatchXeHpc) {
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
EXPECT_EQ(true, commandList->isFlushTaskSubmissionEnabled);
}
HWTEST2_F(CommandListImmediateFlushTaskComputeTests, givenCommandListIsInititalizedThenByDefaultFlushTaskSubmissionDisabled, IsAtMostGen12lp) {
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
EXPECT_EQ(false, commandList->isFlushTaskSubmissionEnabled);
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenFlushTaskSubmissionDisabledWhenCommandListIsInititalizedThenFlushTaskIsSetToFalse) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(0);
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
EXPECT_EQ(false, commandList->isFlushTaskSubmissionEnabled);
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionDisabledForImmediateCommandListForAppendLaunchKernelThenSuccessIsReturned) {
Mock<::L0::Kernel> kernel;
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(0);
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
ze_group_count_t groupCount{1, 1, 1};
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
auto result = commandList->appendLaunchKernel(kernel.toHandle(), &groupCount, nullptr, 0, nullptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionEnabledForImmediateCommandListForAppendPageFaultThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(1);
size_t size = 0x100000001;
NEO::MockGraphicsAllocation mockAllocationSrc(0, NEO::AllocationType::INTERNAL_HOST_MEMORY,
reinterpret_cast<void *>(0x1234), size, 0, sizeof(uint32_t),
MemoryPool::System4KBPages);
NEO::MockGraphicsAllocation mockAllocationDst(0, NEO::AllocationType::INTERNAL_HOST_MEMORY,
reinterpret_cast<void *>(0x100003456), size, 0, sizeof(uint32_t),
MemoryPool::System4KBPages);
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
auto result = commandList->appendPageFaultCopy(&mockAllocationDst, &mockAllocationSrc, size, false);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionEnabledForImmediateWhenAppendEventResetThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(1);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendEventReset(event->toHandle());
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionEnabledForImmediateWhenAppendEventResetWithTimestampThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(1);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendEventReset(event->toHandle());
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionDisabledForImmediateWhenAppendEventResetWithTimestampThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(0);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendEventReset(event->toHandle());
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionEnabledForImmediateWhenAppendSignalEventThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(true);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendSignalEvent(event->toHandle());
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionEnabledForImmediateWhenAppendSignalEventWithTimestampThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(1);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendSignalEvent(event->toHandle());
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionDisabledForImmediateWhenAppendSignalEventWithTimestampThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(0);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendSignalEvent(event->toHandle());
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionDisabledForImmediateWhenAppendWaitOnEventWithTimestampThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(0);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
ze_event_handle_t hEventHandle = event->toHandle();
result = commandList->appendWaitOnEvents(1, &hEventHandle);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionEnabledForImmediateWhenAppendBarrierWithEventThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(1);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendBarrier(event->toHandle(), 0, nullptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionDisabledForImmediateWhenAppendBarrierWithTimestampEventThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(0);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendBarrier(event->toHandle(), 0, nullptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionEnabledForImmediateWhenAppendBarrierWithoutEventThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(1);
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
auto result = commandList->appendBarrier(nullptr, 0, nullptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
}
HWTEST_F(CommandListImmediateFlushTaskComputeTests, givenUseCsrImmediateSubmissionDisabledForImmediateWhenAppendBarrierWithEventThenSuccessIsReturned) {
NEO::DebugManager.flags.EnableFlushTaskSubmission.set(0);
ze_context_handle_t hContext;
ze_context_desc_t desc = {ZE_STRUCTURE_TYPE_CONTEXT_DESC, nullptr, 0};
ze_result_t res = driverHandle->createContext(&desc, 0u, nullptr, &hContext);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto context = static_cast<ContextImp *>(Context::fromHandle(hContext));
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 1;
eventPoolDesc.flags = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.signal = ZE_EVENT_SCOPE_FLAG_DEVICE;
ze_result_t result = ZE_RESULT_SUCCESS;
auto eventPool = std::unique_ptr<EventPool>(EventPool::create(driverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
auto event = std::unique_ptr<Event>(Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
ze_command_queue_desc_t queueDesc = {};
ze_result_t returnValue = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList(CommandList::createImmediate(productFamily, device, &queueDesc, false, NEO::EngineGroupType::Compute, returnValue));
result = commandList->appendBarrier(event->toHandle(), 0, nullptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
context->destroy();
}
HWTEST_F(CommandListCreate, GivenCommandListWhenUnalignedPtrThenLeftMiddleAndRightCopyAdded) {
using XY_COPY_BLT = typename FamilyType::XY_COPY_BLT;
ze_result_t returnValue;
std::unique_ptr<L0::CommandList> commandList(CommandList::create(productFamily, device, NEO::EngineGroupType::Copy, 0u, returnValue));
ASSERT_NE(nullptr, commandList);
EXPECT_EQ(device, commandList->device);
void *srcPtr = reinterpret_cast<void *>(0x4321);
void *dstPtr = reinterpret_cast<void *>(0x2345);
auto result = commandList->appendMemoryCopy(dstPtr, srcPtr, 2 * MemoryConstants::cacheLineSize, nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
GenCmdList cmdList;
ASSERT_TRUE(FamilyType::PARSE::parseCommandBuffer(
cmdList, ptrOffset(commandList->commandContainer.getCommandStream()->getCpuBase(), 0), commandList->commandContainer.getCommandStream()->getUsed()));
auto itor = find<XY_COPY_BLT *>(cmdList.begin(), cmdList.end());
EXPECT_NE(cmdList.end(), itor);
itor = find<XY_COPY_BLT *>(++itor, cmdList.end());
EXPECT_NE(cmdList.end(), itor);
itor = find<XY_COPY_BLT *>(++itor, cmdList.end());
EXPECT_NE(cmdList.end(), itor);
}
HWTEST2_F(CommandListCreate, whenCommandListIsCreatedThenFlagsAreCorrectlySet, IsAtLeastSkl) {
ze_command_list_flags_t flags[] = {0b0, 0b1, 0b10, 0b11};
ze_result_t returnValue;
for (auto flag : flags) {
std::unique_ptr<L0::CommandList> commandList(CommandList::create(productFamily, device, NEO::EngineGroupType::Compute, flag, returnValue));
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
auto pCommandListCoreFamily = static_cast<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>> *>(commandList.get());
EXPECT_EQ(flag, pCommandListCoreFamily->flags);
}
}
using CommandListAppendLaunchKernel = Test<ModuleFixture>;
struct ProgramChangedFieldsInComputeMode {
template <PRODUCT_FAMILY productFamily>
static constexpr bool isMatched() {
if (productFamily == IGFX_BROADWELL)
return false;
return TestTraits<NEO::ToGfxCoreFamily<productFamily>::get()>::programOnlyChangedFieldsInComputeStateMode;
}
};
HWTEST2_F(CommandListAppendLaunchKernel, GivenComputeModePropertiesWhenUpdateStreamPropertiesIsCalledTwiceThenChangedFieldsAreDirty, ProgramChangedFieldsInComputeMode) {
DebugManagerStateRestore restorer;
Mock<::L0::Kernel> kernel;
auto pMockModule = std::unique_ptr<Module>(new Mock<Module>(device, nullptr));
kernel.module = pMockModule.get();
auto pCommandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
auto result = pCommandList->initialize(device, NEO::EngineGroupType::Compute, 0u);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
const_cast<NEO::KernelDescriptor *>(&kernel.getKernelDescriptor())->kernelAttributes.numGrfRequired = 0x100;
pCommandList->updateStreamProperties(kernel, false, false);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.isCoherencyRequired.isDirty);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.largeGrfMode.isDirty);
const_cast<NEO::KernelDescriptor *>(&kernel.getKernelDescriptor())->kernelAttributes.numGrfRequired = 0x80;
pCommandList->updateStreamProperties(kernel, false, false);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.largeGrfMode.isDirty);
EXPECT_FALSE(pCommandList->finalStreamState.stateComputeMode.isCoherencyRequired.isDirty);
}
struct ProgramAllFieldsInComputeMode {
template <PRODUCT_FAMILY productFamily>
static constexpr bool isMatched() {
return !TestTraits<NEO::ToGfxCoreFamily<productFamily>::get()>::programOnlyChangedFieldsInComputeStateMode;
}
};
HWTEST2_F(CommandListAppendLaunchKernel, GivenComputeModeTraitsSetToFalsePropertiesWhenUpdateStreamPropertiesIsCalledTwiceThenAllFieldsAreDirty, ProgramAllFieldsInComputeMode) {
DebugManagerStateRestore restorer;
Mock<::L0::Kernel> kernel;
auto pMockModule = std::unique_ptr<Module>(new Mock<Module>(device, nullptr));
kernel.module = pMockModule.get();
auto pCommandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
auto result = pCommandList->initialize(device, NEO::EngineGroupType::Compute, 0u);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
const_cast<NEO::KernelDescriptor *>(&kernel.getKernelDescriptor())->kernelAttributes.numGrfRequired = 0x100;
pCommandList->updateStreamProperties(kernel, false, false);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.isCoherencyRequired.isDirty);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.largeGrfMode.isDirty);
const_cast<NEO::KernelDescriptor *>(&kernel.getKernelDescriptor())->kernelAttributes.numGrfRequired = 0x80;
pCommandList->updateStreamProperties(kernel, false, false);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.largeGrfMode.isDirty);
EXPECT_FALSE(pCommandList->finalStreamState.stateComputeMode.isCoherencyRequired.isDirty);
}
HWTEST2_F(CommandListAppendLaunchKernel, GivenComputeModePropertiesWhenPropertesNotChangedThenAllFieldsAreNotDirty, IsAtLeastSkl) {
DebugManagerStateRestore restorer;
Mock<::L0::Kernel> kernel;
auto pMockModule = std::unique_ptr<Module>(new Mock<Module>(device, nullptr));
kernel.module = pMockModule.get();
auto pCommandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
auto result = pCommandList->initialize(device, NEO::EngineGroupType::Compute, 0u);
ASSERT_EQ(ZE_RESULT_SUCCESS, result);
const_cast<NEO::KernelDescriptor *>(&kernel.getKernelDescriptor())->kernelAttributes.numGrfRequired = 0x100;
pCommandList->updateStreamProperties(kernel, false, false);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.isCoherencyRequired.isDirty);
EXPECT_TRUE(pCommandList->finalStreamState.stateComputeMode.largeGrfMode.isDirty);
pCommandList->updateStreamProperties(kernel, false, false);
EXPECT_FALSE(pCommandList->finalStreamState.stateComputeMode.isCoherencyRequired.isDirty);
EXPECT_FALSE(pCommandList->finalStreamState.stateComputeMode.largeGrfMode.isDirty);
}
using HostPointerManagerCommandListTest = Test<HostPointerManagerFixure>;
HWTEST2_F(HostPointerManagerCommandListTest,
givenImportedHostPointerWhenAppendMemoryFillUsingHostPointerThenAppendFillUsingHostPointerAllocation,
IsAtLeastSkl) {
auto commandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
commandList->initialize(device, NEO::EngineGroupType::RenderCompute, 0u);
auto ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int pattern = 1;
ret = commandList->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&pattern), sizeof(pattern), 64u, nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest,
givenImportedHostPointerAndCopyEngineWhenAppendMemoryFillUsingHostPointerThenAppendFillUsingHostPointerAllocation,
IsAtLeastSkl) {
auto commandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
commandList->initialize(device, NEO::EngineGroupType::Copy, 0u);
auto ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int pattern = 1;
ret = commandList->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&pattern), sizeof(pattern), 64u, nullptr, 0, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest,
givenHostPointerImportedWhenGettingAlignedAllocationThenRetrieveProperOffsetAndAddress,
IsAtLeastSkl) {
auto commandList = std::make_unique<::L0::ult::CommandListCoreFamily<gfxCoreFamily>>();
commandList->initialize(device, NEO::EngineGroupType::RenderCompute, 0u);
size_t mainOffset = 100;
size_t importSize = 100;
void *importPointer = ptrOffset(heapPointer, mainOffset);
auto ret = hostDriverHandle->importExternalPointer(importPointer, importSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
auto hostAllocation = hostDriverHandle->findHostPointerAllocation(importPointer, importSize, device->getRootDeviceIndex());
ASSERT_NE(nullptr, hostAllocation);
size_t allocOffset = 10;
size_t offsetSize = 20;
void *offsetPointer = ptrOffset(importPointer, allocOffset);
AlignedAllocationData outData = commandList->getAlignedAllocation(device, importPointer, importSize, false);
auto gpuBaseAddress = static_cast<size_t>(hostAllocation->getGpuAddress());
auto expectedAlignedAddress = alignDown(gpuBaseAddress, NEO::EncodeSurfaceState<FamilyType>::getSurfaceBaseAddressAlignment());
size_t expectedOffset = gpuBaseAddress - expectedAlignedAddress;
EXPECT_EQ(importPointer, hostAllocation->getUnderlyingBuffer());
EXPECT_EQ(expectedAlignedAddress, outData.alignedAllocationPtr);
EXPECT_EQ(hostAllocation, outData.alloc);
EXPECT_EQ(expectedOffset, outData.offset);
outData = commandList->getAlignedAllocation(device, offsetPointer, offsetSize, false);
expectedOffset += allocOffset;
EXPECT_EQ(importPointer, hostAllocation->getUnderlyingBuffer());
EXPECT_EQ(expectedAlignedAddress, outData.alignedAllocationPtr);
EXPECT_EQ(hostAllocation, outData.alloc);
EXPECT_EQ(expectedOffset, outData.offset);
ret = hostDriverHandle->releaseImportedPointer(importPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest,
givenHostPointerImportedWhenGettingPointerFromAnotherPageThenRetrieveBaseAddressAndProperOffset,
IsAtLeastSkl) {
auto commandList = std::make_unique<::L0::ult::CommandListCoreFamily<gfxCoreFamily>>();
commandList->initialize(device, NEO::EngineGroupType::RenderCompute, 0u);
size_t pointerSize = MemoryConstants::pageSize;
size_t offset = 100u + 2 * MemoryConstants::pageSize;
void *offsetPointer = ptrOffset(heapPointer, offset);
auto ret = hostDriverHandle->importExternalPointer(heapPointer, heapSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
auto hostAllocation = hostDriverHandle->findHostPointerAllocation(offsetPointer, pointerSize, device->getRootDeviceIndex());
ASSERT_NE(nullptr, hostAllocation);
AlignedAllocationData outData = commandList->getAlignedAllocation(device, offsetPointer, pointerSize, false);
auto expectedAlignedAddress = static_cast<uintptr_t>(hostAllocation->getGpuAddress());
EXPECT_EQ(heapPointer, hostAllocation->getUnderlyingBuffer());
EXPECT_EQ(expectedAlignedAddress, outData.alignedAllocationPtr);
EXPECT_EQ(hostAllocation, outData.alloc);
EXPECT_EQ(offset, outData.offset);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest, givenCommandListWhenMemoryFillWithSignalAndWaitEventsUsingRenderEngineThenPipeControlIsFound, IsAtLeastSkl) {
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
ze_result_t result = ZE_RESULT_SUCCESS;
auto commandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
commandList->initialize(device, NEO::EngineGroupType::RenderCompute, 0u);
auto &commandContainer = commandList->commandContainer;
auto ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int one = 1;
size_t size = 16;
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 2;
auto eventPool = std::unique_ptr<L0::EventPool>(L0::EventPool::create(hostDriverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
std::vector<ze_event_handle_t> events;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.wait = ZE_EVENT_SCOPE_FLAG_HOST;
auto event = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event.get());
eventDesc.index = 1;
auto event1 = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event1.get());
result = commandList->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&one), sizeof(one), size,
events[0], 1u, &events[1]);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
GenCmdList cmdList;
ASSERT_TRUE(FamilyType::PARSE::parseCommandBuffer(
cmdList, ptrOffset(commandContainer.getCommandStream()->getCpuBase(), 0), commandContainer.getCommandStream()->getUsed()));
auto itor = find<PIPE_CONTROL *>(cmdList.begin(), cmdList.end());
EXPECT_NE(cmdList.end(), itor);
}
using SupportedPlatformsSklIcllp = IsWithinProducts<IGFX_SKYLAKE, IGFX_ICELAKE>;
HWTEST2_F(HostPointerManagerCommandListTest, givenCommandListWhenMemoryFillWithSignalAndInvalidWaitHandleUsingRenderEngineThenErrorIsReturnedAndPipeControlIsNotAdded, SupportedPlatformsSklIcllp) {
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
ze_result_t result = ZE_RESULT_SUCCESS;
auto commandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
commandList->initialize(device, NEO::EngineGroupType::RenderCompute, 0u);
auto &commandContainer = commandList->commandContainer;
auto ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int one = 1;
size_t size = 16;
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 2;
auto eventPool = std::unique_ptr<L0::EventPool>(L0::EventPool::create(hostDriverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
std::vector<ze_event_handle_t> events;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.wait = ZE_EVENT_SCOPE_FLAG_HOST;
auto event = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event.get());
eventDesc.index = 1;
auto event1 = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event1.get());
result = commandList->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&one), sizeof(one), size,
events[0], 1u, nullptr);
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, result);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
GenCmdList cmdList;
ASSERT_TRUE(FamilyType::PARSE::parseCommandBuffer(
cmdList, ptrOffset(commandContainer.getCommandStream()->getCpuBase(), 0), commandContainer.getCommandStream()->getUsed()));
auto itor = find<PIPE_CONTROL *>(cmdList.begin(), cmdList.end());
EXPECT_NE(cmdList.end(), itor);
itor++;
itor = find<PIPE_CONTROL *>(itor, cmdList.end());
EXPECT_NE(cmdList.end(), itor);
itor++;
itor = find<PIPE_CONTROL *>(itor, cmdList.end());
EXPECT_EQ(cmdList.end(), itor);
}
HWTEST2_F(HostPointerManagerCommandListTest, givenCommandListWhenMemoryFillWithSignalAndWaitEventsUsingCopyEngineThenSuccessIsReturned, IsAtLeastSkl) {
ze_result_t result = ZE_RESULT_SUCCESS;
auto commandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
commandList->initialize(device, NEO::EngineGroupType::Copy, 0u);
auto ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int one = 1;
size_t size = 16;
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 2;
auto eventPool = std::unique_ptr<L0::EventPool>(L0::EventPool::create(hostDriverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
std::vector<ze_event_handle_t> events;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.wait = ZE_EVENT_SCOPE_FLAG_HOST;
auto event = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event.get());
eventDesc.index = 1;
auto event1 = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event1.get());
result = commandList->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&one), sizeof(one), size,
events[0], 1u, &events[1]);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest, givenCommandListWhenMemoryFillWithSignalAndiInvalidWaitHandleUsingCopyEngineThenErrorIsReturned, SupportedPlatformsSklIcllp) {
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
ze_result_t result = ZE_RESULT_SUCCESS;
auto commandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
commandList->initialize(device, NEO::EngineGroupType::Copy, 0u);
auto &commandContainer = commandList->commandContainer;
auto ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int one = 1;
size_t size = 16;
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 2;
auto eventPool = std::unique_ptr<L0::EventPool>(L0::EventPool::create(hostDriverHandle.get(), context, 0, nullptr, &eventPoolDesc, result));
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
std::vector<ze_event_handle_t> events;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.wait = ZE_EVENT_SCOPE_FLAG_HOST;
auto event = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event.get());
eventDesc.index = 1;
auto event1 = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event1.get());
result = commandList->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&one), sizeof(one), size,
events[0], 1u, nullptr);
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, result);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
GenCmdList cmdList;
ASSERT_TRUE(FamilyType::PARSE::parseCommandBuffer(
cmdList, ptrOffset(commandContainer.getCommandStream()->getCpuBase(), 0), commandContainer.getCommandStream()->getUsed()));
auto itor = find<PIPE_CONTROL *>(cmdList.begin(), cmdList.end());
EXPECT_EQ(cmdList.end(), itor);
}
HWTEST2_F(HostPointerManagerCommandListTest, givenImmediateCommandListWhenMemoryFillWithSignalAndWaitEventsUsingRenderEngineThenSuccessIsReturned, IsAtLeastSkl) {
const ze_command_queue_desc_t desc = {};
bool internalEngine = true;
ze_result_t ret = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList0(CommandList::createImmediate(productFamily,
device,
&desc,
internalEngine,
NEO::EngineGroupType::RenderCompute,
ret));
ASSERT_NE(nullptr, commandList0);
CommandQueueImp *cmdQueue = reinterpret_cast<CommandQueueImp *>(commandList0->cmdQImmediate);
EXPECT_EQ(cmdQueue->getCsr(), neoDevice->getInternalEngine().commandStreamReceiver);
ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int one = 1;
size_t size = 16;
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 2;
auto eventPool = std::unique_ptr<L0::EventPool>(L0::EventPool::create(hostDriverHandle.get(), context, 0, nullptr, &eventPoolDesc, ret));
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
std::vector<ze_event_handle_t> events;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.wait = ZE_EVENT_SCOPE_FLAG_HOST;
auto event = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event.get());
eventDesc.index = 1;
auto event1 = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event1.get());
ret = commandList0->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&one), sizeof(one), size,
events[0], 1u, &events[1]);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest, givenImmediateCommandListWhenMemoryFillWithSignalAndWaitEventsUsingCopyEngineThenSuccessIsReturned, IsAtLeastSkl) {
const ze_command_queue_desc_t desc = {};
bool internalEngine = true;
ze_result_t ret = ZE_RESULT_SUCCESS;
std::unique_ptr<L0::CommandList> commandList0(CommandList::createImmediate(productFamily,
device,
&desc,
internalEngine,
NEO::EngineGroupType::Copy,
ret));
ASSERT_NE(nullptr, commandList0);
CommandQueueImp *cmdQueue = reinterpret_cast<CommandQueueImp *>(commandList0->cmdQImmediate);
if (neoDevice->getInternalCopyEngine()) {
EXPECT_EQ(cmdQueue->getCsr(), neoDevice->getInternalCopyEngine()->commandStreamReceiver);
} else {
EXPECT_EQ(cmdQueue->getCsr(), neoDevice->getInternalEngine().commandStreamReceiver);
}
ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int one = 1;
size_t size = 16;
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 2;
auto eventPool = std::unique_ptr<L0::EventPool>(L0::EventPool::create(hostDriverHandle.get(), context, 0, nullptr, &eventPoolDesc, ret));
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
std::vector<ze_event_handle_t> events;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.wait = ZE_EVENT_SCOPE_FLAG_HOST;
auto event = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event.get());
eventDesc.index = 1;
auto event1 = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event1.get());
ret = commandList0->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&one), sizeof(one), size,
events[0], 1u, &events[1]);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest, givenImmediateCommandListWhenMemoryFillWithSignalAndInvalidWaitHandleUsingCopyEngineThenErrorIsReturned, SupportedPlatformsSklIcllp) {
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
ze_result_t ret = ZE_RESULT_SUCCESS;
const ze_command_queue_desc_t desc = {};
bool internalEngine = true;
std::unique_ptr<L0::CommandList> commandList0(CommandList::createImmediate(productFamily,
device,
&desc,
internalEngine,
NEO::EngineGroupType::Copy,
ret));
ASSERT_NE(nullptr, commandList0);
CommandQueueImp *cmdQueue = reinterpret_cast<CommandQueueImp *>(commandList0->cmdQImmediate);
if (neoDevice->getInternalCopyEngine()) {
EXPECT_EQ(cmdQueue->getCsr(), neoDevice->getInternalCopyEngine()->commandStreamReceiver);
} else {
EXPECT_EQ(cmdQueue->getCsr(), neoDevice->getInternalEngine().commandStreamReceiver);
}
ret = hostDriverHandle->importExternalPointer(heapPointer, MemoryConstants::pageSize);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
int one = 1;
size_t size = 16;
ze_event_pool_desc_t eventPoolDesc = {};
eventPoolDesc.count = 2;
auto eventPool = std::unique_ptr<L0::EventPool>(L0::EventPool::create(hostDriverHandle.get(), context, 0, nullptr, &eventPoolDesc, ret));
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
std::vector<ze_event_handle_t> events;
ze_event_desc_t eventDesc = {};
eventDesc.index = 0;
eventDesc.wait = ZE_EVENT_SCOPE_FLAG_HOST;
auto event = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event.get());
eventDesc.index = 1;
auto event1 = std::unique_ptr<L0::Event>(L0::Event::create<uint32_t>(eventPool.get(), &eventDesc, device));
events.push_back(event1.get());
ret = commandList0->appendMemoryFill(heapPointer, reinterpret_cast<void *>(&one), sizeof(one), size,
events[0], 1u, nullptr);
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, ret);
ret = hostDriverHandle->releaseImportedPointer(heapPointer);
EXPECT_EQ(ZE_RESULT_SUCCESS, ret);
}
HWTEST2_F(HostPointerManagerCommandListTest, givenDebugModeToRegisterAllHostPointerWhenFindIsCalledThenRegisterHappens, IsAtLeastSkl) {
DebugManagerStateRestore restorer;
DebugManager.flags.ForceHostPointerImport.set(1);
void *testPtr = heapPointer;
auto gfxAllocation = hostDriverHandle->findHostPointerAllocation(testPtr, 0x10u, device->getRootDeviceIndex());
EXPECT_NE(nullptr, gfxAllocation);
EXPECT_EQ(testPtr, gfxAllocation->getUnderlyingBuffer());
auto result = hostDriverHandle->releaseImportedPointer(testPtr);
EXPECT_EQ(ZE_RESULT_SUCCESS, result);
}
using SingleTileOnlyPlatforms = IsWithinGfxCore<IGFX_GEN9_CORE, IGFX_GEN12LP_CORE>;
HWTEST2_F(CommandListCreate, givenSingleTileOnlyPlatformsWhenProgrammingMultiTileBarrierThenNoProgrammingIsExpected, SingleTileOnlyPlatforms) {
using GfxFamily = typename NEO::GfxFamilyMapper<gfxCoreFamily>::GfxFamily;
auto neoDevice = device->getNEODevice();
auto &hwInfo = neoDevice->getHardwareInfo();
auto commandList = std::make_unique<::L0::ult::CommandListCoreFamily<gfxCoreFamily>>();
ASSERT_NE(nullptr, commandList);
ze_result_t returnValue = commandList->initialize(device, NEO::EngineGroupType::Compute, 0u);
EXPECT_EQ(ZE_RESULT_SUCCESS, returnValue);
EXPECT_EQ(0u, commandList->estimateBufferSizeMultiTileBarrier(hwInfo));
auto cmdListStream = commandList->commandContainer.getCommandStream();
size_t usedBefore = cmdListStream->getUsed();
commandList->appendMultiTileBarrier(*neoDevice);
size_t usedAfter = cmdListStream->getUsed();
EXPECT_EQ(usedBefore, usedAfter);
}
} // namespace ult
} // namespace L0
| 49.54868 | 196 | 0.73217 | [
"vector"
] |
4b516fd454a503b9338c416e00f1fae08e2f67f1 | 1,323 | cpp | C++ | CoreSystem/lib/CGAL/examples/Point_set_processing_3/random_simplification_example.cpp | josuehfa/DAASystem | a1fe61ffc19f0781eeeddcd589137eefde078a45 | [
"MIT"
] | 1 | 2020-03-17T01:13:02.000Z | 2020-03-17T01:13:02.000Z | CoreSystem/lib/CGAL/examples/Point_set_processing_3/random_simplification_example.cpp | josuehfa/DAASystem | a1fe61ffc19f0781eeeddcd589137eefde078a45 | [
"MIT"
] | null | null | null | CoreSystem/lib/CGAL/examples/Point_set_processing_3/random_simplification_example.cpp | josuehfa/DAASystem | a1fe61ffc19f0781eeeddcd589137eefde078a45 | [
"MIT"
] | 1 | 2021-12-02T11:11:36.000Z | 2021-12-02T11:11:36.000Z | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/random_simplify_point_set.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/IO/write_xyz_points.h>
#include <vector>
#include <fstream>
#include <iostream>
// types
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::Point_3 Point;
int main(int argc, char*argv[])
{
const char* fname = (argc>1)?argv[1]:"data/oni.xyz";
// Reads a .xyz point set file in points[].
std::vector<Point> points;
std::ifstream stream(fname);
if (!stream ||
!CGAL::read_xyz_points(stream, std::back_inserter(points)))
{
std::cerr << "Error: cannot read file " << fname << std::endl;
return EXIT_FAILURE;
}
// Randomly simplifies using erase-remove idiom
const double removed_percentage = 97.0; // percentage of points to remove
points.erase(CGAL::random_simplify_point_set(points, removed_percentage),
points.end());
// Optional: after erase(), use Scott Meyer's "swap trick" to trim excess capacity
std::vector<Point>(points).swap(points);
// Saves point set.
std::ofstream out((argc>2)?argv[2]:"Three_lady_copy.xyz");
out.precision(17);
if (!out ||
!CGAL::write_xyz_points(
out, points))
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 27.5625 | 84 | 0.699169 | [
"vector"
] |
4b51ecc422fa3feffb100ffd83b1d1f2a64a2ae6 | 1,103 | cpp | C++ | src/layers/conv1d.cpp | choiip/kerasify | 9add953ad2333486de66e985213c6e57ea4c17b4 | [
"MIT"
] | 7 | 2018-04-02T07:31:30.000Z | 2019-02-02T15:48:26.000Z | src/layers/conv1d.cpp | choiip/kerasify | 9add953ad2333486de66e985213c6e57ea4c17b4 | [
"MIT"
] | null | null | null | src/layers/conv1d.cpp | choiip/kerasify | 9add953ad2333486de66e985213c6e57ea4c17b4 | [
"MIT"
] | 2 | 2019-04-18T05:43:45.000Z | 2019-07-09T03:58:45.000Z | /*
* Copyright (c) 2016 Robert W. Rose
* Copyright (c) 2018 Paul Maevskikh
*
* MIT License, see LICENSE file.
*/
#include "keras/layers/conv1d.h"
namespace keras {
namespace layers {
Tensor Conv1D::forward(const Tensor& in) const noexcept {
// 'in' have shape (steps, features)
// 'tmp' have shape (new_steps, outputs)
// 'weights' have shape (outputs, kernel, features)
kassert(in.dims_[1] == weights_.dims_[2]);
auto& ww = weights_.dims_;
size_t offset = ww[1] - 1;
auto tmp = Tensor::empty({in.dims_[0] - offset, ww[0]});
auto ws0 = cast(ww[2] * ww[1]);
auto ws1 = cast(ww[2]);
auto tx = cast(tmp.dims_[0]);
auto i_ptr = in.begin();
auto b_ptr = biases_.begin();
auto t_ptr = std::back_inserter(tmp.data_);
for (ptrdiff_t x = 0; x < tx; ++x) {
auto b_ = b_ptr;
auto i_ = i_ptr + x * ws1;
for (auto w0 = weights_.begin(); w0 < weights_.end(); w0 += ws0)
*(t_ptr++) = std::inner_product(w0, w0 + ws0, i_, *(b_++));
}
return activation_(tmp);
}
} // namespace layers
} // namespace keras
| 25.651163 | 72 | 0.587489 | [
"shape"
] |
4b53973a382a72245e85847ad613abd76916fa2d | 9,836 | cpp | C++ | Gomoku_Arbitre/GameC.cpp | Krakcen/Gomoku_2D | 40b1bad6fbaf39384cfa6b667d6ee5a4572ed0ff | [
"MIT"
] | null | null | null | Gomoku_Arbitre/GameC.cpp | Krakcen/Gomoku_2D | 40b1bad6fbaf39384cfa6b667d6ee5a4572ed0ff | [
"MIT"
] | null | null | null | Gomoku_Arbitre/GameC.cpp | Krakcen/Gomoku_2D | 40b1bad6fbaf39384cfa6b667d6ee5a4572ed0ff | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GameC.h"
#include "PyLoader.h"
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Referee.h"
int GomokuA::checkIAPlay() {
int x;
int y;
int* result;
this->pl->PyLoadFunction("main");
this->pl->PyCallFunction(PyTuple_Pack(0, NULL));
int* xy = pl->PyReturnFunctionTuple();
x = xy[0];
y = xy[1];
Referee r;
result = r.checkPlay(this->vectorToChar(this->goMatr), y, x, this->getPlayer());
if (result[0] == 1) {
std::cout << "Invalid Play: Stone Already Here" << std::endl;
this->changeInfoText("Stone Already Here", "ERROR");
return (1);
}
/*if (result[0] == 0) {
this->changeInfoText("", "SUCCESS");
}*/
if (result[1] != 0) {
int j = 2;
int k = 0;
k = result[1];
while (k > 0) {
this->setPairR();
//tmp
std::cout << "[IA] pair nb: " << this->getPairR() << std::endl;
//remove
this->goMatr[result[j + 1]][result[j]] = '0';
this->goMatr[result[j + 3]][result[j + 2]] = '0';
this->pl->PyLoadFunction("delete_pion");
this->pl->PyCallFunction(PyTuple_Pack(2, PyLong_FromLong(j), PyLong_FromLong(j + 1)));
this->pl->PyCallFunction(PyTuple_Pack(2, PyLong_FromLong(j + 3), PyLong_FromLong(j + 4)));
j = j + 4;
k--;
}
this->changeInfoText("Pair Captured", "SUCCESS");
if (this->getPairR() >= 5) {
this->changeInfoText("IA Won (5 Pairs) !", "SUCCESS");
this->end = 1;
this->playerT.setString("Game Over");
this->playerT.setFillColor(sf::Color(255, 255, 255));
this->playerT.setPosition(840, 90);
this->end = 1;
}
}
if (result[0] == 3) {
this->changeInfoText("IA Won !", "ERROR");
this->playerT.setString("Game Over");
this->end = 1;
this->playerT.setFillColor(sf::Color(255, 255, 255));
this->playerT.setPosition(840, 90);
}
this->goMatr[y][x] = 'R';
sf::CircleShape circle(200);
this->stoneTab[y][x] = circle;
this->stoneTab[y][x].setRadius(13);
this->stoneTab[y][x].setPointCount(100);
this->stoneTab[y][x].setPosition(this->coordMatr[y][x][0] - 12, this->coordMatr[y][x][1] - 12);
this->stoneTab[y][x].setFillColor(sf::Color(255, 0, 0));
if (this->end == 0) {
this->playerT.setString("Your Turn");
this->playerT.setFillColor(sf::Color(0, 255, 255));
}
this->setPlayer(0);
return (0);
}
int GomokuA::checkMouseClick(int x, int y) {
int* result;
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
if ((x < this->coordMatr[i][j][0] + 13) && (x > this->coordMatr[i][j][0] - 13) && (y < this->coordMatr[i][j][1] + 13) && (y > this->coordMatr[i][j][1] - 13)) {
//Checking
Referee r;
result = r.checkPlay(this->vectorToChar(this->goMatr), i, j, this->getPlayer());
if (result[0] == 1) {
std::cout << "Invalid Play: Stone Already Here" << std::endl;
this->changeInfoText("Stone Already Here", "ERROR");
return (1);
}
if (result[0] == 0) {
this->changeInfoText("", "SUCCESS");
}
//Pair
if (result[1] != 0) {
int j = 2;
int k = 0;
k = result[1];
while (k > 0) {
this->setPairB();
//remove
this->goMatr[result[j + 1]][result[j]] = '0';
this->goMatr[result[j + 3]][result[j + 2]] = '0';
this->pl->PyLoadFunction("delete_pion");
this->pl->PyCallFunction(PyTuple_Pack(2, PyLong_FromLong(j), PyLong_FromLong(j + 1)));
this->pl->PyCallFunction(PyTuple_Pack(2, PyLong_FromLong(j + 3), PyLong_FromLong(j + 4)));
j = j + 4;
k--;
}
this->changeInfoText("Pair Captured", "SUCCESS");
if (this->getPairB() >= 5) {
this->changeInfoText("You Won (5 Pairs) !", "SUCCESS");
this->end = 1;
this->playerT.setString("Game Over");
this->playerT.setPosition(840, 90);
this->playerT.setFillColor(sf::Color(255, 255, 255));
}
}
if (result[0] == 2) {
this->changeInfoText("You Won (5 Aligned) !", "SUCCESS");
this->end = 1;
this->playerT.setString("Game Over");
this->playerT.setPosition(840, 90);
this->playerT.setFillColor(sf::Color(255, 255, 255));
}
sf::CircleShape circle(200);
this->stoneTab[i][j] = circle;
this->stoneTab[i][j].setRadius(13);
this->stoneTab[i][j].setPointCount(100);
this->stoneTab[i][j].setPosition(this->coordMatr[i][j][0] - 12, this->coordMatr[i][j][1] - 12);
this->goMatr[i][j] = 'B';
this->setPlayer(1);
this->stoneTab[i][j].setFillColor(sf::Color(0, 255, 255));
if (this->end == 0) {
this->playerT.setString("IA Turn");
this->playerT.setFillColor(sf::Color(255, 0, 0));
}
this->pl->PyLoadFunction("put_player_pion");
this->pl->PyCallFunction(PyTuple_Pack(2, PyLong_FromLong(j), PyLong_FromLong(i)));
return (0);
}
}
}
return (1);
}
int** GomokuA::vecToInt(std::vector < std::vector<char> > matr) {
int** intMatr;
intMatr = new int*[19];
for (int i = 0; i < 19; i++) {
intMatr[i] = new int[19];
}
for (int k = 0; k < 19; k++) {
for (int j = 0; j < 19; j++) {
if (matr[k][j] == 'B')
intMatr[k][j] = 1;
else if (matr[k][j] == 'R')
intMatr[k][j] = 2;
else
intMatr[k][j] = 0;
}
}
return (intMatr);
}
char** GomokuA::vectorToChar(std::vector < std::vector<char> > matr) {
char** charMtr;
charMtr = new char*[19];
for (int i = 0; i < 19; i++) {
charMtr[i] = new char[19];
}
for (int k = 0; k < 19; k++) {
for (int j = 0; j < 19; j++) {
charMtr[k][j] = matr[k][j];
}
}
return (charMtr);
}
int GomokuA::displayBoard() {
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
std::cout << this->goMatr[i][j] << " ";
}
std::cout << std::endl;
}
return (0);
}
void GomokuA::changeInfoText(std::string text, std::string type) {
if (type == "ERROR") {
this->infoT.setString(text);
this->infoT.setFillColor(*this->infoE);
}
else if (type == "SUCCESS") {
this->infoT.setString(text);
this->infoT.setFillColor(*this->infoS);
}
else {
this->infoT.setString(text);
this->infoT.setFillColor(*this->infoW);
}
}
//Pair
void GomokuA::setPairB() {
this->pairB++;
}
void GomokuA::setPairR() {
this->pairR++;
}
int GomokuA::getPairB() {
return (this->pairB);
}
int GomokuA::getPairR() {
return (this->pairR);
}
//
sf::Font GomokuA::getFont() {
return (this->font);
}
sf::Text GomokuA::getInfoTText() {
return (this->infoTitle);
}
sf::Text GomokuA::getInfoT() {
return (this->infoT);
}
sf::Text GomokuA::getText() {
return (this->playerT);
}
sf::Text GomokuA::getEndText() {
return (this->endT);
}
int GomokuA::getPlayer() {
return (this->currentP);
}
void GomokuA::setPlayer(int player) {
this->currentP = player;
}
sf::Sprite GomokuA::getBoard() {
return (this->boardSprite);
}
sf::Sprite GomokuA::getSideBoard() {
return (this->sideboardSprite);
}
//Constructor
GomokuA::GomokuA() {
//Init Player
this->currentP = 0;
//Init Font
if (!this->font.loadFromFile("Fh_Space.otf"))
{
// error...
}
//Init Texts
this->endT.setFont(this->font);
this->endT.setString("Game Over");
this->endT.setCharacterSize(40);
this->endT.setFillColor(sf::Color(192, 192, 192));
this->endT.setStyle(sf::Text::Bold);
this->endT.setPosition(900, 500);
this->playerT.setFont(this->font);
this->playerT.setString("Your Turn");
this->playerT.setCharacterSize(40);
this->playerT.setFillColor(sf::Color(0, 255, 255));
this->playerT.setStyle(sf::Text::Bold);
this->playerT.setPosition(860, 90);
this->infoTitle.setFont(this->font);
this->infoTitle.setString("Info");
this->infoTitle.setCharacterSize(40);
this->infoTitle.setFillColor(sf::Color(252, 181, 20));
this->infoTitle.setStyle(sf::Text::Bold);
this->infoTitle.setPosition(900, 500);
this->infoT.setFont(this->font);
this->infoT.setCharacterSize(20);
this->infoT.setString("");
this->infoT.setPosition(850, 600);
//Init Pair
this->pairB = 0;
this->pairR = 0;
//Init Go Matrix
this->goMatr.resize(19);
for (int i = 0; i < 19; ++i)
this->goMatr[i].resize(19);
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
this->goMatr[i][j] = '0';
}
}
//Init End
this->end = 0;
//Init Coord Matrix
int cx = 40;
int cy = 40;
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
this->coordMatr[i][j][0] = cx;
this->coordMatr[i][j][1] = cy;
cx = cx + 40;
}
cx = 40;
cy = cy + 40;
}
//Init Sprites
if (!this->boardTexture.loadFromFile("space_texture.jpg"))
printG("couldnt load space texture");
if (!this->sideboardTexture.loadFromFile("sideboard_texture.jpg"))
printG("couldnt load sideboard texture");
this->boardSprite.setTexture(this->boardTexture);
this->sideboardSprite.setTexture(this->sideboardTexture);
this->sideboardSprite.setPosition(sf::Vector2f(800, 0));
//Init Grid
float x1 = 40;
float y1 = 40;
float y2 = 40;
float x2 = 760;
int j = 0;
for (int i = 0; i < 19; i++) {
this->verTabH[j][0] = sf::Vertex(sf::Vector2f(x1, y1));
this->verTabH[j][1] = sf::Vertex(sf::Vector2f(x2, y2));
this->verTabH[j + 1][0] = sf::Vertex(sf::Vector2f(x1, y1 - 1));
this->verTabH[j + 1][1] = sf::Vertex(sf::Vector2f(x2, y2 - 1));
this->verTabH[j + 2][0] = sf::Vertex(sf::Vector2f(x1, y1 + 1));
this->verTabH[j + 2][1] = sf::Vertex(sf::Vector2f(x2, y2 + 1));
y1 = y1 + 40;
y2 = y2 + 40;
j = j + 3;
}
x1 = 40;
y1 = 40;
x2 = 40;
y2 = 760;
j = 0;
for (int i = 0; i < 19; i++) {
this->verTabV[j][0] = sf::Vertex(sf::Vector2f(x1, y1));
this->verTabV[j][1] = sf::Vertex(sf::Vector2f(x2, y2));
this->verTabV[j + 1][0] = sf::Vertex(sf::Vector2f(x1 - 1, y1));
this->verTabV[j + 1][1] = sf::Vertex(sf::Vector2f(x2 - 1, y2));
this->verTabV[j + 2][0] = sf::Vertex(sf::Vector2f(x1 + 1, y1));
this->verTabV[j + 2][1] = sf::Vertex(sf::Vector2f(x2 + 1, y2));
x1 = x1 + 40;
x2 = x2 + 40;
j = j + 3;
}
}
GomokuA::~GomokuA() {
delete (this->infoE);
delete (this->infoS);
delete (this->infoW);
std::cout << "Bye";
}
| 24.59 | 162 | 0.592517 | [
"vector"
] |
4b53fc963b1af33d4e61c52383a13c19465bd82f | 7,379 | cpp | C++ | src/learning/LinearSolver.cpp | Mostah/parallel-pymcda | d5f5bb0de95dec90b88be9d00a3860e52eed4003 | [
"MIT"
] | 2 | 2020-12-12T22:48:57.000Z | 2021-02-24T09:37:40.000Z | src/learning/LinearSolver.cpp | Mostah/parallel-pymcda | d5f5bb0de95dec90b88be9d00a3860e52eed4003 | [
"MIT"
] | 5 | 2021-01-07T19:34:24.000Z | 2021-03-17T13:52:22.000Z | src/learning/LinearSolver.cpp | Mostah/parallel-pymcda | d5f5bb0de95dec90b88be9d00a3860e52eed4003 | [
"MIT"
] | 3 | 2020-12-12T22:49:56.000Z | 2021-09-08T05:26:38.000Z | #include "../../include/learning/LinearSolver.h"
#include "../../include/app.h"
#include "../../include/types/AlternativesPerformance.h"
#include "ortools/linear_solver/linear_solver.h"
#include <sstream>
#include <string>
LinearSolver::LinearSolver(AlternativesPerformance &ap, Config &conf,
float delta, std::string solver_name)
: ap(ap), conf(conf) {
solver = operations_research::MPSolver::CreateSolver(solver_name);
solver_name = solver_name;
delta = delta;
}
LinearSolver::~LinearSolver() { delete solver; }
AlternativesPerformance &LinearSolver::getAlternativesPerformance() const {
return ap;
}
operations_research::MPSolver *LinearSolver::getSolver() const {
return solver;
}
Config LinearSolver::getConf() const { return conf; }
std::vector<operations_research::MPVariable *>
LinearSolver::getWeights() const {
return weights;
}
std::vector<operations_research::MPVariable *> LinearSolver::getXa() const {
return x_a;
}
std::vector<operations_research::MPVariable *> LinearSolver::getXap() const {
return x_ap;
}
std::vector<operations_research::MPVariable *> LinearSolver::getYa() const {
return y_a;
}
std::vector<operations_research::MPVariable *> LinearSolver::getYap() const {
return y_ap;
}
void LinearSolver::initializeSolver() {
// reset constraints vectors
x_constraints.clear();
y_constraints.clear();
weights_constraint.clear();
// reset variables vectors
x_a.clear();
x_ap.clear();
y_a.clear();
y_ap.clear();
weights.clear();
// reset previous solver
solver->Clear();
const double infinity = solver->infinity();
// weight variables
for (int i = 0; i < ap.getNumberCrit(); i++) {
weights.push_back(solver->MakeNumVar(0., 1.0, "w" + std::to_string(i)));
}
// x, x' (xp), y, y' (yp) variables
for (int i = 0; i < ap.getNumberAlt(); i++) {
x_a.push_back(solver->MakeNumVar(0., infinity, "x" + std::to_string(i)));
x_ap.push_back(solver->MakeNumVar(0., infinity, "xp" + std::to_string(i)));
y_a.push_back(solver->MakeNumVar(0., infinity, "y" + std::to_string(i)));
y_ap.push_back(solver->MakeNumVar(0., infinity, "yp" + std::to_string(i)));
}
// lambda variable
lambda = solver->MakeNumVar(0.5, 1.0, "lambda");
// sum weight = 1 constraint: -sum <= -1 and sum <= 1
// -sum <= -1
auto w_maj = solver->MakeRowConstraint(-infinity, -1, "weight_constraint_p");
for (operations_research::MPVariable *w_i : weights) {
w_maj->SetCoefficient(w_i, -1);
}
weights_constraint.push_back(w_maj);
// sum <= 1
auto w_min = solver->MakeRowConstraint(-infinity, 1, "weight_constraint_m");
for (operations_research::MPVariable *w_i : weights) {
w_min->SetCoefficient(w_i, 1);
}
weights_constraint.push_back(w_min);
// objective function, minimize sum(xp + yp)
operations_research::MPObjective *const objective =
solver->MutableObjective();
for (operations_research::MPVariable *xp : x_ap) {
objective->SetCoefficient(xp, 1);
}
for (operations_research::MPVariable *yp : y_ap) {
objective->SetCoefficient(yp, 1);
}
objective->SetMinimization();
}
void LinearSolver::updateConstraints(
std::vector<std::vector<std::vector<bool>>> x_matrix,
std::vector<std::vector<std::vector<bool>>> y_matrix) {
// re-initialise solver with variable and default constraint
this->initializeSolver();
const double infinity = solver->infinity();
// add new constraints given the matrixs
// Starting with x constraints
// for all profiles
for (int h = 0; h < x_matrix.size(); h++) {
// for all alternative assigned to category h
for (int alt = 0; alt < x_matrix[h].size(); alt++) {
// if alt is empty the alt was not assigned to this category (h)
if (!x_matrix[h][alt].empty()) {
// create constraint with name cst_x_b2_a6
// as with ORTools, the form of the Linear Problem is cannonical, we
// need to add two constraints from the equality : cst_x_b2_a6 = 0 <-->
// cst_x_b2_a6_- <= 0 and cst_x_b2_a6_+ >= 0
// cst_x_b2_a6_+ : - cst_x_b2_a6 <= 0
operations_research::MPConstraint *cst_min = solver->MakeRowConstraint(
-infinity, 0,
"cst_x_b" + std::to_string(h) + "_a" + std::to_string(alt) + "_+");
// cst_x_b2_a6_- : cst_x_b2_a6 <= 0
operations_research::MPConstraint *cst_maj = solver->MakeRowConstraint(
-infinity, 0,
"cst_x_b" + std::to_string(h) + "_a" + std::to_string(alt) + "_-");
// -lambda
cst_min->SetCoefficient(lambda, -1);
cst_maj->SetCoefficient(lambda, 1);
// -x_a
cst_min->SetCoefficient(x_a[alt], -1);
cst_maj->SetCoefficient(x_a[alt], 1);
// +x_ap
cst_min->SetCoefficient(x_ap[alt], 1);
cst_maj->SetCoefficient(x_ap[alt], -1);
// +sum(w_j(a_i, b_h-1) if a_i>=bi_h-1)
for (int crit = 0; crit < x_matrix[h][alt].size(); crit++) {
if (x_matrix[h][alt][crit]) {
cst_min->SetCoefficient(weights[crit], 1);
cst_maj->SetCoefficient(weights[crit], -1);
}
}
x_constraints.push_back(cst_min);
x_constraints.push_back(cst_maj);
}
}
}
// Same for y constraints
for (int h = 0; h < y_matrix.size(); h++) {
for (int alt = 0; alt < y_matrix[h].size(); alt++) {
if (!y_matrix[h][alt].empty()) {
// create constraint with name cst_y_b2_a6 for ex
operations_research::MPConstraint *cst_min = solver->MakeRowConstraint(
-infinity, -delta,
"cst_y_h" + std::to_string(h) + "_a" + std::to_string(alt));
operations_research::MPConstraint *cst_maj = solver->MakeRowConstraint(
-infinity, delta,
"cst_y_h" + std::to_string(h) + "_a" + std::to_string(alt));
cst_min->SetCoefficient(lambda, -1);
cst_maj->SetCoefficient(lambda, 1);
cst_min->SetCoefficient(y_a[alt], 1);
cst_maj->SetCoefficient(y_a[alt], -1);
cst_min->SetCoefficient(y_ap[alt], -1);
cst_maj->SetCoefficient(y_ap[alt], 1);
for (int crit = 0; crit < y_matrix[h][alt].size(); crit++) {
if (y_matrix[h][alt][crit]) {
cst_min->SetCoefficient(weights[crit], 1);
cst_maj->SetCoefficient(weights[crit], -1);
}
}
y_constraints.push_back(cst_min);
y_constraints.push_back(cst_maj);
}
}
}
}
std::pair<float, std::vector<float>>
LinearSolver::solve(std::vector<std::vector<std::vector<bool>>> x_matrix,
std::vector<std::vector<std::vector<bool>>> y_matrix) {
this->updateConstraints(x_matrix, y_matrix);
const operations_research::MPSolver::ResultStatus result_status =
solver->Solve();
if (result_status != operations_research::MPSolver::OPTIMAL) {
conf.logger->warn("Solver couldn't find an optimal solution.");
throw std::logic_error("Solver couldn't find an optimal solution");
}
std::ostringstream ss;
ss << "Problem solved - " << solver->wall_time() << " ms, "
<< solver->iterations() << " iterations.";
conf.logger->debug(ss.str());
std::vector<float> weight_values;
for (auto w_i : weights) {
weight_values.push_back(w_i->solution_value());
}
auto res = std::make_pair(lambda->solution_value(), weight_values);
return res;
} | 32.795556 | 79 | 0.639789 | [
"vector"
] |
4b563eeda109d9982162b2ea3b6d8716d401fa72 | 10,255 | cpp | C++ | test/range/python/python_range_example.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | test/range/python/python_range_example.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | test/range/python/python_range_example.cpp | rogiervd/range | 2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2014, 2015 Rogier van Dalen.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* \file
Provide an example usage of python_range.
The functions defined here are exported to Python, and used by
test-python_range.py.
*/
#include <string>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include "range/python/range.hpp"
using range::python_range;
void test_static() {
BOOST_MPL_ASSERT ((std::is_same <
range::tag_of <python_range <>>::type,
range::python_range_operation::python_range_tag>));
BOOST_MPL_ASSERT ((std::is_same <
range::tag_of <python_range <double> &>::type,
range::python_range_operation::python_range_tag>));
BOOST_MPL_ASSERT ((std::is_same <
range::tag_of <python_range <double> const &>::type,
range::python_range_operation::python_range_tag>));
BOOST_MPL_ASSERT ((std::is_same <
range::tag_of <python_range <double, int> const &&>::type,
range::python_range_operation::python_range_tag>));
BOOST_MPL_ASSERT ((std::is_same <
range::tag_of <python_range <double, int, float> &&>::type,
range::python_range_operation::python_range_tag>));
BOOST_MPL_ASSERT ((range::has <
range::callable::empty (range::python_range <int>)>));
BOOST_MPL_ASSERT ((range::has <
range::callable::empty (range::python_range <int> const &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::size (range::python_range <int> &)>));
BOOST_MPL_ASSERT ((range::has <
range::callable::first (range::python_range <int>)>));
BOOST_MPL_ASSERT ((range::has <
range::callable::first (range::python_range <int> &)>));
BOOST_MPL_ASSERT ((range::has <
range::callable::first (range::python_range <int> const &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::first (direction::back, range::python_range <int>)>));
// drop: only for rvalues.
BOOST_MPL_ASSERT ((range::has <
range::callable::drop (range::python_range <int>)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::drop (range::python_range <int> &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::drop (range::python_range <int> const &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::drop (direction::back, range::python_range <int>)>));
// chop: only for rvalues.
BOOST_MPL_ASSERT ((range::has <
range::callable::chop (range::python_range <int>)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::chop (range::python_range <int> &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::chop (range::python_range <int> const &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::chop (direction::back, range::python_range <int>)>));
// chop_in_place: only for lvalue references.
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::chop_in_place (range::python_range <int>)>));
BOOST_MPL_ASSERT ((range::has <
range::callable::chop_in_place (range::python_range <int> &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::chop_in_place (range::python_range <int> const &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::chop_in_place (
direction::back, range::python_range <int> &)>));
// But only for homogeneous ranges.
BOOST_MPL_ASSERT ((range::has <
range::callable::chop_in_place (range::python_range <> &)>));
BOOST_MPL_ASSERT ((range::has <
range::callable::chop_in_place (range::python_range <int> &)>));
BOOST_MPL_ASSERT_NOT ((range::has <
range::callable::chop_in_place (range::python_range <int, double> &)>));
// Return types.
// first.
BOOST_MPL_ASSERT ((std::is_same <range::result_of <
range::callable::first (range::python_range<>)>::type,
boost::python::object>));
BOOST_MPL_ASSERT ((std::is_same <range::result_of <
range::callable::first (range::python_range <int>)>::type,
int>));
BOOST_MPL_ASSERT ((std::is_same <range::result_of <
range::callable::first (range::python_range <double, char>)>::type,
double>));
// drop.
BOOST_MPL_ASSERT ((std::is_same <range::result_of <
range::callable::drop (range::python_range<>)>::type,
range::python_range<>>));
BOOST_MPL_ASSERT ((std::is_same <range::result_of <
range::callable::drop (range::python_range <int>)>::type,
range::python_range <int>>));
BOOST_MPL_ASSERT ((std::is_same <range::result_of <
range::callable::drop (range::python_range <double, char>)>::type,
range::python_range <char>>));
}
template <class Range> void check_empty (Range range)
{ assert (range::empty (range)); }
template <class DoubleRange>
void check_6_25_8_5 (DoubleRange double_range)
{
assert (range::first (double_range) == 6.25);
double_range = range::drop (std::move (double_range));
assert (!range::empty (double_range));
assert (range::first (double_range) == 8.5);
double_range = range::drop (std::move (double_range));
assert (range::empty (double_range));
assert (range::empty (double_range));
assert (range::empty (double_range));
}
template <class DoubleRange>
void check_6_25_8_5_chop (DoubleRange double_range)
{
assert (range::chop_in_place (double_range) == 6.25);
assert (!range::empty (double_range));
assert (range::chop_in_place (double_range) == 8.5);
assert (range::empty (double_range));
}
template <class DoubleRange>
void check_6_25_8_5_chop_in_place (DoubleRange double_range)
{
auto next = range::chop (std::move (double_range));
assert (next.first() == 6.25);
assert (!range::empty (next.rest()));
next = range::chop (std::move (next.rest()));
assert (next.first() == 8.5);
assert (range::empty (next.rest()));
}
void check_5_hello_untyped (python_range<> range) {
assert (!range::empty (range));
assert (boost::python::extract <int> (range::first (range)) == 5);
auto range2 = range::drop (std::move (range));
std::string s = boost::python::extract <std::string> (
range::first (range2));
assert (s == "hello");
// This should be possible: at the end of the type sequence, the last
// element (here, std::string) gets repeated forever.
range2 = range::drop (std::move (range2));
assert (range::empty (range2));
}
void check_5_hello_typed (python_range <int, std::string> range) {
assert (!range::empty (range));
assert (range::first (range) == 5);
auto range2 = range::drop (std::move (range));
auto second = range::chop (std::move (range2));
assert (second.first() == "hello");
// This should be possible: at the end of the type sequence, the last
// element (here, std::string) gets repeated forever.
range2 = std::move (second.rest());
assert (range::empty (range2));
}
void check_5_hello_overtyped (
python_range <int, std::string, char, double> range)
{
assert (!range::empty (range));
assert (range::first (range) == 5);
auto range2 = range::drop (std::move (range));
std::string s = range::first (range2);
assert (s == "hello");
auto range3 = range::drop (std::move (range2));
assert (range::empty (range3));
}
// List of tuples, i.e. nested python_range's.
void check_hello_5_bye_27 (
python_range <python_range <std::string, int>> r)
{
python_range <std::string, int> element = range::first (r);
assert (range::first (element) == "hello");
assert (range::first (range::drop (std::move (element))) == 5);
r = range::drop (std::move (r));
element = range::first (r);
assert (range::first (element) == "bye");
assert (range::first (range::drop (std::move (element))) == 27);
r = range::drop (std::move (r));
assert (range::empty (r));
}
// Check that None can be an element of the range without problem.
void check_17_None_hi (python_range<> r) {
using boost::python::object;
assert (range::chop_in_place (r) == object (17));
assert (range::chop_in_place (r) == object());
assert (range::chop_in_place (r) == object("hi"));
assert (range::empty (r));
}
boost::python::handle<> test_return_something() {
boost::python::object o (1);
return boost::python::handle<> (boost::python::incref (o.ptr()));
}
BOOST_PYTHON_MODULE (python_range_example) {
using namespace boost::python;
range::python::convert_object_to_range <python_range <>>();
range::python::convert_object_to_range <python_range <double>>();
range::python::convert_object_to_range <python_range <int, std::string>>();
range::python::convert_object_to_range <
python_range <int, std::string, char, double>>();
range::python::convert_object_to_range <python_range <std::string, int>>();
range::python::convert_object_to_range <
python_range <python_range <std::string, int>>>();
def <void (python_range<>)> ("check_empty", check_empty);
def <void (python_range <double>)> ("check_empty_2", check_empty);
def <void (python_range <double>)> ("check_6_25_8_5", check_6_25_8_5);
def <void (python_range <double>)> (
"check_6_25_8_5_chop", check_6_25_8_5_chop);
def <void (python_range <double>)> (
"check_6_25_8_5_chop_in_place", check_6_25_8_5_chop_in_place);
def ("check_5_hello_untyped", check_5_hello_untyped);
def ("check_5_hello_typed", check_5_hello_typed);
def ("check_5_hello_overtyped", check_5_hello_overtyped);
def ("check_hello_5_bye_27", check_hello_5_bye_27);
def ("check_17_None_hi", check_17_None_hi);
def ("test_return_something", test_return_something);
}
| 38.698113 | 80 | 0.660361 | [
"object"
] |
4b58a2ede23e7391573da6501b5f8bd759894219 | 7,374 | cpp | C++ | mlir/tools/qcor-mlir-tool.cpp | moar55/qcor | e744642c3e87ededf60813a442b7cde502467de4 | [
"BSD-3-Clause"
] | null | null | null | mlir/tools/qcor-mlir-tool.cpp | moar55/qcor | e744642c3e87ededf60813a442b7cde502467de4 | [
"BSD-3-Clause"
] | null | null | null | mlir/tools/qcor-mlir-tool.cpp | moar55/qcor | e744642c3e87ededf60813a442b7cde502467de4 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2018-, UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the BSD 3-Clause License
* which accompanies this distribution.
*
* Contributors:
* Alexander J. McCaskey - initial API and implementation
* Thien Nguyen - implementation
*******************************************************************************/
#include <fstream>
#include "Quantum/QuantumDialect.h"
#include "llvm/Support/TargetSelect.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Dialect/Vector/VectorOps.h"
#include "mlir/ExecutionEngine/ExecutionEngine.h"
#include "mlir/ExecutionEngine/OptUtils.h"
#include "mlir/IR/AsmState.h"
#include "mlir/Parser.h"
#include "openqasm_mlir_generator.hpp"
#include "openqasmv3_mlir_generator.hpp"
#include "pass_manager.hpp"
#include "qcor-mlir-helper.hpp"
#include "quantum_to_llvm.hpp"
#include "tools/ast_printer.hpp"
using namespace mlir;
using namespace staq;
using namespace qcor;
namespace cl = llvm::cl;
static cl::opt<std::string> inputFilename(cl::Positional,
cl::desc("<input openqasm file>"),
cl::init("-"),
cl::value_desc("filename"));
static cl::opt<std::string> qpu(
"qpu", cl::desc("The quantum coprocessor to compile to."));
static cl::opt<std::string> qrt(
"qrt", cl::desc("The quantum execution mode: ftqc or nisq."));
static cl::opt<std::string> shots(
"shots", cl::desc("The number of shots for nisq mode execution."));
cl::opt<bool> noEntryPoint("no-entrypoint",
cl::desc("Do not add main() to compiled output."));
cl::opt<bool> mlir_quantum_opt(
"q-optimize",
cl::desc("Turn on MLIR-level quantum instruction optimizations."));
cl::opt<std::string> mlir_specified_func_name(
"internal-func-name", cl::desc("qcor provided function name"));
static cl::opt<bool> verbose_error(
"verbose-error", cl::desc("Printout the full MLIR Module on error."));
static cl::opt<bool> print_final_submission(
"print-final-submission", cl::desc("Print the XACC IR representation for submitted quantum code."));
static cl::opt<bool> OptLevelO0(
"O0", cl::desc("Optimization level 0. Similar to clang -O0. "));
static cl::opt<bool> OptLevelO1(
"O1", cl::desc("Optimization level 1. Similar to clang -O1. "));
static cl::opt<bool> OptLevelO2(
"O2", cl::desc("Optimization level 2. Similar to clang -O2. "));
static cl::opt<bool> OptLevelO3(
"O3", cl::desc("Optimization level 3. Similar to clang -O3. "));
namespace {
enum Action { None, DumpMLIR, DumpMLIRLLVM, DumpLLVMIR };
}
static cl::opt<enum Action> emitAction(
"emit", cl::desc("Select the kind of output desired"),
cl::values(clEnumValN(DumpMLIR, "mlir", "output the MLIR dump")),
cl::values(clEnumValN(DumpLLVMIR, "llvm", "output the LLVM IR dump")),
cl::values(clEnumValN(DumpMLIRLLVM, "mlir-llvm",
"output the MLIR LLVM Dialect dump")));
namespace {
enum InputType { QASM };
}
static cl::opt<enum InputType> inputType(
"x", cl::init(QASM), cl::desc("Decided the kind of output desired"),
cl::values(clEnumValN(QASM, "qasm",
"load the input file as a qasm source.")));
int main(int argc, char **argv) {
mlir::registerAsmPrinterCLOptions();
mlir::registerMLIRContextCLOptions();
mlir::registerPassManagerCLOptions();
llvm::cl::ParseCommandLineOptions(argc, argv,
"qcor quantum assembly compiler\n");
// If any *clang* optimization is requested, turn on quantum optimization as
// well.
bool qoptimizations =
mlir_quantum_opt || OptLevelO1 || OptLevelO2 || OptLevelO3;
std::string input_func_name = "";
if (!mlir_specified_func_name.empty()) {
input_func_name = mlir_specified_func_name;
}
// Check for extra quantum compiler flags.
std::map<std::string, std::string> extra_args;
if (!qpu.empty()) {
extra_args.insert({"qpu", qpu});
}
if (!qrt.empty()) {
extra_args.insert({"qrt", qrt});
}
if (!shots.empty()) {
extra_args.insert({"shots", shots});
}
if (verbose_error) {
extra_args.insert({"verbose_error", ""});
}
if (print_final_submission) {
extra_args.insert({"print_final_submission", ""});
}
auto mlir_gen_result = qcor::util::mlir_gen(inputFilename, !noEntryPoint,
input_func_name, extra_args);
mlir::OwningModuleRef &module = *(mlir_gen_result.module_ref);
mlir::MLIRContext &context = *(mlir_gen_result.mlir_context);
std::vector<std::string> &unique_function_names =
mlir_gen_result.unique_function_names;
// Create the PassManager for lowering to LLVM MLIR and run it
mlir::PassManager pm(&context);
applyPassManagerCLOptions(pm);
std::string BOLD = "\033[1m";
std::string RED = "\033[91m";
std::string CLEAR = "\033[0m";
if (qoptimizations) {
// Add optimization passes
qcor::configureOptimizationPasses(pm);
}
if (emitAction == Action::DumpMLIR) {
if (qoptimizations) {
auto module_op = (*module).getOperation();
if (mlir::failed(pm.run(module_op))) {
std::cout << BOLD << RED
<< "[qcor-mlir-tool] Language-to-MLIR lowering failed.\n"
<< CLEAR;
return 1;
}
}
module->dump();
return 0;
}
// Lower MLIR to LLVM
pm.addPass(std::make_unique<qcor::QuantumToLLVMLoweringPass>(
qoptimizations, unique_function_names));
auto module_op = (*module).getOperation();
if (mlir::failed(pm.run(module_op))) {
std::cout << BOLD << RED
<< "[qcor-mlir-tool] MLIR-to-LLVM_MLIR lowering failed.\n"
<< CLEAR;
return 1;
}
if (emitAction == Action::DumpMLIRLLVM) {
module->dump();
return 0;
}
// Now lower MLIR to LLVM IR
llvm::LLVMContext llvmContext;
auto llvmModule = mlir::translateModuleToLLVMIR(*module, llvmContext);
if (!llvmModule) {
std::cout << BOLD << RED
<< "[qcor-mlir-tool] MLIR_LLVM-to-LLVM_IR lowering failed.\n"
<< CLEAR;
return -1;
}
// Optimize the LLVM IR
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
const unsigned optLevel =
OptLevelO3 ? 3 : (OptLevelO2 ? 2 : (OptLevelO1 ? 1 : 0));
// std::cout << "Opt level: " << optLevel << "\n";
auto optPipeline = mlir::makeOptimizingTransformer(optLevel, 0, nullptr);
if (auto err = optPipeline(llvmModule.get())) {
llvm::errs() << BOLD << RED << "Failed to optimize LLVM IR " << err << "\n"
<< CLEAR;
return -1;
}
if (emitAction == Action::DumpLLVMIR) {
llvmModule->dump();
return 0;
}
// llvmModule->dump();
// Write to an ll file
std::string s;
llvm::raw_string_ostream os(s);
llvmModule->print(os, nullptr, false, true);
os.flush();
auto file_name =
llvm::StringRef(inputFilename).split(StringRef(".")).first.str();
std::ofstream out_file(file_name + ".ll");
out_file << s;
out_file.close();
return 0;
}
| 33.216216 | 104 | 0.632221 | [
"vector"
] |
4b5b7adb67f42a2226aacf756a0e21bdcc6806c6 | 782 | cpp | C++ | src/Network.cpp | ratulSharker/Basic-Neural-Network | f93e5ec154ca5c12b86775b7e53c31818615fdc6 | [
"MIT"
] | null | null | null | src/Network.cpp | ratulSharker/Basic-Neural-Network | f93e5ec154ca5c12b86775b7e53c31818615fdc6 | [
"MIT"
] | null | null | null | src/Network.cpp | ratulSharker/Basic-Neural-Network | f93e5ec154ca5c12b86775b7e53c31818615fdc6 | [
"MIT"
] | null | null | null | #include "Network.hpp"
#include "Neuron.hpp"
#include <iostream>
Network::Network(const std::vector<unsigned> &topology)
{
std::cout<<"Constructing Neural network as topology"<<std::endl;
// loop through the topology and add the layers
for(long long index = 0 ;
index < topology.size();
++index)
{
// adding a new layer
Layer newLayer;
m_layers.push_back(newLayer);
std::cout<<"##"<<index<<" Layer"<<std::endl;
// adding neuron to the newly added layer
for(unsigned n=0; n < topology[index]; n++)
{
newLayer.push_back(Neuron());
std::cout<<"Neuron created"<<std::endl;
}
newLayer.push_back(Neuron()); // 1 extra neuron for the bias neuron
}
} | 26.965517 | 77 | 0.581841 | [
"vector"
] |
4b5d7cd10a5e03e07294d9e7a0e34f459e951f53 | 42,846 | hpp | C++ | 3rdparty/OpenCV/include/opencv2/objdetect.hpp | TaihuLight/darknet-OpenCL-sowson | 321d543dd3a30df422686082a56a88bfb6248156 | [
"MIT"
] | null | null | null | 3rdparty/OpenCV/include/opencv2/objdetect.hpp | TaihuLight/darknet-OpenCL-sowson | 321d543dd3a30df422686082a56a88bfb6248156 | [
"MIT"
] | null | null | null | 3rdparty/OpenCV/include/opencv2/objdetect.hpp | TaihuLight/darknet-OpenCL-sowson | 321d543dd3a30df422686082a56a88bfb6248156 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#ifndef OPENCV_OBJDETECT_HPP
#define OPENCV_OBJDETECT_HPP
#include "opencv2/core.hpp"
/**
@defgroup objdetect Object Detection
Haar Feature-based Cascade Classifier for Object Detection
----------------------------------------------------------
The object detector described below has been initially proposed by Paul Viola @cite Viola01 and
improved by Rainer Lienhart @cite Lienhart02 .
First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is
trained with a few hundred sample views of a particular object (i.e., a face or a car), called
positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary
images of the same size.
After a classifier is trained, it can be applied to a region of interest (of the same size as used
during the training) in an input image. The classifier outputs a "1" if the region is likely to show
the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can
move the search window across the image and check every location using the classifier. The
classifier is designed so that it can be easily "resized" in order to be able to find the objects of
interest at different sizes, which is more efficient than resizing the image itself. So, to find an
object of an unknown size in the image the scan procedure should be done several times at different
scales.
The word "cascade" in the classifier name means that the resultant classifier consists of several
simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some
stage the candidate is rejected or all the stages are passed. The word "boosted" means that the
classifiers at every stage of the cascade are complex themselves and they are built out of basic
classifiers using one of four different boosting techniques (weighted voting). Currently Discrete
Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are
decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic
classifiers, and are calculated as described below. The current algorithm uses the following
Haar-like features:

The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within
the region of interest and the scale (this scale is not the same as the scale used at the detection
stage, though these two scales are multiplied). For example, in the case of the third line feature
(2c) the response is calculated as the difference between the sum of image pixels under the
rectangle covering the whole feature (including the two white stripes and the black stripe in the
middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to
compensate for the differences in the size of areas. The sums of pixel values over a rectangular
regions are calculated rapidly using integral images (see below and the integral description).
To see the object detector at work, have a look at the facedetect demo:
<https://github.com/opencv/opencv/tree/3.4/samples/cpp/dbt_face_detection.cpp>
The following reference is for the detection part only. There is a separate application called
opencv_traincascade that can train a cascade of boosted classifiers from a set of samples.
@note In the new C++ interface it is also possible to use LBP (local binary pattern) features in
addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection
using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at
<http://research.microsoft.com/en-us/um/people/viola/Pubs/Detect/violaJones_CVPR2001.pdf>
@{
@defgroup objdetect_c C API
@}
*/
typedef struct CvHaarClassifierCascade CvHaarClassifierCascade;
namespace cv
{
//! @addtogroup objdetect
//! @{
///////////////////////////// Object Detection ////////////////////////////
//! class for grouping object candidates, detected by Cascade Classifier, HOG etc.
//! instance of the class is to be passed to cv::partition (see cxoperations.hpp)
class CV_EXPORTS SimilarRects
{
public:
SimilarRects(double _eps) : eps(_eps) {}
inline bool operator()(const Rect& r1, const Rect& r2) const
{
double delta = eps * ((std::min)(r1.width, r2.width) + (std::min)(r1.height, r2.height)) * 0.5;
return std::abs(r1.x - r2.x) <= delta &&
std::abs(r1.y - r2.y) <= delta &&
std::abs(r1.x + r1.width - r2.x - r2.width) <= delta &&
std::abs(r1.y + r1.height - r2.y - r2.height) <= delta;
}
double eps;
};
/** @brief Groups the object candidate rectangles.
@param rectList Input/output vector of rectangles. Output vector includes retained and grouped
rectangles. (The Python list is not modified in place.)
@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a
group of rectangles to retain it.
@param eps Relative difference between sides of the rectangles to merge them into a group.
The function is a wrapper for the generic function partition . It clusters all the input rectangles
using the rectangle equivalence criteria that combines rectangles with similar sizes and similar
locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If
\f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small
clusters containing less than or equal to groupThreshold rectangles are rejected. In each other
cluster, the average rectangle is computed and put into the output rectangle list.
*/
CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, int groupThreshold, double eps = 0.2);
/** @overload */
CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector<Rect>& rectList, CV_OUT std::vector<int>& weights,
int groupThreshold, double eps = 0.2);
/** @overload */
CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, int groupThreshold,
double eps, std::vector<int>* weights, std::vector<double>* levelWeights );
/** @overload */
CV_EXPORTS void groupRectangles(std::vector<Rect>& rectList, std::vector<int>& rejectLevels,
std::vector<double>& levelWeights, int groupThreshold, double eps = 0.2);
/** @overload */
CV_EXPORTS void groupRectangles_meanshift(std::vector<Rect>& rectList, std::vector<double>& foundWeights,
std::vector<double>& foundScales,
double detectThreshold = 0.0, Size winDetSize = Size(64, 128));
template<> CV_EXPORTS void DefaultDeleter<CvHaarClassifierCascade>::operator ()(CvHaarClassifierCascade* obj) const;
enum { CASCADE_DO_CANNY_PRUNING = 1,
CASCADE_SCALE_IMAGE = 2,
CASCADE_FIND_BIGGEST_OBJECT = 4,
CASCADE_DO_ROUGH_SEARCH = 8
};
class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm
{
public:
virtual ~BaseCascadeClassifier();
virtual bool empty() const CV_OVERRIDE = 0;
virtual bool load( const String& filename ) = 0;
virtual void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
double scaleFactor,
int minNeighbors, int flags,
Size minSize, Size maxSize ) = 0;
virtual void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& numDetections,
double scaleFactor,
int minNeighbors, int flags,
Size minSize, Size maxSize ) = 0;
virtual void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& rejectLevels,
CV_OUT std::vector<double>& levelWeights,
double scaleFactor,
int minNeighbors, int flags,
Size minSize, Size maxSize,
bool outputRejectLevels ) = 0;
virtual bool isOldFormatCascade() const = 0;
virtual Size getOriginalWindowSize() const = 0;
virtual int getFeatureType() const = 0;
virtual void* getOldCascade() = 0;
class CV_EXPORTS MaskGenerator
{
public:
virtual ~MaskGenerator() {}
virtual Mat generateMask(const Mat& src)=0;
virtual void initializeMask(const Mat& /*src*/) { }
};
virtual void setMaskGenerator(const Ptr<MaskGenerator>& maskGenerator) = 0;
virtual Ptr<MaskGenerator> getMaskGenerator() = 0;
};
/** @example samples/cpp/facedetect.cpp
This program demonstrates usage of the Cascade classifier class
\image html Cascade_Classifier_Tutorial_Result_Haar.jpg "Sample screenshot" width=321 height=254
*/
/** @brief Cascade classifier class for object detection.
*/
class CV_EXPORTS_W CascadeClassifier
{
public:
CV_WRAP CascadeClassifier();
/** @brief Loads a classifier from a file.
@param filename Name of the file from which the classifier is loaded.
*/
CV_WRAP CascadeClassifier(const String& filename);
~CascadeClassifier();
/** @brief Checks whether the classifier has been loaded.
*/
CV_WRAP bool empty() const;
/** @brief Loads a classifier from a file.
@param filename Name of the file from which the classifier is loaded. The file may contain an old
HAAR classifier trained by the haartraining application or a new cascade classifier trained by the
traincascade application.
*/
CV_WRAP bool load( const String& filename );
/** @brief Reads a classifier from a FileStorage node.
@note The file may contain a new cascade classifier (trained traincascade application) only.
*/
CV_WRAP bool read( const FileNode& node );
/** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
of rectangles.
@param image Matrix of the type CV_8U containing an image where objects are detected.
@param objects Vector of rectangles where each rectangle contains the detected object, the
rectangles may be partially outside the original image.
@param scaleFactor Parameter specifying how much the image size is reduced at each image scale.
@param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have
to retain it.
@param flags Parameter with the same meaning for an old cascade as in the function
cvHaarDetectObjects. It is not used for a new cascade.
@param minSize Minimum possible object size. Objects smaller than that are ignored.
@param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale.
The function is parallelized with the TBB library.
@note
- (Python) A face detection example using cascade classifiers can be found at
opencv_source_code/samples/python/facedetect.py
*/
CV_WRAP void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
double scaleFactor = 1.1,
int minNeighbors = 3, int flags = 0,
Size minSize = Size(),
Size maxSize = Size() );
/** @overload
@param image Matrix of the type CV_8U containing an image where objects are detected.
@param objects Vector of rectangles where each rectangle contains the detected object, the
rectangles may be partially outside the original image.
@param numDetections Vector of detection numbers for the corresponding objects. An object's number
of detections is the number of neighboring positively classified rectangles that were joined
together to form the object.
@param scaleFactor Parameter specifying how much the image size is reduced at each image scale.
@param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have
to retain it.
@param flags Parameter with the same meaning for an old cascade as in the function
cvHaarDetectObjects. It is not used for a new cascade.
@param minSize Minimum possible object size. Objects smaller than that are ignored.
@param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale.
*/
CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& numDetections,
double scaleFactor=1.1,
int minNeighbors=3, int flags=0,
Size minSize=Size(),
Size maxSize=Size() );
/** @overload
This function allows you to retrieve the final stage decision certainty of classification.
For this, one needs to set `outputRejectLevels` on true and provide the `rejectLevels` and `levelWeights` parameter.
For each resulting detection, `levelWeights` will then contain the certainty of classification at the final stage.
This value can then be used to separate strong from weaker classifications.
A code sample on how to use it efficiently can be found below:
@code
Mat img;
vector<double> weights;
vector<int> levels;
vector<Rect> detections;
CascadeClassifier model("/path/to/your/model.xml");
model.detectMultiScale(img, detections, levels, weights, 1.1, 3, 0, Size(), Size(), true);
cerr << "Detection " << detections[0] << " with weight " << weights[0] << endl;
@endcode
*/
CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image,
CV_OUT std::vector<Rect>& objects,
CV_OUT std::vector<int>& rejectLevels,
CV_OUT std::vector<double>& levelWeights,
double scaleFactor = 1.1,
int minNeighbors = 3, int flags = 0,
Size minSize = Size(),
Size maxSize = Size(),
bool outputRejectLevels = false );
CV_WRAP bool isOldFormatCascade() const;
CV_WRAP Size getOriginalWindowSize() const;
CV_WRAP int getFeatureType() const;
void* getOldCascade();
CV_WRAP static bool convert(const String& oldcascade, const String& newcascade);
void setMaskGenerator(const Ptr<BaseCascadeClassifier::MaskGenerator>& maskGenerator);
Ptr<BaseCascadeClassifier::MaskGenerator> getMaskGenerator();
Ptr<BaseCascadeClassifier> cc;
};
CV_EXPORTS Ptr<BaseCascadeClassifier::MaskGenerator> createFaceDetectionMaskGenerator();
//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
//! struct for detection region of interest (ROI)
struct DetectionROI
{
//! scale(size) of the bounding box
double scale;
//! set of requested locations to be evaluated
std::vector<cv::Point> locations;
//! vector that will contain confidence values for each location
std::vector<double> confidences;
};
/**@brief Implementation of HOG (Histogram of Oriented Gradients) descriptor and object detector.
the HOG descriptor algorithm introduced by Navneet Dalal and Bill Triggs @cite Dalal2005 .
useful links:
https://hal.inria.fr/inria-00548512/document/
https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients
https://software.intel.com/en-us/ipp-dev-reference-histogram-of-oriented-gradients-hog-descriptor
http://www.learnopencv.com/histogram-of-oriented-gradients
http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial
*/
struct CV_EXPORTS_W HOGDescriptor
{
public:
enum { L2Hys = 0 //!< Default histogramNormType
};
enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value.
};
/**@brief Creates the HOG descriptor and detector with default params.
aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9, 1 )
*/
CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8),
cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1),
histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true),
free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false)
{}
/** @overload
@param _winSize sets winSize with given value.
@param _blockSize sets blockSize with given value.
@param _blockStride sets blockStride with given value.
@param _cellSize sets cellSize with given value.
@param _nbins sets nbins with given value.
@param _derivAperture sets derivAperture with given value.
@param _winSigma sets winSigma with given value.
@param _histogramNormType sets histogramNormType with given value.
@param _L2HysThreshold sets L2HysThreshold with given value.
@param _gammaCorrection sets gammaCorrection with given value.
@param _nlevels sets nlevels with given value.
@param _signedGradient sets signedGradient with given value.
*/
CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride,
Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1,
int _histogramNormType=HOGDescriptor::L2Hys,
double _L2HysThreshold=0.2, bool _gammaCorrection=false,
int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false)
: winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize),
nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma),
histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold),
gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient)
{}
/** @overload
@param filename the file name containing HOGDescriptor properties and coefficients of the trained classifier
*/
CV_WRAP HOGDescriptor(const String& filename)
{
load(filename);
}
/** @overload
@param d the HOGDescriptor which cloned to create a new one.
*/
HOGDescriptor(const HOGDescriptor& d)
{
d.copyTo(*this);
}
/**@brief Default destructor.
*/
virtual ~HOGDescriptor() {}
/**@brief Returns the number of coefficients required for the classification.
*/
CV_WRAP size_t getDescriptorSize() const;
/** @brief Checks if detector size equal to descriptor size.
*/
CV_WRAP bool checkDetectorSize() const;
/** @brief Returns winSigma value
*/
CV_WRAP double getWinSigma() const;
/**@example samples/cpp/peopledetect.cpp
*/
/**@brief Sets coefficients for the linear SVM classifier.
@param _svmdetector coefficients for the linear SVM classifier.
*/
CV_WRAP virtual void setSVMDetector(InputArray _svmdetector);
/** @brief Reads HOGDescriptor parameters from a file node.
@param fn File node
*/
virtual bool read(FileNode& fn);
/** @brief Stores HOGDescriptor parameters in a file storage.
@param fs File storage
@param objname Object name
*/
virtual void write(FileStorage& fs, const String& objname) const;
/** @brief loads coefficients for the linear SVM classifier from a file
@param filename Name of the file to read.
@param objname The optional name of the node to read (if empty, the first top-level node will be used).
*/
CV_WRAP virtual bool load(const String& filename, const String& objname = String());
/** @brief saves coefficients for the linear SVM classifier to a file
@param filename File name
@param objname Object name
*/
CV_WRAP virtual void save(const String& filename, const String& objname = String()) const;
/** @brief clones the HOGDescriptor
@param c cloned HOGDescriptor
*/
virtual void copyTo(HOGDescriptor& c) const;
/**@example samples/cpp/train_HOG.cpp
*/
/** @brief Computes HOG descriptors of given image.
@param img Matrix of the type CV_8U containing an image where HOG features will be calculated.
@param descriptors Matrix of the type CV_32F
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param locations Vector of Point
*/
CV_WRAP virtual void compute(InputArray img,
CV_OUT std::vector<float>& descriptors,
Size winStride = Size(), Size padding = Size(),
const std::vector<Point>& locations = std::vector<Point>()) const;
/** @brief Performs object detection without a multi-scale window.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries.
@param weights Vector that will contain confidence values for each detected object.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param searchLocations Vector of Point includes set of requested locations to be evaluated.
*/
CV_WRAP virtual void detect(const Mat& img, CV_OUT std::vector<Point>& foundLocations,
CV_OUT std::vector<double>& weights,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(),
const std::vector<Point>& searchLocations = std::vector<Point>()) const;
/** @brief Performs object detection without a multi-scale window.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param searchLocations Vector of Point includes locations to search.
*/
virtual void detect(const Mat& img, CV_OUT std::vector<Point>& foundLocations,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(),
const std::vector<Point>& searchLocations=std::vector<Point>()) const;
/** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
of rectangles.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of rectangles where each rectangle contains the detected object.
@param foundWeights Vector that will contain confidence values for each detected object.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param scale Coefficient of the detection window increase.
@param finalThreshold Final threshold
@param useMeanshiftGrouping indicates grouping algorithm
*/
CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector<Rect>& foundLocations,
CV_OUT std::vector<double>& foundWeights, double hitThreshold = 0,
Size winStride = Size(), Size padding = Size(), double scale = 1.05,
double finalThreshold = 2.0,bool useMeanshiftGrouping = false) const;
/** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list
of rectangles.
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of rectangles where each rectangle contains the detected object.
@param hitThreshold Threshold for the distance between features and SVM classifying plane.
Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient).
But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param winStride Window stride. It must be a multiple of block stride.
@param padding Padding
@param scale Coefficient of the detection window increase.
@param finalThreshold Final threshold
@param useMeanshiftGrouping indicates grouping algorithm
*/
virtual void detectMultiScale(InputArray img, CV_OUT std::vector<Rect>& foundLocations,
double hitThreshold = 0, Size winStride = Size(),
Size padding = Size(), double scale = 1.05,
double finalThreshold = 2.0, bool useMeanshiftGrouping = false) const;
/** @brief Computes gradients and quantized gradient orientations.
@param img Matrix contains the image to be computed
@param grad Matrix of type CV_32FC2 contains computed gradients
@param angleOfs Matrix of type CV_8UC2 contains quantized gradient orientations
@param paddingTL Padding from top-left
@param paddingBR Padding from bottom-right
*/
CV_WRAP virtual void computeGradient(const Mat& img, CV_OUT Mat& grad, CV_OUT Mat& angleOfs,
Size paddingTL = Size(), Size paddingBR = Size()) const;
/** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows).
*/
CV_WRAP static std::vector<float> getDefaultPeopleDetector();
/**@example samples/tapi/hog.cpp
*/
/** @brief Returns coefficients of the classifier trained for people detection (for 48x96 windows).
*/
CV_WRAP static std::vector<float> getDaimlerPeopleDetector();
//! Detection window size. Align to block size and block stride. Default value is Size(64,128).
CV_PROP Size winSize;
//! Block size in pixels. Align to cell size. Default value is Size(16,16).
CV_PROP Size blockSize;
//! Block stride. It must be a multiple of cell size. Default value is Size(8,8).
CV_PROP Size blockStride;
//! Cell size. Default value is Size(8,8).
CV_PROP Size cellSize;
//! Number of bins used in the calculation of histogram of gradients. Default value is 9.
CV_PROP int nbins;
//! not documented
CV_PROP int derivAperture;
//! Gaussian smoothing window parameter.
CV_PROP double winSigma;
//! histogramNormType
CV_PROP int histogramNormType;
//! L2-Hys normalization method shrinkage.
CV_PROP double L2HysThreshold;
//! Flag to specify whether the gamma correction preprocessing is required or not.
CV_PROP bool gammaCorrection;
//! coefficients for the linear SVM classifier.
CV_PROP std::vector<float> svmDetector;
//! coefficients for the linear SVM classifier used when OpenCL is enabled
UMat oclSvmDetector;
//! not documented
float free_coef;
//! Maximum number of detection window increases. Default value is 64
CV_PROP int nlevels;
//! Indicates signed gradient will be used or not
CV_PROP bool signedGradient;
/** @brief evaluate specified ROI and return confidence value for each location
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param locations Vector of Point
@param foundLocations Vector of Point where each Point is detected object's top-left point.
@param confidences confidences
@param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually
it is 0 and should be specified in the detector coefficients (as the last free coefficient). But if
the free coefficient is omitted (which is allowed), you can specify it manually here
@param winStride winStride
@param padding padding
*/
virtual void detectROI(const cv::Mat& img, const std::vector<cv::Point> &locations,
CV_OUT std::vector<cv::Point>& foundLocations, CV_OUT std::vector<double>& confidences,
double hitThreshold = 0, cv::Size winStride = Size(),
cv::Size padding = Size()) const;
/** @brief evaluate specified ROI and return confidence value for each location in multiple scales
@param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected.
@param foundLocations Vector of rectangles where each rectangle contains the detected object.
@param locations Vector of DetectionROI
@param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually it is 0 and should be specified
in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here.
@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
*/
virtual void detectMultiScaleROI(const cv::Mat& img,
CV_OUT std::vector<cv::Rect>& foundLocations,
std::vector<DetectionROI>& locations,
double hitThreshold = 0,
int groupThreshold = 0) const;
/** @brief read/parse Dalal's alt model file
@param modelfile Path of Dalal's alt model file.
*/
void readALTModel(String modelfile);
/** @brief Groups the object candidate rectangles.
@param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.)
@param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.)
@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it.
@param eps Relative difference between sides of the rectangles to merge them into a group.
*/
void groupRectangles(std::vector<cv::Rect>& rectList, std::vector<double>& weights, int groupThreshold, double eps) const;
};
class CV_EXPORTS_W QRCodeDetector
{
public:
CV_WRAP QRCodeDetector();
~QRCodeDetector();
/** @brief sets the epsilon used during the horizontal scan of QR code stop marker detection.
@param epsX Epsilon neighborhood, which allows you to determine the horizontal pattern
of the scheme 1:1:3:1:1 according to QR code standard.
*/
CV_WRAP void setEpsX(double epsX);
/** @brief sets the epsilon used during the vertical scan of QR code stop marker detection.
@param epsY Epsilon neighborhood, which allows you to determine the vertical pattern
of the scheme 1:1:3:1:1 according to QR code standard.
*/
CV_WRAP void setEpsY(double epsY);
/** @brief Detects QR code in image and returns the quadrangle containing the code.
@param img grayscale or color (BGR) image containing (or not) QR code.
@param points Output vector of vertices of the minimum-area quadrangle containing the code.
*/
CV_WRAP bool detect(InputArray img, OutputArray points) const;
/** @brief Decodes QR code in image once it's found by the detect() method.
Returns UTF8-encoded output string or empty string if the code cannot be decoded.
@param img grayscale or color (BGR) image containing QR code.
@param points Quadrangle vertices found by detect() method (or some other algorithm).
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
CV_WRAP cv::String decode(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
/** @brief Decodes QR code on a curved surface in image once it's found by the detect() method.
Returns UTF8-encoded output string or empty string if the code cannot be decoded.
@param img grayscale or color (BGR) image containing QR code.
@param points Quadrangle vertices found by detect() method (or some other algorithm).
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
CV_WRAP cv::String decodeCurved(InputArray img, InputArray points, OutputArray straight_qrcode = noArray());
/** @brief Both detects and decodes QR code
@param img grayscale or color (BGR) image containing QR code.
@param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found.
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
CV_WRAP cv::String detectAndDecode(InputArray img, OutputArray points=noArray(),
OutputArray straight_qrcode = noArray());
/** @brief Both detects and decodes QR code on a curved surface
@param img grayscale or color (BGR) image containing QR code.
@param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found.
@param straight_qrcode The optional output image containing rectified and binarized QR code
*/
CV_WRAP cv::String detectAndDecodeCurved(InputArray img, OutputArray points=noArray(),
OutputArray straight_qrcode = noArray());
/** @brief Detects QR codes in image and returns the vector of the quadrangles containing the codes.
@param img grayscale or color (BGR) image containing (or not) QR codes.
@param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes.
*/
CV_WRAP
bool detectMulti(InputArray img, OutputArray points) const;
/** @brief Decodes QR codes in image once it's found by the detect() method.
@param img grayscale or color (BGR) image containing QR codes.
@param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
@param points vector of Quadrangle vertices found by detect() method (or some other algorithm).
@param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
*/
CV_WRAP
bool decodeMulti(
InputArray img, InputArray points,
CV_OUT std::vector<cv::String>& decoded_info,
OutputArrayOfArrays straight_qrcode = noArray()
) const;
/** @brief Both detects and decodes QR codes
@param img grayscale or color (BGR) image containing QR codes.
@param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded.
@param points optional output vector of vertices of the found QR code quadrangles. Will be empty if not found.
@param straight_qrcode The optional output vector of images containing rectified and binarized QR codes
*/
CV_WRAP
bool detectAndDecodeMulti(
InputArray img, CV_OUT std::vector<cv::String>& decoded_info,
OutputArray points = noArray(),
OutputArrayOfArrays straight_qrcode = noArray()
) const;
#ifndef CV_DOXYGEN // COMPATIBILITY
inline bool decodeMulti(
InputArray img, InputArray points,
CV_OUT std::vector<std::string>& decoded_info,
OutputArrayOfArrays straight_qrcode = noArray()
) const
{
std::vector<cv::String> decoded_info_;
bool res = decodeMulti(img, points, decoded_info_, straight_qrcode);
decoded_info.resize(decoded_info_.size());
for (size_t i = 0; i < decoded_info.size(); ++i)
{
cv::String s; std::swap(s, decoded_info_[i]);
decoded_info[i] = s;
}
return res;
}
inline bool detectAndDecodeMulti(
InputArray img, CV_OUT std::vector<std::string>& decoded_info,
OutputArray points = noArray(),
OutputArrayOfArrays straight_qrcode = noArray()
) const
{
std::vector<cv::String> decoded_info_;
bool res = detectAndDecodeMulti(img, decoded_info_, points, straight_qrcode);
decoded_info.resize(decoded_info_.size());
for (size_t i = 0; i < decoded_info.size(); ++i)
{
cv::String s; std::swap(s, decoded_info_[i]);
decoded_info[i] = s;
}
return res;
}
#endif
protected:
struct Impl;
Ptr<Impl> p;
};
/** @brief Detect QR code in image and return minimum area of quadrangle that describes QR code.
@param in Matrix of the type CV_8UC1 containing an image where QR code are detected.
@param points Output vector of vertices of a quadrangle of minimal area that describes QR code.
@param eps_x Epsilon neighborhood, which allows you to determine the horizontal pattern of the scheme 1:1:3:1:1 according to QR code standard.
@param eps_y Epsilon neighborhood, which allows you to determine the vertical pattern of the scheme 1:1:3:1:1 according to QR code standard.
*/
CV_EXPORTS bool detectQRCode(InputArray in, std::vector<Point> &points, double eps_x = 0.2, double eps_y = 0.1);
/** @brief Decode QR code in image and return text that is encrypted in QR code.
@param in Matrix of the type CV_8UC1 containing an image where QR code are detected.
@param points Input vector of vertices of a quadrangle of minimal area that describes QR code.
@param decoded_info String information that is encrypted in QR code.
@param straight_qrcode Matrix of the type CV_8UC1 containing an binary straight QR code.
*/
CV_EXPORTS bool decodeQRCode(InputArray in, InputArray points, std::string &decoded_info, OutputArray straight_qrcode = noArray());
/** @brief Decode QR code on a curved surface in image and return text that is encrypted in QR code.
@param in Matrix of the type CV_8UC1 containing an image where QR code are detected.
@param points Input vector of vertices of a quadrangle of minimal area that describes QR code.
@param decoded_info String information that is encrypted in QR code.
@param straight_qrcode Matrix of the type CV_8UC1 containing an binary straight QR code.
*/
CV_EXPORTS bool decodeCurvedQRCode(InputArray in, InputArray points, std::string &decoded_info, OutputArray straight_qrcode = noArray());
//! @} objdetect
}
#include "opencv2/objdetect/detection_based_tracker.hpp"
#ifndef DISABLE_OPENCV_24_COMPATIBILITY
#include "opencv2/objdetect/objdetect_c.h"
#endif
#endif
| 50.946492 | 176 | 0.685035 | [
"object",
"shape",
"vector",
"model"
] |
4b62aee9a865594d90ab6527d3a8014cc87e9a11 | 12,394 | cpp | C++ | OpenGL/i0rShaderManager/Shader.cpp | i0r/i0rTech | c74b327345e6e9e1a08c6b5631e84383431f2661 | [
"BSD-3-Clause"
] | null | null | null | OpenGL/i0rShaderManager/Shader.cpp | i0r/i0rTech | c74b327345e6e9e1a08c6b5631e84383431f2661 | [
"BSD-3-Clause"
] | null | null | null | OpenGL/i0rShaderManager/Shader.cpp | i0r/i0rTech | c74b327345e6e9e1a08c6b5631e84383431f2661 | [
"BSD-3-Clause"
] | null | null | null | #include "../Common.hpp"
#include "UberShader.hpp"
#include "Shader.hpp"
bool GetStageCompileStatus( const u32 stage ) {
i32 linkStatus = 0, logLength = 0;
glGetShaderiv( stage, GL_COMPILE_STATUS, &linkStatus );
glGetShaderiv( stage, GL_INFO_LOG_LENGTH, &logLength );
if( logLength ) {
std::vector<char> debugLog( logLength );
glGetShaderInfoLog( stage, logLength, &logLength, &debugLog[0] );
CONSOLE_PRINT_ALL( "***STAGE COMPILATION INFORMATIONS***\n" );
CONSOLE_PRINT_ALL( debugLog.data() );
}
return ( linkStatus == GENERIC_RENDER_TRUE ) ? true : false;
}
bool GetProgramLinkStatus( const u32 program ) {
i32 linkStatus = 0, logLength = 0;
glGetProgramiv( program, GL_LINK_STATUS, &linkStatus );
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLength );
if( logLength ) {
std::vector<char> debugLog( logLength );
glGetProgramInfoLog( program, logLength, &logLength, &debugLog[0] );
CONSOLE_PRINT_ALL( "***PROGRAM LINKING INFORMATIONS***\n" );
CONSOLE_PRINT_ALL( debugLog.data() );
}
return ( linkStatus == GENERIC_RENDER_TRUE ) ? true : false;
}
Shader::Shader() : m_VertexStage( 0 ),
m_GeometryStage( 0 ),
m_FragmentStage( 0 ),
m_TessellationControlStage( 0 ),
m_TessellationEvaluationStage( 0 ),
m_ComputeStage( 0 ),
m_IsCompiled( false ) {
m_Program = glCreateProgram();
}
Shader::~Shader() {
m_Uniforms.clear();
m_UniformsStorage.clear();
m_UniformsBlock.clear();
DeleteStages();
m_IsCompiled = false;
if( m_Program ) {
glDeleteProgram( m_Program );
m_Program = 0;
}
}
void Shader::AddStage( const std::string uberStageFile, const u32 stageType, std::vector<std::string>* stageFlags,
bool isReloading ) {
char* sft = Instance.FileSystem->GetFileText( uberStageFile.c_str() ) ;
if( !sft ) {
CONSOLE_PRINT_ERROR( "UberStage %s is empty or does not exist\n", uberStageFile.c_str() );
return;
}
std::vector<std::string> stageFileText = StringToStringArray( sft );
// preprocessing
std::size_t data = std::string::npos;
for( u32 i = 0; i < stageFileText.size(); i++ ) {
data = stageFileText[i].find( "#include" );
if (data != std::string::npos) {
std::string fileName = stageFileText[i].substr( data + 9 );
#if defined( FLAG_DEBUG )
if( !isReloading ) {
std::string newFileName = RemoveFileExtension( fileName );
Instance.ShaderManager->WatchShader( newFileName, this );
}
#endif
char* is = Instance.FileSystem->GetFileText( ( uberShaderFolder + fileName ).c_str() );
if( !is ) {
CONSOLE_PRINT_ERROR( "UberStage %s is empty or does not exist\n", ( uberShaderFolder + fileName ).c_str() );
continue;
}
std::vector<std::string> includedShader = StringToStringArray( is );
u32 lineAppend = i;
stageFileText.insert( stageFileText.begin() + lineAppend++, "" ); // fix recursive inclusion
for (const std::string &line : includedShader ) {
stageFileText.insert( stageFileText.begin() + lineAppend++, line );
}
stageFileText[lineAppend].clear();
includedShader.clear();
Instance.FileSystem->FreeUncompressedFile( is );
continue;
}
// once we reach the stage entry point, we wont find any preprocessor, so we can stop here
data = stageFileText[i].find( "void main()" );
if( data != std::string::npos ) {
break;
}
}
std::string shaderLine_ = TextFileToString(stageFileText);
if( stageFlags && stageFlags->size() ) {
std::size_t definitionIndex = shaderLine_.find( "\n" );
if (definitionIndex == std::string::npos) {
CONSOLE_PRINT_WARNING( "UberStage %s has no version preprocessor\n", uberStageFile.c_str() );
definitionIndex = 0;
} else {
definitionIndex++; // jumps the first new line char
}
shaderLine_.insert( definitionIndex, "\r\n" ); // we insert at least one carriage return before injecting preprocessor
for( std::string flag : *stageFlags ) {
shaderLine_.insert( definitionIndex, "#define " + flag + "\r\n" );
}
}
const char* shaderLine = shaderLine_.c_str();
u32* stage = NULL;
switch (stageType) {
case GL_VERTEX_SHADER:
stage = &m_VertexStage;
break;
case GL_FRAGMENT_SHADER:
stage = &m_FragmentStage;
break;
case GL_GEOMETRY_SHADER:
stage = &m_GeometryStage;
break;
case GL_TESS_CONTROL_SHADER:
stage = &m_TessellationControlStage;
break;
case GL_TESS_EVALUATION_SHADER:
stage = &m_TessellationEvaluationStage;
break;
case GL_COMPUTE_SHADER:
stage = &m_ComputeStage;
break;
default:
CONSOLE_PRINT_WARNING( "%s() => Unknown stage type 0x%X\n", __FUNCTION__, stageType );
stage = &m_VertexStage; // let's assume it's a vertex stage...
break;
}
*stage = glCreateShader( stageType );
glShaderSource( *stage, 1, &shaderLine, NULL );
glCompileShader( *stage );
if (!GetStageCompileStatus( *stage )) {
CONSOLE_PRINT_ERROR( "Failed to compile stage %s\n", uberStageFile.c_str() );
return;
}
glAttachShader( m_Program, *stage );
stageFileText.clear();
Instance.FileSystem->FreeUncompressedFile( sft );
}
void Shader::AddAttribute( const char* attributeName ) {
u32 uniform = glGetUniformLocation( m_Program, attributeName );
if ( uniform == -1 ) {
// CONSOLE_PRINT_ERROR( "Couldn't add attribute %s\n", attributeName );
return;
}
m_Uniforms.insert( std::make_pair( attributeName, uniform ) );
}
void Shader::AddUniformBlock( const char* uniformBlockName ) {
u32 uniform = glGetUniformBlockIndex( m_Program, uniformBlockName );
if ( uniform == -1 ) {
CONSOLE_PRINT_ERROR( "Could not add uniform block %s (error code: %i)\n", uniformBlockName, glGetError() );
return;
}
m_UniformsBlock.insert( std::make_pair( uniformBlockName, uniform ) );
}
void Shader::AddStorageBlock( const char* storageBlockName ) {
u32 uniform = glGetProgramResourceIndex( m_Program, GL_SHADER_STORAGE_BLOCK, storageBlockName );
if ( uniform == -1 ) {
CONSOLE_PRINT_ERROR( "Couldn't add block %s\n", storageBlockName );
return;
}
m_UniformsStorage.insert( std::make_pair( storageBlockName, uniform ) );
}
void Shader::SetAttribute1fv( const char* attribute, const f32* value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform1fv( m_UniformIterator->second, 1, value );
}
}
void Shader::SetAttribute2fv( const char* attribute, const vec2f value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform2fv( m_UniformIterator->second, 1, &value.x );
}
}
void Shader::SetAttribute2iv( const char* attribute, const vec2i value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform2iv( m_UniformIterator->second, 1, &value.x );
}
}
void Shader::SetAttribute3fv( const char* attribute, const vec3f value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform3fv( m_UniformIterator->second, 1, &value.x );
}
}
void Shader::SetAttribute3fv( const char* attribute, const colorrgbf value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform3fv( m_UniformIterator->second, 1, &value.r );
}
}
void Shader::SetAttribute4fv( const char* attribute, const vec4f value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform4fv( m_UniformIterator->second, 1, &value.x );
}
}
void Shader::SetAttribute4iv( const char* attribute, const vec4i value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform4iv( m_UniformIterator->second, 1, &value.x );
}
}
void Shader::SetAttribute4fv( const char* attribute, const colorrgbaf value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform4fv( m_UniformIterator->second, 1, &value.r );
}
}
void Shader::SetAttribute3x3fv( const char* attribute, const mat3x3f value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniformMatrix3fv( m_UniformIterator->second, 1, GENERIC_RENDER_FALSE, &value.r0.x );
}
}
void Shader::SetAttribute4x4fv( const char* attribute, const mat4x4f value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniformMatrix4fv( m_UniformIterator->second, 1, GENERIC_RENDER_FALSE, &value.r0.x );
}
}
void Shader::SetAttribute1i( const char* attribute, const i32 value ) {
m_UniformIterator = m_Uniforms.find( attribute );
if ( m_UniformIterator != m_Uniforms.end() ) {
glUniform1i( m_UniformIterator->second, value );
}
}
void Shader::SetUniformBufferIndex( const char* attribute, const u32 value ) {
m_UniformIterator = m_UniformsBlock.find( attribute );
if( m_UniformIterator != m_UniformsBlock.end() ) {
glUniformBlockBinding( m_Program, m_UniformIterator->second, value );
}
}
void Shader::SetStorageBufferIndex( const char* attribute, const u32 value ) {
m_UniformIterator = m_UniformsStorage.find( attribute );
if( m_UniformIterator != m_UniformsStorage.end() ) {
glShaderStorageBlockBinding( m_Program, m_UniformIterator->second, value );
}
}
void Shader::SetConstantAttribute1i( const char* attribute, const i32 value ) {
SetAttribute1i( attribute, value );
m_Constants[attribute] = { value, SHADER_CONSTANT_TYPE_INTEGER };
}
void Shader::SetConstantUniformBufferIndex( const char* attribute, const i32 value ) {
SetUniformBufferIndex( attribute, value );
m_Constants[attribute] = { value, SHADER_CONSTANT_TYPE_UBO };
}
void Shader::SetConstantStorageBufferIndex( const char* attribute, const i32 value ) {
SetStorageBufferIndex( attribute, value );
m_Constants[attribute] = { value, SHADER_CONSTANT_TYPE_SSBO };
}
void Shader::DeleteStages() {
if ( m_VertexStage ) {
glDetachShader( m_Program, m_VertexStage );
glDeleteShader( m_VertexStage );
m_VertexStage = 0;
}
if ( m_GeometryStage ) {
glDetachShader( m_Program, m_GeometryStage );
glDeleteShader( m_GeometryStage );
m_GeometryStage = 0;
}
if ( m_FragmentStage ) {
glDetachShader( m_Program, m_FragmentStage );
glDeleteShader( m_FragmentStage );
m_FragmentStage = 0;
}
if ( m_TessellationControlStage ) {
glDetachShader( m_Program, m_TessellationControlStage );
glDeleteShader( m_TessellationControlStage );
m_TessellationControlStage = 0;
}
if ( m_TessellationEvaluationStage ) {
glDetachShader( m_Program, m_TessellationEvaluationStage );
glDeleteShader( m_TessellationEvaluationStage );
m_TessellationEvaluationStage = 0;
}
if ( m_ComputeStage ) {
glDetachShader( m_Program, m_ComputeStage );
glDeleteShader( m_ComputeStage );
m_ComputeStage = 0;
}
}
bool Shader::Compile() {
glLinkProgram( m_Program );
m_IsCompiled = GetProgramLinkStatus( m_Program );
return m_IsCompiled;
}
void Shader::Flush() {
DeleteStages();
glDeleteProgram( m_Program );
m_Program = glCreateProgram();
m_IsCompiled = false;
}
void Shader::OnRecompile() {
// get the new uniform location
std::unordered_map<std::string, u32> tmpUniforms = m_Uniforms;
m_Uniforms.clear();
for( std::pair<std::string, u32> uniform : tmpUniforms ) {
AddAttribute( uniform.first.c_str() );
}
tmpUniforms = m_UniformsBlock;
m_UniformsBlock.clear();
for( std::pair<std::string, u32> uniformBlock : tmpUniforms ) {
AddUniformBlock( uniformBlock.first.c_str() );
}
tmpUniforms = m_UniformsStorage;
m_UniformsStorage.clear();
for( std::pair<std::string, u32> uniformStorage : tmpUniforms ) {
AddStorageBlock( uniformStorage.first.c_str() );
}
std::unordered_map<std::string, shader_constant_attribute_t> tmpConstant = m_Constants;
m_Constants.clear();
for( std::pair<std::string, shader_constant_attribute_t> constant : tmpConstant ) {
if( constant.second.Type == SHADER_CONSTANT_TYPE_INTEGER ) {
SetConstantAttribute1i( constant.first.c_str(), constant.second.Value );
} else if( constant.second.Type == SHADER_CONSTANT_TYPE_UBO ) {
SetConstantUniformBufferIndex( constant.first.c_str(), constant.second.Value );
} else if( constant.second.Type == SHADER_CONSTANT_TYPE_SSBO ) {
SetConstantStorageBufferIndex( constant.first.c_str(), constant.second.Value );
}
}
}
| 29.43943 | 120 | 0.714136 | [
"vector"
] |
4b63a02652a1f440483e86195088a14eb94ab3a5 | 5,594 | hpp | C++ | consensus/server/consensusobject.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | consensus/server/consensusobject.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | consensus/server/consensusobject.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | // consensus/server/consensusobject.hpp
//
// Copyright (c) 2011, 2012 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// 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 SOLID_CONSENSUS_CONSENSUSOBJECT_HPP
#define SOLID_CONSENSUS_CONSENSUSOBJECT_HPP
#include <vector>
#include "system/socketaddress.hpp"
#include "frame/object.hpp"
namespace solid{
namespace frame{
namespace ipc{
class Service;
struct Message;
}//namespace ipc
}//namespace frame
namespace consensus{
struct WriteRequestMessage;
struct ReadRequestMessage;
struct RequestId;
namespace server{
template <uint16 Count>
struct OperationMessage;
struct OperationStub;
struct Configuration: Dynamic<Configuration, DynamicShared<> >{
typedef std::vector<SocketAddressInet4> AddressVectorT;
AddressVectorT addrvec;
uint8 crtidx;
uint8 quorum;
};
//! The base class for distributed objects needing consensus on processing requests
/*!
* Inherit this class and implement accept, [init,] [prepareRun,] [prepareRecovery,] and
* recovery to have a replicated object which needs consensus on the order it(they) process
* the incomming requests from clients.<br>
* The distributed::consensus::Object implements fast multi Paxos algorithm.<br>
*
* \see example/distributed/consensus for a proof-of-concept
*
*/
class Object: public Dynamic<Object, frame::Object>{
struct RunData;
typedef DynamicMapper<void, Object, RunData> DynamicMapperT;
public:
static void dynamicRegister();
static void registerMessages(frame::ipc::Service &_ripcsvc);
Object(DynamicPointer<Configuration> &_rcfgptr);
~Object();
void serverIndex(const frame::IndexT &_ridx);
frame::IndexT serverIndex()const;
void dynamicHandle(DynamicPointer<> &_dp, RunData &_rrd);
void dynamicHandle(DynamicPointer<WriteRequestMessage> &_rmsgptr, RunData &_rrd);
void dynamicHandle(DynamicPointer<ReadRequestMessage> &_rmsgptr, RunData &_rrd);
void dynamicHandle(DynamicPointer<OperationMessage<1> > &_rmsgptr, RunData &_rrd);
void dynamicHandle(DynamicPointer<OperationMessage<2> > &_rmsgptr, RunData &_rrd);
void dynamicHandle(DynamicPointer<OperationMessage<4> > &_rmsgptr, RunData &_rrd);
void dynamicHandle(DynamicPointer<OperationMessage<8> > &_rmsgptr, RunData &_rrd);
void dynamicHandle(DynamicPointer<OperationMessage<16> > &_rmsgptr, RunData &_rrd);
void dynamicHandle(DynamicPointer<OperationMessage<32> > &_rmsgptr, RunData &_rrd);
protected:
static DynamicMapperT dm;
enum State{
InitState,
PrepareRunState,
RunState,
PrepareRecoveryState,
FirstRecoveryState,
LastRecoveryState = FirstRecoveryState + 32,
};
bool isCoordinator()const;
uint32 acceptId()const;
uint32 proposeId()const;
void enterRunState();
bool isRecoveryState()const;
virtual void doSendMessage(DynamicPointer<frame::ipc::Message> &_rmsgptr, const SocketAddressInet4 &_raddr) = 0;
private:
void state(int _st);
int state()const;
/*virtual*/ void execute(ExecuteContext &_rexectx);
/*virtual*/ bool notify(DynamicPointer<frame::Message> &_rmsgptr);
//! It should dynamically cast the signal to an accepted Request and process it.
virtual void accept(DynamicPointer<WriteRequestMessage> &_rmsgptr) = 0;
//! Called once while initializing the Object
virtual void init();
//! Called once before entering RunState
virtual void prepareRun();
//! Called once before entering RecoveryState
virtual void prepareRecovery();
//! Called continuously by execute method until exiting RecoveryState
virtual AsyncE recovery() = 0;
AsyncE doInit(RunData &_rd);
AsyncE doPrepareRun(RunData &_rd);
AsyncE doRun(RunData &_rd);
AsyncE doPrepareRecovery(RunData &_rd);
AsyncE doRecovery(RunData &_rd);
void doProcessRequest(RunData &_rd, const size_t _reqidx);
void doSendAccept(RunData &_rd, const size_t _reqidx);
void doSendFastAccept(RunData &_rd, const size_t _reqidx);
void doSendPropose(RunData &_rd, const size_t _reqidx);
void doSendConfirmPropose(RunData &_rd, const uint8 _replicaidx, const size_t _reqidx);
void doSendDeclinePropose(RunData &_rd, const uint8 _replicaidx, const OperationStub &_rop);
void doSendConfirmAccept(RunData &_rd, const uint8 _replicaidx, const size_t _reqidx);
void doSendDeclineAccept(RunData &_rd, const uint8 _replicaidx, const OperationStub &_rop);
void doFlushOperations(RunData &_rd);
void doScanPendingRequests(RunData &_rd);
void doAcceptRequest(RunData &_rd, const size_t _reqidx);
void doEraseRequest(RunData &_rd, const size_t _reqidx);
void doExecuteOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doExecuteProposeOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doExecuteProposeConfirmOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doExecuteProposeDeclineOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doExecuteAcceptOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doExecuteFastAcceptOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doExecuteAcceptConfirmOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doExecuteAcceptDeclineOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop);
void doStartCoordinate(RunData &_rd, const size_t _reqidx);
void doEnterRecoveryState();
private:
struct Data;
Data &d;
};
}//namespace server
}//namespace consensus
}//namespace distributed
#endif
| 38.847222 | 113 | 0.786736 | [
"object",
"vector",
"solid"
] |
4b6681dadebedf27a38ec4e31305f5a6b70d2236 | 6,000 | cpp | C++ | tests/MutationTestingElementsReporterTest.cpp | BuildJet/mull | 9064707fb45864a39b45901599182e0a32a7eeaa | [
"Apache-2.0"
] | null | null | null | tests/MutationTestingElementsReporterTest.cpp | BuildJet/mull | 9064707fb45864a39b45901599182e0a32a7eeaa | [
"Apache-2.0"
] | null | null | null | tests/MutationTestingElementsReporterTest.cpp | BuildJet/mull | 9064707fb45864a39b45901599182e0a32a7eeaa | [
"Apache-2.0"
] | null | null | null | #include "mull/Reporters/MutationTestingElementsReporter.h"
#include "FixturePaths.h"
#include "TestModuleFactory.h"
#include "mull/Bitcode.h"
#include "mull/BitcodeLoader.h"
#include "mull/Config/Configuration.h"
#include "mull/FunctionUnderTest.h"
#include "mull/JunkDetection/CXX/ASTStorage.h"
#include "mull/Metrics/MetricsMeasure.h"
#include "mull/MutationsFinder.h"
#include "mull/Program/Program.h"
#include "mull/Reporters/ASTSourceInfoProvider.h"
#include "mull/Result.h"
#include <mull/Mutators/CXX/ArithmeticMutators.h>
#include <fstream>
#include <gtest/gtest.h>
#include <json11/json11.hpp>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Type.h>
#include <mull/Diagnostics/Diagnostics.h>
#include <ostream>
using namespace mull;
using namespace llvm;
using namespace json11;
static const int beginColumnStub = 1;
static const int beginLineStub = 2;
static const int endColumnStub = 3;
static const int endLineStub = 4;
class MockASTSourceInfoProvider : public SourceInfoProvider {
public:
virtual ~MockASTSourceInfoProvider() = default;
MutationPointSourceInfo getSourceInfo(Mutant *mutant) override {
MutationPointSourceInfo info;
info.beginColumn = beginColumnStub;
info.beginLine = beginLineStub;
info.endColumn = endColumnStub;
info.endLine = endLineStub;
return info;
}
};
TEST(MutationTestingElementsReporterTest, integrationTest) {
/// STEP 1. Long setup of:
/// - 1 test with 1 testee with 1 mutation point.
/// - 1 test execution result which includes 1 normal test execution and 1
/// mutated test execution.
Diagnostics diagnostics;
LLVMContext llvmContext;
BitcodeLoader loader;
auto bitcodeWithTests = loader.loadBitcodeAtPath(
fixtures::simple_test_count_letters_test_count_letters_bc_path(), llvmContext, diagnostics);
auto bitcodeWithTestees = loader.loadBitcodeAtPath(
fixtures::simple_test_count_letters_count_letters_bc_path(), llvmContext, diagnostics);
Function *reachableFunction = bitcodeWithTestees->getModule()->getFunction("count_letters");
std::vector<std::unique_ptr<Bitcode>> modules;
modules.push_back(std::move(bitcodeWithTests));
modules.push_back(std::move(bitcodeWithTestees));
Program program(std::move(modules));
Configuration configuration;
std::vector<std::unique_ptr<Mutator>> mutators;
mutators.emplace_back(std::make_unique<cxx::AddToSub>());
MutationsFinder mutationsFinder(std::move(mutators), configuration);
ASSERT_FALSE(reachableFunction->empty());
std::vector<FunctionUnderTest> functionsUnderTest(
{ FunctionUnderTest(reachableFunction, program.bitcode().front().get()) });
functionsUnderTest.back().selectInstructions({});
std::vector<MutationPoint *> mutationPoints =
mutationsFinder.getMutationPoints(diagnostics, program, functionsUnderTest);
ASSERT_EQ(1U, mutationPoints.size());
MutationPoint *mutationPoint = mutationPoints.front();
std::vector<std::string> mutationPointIds({ "", mutationPoint->getUserIdentifier() });
const long long RunningTime_2 = 2;
ExecutionResult mutatedTestExecutionResult;
mutatedTestExecutionResult.status = Failed;
mutatedTestExecutionResult.runningTime = RunningTime_2;
mutatedTestExecutionResult.stdoutOutput = "mutatedTestExecutionResult.STDOUT";
mutatedTestExecutionResult.stderrOutput = "mutatedTestExecutionResult.STDERR";
auto anyPoint = mutationPoints.front();
auto mutant = std::make_unique<Mutant>(mutationPoint->getUserIdentifier(),
anyPoint->getMutatorIdentifier(),
anyPoint->getSourceLocation(),
anyPoint->isCovered());
auto mutationResult = std::make_unique<MutationResult>(mutatedTestExecutionResult, mutant.get());
std::vector<std::unique_ptr<Mutant>> mutants;
mutants.push_back(std::move(mutant));
std::vector<std::unique_ptr<MutationResult>> mutationResults;
mutationResults.push_back(std::move(mutationResult));
MetricsMeasure resultTime;
Result result(std::move(mutants), std::move(mutationResults));
/// STEP2. Reporting results to JSON
MockASTSourceInfoProvider sourceInfoProvider;
MutationTestingElementsReporter reporter(diagnostics, "", "", sourceInfoProvider);
reporter.reportResults(result);
/// STEP3. Making assertions.
std::vector<ExecutionResult> executionResults{ mutatedTestExecutionResult };
std::ifstream t(reporter.getJSONPath());
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
std::string err;
Json object = Json::parse(str, err);
std::cout << object.dump() << '\n';
ASSERT_FALSE(object.is_null());
const std::string &schemaJSON = object["schemaVersion"].string_value();
ASSERT_EQ(std::string("1.1.1"), schemaJSON);
const std::map<std::string, Json> &filesJSON = object["files"].object_items();
ASSERT_EQ(1, filesJSON.size());
const Json &fileJSON = filesJSON.begin()->second;
const std::vector<Json> &mutantsJSON = fileJSON["mutants"].array_items();
ASSERT_EQ(1, mutantsJSON.size());
const Json &mutationJSON = mutantsJSON.at(0);
const std::string &mutationId = mutationJSON["id"].string_value();
ASSERT_EQ("cxx_add_to_sub", mutationId);
const std::string &mutationStatus = mutationJSON["status"].string_value();
ASSERT_EQ("Killed", mutationStatus);
const Json &locationJSON = mutationJSON["location"].object_items();
const Json &startLocationJSON = locationJSON["start"].object_items();
const Json &endLocationJSON = locationJSON["end"].object_items();
const int &startLine = startLocationJSON["line"].int_value();
ASSERT_EQ(beginLineStub, startLine);
const int &startColumn = startLocationJSON["column"].int_value();
ASSERT_EQ(beginColumnStub, startColumn);
const int &endLine = endLocationJSON["line"].int_value();
ASSERT_EQ(endLineStub, endLine);
const int &endColumn = endLocationJSON["column"].int_value();
ASSERT_EQ(endColumnStub, endColumn);
}
| 35.928144 | 99 | 0.747333 | [
"object",
"vector"
] |
4b668da98591df69a11c15dde8cee252781d3331 | 1,804 | cpp | C++ | src/Libs/scream/code/NetQueue.cpp | miseri/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 1 | 2021-07-14T08:15:05.000Z | 2021-07-14T08:15:05.000Z | src/Libs/scream/code/NetQueue.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | null | null | null | src/Libs/scream/code/NetQueue.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T08:15:02.000Z | 2021-07-14T08:56:10.000Z | #include "stdafx.h"
#include "NetQueue.h"
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//#include <glib-object.h>
using namespace std;
/*
* Implements a simple RTP packet queue
*/
NetQueueItem::NetQueueItem() {
packet = 0;
used = false;
size = 0;
seqNr = 0;
tRelease = 0.0;
}
NetQueue::NetQueue(float delay_, float rate_, float jitter_) {
for (int n=0; n < NetQueueSize; n++) {
items[n] = new NetQueueItem();
}
head = -1;
tail = 0;
nItems = 0;
rate = rate_;
delay = delay_;
jitter = jitter_;
nextTx = 0;
}
void NetQueue::insert(float time,
void *rtpPacket,
unsigned int ssrc,
int size,
unsigned short seqNr) {
head++; if (head == NetQueueSize) head = 0;
items[head]->used = true;
items[head]->packet = rtpPacket;
items[head]->ssrc = ssrc;
items[head]->size = size;
items[head]->seqNr = seqNr;
items[head]->tRelease = time+delay+jitter*(rand()/float(RAND_MAX));
if (rate > 0)
items[head]->tRelease += sizeOfQueue()*8.0f/rate;
items[head]->tRelease = std::max(items[head]->tRelease, nextTx);
nextTx = items[head]->tRelease;
}
bool NetQueue::extract(float time,
void *rtpPacket,
unsigned int &ssrc,
int& size,
unsigned short& seqNr) {
if (items[tail]->used == false) {
return false;
} else {
if (time >= items[tail]->tRelease) {
rtpPacket = items[tail]->packet;
seqNr = items[tail]->seqNr;
ssrc = items[tail]->ssrc;
size = items[tail]->size;
items[tail]->used = false;
tail++; if (tail == NetQueueSize) tail = 0;
return true;
}
return false;
}
}
int NetQueue::sizeOfQueue() {
int size = 0;
for (int n=0; n < NetQueueSize; n++) {
if (items[n]->used)
size += items[n]->size;
}
return size;
}
| 21.73494 | 68 | 0.605876 | [
"object"
] |
b49d593fc3794285e48cc1c37f77c88add1ba571 | 2,594 | cpp | C++ | codeforces/practice/DIV2_261E.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 3 | 2020-02-08T10:34:16.000Z | 2020-02-09T10:23:19.000Z | codeforces/practice/DIV2_261E.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | null | null | null | codeforces/practice/DIV2_261E.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 2 | 2020-10-02T19:05:32.000Z | 2021-09-08T07:01:49.000Z | //Optimise
#include <bits/stdc++.h>
using namespace std;
// #define multitest 1
#ifdef WIN32
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
#define pc(...) PC(#__VA_ARGS__, __VA_ARGS__);
template <typename T, typename U>
ostream &operator<<(ostream &out, const pair<T, U> &p)
{
out << '[' << p.first << ", " << p.second << ']';
return out;
}
template <typename Arg>
void PC(const char *name, Arg &&arg)
{
while (*name == ',' || *name == ' ')
name++;
std::cerr << name << " { ";
for (const auto &v : arg)
cerr << v << ' ';
cerr << " }\n";
}
template <typename Arg1, typename... Args>
void PC(const char *names, Arg1 &&arg1, Args &&... args)
{
while (*names == ',' || *names == ' ')
names++;
const char *comma = strchr(names, ',');
std::cerr.write(names, comma - names) << " { ";
for (const auto &v : arg1)
cerr << v << ' ';
cerr << " }\n";
PC(comma, args...);
}
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
const char *comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << " = " << arg1;
ZZ(comma, args...);
}
#else
#define db(...)
#define pc(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
auto TimeStart = chrono::steady_clock::now();
const int nax = 3e5 + 10, mod = 1000000007;
int n, m;
using edge = pair<int, pair<int, int>>;
vector<edge> Edges;
map<int, int> dpSofar[nax];
void solve()
{
cin >> n >> m;
int u, v, w;
for (int i = 0; i < m; ++i)
{
cin >> u >> v >> w;
Edges.pb({w, {u, v}});
// Edges.pb({w, {v, u}});
}
int res = 0;
sort(Edges.begin(), Edges.end());
pc(Edges);
for (int i = m - 1; i >= 0; --i)
{
int start = Edges[i].s.f, End = Edges[i].s.s;
int wr = Edges[i].f;
auto it = dpSofar[End].upper_bound(wr);
if (it != dpSofar[End].end())
dpSofar[start][wr] = max(dpSofar[start][wr], it->s + 1);
else
dpSofar[start][wr] = max(1, dpSofar[start][wr]);
it = dpSofar[start].upper_bound(wr);
if (it != dpSofar[start].end())
dpSofar[start][wr] = max(it->s, dpSofar[start][wr]);
db(start, End, wr, dpSofar[start][wr]);
res = max(res, dpSofar[start][wr]);
}
cout << res << '\n';
}
int main()
{
#ifndef WIN32
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
#ifdef multitest
cin >> t;
#endif
while (t--)
solve();
#ifdef WIN32
cerr << "\n\nTime elapsed: " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " seconds.\n";
#endif
return 0;
} | 22.955752 | 124 | 0.578258 | [
"vector"
] |
b49deded2ac2ccaedd414d95b016bc5775399fdc | 29,379 | cpp | C++ | src/tools.cpp | ipbc-dev/onion-bittube-blockchain-explorer | 0f3cc6b2498bbbf4a53c8adff8f2f7101a1ad99a | [
"BSD-3-Clause"
] | 9 | 2018-11-26T10:38:22.000Z | 2021-11-09T12:57:04.000Z | src/tools.cpp | ipbc-dev/onion-bittube-blockchain-explorer | 0f3cc6b2498bbbf4a53c8adff8f2f7101a1ad99a | [
"BSD-3-Clause"
] | 1 | 2020-01-08T14:40:07.000Z | 2020-01-08T14:40:07.000Z | src/tools.cpp | ilie1988/bittube-blockchain-explorer | 0f3cc6b2498bbbf4a53c8adff8f2f7101a1ad99a | [
"BSD-3-Clause"
] | 11 | 2018-07-08T04:55:26.000Z | 2021-04-22T12:11:07.000Z | //
// Created by marcin on 5/11/15.
//
#include "tools.h"
#include <codecvt>
#include <thread>
namespace xmreg
{
/**
* Parse key string, e.g., a viewkey in a string
* into crypto::secret_key or crypto::public_key
* depending on the template argument.
*/
template <typename T>
bool
parse_str_secret_key(const string& key_str, T& secret_key)
{
// hash and keys have same structure, so to parse string of
// a key, e.g., a view key, we can first parse it into the hash
// object using parse_hash256 function, and then copy the reslting
// hash data into secret key.
crypto::hash hash_;
if(!parse_hash256(key_str, hash_))
{
cerr << "Cant parse a key (e.g. viewkey): " << key_str << endl;
return false;
}
// crypto::hash and crypto::secret_key have basicly same
// structure. They both keep they key/hash as c-style char array
// of fixed size. Thus we can just copy data from hash
// to key
copy(begin(hash_.data), end(hash_.data), secret_key.data);
return true;
}
// explicit instantiations of get template function
template bool parse_str_secret_key<crypto::secret_key>(const string& key_str, crypto::secret_key& secret_key);
template bool parse_str_secret_key<crypto::public_key>(const string& key_str, crypto::public_key& secret_key);
template bool parse_str_secret_key<crypto::hash>(const string& key_str, crypto::hash& secret_key);
/**
* Get transaction tx using given tx hash. Hash is represent as string here,
* so before we can tap into the blockchain, we need to pare it into
* crypto::hash object.
*/
bool
get_tx_pub_key_from_str_hash(Blockchain& core_storage, const string& hash_str, transaction& tx)
{
crypto::hash tx_hash;
parse_hash256(hash_str, tx_hash);
try
{
// get transaction with given hash
tx = core_storage.get_db().get_tx(tx_hash);
}
catch (const TX_DNE& e)
{
cerr << e.what() << endl;
return false;
}
return true;
}
/**
* Parse BitTube address in a string form into
* cryptonote::account_public_address object
*/
bool
parse_str_address(const string& address_str,
address_parse_info& address_info,
cryptonote::network_type nettype)
{
if (!get_account_address_from_str(address_info, nettype, address_str))
{
cerr << "Error getting address: " << address_str << endl;
return false;
}
return true;
}
/**
* Return string representation of BitTube address
*/
string
print_address(const address_parse_info& address_info, cryptonote::network_type nettype)
{
return "<" + get_account_address_as_str(
nettype, address_info.is_subaddress, address_info.address)
+ ">";
}
string
print_sig (const signature& sig)
{
stringstream ss;
ss << "c: <" << epee::string_tools::pod_to_hex(sig.c) << "> "
<< "r: <" << epee::string_tools::pod_to_hex(sig.r) << ">";
return ss.str();
}
/**
* Check if a character is a path seprator
*/
inline bool
is_separator(char c)
{
// default linux path separator
const char separator = PATH_SEPARARTOR;
return c == separator;
}
/**
* Remove trailinig path separator.
*/
string
remove_trailing_path_separator(const string& in_path)
{
string new_string = in_path;
if (!new_string.empty() && is_separator(new_string[new_string.size() - 1]))
new_string.erase(new_string.size() - 1);
return new_string;
}
bf::path
remove_trailing_path_separator(const bf::path& in_path)
{
#ifdef WIN32
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
string path_str = converter.to_bytes(in_path.native());
#else
string path_str = in_path.native();
#endif
return bf::path(remove_trailing_path_separator(path_str));
}
//string
//timestamp_to_str(time_t timestamp, const char* format)
//{
// return get_human_readable_timestamp(timestamp);
//}
string
timestamp_to_str_gm(time_t timestamp, const char* format)
{
const time_t* t = ×tamp;
const int TIME_LENGTH = 60;
char str_buff[TIME_LENGTH];
std::tm tmp;
gmtime_r(t, &tmp);
size_t len;
len = std::strftime(str_buff, TIME_LENGTH, format, &tmp);
return string(str_buff, len);
}
ostream&
operator<< (ostream& os, const address_parse_info& addr_info)
{
os << get_account_address_as_str(network_type::MAINNET, addr_info.is_subaddress, addr_info.address);
return os;
}
/*
* Generate key_image of foran ith output
*/
bool
generate_key_image(const crypto::key_derivation& derivation,
const std::size_t i,
const crypto::secret_key& sec_key,
const crypto::public_key& pub_key,
crypto::key_image& key_img)
{
cryptonote::keypair in_ephemeral;
if (!crypto::derive_public_key(derivation, i,
pub_key,
in_ephemeral.pub))
{
cerr << "Error generating publick key " << pub_key << endl;
return false;
}
try
{
crypto::derive_secret_key(derivation, i,
sec_key,
in_ephemeral.sec);
}
catch(const std::exception& e)
{
cerr << "Error generate secret image: " << e.what() << endl;
return false;
}
try
{
crypto::generate_key_image(in_ephemeral.pub,
in_ephemeral.sec,
key_img);
}
catch(const std::exception& e)
{
cerr << "Error generate key image: " << e.what() << endl;
return false;
}
return true;
}
string
get_default_lmdb_folder(cryptonote::network_type nettype)
{
// default path to bittube folder
// on linux this is /home/<username>/.bittube
string default_bittube_dir = tools::get_default_data_dir();
if (nettype == cryptonote::network_type::TESTNET)
default_bittube_dir += "/testnet";
if (nettype == cryptonote::network_type::STAGENET)
default_bittube_dir += "/stagenet";
// the default folder of the lmdb blockchain database
// is therefore as follows
return default_bittube_dir + string("/lmdb");
}
/*
* Ge blockchain exception from command line option
*
* If not given, provide default path
*/
bool
get_blockchain_path(const boost::optional<string>& bc_path,
bf::path& blockchain_path,
cryptonote::network_type nettype)
{
// the default folder of the lmdb blockchain database
string default_lmdb_dir = xmreg::get_default_lmdb_folder(nettype);
blockchain_path = bc_path
? bf::path(*bc_path)
: bf::path(default_lmdb_dir);
if (!bf::is_directory(blockchain_path))
{
cerr << "Given path \"" << blockchain_path << "\" "
<< "is not a folder or does not exist" << " "
<< endl;
return false;
}
blockchain_path = xmreg::remove_trailing_path_separator(blockchain_path);
return true;
}
uint64_t
sum_money_in_outputs(const transaction& tx)
{
uint64_t sum_xmr {0};
for (const tx_out& txout: tx.vout)
{
sum_xmr += txout.amount;
}
return sum_xmr;
}
pair<uint64_t, uint64_t>
sum_money_in_outputs(const string& json_str)
{
pair<uint64_t, uint64_t> sum_xmr {0, 0};
json j;
try
{
j = json::parse( json_str);
}
catch (std::invalid_argument& e)
{
cerr << "sum_money_in_outputs: " << e.what() << endl;
return sum_xmr;
}
for (json& vout: j["vout"])
{
sum_xmr.first += vout["amount"].get<uint64_t>();
++sum_xmr.second;
}
return sum_xmr;
};
pair<uint64_t, uint64_t>
sum_money_in_outputs(const json& _json)
{
pair<uint64_t, uint64_t> sum_xmr {0ULL, 0ULL};
for (const json& vout: _json["vout"])
{
sum_xmr.first += vout["amount"].get<uint64_t>();
++sum_xmr.second;
}
return sum_xmr;
};
array<uint64_t, 4>
summary_of_in_out_rct(
const transaction& tx,
vector<pair<txout_to_key, uint64_t>>& output_pub_keys,
vector<txin_to_key>& input_key_imgs)
{
uint64_t xmr_outputs {0};
uint64_t xmr_inputs {0};
uint64_t mixin_no {0};
uint64_t num_nonrct_inputs {0};
for (const tx_out& txout: tx.vout)
{
if (txout.target.type() != typeid(txout_to_key))
{
// push empty pair.
output_pub_keys.push_back(pair<txout_to_key, uint64_t>{});
continue;
}
// get tx input key
const txout_to_key& txout_key
= boost::get<cryptonote::txout_to_key>(txout.target);
output_pub_keys.push_back(make_pair(txout_key, txout.amount));
xmr_outputs += txout.amount;
}
size_t input_no = tx.vin.size();
for (size_t i = 0; i < input_no; ++i)
{
if(tx.vin[i].type() != typeid(cryptonote::txin_to_key))
{
continue;
}
// get tx input key
const cryptonote::txin_to_key& tx_in_to_key
= boost::get<cryptonote::txin_to_key>(tx.vin[i]);
xmr_inputs += tx_in_to_key.amount;
if (tx_in_to_key.amount != 0)
{
++num_nonrct_inputs;
}
if (mixin_no == 0)
{
mixin_no = tx_in_to_key.key_offsets.size();
}
input_key_imgs.push_back(tx_in_to_key);
} // for (size_t i = 0; i < input_no; ++i)
return {xmr_outputs, xmr_inputs, mixin_no, num_nonrct_inputs};
};
// this version for mempool txs from json
array<uint64_t, 6>
summary_of_in_out_rct(const json& _json)
{
uint64_t xmr_outputs {0};
uint64_t xmr_inputs {0};
uint64_t no_outputs {0};
uint64_t no_inputs {0};
uint64_t mixin_no {0};
uint64_t num_nonrct_inputs {0};
for (const json& vout: _json["vout"])
{
xmr_outputs += vout["amount"].get<uint64_t>();
}
no_outputs = _json["vout"].size();
for (const json& vin: _json["vin"])
{
uint64_t amount = vin["key"]["amount"].get<uint64_t>();
xmr_inputs += amount;
if (amount != 0)
++num_nonrct_inputs;
}
no_inputs = _json["vin"].size();
mixin_no = _json["vin"].at(0)["key"]["key_offsets"].size() - 1;
return {xmr_outputs, xmr_inputs, no_outputs, no_inputs, mixin_no, num_nonrct_inputs};
};
uint64_t
sum_money_in_inputs(const transaction& tx)
{
uint64_t sum_xmr {0};
size_t input_no = tx.vin.size();
for (size_t i = 0; i < input_no; ++i)
{
if(tx.vin[i].type() != typeid(cryptonote::txin_to_key))
{
continue;
}
// get tx input key
const cryptonote::txin_to_key& tx_in_to_key
= boost::get<cryptonote::txin_to_key>(tx.vin[i]);
sum_xmr += tx_in_to_key.amount;
}
return sum_xmr;
}
pair<uint64_t, uint64_t>
sum_money_in_inputs(const string& json_str)
{
pair<uint64_t, uint64_t> sum_xmr {0, 0};
json j;
try
{
j = json::parse( json_str);
}
catch (std::invalid_argument& e)
{
cerr << "sum_money_in_outputs: " << e.what() << endl;
return sum_xmr;
}
for (json& vin: j["vin"])
{
sum_xmr.first += vin["key"]["amount"].get<uint64_t>();
++sum_xmr.second;
}
return sum_xmr;
};
pair<uint64_t, uint64_t>
sum_money_in_inputs(const json& _json)
{
pair<uint64_t, uint64_t> sum_xmr {0, 0};
for (const json& vin: _json["vin"])
{
sum_xmr.first += vin["key"]["amount"].get<uint64_t>();
++sum_xmr.second;
}
return sum_xmr;
};
uint64_t
count_nonrct_inputs(const transaction& tx)
{
uint64_t num {0};
size_t input_no = tx.vin.size();
for (size_t i = 0; i < input_no; ++i)
{
if(tx.vin[i].type() != typeid(cryptonote::txin_to_key))
{
continue;
}
// get tx input key
const cryptonote::txin_to_key& tx_in_to_key
= boost::get<cryptonote::txin_to_key>(tx.vin[i]);
if (tx_in_to_key.amount != 0)
++num;
}
return num;
}
uint64_t
count_nonrct_inputs(const string& json_str)
{
uint64_t num {0};
json j;
try
{
j = json::parse( json_str);
}
catch (std::invalid_argument& e)
{
cerr << "count_nonrct_inputs: " << e.what() << endl;
return num;
}
for (json& vin: j["vin"])
{
uint64_t amount = vin["key"]["amount"].get<uint64_t>();
if (amount != 0)
++num;
}
return num;
};
uint64_t
count_nonrct_inputs(const json& _json)
{
uint64_t num {0};
for (const json& vin: _json["vin"])
{
uint64_t amount = vin["key"]["amount"].get<uint64_t>();
if (amount != 0)
++num;
}
return num;
};
array<uint64_t, 2>
sum_money_in_tx(const transaction& tx)
{
array<uint64_t, 2> sum_xmr;
sum_xmr[0] = sum_money_in_inputs(tx);
sum_xmr[1] = sum_money_in_outputs(tx);
return sum_xmr;
};
array<uint64_t, 2>
sum_money_in_txs(const vector<transaction>& txs)
{
array<uint64_t, 2> sum_xmr {0,0};
for (const transaction& tx: txs)
{
sum_xmr[0] += sum_money_in_inputs(tx);
sum_xmr[1] += sum_money_in_outputs(tx);
}
return sum_xmr;
};
uint64_t
sum_fees_in_txs(const vector<transaction>& txs)
{
uint64_t fees_sum {0};
for (const transaction& tx: txs)
{
fees_sum += get_tx_fee(tx);
}
return fees_sum;
}
vector<pair<txout_to_key, uint64_t>>
get_ouputs(const transaction& tx)
{
vector<pair<txout_to_key, uint64_t>> outputs;
for (const tx_out& txout: tx.vout)
{
if (txout.target.type() != typeid(txout_to_key))
{
// push empty pair.
outputs.push_back(pair<txout_to_key, uint64_t>{});
continue;
}
// get tx input key
const txout_to_key& txout_key
= boost::get<cryptonote::txout_to_key>(txout.target);
outputs.push_back(make_pair(txout_key, txout.amount));
}
return outputs;
};
vector<tuple<txout_to_key, uint64_t, uint64_t>>
get_ouputs_tuple(const transaction& tx)
{
vector<tuple<txout_to_key, uint64_t, uint64_t>> outputs;
for (uint64_t n = 0; n < tx.vout.size(); ++n)
{
if (tx.vout[n].target.type() != typeid(txout_to_key))
{
continue;
}
// get tx input key
const txout_to_key& txout_key
= boost::get<cryptonote::txout_to_key>(tx.vout[n].target);
outputs.push_back(make_tuple(txout_key, tx.vout[n].amount, n));
}
return outputs;
};
uint64_t
get_mixin_no(const transaction& tx)
{
uint64_t mixin_no {0};
size_t input_no = tx.vin.size();
for (size_t i = 0; i < input_no; ++i)
{
if(tx.vin[i].type() != typeid(cryptonote::txin_to_key))
{
continue;
}
// get tx input key
const txin_to_key& tx_in_to_key
= boost::get<cryptonote::txin_to_key>(tx.vin[i]);
mixin_no = tx_in_to_key.key_offsets.size();
// look for first mixin number.
// all inputs in a single transaction have same number
if (mixin_no > 0)
{
break;
}
}
return mixin_no;
}
vector<uint64_t>
get_mixin_no(const string& json_str)
{
vector<uint64_t> mixin_no;
json j;
try
{
j = json::parse(json_str);
mixin_no.push_back(j["vin"].at(0)["key"]["key_offsets"].size());
}
catch (std::invalid_argument& e)
{
cerr << "get_mixin_no: " << e.what() << endl;
return mixin_no;
}
return mixin_no;
}
vector<uint64_t>
get_mixin_no(const json& _json)
{
vector<uint64_t> mixin_no;
mixin_no.push_back(_json["vin"].at(0)["key"]["key_offsets"].size());
return mixin_no;
}
vector<uint64_t>
get_mixin_no_in_txs(const vector<transaction>& txs)
{
vector<uint64_t> mixin_no;
for (const transaction& tx: txs)
{
mixin_no.push_back(get_mixin_no(tx));
}
return mixin_no;
}
vector<txin_to_key>
get_key_images(const transaction& tx)
{
vector<txin_to_key> key_images;
size_t input_no = tx.vin.size();
for (size_t i = 0; i < input_no; ++i)
{
if(tx.vin[i].type() != typeid(txin_to_key))
{
continue;
}
// get tx input key
const txin_to_key& tx_in_to_key
= boost::get<cryptonote::txin_to_key>(tx.vin[i]);
key_images.push_back(tx_in_to_key);
}
return key_images;
}
bool
get_payment_id(const vector<uint8_t>& extra,
crypto::hash& payment_id,
crypto::hash8& payment_id8)
{
payment_id = null_hash;
payment_id8 = null_hash8;
std::vector<tx_extra_field> tx_extra_fields;
if(!parse_tx_extra(extra, tx_extra_fields))
{
return false;
}
tx_extra_nonce extra_nonce;
if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
{
// first check for encrypted id and then for normal one
if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
{
return true;
}
else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
{
return true;
}
}
return false;
}
bool
get_payment_id(const transaction& tx,
crypto::hash& payment_id,
crypto::hash8& payment_id8)
{
return get_payment_id(tx.extra, payment_id, payment_id8);
}
array<size_t, 5>
timestamp_difference(uint64_t t1, uint64_t t2)
{
uint64_t timestamp_diff = t1 - t2;
// calculate difference of timestamps from current block to the mixin one
if (t2 > t1)
{
timestamp_diff = t2 - t1;
}
uint64_t time_diff_years = timestamp_diff / 31536000;
timestamp_diff -= time_diff_years * 31536000;
uint64_t time_diff_days = timestamp_diff / 86400;
timestamp_diff -= time_diff_days * 86400;
uint64_t time_diff_hours = timestamp_diff / 3600;
timestamp_diff -= time_diff_hours * 3600;
uint64_t time_diff_minutes = timestamp_diff / 60;
timestamp_diff -= time_diff_minutes * 60;
uint64_t time_diff_seconds = timestamp_diff ;
return array<size_t, 5> {time_diff_years, time_diff_days,
time_diff_hours, time_diff_minutes,
time_diff_seconds};
};
string
read(string filename)
{
if (!bf::exists(bf::path(filename)))
{
cerr << "File does not exist: " << filename << endl;
return string();
}
std::ifstream t(filename);
return string(std::istreambuf_iterator<char>(t),
std::istreambuf_iterator<char>());
}
pair<string, double>
timestamps_time_scale(const vector<uint64_t>& timestamps,
uint64_t timeN,
uint64_t resolution,
uint64_t time0)
{
string empty_time = string(resolution, '_');
size_t time_axis_length = empty_time.size();
uint64_t interval_length = timeN-time0;
double scale = double(interval_length) / double(time_axis_length);
for (const auto& timestamp: timestamps)
{
if (timestamp < time0 || timestamp > timeN)
{
cout << "Out of range" << endl;
continue;
}
uint64_t timestamp_place = double(timestamp-time0)
/ double(interval_length)*(time_axis_length - 1);
empty_time[timestamp_place + 1] = '*';
}
return make_pair(empty_time, scale);
}
bool
decode_ringct(const rct::rctSig& rv,
const crypto::public_key pub,
const crypto::secret_key &sec,
unsigned int i,
rct::key & mask,
uint64_t & amount)
{
crypto::key_derivation derivation;
bool r = crypto::generate_key_derivation(pub, sec, derivation);
if (!r)
{
cerr <<"Failed to generate key derivation to decode rct output " << i << endl;
return false;
}
return decode_ringct(rv, derivation, i, mask, amount);
}
bool
decode_ringct(rct::rctSig const& rv,
crypto::key_derivation const& derivation,
unsigned int i,
rct::key& mask,
uint64_t& amount)
{
try
{
crypto::secret_key scalar1;
crypto::derivation_to_scalar(derivation, i, scalar1);
switch (rv.type)
{
case rct::RCTTypeSimple:
case rct::RCTTypeBulletproof:
case rct::RCTTypeBulletproof2:
amount = rct::decodeRctSimple(rv,
rct::sk2rct(scalar1),
i,
mask,
hw::get_device("default"));
break;
case rct::RCTTypeFull:
amount = rct::decodeRct(rv,
rct::sk2rct(scalar1),
i,
mask,
hw::get_device("default"));
break;
default:
cerr << "Unsupported rct type: " << rv.type << '\n';
return false;
}
}
catch (...)
{
cerr << "Failed to decode input " << i << '\n';
return false;
}
return true;
}
bool
url_decode(const std::string& in, std::string& out)
{
out.clear();
out.reserve(in.size());
for (std::size_t i = 0; i < in.size(); ++i)
{
if (in[i] == '%')
{
if (i + 3 <= in.size())
{
int value = 0;
std::istringstream is(in.substr(i + 1, 2));
if (is >> std::hex >> value)
{
out += static_cast<char>(value);
i += 2;
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (in[i] == '+')
{
out += ' ';
}
else
{
out += in[i];
}
}
return true;
}
map<std::string, std::string>
parse_crow_post_data(const string& req_body)
{
map<std::string, std::string> body;
vector<string> vec;
string tmp;
bool result = url_decode(req_body, tmp);
if (result)
{
boost::algorithm::split(vec, tmp,
[](char x) {return x == '&';
});
for(auto &it : vec)
{
auto pos = it.find("=");
if (pos != string::npos)
body[it.substr(0, pos)] = it.substr(pos + 1);
else
break;
}
}
return body;
}
// from wallet2::decrypt
string
decrypt(const std::string &ciphertext,
const crypto::secret_key &skey,
bool authenticated)
{
const size_t prefix_size = sizeof(chacha_iv)
+ (authenticated ? sizeof(crypto::signature) : 0);
if (ciphertext.size() < prefix_size)
{
cerr << "Unexpected ciphertext size" << endl;
return {};
}
crypto::chacha_key key;
crypto::generate_chacha_key(&skey, sizeof(skey), key, 1);
const crypto::chacha_iv &iv = *(const crypto::chacha_iv*)&ciphertext[0];
std::string plaintext;
plaintext.resize(ciphertext.size() - prefix_size);
if (authenticated)
{
crypto::hash hash;
crypto::cn_fast_hash(ciphertext.data(), ciphertext.size() - sizeof(signature), hash);
crypto::public_key pkey;
crypto::secret_key_to_public_key(skey, pkey);
const crypto::signature &signature =
*(const crypto::signature*)&ciphertext[ciphertext.size()
- sizeof(crypto::signature)];
if (!crypto::check_signature(hash, pkey, signature))
{
cerr << "Failed to authenticate criphertext" << endl;
return {};
}
}
crypto::chacha20(ciphertext.data() + sizeof(iv),
ciphertext.size() - prefix_size,
key, iv, &plaintext[0]);
return plaintext;
}
// based on
// crypto::public_key wallet2::get_tx_pub_key_from_received_outs(const tools::wallet2::transfer_details &td) const
public_key
get_tx_pub_key_from_received_outs(const transaction &tx)
{
std::vector<tx_extra_field> tx_extra_fields;
if(!parse_tx_extra(tx.extra, tx_extra_fields))
{
// Extra may only be partially parsed, it's OK if tx_extra_fields contains public key
}
// Due to a previous bug, there might be more than one tx pubkey in extra, one being
// the result of a previously discarded signature.
// For speed, since scanning for outputs is a slow process, we check whether extra
// contains more than one pubkey. If not, the first one is returned. If yes, they're
// checked for whether they yield at least one output
tx_extra_pub_key pub_key_field;
if (!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, 0))
{
return null_pkey;
}
public_key tx_pub_key = pub_key_field.pub_key;
bool two_found = find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, 1);
if (!two_found)
{
// easy case, just one found
return tx_pub_key;
}
else
{
// just return second one if there are two.
// this does not require private view key, as
// its not needed for my use case.
return pub_key_field.pub_key;
}
return null_pkey;
}
/**
* Check if given output (specified by output_index)
* belongs is ours based
* on our private view key and public spend key
*/
bool
is_output_ours(const size_t& output_index,
const transaction& tx,
const public_key& pub_tx_key,
const secret_key& private_view_key,
const public_key& public_spend_key)
{
// public transaction key is combined with our viewkey
// to create, so called, derived key.
key_derivation derivation;
if (!generate_key_derivation(pub_tx_key, private_view_key, derivation))
{
cerr << "Cant get dervied key for: " << "\n"
<< "pub_tx_key: " << pub_tx_key << " and "
<< "prv_view_key" << private_view_key << endl;
return false;
}
// get the tx output public key
// that normally would be generated for us,
// if someone had sent us some xmr.
public_key pubkey;
derive_public_key(derivation,
output_index,
public_spend_key,
pubkey);
//cout << "\n" << tx.vout.size() << " " << output_index << endl;
// get tx output public key
const txout_to_key tx_out_to_key
= boost::get<txout_to_key>(tx.vout[output_index].target);
if (tx_out_to_key.key == pubkey)
{
return true;
}
return false;
}
bool
get_real_output_for_key_image(const key_image& ki,
const transaction& tx,
const secret_key& private_view_key,
const public_key& public_spend_key,
uint64_t output_idx,
public_key output_pub_key)
{
return false;
}
string
make_printable(const string& in_s)
{
string output;
for (char c: in_s)
{
if (isprint(c))
{
output += c;
}
else
{
switch(c){
case '\000': output += "\\000";break;
case '\001': output += "\\001";break;
case '\002': output += "\\002";break;
case '\003': output += "\\003";break;
case '\004': output += "\\004";break;
case '\005': output += "\\005";break;
case '\006': output += "\\006";break;
case '\007': output += "\\007";break;
// there are more case but for now its ok
default:
stringstream ss;
ss << std::hex << (int)c;
output += "0x" + ss.str();
break;
}
}
}
return output;
}
string
get_human_readable_timestamp(uint64_t ts)
{
char buffer[64];
if (ts < 1234567890)
return "<unknown>";
time_t tt = ts;
struct tm tm;
gmtime_r(&tt, &tm);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %I:%M:%S", &tm);
return std::string(buffer);
}
void
pause_execution(uint64_t no_seconds, const string& text)
{
cout << "\nPausing " << text
<< " for " << no_seconds << " seconds: "
<< flush;
for (size_t i = 0; i < no_seconds; ++i)
{
cout << "." << flush;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
cout << endl;
}
string
tx_to_hex(transaction const& tx)
{
return epee::string_tools::buff_to_hex_nodelimer(t_serializable_object_to_blob(tx));
}
}
| 23.024295 | 114 | 0.57439 | [
"object",
"vector"
] |
b49f346e8bd1e621c6ce41f78e4fbdfad7545830 | 1,856 | cpp | C++ | torch_ipex/csrc/cpu/dbl/DNNLChecker.cpp | JianpingChen066/intel-extension-for-pytorch | fbc3b7a2b0c52e552c927f3e99a3a988075385fb | [
"Apache-2.0"
] | null | null | null | torch_ipex/csrc/cpu/dbl/DNNLChecker.cpp | JianpingChen066/intel-extension-for-pytorch | fbc3b7a2b0c52e552c927f3e99a3a988075385fb | [
"Apache-2.0"
] | null | null | null | torch_ipex/csrc/cpu/dbl/DNNLChecker.cpp | JianpingChen066/intel-extension-for-pytorch | fbc3b7a2b0c52e552c927f3e99a3a988075385fb | [
"Apache-2.0"
] | null | null | null | #include "DNNLChecker.h"
#include "torch_ipex/csrc/utils.h"
#include "torch_ipex/csrc/auto_opt_config.h"
namespace torch_ipex {
namespace cpu {
namespace dbl {
namespace chk {
bool dnnl_support_the_tensors(const std::vector<at::Tensor> &tensor_vec) {
return dnnl_tensor_has_data(tensor_vec) &&
dnnl_support_the_dimension_of(tensor_vec) &&
dnnl_support_the_data_type_of(tensor_vec);
}
bool dnnl_inplace_support_the_tensors(const std::vector<at::Tensor> &tensor_vec) {
return dnnl_tensor_has_data(tensor_vec) &&
dnnl_support_the_data_type_of(tensor_vec) &&
dnnl_support_the_memory_layout_of(tensor_vec);
}
bool dnnl_support_the_memory_layout_of(const std::vector<at::Tensor> &tensor_vec) {
for (auto it = tensor_vec.begin(); it != tensor_vec.end(); ++it) {
if (! (dnnl_support_the_memory_layout_of(*it))) {
return false;
}
}
return true;
}
bool dnnl_support_the_memory_layout_of(const at::Tensor& tensor) {
return tensor.is_contiguous() &&
tensor.layout() == at::Layout::Strided;
}
bool dnnl_support_the_data_type_of(const std::vector<at::Tensor> &tensor_vec) {
for (auto it = tensor_vec.begin(); it != tensor_vec.end(); ++it) {
if (torch_ipex::get_dil_data_type(it->scalar_type()) == dil::data_type::undef) {
return false;
}
}
return true;
}
bool dnnl_support_the_dimension_of(const std::vector<at::Tensor> &tensor_vec) {
for (auto it = tensor_vec.begin(); it != tensor_vec.end(); ++it) {
if (it->dim() <= 0) {
return false;
}
}
return true;
}
bool dnnl_tensor_has_data(const std::vector<at::Tensor> &tensor_vec) {
for (auto it = tensor_vec.begin(); it != tensor_vec.end(); ++it)
if (it->numel() == 0)
return false;
return true;
}
} // namespace chk
} // namespace dbl
} // namespace cpu
} // namespace torch_ipex
| 26.898551 | 85 | 0.688578 | [
"vector"
] |
b49f8884e7510578822ed58a5a9b25cee56f4291 | 39,314 | cpp | C++ | sdl1/eod4sdl/wl_play.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/eod4sdl/wl_play.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/eod4sdl/wl_play.cpp | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | // WL_PLAY.C
#include "wl_def.h"
#pragma hdrstop
#include "wl_cloudsky.h"
#include "wl_shade.h"
#ifdef VARIABLEWEATHER
#include "wl_atmos.h"
#endif
/*
=============================================================================
LOCAL CONSTANTS
=============================================================================
*/
#define sc_Question 0x35
/*
=============================================================================
GLOBAL VARIABLES
=============================================================================
*/
boolean madenoise; // true when shooting or screaming
exit_t playstate;
static musicnames lastmusicchunk = (musicnames) 0;
int DebugOk;
objtype objlist[MAXACTORS];
objtype *newobj, *obj, *player, *lastobj, *objfreelist, *killerobj;
boolean noclip = 0, ammocheat = 0, ratiocheat = 0;
int singlestep, extravbls = 0;
uint16_t tilemap[MAPSIZE][MAPSIZE]; // wall values only
byte spotvis[MAPSIZE][MAPSIZE];
#ifdef REVEALMAP
byte spotsaw[MAPSIZE][MAPSIZE];
#endif
objtype *actorat[MAPSIZE][MAPSIZE];
statobj_t *statat[MAPSIZE][MAPSIZE];
//
// replacing refresh manager
//
int tics;
//
// control info
//
boolean mouseenabled, joystickenabled;
int dirscan[4] = { sc_UpArrow, sc_RightArrow, sc_DownArrow, sc_LeftArrow };
int buttonscan[NUMBUTTONS] = { sc_Control, sc_Alt, sc_LShift, sc_Space,
sc_1, sc_2, sc_3, sc_4,
sc_5, sc_6, sc_7, sc_9};
#ifdef MOUSEWHEEL
int buttonmouse[5] = { bt_attack, bt_strafe, bt_use, bt_prevweapon, bt_nextweapon };
#else
int buttonmouse[4] = { bt_attack, bt_strafe, bt_use, bt_nobutton };
#endif
int buttonjoy[32] = {
#ifdef _arch_dreamcast
bt_attack, bt_strafe, bt_use, bt_altspeed, bt_esc, bt_prevweapon, bt_nobutton, bt_nextweapon,
bt_pause, bt_strafeleft, bt_straferight, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton,
#else
bt_attack, bt_strafe, bt_use, bt_altspeed, bt_strafeleft, bt_straferight, bt_esc, bt_pause,
bt_prevweapon, bt_nextweapon, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton,
#endif
bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton,
bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton, bt_nobutton
};
int viewsize;
boolean buttonheld[NUMBUTTONS];
boolean demorecord, demoplayback;
int8_t *demoptr, *lastdemoptr;
memptr demobuffer;
//
// current user input
//
int controlx, controly, controlh; // range from -100 to 100 per tic
boolean buttonstate[NUMBUTTONS];
#define MOVE1FORWARD() controly = ((switches.alwaysrun && buttonstate[bt_altspeed]) || (!switches.alwaysrun && !buttonstate[bt_altspeed])) ? -BASEMOVE * tics : -RUNMOVE * tics;
#define MOVE1FORWARDRIGHT() { \
controlx = ((switches.alwaysrun && buttonstate[bt_altspeed]) || (!switches.alwaysrun && !buttonstate[bt_altspeed])) ? BASEMOVEDIAG * tics : RUNMOVEDIAG * tics; \
controly = -controlx; \
}
#define MOVE1RIGHT() controlx = BASEMOVE * tics;
#define MOVE1BACKWARDRIGHT() { \
controlx = ((switches.alwaysrun && buttonstate[bt_altspeed]) || (!switches.alwaysrun && !buttonstate[bt_altspeed])) ? BASEMOVEDIAG * tics : RUNMOVEDIAG * tics; \
controly = controlx; \
}
#define MOVE1BACKWARD() controly = ((switches.alwaysrun && buttonstate[bt_altspeed]) || (!switches.alwaysrun && !buttonstate[bt_altspeed])) ? BASEMOVE * tics : RUNMOVE * tics;
#define MOVE1BACKWARDLEFT() { \
controly = ((switches.alwaysrun && buttonstate[bt_altspeed]) || (!switches.alwaysrun && !buttonstate[bt_altspeed])) ? BASEMOVEDIAG * tics : RUNMOVEDIAG * tics; \
controlx = -controly; \
}
#define MOVE1LEFT() controlx = -BASEMOVE * tics;
#define MOVE1FORWARDLEFT() { \
controlx = ((switches.alwaysrun && buttonstate[bt_altspeed]) || (!switches.alwaysrun && !buttonstate[bt_altspeed])) ? -BASEMOVEDIAG * tics : -RUNMOVEDIAG * tics; \
controly = controlx; \
}
#define TURNLEFT() controlh = (buttonstate[bt_altspeed]) ? -RUNTURN * tics : -BASETURN * tics;
#define TURNRIGHT() controlh = (buttonstate[bt_altspeed]) ? RUNTURN * tics : BASETURN * tics;
#define MOVE2FORWARD() controly = (buttonstate[bt_altspeed]) ? -RUNMOVE * tics : -BASEMOVE * tics;
#define MOVE2FORWARDRIGHT() { \
controlx = (buttonstate[bt_altspeed]) ? RUNMOVEDIAG * tics : BASEMOVEDIAG * tics; \
controly = -controlx; \
}
#define MOVE2RIGHT() controlx = BASEMOVE * tics;
#define MOVE2BACKWARDRIGHT() { \
controlx = (buttonstate[bt_altspeed]) ? RUNMOVEDIAG * tics : BASEMOVEDIAG * tics; \
controly = controlx; \
}
#define MOVE2BACKWARD() controly = (buttonstate[bt_altspeed]) ? RUNMOVE * tics : BASEMOVE * tics;
#define MOVE2BACKWARDLEFT() { \
controly = (buttonstate[bt_altspeed]) ? RUNMOVEDIAG * tics : BASEMOVEDIAG * tics; \
controlx = -controly; \
}
#define MOVE2LEFT() controlx = -BASEMOVE * tics;
#define MOVE2FORWARDLEFT() { \
controlx = (buttonstate[bt_altspeed]) ? -RUNMOVEDIAG * tics : -BASEMOVEDIAG * tics; \
controly = controlx; \
}
int lastgamemusicoffset = 0;
//===========================================================================
void CenterWindow (word w, word h);
void InitObjList (void);
void RemoveObj (objtype * gone);
void PollControls (void);
int StopMusic (void);
void StartMusic (void);
void ContinueMusic (int offs);
void PlayLoop (void);
/*
=============================================================================
LOCAL VARIABLES
=============================================================================
*/
objtype dummyobj;
/*
=============================================================================
USER CONTROL
=============================================================================
*/
/*
===================
=
= PollKeyboardButtons
=
===================
*/
void PollKeyboardButtons (void)
{
int i;
for (i = 0; i < NUMBUTTONS; i++)
if (Keyboard[buttonscan[i]])
buttonstate[i] = true;
}
/*
===================
=
= PollMouseButtons
=
===================
*/
void PollMouseButtons (void)
{
int buttons = IN_MouseButtons ();
if (buttons & 1)
buttonstate[buttonmouse[0]] = true;
if (buttons & 2)
buttonstate[buttonmouse[1]] = true;
if (buttons & 4)
buttonstate[buttonmouse[2]] = true;
#ifdef MOUSEWHEEL
if (buttons & 8) {
GetMessage("TEST",DEF_MSG_CLR);
buttonstate[buttonmouse[3]] = true;
}
if (buttons & 16)
buttonstate[buttonmouse[4]] = true;
#endif
}
/*
===================
=
= PollJoystickButtons
=
===================
*/
void PollJoystickButtons (void)
{
int buttons = IN_JoyButtons();
for(int i = 0, val = 1; i < JoyNumButtons; i++, val <<= 1)
{
if(buttons & val)
buttonstate[buttonjoy[i]] = true;
}
}
/*
===================
=
= PollKeyboardMove
=
===================
*/
void PollKeyboardMove (void)
{
if (Keyboard[sc_Tab] || Keyboard [sc_BackSpace]) return; // annoying move when using debug/cheat keys
if (Keyboard[dirscan[di_north]])
if (Keyboard[dirscan[di_south]])
if (Keyboard[dirscan[di_west]])
{
if (!Keyboard[dirscan[di_east]])
MOVE1LEFT()
}
else
{
if (Keyboard[dirscan[di_east]])
MOVE1RIGHT()
}
else
if (Keyboard[dirscan[di_west]])
if (Keyboard[dirscan[di_east]])
MOVE1FORWARD()
else
MOVE1FORWARDLEFT()
else
if (Keyboard[dirscan[di_east]])
MOVE1FORWARDRIGHT()
else
MOVE1FORWARD()
else
if (Keyboard[dirscan[di_south]])
if (Keyboard[dirscan[di_west]])
if (Keyboard[dirscan[di_east]])
MOVE1BACKWARD()
else
MOVE1BACKWARDLEFT()
else
if (Keyboard[dirscan[di_east]])
MOVE1BACKWARDRIGHT()
else
MOVE1BACKWARD()
else
if (Keyboard[dirscan[di_west]])
{
if (!Keyboard[dirscan[di_east]])
MOVE1LEFT()
}
else
if (Keyboard[dirscan[di_east]])
MOVE1RIGHT()
}
void PollKeyboardMoveClassic(void) {
if (Keyboard[sc_Tab] || Keyboard [sc_BackSpace]) return; // annoying move when using debug/cheat keys
if (buttonstate[bt_strafe])
{
if (Keyboard[dirscan[di_north]])
if (Keyboard[dirscan[di_south]])
if (Keyboard[dirscan[di_west]])
{
if (!Keyboard[dirscan[di_east]])
MOVE2LEFT()
}
else
{
if (Keyboard[dirscan[di_east]])
MOVE2RIGHT()
}
else
if (Keyboard[dirscan[di_west]])
{
if (Keyboard[dirscan[di_east]])
MOVE2FORWARD()
else
MOVE2FORWARDLEFT()
}
else
{
if (Keyboard[dirscan[di_east]])
MOVE2FORWARDRIGHT()
else
MOVE2FORWARD()
}
else
if (Keyboard[dirscan[di_south]])
if (Keyboard[dirscan[di_west]])
if (Keyboard[dirscan[di_east]])
MOVE2BACKWARD()
else
MOVE2BACKWARDLEFT()
else
if (Keyboard[dirscan[di_east]])
MOVE2BACKWARDRIGHT()
else
MOVE2BACKWARD()
else
if (Keyboard[dirscan[di_west]])
{
if (!Keyboard[dirscan[di_east]])
MOVE2LEFT()
}
else
{
if (Keyboard[dirscan[di_east]])
MOVE2RIGHT()
}
}
else
{
if (Keyboard[dirscan[di_west]])
{
if (!Keyboard[dirscan[di_east]])
TURNLEFT()
}
if (Keyboard[dirscan[di_east]])
TURNRIGHT()
if (Keyboard[dirscan[di_north]])
{
if (!Keyboard[dirscan[di_south]])
MOVE2FORWARD()
}
else
if (Keyboard[dirscan[di_south]])
MOVE2BACKWARD();
}
}
/*
===================
=
= PollMouseMove
=
===================
*/
byte viewingmap = 0;
void PollMouseMove (void)
{
int mousexmove, mouseymove;
SDL_GetMouseState(&mousexmove, &mouseymove);
if(IN_IsInputGrabbed())
IN_CenterMouse();
mousexmove -= screenWidth / 2;
mouseymove -= screenHeight / 2;
if (!switches.strafe || viewingmap)
{
controlx += mousexmove * 10 / (13 - mouseadjustment);
controly += mouseymove * 20 / (13 - mouseadjustment);
}
controlh += (mousexmove << 4) / (13 - mouseadjustment);
}
/*
===================
=
= PollJoystickMove
=
===================
*/
void PollJoystickMove (void)
{
int joyx, joyy;
IN_GetJoyDelta (&joyx, &joyy);
if (buttonstate[bt_strafe])
{
if (joyy < -64)
if (joyx < -64)
MOVE2FORWARDLEFT()
else if (joyx > 64)
MOVE2FORWARDRIGHT()
else
MOVE2FORWARD()
else
if (joyy > 64)
if (joyx < -64)
MOVE2BACKWARDLEFT()
else if (joyx > 64)
MOVE2BACKWARDRIGHT()
else
MOVE2BACKWARD()
}
else
{
if (joyx < -64)
TURNLEFT()
else if (joyx > 64)
TURNRIGHT()
if (joyy < -64)
MOVE2FORWARD()
else if (joyy > 64)
MOVE2BACKWARD()
}
}
/*
===================
=
= PollControls
=
= Gets user or demo input, call once each frame
=
= controlx set between -100 and 100 per tic
= controly
= buttonheld[] the state of the buttons LAST frame
= buttonstate[] the state of the buttons THIS frame
=
===================
*/
void PollControls (void)
{
int max, min, rmax, rmin, i;
byte buttonbits;
IN_ProcessEvents();
//
// get timing info for last frame
//
if (demoplayback || demorecord) // demo recording and playback needs to be constant
{
// wait up to DEMOTICS Wolf tics
uint32_t curtime = SDL_GetTicks();
lasttimecount += DEMOTICS;
int32_t timediff = (lasttimecount * 100) / 7 - curtime;
if(timediff > 0)
SDL_Delay(timediff);
if(timediff < -2 * DEMOTICS) // more than 2-times DEMOTICS behind?
lasttimecount = (curtime * 7) / 100; // yes, set to current timecount
tics = DEMOTICS;
}
else
CalcTics ();
controlx = 0;
controly = 0;
controlh = 0;
memcpy (buttonheld, buttonstate, sizeof (buttonstate));
memset (buttonstate, 0, sizeof (buttonstate));
if (demoplayback)
{
//
// read commands from demo buffer
//
buttonbits = *demoptr++;
for (i = 0; i < NUMBUTTONS; i++)
{
buttonstate[i] = buttonbits & 1;
buttonbits >>= 1;
}
controlx = *demoptr++;
controly = *demoptr++;
controlh = *demoptr++;
if (demoptr == lastdemoptr)
playstate = ex_completed; // demo is done
controlx *= (int)tics;
controly *= (int)tics;
controlh *= (int)tics;
return;
}
//
// get button states
//
PollKeyboardButtons ();
if (mouseenabled && IN_IsInputGrabbed())
PollMouseButtons ();
if (joystickenabled)
PollJoystickButtons ();
//
// get movements
//
if (!switches.strafe) {
PollKeyboardMoveClassic ();
} else {
PollKeyboardMove();
}
if (mouseenabled && IN_IsInputGrabbed())
PollMouseMove ();
if (joystickenabled)
PollJoystickMove ();
//
// bound movement to a maximum
//
max = 100 * tics;
min = -max;
rmax = max << 4;
rmin = -rmax;
if (controlh > rmax)
controlh = rmax;
else if (controlh < rmin)
controlh = rmin;
if (controlx > max)
controlx = max;
else if (controlx < min)
controlx = min;
if (controly > max)
controly = max;
else if (controly < min)
controly = min;
if (demorecord)
{
//
// save info out to demo buffer
//
controlx /= (int)tics;
controly /= (int)tics;
controlh /= (int)tics;
buttonbits = 0;
// TODO: Support 32-bit buttonbits
for (i = NUMBUTTONS - 1; i >= 0; i--)
{
buttonbits <<= 1;
if (buttonstate[i])
buttonbits |= 1;
}
*demoptr++ = buttonbits;
*demoptr++ = controlx;
*demoptr++ = controly;
*demoptr++ = controlh;
if (demoptr >= lastdemoptr - 8)
playstate = ex_completed;
else
{
controlx *= (int)tics;
controly *= (int)tics;
controlh *= (int)tics;
}
}
}
//==========================================================================
///////////////////////////////////////////////////////////////////////////
//
// CenterWindow() - Generates a window of a given width & height in the
// middle of the screen
//
///////////////////////////////////////////////////////////////////////////
#define MAXX 320
#define MAXY 160
void CenterWindow (word w, word h)
{
US_DrawWindow (((MAXX / 8) - w) / 2, ((MAXY / 8) - h) / 2, w, h);
}
//===========================================================================
/*
=====================
=
= CheckKeys
=
=====================
*/
void CheckKeys (void)
{
ScanCode scan;
if (screenfaded || demoplayback) // don't do anything with a faded screen
return;
scan = LastScan;
//
// SECRET CHEAT CODE: 'MLI'
//
if (Keyboard[sc_M] && !Keyboard[sc_Tab] && !Keyboard[sc_C])
{
ViewMap(0);
/*ClearMemory ();
SD_PlaySound(BOSSACTIVESND);
CA_CacheGrChunk (STARTFONT + 1);
ClearSplitVWB ();
Message ("Visit www.areyep.com!");
gamestate.weapon = (weapontype) -1;
gamestate.weapons = 0;
DrawWeapon();
DrawAmmo();
UNCACHEGRCHUNK (STARTFONT + 1);
IN_ClearKeysDown ();
IN_Ack ();
if (viewsize < 18)
DrawPlayBorder ();
gamestate.health = 100;
gamestate.primaryammo = MAXPRIMARYAMMO;
gamestate.keys = 0xF;
gamestate.score = 0;
gamestate.TimeCount += 42000L;
GiveWeapon (wp_mk3);
DrawWeapon ();
DrawHealth ();
DrawKeys ();
DrawAmmo ();
DrawScore ();
ClearMemory ();
CA_CacheGrChunk (STARTFONT + 1);
ClearSplitVWB ();
Message (STR_CHEATER1 "\n"
STR_CHEATER2 "\n\n" STR_CHEATER3 "\n" STR_CHEATER4 "\n" STR_CHEATER5);
UNCACHEGRCHUNK (STARTFONT + 1);
IN_ClearKeysDown ();
IN_Ack ();
if (viewsize < 17)
DrawPlayBorder ();*/
}
//
// SECRET CHEAT CODE: 'HAC'
//
if (Keyboard[sc_H] && Keyboard[sc_C] && Keyboard[sc_A]) {
}
//
// TRYING THE MCS/RIP CHEAT CODE!
//
if (Keyboard[sc_R] && Keyboard[sc_I] && Keyboard[sc_P])
{
if (gamestate.difficulty > gd_easy) {
gamestate.health--;
DrawHealth();
}
ClearMemory ();
SD_PlaySound(TAKEDAMAGESND);
CA_CacheGrChunk (STARTFONT + 1);
ClearSplitVWB ();
Message ("Try MCS!");
UNCACHEGRCHUNK (STARTFONT + 1);
IN_ClearKeysDown ();
IN_Ack ();
if (viewsize < 18)
DrawPlayBorder ();
}
if (Keyboard[sc_M] && Keyboard[sc_C] && Keyboard[sc_S]) {
if (gamestate.difficulty > gd_easy) {
gamestate.health--;
DrawHealth();
}
ClearMemory ();
SD_PlaySound(TAKEDAMAGESND);
CA_CacheGrChunk (STARTFONT + 1);
ClearSplitVWB ();
Message ("Try RIP!");
UNCACHEGRCHUNK (STARTFONT + 1);
IN_ClearKeysDown ();
IN_Ack ();
if (viewsize < 18)
DrawPlayBorder ();
}
if (Keyboard[sc_O] && Keyboard[sc_E] && Keyboard[sc_D]) {
ClearMemory ();
CA_CacheGrChunk (STARTFONT + 1);
ClearSplitVWB ();
Message ("End of Destiny SDL v1.0b\n"
"---------------------------\n"
"Original game by:\n"
" AReyeP and MCS\n"
"Ported by:\n"
" Kyle Albert\n"
"Visit www.areyep.com!");
UNCACHEGRCHUNK (STARTFONT + 1);
IN_ClearKeysDown ();
IN_Ack ();
if (viewsize < 18)
DrawPlayBorder ();
}
if (Keyboard[sc_BackSpace]) {
if (Keyboard[sc_T]) {
if (switches.textures)
GetMessage("Textures OFF",DEF_MSG_CLR);
else
GetMessage("Textures ON",DEF_MSG_CLR);
switches.textures ^= 1;
if (!switches.textures) {
switches.weather = 0;
switches.clouds = 0;
}
IN_ClearKeysDown();
} else if (Keyboard[sc_S]) {
if (switches.shading)
GetMessage("Shading OFF",DEF_MSG_CLR);
else
GetMessage("Shading ON",DEF_MSG_CLR);
switches.shading ^= 1;
InitLevelShadeTable();
IN_ClearKeysDown();
} else if (Keyboard[sc_W] && switches.textures) {
if (switches.weather)
GetMessage("Weather OFF",DEF_MSG_CLR);
else
GetMessage("Weather ON",DEF_MSG_CLR);
switches.weather ^= 1;
IN_ClearKeysDown();
} else if (Keyboard[sc_C] && switches.textures) {
if (switches.clouds)
GetMessage("Clouds OFF",DEF_MSG_CLR);
else
GetMessage("Clouds ON",DEF_MSG_CLR);
switches.clouds ^= 1;
IN_ClearKeysDown();
} else if (Keyboard[sc_B]) {
char buffer[40];
if (!gamestate.cheated)
sprintf(buffer, "Game saved %lu times without cheating", gamestate.saves);
else
sprintf(buffer, "Game saved %lu times with cheating", gamestate.saves);
GetMessage(buffer,DEF_MSG_CLR);
} else if (Keyboard[sc_F]) {
if (!fpscounter)
GetMessage("FPS counter ON",DEF_MSG_CLR);
else
GetMessage("FPS counter OFF",DEF_MSG_CLR);
fpscounter ^= 1;
IN_ClearKeysDown();
} else if (Keyboard[sc_N]) {
if (!switches.messages) {
GetMessage("Notifications ON",DEF_MSG_CLR);
IN_ClearKeysDown();
} else {
ClearMemory ();
ClearSplitVWB ();
Message("Notifications OFF");
IN_ClearKeysDown();
IN_Ack();
}
switches.messages ^= 1;
}
}
if ((Keyboard[SDLK_KP_PLUS] || Keyboard[SDLK_EQUALS]) && viewsize != 21) {
NewViewSize(viewsize+1);
if (viewsize != 21)
DrawPlayScreen();
VW_UpdateScreen();
IN_ClearKeysDown();
}
if ((Keyboard[SDLK_KP_MINUS] || Keyboard[SDLK_MINUS]) && viewsize != 4) {
NewViewSize(viewsize-1);
if (viewsize != 21)
DrawPlayScreen();
VW_UpdateScreen();
IN_ClearKeysDown();
}
//
// pause key weirdness can't be checked as a scan code
//
if(buttonstate[bt_pause]) Paused = true;
if(Paused)
{
int lastoffs = StopMusic();
LatchDrawPic (20 - 4, 80 - 2 * 8, PAUSEDPIC);
VH_UpdateScreen();
IN_Ack ();
Paused = false;
ContinueMusic(lastoffs);
if (MousePresent && IN_IsInputGrabbed())
IN_CenterMouse(); // Clear accumulated mouse movement
lasttimecount = GetTimeCount();
return;
}
//
// F1-F7/ESC to enter control panel
//
if (
#ifndef DEBCHECK
scan == sc_F10 ||
#endif
scan == sc_F9 || scan == sc_F7 || scan == sc_F8) // pop up quit dialog
{
ClearMemory ();
ClearSplitVWB ();
US_ControlPanel (scan);
DrawPlayBorderSides ();
SETFONTCOLOR (0, 15);
IN_ClearKeysDown ();
return;
}
if ((scan >= sc_F1 && scan <= sc_F9) || scan == sc_Escape || scan == sc_F11 ||buttonstate[bt_esc])
{
int lastoffs = StopMusic ();
ClearMemory ();
VW_FadeOut ();
US_ControlPanel (buttonstate[bt_esc] ? sc_Escape : scan);
SETFONTCOLOR (0, 15);
IN_ClearKeysDown ();
VW_FadeOut();
if(viewsize != 21)
DrawPlayScreen ();
if (!startgame && !loadedgame)
ContinueMusic (lastoffs);
if (loadedgame)
playstate = ex_abort;
lasttimecount = GetTimeCount();
if (MousePresent && IN_IsInputGrabbed())
IN_CenterMouse(); // Clear accumulated mouse movement
return;
}
//
// TAB-? debug keys
//
#ifdef DEBUGKEYS
if (DebugOk && Keyboard[sc_Tab])
{
CA_CacheGrChunk (STARTFONT);
fontnumber = 0;
SETFONTCOLOR (0x1E, 0x17); // center window font stuff
if (gamestate.difficulty != gd_extreme && DebugKeys ()) {
if (viewsize < 18)
DrawPlayBorder (); // dont let the blue borders flash
gamestate.cheated = true;
gamestate.score = gamestate.oldscore = 0;
DrawScore();
}
if (MousePresent && IN_IsInputGrabbed())
IN_CenterMouse(); // Clear accumulated mouse movement
lasttimecount = GetTimeCount();
return;
}
#endif
}
//===========================================================================
/*
#############################################################################
The objlist data structure
#############################################################################
objlist containt structures for every actor currently playing. The structure
is accessed as a linked list starting at *player, ending when ob->next ==
NULL. GetNewObj inserts a new object at the end of the list, meaning that
if an actor spawn another actor, the new one WILL get to think and react the
same frame. RemoveObj unlinks the given object and returns it to the free
list, but does not damage the objects ->next pointer, so if the current object
removes itself, a linked list following loop can still safely get to the
next element.
<backwardly linked free list>
#############################################################################
*/
/*
=========================
=
= InitActorList
=
= Call to clear out the actor object lists returning them all to the free
= list. Allocates a special spot for the player.
=
=========================
*/
int objcount;
void InitActorList (void)
{
int i;
//
// init the actor lists
//
for (i = 0; i < MAXACTORS; i++)
{
objlist[i].prev = &objlist[i + 1];
objlist[i].next = NULL;
}
objlist[MAXACTORS - 1].prev = NULL;
objfreelist = &objlist[0];
lastobj = NULL;
objcount = 0;
//
// give the player the first free spots
//
GetNewActor ();
player = newobj;
}
//===========================================================================
/*
=========================
=
= GetNewActor
=
= Sets the global variable new to point to a free spot in objlist.
= The free spot is inserted at the end of the liked list
=
= When the object list is full, the caller can either have it bomb out ot
= return a dummy object pointer that will never get used
=
=========================
*/
void GetNewActor (void)
{
if (!objfreelist)
Quit ("GetNewActor: No free spots in objlist!");
newobj = objfreelist;
objfreelist = newobj->prev;
memset (newobj, 0, sizeof (*newobj));
if (lastobj)
lastobj->next = newobj;
newobj->prev = lastobj; // new->next is allready NULL from memset
newobj->active = ac_no;
lastobj = newobj;
objcount++;
}
//===========================================================================
/*
=========================
=
= RemoveObj
=
= Add the given object back into the free list, and unlink it from it's
= neighbors
=
=========================
*/
void RemoveObj (objtype * gone)
{
if (gone == player)
Quit ("RemoveObj: Tried to remove the player!");
gone->state = NULL;
//
// fix the next object's back link
//
if (gone == lastobj)
lastobj = (objtype *) gone->prev;
else
gone->next->prev = gone->prev;
//
// fix the previous object's forward link
//
gone->prev->next = gone->next;
//
// add it back in to the free list
//
gone->prev = objfreelist;
objfreelist = gone;
objcount--;
}
/*
=============================================================================
MUSIC STUFF
=============================================================================
*/
/*
=================
=
= StopMusic
=
=================
*/
int StopMusic (void)
{
int lastoffs = SD_MusicOff ();
UNCACHEAUDIOCHUNK (STARTMUSIC + lastmusicchunk);
return lastoffs;
}
//==========================================================================
/*
=================
=
= StartMusic
=
=================
*/
void StartMusic ()
{
SD_MusicOff ();
lastmusicchunk = (musicnames) levelinfo.music;
SD_StartMusic(STARTMUSIC + lastmusicchunk);
}
void ContinueMusic (int offs)
{
SD_MusicOff ();
lastmusicchunk = (musicnames) levelinfo.music;
SD_ContinueMusic(STARTMUSIC + lastmusicchunk, offs);
}
/*
=============================================================================
PALETTE SHIFTING STUFF
=============================================================================
*/
#define NUMREDSHIFTS 6
#define REDSTEPS 8
#define NUMWHITESHIFTS 3
#define WHITESTEPS 20
#define WHITETICS 6
SDL_Color redshifts[NUMREDSHIFTS][256];
SDL_Color whiteshifts[NUMWHITESHIFTS][256];
int damagecount, bonuscount;
boolean palshifted;
/*
=====================
=
= InitRedShifts
=
=====================
*/
void InitRedShifts (void)
{
SDL_Color *workptr, *baseptr;
int i, j, delta;
//
// fade through intermediate frames
//
for (i = 1; i <= NUMREDSHIFTS; i++)
{
workptr = redshifts[i - 1];
baseptr = gamepal;
for (j = 0; j <= 255; j++)
{
delta = 256 - baseptr->r;
workptr->r = baseptr->r + delta * i / REDSTEPS;
delta = -baseptr->g;
workptr->g = baseptr->g + delta * i / REDSTEPS;
delta = -baseptr->b;
workptr->b = baseptr->b + delta * i / REDSTEPS;
baseptr++;
workptr++;
}
}
for (i = 1; i <= NUMWHITESHIFTS; i++)
{
workptr = whiteshifts[i - 1];
baseptr = gamepal;
for (j = 0; j <= 255; j++)
{
delta = 256 - baseptr->r;
workptr->r = baseptr->r + delta * i / WHITESTEPS;
delta = 248 - baseptr->g;
workptr->g = baseptr->g + delta * i / WHITESTEPS;
delta = 0-baseptr->b;
workptr->b = baseptr->b + delta * i / WHITESTEPS;
baseptr++;
workptr++;
}
}
}
/*
=====================
=
= ClearPaletteShifts
=
=====================
*/
void ClearPaletteShifts (void)
{
bonuscount = damagecount = 0;
palshifted = false;
}
/*
=====================
=
= StartBonusFlash
=
=====================
*/
void StartBonusFlash (void)
{
bonuscount = NUMWHITESHIFTS * WHITETICS; // white shift palette
}
/*
=====================
=
= StartDamageFlash
=
=====================
*/
void StartDamageFlash (int damage)
{
damagecount += damage;
}
/*
=====================
=
= UpdatePaletteShifts
=
=====================
*/
void UpdatePaletteShifts (void)
{
int red, white;
if (bonuscount)
{
white = bonuscount / WHITETICS + 1;
if (white > NUMWHITESHIFTS)
white = NUMWHITESHIFTS;
bonuscount -= tics;
if (bonuscount < 0)
bonuscount = 0;
}
else
white = 0;
if (damagecount)
{
red = damagecount / 10 + 1;
if (red > NUMREDSHIFTS)
red = NUMREDSHIFTS;
damagecount -= tics;
if (damagecount < 0)
damagecount = 0;
}
else
red = 0;
if (red)
{
VL_SetPalette (redshifts[red - 1], false);
palshifted = true;
}
else if (white)
{
VL_SetPalette (whiteshifts[white - 1], false);
palshifted = true;
}
else if (palshifted)
{
VL_SetPalette (gamepal, false); // back to normal
palshifted = false;
}
}
/*
=====================
=
= FinishPaletteShifts
=
= Resets palette to normal if needed
=
=====================
*/
void FinishPaletteShifts (void)
{
if (palshifted)
{
palshifted = 0;
VL_SetPalette (gamepal, true);
}
}
/*
=============================================================================
CORE PLAYLOOP
=============================================================================
*/
/*
=====================
=
= DoActor
=
=====================
*/
void DoActor (objtype * ob)
{
void (*think) (objtype *);
if (!ob->active && !areabyplayer[ob->areanumber])
return;
if (!(ob->flags & (FL_NONMARK | FL_NEVERMARK)) && MAPSPOT(ob->tilex,ob->tiley,1) != CLONETOILETTILE)
actorat[ob->tilex][ob->tiley] = NULL;
//
// non transitional object
//
if (!ob->ticcount)
{
think = (void (*)(objtype *)) ob->state->think;
if (think)
{
think (ob);
if (!ob->state)
{
RemoveObj (ob);
return;
}
}
if (ob->flags & FL_NEVERMARK)
return;
if ((ob->flags & FL_NONMARK) && actorat[ob->tilex][ob->tiley])
return;
actorat[ob->tilex][ob->tiley] = ob;
return;
}
//
// transitional object
//
ob->ticcount -= (short) tics;
while (ob->ticcount <= 0)
{
think = (void (*)(objtype *)) ob->state->action; // end of state action
if (think)
{
think (ob);
if (!ob->state)
{
RemoveObj (ob);
return;
}
}
ob->state = ob->state->next;
if (!ob->state)
{
RemoveObj (ob);
return;
}
if (!ob->state->tictime)
{
ob->ticcount = 0;
goto think;
}
ob->ticcount += ob->state->tictime;
if (ob->obclass == turretobj && ob->dir != nodir) {
ob->dir = (dirtype)((ob->dir + 1) % 8);
}
}
think:
//
// think
//
think = (void (*)(objtype *)) ob->state->think;
if (think)
{
think (ob);
if (!ob->state)
{
RemoveObj (ob);
return;
}
}
if (ob->flags & FL_NEVERMARK)
return;
if ((ob->flags & FL_NONMARK) && actorat[ob->tilex][ob->tiley])
return;
actorat[ob->tilex][ob->tiley] = ob;
}
//==========================================================================
/*
===================
=
= DoTimers
=
===================
*/
int32_t funnyticount = 0;
void DoTimers(void) {
if (gamestate.godmodetics > 0) {
StartBonusFlash();
gamestate.godmodetics -= tics;
if (gamestate.godmodetics <= 0) {
SD_PlaySound(TAKEDAMAGESND);
gamestate.godmode = false;
}
}
if (gamestate.furytics > 0) {
StartBonusFlash();
gamestate.furytics -= tics;
if (gamestate.furytics <= 0) {
SD_PlaySound(TAKEDAMAGESND);
gamestate.fury = false;
if (gamestate.weapon == wp_knife && gamestate.lastweaponfury != wp_knife) {
NEXTWEAPON(gamestate.lastweaponfury);
}
}
}
if(gamestate.changingweapon && gamestate.attackframe == 0) {
if(!gamestate.goingdown) {
gamestate.weapchange -= 50 * tics; // 60
if(gamestate.weapchange <= 0) {
gamestate.weapchange = 0;
gamestate.changingweapon = false;
}
} else {
gamestate.weapchange += 50 * tics; // 60
if(gamestate.weapchange >= 1200) { // 700
gamestate.goingdown = false;
gamestate.weapon = gamestate.nextweapon;
DrawWeapon();
DrawAmmo();
}
}
}
if (gamestate.levelTimer > 0) {
gamestate.levelTimer -= tics;
if (gamestate.levelTimer <= 0) {
playstate=ex_completed;
}
}
if (gamestate.reloadtics > 0)
gamestate.reloadtics-=tics;
#ifdef VARIABLEWEATHER
if (switches.weather) {
if (gamestate.weatherchecktics > 0) {
gamestate.weatherchecktics -= tics;
if (gamestate.weatherchecktics <= 0)
PollWeatherChange();
}
if (gamestate.weatherchange == -1) {
if (gamestate.weatherpoints != 0) {
gamestate.weatherdelaytics -= tics;
if (gamestate.weatherdelaytics <= 0) {
gamestate.weatherdelaytics = WEATHERDELAY * 70;
gamestate.weatherpoints-=10;
if (gamestate.weatherpoints < 0)
gamestate.weatherpoints = 0;
}
} else {
gamestate.weatherchange = 0;
}
} else if (gamestate.weatherchange == 1) {
if (gamestate.weatherpoints != 500) {
gamestate.weatherdelaytics -= tics;
if (gamestate.weatherdelaytics <= 0) {
gamestate.weatherdelaytics = WEATHERDELAY * 70;
gamestate.weatherpoints+=10;
if (gamestate.weatherpoints > 500)
gamestate.weatherpoints = 500;
}
} else {
gamestate.weatherchange = 0;
}
}
}
#endif
//
// MAKE FUNNY FACE IF BJ DOESN'T MOVE FOR AWHILE
//
#ifdef SPEAR
funnyticount += tics;
if (funnyticount > 2100)
{
funnyticount = 0;
StatusDrawFace(BJWAITING1PIC + (US_RndT () & 1));
facecount = 0;
}
#endif
}
/*
===================
=
= PlayLoop
=
===================
*/
void PlayLoop (void)
{
#if defined(USE_FEATUREFLAGS) && defined(USE_CLOUDSKY)
if(levelinfo.weather & FF_CLOUDSKY)
InitSky();
#endif
#ifdef USE_SHADING
InitLevelShadeTable();
#endif
playstate = ex_stillplaying;
lasttimecount = GetTimeCount();
frameon = 0;
anglefrac = 0;
facecount = 0;
funnyticount = 0;
memset (buttonstate, 0, sizeof (buttonstate));
ClearPaletteShifts ();
if (MousePresent && IN_IsInputGrabbed())
IN_CenterMouse(); // Clear accumulated mouse movement
if (demoplayback)
IN_StartAck ();
// Level beginning stuff
do
{
PollControls ();
//
// actor thinking
//
madenoise = false;
MoveDoors ();
MovePWalls ();
ShootFireballs();
DoTimers();
for (obj = player; obj; obj = obj->next) {
DoActor (obj);
}
UpdatePaletteShifts ();
ThreeDRefresh ();
gamestate.TimeCount += tics;
UpdateSoundLoc (); // JAB
if (screenfaded)
VW_FadeIn ();
CheckKeys ();
//
// debug aids
//
if (singlestep)
{
VW_WaitVBL (singlestep);
lasttimecount = GetTimeCount();
}
if (extravbls)
VW_WaitVBL (extravbls);
if (demoplayback)
{
if (IN_CheckAck ())
{
IN_ClearKeysDown ();
playstate = ex_abort;
}
}
}
while (!playstate && !startgame);
if (playstate != ex_died)
FinishPaletteShifts ();
}
| 23.345606 | 180 | 0.492547 | [
"object"
] |
b4a01689645017bee76f4fc10e6a0851ca3c74bb | 8,608 | cpp | C++ | src/json/JsonParticleParser.cpp | Jino42/stf | f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db | [
"Unlicense"
] | null | null | null | src/json/JsonParticleParser.cpp | Jino42/stf | f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db | [
"Unlicense"
] | null | null | null | src/json/JsonParticleParser.cpp | Jino42/stf | f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db | [
"Unlicense"
] | null | null | null | #include "JsonParticleParser.hpp"
#include "Particle/ParticleSystemManager.hpp"
#include "cl_type.hpp"
#include "Particle/PaticleEmitter/ParticleEmitterMesh.hpp"
#include "Particle/PaticleEmitter/ParticleEmitterPoint.hpp"
#include "Particle/PaticleEmitter/ParticleEmitterSPH.hpp"
#include "Particle/PaticleEmitter/ParticleEmitterSprite.hpp"
#include "Particle/ParticleModule/ModuleAttractor.hpp"
#include "Particle/ParticleModule/ModuleColor.hpp"
#include "Particle/ParticleModule/ModuleMeshParticulizer.hpp"
#include "Particle/ParticleModule/ModuleMoveToTarget.hpp"
#include "Particle/ParticleModule/ModuleMovement.hpp"
#include "Particle/ParticleModule/ModulePhysicConstrainInShape.hpp"
#include "Particle/ParticleModule/ModulePhysicGravity.hpp"
#include "Particle/ParticleModule/ModulePhysicNoise.hpp"
#include "Particle/ParticleModule/ModuleResolvePhysic.hpp"
#include "Particle/ParticleModule/ModuleSPH.hpp"
#include "Particle/ParticleModule/ModuleSizeOverLifetime.hpp"
#include "Particle/ParticleModule/ParticleSpawnModule.hpp"
JsonParticleParser::JsonParticleParser(boost::filesystem::path path)
: jsonPath_(path),
currentSystem_(nullptr),
currentEmitter_(nullptr) {
}
void JsonParticleParser::parse() {
std::cout << "begin parse" << std::endl;
std::cout << jsonPath_ << std::endl;
json_ = getJsonFromFileAbsolutePath(jsonPath_.generic_string());
std::cout << json_ << std::endl;
for (auto &itSystem: json_["Systems"]) {
std::cout << itSystem["name"] << std::endl;
std::cout << itSystem["options"] << std::endl;
std::cout << itSystem["emitters"] << std::endl;
ParticleSystemManager::Get().addParticleSystem(itSystem["name"].get<std::string>());
currentSystem_ = &ParticleSystemManager::Get().getParticleSystem(itSystem["name"].get<std::string>());
if (itSystem.find("options") != itSystem.end()) {
std::cout << "There are options : " << std::endl;
if (itSystem["options"].find("position") != itSystem["options"].end()) {
json &position = *itSystem["options"].find("position");
currentSystem_->setPosition(jsonToVec3(position));
}
if (itSystem.find("emitters") != itSystem.end()) {
for (auto &itEmitter: *itSystem.find("emitters")) {
if (itEmitter.find("active") != itEmitter.end() && !itEmitter["active"].get<bool>())
continue;
std::cout << itEmitter["type"] << std::endl;
if (itEmitter["type"].get<std::string>() == "Sprite") {
auto name = itEmitter["name"].get<std::string>();
currentSystem_->addEmitter<ParticleEmitterSprite>(name, itEmitter["particlesMax"].get<int>());
currentEmitter_ = ¤tSystem_->getEmitter<ParticleEmitterSprite>(name);
} else if (itEmitter["type"].get<std::string>() == "Point") {
auto name = itEmitter["name"].get<std::string>();
currentSystem_->addEmitter<ParticleEmitterPoint>(name, itEmitter["particlesMax"].get<int>());
currentEmitter_ = ¤tSystem_->getEmitter<ParticleEmitterPoint>(name);
} else if (itEmitter["type"].get<std::string>() == "Mesh") {
auto name = itEmitter["name"].get<std::string>();
currentSystem_->addEmitter<ParticleEmitterMesh>(name, itEmitter["particlesMax"].get<int>());
currentEmitter_ = ¤tSystem_->getEmitter<ParticleEmitterMesh>(name);
} else if (itEmitter["type"].get<std::string>() == "SPH") {
auto name = itEmitter["name"].get<std::string>();
currentSystem_->addEmitter<ParticleEmitterSPH>(name, itEmitter["particlesMax"].get<int>());
currentEmitter_ = ¤tSystem_->getEmitter<ParticleEmitterSPH>(name);
} else {
currentEmitter_ = nullptr;
}
if (currentEmitter_ && itEmitter["options"].find("position") != itEmitter["options"].end()) {
json &position = *itEmitter["options"].find("position");
currentEmitter_->getPosition() = jsonToVec3(position);
}
if (currentEmitter_ && itEmitter.find("modules") != itEmitter.end()) {
for (auto &itModule: *itEmitter.find("modules")) {
if (itModule.find("active") != itModule.end() && !itModule["active"].get<bool>())
continue;
std::cout << itModule["type"] << std::endl;
if (itModule["type"].get<std::string>() == "Spawn") {
currentEmitter_->addModule<ParticleSpawnModule>();
currentEmitter_->getModule<ParticleSpawnModule>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "Physic") {
currentEmitter_->addModule<ModuleResolvePhysic>();
currentEmitter_->getModule<ModuleResolvePhysic>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "Movement") {
currentEmitter_->addModule<ModuleMovement>();
currentEmitter_->getModule<ModuleMovement>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "Target") {
currentEmitter_->addModule<ModuleTarget>();
currentEmitter_->getModule<ModuleTarget>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "MeshParticulizer") {
currentEmitter_->addModule<ModuleMeshParticulizer>();
currentEmitter_->getModule<ModuleMeshParticulizer>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "MoveToTarget") {
currentEmitter_->addModule<ModuleMoveToTarget>();
currentEmitter_->getModule<ModuleMoveToTarget>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "SizeOverLifetime") {
currentEmitter_->addModule<ModuleSizeOverLifetime>();
currentEmitter_->getModule<ModuleSizeOverLifetime>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "Attractor") {
currentEmitter_->addModule<ModuleAttractor>();
currentEmitter_->getModule<ModuleAttractor>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "PhysicGravity") {
currentEmitter_->addModule<ModulePhysicGravity>();
currentEmitter_->getModule<ModulePhysicGravity>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "PhysicNoise") {
currentEmitter_->addModule<ModulePhysicNoise>();
currentEmitter_->getModule<ModulePhysicNoise>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "Color") {
currentEmitter_->addModule<ModuleColor>();
currentEmitter_->getModule<ModuleColor>()->jsonParse(itModule);
} else if (itModule["type"].get<std::string>() == "PhysicConstrainInShape") {
currentEmitter_->addModule<ModulePhysicConstrainInShape>(itModule["options"].find("shape")->get<std::string>());
currentEmitter_->getModule<ModulePhysicConstrainInShape>()->jsonParse(itModule);
}
}
}
}
}
}
currentSystem_ = nullptr;
currentEmitter_ = nullptr;
}
std::cout << "end parse" << std::endl;
}
glm::vec3 JsonParticleParser::jsonToVec3(json &json) {
glm::vec3 vec;
vec.x = json["x"];
vec.y = json["y"];
vec.z = json["z"];
return vec;
}
| 60.619718 | 144 | 0.558086 | [
"mesh",
"shape"
] |
b4a01c8f77318578c5254ad9114bf3eb7c3852f9 | 4,417 | cpp | C++ | SimulationCore/ParticleContactDetectionGrid.cpp | MingAtUWA/SimpleMPM2 | 7a1d7c257c621123d85a0630e93d42ae25c70fb4 | [
"MIT"
] | null | null | null | SimulationCore/ParticleContactDetectionGrid.cpp | MingAtUWA/SimpleMPM2 | 7a1d7c257c621123d85a0630e93d42ae25c70fb4 | [
"MIT"
] | null | null | null | SimulationCore/ParticleContactDetectionGrid.cpp | MingAtUWA/SimpleMPM2 | 7a1d7c257c621123d85a0630e93d42ae25c70fb4 | [
"MIT"
] | null | null | null | #include "SimulationCore_pcp.h"
#include "ParticleContactDetectionGrid.h"
void ParticleContactDetectionGrid::init_grid(
double xl, double xu,
double yl, double yu,
double hx, double hy
)
{
if (xl >= xu || yl >= yu)
return;
clear_grid();
x_num = size_t(ceil((xu - xl) / hx));
y_num = size_t(ceil((yu - yl) / hy));
x0 = xl;
xn = xu;
y0 = yl;
yn = yu;
dx = (xu - xl) / double(x_num);
dy = (yu - yl) / double(y_num);
grids = new Grid[x_num * y_num];
Grid *pg = grids;
for (size_t y_id = 0; y_id < y_num; ++y_id)
for (size_t x_id = 0; x_id < x_num; ++x_id)
{
pg->x_id = x_id;
pg->y_id = y_id;
pg->bbox_list = nullptr;
++pg;
}
bbox_mem.reset();
}
inline void ParticleContactDetectionGrid::clear_grid(void)
{
if (grids)
{
delete[] grids;
grids = nullptr;
}
x_num = 0;
y_num = 0;
}
inline void ParticleContactDetectionGrid::reset_grid(void)
{
bbox_mem.reset();
Grid *pg = grids;
for (size_t y_id = 0; y_id < y_num; ++y_id)
for (size_t x_id = 0; x_id < x_num; ++x_id)
{
pg->bbox_list = nullptr;
++pg;
}
}
// return the number of grids that this particle overlaps
size_t ParticleContactDetectionGrid::add_particle(double x, double y, double vol)
{
BoundingBox bbox(x, y, vol);
// check whether the particle overlap the mesh
if (!detect_contact(bbox))
return 0;
// trim particle if it lies at the edge
if (bbox.xl < x0)
bbox.xl = x0;
if (bbox.xu > xn)
bbox.xu = xn;
if (bbox.yl < y0)
bbox.yl = y0;
if (bbox.yu > yn)
bbox.yu = yn;
size_t xl_id = size_t(floor((bbox.xl - x0) / dx));
size_t xu_id = size_t(ceil((bbox.xu - x0) / dx));
size_t x_num = xu_id - xl_id;
size_t yl_id = size_t(floor((bbox.yl - y0) / dy));
size_t yu_id = size_t(ceil((bbox.yu - y0) / dy));
size_t y_num = yu_id - yl_id;
Grid *pg;
if (x_num == 1)
{
if (y_num == 1)
{
pg = pgrid_by_id(xl_id, yl_id);
add_bbox_to_grid(bbox, *pg);
return 1;
}
else if (y_num == 2)
{
pg = pgrid_by_id(xl_id, yl_id);
add_bbox_to_grid(bbox, *pg);
pg += x_num;
add_bbox_to_grid(bbox, *pg);
return 2;
}
}
else if (x_num == 2)
{
if (y_num == 1)
{
pg = pgrid_by_id(xl_id, yl_id);
add_bbox_to_grid(bbox, *pg);
++pg;
add_bbox_to_grid(bbox, *pg);
return 2;
}
else if (y_num == 2)
{
pg = pgrid_by_id(xl_id, yl_id);
add_bbox_to_grid(bbox, *pg);
++pg;
add_bbox_to_grid(bbox, *pg);
pg += x_num;
add_bbox_to_grid(bbox, *pg);
--pg;
add_bbox_to_grid(bbox, *pg);
return 4;
}
}
size_t elem_num = x_num * y_num;
for (size_t j = 0; j < y_num; ++j)
{
pg = pgrid_by_id(xl_id, yl_id + j);
for (size_t i = 0; i < x_num; ++i)
{
add_bbox_to_grid(bbox, *pg);
++pg;
}
}
return elem_num;
}
// return value:
// true: in contact
// false: not in contact
bool ParticleContactDetectionGrid::detect_contact(double x, double y, double vol)
{
BoundingBox bbox(x, y, vol);
// check whether the particle overlap the mesh
if (!detect_contact(bbox))
return 0;
// trim particle if it lies at the edge
if (bbox.xl < x0)
bbox.xl = x0;
if (bbox.xu > xn)
bbox.xu = xn;
if (bbox.yl < y0)
bbox.yl = y0;
if (bbox.yu > yn)
bbox.yu = yn;
size_t xl_id = size_t(floor((bbox.xl - x0) / dx));
size_t xu_id = size_t(ceil((bbox.xu - x0) / dx));
size_t x_num = xu_id - xl_id;
size_t yl_id = size_t(floor((bbox.yl - y0) / dy));
size_t yu_id = size_t(ceil((bbox.yu - y0) / dy));
size_t y_num = yu_id - yl_id;
Grid *pg;
if (x_num == 1)
{
if (y_num == 1)
{
pg = pgrid_by_id(xl_id, yl_id);
return pg->detect_contact(bbox);
}
else if (y_num == 2)
{
pg = pgrid_by_id(xl_id, yl_id);
if (pg->detect_contact(bbox)) return true;
pg += x_num;
return pg->detect_contact(bbox);
}
}
else if (x_num == 2)
{
if (y_num == 1)
{
pg = pgrid_by_id(xl_id, yl_id);
if (pg->detect_contact(bbox)) return true;
++pg;
return pg->detect_contact(bbox);
}
else if (y_num == 2)
{
pg = pgrid_by_id(xl_id, yl_id);
if (pg->detect_contact(bbox)) return true;
++pg;
if (pg->detect_contact(bbox)) return true;
pg += x_num;
if (pg->detect_contact(bbox)) return true;
--pg;
return pg->detect_contact(bbox);
}
}
size_t elem_num = x_num * y_num;
for (size_t j = 0; j < y_num; ++j)
{
pg = pgrid_by_id(xl_id, yl_id + j);
for (size_t i = 0; i < x_num; ++i)
{
if (pg->detect_contact(bbox))
return true;
++pg;
}
}
return false;
} | 20.077273 | 81 | 0.606973 | [
"mesh"
] |
b4a102b1510ad6413d64977a85086dee8675e746 | 879 | cpp | C++ | usaco_practice/gold/DP/time_mooney.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | usaco_practice/gold/DP/time_mooney.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | usaco_practice/gold/DP/time_mooney.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX_N=1005, MAX_M=2005;
int N, M, C;
int m[MAX_M]={};
vector<int> to_i[MAX_N];
int dp[2005][MAX_N];
int ans=0;
int main()
{
freopen("time.in", "r", stdin);
freopen("time.out", "w", stdout);
cin >> N >> M >> C;
for (int i=1; i<=N; i++) cin >> m[i];
for (int i=0; i<M; i++) {
int a, b; cin >> a >> b;
to_i[b].push_back(a);
}
dp[0][1]=0;
for (int t=1; t<1005; t++) {
for (int i=1; i<=N; i++) {
for (int j=0; j<to_i[i].size(); j++) {
if (dp[t-1][to_i[i][j]]==0 && to_i[i][j]!=1) continue;
dp[t][i]=max(dp[t][i], dp[t-1][to_i[i][j]]+m[i]);
}
}
ans=max(ans, dp[t][1]-C*t*t);
//cout << t << " " << dp[t][1] << " " << C*t*t << "\n";
}
cout << ans;
}
| 23.756757 | 70 | 0.434585 | [
"vector"
] |
b4a7d249e76600961a3edecca7f48357083e2347 | 6,115 | cpp | C++ | extras/demos/Demo11/SysCore/Hal/Hal.cpp | kammce/KinXOS | 637ecc7a345e19df7ebffd95b476591ce1134829 | [
"MIT"
] | null | null | null | extras/demos/Demo11/SysCore/Hal/Hal.cpp | kammce/KinXOS | 637ecc7a345e19df7ebffd95b476591ce1134829 | [
"MIT"
] | null | null | null | extras/demos/Demo11/SysCore/Hal/Hal.cpp | kammce/KinXOS | 637ecc7a345e19df7ebffd95b476591ce1134829 | [
"MIT"
] | null | null | null |
//****************************************************************************
//**
//** Hal.cpp
//** Hardware Abstraction Layer for i86 architecture
//**
//** The Hardware Abstraction Layer (HAL) provides an abstract interface
//** to control the basic motherboard hardware devices. This is accomplished
//** by abstracting hardware dependencies behind this interface.
//**
//****************************************************************************
#ifndef ARCH_X86
#error "[hal.cpp for i86] requires i86 architecture. Define ARCH_X86"
#endif
//============================================================================
// IMPLEMENTATION HEADERS
//============================================================================
#include <Hal.h>
#include "cpu.h"
#include "pic.h"
#include "pit.h"
#include "idt.h"
//============================================================================
// IMPLEMENTATION PRIVATE DEFINITIONS / ENUMERATIONS / SIMPLE TYPEDEFS
//============================================================================
//============================================================================
// IMPLEMENTATION PRIVATE CLASS PROTOTYPES / EXTERNAL CLASS REFERENCES
//============================================================================
//============================================================================
// IMPLEMENTATION PRIVATE STRUCTURES / UTILITY CLASSES
//============================================================================
//============================================================================
// IMPLEMENTATION REQUIRED EXTERNAL REFERENCES (AVOID)
//============================================================================
//============================================================================
// IMPLEMENTATION PRIVATE DATA
//============================================================================
//============================================================================
// INTERFACE DATA
//============================================================================
//============================================================================
// IMPLEMENTATION PRIVATE FUNCTION PROTOTYPES
//============================================================================
//============================================================================
// IMPLEMENTATION PRIVATE FUNCTIONS
//============================================================================
//============================================================================
// INTERFACE FUNCTIONS
//============================================================================
//! initialize hardware devices
int _cdecl hal_initialize () {
//! disable hardware interrupts
disable ();
//! initialize motherboard controllers and system timer
i86_cpu_initialize ();
i86_pic_initialize (0x20,0x28);
i86_pit_initialize ();
i86_pit_start_counter (100,I86_PIT_OCW_COUNTER_0, I86_PIT_OCW_MODE_SQUAREWAVEGEN);
//! enable interrupts
enable ();
return 0;
}
//! shutdown hardware devices
int _cdecl hal_shutdown () {
//! shutdown system resources
i86_cpu_shutdown ();
return 0;
}
//! generate i86 interrupt request
void _cdecl geninterrupt (int n) {
#ifdef _MSC_VER
_asm {
mov al, byte ptr [n]
mov byte ptr [genint+1], al
jmp genint
genint:
int 0 // above code modifies the 0 to int number to generate
}
#endif
}
//! notifies hal interrupt is done
inline void _cdecl interruptdone (unsigned int intno) {
//! insure its a valid hardware irq
if (intno > 16)
return;
//! test if we need to send end-of-interrupt to second pic
if (intno >= 8)
i86_pic_send_command (I86_PIC_OCW2_MASK_EOI, 1);
//! always send end-of-interrupt to primary pic
i86_pic_send_command (I86_PIC_OCW2_MASK_EOI, 0);
}
//! output sound to speaker
void _cdecl sound (unsigned frequency) {
//! sets frequency for speaker. frequency of 0 disables speaker
outportb (0x61, 3 | unsigned char(frequency<<2) );
}
//! read byte from device using port mapped io
unsigned char _cdecl inportb (unsigned short portid) {
#ifdef _MSC_VER
_asm {
mov dx, word ptr [portid]
in al, dx
mov byte ptr [portid], al
}
#endif
return (unsigned char)portid;
}
//! write byte to device through port mapped io
void _cdecl outportb (unsigned short portid, unsigned char value) {
#ifdef _MSC_VER
_asm {
mov al, byte ptr [value]
mov dx, word ptr [portid]
out dx, al
}
#endif
}
//! enable all hardware interrupts
void _cdecl enable () {
#ifdef _MSC_VER
_asm sti
#endif
}
//! disable all hardware interrupts
void _cdecl disable () {
#ifdef _MSC_VER
_asm cli
#endif
}
//! sets new interrupt vector
void _cdecl setvect (int intno, void (_cdecl far &vect) ( ) ) {
//! install interrupt handler! This overwrites prev interrupt descriptor
i86_install_ir (intno, I86_IDT_DESC_PRESENT | I86_IDT_DESC_BIT32,
0x8, vect);
}
//! returns current interrupt vector
void (_cdecl far * _cdecl getvect (int intno)) ( ) {
//! get the descriptor from the idt
idt_descriptor* desc = i86_get_ir (intno);
if (!desc)
return 0;
//! get address of interrupt handler
uint32_t addr = desc->baseLo | (desc->baseHi << 16);
//! return interrupt handler
I86_IRQ_HANDLER irq = (I86_IRQ_HANDLER)addr;
return irq;
}
//! returns cpu vender
const char* _cdecl get_cpu_vender () {
return i86_cpu_get_vender();
}
//! returns current tick count (only for demo)
int _cdecl get_tick_count () {
return i86_pit_get_tick_count();
}
//============================================================================
// INTERFACE CLASS BODIES
//============================================================================
//****************************************************************************
//**
//** END[Hal.cpp]
//**
//****************************************************************************
| 29.541063 | 84 | 0.452003 | [
"vector"
] |
b4aa41c0bd13d24ebff7cd8489b9bfd7e6cc508a | 34,900 | hpp | C++ | include/common_robotics_utilities/simple_prm_planner.hpp | hidmic/common_robotics_utilities | b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c | [
"BSD-3-Clause"
] | null | null | null | include/common_robotics_utilities/simple_prm_planner.hpp | hidmic/common_robotics_utilities | b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c | [
"BSD-3-Clause"
] | null | null | null | include/common_robotics_utilities/simple_prm_planner.hpp | hidmic/common_robotics_utilities | b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <omp.h>
#include <chrono>
#include <cstdint>
#include <functional>
#include <limits>
#include <map>
#include <stdexcept>
#include <utility>
#include <vector>
#include <common_robotics_utilities/simple_graph.hpp>
#include <common_robotics_utilities/simple_graph_search.hpp>
#include <common_robotics_utilities/simple_knearest_neighbors.hpp>
namespace common_robotics_utilities
{
namespace simple_prm_planner
{
/// Enum to select the direction of node-to-graph connection. If the "distance"
/// function is not symmetrical (i.e. an edge can have different "distance" in
/// different directions), then the direction is needed to call the distance
/// function correctly.
enum class NNDistanceDirection {ROADMAP_TO_NEW_STATE, NEW_STATE_TO_ROADMAP};
/// Attempt to add a single state as a new node to the roadmap.
/// @param state new state to add.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return the index of the newly-added node OR the index of an existing
/// duplicate node in the roadmap. You can check which happended by querying the
/// size of the roadmap before and after calling AddNodeToRoadmap.
template<typename T>
inline int64_t AddNodeToRoadmap(
const T& state, const NNDistanceDirection nn_distance_direction,
simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false)
{
// Make the node->graph or graph->node distance function as needed
std::function<double(const simple_graph::GraphNode<T>&, const T&)>
graph_distance_fn = nullptr;
if (nn_distance_direction == NNDistanceDirection::ROADMAP_TO_NEW_STATE)
{
graph_distance_fn = [&] (const simple_graph::GraphNode<T>& node,
const T& query_state)
{
return distance_fn(node.GetValueImmutable(), query_state);
};
}
else
{
graph_distance_fn = [&] (const simple_graph::GraphNode<T>& node,
const T& query_state)
{
return distance_fn(query_state, node.GetValueImmutable());
};
}
// Call KNN with the distance function
const auto nearest_neighbors =
simple_knearest_neighbors::GetKNearestNeighbors(
roadmap.GetNodesImmutable(), state, graph_distance_fn, K,
use_parallel);
// Check if we already have this state in the roadmap
// (and we don't want to add duplicates)
if (add_duplicate_states == false)
{
for (const auto& neighbor : nearest_neighbors)
{
if (neighbor.Distance() == 0.0)
{
return neighbor.Index();
}
}
}
// Add the new node AFTER KNN is performed
const int64_t new_node_index = roadmap.AddNode(state);
// Parallelize the collision-checking and distance computation
// Because we don't need any special caching here, we define the loop contents
// as a lambda and then call branch between parfor/for loops that call it.
std::vector<std::pair<double, double>> nearest_neighbors_distances(
nearest_neighbors.size());
auto collision_check_and_distance_fn = [&] (const size_t idx)
{
const auto& nearest_neighbor = nearest_neighbors.at(idx);
const int64_t nearest_neighbor_index = nearest_neighbor.Index();
const double graph_to_node_distance = nearest_neighbor.Distance();
const T& nearest_neighbor_state
= roadmap.GetNodeImmutable(nearest_neighbor_index).GetValueImmutable();
const bool graph_to_node_edge_validity
= edge_validity_check_fn(nearest_neighbor_state, state);
if (graph_to_node_edge_validity && distance_is_symmetric)
{
// Distance is symmetric and the edge is valid
nearest_neighbors_distances.at(idx)
= std::make_pair(graph_to_node_distance,
graph_to_node_distance);
}
else if (!distance_is_symmetric)
{
const bool node_to_graph_edge_validity
= edge_validity_check_fn(nearest_neighbor_state, state);
const double node_to_graph_distance
= distance_fn(state,
roadmap.GetNodeImmutable(nearest_neighbor_index)
.GetValueImmutable());
// We use -1 as a signaling value of an infeasible edge
const double real_graph_to_node_distance
= (graph_to_node_edge_validity) ? graph_to_node_distance : -1.0;
const double real_node_to_graph_distance
= (node_to_graph_edge_validity) ? node_to_graph_distance : -1.0;
// Set the distance values depending on direction
if (nn_distance_direction == NNDistanceDirection::ROADMAP_TO_NEW_STATE)
{
nearest_neighbors_distances.at(idx)
= std::make_pair(real_graph_to_node_distance,
real_node_to_graph_distance);
}
else
{
nearest_neighbors_distances.at(idx)
= std::make_pair(real_node_to_graph_distance,
real_graph_to_node_distance);
}
}
else
{
// Distance is symmetric, but the edge is not valid!
nearest_neighbors_distances.at(idx) = std::make_pair(-1.0, -1.0);
}
};
if (use_parallel)
{
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (size_t idx = 0; idx < nearest_neighbors.size(); idx++)
{
collision_check_and_distance_fn(idx);
}
}
else
{
for (size_t idx = 0; idx < nearest_neighbors.size(); idx++)
{
collision_check_and_distance_fn(idx);
}
}
// THIS MUST BE SERIAL - add edges to roadmap
for (size_t idx = 0; idx < nearest_neighbors.size(); idx++)
{
const auto& nearest_neighbor = nearest_neighbors.at(idx);
const int64_t nearest_neighbor_index = nearest_neighbor.Index();
const std::pair<double, double>& nearest_neighbor_distances
= nearest_neighbors_distances.at(idx);
if (nearest_neighbor_distances.first >= 0.0
&& nearest_neighbor_distances.second >= 0.0)
{
// Add the edges individually to allow for different "distances" in each
// direction - for example, if the "distance" is a probability of the edge
// being traversable, the probability may not be symmetric.
roadmap.AddEdgeBetweenNodes(nearest_neighbor_index, new_node_index,
nearest_neighbor_distances.first);
roadmap.AddEdgeBetweenNodes(new_node_index, nearest_neighbor_index,
nearest_neighbor_distances.second);
}
}
return new_node_index;
}
/// Attempt to grow a roadmap consisting of a graph of states.
/// @param roadmap roadmap to grow. This may be empty to start with.
/// @param sampling_fn function to sample new states.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param state_validity_check function to check if a sampled state is valid.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param termination_check_fn function to check if we have finished building
/// the roadmap. Returns true when roadmap construction is done. The provided
/// int64_t is the current size of the roadmap, since roadmap size is a common
/// termination condition.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should a new state be added to the roadmap if
/// it is a duplicate of an existing state? A new state is considered a
/// duplicate if one of the K neighboring states has distance zero from the
/// state.
/// @return statistics as a map<string, double> of useful statistics collected
/// while growing the roadmap.
template<typename T>
inline std::map<std::string, double> GrowRoadMap(
simple_graph::Graph<T>& roadmap,
const std::function<T(void)>& sampling_fn,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&)>& state_validity_check_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const std::function<bool(const int64_t)>& termination_check_fn,
const size_t K,
const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false)
{
std::map<std::string, double> statistics;
statistics["total_samples"] = 0.0;
statistics["successful_samples"] = 0.0;
statistics["duplicate_samples"] = 0.0;
statistics["failed_samples"] = 0.0;
// Update the start time
const std::chrono::time_point<std::chrono::steady_clock> start_time
= std::chrono::steady_clock::now();
while (!termination_check_fn(static_cast<int64_t>(roadmap.Size())))
{
const T random_state = sampling_fn();
statistics["total_samples"] += 1.0;
if (state_validity_check_fn(random_state))
{
const size_t pre_size = roadmap.Size();
AddNodeToRoadmap(random_state, NNDistanceDirection::ROADMAP_TO_NEW_STATE,
roadmap, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric,
add_duplicate_states);
const size_t post_size = roadmap.Size();
if (post_size > pre_size)
{
statistics["successful_samples"] += 1.0;
}
else
{
statistics["duplicate_samples"] += 1.0;
}
}
else
{
statistics["failed_samples"] += 1.0;
}
}
const std::chrono::time_point<std::chrono::steady_clock> cur_time
= std::chrono::steady_clock::now();
const std::chrono::duration<double> growing_time(cur_time - start_time);
statistics["growing_time"] = growing_time.count();
return statistics;
}
/// Update edge distances in a roadmap.
/// @param roadmap existing roadmap to update.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param use_parallel use parallel operations when possible.
template<typename T>
inline void UpdateRoadMapEdges(
simple_graph::Graph<T>& roadmap,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const std::function<double(const T&, const T&)>& distance_fn,
const bool use_parallel = true)
{
if (roadmap.CheckGraphLinkage() == false)
{
throw std::invalid_argument("Provided roadmap has invalid linkage");
}
// Because we don't need any special caching here, we define the loop contents
// as a lambda and then call branch between parfor/for loops that call it.
auto update_node_fn = [&] (const size_t current_node_index)
{
simple_graph::GraphNode<T>& current_node
= roadmap.GetNodeMutable(current_node_index);
std::vector<simple_graph::GraphEdge>& current_node_out_edges
= current_node.GetOutEdgesMutable();
for (auto& current_out_edge : current_node_out_edges)
{
const int64_t other_node_idx = current_out_edge.GetToIndex();
simple_graph::GraphNode<T>& other_node
= roadmap.GetNodeMutable(other_node_idx);
std::vector<simple_graph::GraphEdge>& other_node_in_edges
= other_node.GetInEdgesMutable();
const double updated_weight
= (edge_validity_check_fn(current_node.GetValueImmutable(),
other_node.GetValueImmutable()))
? distance_fn(current_node.GetValueImmutable(),
other_node.GetValueImmutable())
: std::numeric_limits<double>::infinity();
// Update our out edge
current_out_edge.SetWeight(updated_weight);
// Update the other node's in edges
for (auto& other_in_edge : other_node_in_edges)
{
if (other_in_edge.GetFromIndex()
== static_cast<int64_t>(current_node_index))
{
other_in_edge.SetWeight(updated_weight);
}
}
}
};
if (use_parallel)
{
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (size_t current_node_index = 0; current_node_index < roadmap.Size();
current_node_index++)
{
update_node_fn(current_node_index);
}
}
else
{
for (size_t current_node_index = 0; current_node_index < roadmap.Size();
current_node_index++)
{
update_node_fn(current_node_index);
}
}
}
/// Extracts the solution path from the roadmap.
/// @param roadmap roadmap used to find solution path.
/// @param astar_index_solution A* planned path, in terms of node indices in the
/// provided roadmap.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container> ExtractSolution(
const simple_graph::Graph<T>& roadmap,
const simple_astar_search::AstarIndexResult& astar_index_solution)
{
Container solution_path;
solution_path.reserve(astar_index_solution.Path().size());
for (const int64_t solution_path_index : astar_index_solution.Path())
{
const T& solution_path_state
= roadmap.GetNodeImmutable(solution_path_index).GetValueImmutable();
solution_path.push_back(solution_path_state);
}
solution_path.shrink_to_fit();
return simple_astar_search::AstarResult<T, Container>(
solution_path, astar_index_solution.PathCost());
}
/// Find the best path from one of a set of starting states to a single goal.
/// This implementation uses a much more expensive search method optimized for
/// large numbers of starting states. If the number of starting states is low,
/// you may be better off with multiple calls to
/// QueryPathAndAddNodesSingleStartSingleGoal instead.
/// Starting and goal states are added to the roadmap.
/// @param starts multiple start states.
/// @param goal goal state.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return path + length of the best path from a single start to the goal.
/// If no solution exists, path is empty and length is infinity.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container>
QueryPathAndAddNodesMultiStartSingleGoal(
const Container& starts, const T& goal,
simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false)
{
if (starts.empty())
{
throw std::runtime_error("starts is empty");
}
// Add the multiple start nodes to the roadmap
std::vector<int64_t> start_node_indices(starts.size());
for (size_t start_idx = 0; start_idx < starts.size(); start_idx++)
{
const T& start = starts.at(start_idx);
start_node_indices.at(start_idx)
= AddNodeToRoadmap<T>(start, NNDistanceDirection::NEW_STATE_TO_ROADMAP,
roadmap, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric,
add_duplicate_states);
}
// Add the goal node to the roadmap
const int64_t goal_node_index
= AddNodeToRoadmap<T>(goal, NNDistanceDirection::ROADMAP_TO_NEW_STATE,
roadmap, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric,
add_duplicate_states);
// Call Dijkstra's
const auto dijkstras_solution
= simple_graph_search::PerformDijkstrasAlgorithm<T>(roadmap,
goal_node_index);
// Identify the lowest-distance starting state
double best_start_node_distance = std::numeric_limits<double>::infinity();
int64_t best_start_node_index = -1;
for (const int64_t start_node_index : start_node_indices)
{
const double start_node_distance
= dijkstras_solution.GetNodeDistance(start_node_index);
if (start_node_distance < best_start_node_distance)
{
best_start_node_distance = start_node_distance;
best_start_node_index = start_node_index;
}
}
const int64_t start_node_index = best_start_node_index;
const double start_node_distance = best_start_node_distance;
// Extract solution path
if (std::isinf(start_node_distance))
{
return simple_astar_search::AstarResult<T, Container>();
}
else
{
std::vector<int64_t> solution_path_indices;
solution_path_indices.push_back(start_node_index);
int64_t previous_index
= dijkstras_solution.GetPreviousIndex(start_node_index);
while (previous_index >= 0)
{
const int64_t current_index = previous_index;
solution_path_indices.push_back(current_index);
if (current_index == goal_node_index)
{
break;
}
else
{
previous_index = dijkstras_solution.GetPreviousIndex(current_index);
}
}
return ExtractSolution<T, Container>(
roadmap,
simple_astar_search::AstarIndexResult(
solution_path_indices, start_node_distance));
}
}
/// Find the best path from one of a set of starting states to a single goal.
/// @param starts multiple start states.
/// @param goal goal state.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return path + length of the best path from a single start to the goal.
/// If no solution exists, path is empty and length is infinity.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container>
QueryPathMultiStartSingleGoal(
const Container& starts, const T& goal,
const simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false)
{
auto working_copy = roadmap;
return QueryPathAndAddNodesMultiStartSingleGoal<T, Container>(
starts, goal, working_copy, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric, add_duplicate_states);
}
/// Find the best path from start state to goal state.
/// Start and goal states are added to the roadmap.
/// @param start start state.
/// @param goal goal state.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return path + length of the best path from start to goal.
/// If no solution exists, path is empty and length is infinity.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container>
QueryPathAndAddNodesSingleStartSingleGoal(
const T& start, const T& goal, simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false,
const bool limit_astar_pqueue_duplicates=true)
{
// Add the start node to the roadmap
const int64_t start_node_index
= AddNodeToRoadmap<T>(start, NNDistanceDirection::NEW_STATE_TO_ROADMAP,
roadmap, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric,
add_duplicate_states);
// Add the goal node to the roadmap
const int64_t goal_node_index
= AddNodeToRoadmap<T>(goal, NNDistanceDirection::ROADMAP_TO_NEW_STATE,
roadmap, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric,
add_duplicate_states);
// Call graph A*
const auto astar_result = simple_graph_search::PerformAstarSearch<T>(
roadmap, start_node_index, goal_node_index, distance_fn,
limit_astar_pqueue_duplicates);
// Convert the solution path from A* provided as indices into real states
return ExtractSolution<T, Container>(roadmap, astar_result);
}
/// Find the best path from start state to goal state.
/// @param start start state.
/// @param goal goal state.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return path + length of the best path from start to goal.
/// If no solution exists, path is empty and length is infinity.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container>
QueryPathSingleStartSingleGoal(
const T& start, const T& goal, const simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false,
const bool limit_astar_pqueue_duplicates=true)
{
auto working_copy = roadmap;
return QueryPathAndAddNodesSingleStartSingleGoal<T, Container>(
start, goal, working_copy, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric, add_duplicate_states,
limit_astar_pqueue_duplicates);
}
/// Find the best path from start state to goal state in a lazy manner, i.e.
/// the edge validity and distances of the graph are not trusted and instead the
/// provided @param edge_validity_check_fn and @param distance_fn are used. This
/// is used in "lazy-PRM" where collision checking is deferred from roadmap
/// construction to query time. Note that this can be much more expensive than
/// normal PRM queries, so it sohuld only be used when the roadmap is frequently
/// changing or vastly larger than the region needed for most queries.
/// Start and goal states are added to the roadmap.
/// @param start start state.
/// @param goal goal state.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return path + length of the best path from start to goal.
/// If no solution exists, path is empty and length is infinity.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container>
LazyQueryPathAndAddNodesSingleStartSingleGoal(
const T& start, const T& goal, simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false,
const bool limit_astar_pqueue_duplicates=true)
{
// Add the start node to the roadmap
const int64_t start_node_index
= AddNodeToRoadmap<T>(start, NNDistanceDirection::NEW_STATE_TO_ROADMAP,
roadmap, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric,
add_duplicate_states);
// Add the goal node to the roadmap
const int64_t goal_node_index
= AddNodeToRoadmap<T>(goal, NNDistanceDirection::ROADMAP_TO_NEW_STATE,
roadmap, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric,
add_duplicate_states);
// Call graph A*
const auto astar_result = simple_graph_search::PerformLazyAstarSearch<T>(
roadmap, start_node_index, goal_node_index, edge_validity_check_fn,
distance_fn, distance_fn, limit_astar_pqueue_duplicates);
// Convert the solution path from A* provided as indices into real states
return ExtractSolution<T, Container>(roadmap, astar_result);
}
/// Find the best path from start state to goal state in a lazy manner, i.e.
/// the edge validity and distances of the graph are not trusted and instead the
/// provided @param edge_validity_check_fn and @param distance_fn are used. This
/// is used in "lazy-PRM" where collision checking is deferred from roadmap
/// construction to query time. Note that this can be much more expensive than
/// normal PRM queries, so it sohuld only be used when the roadmap is frequently
/// changing or vastly larger than the region needed for most queries.
/// @param start start state.
/// @param goal goal state.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return path + length of the best path from start to goal.
/// If no solution exists, path is empty and length is infinity.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container>
LazyQueryPathSingleStartSingleGoal(
const T& start, const T& goal, const simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false,
const bool limit_astar_pqueue_duplicates=true)
{
auto working_copy = roadmap;
return LazyQueryPathAndAddNodesSingleStartSingleGoal<T, Container>(
start, goal, working_copy, distance_fn, edge_validity_check_fn, K,
use_parallel, distance_is_symmetric, add_duplicate_states,
limit_astar_pqueue_duplicates);
}
/// Find the best path from one of a set of starting states to one of a set of
/// goal states. This is the most expensive search possible, and should only be
/// used if there are a large number of starting states. If @param
/// distance_is_symmetric is true, you can swap starts and goals to ensure that
/// |starts| > |goals|.
/// @param starts multiple start states.
/// @param goals multiple goal states.
/// @param roadmap existing roadmap.
/// @param distance_fn distance function for state-to-state distance. If
/// use_parallel is true, this must be thread-safe.
/// @param edge_validity_check_fn edge validity checking function. If
/// use_parallel is true, this must be thread-safe.
/// @param K number of K neighboring states in the roadmap to attempt to connect
/// the new state to.
/// @param use_parallel use parallel operations when possible.
/// @param distance_is_symmetric is the distance symmetric
/// (i.e. distance_fn(a, b) == distance_fn(b, a))? Asymmetric distance functions
/// are more expensive to work with and should be avoided when possible.
/// @param add_duplicate_states should @param state be added to the roadmap if
/// it is a duplicate of an existing state? @param state is considered a
/// duplicate if one of the K neighboring states has distance zero from @param
/// state.
/// @return path + length of the best path from a single start to a single
/// goal. If no solution exists, path is empty and length is infinity.
template<typename T, typename Container=std::vector<T>>
inline simple_astar_search::AstarResult<T, Container>
QueryPathMultiStartMultiGoal(
const Container& starts,
const Container& goals,
const simple_graph::Graph<T>& roadmap,
const std::function<double(const T&, const T&)>& distance_fn,
const std::function<bool(const T&, const T&)>& edge_validity_check_fn,
const size_t K, const bool use_parallel = true,
const bool distance_is_symmetric = true,
const bool add_duplicate_states = false)
{
std::vector<simple_astar_search::AstarResult<T, Container>>
possible_solutions(goals.size());
for (size_t goal_idx = 0; goal_idx < goals.size(); goal_idx++)
{
possible_solutions.at(goal_idx)
= QueryPathMultiStartSingleGoal<T, Container>(
starts, goals.at(goal_idx), roadmap, distance_fn,
edge_validity_check_fn, K, use_parallel, distance_is_symmetric,
add_duplicate_states);
}
double best_solution_distance = std::numeric_limits<double>::infinity();
int64_t best_solution_index = -1;
for (size_t goal_idx = 0; goal_idx < goals.size(); goal_idx++)
{
const double solution_distance = possible_solutions.at(goal_idx).PathCost();
if (solution_distance < best_solution_distance)
{
best_solution_distance = solution_distance;
best_solution_index = goal_idx;
}
}
if ((best_solution_index >= 0)
&& (best_solution_distance < std::numeric_limits<double>::infinity()))
{
return possible_solutions.at(best_solution_index);
}
else
{
return simple_astar_search::AstarResult<T, Container>();
}
}
} // namespace simple_prm_planner
} // namespace common_robotics_utilities
| 45.501956 | 80 | 0.717994 | [
"vector"
] |
b4ad0c06c8b028b586520dc7b52b2f0c645c23e4 | 12,504 | cpp | C++ | src/Magnum/Test/BufferGLTest.cpp | costashatz/magnum | 8f87ca92334b326a54d27789f370fd8556d557de | [
"MIT"
] | null | null | null | src/Magnum/Test/BufferGLTest.cpp | costashatz/magnum | 8f87ca92334b326a54d27789f370fd8556d557de | [
"MIT"
] | null | null | null | src/Magnum/Test/BufferGLTest.cpp | costashatz/magnum | 8f87ca92334b326a54d27789f370fd8556d557de | [
"MIT"
] | null | null | null | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <array>
#include <vector>
#include <Corrade/Containers/Array.h>
#include <Corrade/TestSuite/Compare/Container.h>
#include "Magnum/Buffer.h"
#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Magnum/OpenGLTester.h"
namespace Magnum { namespace Test {
struct BufferGLTest: OpenGLTester {
explicit BufferGLTest();
void construct();
void constructCopy();
void constructMove();
void wrap();
void label();
#ifndef MAGNUM_TARGET_GLES2
void bindBase();
void bindRange();
#endif
void data();
void map();
void mapRange();
void mapRangeExplicitFlush();
#ifndef MAGNUM_TARGET_GLES2
void copy();
#endif
void invalidate();
};
BufferGLTest::BufferGLTest() {
addTests({&BufferGLTest::construct,
&BufferGLTest::constructCopy,
&BufferGLTest::constructMove,
&BufferGLTest::wrap,
&BufferGLTest::label,
#ifndef MAGNUM_TARGET_GLES2
&BufferGLTest::bindBase,
&BufferGLTest::bindRange,
#endif
&BufferGLTest::data,
&BufferGLTest::map,
&BufferGLTest::mapRange,
&BufferGLTest::mapRangeExplicitFlush,
#ifndef MAGNUM_TARGET_GLES2
&BufferGLTest::copy,
#endif
&BufferGLTest::invalidate});
}
void BufferGLTest::construct() {
{
Buffer buffer;
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(buffer.id() > 0);
CORRADE_COMPARE(buffer.targetHint(), Buffer::TargetHint::Array);
CORRADE_COMPARE(buffer.size(), 0);
}
MAGNUM_VERIFY_NO_ERROR();
}
void BufferGLTest::constructCopy() {
CORRADE_VERIFY(!(std::is_constructible<Buffer, const Buffer&>{}));
CORRADE_VERIFY(!(std::is_assignable<Buffer, const Buffer&>{}));
}
void BufferGLTest::constructMove() {
Buffer a;
const Int id = a.id();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(id > 0);
Buffer b(std::move(a));
CORRADE_COMPARE(a.id(), 0);
CORRADE_COMPARE(b.id(), id);
Buffer c;
const Int cId = c.id();
c = std::move(b);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(cId > 0);
CORRADE_COMPARE(b.id(), cId);
CORRADE_COMPARE(c.id(), id);
}
void BufferGLTest::wrap() {
GLuint id;
glGenBuffers(1, &id);
/* Releasing won't delete anything */
{
auto buffer = Buffer::wrap(id, ObjectFlag::DeleteOnDestruction);
CORRADE_COMPARE(buffer.release(), id);
}
/* ...so we can wrap it again */
Buffer::wrap(id);
glDeleteBuffers(1, &id);
}
void BufferGLTest::label() {
/* No-Op version is tested in AbstractObjectGLTest */
if(!Context::current().isExtensionSupported<Extensions::GL::KHR::debug>() &&
!Context::current().isExtensionSupported<Extensions::GL::EXT::debug_label>())
CORRADE_SKIP("Required extension is not available");
Buffer buffer;
CORRADE_COMPARE(buffer.label(), "");
MAGNUM_VERIFY_NO_ERROR();
buffer.setLabel("MyBuffer");
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(buffer.label(), "MyBuffer");
}
#ifndef MAGNUM_TARGET_GLES2
void BufferGLTest::bindBase() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::uniform_buffer_object>())
CORRADE_SKIP(Extensions::GL::ARB::uniform_buffer_object::string() + std::string{" is not supported."});
#endif
Buffer buffer;
buffer.bind(Buffer::Target::Uniform, 15);
MAGNUM_VERIFY_NO_ERROR();
Buffer::unbind(Buffer::Target::Uniform, 15);
MAGNUM_VERIFY_NO_ERROR();
Buffer::bind(Buffer::Target::Uniform, 7, {&buffer, nullptr, &buffer});
MAGNUM_VERIFY_NO_ERROR();
Buffer::unbind(Buffer::Target::Uniform, 7, 3);
MAGNUM_VERIFY_NO_ERROR();
}
void BufferGLTest::bindRange() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::uniform_buffer_object>())
CORRADE_SKIP(Extensions::GL::ARB::uniform_buffer_object::string() + std::string{" is not supported."});
#endif
/* Check that we have correct offset alignment */
CORRADE_INTERNAL_ASSERT(256 % Buffer::uniformOffsetAlignment() == 0);
Buffer buffer;
buffer.setData({nullptr, 1024}, BufferUsage::StaticDraw)
.bind(Buffer::Target::Uniform, 15, 256, 13);
MAGNUM_VERIFY_NO_ERROR();
/** @todo C++14: get rid of std::make_tuple */
Buffer::bind(Buffer::Target::Uniform, 7, {
std::make_tuple(&buffer, 256, 13), {},
std::make_tuple(&buffer, 768, 64)});
MAGNUM_VERIFY_NO_ERROR();
}
#endif
void BufferGLTest::data() {
Buffer buffer;
/* Plain array */
constexpr Int data[] = {2, 7, 5, 13, 25};
buffer.setData({data, 5}, BufferUsage::StaticDraw);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(buffer.size(), 5*4);
/* STL vector */
std::vector<Int> data2{2, 7, 5, 13, 25};
buffer.setData(data2, BufferUsage::StaticDraw);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(buffer.size(), 5*4);
/* STL array */
std::array<Int, 5> data3{{2, 7, 5, 13, 25}};
buffer.setData(data3, BufferUsage::StaticDraw);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(buffer.size(), 5*4);
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
auto contents = buffer.data();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE_AS(Containers::arrayCast<Int>(contents),
Containers::arrayView(data),
TestSuite::Compare::Container);
#endif
/* Plain array */
constexpr Int subData[] = {125, 3, 15};
buffer.setSubData(4, {subData, 3});
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(buffer.size(), 5*4);
/* STL vector */
std::vector<Int> subData2{125, 3, 15};
buffer.setSubData(4, subData2);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(buffer.size(), 5*4);
/* STL array */
std::array<Int, 3> subData3{{125, 3, 15}};
buffer.setSubData(4, subData3);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(buffer.size(), 5*4);
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
auto subContents = buffer.subData(4, 3*4);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE_AS(Containers::arrayCast<Int>(subContents),
Containers::arrayView(subData),
TestSuite::Compare::Container);
#endif
}
void BufferGLTest::map() {
#ifdef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::OES::mapbuffer>())
CORRADE_SKIP(Extensions::GL::OES::mapbuffer::string() + std::string(" is not supported"));
#endif
Buffer buffer;
constexpr char data[] = {2, 7, 5, 13, 25};
buffer.setData(data, BufferUsage::StaticDraw);
char* contents = buffer.map(
#ifndef MAGNUM_TARGET_GLES
Buffer::MapAccess::ReadWrite
#else
Buffer::MapAccess::WriteOnly
#endif
);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(contents);
#ifndef MAGNUM_TARGET_GLES2
CORRADE_COMPARE(contents[2], 5);
#endif
contents[3] = 107;
CORRADE_VERIFY(buffer.unmap());
MAGNUM_VERIFY_NO_ERROR();
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
Containers::Array<char> changedContents = buffer.data();
CORRADE_COMPARE(changedContents.size(), 5);
CORRADE_COMPARE(changedContents[3], 107);
#endif
}
void BufferGLTest::mapRange() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::map_buffer_range>())
CORRADE_SKIP(Extensions::GL::ARB::map_buffer_range::string() + std::string(" is not supported"));
#elif defined(MAGNUM_TARGET_GLES2)
if(!Context::current().isExtensionSupported<Extensions::GL::EXT::map_buffer_range>())
CORRADE_SKIP(Extensions::GL::EXT::map_buffer_range::string() + std::string(" is not supported"));
#endif
constexpr char data[] = {2, 7, 5, 13, 25};
Buffer buffer;
buffer.setData(data, BufferUsage::StaticDraw);
Containers::ArrayView<char> contents = buffer.map(1, 4, Buffer::MapFlag::Read|Buffer::MapFlag::Write);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(contents);
CORRADE_COMPARE(contents.size(), 4);
CORRADE_COMPARE(contents[2], 13);
contents[3] = 107;
CORRADE_VERIFY(buffer.unmap());
MAGNUM_VERIFY_NO_ERROR();
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
Containers::Array<char> changedContents = buffer.data();
CORRADE_COMPARE(changedContents.size(), 5);
CORRADE_COMPARE(changedContents[4], 107);
#endif
}
void BufferGLTest::mapRangeExplicitFlush() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::map_buffer_range>())
CORRADE_SKIP(Extensions::GL::ARB::map_buffer_range::string() + std::string(" is not supported"));
#elif defined(MAGNUM_TARGET_GLES2)
if(!Context::current().isExtensionSupported<Extensions::GL::EXT::map_buffer_range>())
CORRADE_SKIP(Extensions::GL::EXT::map_buffer_range::string() + std::string(" is not supported"));
#endif
constexpr char data[] = {2, 7, 5, 13, 25};
Buffer buffer;
buffer.setData(data, BufferUsage::StaticDraw);
/* Map, set byte, don't flush and unmap */
Containers::ArrayView<char> contents = buffer.map(1, 4, Buffer::MapFlag::Write|Buffer::MapFlag::FlushExplicit);
CORRADE_VERIFY(contents);
contents[2] = 99;
CORRADE_VERIFY(buffer.unmap());
MAGNUM_VERIFY_NO_ERROR();
/* Unflushed range _might_ not be changed, thus nothing to test */
/* Map, set byte, flush and unmap */
contents = buffer.map(1, 4, Buffer::MapFlag::Write|Buffer::MapFlag::FlushExplicit);
CORRADE_VERIFY(contents);
contents[3] = 107;
buffer.flushMappedRange(3, 1);
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(buffer.unmap());
MAGNUM_VERIFY_NO_ERROR();
/* Flushed range should be changed */
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
Containers::Array<char> changedContents = buffer.data();
CORRADE_COMPARE(changedContents.size(), 5);
CORRADE_COMPARE(changedContents[4], 107);
#endif
}
#ifndef MAGNUM_TARGET_GLES2
void BufferGLTest::copy() {
Buffer buffer1;
constexpr char data[] = {2, 7, 5, 13, 25};
buffer1.setData(data, BufferUsage::StaticCopy);
Buffer buffer2;
buffer2.setData({nullptr, 5}, BufferUsage::StaticRead);
Buffer::copy(buffer1, buffer2, 1, 2, 3);
MAGNUM_VERIFY_NO_ERROR();
/** @todo How to verify the contents in ES? */
#ifndef MAGNUM_TARGET_GLES
const Containers::Array<char> subContents = buffer2.subData(2, 3);
CORRADE_COMPARE_AS(subContents, Containers::arrayView(data).slice(1, 4),
TestSuite::Compare::Container);
#endif
}
#endif
void BufferGLTest::invalidate() {
Buffer buffer;
constexpr char data[] = {2, 7, 5, 13, 25};
buffer.setData(data, BufferUsage::StaticDraw);
/* Just test that no errors are emitted */
buffer.invalidateSubData(3, 2);
MAGNUM_VERIFY_NO_ERROR();
buffer.invalidateData();
MAGNUM_VERIFY_NO_ERROR();
}
}}
CORRADE_TEST_MAIN(Magnum::Test::BufferGLTest)
| 30.423358 | 115 | 0.666587 | [
"vector"
] |
b4adf7b5b79af2c2dae322200470bdc2e8a44483 | 14,576 | cpp | C++ | main.cpp | c1728p9/client-with-metrics | 50bdb3c1ed091b6317016e954868a06683cfc48a | [
"Apache-2.0"
] | null | null | null | main.cpp | c1728p9/client-with-metrics | 50bdb3c1ed091b6317016e954868a06683cfc48a | [
"Apache-2.0"
] | null | null | null | main.cpp | c1728p9/client-with-metrics | 50bdb3c1ed091b6317016e954868a06683cfc48a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* 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 "simpleclient.h"
#include <string>
#include <sstream>
#include <vector>
#include "mbed-trace/mbed_trace.h"
#include "mbed_stats.h"
#include "security.h"
#include "mbed.h"
#include "rtos.h"
#define ETHERNET 1
#define WIFI 2
#define MESH_LOWPAN_ND 3
#define MESH_THREAD 4
#define STRINGIFY(s) #s
#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI
#include "ESP8266Interface.h"
ESP8266Interface esp(MBED_CONF_APP_WIFI_TX, MBED_CONF_APP_WIFI_RX);
#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET
#include "EthernetInterface.h"
EthernetInterface eth;
#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_LOWPAN_ND
#define MESH
#include "NanostackInterface.h"
LoWPANNDInterface mesh;
#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_THREAD
#define MESH
#include "NanostackInterface.h"
ThreadInterface mesh;
#endif
#ifndef MESH
// This is address to mbed Device Connector
#define MBED_SERVER_ADDRESS "coap://api.connector.mbed.com:5684"
#else
// This is address to mbed Device Connector
#define MBED_SERVER_ADDRESS "coaps://[2607:f0d0:2601:52::20]:5684"
#endif
Serial output(USBTX, USBRX);
// These are example resource values for the Device Object
struct MbedClientDevice device = {
"Manufacturer_String", // Manufacturer
"Type_String", // Type
"ModelNumber_String", // ModelNumber
"SerialNumber_String" // SerialNumber
};
// Instantiate the class which implements LWM2M Client API (from simpleclient.h)
MbedClient mbed_client(device);
// In case of K64F board , there is button resource available
// to change resource value and unregister
#ifdef TARGET_K64F
// Set up Hardware interrupt button.
InterruptIn obs_button(SW2);
InterruptIn unreg_button(SW3);
#else
//In non K64F boards , set up a timer to simulate updating resource,
// there is no functionality to unregister.
Ticker timer;
#endif
// LED Output
DigitalOut led1(LED1);
/*
* The Led contains one property (pattern) and a function (blink).
* When the function blink is executed, the pattern is read, and the LED
* will blink based on the pattern.
*/
class LedResource {
public:
LedResource() {
// create ObjectID with metadata tag of '3201', which is 'digital output'
led_object = M2MInterfaceFactory::create_object("3201");
M2MObjectInstance* led_inst = led_object->create_object_instance();
// 5853 = Multi-state output
M2MResource* pattern_res = led_inst->create_dynamic_resource("5853", "Pattern",
M2MResourceInstance::STRING, false);
// read and write
pattern_res->set_operation(M2MBase::GET_PUT_ALLOWED);
// set initial pattern (toggle every 200ms. 7 toggles in total)
pattern_res->set_value((const uint8_t*)"500:500:500:500:500:500:500", 27);
// there's not really an execute LWM2M ID that matches... hmm...
M2MResource* led_res = led_inst->create_dynamic_resource("5850", "Blink",
M2MResourceInstance::OPAQUE, false);
// we allow executing a function here...
led_res->set_operation(M2MBase::POST_ALLOWED);
// when a POST comes in, we want to execute the led_execute_callback
led_res->set_execute_function(execute_callback(this, &LedResource::blink));
}
M2MObject* get_object() {
return led_object;
}
void blink(void *) {
// read the value of 'Pattern'
M2MObjectInstance* inst = led_object->object_instance();
M2MResource* res = inst->resource("5853");
// values in mbed Client are all buffers, and we need a vector of int's
uint8_t* buffIn = NULL;
uint32_t sizeIn;
res->get_value(buffIn, sizeIn);
// turn the buffer into a string, and initialize a vector<int> on the heap
std::string s((char*)buffIn, sizeIn);
std::vector<uint32_t>* v = new std::vector<uint32_t>;
output.printf("led_execute_callback pattern=%s\r\n", s.c_str());
// our pattern is something like 500:200:500, so parse that
std::size_t found = s.find_first_of(":");
while (found!=std::string::npos) {
v->push_back(atoi((const char*)s.substr(0,found).c_str()));
s = s.substr(found+1);
found=s.find_first_of(":");
if(found == std::string::npos) {
v->push_back(atoi((const char*)s.c_str()));
}
}
// do_blink is called with the vector, and starting at -1
do_blink(v, 0);
}
private:
M2MObject* led_object;
void do_blink(std::vector<uint32_t>* pattern, uint16_t position) {
// blink the LED
led1 = !led1;
// up the position, if we reached the end of the vector
if (position >= pattern->size()) {
// free memory, and exit this function
delete pattern;
return;
}
// how long do we need to wait before the next blink?
uint32_t delay_ms = pattern->at(position);
// Invoke same function after `delay_ms` (upping position)
Thread::wait(delay_ms);
do_blink(pattern, ++position);
}
};
/*
* The button contains one property (click count).
* When `handle_button_click` is executed, the counter updates.
*/
class ButtonResource {
public:
ButtonResource(): counter(0) {
// create ObjectID with metadata tag of '3200', which is 'digital input'
btn_object = M2MInterfaceFactory::create_object("3200");
M2MObjectInstance* btn_inst = btn_object->create_object_instance();
// create resource with ID '5501', which is digital input counter
M2MResource* btn_res = btn_inst->create_dynamic_resource("5501", "Button",
M2MResourceInstance::INTEGER, true /* observable */);
// we can read this value
btn_res->set_operation(M2MBase::GET_ALLOWED);
// set initial value (all values in mbed Client are buffers)
// to be able to read this data easily in the Connector console, we'll use a string
btn_res->set_value((uint8_t*)"0", 1);
}
~ButtonResource() {
}
M2MObject* get_object() {
return btn_object;
}
/*
* When you press the button, we read the current value of the click counter
* from mbed Device Connector, then up the value with one.
*/
void handle_button_click() {
M2MObjectInstance* inst = btn_object->object_instance();
M2MResource* res = inst->resource("5501");
// Uhoh, a memory leak on button presses
malloc(1024);
// up counter
counter++;
#ifdef TARGET_K64F
printf("handle_button_click, new value of counter is %d\r\n", counter);
#else
printf("simulate button_click, new value of counter is %d\r\n", counter);
#endif
// serialize the value of counter as a string, and tell connector
char buffer[20];
int size = sprintf(buffer,"%d",counter);
res->set_value((uint8_t*)buffer, size);
}
private:
M2MObject* btn_object;
uint16_t counter;
};
/*
* The device resource contains device specific metrics
*/
class DeviceResource {
public:
DeviceResource() {
// create ObjectID with metadata tag of '3', which is 'device'
device_object = M2MInterfaceFactory::create_object("3");
M2MObjectInstance* instance = device_object->create_object_instance();
// create resource with ID '11000' which is custom
M2MResource* res_max_heap = instance->create_dynamic_resource("11000", "MaxHeap",
M2MResourceInstance::INTEGER, true /* observable */);
// we can read this value
res_max_heap->set_operation(M2MBase::GET_POST_ALLOWED);
res_max_heap->set_execute_function(execute_callback(this, &DeviceResource::update_heap_max));
// Set the initial value
update_heap_max(NULL);
M2MResource* res_cur_heap = instance->create_dynamic_resource("11001", "CurrentHeap",
M2MResourceInstance::INTEGER, true /* observable */);
// we can read this value
res_cur_heap->set_operation(M2MBase::GET_POST_ALLOWED);
res_cur_heap->set_execute_function(execute_callback(this, &DeviceResource::update_heap_cur));
// Set the initial value
update_heap_cur(NULL);
}
~DeviceResource() {
}
M2MObject* get_object() {
return device_object;
}
void update_heap_max(void*) {
M2MObjectInstance* inst = device_object->object_instance();
M2MResource* res = inst->resource("11000");
// serialize the value of counter as a string, and tell connector
char buffer[20];
mbed_stats_heap_t stats;
mbed_stats_heap_get(&stats);
int size = sprintf(buffer,"%lu",stats.max_size);
res->set_value((uint8_t*)buffer, size);
}
void update_heap_cur(void*) {
M2MObjectInstance* inst = device_object->object_instance();
M2MResource* res = inst->resource("11001");
// serialize the value of counter as a string, and tell connector
char buffer[20];
mbed_stats_heap_t stats;
mbed_stats_heap_get(&stats);
int size = sprintf(buffer,"%lu",stats.current_size);
res->set_value((uint8_t*)buffer, size);
}
private:
M2MObject* device_object;
};
// Network interaction must be performed outside of interrupt context
Semaphore updates(0);
volatile bool registered = false;
volatile bool clicked = false;
osThreadId mainThread;
void unregister() {
registered = false;
updates.release();
}
void button_clicked() {
clicked = true;
updates.release();
}
// debug printf function
void trace_printer(const char* str) {
printf("%s\r\n", str);
}
// Status indication
Ticker status_ticker;
DigitalOut status_led(LED1);
void blinky() { status_led = !status_led; }
// Entry point to the program
int main() {
#ifndef MBEDTLS_ENTROPY_HARDWARE_ALT
#ifdef MBEDTLS_TEST_NULL_ENTROPY
#warning "mbedTLS security feature is disabled. Connection will not be secure !! Implement proper hardware entropy for your selected hardware."
#else
#error "This hardware does not have entropy, endpoint will not register to Connector.\
You need to enable NULL ENTROPY for your application, but if this configuration change is made then no security is offered by mbed TLS.\
Add MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES and MBEDTLS_TEST_NULL_ENTROPY in mbed_app.json macros to register your endpoint."
#endif
#endif
status_ticker.attach_us(blinky, 250000);
// Keep track of the main thread
mainThread = osThreadGetId();
// Sets the console baud-rate
output.baud(115200);
output.printf("Starting mbed Client example...\r\n");
mbed_trace_init();
mbed_trace_print_function_set(trace_printer);
NetworkInterface *network_interface = 0;
int connect_success = -1;
#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI
output.printf("\n\rUsing WiFi \r\n");
output.printf("\n\rConnecting to WiFi..\r\n");
connect_success = esp.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD);
network_interface = &esp;
#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET
output.printf("Using Ethernet\r\n");
connect_success = eth.connect();
network_interface = ð
#endif
#ifdef MESH
output.printf("Using Mesh\r\n");
output.printf("\n\rConnecting to Mesh..\r\n");
connect_success = mesh.connect();
network_interface = &mesh;
#endif
if(connect_success == 0) {
output.printf("\n\rConnected to Network successfully\r\n");
} else {
output.printf("\n\rConnection to Network Failed %d! Exiting application....\r\n", connect_success);
return 0;
}
const char *ip_addr = network_interface->get_ip_address();
if (ip_addr) {
output.printf("IP address %s\r\n", ip_addr);
} else {
output.printf("No IP address\r\n");
}
// we create our button and LED resources
ButtonResource button_resource;
LedResource led_resource;
DeviceResource device_resource;
#ifdef TARGET_K64F
// On press of SW3 button on K64F board, example application
// will call unregister API towards mbed Device Connector
//unreg_button.fall(&mbed_client,&MbedClient::test_unregister);
unreg_button.fall(&unregister);
// Observation Button (SW2) press will send update of endpoint resource values to connector
obs_button.fall(&button_clicked);
#else
// Send update of endpoint resource values to connector every 15 seconds periodically
timer.attach(&button_clicked, 15.0);
#endif
// Create endpoint interface to manage register and unregister
mbed_client.create_interface(MBED_SERVER_ADDRESS, network_interface);
// Create Objects of varying types, see simpleclient.h for more details on implementation.
M2MSecurity* register_object = mbed_client.create_register_object(); // server object specifying connector info
M2MDevice* device_object = mbed_client.create_device_object(); // device resources object
// Create list of Objects to register
M2MObjectList object_list;
// Add objects to list
object_list.push_back(device_object);
object_list.push_back(button_resource.get_object());
object_list.push_back(led_resource.get_object());
object_list.push_back(device_resource.get_object());
// Set endpoint registration object
mbed_client.set_register_object(register_object);
// Register with mbed Device Connector
mbed_client.test_register(register_object, object_list);
registered = true;
while (true) {
updates.wait(25000);
if(registered) {
if(!clicked) {
mbed_client.test_update_register();
}
}else {
break;
}
if(clicked) {
clicked = false;
button_resource.handle_button_click();
}
}
mbed_client.test_unregister();
status_ticker.detach();
}
| 33.052154 | 143 | 0.681463 | [
"mesh",
"object",
"vector"
] |
b4ae40da22309b1d25a470227174d5a61092e0a3 | 3,054 | cpp | C++ | GeometryDash.cpp | Cos8o/gdbox | c6462ff0d76556bd6a8f9ae527fee80def7652fa | [
"Unlicense"
] | 1 | 2020-10-09T07:09:59.000Z | 2020-10-09T07:09:59.000Z | GeometryDash.cpp | Cos8o/gdbox | c6462ff0d76556bd6a8f9ae527fee80def7652fa | [
"Unlicense"
] | null | null | null | GeometryDash.cpp | Cos8o/gdbox | c6462ff0d76556bd6a8f9ae527fee80def7652fa | [
"Unlicense"
] | null | null | null | #include <Windows.h>
#include "GeometryDash.hpp"
#include <mutex>
#include <vector>
#include <functional>
using namespace GeometryDash;
typedef void* (__fastcall* create_T)(
void* protocol,
const char* title,
const char* button1,
const char* button2,
float width,
unsigned long smth,
unsigned long smth2,
std::string text);
typedef void(__thiscall* show_T)(void*);
//Globals
DWORD updateAddress = 0x0;
DWORD menuAddress = 0x0;
static create_T flalertlayer_create = nullptr;
static show_T flalertlayer_show = nullptr;
static std::mutex mtx;
static std::vector<std::function<void()>> funcs;
//Helper
void msgboxHelper(
std::string const& title,
std::string const& text,
std::string const& button1 = "Ok",
std::string const& button2 = "")
{
auto box = flalertlayer_create(
nullptr,
title.c_str(),
button1.size() ? button1.c_str() : "Ok",
button2.size() ? button2.c_str() : nullptr,
300.0,
0,
0,
text);
__asm
{
add esp, 44
}
flalertlayer_show(box);
}
//Engine
__declspec(naked) void __fastcall updateTrampoline(void* pthis, void* edx, float f)
{
__asm
{
push ebp
mov ebp, esp
push esi
push edi
mov edi, [updateAddress]
add edi, 5
jmp edi
}
}
void __fastcall updateCallback(void* pthis, void* edx, float f)
{
updateTrampoline(pthis, edx, f);
mtx.lock();
auto calls = std::move(funcs);
mtx.unlock();
for (auto const& f : calls) f();
}
//GeometryDash
bool GeometryDash::init(void* addr)
{
DWORD base = reinterpret_cast<DWORD>(GetModuleHandleA(NULL));
auto cocos = GetModuleHandleA("libcocos2d.dll");
flalertlayer_create = reinterpret_cast<create_T>(base + 0x227E0);
flalertlayer_show = reinterpret_cast<show_T>(base + 0x23560);
menuAddress = base + 0x1907B0;
updateAddress = reinterpret_cast<DWORD>(
GetProcAddress(cocos, "?update@CCScheduler@cocos2d@@UAEXM@Z"));
//Hook1
DWORD offset = reinterpret_cast<DWORD>(&updateCallback) - updateAddress - 5;
DWORD tmp;
VirtualProtect(
reinterpret_cast<LPVOID>(updateAddress),
0x1000,
PAGE_EXECUTE_READWRITE,
&tmp);
*reinterpret_cast<byte*>(updateAddress) = 0xE9;
memcpy(reinterpret_cast<void*>(updateAddress + 1), &offset, sizeof(DWORD));
//Hook2
offset = reinterpret_cast<DWORD>(addr) - menuAddress - 5;
VirtualProtect(
reinterpret_cast<LPVOID>(menuAddress),
0x1000,
PAGE_EXECUTE_READWRITE,
&tmp);
*reinterpret_cast<byte*>(menuAddress) = 0xE9;
memcpy(reinterpret_cast<void*>(menuAddress + 1), &offset, sizeof(DWORD));
return true;
}
bool GeometryDash::showMessageBox(
std::string const& title,
std::string const& text,
std::string const& button1,
std::string const& button2)
{
std::lock_guard<std::mutex> lock(mtx);
if (flalertlayer_create && flalertlayer_show)
{
funcs.push_back([title, text, button1, button2]()
{
msgboxHelper(title, text, button1, button2);
});
return true;
}
return false;
}
__declspec(naked) void GeometryDash::showMenu(void* pthis)
{
__asm
{
push ebp
mov ebp, esp
and esp, 0xFFFFFFF8
mov eax, [menuAddress]
add eax, 6
jmp eax
}
} | 18.736196 | 83 | 0.708251 | [
"vector"
] |
b4b8bcfea06f7e99acb102896dfe9171ab9d326e | 684 | cpp | C++ | Leetcode/The kth Factor of n/The kth Factor of n.cpp | rahil-1407/Data-Structure-and-Algorithms | ea3eb9849aeb2716ef5812a0b5621a28120b1880 | [
"MIT"
] | 51 | 2021-01-14T04:05:55.000Z | 2022-01-25T11:25:37.000Z | Leetcode/The kth Factor of n/The kth Factor of n.cpp | rahil-1407/Data-Structure-and-Algorithms | ea3eb9849aeb2716ef5812a0b5621a28120b1880 | [
"MIT"
] | 638 | 2020-12-27T18:49:53.000Z | 2021-11-21T05:22:52.000Z | Leetcode/The kth Factor of n/The kth Factor of n.cpp | rahil-1407/Data-Structure-and-Algorithms | ea3eb9849aeb2716ef5812a0b5621a28120b1880 | [
"MIT"
] | 124 | 2021-01-30T06:40:20.000Z | 2021-11-21T15:14:40.000Z | class Solution {
public:
int kthFactor(int n, int k) {
// array: 1 2 3 4 6 8 12 24
// index: 0 1 2 3 4 5 6 7
// suppose k:6, we should return 8
// we check until sqrt(24) = 4 so array will be 1 2 3 4 (array.size()==4)
// we find the answer(8) by dividing n by array[array.size() - k]==array[2]==3
// note that if k>array.size() than we should return -1
vector<int>array;
int i;
for(i=1;i*i<=n;i++){
if(n%i==0){
if(i*i!=n){array.push_back(i);}
if(--k==0){return i;}
}
}
return (k>array.size())? -1 : n/(array[array.size()-k]);
}
}; | 34.2 | 86 | 0.472222 | [
"vector"
] |
b4b8cd5e957210e6efbdd4822924d5956049fbf3 | 59,401 | hpp | C++ | src/3rd_party/mio/mio.hpp | hieuhoang/marian-dev | f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2 | [
"MIT"
] | 829 | 2017-06-05T12:14:34.000Z | 2022-03-29T17:24:03.000Z | src/3rd_party/mio/mio.hpp | hieuhoang/marian-dev | f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2 | [
"MIT"
] | 732 | 2017-07-21T15:32:27.000Z | 2022-03-22T10:26:09.000Z | src/3rd_party/mio/mio.hpp | hieuhoang/marian-dev | f2347a827fcfd7eebaaa552e2b3c2461f8ea45c2 | [
"MIT"
] | 192 | 2017-06-27T10:17:26.000Z | 2022-03-28T05:33:11.000Z | /* Copyright 2017 https://github.com/mandreyel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MIO_MMAP_HEADER
#define MIO_MMAP_HEADER
// #include "mio/page.hpp"
/* Copyright 2017 https://github.com/mandreyel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MIO_PAGE_HEADER
#define MIO_PAGE_HEADER
#ifdef _WIN32
# include <windows.h>
#else
# include <unistd.h>
#endif
namespace mio {
/**
* This is used by `basic_mmap` to determine whether to create a read-only or
* a read-write memory mapping.
*/
enum class access_mode
{
read,
write
};
/**
* Determines the operating system's page allocation granularity.
*
* On the first call to this function, it invokes the operating system specific syscall
* to determine the page size, caches the value, and returns it. Any subsequent call to
* this function serves the cached value, so no further syscalls are made.
*/
inline size_t page_size()
{
static const size_t page_size = []
{
#ifdef _WIN32
SYSTEM_INFO SystemInfo;
GetSystemInfo(&SystemInfo);
return SystemInfo.dwAllocationGranularity;
#else
return sysconf(_SC_PAGE_SIZE);
#endif
}();
return page_size;
}
/**
* Alligns `offset` to the operating's system page size such that it subtracts the
* difference until the nearest page boundary before `offset`, or does nothing if
* `offset` is already page aligned.
*/
inline size_t make_offset_page_aligned(size_t offset) noexcept
{
const size_t page_size_ = page_size();
// Use integer division to round down to the nearest page alignment.
return offset / page_size_ * page_size_;
}
} // namespace mio
#endif // MIO_PAGE_HEADER
#include <iterator>
#include <string>
#include <system_error>
#include <cstdint>
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif // WIN32_LEAN_AND_MEAN
# include <windows.h>
#else // ifdef _WIN32
# define INVALID_HANDLE_VALUE -1
#endif // ifdef _WIN32
namespace mio {
// This value may be provided as the `length` parameter to the constructor or
// `map`, in which case a memory mapping of the entire file is created.
enum { map_entire_file = 0 };
#ifdef _WIN32
using file_handle_type = HANDLE;
#else
using file_handle_type = int;
#endif
// This value represents an invalid file handle type. This can be used to
// determine whether `basic_mmap::file_handle` is valid, for example.
const static file_handle_type invalid_handle = INVALID_HANDLE_VALUE;
template<access_mode AccessMode, typename ByteT>
struct basic_mmap
{
using value_type = ByteT;
using size_type = size_t;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
using difference_type = std::ptrdiff_t;
using iterator = pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using iterator_category = std::random_access_iterator_tag;
using handle_type = file_handle_type;
static_assert(sizeof(ByteT) == sizeof(char), "ByteT must be the same size as char.");
private:
// Points to the first requested byte, and not to the actual start of the mapping.
pointer data_ = nullptr;
// Length--in bytes--requested by user (which may not be the length of the
// full mapping) and the length of the full mapping.
size_type length_ = 0;
size_type mapped_length_ = 0;
// Letting user map a file using both an existing file handle and a path
// introcudes some complexity (see `is_handle_internal_`).
// On POSIX, we only need a file handle to create a mapping, while on
// Windows systems the file handle is necessary to retrieve a file mapping
// handle, but any subsequent operations on the mapped region must be done
// through the latter.
handle_type file_handle_ = INVALID_HANDLE_VALUE;
#ifdef _WIN32
handle_type file_mapping_handle_ = INVALID_HANDLE_VALUE;
#endif
// Letting user map a file using both an existing file handle and a path
// introcudes some complexity in that we must not close the file handle if
// user provided it, but we must close it if we obtained it using the
// provided path. For this reason, this flag is used to determine when to
// close `file_handle_`.
bool is_handle_internal_;
public:
/**
* The default constructed mmap object is in a non-mapped state, that is,
* any operation that attempts to access nonexistent underlying data will
* result in undefined behaviour/segmentation faults.
*/
basic_mmap() = default;
#ifdef __cpp_exceptions
/**
* The same as invoking the `map` function, except any error that may occur
* while establishing the mapping is wrapped in a `std::system_error` and is
* thrown.
*/
template<typename String>
basic_mmap(const String& path, const size_type offset = 0, const size_type length = map_entire_file)
{
std::error_code error;
map(path, offset, length, error);
if(error) { throw std::system_error(error); }
}
/**
* The same as invoking the `map` function, except any error that may occur
* while establishing the mapping is wrapped in a `std::system_error` and is
* thrown.
*/
basic_mmap(const handle_type handle, const size_type offset = 0, const size_type length = map_entire_file)
{
std::error_code error;
map(handle, offset, length, error);
if(error) { throw std::system_error(error); }
}
#endif // __cpp_exceptions
/**
* `basic_mmap` has single-ownership semantics, so transferring ownership
* may only be accomplished by moving the object.
*/
basic_mmap(const basic_mmap&) = delete;
basic_mmap(basic_mmap&&);
basic_mmap& operator=(const basic_mmap&) = delete;
basic_mmap& operator=(basic_mmap&&);
/**
* If this is a read-write mapping, the destructor invokes sync. Regardless
* of the access mode, unmap is invoked as a final step.
*/
~basic_mmap();
/**
* On UNIX systems 'file_handle' and 'mapping_handle' are the same. On Windows,
* however, a mapped region of a file gets its own handle, which is returned by
* 'mapping_handle'.
*/
handle_type file_handle() const noexcept { return file_handle_; }
handle_type mapping_handle() const noexcept;
/** Returns whether a valid memory mapping has been created. */
bool is_open() const noexcept { return file_handle_ != invalid_handle; }
/**
* Returns true if no mapping was established, that is, conceptually the
* same as though the length that was mapped was 0. This function is
* provided so that this class has Container semantics.
*/
bool empty() const noexcept { return length() == 0; }
/** Returns true if a mapping was established. */
bool is_mapped() const noexcept;
/**
* `size` and `length` both return the logical length, i.e. the number of bytes
* user requested to be mapped, while `mapped_length` returns the actual number of
* bytes that were mapped which is a multiple of the underlying operating system's
* page allocation granularity.
*/
size_type size() const noexcept { return length(); }
size_type length() const noexcept { return length_; }
size_type mapped_length() const noexcept { return mapped_length_; }
/** Returns the offset relative to the start of the mapping. */
size_type mapping_offset() const noexcept
{
return mapped_length_ - length_;
}
/**
* Returns a pointer to the first requested byte, or `nullptr` if no memory mapping
* exists.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> pointer data() noexcept { return data_; }
const_pointer data() const noexcept { return data_; }
/**
* Returns an iterator to the first requested byte, if a valid memory mapping
* exists, otherwise this function call is undefined behaviour.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> iterator begin() noexcept { return data(); }
const_iterator begin() const noexcept { return data(); }
const_iterator cbegin() const noexcept { return data(); }
/**
* Returns an iterator one past the last requested byte, if a valid memory mapping
* exists, otherwise this function call is undefined behaviour.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> iterator end() noexcept { return data() + length(); }
const_iterator end() const noexcept { return data() + length(); }
const_iterator cend() const noexcept { return data() + length(); }
/**
* Returns a reverse iterator to the last memory mapped byte, if a valid
* memory mapping exists, otherwise this function call is undefined
* behaviour.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const noexcept
{ return const_reverse_iterator(end()); }
const_reverse_iterator crbegin() const noexcept
{ return const_reverse_iterator(end()); }
/**
* Returns a reverse iterator past the first mapped byte, if a valid memory
* mapping exists, otherwise this function call is undefined behaviour.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
const_reverse_iterator rend() const noexcept
{ return const_reverse_iterator(begin()); }
const_reverse_iterator crend() const noexcept
{ return const_reverse_iterator(begin()); }
/**
* Returns a reference to the `i`th byte from the first requested byte (as returned
* by `data`). If this is invoked when no valid memory mapping has been created
* prior to this call, undefined behaviour ensues.
*/
reference operator[](const size_type i) noexcept { return data_[i]; }
const_reference operator[](const size_type i) const noexcept { return data_[i]; }
/**
* Establishes a memory mapping with AccessMode. If the mapping is unsuccesful, the
* reason is reported via `error` and the object remains in a state as if this
* function hadn't been called.
*
* `path`, which must be a path to an existing file, is used to retrieve a file
* handle (which is closed when the object destructs or `unmap` is called), which is
* then used to memory map the requested region. Upon failure, `error` is set to
* indicate the reason and the object remains in an unmapped state.
*
* `offset` is the number of bytes, relative to the start of the file, where the
* mapping should begin. When specifying it, there is no need to worry about
* providing a value that is aligned with the operating system's page allocation
* granularity. This is adjusted by the implementation such that the first requested
* byte (as returned by `data` or `begin`), so long as `offset` is valid, will be at
* `offset` from the start of the file.
*
* `length` is the number of bytes to map. It may be `map_entire_file`, in which
* case a mapping of the entire file is created.
*/
template<typename String>
void map(const String& path, const size_type offset,
const size_type length, std::error_code& error);
/**
* Establishes a memory mapping with AccessMode. If the mapping is unsuccesful, the
* reason is reported via `error` and the object remains in a state as if this
* function hadn't been called.
*
* `path`, which must be a path to an existing file, is used to retrieve a file
* handle (which is closed when the object destructs or `unmap` is called), which is
* then used to memory map the requested region. Upon failure, `error` is set to
* indicate the reason and the object remains in an unmapped state.
*
* The entire file is mapped.
*/
template<typename String>
void map(const String& path, std::error_code& error)
{
map(path, 0, map_entire_file, error);
}
/**
* Establishes a memory mapping with AccessMode. If the mapping is
* unsuccesful, the reason is reported via `error` and the object remains in
* a state as if this function hadn't been called.
*
* `handle`, which must be a valid file handle, which is used to memory map the
* requested region. Upon failure, `error` is set to indicate the reason and the
* object remains in an unmapped state.
*
* `offset` is the number of bytes, relative to the start of the file, where the
* mapping should begin. When specifying it, there is no need to worry about
* providing a value that is aligned with the operating system's page allocation
* granularity. This is adjusted by the implementation such that the first requested
* byte (as returned by `data` or `begin`), so long as `offset` is valid, will be at
* `offset` from the start of the file.
*
* `length` is the number of bytes to map. It may be `map_entire_file`, in which
* case a mapping of the entire file is created.
*/
void map(const handle_type handle, const size_type offset,
const size_type length, std::error_code& error);
/**
* Establishes a memory mapping with AccessMode. If the mapping is
* unsuccesful, the reason is reported via `error` and the object remains in
* a state as if this function hadn't been called.
*
* `handle`, which must be a valid file handle, which is used to memory map the
* requested region. Upon failure, `error` is set to indicate the reason and the
* object remains in an unmapped state.
*
* The entire file is mapped.
*/
void map(const handle_type handle, std::error_code& error)
{
map(handle, 0, map_entire_file, error);
}
/**
* If a valid memory mapping has been created prior to this call, this call
* instructs the kernel to unmap the memory region and disassociate this object
* from the file.
*
* The file handle associated with the file that is mapped is only closed if the
* mapping was created using a file path. If, on the other hand, an existing
* file handle was used to create the mapping, the file handle is not closed.
*/
void unmap();
void swap(basic_mmap& other);
/** Flushes the memory mapped page to disk. Errors are reported via `error`. */
template<access_mode A = AccessMode>
typename std::enable_if<A == access_mode::write, void>::type
sync(std::error_code& error);
/**
* All operators compare the address of the first byte and size of the two mapped
* regions.
*/
private:
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> pointer get_mapping_start() noexcept
{
return !data() ? nullptr : data() - mapping_offset();
}
const_pointer get_mapping_start() const noexcept
{
return !data() ? nullptr : data() - mapping_offset();
}
/**
* The destructor syncs changes to disk if `AccessMode` is `write`, but not
* if it's `read`, but since the destructor cannot be templated, we need to
* do SFINAE in a dedicated function, where one syncs and the other is a noop.
*/
template<access_mode A = AccessMode>
typename std::enable_if<A == access_mode::write, void>::type
conditional_sync();
template<access_mode A = AccessMode>
typename std::enable_if<A == access_mode::read, void>::type conditional_sync();
};
template<access_mode AccessMode, typename ByteT>
bool operator==(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b);
template<access_mode AccessMode, typename ByteT>
bool operator!=(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b);
template<access_mode AccessMode, typename ByteT>
bool operator<(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b);
template<access_mode AccessMode, typename ByteT>
bool operator<=(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b);
template<access_mode AccessMode, typename ByteT>
bool operator>(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b);
template<access_mode AccessMode, typename ByteT>
bool operator>=(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b);
/**
* This is the basis for all read-only mmap objects and should be preferred over
* directly using `basic_mmap`.
*/
template<typename ByteT>
using basic_mmap_source = basic_mmap<access_mode::read, ByteT>;
/**
* This is the basis for all read-write mmap objects and should be preferred over
* directly using `basic_mmap`.
*/
template<typename ByteT>
using basic_mmap_sink = basic_mmap<access_mode::write, ByteT>;
/**
* These aliases cover the most common use cases, both representing a raw byte stream
* (either with a char or an unsigned char/uint8_t).
*/
using mmap_source = basic_mmap_source<char>;
using ummap_source = basic_mmap_source<unsigned char>;
using mmap_sink = basic_mmap_sink<char>;
using ummap_sink = basic_mmap_sink<unsigned char>;
/**
* Convenience factory method that constructs a mapping for any `basic_mmap` or
* `basic_mmap` type.
*/
template<
typename MMap,
typename MappingToken
> MMap make_mmap(const MappingToken& token,
int64_t offset, int64_t length, std::error_code& error)
{
MMap mmap;
mmap.map(token, offset, length, error);
return mmap;
}
/**
* Convenience factory method.
*
* MappingToken may be a String (`std::string`, `std::string_view`, `const char*`,
* `std::filesystem::path`, `std::vector<char>`, or similar), or a
* `mmap_source::handle_type`.
*/
template<typename MappingToken>
mmap_source make_mmap_source(const MappingToken& token, mmap_source::size_type offset,
mmap_source::size_type length, std::error_code& error)
{
return make_mmap<mmap_source>(token, offset, length, error);
}
template<typename MappingToken>
mmap_source make_mmap_source(const MappingToken& token, std::error_code& error)
{
return make_mmap_source(token, 0, map_entire_file, error);
}
/**
* Convenience factory method.
*
* MappingToken may be a String (`std::string`, `std::string_view`, `const char*`,
* `std::filesystem::path`, `std::vector<char>`, or similar), or a
* `mmap_sink::handle_type`.
*/
template<typename MappingToken>
mmap_sink make_mmap_sink(const MappingToken& token, mmap_sink::size_type offset,
mmap_sink::size_type length, std::error_code& error)
{
return make_mmap<mmap_sink>(token, offset, length, error);
}
template<typename MappingToken>
mmap_sink make_mmap_sink(const MappingToken& token, std::error_code& error)
{
return make_mmap_sink(token, 0, map_entire_file, error);
}
} // namespace mio
// #include "detail/mmap.ipp"
/* Copyright 2017 https://github.com/mandreyel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MIO_BASIC_MMAP_IMPL
#define MIO_BASIC_MMAP_IMPL
// #include "mio/mmap.hpp"
// #include "mio/page.hpp"
// #include "mio/detail/string_util.hpp"
/* Copyright 2017 https://github.com/mandreyel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MIO_STRING_UTIL_HEADER
#define MIO_STRING_UTIL_HEADER
#include <type_traits>
namespace mio {
namespace detail {
template<
typename S,
typename C = typename std::decay<S>::type,
typename = decltype(std::declval<C>().data()),
typename = typename std::enable_if<
std::is_same<typename C::value_type, char>::value
#ifdef _WIN32
|| std::is_same<typename C::value_type, wchar_t>::value
#endif
>::type
> struct char_type_helper {
using type = typename C::value_type;
};
template<class T>
struct char_type {
using type = typename char_type_helper<T>::type;
};
// TODO: can we avoid this brute force approach?
template<>
struct char_type<char*> {
using type = char;
};
template<>
struct char_type<const char*> {
using type = char;
};
template<size_t N>
struct char_type<char[N]> {
using type = char;
};
template<size_t N>
struct char_type<const char[N]> {
using type = char;
};
#ifdef _WIN32
template<>
struct char_type<wchar_t*> {
using type = wchar_t;
};
template<>
struct char_type<const wchar_t*> {
using type = wchar_t;
};
template<size_t N>
struct char_type<wchar_t[N]> {
using type = wchar_t;
};
template<size_t N>
struct char_type<const wchar_t[N]> {
using type = wchar_t;
};
#endif // _WIN32
template<typename CharT, typename S>
struct is_c_str_helper
{
static constexpr bool value = std::is_same<
CharT*,
// TODO: I'm so sorry for this... Can this be made cleaner?
typename std::add_pointer<
typename std::remove_cv<
typename std::remove_pointer<
typename std::decay<
S
>::type
>::type
>::type
>::type
>::value;
};
template<typename S>
struct is_c_str
{
static constexpr bool value = is_c_str_helper<char, S>::value;
};
#ifdef _WIN32
template<typename S>
struct is_c_wstr
{
static constexpr bool value = is_c_str_helper<wchar_t, S>::value;
};
#endif // _WIN32
template<typename S>
struct is_c_str_or_c_wstr
{
static constexpr bool value = is_c_str<S>::value
#ifdef _WIN32
|| is_c_wstr<S>::value
#endif
;
};
template<
typename String,
typename = decltype(std::declval<String>().data()),
typename = typename std::enable_if<!is_c_str_or_c_wstr<String>::value>::type
> const typename char_type<String>::type* c_str(const String& path)
{
return path.data();
}
template<
typename String,
typename = decltype(std::declval<String>().empty()),
typename = typename std::enable_if<!is_c_str_or_c_wstr<String>::value>::type
> bool empty(const String& path)
{
return path.empty();
}
template<
typename String,
typename = typename std::enable_if<is_c_str_or_c_wstr<String>::value>::type
> const typename char_type<String>::type* c_str(String path)
{
return path;
}
template<
typename String,
typename = typename std::enable_if<is_c_str_or_c_wstr<String>::value>::type
> bool empty(String path)
{
return !path || (*path == 0);
}
} // namespace detail
} // namespace mio
#endif // MIO_STRING_UTIL_HEADER
#include <algorithm>
#ifndef _WIN32
# include <unistd.h>
# include <fcntl.h>
# include <sys/mman.h>
# include <sys/stat.h>
#endif
namespace mio {
namespace detail {
#ifdef _WIN32
namespace win {
/** Returns the 4 upper bytes of an 8-byte integer. */
inline DWORD int64_high(int64_t n) noexcept
{
return n >> 32;
}
/** Returns the 4 lower bytes of an 8-byte integer. */
inline DWORD int64_low(int64_t n) noexcept
{
return n & 0xffffffff;
}
template<
typename String,
typename = typename std::enable_if<
std::is_same<typename char_type<String>::type, char>::value
>::type
> file_handle_type open_file_helper(const String& path, const access_mode mode)
{
return ::CreateFileA(c_str(path),
mode == access_mode::read ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
}
template<typename String>
typename std::enable_if<
std::is_same<typename char_type<String>::type, wchar_t>::value,
file_handle_type
>::type open_file_helper(const String& path, const access_mode mode)
{
return ::CreateFileW(c_str(path),
mode == access_mode::read ? GENERIC_READ : GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
}
} // win
#endif // _WIN32
/**
* Returns the last platform specific system error (errno on POSIX and
* GetLastError on Win) as a `std::error_code`.
*/
inline std::error_code last_error() noexcept
{
std::error_code error;
#ifdef _WIN32
error.assign(GetLastError(), std::system_category());
#else
error.assign(errno, std::system_category());
#endif
return error;
}
template<typename String>
file_handle_type open_file(const String& path, const access_mode mode,
std::error_code& error)
{
error.clear();
if(detail::empty(path))
{
error = std::make_error_code(std::errc::invalid_argument);
return invalid_handle;
}
#ifdef _WIN32
const auto handle = win::open_file_helper(path, mode);
#else // POSIX
const auto handle = ::open(c_str(path),
mode == access_mode::read ? O_RDONLY : O_RDWR);
#endif
if(handle == invalid_handle)
{
error = detail::last_error();
}
return handle;
}
inline size_t query_file_size(file_handle_type handle, std::error_code& error)
{
error.clear();
#ifdef _WIN32
LARGE_INTEGER file_size;
if(::GetFileSizeEx(handle, &file_size) == 0)
{
error = detail::last_error();
return 0;
}
return static_cast<int64_t>(file_size.QuadPart);
#else // POSIX
struct stat sbuf;
if(::fstat(handle, &sbuf) == -1)
{
error = detail::last_error();
return 0;
}
return sbuf.st_size;
#endif
}
struct mmap_context
{
char* data;
int64_t length;
int64_t mapped_length;
#ifdef _WIN32
file_handle_type file_mapping_handle;
#endif
};
inline mmap_context memory_map(const file_handle_type file_handle, const int64_t offset,
const int64_t length, const access_mode mode, std::error_code& error)
{
const int64_t aligned_offset = make_offset_page_aligned(offset);
const int64_t length_to_map = offset - aligned_offset + length;
#ifdef _WIN32
const int64_t max_file_size = offset + length;
const auto file_mapping_handle = ::CreateFileMapping(
file_handle,
0,
mode == access_mode::read ? PAGE_READONLY : PAGE_READWRITE,
win::int64_high(max_file_size),
win::int64_low(max_file_size),
0);
if(file_mapping_handle == invalid_handle)
{
error = detail::last_error();
return {};
}
char* mapping_start = static_cast<char*>(::MapViewOfFile(
file_mapping_handle,
mode == access_mode::read ? FILE_MAP_READ : FILE_MAP_WRITE,
win::int64_high(aligned_offset),
win::int64_low(aligned_offset),
length_to_map));
if(mapping_start == nullptr)
{
error = detail::last_error();
return {};
}
#else // POSIX
char* mapping_start = static_cast<char*>(::mmap(
0, // Don't give hint as to where to map.
length_to_map,
mode == access_mode::read ? PROT_READ : PROT_WRITE,
MAP_SHARED,
file_handle,
aligned_offset));
if(mapping_start == MAP_FAILED)
{
error = detail::last_error();
return {};
}
#endif
mmap_context ctx;
ctx.data = mapping_start + offset - aligned_offset;
ctx.length = length;
ctx.mapped_length = length_to_map;
#ifdef _WIN32
ctx.file_mapping_handle = file_mapping_handle;
#endif
return ctx;
}
} // namespace detail
// -- basic_mmap --
template<access_mode AccessMode, typename ByteT>
basic_mmap<AccessMode, ByteT>::~basic_mmap()
{
conditional_sync();
unmap();
}
template<access_mode AccessMode, typename ByteT>
basic_mmap<AccessMode, ByteT>::basic_mmap(basic_mmap&& other)
: data_(std::move(other.data_))
, length_(std::move(other.length_))
, mapped_length_(std::move(other.mapped_length_))
, file_handle_(std::move(other.file_handle_))
#ifdef _WIN32
, file_mapping_handle_(std::move(other.file_mapping_handle_))
#endif
, is_handle_internal_(std::move(other.is_handle_internal_))
{
other.data_ = nullptr;
other.length_ = other.mapped_length_ = 0;
other.file_handle_ = invalid_handle;
#ifdef _WIN32
other.file_mapping_handle_ = invalid_handle;
#endif
}
template<access_mode AccessMode, typename ByteT>
basic_mmap<AccessMode, ByteT>&
basic_mmap<AccessMode, ByteT>::operator=(basic_mmap&& other)
{
if(this != &other)
{
// First the existing mapping needs to be removed.
unmap();
data_ = std::move(other.data_);
length_ = std::move(other.length_);
mapped_length_ = std::move(other.mapped_length_);
file_handle_ = std::move(other.file_handle_);
#ifdef _WIN32
file_mapping_handle_ = std::move(other.file_mapping_handle_);
#endif
is_handle_internal_ = std::move(other.is_handle_internal_);
// The moved from basic_mmap's fields need to be reset, because
// otherwise other's destructor will unmap the same mapping that was
// just moved into this.
other.data_ = nullptr;
other.length_ = other.mapped_length_ = 0;
other.file_handle_ = invalid_handle;
#ifdef _WIN32
other.file_mapping_handle_ = invalid_handle;
#endif
other.is_handle_internal_ = false;
}
return *this;
}
template<access_mode AccessMode, typename ByteT>
typename basic_mmap<AccessMode, ByteT>::handle_type
basic_mmap<AccessMode, ByteT>::mapping_handle() const noexcept
{
#ifdef _WIN32
return file_mapping_handle_;
#else
return file_handle_;
#endif
}
template<access_mode AccessMode, typename ByteT>
template<typename String>
void basic_mmap<AccessMode, ByteT>::map(const String& path, const size_type offset,
const size_type length, std::error_code& error)
{
error.clear();
if(detail::empty(path))
{
error = std::make_error_code(std::errc::invalid_argument);
return;
}
const auto handle = detail::open_file(path, AccessMode, error);
if(error)
{
return;
}
map(handle, offset, length, error);
// This MUST be after the call to map, as that sets this to true.
if(!error)
{
is_handle_internal_ = true;
}
}
template<access_mode AccessMode, typename ByteT>
void basic_mmap<AccessMode, ByteT>::map(const handle_type handle,
const size_type offset, const size_type length, std::error_code& error)
{
error.clear();
if(handle == invalid_handle)
{
error = std::make_error_code(std::errc::bad_file_descriptor);
return;
}
const auto file_size = detail::query_file_size(handle, error);
if(error)
{
return;
}
if(offset + length > file_size)
{
error = std::make_error_code(std::errc::invalid_argument);
return;
}
const auto ctx = detail::memory_map(handle, offset,
length == map_entire_file ? (file_size - offset) : length,
AccessMode, error);
if(!error)
{
// We must unmap the previous mapping that may have existed prior to this call.
// Note that this must only be invoked after a new mapping has been created in
// order to provide the strong guarantee that, should the new mapping fail, the
// `map` function leaves this instance in a state as though the function had
// never been invoked.
unmap();
file_handle_ = handle;
is_handle_internal_ = false;
data_ = reinterpret_cast<pointer>(ctx.data);
length_ = ctx.length;
mapped_length_ = ctx.mapped_length;
#ifdef _WIN32
file_mapping_handle_ = ctx.file_mapping_handle;
#endif
}
}
template<access_mode AccessMode, typename ByteT>
template<access_mode A>
typename std::enable_if<A == access_mode::write, void>::type
basic_mmap<AccessMode, ByteT>::sync(std::error_code& error)
{
error.clear();
if(!is_open())
{
error = std::make_error_code(std::errc::bad_file_descriptor);
return;
}
if(data())
{
#ifdef _WIN32
if(::FlushViewOfFile(get_mapping_start(), mapped_length_) == 0
|| ::FlushFileBuffers(file_handle_) == 0)
#else // POSIX
if(::msync(get_mapping_start(), mapped_length_, MS_SYNC) != 0)
#endif
{
error = detail::last_error();
return;
}
}
#ifdef _WIN32
if(::FlushFileBuffers(file_handle_) == 0)
{
error = detail::last_error();
}
#endif
}
template<access_mode AccessMode, typename ByteT>
void basic_mmap<AccessMode, ByteT>::unmap()
{
if(!is_open()) { return; }
// TODO do we care about errors here?
#ifdef _WIN32
if(is_mapped())
{
::UnmapViewOfFile(get_mapping_start());
::CloseHandle(file_mapping_handle_);
}
#else // POSIX
if(data_) { ::munmap(const_cast<pointer>(get_mapping_start()), mapped_length_); }
#endif
// If `file_handle_` was obtained by our opening it (when map is called with
// a path, rather than an existing file handle), we need to close it,
// otherwise it must not be closed as it may still be used outside this
// instance.
if(is_handle_internal_)
{
#ifdef _WIN32
::CloseHandle(file_handle_);
#else // POSIX
::close(file_handle_);
#endif
}
// Reset fields to their default values.
data_ = nullptr;
length_ = mapped_length_ = 0;
file_handle_ = invalid_handle;
#ifdef _WIN32
file_mapping_handle_ = invalid_handle;
#endif
}
template<access_mode AccessMode, typename ByteT>
bool basic_mmap<AccessMode, ByteT>::is_mapped() const noexcept
{
#ifdef _WIN32
return file_mapping_handle_ != invalid_handle;
#else // POSIX
return is_open();
#endif
}
template<access_mode AccessMode, typename ByteT>
void basic_mmap<AccessMode, ByteT>::swap(basic_mmap& other)
{
if(this != &other)
{
using std::swap;
swap(data_, other.data_);
swap(file_handle_, other.file_handle_);
#ifdef _WIN32
swap(file_mapping_handle_, other.file_mapping_handle_);
#endif
swap(length_, other.length_);
swap(mapped_length_, other.mapped_length_);
swap(is_handle_internal_, other.is_handle_internal_);
}
}
template<access_mode AccessMode, typename ByteT>
template<access_mode A>
typename std::enable_if<A == access_mode::write, void>::type
basic_mmap<AccessMode, ByteT>::conditional_sync()
{
// This is invoked from the destructor, so not much we can do about
// failures here.
std::error_code ec;
sync(ec);
}
template<access_mode AccessMode, typename ByteT>
template<access_mode A>
typename std::enable_if<A == access_mode::read, void>::type
basic_mmap<AccessMode, ByteT>::conditional_sync()
{
// noop
}
template<access_mode AccessMode, typename ByteT>
bool operator==(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b)
{
return a.data() == b.data()
&& a.size() == b.size();
}
template<access_mode AccessMode, typename ByteT>
bool operator!=(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b)
{
return !(a == b);
}
template<access_mode AccessMode, typename ByteT>
bool operator<(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b)
{
if(a.data() == b.data()) { return a.size() < b.size(); }
return a.data() < b.data();
}
template<access_mode AccessMode, typename ByteT>
bool operator<=(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b)
{
return !(a > b);
}
template<access_mode AccessMode, typename ByteT>
bool operator>(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b)
{
if(a.data() == b.data()) { return a.size() > b.size(); }
return a.data() > b.data();
}
template<access_mode AccessMode, typename ByteT>
bool operator>=(const basic_mmap<AccessMode, ByteT>& a,
const basic_mmap<AccessMode, ByteT>& b)
{
return !(a < b);
}
} // namespace mio
#endif // MIO_BASIC_MMAP_IMPL
#endif // MIO_MMAP_HEADER
/* Copyright 2017 https://github.com/mandreyel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MIO_PAGE_HEADER
#define MIO_PAGE_HEADER
#ifdef _WIN32
# include <windows.h>
#else
# include <unistd.h>
#endif
namespace mio {
/**
* This is used by `basic_mmap` to determine whether to create a read-only or
* a read-write memory mapping.
*/
enum class access_mode
{
read,
write
};
/**
* Determines the operating system's page allocation granularity.
*
* On the first call to this function, it invokes the operating system specific syscall
* to determine the page size, caches the value, and returns it. Any subsequent call to
* this function serves the cached value, so no further syscalls are made.
*/
inline size_t page_size()
{
static const size_t page_size = []
{
#ifdef _WIN32
SYSTEM_INFO SystemInfo;
GetSystemInfo(&SystemInfo);
return SystemInfo.dwAllocationGranularity;
#else
return sysconf(_SC_PAGE_SIZE);
#endif
}();
return page_size;
}
/**
* Alligns `offset` to the operating's system page size such that it subtracts the
* difference until the nearest page boundary before `offset`, or does nothing if
* `offset` is already page aligned.
*/
inline size_t make_offset_page_aligned(size_t offset) noexcept
{
const size_t page_size_ = page_size();
// Use integer division to round down to the nearest page alignment.
return offset / page_size_ * page_size_;
}
} // namespace mio
#endif // MIO_PAGE_HEADER
/* Copyright 2017 https://github.com/mandreyel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MIO_SHARED_MMAP_HEADER
#define MIO_SHARED_MMAP_HEADER
// #include "mio/mmap.hpp"
#include <system_error> // std::error_code
#include <memory> // std::shared_ptr
namespace mio {
/**
* Exposes (nearly) the same interface as `basic_mmap`, but endowes it with
* `std::shared_ptr` semantics.
*
* This is not the default behaviour of `basic_mmap` to avoid allocating on the heap if
* shared semantics are not required.
*/
template<
access_mode AccessMode,
typename ByteT
> class basic_shared_mmap
{
using impl_type = basic_mmap<AccessMode, ByteT>;
std::shared_ptr<impl_type> pimpl_;
public:
using value_type = typename impl_type::value_type;
using size_type = typename impl_type::size_type;
using reference = typename impl_type::reference;
using const_reference = typename impl_type::const_reference;
using pointer = typename impl_type::pointer;
using const_pointer = typename impl_type::const_pointer;
using difference_type = typename impl_type::difference_type;
using iterator = typename impl_type::iterator;
using const_iterator = typename impl_type::const_iterator;
using reverse_iterator = typename impl_type::reverse_iterator;
using const_reverse_iterator = typename impl_type::const_reverse_iterator;
using iterator_category = typename impl_type::iterator_category;
using handle_type = typename impl_type::handle_type;
using mmap_type = impl_type;
basic_shared_mmap() = default;
basic_shared_mmap(const basic_shared_mmap&) = default;
basic_shared_mmap& operator=(const basic_shared_mmap&) = default;
basic_shared_mmap(basic_shared_mmap&&) = default;
basic_shared_mmap& operator=(basic_shared_mmap&&) = default;
/** Takes ownership of an existing mmap object. */
basic_shared_mmap(mmap_type&& mmap)
: pimpl_(std::make_shared<mmap_type>(std::move(mmap)))
{}
/** Takes ownership of an existing mmap object. */
basic_shared_mmap& operator=(mmap_type&& mmap)
{
pimpl_ = std::make_shared<mmap_type>(std::move(mmap));
return *this;
}
/** Initializes this object with an already established shared mmap. */
basic_shared_mmap(std::shared_ptr<mmap_type> mmap) : pimpl_(std::move(mmap)) {}
/** Initializes this object with an already established shared mmap. */
basic_shared_mmap& operator=(std::shared_ptr<mmap_type> mmap)
{
pimpl_ = std::move(mmap);
return *this;
}
#ifdef __cpp_exceptions
/**
* The same as invoking the `map` function, except any error that may occur
* while establishing the mapping is wrapped in a `std::system_error` and is
* thrown.
*/
template<typename String>
basic_shared_mmap(const String& path, const size_type offset = 0, const size_type length = map_entire_file)
{
std::error_code error;
map(path, offset, length, error);
if(error) { throw std::system_error(error); }
}
/**
* The same as invoking the `map` function, except any error that may occur
* while establishing the mapping is wrapped in a `std::system_error` and is
* thrown.
*/
basic_shared_mmap(const handle_type handle, const size_type offset = 0, const size_type length = map_entire_file)
{
std::error_code error;
map(handle, offset, length, error);
if(error) { throw std::system_error(error); }
}
#endif // __cpp_exceptions
/**
* If this is a read-write mapping and the last reference to the mapping,
* the destructor invokes sync. Regardless of the access mode, unmap is
* invoked as a final step.
*/
~basic_shared_mmap() = default;
/** Returns the underlying `std::shared_ptr` instance that holds the mmap. */
std::shared_ptr<mmap_type> get_shared_ptr() { return pimpl_; }
/**
* On UNIX systems 'file_handle' and 'mapping_handle' are the same. On Windows,
* however, a mapped region of a file gets its own handle, which is returned by
* 'mapping_handle'.
*/
handle_type file_handle() const noexcept
{
return pimpl_ ? pimpl_->file_handle() : invalid_handle;
}
handle_type mapping_handle() const noexcept
{
return pimpl_ ? pimpl_->mapping_handle() : invalid_handle;
}
/** Returns whether a valid memory mapping has been created. */
bool is_open() const noexcept { return pimpl_ && pimpl_->is_open(); }
/**
* Returns true if no mapping was established, that is, conceptually the
* same as though the length that was mapped was 0. This function is
* provided so that this class has Container semantics.
*/
bool empty() const noexcept { return !pimpl_ || pimpl_->empty(); }
/**
* `size` and `length` both return the logical length, i.e. the number of bytes
* user requested to be mapped, while `mapped_length` returns the actual number of
* bytes that were mapped which is a multiple of the underlying operating system's
* page allocation granularity.
*/
size_type size() const noexcept { return pimpl_ ? pimpl_->length() : 0; }
size_type length() const noexcept { return pimpl_ ? pimpl_->length() : 0; }
size_type mapped_length() const noexcept
{
return pimpl_ ? pimpl_->mapped_length() : 0;
}
/**
* Returns a pointer to the first requested byte, or `nullptr` if no memory mapping
* exists.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> pointer data() noexcept { return pimpl_->data(); }
const_pointer data() const noexcept { return pimpl_ ? pimpl_->data() : nullptr; }
/**
* Returns an iterator to the first requested byte, if a valid memory mapping
* exists, otherwise this function call is undefined behaviour.
*/
iterator begin() noexcept { return pimpl_->begin(); }
const_iterator begin() const noexcept { return pimpl_->begin(); }
const_iterator cbegin() const noexcept { return pimpl_->cbegin(); }
/**
* Returns an iterator one past the last requested byte, if a valid memory mapping
* exists, otherwise this function call is undefined behaviour.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> iterator end() noexcept { return pimpl_->end(); }
const_iterator end() const noexcept { return pimpl_->end(); }
const_iterator cend() const noexcept { return pimpl_->cend(); }
/**
* Returns a reverse iterator to the last memory mapped byte, if a valid
* memory mapping exists, otherwise this function call is undefined
* behaviour.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> reverse_iterator rbegin() noexcept { return pimpl_->rbegin(); }
const_reverse_iterator rbegin() const noexcept { return pimpl_->rbegin(); }
const_reverse_iterator crbegin() const noexcept { return pimpl_->crbegin(); }
/**
* Returns a reverse iterator past the first mapped byte, if a valid memory
* mapping exists, otherwise this function call is undefined behaviour.
*/
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> reverse_iterator rend() noexcept { return pimpl_->rend(); }
const_reverse_iterator rend() const noexcept { return pimpl_->rend(); }
const_reverse_iterator crend() const noexcept { return pimpl_->crend(); }
/**
* Returns a reference to the `i`th byte from the first requested byte (as returned
* by `data`). If this is invoked when no valid memory mapping has been created
* prior to this call, undefined behaviour ensues.
*/
reference operator[](const size_type i) noexcept { return (*pimpl_)[i]; }
const_reference operator[](const size_type i) const noexcept { return (*pimpl_)[i]; }
/**
* Establishes a memory mapping with AccessMode. If the mapping is unsuccesful, the
* reason is reported via `error` and the object remains in a state as if this
* function hadn't been called.
*
* `path`, which must be a path to an existing file, is used to retrieve a file
* handle (which is closed when the object destructs or `unmap` is called), which is
* then used to memory map the requested region. Upon failure, `error` is set to
* indicate the reason and the object remains in an unmapped state.
*
* `offset` is the number of bytes, relative to the start of the file, where the
* mapping should begin. When specifying it, there is no need to worry about
* providing a value that is aligned with the operating system's page allocation
* granularity. This is adjusted by the implementation such that the first requested
* byte (as returned by `data` or `begin`), so long as `offset` is valid, will be at
* `offset` from the start of the file.
*
* `length` is the number of bytes to map. It may be `map_entire_file`, in which
* case a mapping of the entire file is created.
*/
template<typename String>
void map(const String& path, const size_type offset,
const size_type length, std::error_code& error)
{
map_impl(path, offset, length, error);
}
/**
* Establishes a memory mapping with AccessMode. If the mapping is unsuccesful, the
* reason is reported via `error` and the object remains in a state as if this
* function hadn't been called.
*
* `path`, which must be a path to an existing file, is used to retrieve a file
* handle (which is closed when the object destructs or `unmap` is called), which is
* then used to memory map the requested region. Upon failure, `error` is set to
* indicate the reason and the object remains in an unmapped state.
*
* The entire file is mapped.
*/
template<typename String>
void map(const String& path, std::error_code& error)
{
map_impl(path, 0, map_entire_file, error);
}
/**
* Establishes a memory mapping with AccessMode. If the mapping is unsuccesful, the
* reason is reported via `error` and the object remains in a state as if this
* function hadn't been called.
*
* `handle`, which must be a valid file handle, which is used to memory map the
* requested region. Upon failure, `error` is set to indicate the reason and the
* object remains in an unmapped state.
*
* `offset` is the number of bytes, relative to the start of the file, where the
* mapping should begin. When specifying it, there is no need to worry about
* providing a value that is aligned with the operating system's page allocation
* granularity. This is adjusted by the implementation such that the first requested
* byte (as returned by `data` or `begin`), so long as `offset` is valid, will be at
* `offset` from the start of the file.
*
* `length` is the number of bytes to map. It may be `map_entire_file`, in which
* case a mapping of the entire file is created.
*/
void map(const handle_type handle, const size_type offset,
const size_type length, std::error_code& error)
{
map_impl(handle, offset, length, error);
}
/**
* Establishes a memory mapping with AccessMode. If the mapping is unsuccesful, the
* reason is reported via `error` and the object remains in a state as if this
* function hadn't been called.
*
* `handle`, which must be a valid file handle, which is used to memory map the
* requested region. Upon failure, `error` is set to indicate the reason and the
* object remains in an unmapped state.
*
* The entire file is mapped.
*/
void map(const handle_type handle, std::error_code& error)
{
map_impl(handle, 0, map_entire_file, error);
}
/**
* If a valid memory mapping has been created prior to this call, this call
* instructs the kernel to unmap the memory region and disassociate this object
* from the file.
*
* The file handle associated with the file that is mapped is only closed if the
* mapping was created using a file path. If, on the other hand, an existing
* file handle was used to create the mapping, the file handle is not closed.
*/
void unmap() { if(pimpl_) pimpl_->unmap(); }
void swap(basic_shared_mmap& other) { pimpl_.swap(other.pimpl_); }
/** Flushes the memory mapped page to disk. Errors are reported via `error`. */
template<
access_mode A = AccessMode,
typename = typename std::enable_if<A == access_mode::write>::type
> void sync(std::error_code& error) { if(pimpl_) pimpl_->sync(error); }
/** All operators compare the underlying `basic_mmap`'s addresses. */
friend bool operator==(const basic_shared_mmap& a, const basic_shared_mmap& b)
{
return a.pimpl_ == b.pimpl_;
}
friend bool operator!=(const basic_shared_mmap& a, const basic_shared_mmap& b)
{
return !(a == b);
}
friend bool operator<(const basic_shared_mmap& a, const basic_shared_mmap& b)
{
return a.pimpl_ < b.pimpl_;
}
friend bool operator<=(const basic_shared_mmap& a, const basic_shared_mmap& b)
{
return a.pimpl_ <= b.pimpl_;
}
friend bool operator>(const basic_shared_mmap& a, const basic_shared_mmap& b)
{
return a.pimpl_ > b.pimpl_;
}
friend bool operator>=(const basic_shared_mmap& a, const basic_shared_mmap& b)
{
return a.pimpl_ >= b.pimpl_;
}
private:
template<typename MappingToken>
void map_impl(const MappingToken& token, const size_type offset,
const size_type length, std::error_code& error)
{
if(!pimpl_)
{
mmap_type mmap = make_mmap<mmap_type>(token, offset, length, error);
if(error) { return; }
pimpl_ = std::make_shared<mmap_type>(std::move(mmap));
}
else
{
pimpl_->map(token, offset, length, error);
}
}
};
/**
* This is the basis for all read-only mmap objects and should be preferred over
* directly using basic_shared_mmap.
*/
template<typename ByteT>
using basic_shared_mmap_source = basic_shared_mmap<access_mode::read, ByteT>;
/**
* This is the basis for all read-write mmap objects and should be preferred over
* directly using basic_shared_mmap.
*/
template<typename ByteT>
using basic_shared_mmap_sink = basic_shared_mmap<access_mode::write, ByteT>;
/**
* These aliases cover the most common use cases, both representing a raw byte stream
* (either with a char or an unsigned char/uint8_t).
*/
using shared_mmap_source = basic_shared_mmap_source<char>;
using shared_ummap_source = basic_shared_mmap_source<unsigned char>;
using shared_mmap_sink = basic_shared_mmap_sink<char>;
using shared_ummap_sink = basic_shared_mmap_sink<unsigned char>;
} // namespace mio
#endif // MIO_SHARED_MMAP_HEADER
| 33.962836 | 117 | 0.690056 | [
"object",
"vector"
] |
b4ba6d8b2f2025f50921c25b0f34c5448364c4fd | 13,137 | cpp | C++ | src/storage/local_storage.cpp | pacien/duckdb | d887d2f80f283160643a3adf74ae3d1b7f8662c1 | [
"MIT"
] | null | null | null | src/storage/local_storage.cpp | pacien/duckdb | d887d2f80f283160643a3adf74ae3d1b7f8662c1 | [
"MIT"
] | 7 | 2020-08-25T22:24:16.000Z | 2020-09-06T00:16:49.000Z | src/storage/local_storage.cpp | pacien/duckdb | d887d2f80f283160643a3adf74ae3d1b7f8662c1 | [
"MIT"
] | null | null | null | #include "duckdb/transaction/local_storage.hpp"
#include "duckdb/execution/index/art/art.hpp"
#include "duckdb/storage/table/append_state.hpp"
#include "duckdb/storage/write_ahead_log.hpp"
#include "duckdb/common/vector_operations/vector_operations.hpp"
#include "duckdb/storage/uncompressed_segment.hpp"
namespace duckdb {
using namespace std;
LocalTableStorage::LocalTableStorage(DataTable &table) : max_row(0) {
for (auto &index : table.info->indexes) {
assert(index->type == IndexType::ART);
auto &art = (ART &)*index;
if (art.is_unique) {
// unique index: create a local ART index that maintains the same unique constraint
vector<unique_ptr<Expression>> unbound_expressions;
for (auto &expr : art.unbound_expressions) {
unbound_expressions.push_back(expr->Copy());
}
indexes.push_back(make_unique<ART>(art.column_ids, move(unbound_expressions), true));
}
}
}
LocalTableStorage::~LocalTableStorage() {
}
void LocalTableStorage::InitializeScan(LocalScanState &state) {
state.storage = this;
state.chunk_index = 0;
state.max_index = collection.chunks.size() - 1;
state.last_chunk_count = collection.chunks.back()->size();
}
void LocalTableStorage::Clear() {
collection.chunks.clear();
indexes.clear();
deleted_entries.clear();
}
void LocalStorage::InitializeScan(DataTable *table, LocalScanState &state) {
auto entry = table_storage.find(table);
if (entry == table_storage.end()) {
// no local storage for table: set scan to nullptr
state.storage = nullptr;
return;
}
state.storage = entry->second.get();
state.storage->InitializeScan(state);
}
void LocalStorage::Scan(LocalScanState &state, const vector<column_t> &column_ids, DataChunk &result,
unordered_map<idx_t, vector<TableFilter>> *table_filters) {
if (!state.storage || state.chunk_index > state.max_index) {
// nothing left to scan
result.Reset();
return;
}
auto &chunk = *state.storage->collection.chunks[state.chunk_index];
idx_t chunk_count = state.chunk_index == state.max_index ? state.last_chunk_count : chunk.size();
idx_t count = chunk_count;
// first create a selection vector from the deleted entries (if any)
SelectionVector valid_sel(STANDARD_VECTOR_SIZE);
auto entry = state.storage->deleted_entries.find(state.chunk_index);
if (entry != state.storage->deleted_entries.end()) {
// deleted entries! create a selection vector
auto deleted = entry->second.get();
idx_t new_count = 0;
for (idx_t i = 0; i < count; i++) {
if (!deleted[i]) {
valid_sel.set_index(new_count++, i);
}
}
if (new_count == 0 && count > 0) {
// all entries in this chunk were deleted: continue to next chunk
state.chunk_index++;
Scan(state, column_ids, result, table_filters);
return;
}
count = new_count;
}
SelectionVector sel;
if (count != chunk_count) {
sel.Initialize(valid_sel);
} else {
sel.Initialize(FlatVector::IncrementalSelectionVector);
}
// now scan the vectors of the chunk
for (idx_t i = 0; i < column_ids.size(); i++) {
auto id = column_ids[i];
if (id == COLUMN_IDENTIFIER_ROW_ID) {
// row identifier: return a sequence of rowids starting from MAX_ROW_ID plus the row offset in the chunk
result.data[i].Sequence(MAX_ROW_ID + state.chunk_index * STANDARD_VECTOR_SIZE, 1);
} else {
result.data[i].Reference(chunk.data[id]);
}
idx_t approved_tuple_count = count;
if (table_filters) {
auto column_filters = table_filters->find(i);
if (column_filters != table_filters->end()) {
//! We have filters to apply here
for (auto &column_filter : column_filters->second) {
nullmask_t nullmask = FlatVector::Nullmask(result.data[i]);
UncompressedSegment::filterSelection(sel, result.data[i], column_filter, approved_tuple_count,
nullmask);
}
count = approved_tuple_count;
}
}
}
if (count == 0) {
// all entries in this chunk were filtered:: Continue on next chunk
state.chunk_index++;
Scan(state, column_ids, result, table_filters);
return;
}
if (count == chunk_count) {
result.SetCardinality(count);
} else {
result.Slice(sel, count);
}
state.chunk_index++;
}
void LocalStorage::Append(DataTable *table, DataChunk &chunk) {
auto entry = table_storage.find(table);
LocalTableStorage *storage;
if (entry == table_storage.end()) {
auto new_storage = make_unique<LocalTableStorage>(*table);
storage = new_storage.get();
table_storage.insert(make_pair(table, move(new_storage)));
} else {
storage = entry->second.get();
}
// append to unique indices (if any)
if (storage->indexes.size() > 0) {
idx_t base_id = MAX_ROW_ID + storage->collection.count;
// first generate the vector of row identifiers
Vector row_ids(LOGICAL_ROW_TYPE);
VectorOperations::GenerateSequence(row_ids, chunk.size(), base_id, 1);
// now append the entries to the indices
for (auto &index : storage->indexes) {
if (!index->Append(chunk, row_ids)) {
throw ConstraintException("PRIMARY KEY or UNIQUE constraint violated: duplicated key");
}
}
}
//! Append to the chunk
storage->collection.Append(chunk);
}
LocalTableStorage *LocalStorage::GetStorage(DataTable *table) {
auto entry = table_storage.find(table);
assert(entry != table_storage.end());
return entry->second.get();
}
static idx_t GetChunk(Vector &row_ids) {
auto ids = FlatVector::GetData<row_t>(row_ids);
auto first_id = ids[0] - MAX_ROW_ID;
return first_id / STANDARD_VECTOR_SIZE;
}
void LocalStorage::Delete(DataTable *table, Vector &row_ids, idx_t count) {
auto storage = GetStorage(table);
// figure out the chunk from which these row ids came
idx_t chunk_idx = GetChunk(row_ids);
assert(chunk_idx < storage->collection.chunks.size());
// get a pointer to the deleted entries for this chunk
bool *deleted;
auto entry = storage->deleted_entries.find(chunk_idx);
if (entry == storage->deleted_entries.end()) {
// nothing deleted yet, add the deleted entries
auto del_entries = unique_ptr<bool[]>(new bool[STANDARD_VECTOR_SIZE]);
memset(del_entries.get(), 0, sizeof(bool) * STANDARD_VECTOR_SIZE);
deleted = del_entries.get();
storage->deleted_entries.insert(make_pair(chunk_idx, move(del_entries)));
} else {
deleted = entry->second.get();
}
// now actually mark the entries as deleted in the deleted vector
idx_t base_index = MAX_ROW_ID + chunk_idx * STANDARD_VECTOR_SIZE;
auto ids = FlatVector::GetData<row_t>(row_ids);
for (idx_t i = 0; i < count; i++) {
auto id = ids[i] - base_index;
deleted[id] = true;
}
}
template <class T>
static void update_data(Vector &data_vector, Vector &update_vector, Vector &row_ids, idx_t count, idx_t base_index) {
VectorData udata;
update_vector.Orrify(count, udata);
auto target = FlatVector::GetData<T>(data_vector);
auto &nullmask = FlatVector::Nullmask(data_vector);
auto ids = FlatVector::GetData<row_t>(row_ids);
auto updates = (T *)udata.data;
for (idx_t i = 0; i < count; i++) {
auto uidx = udata.sel->get_index(i);
auto id = ids[i] - base_index;
target[id] = updates[uidx];
nullmask[id] = (*udata.nullmask)[uidx];
}
}
static void update_chunk(Vector &data, Vector &updates, Vector &row_ids, idx_t count, idx_t base_index) {
assert(data.type == updates.type);
assert(row_ids.type == LOGICAL_ROW_TYPE);
switch (data.type.InternalType()) {
case PhysicalType::INT8:
update_data<int8_t>(data, updates, row_ids, count, base_index);
break;
case PhysicalType::INT16:
update_data<int16_t>(data, updates, row_ids, count, base_index);
break;
case PhysicalType::INT32:
update_data<int32_t>(data, updates, row_ids, count, base_index);
break;
case PhysicalType::INT64:
update_data<int64_t>(data, updates, row_ids, count, base_index);
break;
case PhysicalType::FLOAT:
update_data<float>(data, updates, row_ids, count, base_index);
break;
case PhysicalType::DOUBLE:
update_data<double>(data, updates, row_ids, count, base_index);
break;
default:
throw Exception("Unsupported type for in-place update");
}
}
void LocalStorage::Update(DataTable *table, Vector &row_ids, vector<column_t> &column_ids, DataChunk &data) {
auto storage = GetStorage(table);
// figure out the chunk from which these row ids came
idx_t chunk_idx = GetChunk(row_ids);
assert(chunk_idx < storage->collection.chunks.size());
idx_t base_index = MAX_ROW_ID + chunk_idx * STANDARD_VECTOR_SIZE;
// now perform the actual update
auto &chunk = *storage->collection.chunks[chunk_idx];
for (idx_t i = 0; i < column_ids.size(); i++) {
auto col_idx = column_ids[i];
update_chunk(chunk.data[col_idx], data.data[i], row_ids, data.size(), base_index);
}
}
template <class T> bool LocalStorage::ScanTableStorage(DataTable *table, LocalTableStorage *storage, T &&fun) {
vector<column_t> column_ids;
for (idx_t i = 0; i < table->types.size(); i++) {
column_ids.push_back(i);
}
DataChunk chunk;
chunk.Initialize(table->types);
// initialize the scan
LocalScanState state;
storage->InitializeScan(state);
while (true) {
Scan(state, column_ids, chunk);
if (chunk.size() == 0) {
return true;
}
if (!fun(chunk)) {
return false;
}
}
}
void LocalStorage::Commit(LocalStorage::CommitState &commit_state, Transaction &transaction, WriteAheadLog *log,
transaction_t commit_id) {
// commit local storage, iterate over all entries in the table storage map
for (auto &entry : table_storage) {
auto table = entry.first;
auto storage = entry.second.get();
// initialize the append state
auto append_state_ptr = make_unique<TableAppendState>();
auto &append_state = *append_state_ptr;
// add it to the set of append states
commit_state.append_states[table] = move(append_state_ptr);
table->InitializeAppend(append_state);
if (log && !table->info->IsTemporary()) {
log->WriteSetTable(table->info->schema, table->info->table);
}
// scan all chunks in this storage
ScanTableStorage(table, storage, [&](DataChunk &chunk) -> bool {
// append this chunk to the indexes of the table
if (!table->AppendToIndexes(append_state, chunk, append_state.current_row)) {
throw ConstraintException("PRIMARY KEY or UNIQUE constraint violated: duplicated key");
}
// append to base table
table->Append(transaction, commit_id, chunk, append_state);
// if there is a WAL, write the chunk to there as well
if (log && !table->info->IsTemporary()) {
log->WriteInsert(chunk);
}
return true;
});
}
// finished commit: clear local storage
for (auto &entry : table_storage) {
entry.second->Clear();
}
table_storage.clear();
}
void LocalStorage::RevertCommit(LocalStorage::CommitState &commit_state) {
for (auto &entry : commit_state.append_states) {
auto table = entry.first;
auto storage = table_storage[table].get();
auto &append_state = *entry.second;
if (table->info->indexes.size() > 0 && !table->info->IsTemporary()) {
row_t current_row = append_state.row_start;
// remove the data from the indexes, if there are any indexes
ScanTableStorage(table, storage, [&](DataChunk &chunk) -> bool {
// append this chunk to the indexes of the table
table->RemoveFromIndexes(append_state, chunk, current_row);
current_row += chunk.size();
if (current_row >= append_state.current_row) {
// finished deleting all rows from the index: abort now
return false;
}
return true;
});
}
table->RevertAppend(*entry.second);
}
}
void LocalStorage::AddColumn(DataTable *old_dt, DataTable *new_dt, ColumnDefinition &new_column,
Expression *default_value) {
// check if there are any pending appends for the old version of the table
auto entry = table_storage.find(old_dt);
if (entry == table_storage.end()) {
return;
}
// take over the storage from the old entry
auto new_storage = move(entry->second);
// now add the new column filled with the default value to all chunks
auto new_column_type = new_column.type;
ExpressionExecutor executor;
DataChunk dummy_chunk;
if (default_value) {
executor.AddExpression(*default_value);
}
new_storage->collection.types.push_back(new_column_type);
for (idx_t chunk_idx = 0; chunk_idx < new_storage->collection.chunks.size(); chunk_idx++) {
auto &chunk = new_storage->collection.chunks[chunk_idx];
Vector result(new_column_type);
if (default_value) {
dummy_chunk.SetCardinality(chunk->size());
executor.ExecuteExpression(dummy_chunk, result);
} else {
FlatVector::Nullmask(result).set();
}
chunk->data.push_back(move(result));
}
table_storage.erase(entry);
table_storage[new_dt] = move(new_storage);
}
void LocalStorage::ChangeType(DataTable *old_dt, DataTable *new_dt, idx_t changed_idx, LogicalType target_type,
vector<column_t> bound_columns, Expression &cast_expr) {
// check if there are any pending appends for the old version of the table
auto entry = table_storage.find(old_dt);
if (entry == table_storage.end()) {
return;
}
throw NotImplementedException("FIXME: ALTER TYPE with transaction local data not currently supported");
}
} // namespace duckdb
| 32.8425 | 117 | 0.712263 | [
"vector"
] |
b4bc2ebb67d09160e6331c8ed0c63b8c7eda7539 | 2,747 | hpp | C++ | src/core/lib/core_reflection/definition_manager.hpp | wgsyd/wgtf | d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed | [
"BSD-3-Clause"
] | 28 | 2016-06-03T05:28:25.000Z | 2019-02-14T12:04:31.000Z | src/core/lib/core_reflection/definition_manager.hpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | null | null | null | src/core/lib/core_reflection/definition_manager.hpp | karajensen/wgtf | 740397bcfdbc02bc574231579d57d7c9cd5cc26d | [
"BSD-3-Clause"
] | 14 | 2016-06-03T05:52:27.000Z | 2019-03-21T09:56:03.000Z | #ifndef DEFINITION_MANAGER_HPP
#define DEFINITION_MANAGER_HPP
#include <map>
#include <unordered_map>
#include "i_definition_manager.hpp"
#include "core_common/wg_read_write_lock.hpp"
#include "core_dependency_system/i_interface.hpp"
#include "wg_types/hashed_string_ref.hpp"
#include "reflection_dll.hpp"
namespace wgt
{
/**
* DefinitionManager
*/
class REFLECTION_DLL DefinitionManager : public Implements<IDefinitionManager>
{
public:
// IDefinitionManager
virtual IClassDefinition* getDefinition(const char* name) const override;
virtual IClassDefinition* findDefinition(const char* name) const override;
virtual IClassDefinition* getObjectDefinition(const ObjectHandle& object) const override;
std::unique_ptr<IClassDefinitionDetails> createGenericDefinition(const char* name) const override;
virtual void getDefinitionsOfType(const IClassDefinition* definition,
std::vector<IClassDefinition*>& o_Definitions) const override;
virtual void getDefinitionsOfType(const std::string& type,
std::vector<IClassDefinition*>& o_Definitions) const override;
void registerDefinitionHelper(const IDefinitionHelper& helper) override;
void deregisterDefinitionHelper(const IDefinitionHelper& helper) override;
void registerPropertyAccessorListener(std::shared_ptr<PropertyAccessorListener>& listener) override;
void deregisterPropertyAccessorListener(std::shared_ptr<PropertyAccessorListener>& listener) override;
const PropertyAccessorListeners& getPropertyAccessorListeners() const override;
virtual IObjectManager* getObjectManager() const override;
virtual IClassDefinition* registerDefinition(std::unique_ptr<IClassDefinitionDetails> definition) override;
virtual bool deregisterDefinition(const IClassDefinition* definition) override;
virtual void deregisterDefinitions() override;
bool serializeDefinitions(ISerializer& serializer) override;
bool deserializeDefinitions(ISerializer& serializer) override;
DefinitionManager(IObjectManager& objectManager);
virtual ~DefinitionManager();
private:
mutable wg_read_write_lock lock_;
typedef std::unordered_map<HashedStringRef, IClassDefinition*> ClassDefCollection;
ClassDefCollection definitions_;
void getDefinitionsOfType(IClassDefinition* definition, std::vector<IClassDefinition*>& o_Definitions,
size_t startIndex) const;
mutable wg_read_write_lock helpersLock_;
std::map<TypeId, const IDefinitionHelper*> helpers_;
std::unique_ptr<IDefinitionHelper> genericDefinitionHelper_;
mutable wg_read_write_lock listenersLock_;
PropertyAccessorListeners listeners_;
IObjectManager& objectManager_;
};
} // end namespace wgt
#endif // DEFINITION_MANAGER_HPP
| 38.152778 | 108 | 0.807426 | [
"object",
"vector"
] |
b4bf3483629caaf379e75b798e5958283ca73ab1 | 3,563 | cpp | C++ | src/planning/validators.cpp | zanmato1984/cura | 0d6ff23bb3f6456911cf1e9dc34754173e7652ed | [
"Apache-2.0"
] | 29 | 2020-08-10T03:44:05.000Z | 2022-01-29T16:19:32.000Z | src/planning/validators.cpp | zanmato1984/cura | 0d6ff23bb3f6456911cf1e9dc34754173e7652ed | [
"Apache-2.0"
] | 8 | 2020-08-10T03:54:54.000Z | 2022-02-15T04:11:01.000Z | src/planning/validators.cpp | zanmato1984/cura | 0d6ff23bb3f6456911cf1e9dc34754173e7652ed | [
"Apache-2.0"
] | 11 | 2020-10-10T09:52:52.000Z | 2022-01-20T01:58:26.000Z | #include "validators.h"
#include "cura/expression/expression_visitor.h"
namespace cura::planning {
using cura::expression::ColumnRef;
using cura::expression::Expression;
using cura::expression::ExpressionVisitor;
using cura::relational::Schema;
namespace detail {
struct ColumnRefCollector
: public ExpressionVisitor<ColumnRefCollector,
std::vector<std::shared_ptr<const ColumnRef>>> {
std::vector<std::shared_ptr<const ColumnRef>>
visitColumnRef(const std::shared_ptr<const ColumnRef> &column_ref) {
return {column_ref};
}
std::vector<std::shared_ptr<const ColumnRef>>
defaultVisit(const std::shared_ptr<const Expression> &,
const std::vector<std::vector<std::shared_ptr<const ColumnRef>>>
&children) {
std::vector<std::shared_ptr<const ColumnRef>> column_refs;
for (auto &child : children) {
column_refs.insert(column_refs.end(),
std::make_move_iterator(child.begin()),
std::make_move_iterator(child.end()));
}
return column_refs;
}
};
void validateExpression(const Schema &input_schema,
const std::shared_ptr<const Expression> &expression) {
auto column_refs = ColumnRefCollector().visit(expression);
std::for_each(column_refs.begin(), column_refs.end(),
[&input_schema](const auto &column_ref) {
CURA_ASSERT(column_ref->columnIdx() < input_schema.size(),
"Column ref out of bound");
CURA_ASSERT(column_ref->dataType() ==
input_schema[column_ref->columnIdx()],
"Column ref data type mismatch with column");
});
}
} // namespace detail
void ColumnRefValidator::visitFilter(
const std::shared_ptr<const RelFilter> &filter) {
detail::validateExpression(filter->inputs[0]->output(), filter->condition());
}
void ColumnRefValidator::visitHashJoin(
const std::shared_ptr<const RelHashJoin> &hash_join) {
auto input_schema = hash_join->left()->output();
input_schema.insert(input_schema.end(), hash_join->right()->output().begin(),
hash_join->right()->output().end());
detail::validateExpression(input_schema, hash_join->condition());
}
void ColumnRefValidator::visitProject(
const std::shared_ptr<const RelProject> &project) {
std::for_each(project->expressions().begin(), project->expressions().end(),
[&](const auto &e) {
detail::validateExpression(project->inputs[0]->output(), e);
});
}
void ColumnRefValidator::visitAggregate(
const std::shared_ptr<const RelAggregate> &aggregate) {
std::for_each(aggregate->groups().begin(), aggregate->groups().end(),
[&](const auto &e) {
detail::validateExpression(aggregate->inputs[0]->output(), e);
});
std::for_each(aggregate->aggregations().begin(),
aggregate->aggregations().end(), [&](const auto &e) {
detail::validateExpression(aggregate->inputs[0]->output(), e);
});
}
void ColumnRefValidator::visitSort(const std::shared_ptr<const RelSort> &sort) {
std::for_each(sort->sortInfos().begin(), sort->sortInfos().end(),
[&](const auto &sort_info) {
detail::validateExpression(sort->inputs[0]->output(),
sort_info.expression);
});
}
} // namespace cura::planning
| 38.728261 | 80 | 0.615212 | [
"vector"
] |
b4c1eaef72346a96c471cdb592288c564659d4bd | 5,410 | cc | C++ | tonic-suite/asr/src/bin/get-silence-probs.cc | csb1024/djinn_csb | de50d6b6bc9c137e9f4b881de9048eba9e83142d | [
"BSD-3-Clause"
] | 59 | 2015-07-01T21:41:47.000Z | 2021-07-28T07:07:42.000Z | tonic-suite/asr/src/bin/get-silence-probs.cc | csb1024/djinn_csb | de50d6b6bc9c137e9f4b881de9048eba9e83142d | [
"BSD-3-Clause"
] | 4 | 2016-01-24T13:25:03.000Z | 2021-07-06T09:10:23.000Z | tonic-suite/asr/src/bin/get-silence-probs.cc | csb1024/djinn_csb | de50d6b6bc9c137e9f4b881de9048eba9e83142d | [
"BSD-3-Clause"
] | 54 | 2015-06-13T15:31:20.000Z | 2021-07-28T07:07:43.000Z | // bin/get-silence-probs.cc
// Copyright 2009-2011 Microsoft Corporation
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "gmm/am-diag-gmm.h"
#include "hmm/transition-model.h"
#include "hmm/hmm-utils.h"
int main(int argc, char *argv[]) {
using namespace kaldi;
typedef kaldi::int32 int32;
typedef kaldi::int64 int64;
try {
const char *usage =
"This program takes two archives of Vector<BaseFloat>, representing\n"
"per-frame log-likelihoods for silence and non-silence models "
"respectively.\n"
"It outputs per-frame silence probabilities in the same format.\n"
"To get non-silence probs instead, use --write-nonsil-probs "
"Usage: get-silence-probs [options] <silence-loglikes-rspecifier> "
" <nonsilence-loglikes-rspecifier> <silence-probs-wspecifier>\n"
"e.g.: get-silence-probs --silence-prior=0.9 --quantize=0.25 "
"ark:sil.likes "
"ark:nonsil.likes ark:sil.probs\n";
ParseOptions po(usage);
BaseFloat sil_prior = 0.5;
BaseFloat quantize = 0.0;
bool write_nonsil_probs = false;
po.Register(
"sil-prior", &sil_prior,
"Prior probability of silence, must be strictly between 0 and 1.");
po.Register("quantize", &quantize,
"If nonzero, quantize probs to this level (to improve "
"compressibility).");
po.Register("write-nonsil-probs", &write_nonsil_probs,
"If true, write non-silence probs instead of silence probs");
po.Read(argc, argv);
if (po.NumArgs() != 3) {
po.PrintUsage();
exit(1);
}
KALDI_ASSERT(sil_prior > 0.0 && sil_prior < 1.0);
KALDI_ASSERT(quantize >= 0.0 && quantize <= 1.0);
double sil_log_bias = log(sil_prior / (1.0 - sil_prior));
std::string silence_likes_rspecifier = po.GetArg(1),
nonsilence_likes_rspecifier = po.GetArg(2),
silence_probs_wspecifier = po.GetArg(3);
SequentialBaseFloatVectorReader silence_likes_reader(
silence_likes_rspecifier);
RandomAccessBaseFloatVectorReader nonsilence_likes_reader(
nonsilence_likes_rspecifier);
BaseFloatVectorWriter silence_probs_writer(silence_probs_wspecifier);
int num_done = 0, num_err = 0;
double tot_frames = 0.0, tot_sil_prob = 0.0;
for (; !silence_likes_reader.Done(); silence_likes_reader.Next()) {
std::string key = silence_likes_reader.Key();
if (!nonsilence_likes_reader.HasKey(key)) {
KALDI_WARN << "No non-silence likes available for utterance " << key;
num_err++;
continue;
}
const Vector<BaseFloat> &sil_likes = silence_likes_reader.Value();
const Vector<BaseFloat> &nonsil_likes =
nonsilence_likes_reader.Value(key);
if (sil_likes.Dim() != nonsil_likes.Dim()) {
KALDI_WARN << "Dimension mismatch between sil and non-sil likes";
num_err++;
continue;
}
int32 num_frames = sil_likes.Dim();
Vector<BaseFloat> sil_probs(num_frames);
for (int32 f = 0; f < num_frames; f++) {
// We're basically just applying Bayes' rule here to get the
// posterior prob of silence.
BaseFloat sil_loglike = sil_likes(f), nonsil_loglike = nonsil_likes(f);
sil_loglike -= nonsil_loglike;
nonsil_loglike = 0; // improve floating-point range.
sil_loglike += sil_log_bias; // relates to prior. Zero if prior==0.5.
if (sil_loglike > 10) {
sil_probs(f) = 1.0; // because the exp below might fail.
} else {
BaseFloat e_sil_loglike = exp(sil_loglike);
BaseFloat sil_prob = e_sil_loglike / (1.0 + e_sil_loglike);
if (!(sil_prob >= 0.0 && sil_prob <= 1.0)) {
KALDI_WARN << "Bad silence prob (NaNs found?), setting to 0.5";
sil_prob = 0.5;
}
sil_probs(f) = sil_prob;
}
if (quantize != 0.0) {
int64 i = static_cast<int64>(0.5 + (sil_probs(f) / quantize));
sil_probs(f) = quantize * i;
}
}
tot_frames += num_frames;
tot_sil_prob += sil_probs.Sum();
if (write_nonsil_probs) { // sil_prob <-- 1.0 - sil_prob
sil_probs.Scale(-1.0);
sil_probs.Add(1.0);
}
silence_probs_writer.Write(key, sil_probs);
num_done++;
}
KALDI_LOG << "Done " << num_done << " utterances, " << num_err
<< " with errors.";
KALDI_LOG << "Average silence prob is " << (tot_sil_prob / tot_frames)
<< " over " << tot_frames << " frames.";
return (num_done != 0 ? 0 : 1);
} catch (const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 38.368794 | 79 | 0.632717 | [
"vector",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.