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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4f73d0cee340ea2e738990ce01b8e2eff71a5c08 | 26,022 | cpp | C++ | src/ltimage.cpp | ianmaclarty/lotech | 0b828778b41ed09df9aba3bfd8b63ac683acffc3 | [
"curl"
] | 9 | 2015-06-28T05:47:33.000Z | 2021-06-29T13:35:48.000Z | src/ltimage.cpp | ianmaclarty/lotech | 0b828778b41ed09df9aba3bfd8b63ac683acffc3 | [
"curl"
] | 5 | 2015-01-10T02:56:53.000Z | 2018-07-27T03:21:14.000Z | src/ltimage.cpp | ianmaclarty/lotech | 0b828778b41ed09df9aba3bfd8b63ac683acffc3 | [
"curl"
] | 3 | 2015-04-01T14:48:54.000Z | 2015-11-12T11:52:50.000Z | /* Copyright (C) 2010-2013 Ian MacLarty. See Copyright Notice in lt.h. */
#include "lt.h"
LT_INIT_IMPL(ltimage)
#define BBCHUNK_KEY "LTBB"
// w and h are the width and height of the original image.
// l, b, r and t are the left, bottom, right and top dimensions of the bounding box.
#define BBCHUNK_FORMAT "w%dh%dl%db%dr%dt%d"
void ltEnableAtlas(LTAtlas *atlas) {
ltEnableTexture(atlas->texture_id);
}
void ltEnableTexture(LTtexid texture_id) {
ltBindTexture(texture_id);
ltEnableTexturing();
ltEnableTextureCoordArrays();
}
void ltDisableTextures() {
ltDisableTexturing();
ltDisableTextureCoordArrays();
}
LTAtlas::LTAtlas(LTImagePacker *packer, LTTextureFilter minfilter, LTTextureFilter magfilter) {
static int atlas_num = 1;
char atlas_name[64];
snprintf(atlas_name, 64, "atlas%d", atlas_num++);
ref_count = 0;
LTImageBuffer *buf = ltCreateAtlasImage(atlas_name, packer);
#ifdef LT_DUMP_ATLASES
{
static int dump_id = 1;
char dump_file[128];
snprintf(dump_file, 128, "/tmp/atlas_%d.png", dump_id++);
ltLog("Dumping atlas to file %s (%d x %d)", dump_file, buf->bb_width(), buf->bb_height());
ltWriteImage(dump_file, buf);
}
#endif
texture_id = ltGenTexture();
ltBindTexture(texture_id);
ltTextureMinFilter(minfilter);
ltTextureMagFilter(magfilter);
ltTexImage(buf->width, buf->height, buf->bb_pixels);
delete buf;
}
LTAtlas::~LTAtlas() {
ltDeleteTexture(texture_id);
}
LTImageBuffer::LTImageBuffer(const char *name) {
LTImageBuffer::name = new char[strlen(name) + 1];
strcpy(LTImageBuffer::name, name);
is_glyph = false;
glyph_str[0] = '\0';
scaling = 1.0f;
bb_pixels = NULL;
}
LTImageBuffer::~LTImageBuffer() {
if (bb_pixels != NULL) {
delete[] bb_pixels;
}
delete[] name;
}
int LTImageBuffer::bb_width() {
return bb_right - bb_left + 1;
}
int LTImageBuffer::bb_height() {
return bb_top - bb_bottom + 1;
}
int LTImageBuffer::num_bb_pixels() {
return bb_width() * bb_height();
}
static void compute_bbox(const char *path, LTpixel **rows, int w, int h,
int *bb_left, int *bb_top, int *bb_right, int *bb_bottom)
{
int row;
int col;
LTpixel pxl;
bool row_clear = true;
bool found_bb_top = false;
*bb_top = h - 1;
*bb_left = w - 1;
*bb_right = 0;
*bb_bottom = 0;
for (row = 0; row < h; row++) {
row_clear = true;
for (col = 0; col < w; col++) {
pxl = rows[row][col];
if (LT_PIXEL_VISIBLE(pxl)) {
row_clear = false;
if (col < *bb_left) {
*bb_left = col;
}
if (col > *bb_right) {
*bb_right = col;
}
}
}
if (!row_clear) {
if (!found_bb_top) {
*bb_top = row;
found_bb_top = true;
}
*bb_bottom = row;
}
}
if (*bb_left > *bb_right) {
*bb_right = *bb_left;
}
if (*bb_top > *bb_bottom) {
*bb_top = *bb_bottom;
}
}
static void lt_png_error_fn(png_structp png_ptr, png_const_charp error_msg) {
const char *file = (const char*)png_get_error_ptr(png_ptr);
ltLog("libpng error while reading %s: %s", file, error_msg);
longjmp(png_jmpbuf(png_ptr), 1);
}
static void lt_png_warning_fn(png_structp png_ptr, png_const_charp warning_msg) {
const char *file = (const char*)png_get_error_ptr(png_ptr);
ltLog("libpng warning while reading %s: %s", file, warning_msg);
}
static void lt_png_read_fn(png_structp png_ptr, png_bytep data, png_size_t length) {
LTResource *in = (LTResource*)png_get_io_ptr(png_ptr);
int n = ltReadResource(in, data, length);
if (n < (int)length) {
ltLog("Error reading png data");
}
}
static LTfloat get_img_scaling(const char *path) {
if (strstr(path, "_025x.") != NULL) {
return 0.25f;
} else if (strstr(path, "_05x.") != NULL) {
return 0.5f;
} else if (strstr(path, "_1x.") != NULL) {
return 1.0f;
} else if (strstr(path, "_2x.") != NULL) {
return 2.0f;
} else if (strstr(path, "_4x.") != NULL) {
return 4.0f;
} else if (strstr(path, "_8x.") != NULL) {
return 8.0f;
}
return 1.0f;
}
LTImageBuffer *ltReadImage(const char *path, const char *name) {
LTResource *in;
png_structp png_ptr;
png_infop info_ptr;
png_infop end_ptr;
png_text *text_ptr;
unsigned char sig[8];
bool has_alpha;
bool has_bbchunk = false;
int num_txt_chunks;
png_uint_32 uwidth;
png_uint_32 uheight;
int width, height;
int bit_depth;
int color_type;
int png_transforms;
int bb_left = 0, bb_top = 0, bb_right = 0, bb_bottom = 0; // Only valid if has_bbchunk == false.
png_byte **rows;
in = ltOpenResource(path);
if (in == NULL) {
ltLog("Error: Unable to open %s for reading: %s", path, strerror(errno));
return NULL;
}
// Check for 8 byte signature.
int n = ltReadResource(in, sig, 8);
if (n != 8) {
ltCloseResource(in);
ltLog("Unable to read first 8 bytes of %s", path);
return NULL;
}
if (!png_check_sig(sig, 8)) {
ltCloseResource(in);
ltLog("%s has an invalid PNG signature", path);
return NULL;
}
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
end_ptr = png_create_info_struct(png_ptr);
png_set_error_fn(png_ptr, (void*)path, lt_png_error_fn, lt_png_warning_fn);
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_ptr);
ltCloseResource(in);
return NULL;
}
png_set_read_fn(png_ptr, in, lt_png_read_fn);
png_set_sig_bytes(png_ptr, 8);
// Read the data.
#ifdef LTGLES1
png_transforms = PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING |
PNG_TRANSFORM_GRAY_TO_RGB | PNG_TRANSFORM_EXPAND;
#else
png_transforms = PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING |
PNG_TRANSFORM_GRAY_TO_RGB | PNG_TRANSFORM_BGR | PNG_TRANSFORM_EXPAND;
#endif
png_set_filler(png_ptr, 0xFF, PNG_FILLER_AFTER);
png_set_filler(png_ptr, 0xFF, PNG_FILLER_AFTER);
png_read_png(png_ptr, info_ptr, png_transforms, NULL);
ltCloseResource(in);
png_get_IHDR(png_ptr, info_ptr, &uwidth, &uheight, &bit_depth, &color_type,
NULL, NULL, NULL);
width = (int)uwidth;
height = (int)uheight;
if (color_type & PNG_COLOR_MASK_ALPHA) {
has_alpha = true;
} else {
has_alpha = false;
}
if (bit_depth != 8) {
ltLog("Error: %s does not have bit depth 8 (in fact %d).\n", path, bit_depth);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_ptr);
return NULL;
}
rows = png_get_rows(png_ptr, info_ptr);
LTImageBuffer *imgbuf = new LTImageBuffer(name);
imgbuf->scaling = get_img_scaling(path);
// Check for bounding box chunk.
png_get_text(png_ptr, info_ptr, &text_ptr, &num_txt_chunks);
for (int i = 0; i < num_txt_chunks; i++) {
if (strcmp(text_ptr[i].key, BBCHUNK_KEY) == 0) {
has_bbchunk = true;
sscanf(text_ptr[i].text, BBCHUNK_FORMAT,
&imgbuf->width, &imgbuf->height,
&imgbuf->bb_left, &imgbuf->bb_bottom, &imgbuf->bb_right, &imgbuf->bb_top);
break;
}
}
// Compute the bounding box if no bounding box chunk found.
if (!has_bbchunk) {
if (has_alpha) {
compute_bbox(path, (LTpixel**)rows, width, height, &bb_left, &bb_top, &bb_right,
&bb_bottom);
} else {
// No alpha, so bbox calculation trivial.
bb_left = 0;
bb_top = 0;
bb_right = width - 1;
bb_bottom = height - 1;
}
imgbuf->width = width;
imgbuf->height = height;
imgbuf->bb_left = bb_left;
imgbuf->bb_top = height - bb_top - 1; // Normalize coordinate system.
imgbuf->bb_right = bb_right;
imgbuf->bb_bottom = height - bb_bottom - 1;
}
// Copy data to new LTImageBuffer.
int num_bb_pixels = imgbuf->num_bb_pixels();
int bb_width = imgbuf->bb_width();
LTpixel *pixels = new LTpixel[num_bb_pixels];
LTpixel *pxl_ptr = pixels;
if (has_bbchunk) {
// png contains only bounding box pixels so copy all of them.
for (int row = height - 1; row >= 0; row--) {
memcpy(pxl_ptr, &rows[row][0], bb_width * 4);
pxl_ptr += bb_width;
}
} else {
// Copy only the pixels in the bounding box.
for (int row = bb_bottom; row >= bb_top; row--) {
memcpy(pxl_ptr, &rows[row][bb_left * 4], bb_width * 4);
pxl_ptr += bb_width;
}
}
imgbuf->bb_pixels = pixels;
// Free libpng data (including rows).
png_destroy_read_struct(&png_ptr, &info_ptr, &end_ptr);
return imgbuf;
}
void ltWriteImage(const char *path, LTImageBuffer *img) {
FILE *out;
png_structp png_ptr;
png_infop info_ptr;
png_byte **rows;
int bb_height = img->bb_height();
int bb_width = img->bb_width();
// Open the file.
out = fopen(path, "wb");
if (out == NULL) {
ltLog("Error: Unable to open %s for writing: %s.\n", path, strerror(errno));
return;
}
// Setup.
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
png_init_io(png_ptr, out);
png_set_IHDR(png_ptr, info_ptr, bb_width, bb_height,
8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
// Record bounding box information in a private tEXt chunk.
png_text bbchunk;
char bbtext[128];
sprintf(bbtext, BBCHUNK_FORMAT, img->width, img->height,
img->bb_left, img->bb_bottom, img->bb_right, img->bb_top);
bbchunk.compression = PNG_TEXT_COMPRESSION_NONE;
bbchunk.key = (char*)BBCHUNK_KEY;
bbchunk.text = bbtext;
bbchunk.text_length = strlen(bbtext);
bbchunk.itxt_length = 0;
bbchunk.lang = 0;
bbchunk.lang_key = NULL;
png_set_text(png_ptr, info_ptr, &bbchunk, 1);
// Tell libpng where the data is.
rows = new png_byte*[bb_height];
LTpixel *pxl_ptr = img->bb_pixels;
for (int i = bb_height - 1; i >= 0; i--) {
rows[i] = (png_byte*)pxl_ptr;
pxl_ptr += bb_width;
}
png_set_rows(png_ptr, info_ptr, rows);
// Write image.
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL); //PNG_TRANSFORM_SWAP_ALPHA | PNG_TRANSFORM_BGR, NULL);
// Free libpng data.
png_destroy_write_struct(&png_ptr, &info_ptr);
delete[] rows;
fclose(out);
}
void ltPasteImage(LTImageBuffer *src, LTImageBuffer *dest, int x, int y, bool rotate) {
int src_width;
int src_height;
src_width = src->bb_width();
src_height = src->bb_height();
int dest_width = dest->bb_width();
int dest_height = dest->bb_height();
if (!rotate && (x + src_width > dest_width)) {
ltLog("%s too wide to be pasted into %s at x = %d",
src->name, dest->name, x);
return;
}
if (!rotate && (y + src_height > dest_height)) {
ltLog("%s too high to be pasted into %s at y = %d",
src->name, dest->name, y);
return;
}
if (rotate && (x + src_height > dest_width)) {
ltLog("%s too high to be pasted into %s at x = %d after rotation",
src->name, dest->name, x);
return;
}
if (rotate && (y + src_width > dest_height)) {
ltLog("%s too wide to be pasted into %s at y = %d after rotation",
src->name, dest->name, y);
return;
}
LTpixel *dest_ptr = dest->bb_pixels + y * dest_width + x;
if (rotate) {
LTpixel *src_ptr = src->bb_pixels + src_width - 1;
int src_row = 0;
int src_col = src_width - 1;
while (src_col >= 0) {
*dest_ptr = *src_ptr;
src_ptr += src_width;
dest_ptr++;
src_row++;
if (src_row >= src_height) {
src_col--;
src_row = 0;
dest_ptr += dest_width - src_height;
src_ptr = src->bb_pixels + src_col;
}
}
} else {
LTpixel *src_ptr = src->bb_pixels;
int src_row = 0;
while (src_row < src_height) {
memcpy(dest_ptr, src_ptr, src_width * 4);
src_ptr += src_width;
dest_ptr += dest_width;
src_row++;
}
}
}
//-----------------------------------------------------------------
LTImagePacker::LTImagePacker(int l, int b, int w, int h, int max) {
left = l;
bottom = b;
width = w;
height = h;
max_size = max;
occupant = NULL;
rotated = false;
hi_child = NULL;
lo_child = NULL;
}
LTImagePacker::~LTImagePacker() {
if (occupant != NULL) {
delete hi_child;
delete lo_child;
}
}
static bool pack_image(LTImagePacker *packer, LTImageBuffer *img) {
int pkr_w = packer->width;
int pkr_h = packer->height;
int img_w = img->bb_width() + 1; // add 1 pixel buffer.
int img_h = img->bb_height() + 1;
if (packer->occupant == NULL) {
bool fits_rotated = img_h <= pkr_w && img_w <= pkr_h;
bool fits_non_rotated = img_w <= pkr_w && img_h <= pkr_h;
if (!fits_rotated && !fits_non_rotated) {
return false;
}
bool should_rotate = false;
if (!fits_non_rotated) {
// XXX There are some unresolved issues with rotating images:
// - You need to know both the x and y coords of each corner
// of the texture quad. Knowing left, bottom, right and top
// is not enough. This makes using the tex_left, etc fields
// in Lua dangerous.
// - If the atlas width is different from the atlas height, then
// the texture coords are miscalculated when the images is
// rotated.
// Resolving these issues is possibly more trouble than it's worth.
//
// should_rotate = true;
return false;
}
int hi_l;
int hi_b;
int hi_w;
int hi_h;
int lo_l;
int lo_b;
int lo_w;
int lo_h;
if (should_rotate) {
hi_l = packer->left;
hi_b = packer->bottom + img_w;
hi_w = pkr_w;
hi_h = pkr_h - img_w;
lo_l = packer->left + img_h;
lo_b = packer->bottom;
lo_w = pkr_w - img_h;
lo_h = img_w;
} else {
hi_l = packer->left;
hi_b = packer->bottom + img_h;
hi_w = pkr_w;
hi_h = pkr_h - img_h;
lo_l = packer->left + img_w;
lo_b = packer->bottom;
lo_w = pkr_w - img_w;
lo_h = img_h;
}
packer->occupant = img;
packer->rotated = should_rotate;
packer->hi_child = new LTImagePacker(hi_l, hi_b, hi_w, hi_h, packer->max_size);
packer->lo_child = new LTImagePacker(lo_l, lo_b, lo_w, lo_h, packer->max_size);
return true;
}
return pack_image(packer->lo_child, img) || pack_image(packer->hi_child, img);
}
static int compare_img_bufs(const void *v1, const void *v2) {
LTImageBuffer **img1 = (LTImageBuffer **)v1;
LTImageBuffer **img2 = (LTImageBuffer **)v2;
int h1 = (*img1)->bb_height();
int h2 = (*img2)->bb_height();
if (h1 < h2) {
return -1;
} else if (h1 == h2) {
return 0;
} else {
return 1;
}
}
bool ltPackImage(LTImagePacker *packer, LTImageBuffer *img) {
if (pack_image(packer, img)) {
return true;
} else {
// Sort images and try again.
int n = packer->size() + 1;
bool fitted = true;
LTImagePacker *test_packer = new LTImagePacker(packer->left, packer->bottom,
packer->width, packer->height, packer->max_size);
LTImageBuffer **imgs = new LTImageBuffer *[n];
packer->getImages(imgs);
imgs[n - 1] = img;
qsort(imgs, n, sizeof(LTImageBuffer *), compare_img_bufs);
for (int i = n - 1; i >= 0; i--) {
if (!pack_image(test_packer, imgs[i])) {
fitted = false;
break;
}
}
if (fitted) {
packer->clear();
for (int i = n - 1; i >= 0; i--) {
pack_image(packer, imgs[i]);
}
}
test_packer->clear();
while (!fitted) {
// Sorting didn't help. Try doubling the area.
if (test_packer->width > test_packer->height) {
test_packer->height = test_packer->width;
} else {
test_packer->width *= 2;
}
if (test_packer->width <= test_packer->max_size) {
fitted = true;
for (int i = n - 1; i >= 0; i--) {
if (!pack_image(test_packer, imgs[i])) {
fitted = false;
break;
}
}
test_packer->clear();
if (fitted) {
packer->clear();
packer->width = test_packer->width;
packer->height = test_packer->height;
for (int i = n - 1; i >= 0; i--) {
pack_image(packer, imgs[i]);
}
}
} else {
break;
}
}
delete[] imgs;
delete test_packer;
return fitted;
}
}
void LTImagePacker::deleteOccupants() {
if (occupant != NULL) {
delete occupant;
occupant = NULL;
hi_child->deleteOccupants();
lo_child->deleteOccupants();
delete hi_child;
hi_child = NULL;
delete lo_child;
lo_child = NULL;
}
}
void LTImagePacker::clear() {
if (occupant != NULL) {
occupant = NULL;
hi_child->clear();
lo_child->clear();
delete hi_child;
hi_child = NULL;
delete lo_child;
lo_child = NULL;
}
}
int LTImagePacker::size() {
if (occupant != NULL) {
return hi_child->size() + lo_child->size() + 1;
} else {
return 0;
}
}
static void get_images(LTImagePacker *packer, int *i, LTImageBuffer **imgs) {
if (packer->occupant != NULL) {
imgs[*i] = packer->occupant;
*i = *i + 1;
get_images(packer->hi_child, i, imgs);
get_images(packer->lo_child, i, imgs);
}
}
void LTImagePacker::getImages(LTImageBuffer **imgs) {
int i = 0;
get_images(this, &i, imgs);
}
static void paste_packer_images(LTImageBuffer *img, LTImagePacker *packer) {
if (packer->occupant != NULL) {
ltPasteImage(packer->occupant, img, packer->left, packer->bottom, packer->rotated);
paste_packer_images(img, packer->lo_child);
paste_packer_images(img, packer->hi_child);
}
}
//-----------------------------------------------------------------
LTImageBuffer *ltCreateAtlasImage(const char *name, LTImagePacker *packer) {
int num_pixels = packer->width * packer->height;
LTImageBuffer *atlas = new LTImageBuffer(name);
atlas->width = packer->width;
atlas->height = packer->height;
atlas->bb_left = 0;
atlas->bb_right = packer->width - 1;
atlas->bb_top = packer->height - 1;
atlas->bb_bottom = 0;
atlas->bb_pixels = new LTpixel[num_pixels];
memset(atlas->bb_pixels, 0x00, num_pixels * 4);
paste_packer_images(atlas, packer);
return atlas;
}
LTImageBuffer *ltCreateEmptyImageBuffer(const char *name, int w, int h) {
int num_pixels = w * h;
LTImageBuffer *buf = new LTImageBuffer(name);
buf->width = w;
buf->height = h;
buf->bb_left = 0;
buf->bb_right = w - 1;
buf->bb_top = h - 1;
buf->bb_bottom = 0;
buf->bb_pixels = new LTpixel[num_pixels];
memset(buf->bb_pixels, 0x00, num_pixels * 4);
return buf;
}
//-----------------------------------------------------------------
LTTexturedNode::~LTTexturedNode() {
if (vertbuf != 0) {
ltDeleteVertBuffer(vertbuf);
}
if (texbuf != 0) {
ltDeleteVertBuffer(texbuf);
}
}
void LTTexturedNode::draw() {
ltEnableTexture(texture_id);
ltBindVertBuffer(vertbuf);
ltVertexPointer(2, LT_VERT_DATA_TYPE_FLOAT, 0, 0);
ltBindVertBuffer(texbuf);
ltTexCoordPointer(2, LT_VERT_DATA_TYPE_SHORT, 0, 0);
ltDrawArrays(LT_DRAWMODE_TRIANGLE_FAN, 0, 4);
}
static LTfloat get_wld_left(LTObject *obj) {
return ((LTTexturedNode*)obj)->world_vertices[0];
}
static LTfloat get_wld_bottom(LTObject *obj) {
return ((LTTexturedNode*)obj)->world_vertices[1];
}
static LTfloat get_wld_right(LTObject *obj) {
return ((LTTexturedNode*)obj)->world_vertices[2];
}
static LTfloat get_wld_top(LTObject *obj) {
return ((LTTexturedNode*)obj)->world_vertices[5];
}
static LTfloat get_tex_left(LTObject *obj) {
return ((LTTexturedNode*)obj)->tex_coords[0];
}
static LTfloat get_tex_bottom(LTObject *obj) {
return ((LTTexturedNode*)obj)->tex_coords[1];
}
static LTfloat get_tex_right(LTObject *obj) {
return ((LTTexturedNode*)obj)->tex_coords[2];
}
static LTfloat get_tex_top(LTObject *obj) {
return ((LTTexturedNode*)obj)->tex_coords[5];
}
LT_REGISTER_TYPE(LTTexturedNode, "lt.TexturedNode", "lt.SceneNode")
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, left, &get_wld_left, NULL);
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, bottom, &get_wld_bottom, NULL);
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, right, &get_wld_right, NULL);
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, top, &get_wld_top, NULL);
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, tex_left, &get_tex_left, NULL);
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, tex_bottom, &get_tex_bottom, NULL);
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, tex_right, &get_tex_right, NULL);
LT_REGISTER_PROPERTY_FLOAT(LTTexturedNode, tex_top, &get_tex_top, NULL);
static int to_mesh(lua_State *L) {
ltLuaCheckNArgs(L, 1);
LTTexturedNode *img = lt_expect_LTTexturedNode(L, 1);
LTMesh *mesh = new (lt_alloc_LTMesh(L)) LTMesh(img);
mesh->texture_ref = ltLuaAddRef(L, -1, 1); // add ref from mesh to image
return 1;
}
LT_REGISTER_METHOD(LTTexturedNode, Mesh, to_mesh);
LTImage::LTImage(LTAtlas *atls, int atlas_w, int atlas_h, LTImagePacker *packer) {
if (packer->occupant == NULL) {
ltLog("Packer occupant is NULL");
ltAbort();
}
LTfloat scaling = packer->occupant->scaling;
LTfloat pix_w = ltGetPixelWidth() / scaling;
LTfloat pix_h = ltGetPixelHeight() / scaling;
atlas = atls;
atlas->ref_count++;
texture_id = atlas->texture_id;
rotated = packer->rotated;
int texel_w = LT_MAX_TEX_COORD / atlas_w;
int texel_h = LT_MAX_TEX_COORD / atlas_h;
LTtexcoord tex_left = packer->left * texel_w;
LTtexcoord tex_bottom = packer->bottom * texel_h;
LTtexcoord tex_width = packer->occupant->bb_width() * texel_w;
LTtexcoord tex_height = packer->occupant->bb_height() * texel_h;
LTfloat bb_left = (LTfloat)packer->occupant->bb_left * pix_w;
LTfloat bb_bottom = (LTfloat)packer->occupant->bb_bottom * pix_h;
bb_width = (LTfloat)packer->occupant->bb_width() * pix_w;
bb_height = (LTfloat)packer->occupant->bb_height() * pix_h;
orig_width = (LTfloat)packer->occupant->width * pix_w;
orig_height = (LTfloat)packer->occupant->height * pix_h;
pixel_width = packer->occupant->width;
pixel_height = packer->occupant->height;
LTfloat world_left = bb_left - orig_width * 0.5f;
LTfloat world_bottom = bb_bottom - orig_height * 0.5f;
LTfloat world_top = world_bottom + bb_height;
LTfloat world_right = world_left + bb_width;
world_vertices[0] = world_left;
world_vertices[1] = world_bottom;
world_vertices[2] = world_right;
world_vertices[3] = world_bottom;
world_vertices[4] = world_right;
world_vertices[5] = world_top;
world_vertices[6] = world_left;
world_vertices[7] = world_top;
vertbuf = ltGenVertBuffer();
ltBindVertBuffer(vertbuf);
ltStaticVertBufferData(sizeof(LTfloat) * 8, world_vertices);
if (rotated) {
assert(false); // XXX This code is broken and should not be invoked
tex_coords[0] = tex_left + tex_height; tex_coords[1] = tex_bottom + tex_width;
tex_coords[2] = tex_left + tex_height; tex_coords[3] = tex_bottom;
tex_coords[4] = tex_left; tex_coords[5] = tex_bottom;
tex_coords[6] = tex_left; tex_coords[7] = tex_bottom + tex_width;
} else {
tex_coords[0] = tex_left; tex_coords[1] = tex_bottom;
tex_coords[2] = tex_left + tex_width; tex_coords[3] = tex_bottom;
tex_coords[4] = tex_left + tex_width; tex_coords[5] = tex_bottom + tex_height;
tex_coords[6] = tex_left; tex_coords[7] = tex_bottom + tex_height;
}
texbuf = ltGenVertBuffer();
ltBindVertBuffer(texbuf);
ltStaticVertBufferData(sizeof(LTtexcoord) * 8, tex_coords);
}
LTImage::~LTImage() {
atlas->ref_count--;
if (atlas->ref_count <= 0) {
delete atlas;
}
}
static LTfloat get_width(LTObject *obj) {
return ((LTImage*)obj)->orig_width;
}
static LTfloat get_height(LTObject *obj) {
return ((LTImage*)obj)->orig_height;
}
LT_REGISTER_TYPE(LTImage, "lt.Image", "lt.TexturedNode")
LT_REGISTER_PROPERTY_FLOAT(LTImage, width, &get_width, NULL)
LT_REGISTER_PROPERTY_FLOAT(LTImage, height, &get_height, NULL)
| 31.734146 | 117 | 0.594535 | [
"mesh"
] |
4f7432cd657aa9d2bdbb7ffe2f4743b7edc31c44 | 51,642 | cpp | C++ | editor/editor_help.cpp | dgap97/godot | fbaaf11531392598a2ba8164b62bbfb72b5acaea | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2021-09-30T15:21:10.000Z | 2021-09-30T15:21:10.000Z | editor/editor_help.cpp | dgap97/godot | fbaaf11531392598a2ba8164b62bbfb72b5acaea | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 9 | 2019-11-07T20:47:48.000Z | 2019-12-12T13:25:14.000Z | editor/editor_help.cpp | dgap97/godot | fbaaf11531392598a2ba8164b62bbfb72b5acaea | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2019-10-24T20:17:21.000Z | 2019-10-24T20:17:21.000Z | /*************************************************************************/
/* editor_help.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_help.h"
#include "core/os/input.h"
#include "core/os/keyboard.h"
#include "doc_data_compressed.gen.h"
#include "editor/plugins/script_editor_plugin.h"
#include "editor_node.h"
#include "editor_settings.h"
#define CONTRIBUTE_URL "https://docs.godotengine.org/en/latest/community/contributing/updating_the_class_reference.html"
#define CONTRIBUTE2_URL "https://github.com/godotengine/godot-docs"
#define REQUEST_URL "https://github.com/godotengine/godot-docs/issues/new"
DocData *EditorHelp::doc = NULL;
void EditorHelp::_init_colors() {
title_color = get_color("accent_color", "Editor");
text_color = get_color("default_color", "RichTextLabel");
headline_color = get_color("headline_color", "EditorHelp");
base_type_color = title_color.linear_interpolate(text_color, 0.5);
comment_color = text_color * Color(1, 1, 1, 0.4);
symbol_color = comment_color;
value_color = text_color * Color(1, 1, 1, 0.6);
qualifier_color = text_color * Color(1, 1, 1, 0.8);
type_color = get_color("accent_color", "Editor").linear_interpolate(text_color, 0.5);
class_desc->add_color_override("selection_color", get_color("accent_color", "Editor") * Color(1, 1, 1, 0.4));
class_desc->add_constant_override("line_separation", Math::round(5 * EDSCALE));
}
void EditorHelp::_unhandled_key_input(const Ref<InputEvent> &p_ev) {
if (!is_visible_in_tree())
return;
Ref<InputEventKey> k = p_ev;
if (k.is_valid() && k->get_control() && k->get_scancode() == KEY_F) {
search->grab_focus();
search->select_all();
}
}
void EditorHelp::_search(bool p_search_previous) {
if (p_search_previous)
find_bar->search_prev();
else
find_bar->search_next();
}
void EditorHelp::_class_list_select(const String &p_select) {
_goto_desc(p_select);
}
void EditorHelp::_class_desc_select(const String &p_select) {
if (p_select.begins_with("$")) { //enum
String select = p_select.substr(1, p_select.length());
String class_name;
if (select.find(".") != -1) {
class_name = select.get_slice(".", 0);
select = select.get_slice(".", 1);
} else {
class_name = "@GlobalScope";
}
emit_signal("go_to_help", "class_enum:" + class_name + ":" + select);
return;
} else if (p_select.begins_with("#")) {
emit_signal("go_to_help", "class_name:" + p_select.substr(1, p_select.length()));
return;
} else if (p_select.begins_with("@")) {
int tag_end = p_select.find(" ");
String tag = p_select.substr(1, tag_end - 1);
String link = p_select.substr(tag_end + 1, p_select.length()).lstrip(" ");
String topic;
Map<String, int> *table = NULL;
if (tag == "method") {
topic = "class_method";
table = &this->method_line;
} else if (tag == "member") {
topic = "class_property";
table = &this->property_line;
} else if (tag == "enum") {
topic = "class_enum";
table = &this->enum_line;
} else if (tag == "signal") {
topic = "class_signal";
table = &this->signal_line;
} else if (tag == "constant") {
topic = "class_constant";
table = &this->constant_line;
} else {
return;
}
if (link.find(".") != -1) {
emit_signal("go_to_help", topic + ":" + link.get_slice(".", 0) + ":" + link.get_slice(".", 1));
} else {
if (table->has(link)) {
// Found in the current page
class_desc->scroll_to_line((*table)[link]);
} else {
if (topic == "class_enum") {
// Try to find the enum in @GlobalScope
const DocData::ClassDoc &cd = doc->class_list["@GlobalScope"];
for (int i = 0; i < cd.constants.size(); i++) {
if (cd.constants[i].enumeration == link) {
// Found in @GlobalScope
emit_signal("go_to_help", topic + ":@GlobalScope:" + link);
break;
}
}
} else if (topic == "class_constant") {
// Try to find the constant in @GlobalScope
const DocData::ClassDoc &cd = doc->class_list["@GlobalScope"];
for (int i = 0; i < cd.constants.size(); i++) {
if (cd.constants[i].name == link) {
// Found in @GlobalScope
emit_signal("go_to_help", topic + ":@GlobalScope:" + link);
break;
}
}
}
}
}
} else if (p_select.begins_with("http")) {
OS::get_singleton()->shell_open(p_select);
}
}
void EditorHelp::_class_desc_input(const Ref<InputEvent> &p_input) {
}
void EditorHelp::_class_desc_resized() {
// Add extra horizontal margins for better readability.
// The margins increase as the width of the editor help container increases.
Ref<Font> doc_code_font = get_font("doc_source", "EditorFonts");
real_t char_width = doc_code_font->get_char_size('x').width;
const int display_margin = MAX(30 * EDSCALE, get_parent_anchorable_rect().size.width - char_width * 120 * EDSCALE) * 0.5;
Ref<StyleBox> class_desc_stylebox = EditorNode::get_singleton()->get_theme_base()->get_stylebox("normal", "RichTextLabel")->duplicate();
class_desc_stylebox->set_default_margin(MARGIN_LEFT, display_margin);
class_desc_stylebox->set_default_margin(MARGIN_RIGHT, display_margin);
class_desc->add_style_override("normal", class_desc_stylebox);
}
void EditorHelp::_add_type(const String &p_type, const String &p_enum) {
String t = p_type;
if (t == "")
t = "void";
bool can_ref = (t != "int" && t != "real" && t != "bool" && t != "void") || p_enum != String();
if (p_enum != String()) {
if (p_enum.get_slice_count(".") > 1) {
t = p_enum.get_slice(".", 1);
} else {
t = p_enum.get_slice(".", 0);
}
}
const Color text_color = get_color("default_color", "RichTextLabel");
const Color type_color = get_color("accent_color", "Editor").linear_interpolate(text_color, 0.5);
class_desc->push_color(type_color);
if (can_ref) {
if (p_enum == "") {
class_desc->push_meta("#" + t); //class
} else {
class_desc->push_meta("$" + p_enum); //class
}
}
class_desc->add_text(t);
if (can_ref)
class_desc->pop();
class_desc->pop();
}
String EditorHelp::_fix_constant(const String &p_constant) const {
if (p_constant.strip_edges() == "4294967295") {
return "0xFFFFFFFF";
}
if (p_constant.strip_edges() == "2147483647") {
return "0x7FFFFFFF";
}
if (p_constant.strip_edges() == "1048575") {
return "0xFFFFF";
}
return p_constant;
}
void EditorHelp::_add_method(const DocData::MethodDoc &p_method, bool p_overview) {
method_line[p_method.name] = class_desc->get_line_count() - 2; //gets overridden if description
const bool is_vararg = p_method.qualifiers.find("vararg") != -1;
if (p_overview) {
class_desc->push_cell();
class_desc->push_align(RichTextLabel::ALIGN_RIGHT);
}
_add_type(p_method.return_type, p_method.return_enum);
if (p_overview) {
class_desc->pop(); //align
class_desc->pop(); //cell
class_desc->push_cell();
} else {
class_desc->add_text(" ");
}
if (p_overview && p_method.description != "") {
class_desc->push_meta("@method " + p_method.name);
}
class_desc->push_color(headline_color);
_add_text(p_method.name);
class_desc->pop();
if (p_overview && p_method.description != "") {
class_desc->pop(); //meta
}
class_desc->push_color(symbol_color);
class_desc->add_text("(");
class_desc->pop();
for (int j = 0; j < p_method.arguments.size(); j++) {
class_desc->push_color(text_color);
if (j > 0)
class_desc->add_text(", ");
_add_text(p_method.arguments[j].name);
class_desc->add_text(": ");
_add_type(p_method.arguments[j].type, p_method.arguments[j].enumeration);
if (p_method.arguments[j].default_value != "") {
class_desc->push_color(symbol_color);
class_desc->add_text(" = ");
class_desc->pop();
class_desc->push_color(value_color);
_add_text(_fix_constant(p_method.arguments[j].default_value));
class_desc->pop();
}
class_desc->pop();
}
if (is_vararg) {
class_desc->push_color(text_color);
if (p_method.arguments.size())
class_desc->add_text(", ");
class_desc->push_color(symbol_color);
class_desc->add_text("...");
class_desc->pop();
class_desc->pop();
}
class_desc->push_color(symbol_color);
class_desc->add_text(")");
class_desc->pop();
if (p_method.qualifiers != "") {
class_desc->push_color(qualifier_color);
class_desc->add_text(" ");
_add_text(p_method.qualifiers);
class_desc->pop();
}
if (p_overview)
class_desc->pop(); //cell
}
Error EditorHelp::_goto_desc(const String &p_class, int p_vscr) {
if (!doc->class_list.has(p_class))
return ERR_DOES_NOT_EXIST;
select_locked = true;
class_desc->show();
description_line = 0;
if (p_class == edited_class)
return OK; //already there
edited_class = p_class;
_update_doc();
return OK;
}
void EditorHelp::_update_doc() {
if (!doc->class_list.has(edited_class))
return;
scroll_locked = true;
class_desc->clear();
method_line.clear();
section_line.clear();
_init_colors();
DocData::ClassDoc cd = doc->class_list[edited_class]; //make a copy, so we can sort without worrying
Ref<Font> doc_font = get_font("doc", "EditorFonts");
Ref<Font> doc_bold_font = get_font("doc_bold", "EditorFonts");
Ref<Font> doc_title_font = get_font("doc_title", "EditorFonts");
Ref<Font> doc_code_font = get_font("doc_source", "EditorFonts");
String link_color_text = title_color.to_html(false);
// Class name
section_line.push_back(Pair<String, int>(TTR("Top"), 0));
class_desc->push_font(doc_title_font);
class_desc->push_color(title_color);
class_desc->add_text(TTR("Class:") + " ");
class_desc->push_color(headline_color);
_add_text(edited_class);
class_desc->pop();
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
// Inheritance tree
// Ascendents
if (cd.inherits != "") {
class_desc->push_color(title_color);
class_desc->push_font(doc_font);
class_desc->add_text(TTR("Inherits:") + " ");
class_desc->pop();
String inherits = cd.inherits;
while (inherits != "") {
_add_type(inherits);
inherits = doc->class_list[inherits].inherits;
if (inherits != "") {
class_desc->add_text(" < ");
}
}
class_desc->pop();
class_desc->add_newline();
}
// Descendents
if (ClassDB::class_exists(cd.name)) {
bool found = false;
bool prev = false;
for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
if (E->get().inherits == cd.name) {
if (!found) {
class_desc->push_color(title_color);
class_desc->push_font(doc_font);
class_desc->add_text(TTR("Inherited by:") + " ");
class_desc->pop();
found = true;
}
if (prev) {
class_desc->add_text(" , ");
}
_add_type(E->get().name);
prev = true;
}
}
if (found)
class_desc->pop();
class_desc->add_newline();
}
class_desc->add_newline();
class_desc->add_newline();
// Brief description
if (cd.brief_description != "") {
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Brief Description"));
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->push_color(text_color);
class_desc->push_font(doc_font);
class_desc->push_indent(1);
_add_text(cd.brief_description);
class_desc->pop();
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->add_newline();
}
// Properties overview
Set<String> skip_methods;
bool property_descr = false;
if (cd.properties.size()) {
section_line.push_back(Pair<String, int>(TTR("Properties"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Properties"));
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->push_font(doc_code_font);
class_desc->push_indent(1);
class_desc->push_table(2);
class_desc->set_table_column_expand(1, 1);
for (int i = 0; i < cd.properties.size(); i++) {
property_line[cd.properties[i].name] = class_desc->get_line_count() - 2; //gets overridden if description
class_desc->push_cell();
class_desc->push_align(RichTextLabel::ALIGN_RIGHT);
class_desc->push_font(doc_code_font);
_add_type(cd.properties[i].type, cd.properties[i].enumeration);
class_desc->pop();
class_desc->pop();
class_desc->pop();
bool describe = false;
if (cd.properties[i].setter != "") {
skip_methods.insert(cd.properties[i].setter);
describe = true;
}
if (cd.properties[i].getter != "") {
skip_methods.insert(cd.properties[i].getter);
describe = true;
}
if (cd.properties[i].description != "") {
describe = true;
}
if (cd.properties[i].overridden) {
describe = false;
}
class_desc->push_cell();
class_desc->push_font(doc_code_font);
class_desc->push_color(headline_color);
if (describe) {
class_desc->push_meta("@member " + cd.properties[i].name);
}
_add_text(cd.properties[i].name);
if (describe) {
class_desc->pop();
property_descr = true;
}
if (cd.properties[i].default_value != "") {
class_desc->push_color(symbol_color);
class_desc->add_text(cd.properties[i].overridden ? " [override: " : " [default: ");
class_desc->pop();
class_desc->push_color(value_color);
_add_text(_fix_constant(cd.properties[i].default_value));
class_desc->pop();
class_desc->push_color(symbol_color);
class_desc->add_text("]");
class_desc->pop();
}
class_desc->pop();
class_desc->pop();
class_desc->pop();
}
class_desc->pop(); //table
class_desc->pop();
class_desc->pop(); // font
class_desc->add_newline();
class_desc->add_newline();
}
// Methods overview
bool method_descr = false;
bool sort_methods = EditorSettings::get_singleton()->get("text_editor/help/sort_functions_alphabetically");
Vector<DocData::MethodDoc> methods;
for (int i = 0; i < cd.methods.size(); i++) {
if (skip_methods.has(cd.methods[i].name))
continue;
methods.push_back(cd.methods[i]);
}
if (methods.size()) {
if (sort_methods)
methods.sort();
section_line.push_back(Pair<String, int>(TTR("Methods"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Methods"));
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->push_font(doc_code_font);
class_desc->push_indent(1);
class_desc->push_table(2);
class_desc->set_table_column_expand(1, 1);
bool any_previous = false;
for (int pass = 0; pass < 2; pass++) {
Vector<DocData::MethodDoc> m;
for (int i = 0; i < methods.size(); i++) {
const String &q = methods[i].qualifiers;
if ((pass == 0 && q.find("virtual") != -1) || (pass == 1 && q.find("virtual") == -1)) {
m.push_back(methods[i]);
}
}
if (any_previous && !m.empty()) {
class_desc->push_cell();
class_desc->pop(); //cell
class_desc->push_cell();
class_desc->pop(); //cell
}
String group_prefix;
for (int i = 0; i < m.size(); i++) {
const String new_prefix = m[i].name.substr(0, 3);
bool is_new_group = false;
if (i < m.size() - 1 && new_prefix == m[i + 1].name.substr(0, 3) && new_prefix != group_prefix) {
is_new_group = i > 0;
group_prefix = new_prefix;
} else if (group_prefix != "" && new_prefix != group_prefix) {
is_new_group = true;
group_prefix = "";
}
if (is_new_group && pass == 1) {
class_desc->push_cell();
class_desc->pop(); //cell
class_desc->push_cell();
class_desc->pop(); //cell
}
if (m[i].description != "") {
method_descr = true;
}
_add_method(m[i], true);
}
any_previous = !m.empty();
}
class_desc->pop(); //table
class_desc->pop();
class_desc->pop(); // font
class_desc->add_newline();
class_desc->add_newline();
}
// Theme properties
if (cd.theme_properties.size()) {
section_line.push_back(Pair<String, int>(TTR("Theme Properties"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Theme Properties"));
class_desc->pop();
class_desc->pop();
class_desc->push_indent(1);
class_desc->push_table(2);
class_desc->set_table_column_expand(1, 1);
for (int i = 0; i < cd.theme_properties.size(); i++) {
theme_property_line[cd.theme_properties[i].name] = class_desc->get_line_count() - 2; //gets overridden if description
class_desc->push_cell();
class_desc->push_align(RichTextLabel::ALIGN_RIGHT);
class_desc->push_font(doc_code_font);
_add_type(cd.theme_properties[i].type);
class_desc->pop();
class_desc->pop();
class_desc->pop();
class_desc->push_cell();
class_desc->push_font(doc_code_font);
class_desc->push_color(headline_color);
_add_text(cd.theme_properties[i].name);
class_desc->pop();
if (cd.theme_properties[i].default_value != "") {
class_desc->push_color(symbol_color);
class_desc->add_text(" [default: ");
class_desc->pop();
class_desc->push_color(value_color);
_add_text(_fix_constant(cd.theme_properties[i].default_value));
class_desc->pop();
class_desc->push_color(symbol_color);
class_desc->add_text("]");
class_desc->pop();
}
class_desc->pop();
if (cd.theme_properties[i].description != "") {
class_desc->push_font(doc_font);
class_desc->add_text(" ");
class_desc->push_color(comment_color);
_add_text(cd.theme_properties[i].description);
class_desc->pop();
class_desc->pop();
}
class_desc->pop(); // cell
}
class_desc->pop(); // table
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
}
// Signals
if (cd.signals.size()) {
if (sort_methods) {
cd.signals.sort();
}
section_line.push_back(Pair<String, int>(TTR("Signals"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Signals"));
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->push_indent(1);
for (int i = 0; i < cd.signals.size(); i++) {
signal_line[cd.signals[i].name] = class_desc->get_line_count() - 2; //gets overridden if description
class_desc->push_font(doc_code_font); // monofont
class_desc->push_color(headline_color);
_add_text(cd.signals[i].name);
class_desc->pop();
class_desc->push_color(symbol_color);
class_desc->add_text("(");
class_desc->pop();
for (int j = 0; j < cd.signals[i].arguments.size(); j++) {
class_desc->push_color(text_color);
if (j > 0)
class_desc->add_text(", ");
_add_text(cd.signals[i].arguments[j].name);
class_desc->add_text(": ");
_add_type(cd.signals[i].arguments[j].type);
if (cd.signals[i].arguments[j].default_value != "") {
class_desc->push_color(symbol_color);
class_desc->add_text(" = ");
class_desc->pop();
_add_text(cd.signals[i].arguments[j].default_value);
}
class_desc->pop();
}
class_desc->push_color(symbol_color);
class_desc->add_text(")");
class_desc->pop();
class_desc->pop(); // end monofont
if (cd.signals[i].description != "") {
class_desc->push_font(doc_font);
class_desc->push_color(comment_color);
class_desc->push_indent(1);
_add_text(cd.signals[i].description);
class_desc->pop(); // indent
class_desc->pop();
class_desc->pop(); // font
}
class_desc->add_newline();
class_desc->add_newline();
}
class_desc->pop();
class_desc->add_newline();
}
// Constants and enums
if (cd.constants.size()) {
Map<String, Vector<DocData::ConstantDoc> > enums;
Vector<DocData::ConstantDoc> constants;
for (int i = 0; i < cd.constants.size(); i++) {
if (cd.constants[i].enumeration != String()) {
if (!enums.has(cd.constants[i].enumeration)) {
enums[cd.constants[i].enumeration] = Vector<DocData::ConstantDoc>();
}
enums[cd.constants[i].enumeration].push_back(cd.constants[i]);
} else {
constants.push_back(cd.constants[i]);
}
}
// Enums
if (enums.size()) {
section_line.push_back(Pair<String, int>(TTR("Enumerations"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Enumerations"));
class_desc->pop();
class_desc->pop();
class_desc->push_indent(1);
class_desc->add_newline();
for (Map<String, Vector<DocData::ConstantDoc> >::Element *E = enums.front(); E; E = E->next()) {
enum_line[E->key()] = class_desc->get_line_count() - 2;
class_desc->push_color(title_color);
class_desc->add_text(TTR("enum "));
class_desc->pop();
class_desc->push_font(doc_code_font);
String e = E->key();
if (e.get_slice_count(".")) {
e = e.get_slice(".", 1);
}
class_desc->push_color(headline_color);
class_desc->add_text(e);
class_desc->pop();
class_desc->pop();
class_desc->push_color(symbol_color);
class_desc->add_text(":");
class_desc->pop();
class_desc->add_newline();
class_desc->push_indent(1);
Vector<DocData::ConstantDoc> enum_list = E->get();
Map<String, int> enumValuesContainer;
int enumStartingLine = enum_line[E->key()];
for (int i = 0; i < enum_list.size(); i++) {
if (cd.name == "@GlobalScope")
enumValuesContainer[enum_list[i].name] = enumStartingLine;
// Add the enum constant line to the constant_line map so we can locate it as a constant
constant_line[enum_list[i].name] = class_desc->get_line_count() - 2;
class_desc->push_font(doc_code_font);
class_desc->push_color(headline_color);
_add_text(enum_list[i].name);
class_desc->pop();
class_desc->push_color(symbol_color);
class_desc->add_text(" = ");
class_desc->pop();
class_desc->push_color(value_color);
_add_text(_fix_constant(enum_list[i].value));
class_desc->pop();
class_desc->pop();
if (enum_list[i].description != "") {
class_desc->push_font(doc_font);
//class_desc->add_text(" ");
class_desc->push_indent(1);
class_desc->push_color(comment_color);
_add_text(enum_list[i].description);
class_desc->pop();
class_desc->pop();
class_desc->pop(); // indent
class_desc->add_newline();
}
class_desc->add_newline();
}
if (cd.name == "@GlobalScope")
enum_values_line[E->key()] = enumValuesContainer;
class_desc->pop();
class_desc->add_newline();
}
class_desc->pop();
class_desc->add_newline();
}
// Constants
if (constants.size()) {
section_line.push_back(Pair<String, int>(TTR("Constants"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Constants"));
class_desc->pop();
class_desc->pop();
class_desc->push_indent(1);
class_desc->add_newline();
for (int i = 0; i < constants.size(); i++) {
constant_line[constants[i].name] = class_desc->get_line_count() - 2;
class_desc->push_font(doc_code_font);
if (constants[i].value.begins_with("Color(") && constants[i].value.ends_with(")")) {
String stripped = constants[i].value.replace(" ", "").replace("Color(", "").replace(")", "");
Vector<float> color = stripped.split_floats(",");
if (color.size() >= 3) {
class_desc->push_color(Color(color[0], color[1], color[2]));
static const CharType prefix[3] = { 0x25CF /* filled circle */, ' ', 0 };
class_desc->add_text(String(prefix));
class_desc->pop();
}
}
class_desc->push_color(headline_color);
_add_text(constants[i].name);
class_desc->pop();
class_desc->push_color(symbol_color);
class_desc->add_text(" = ");
class_desc->pop();
class_desc->push_color(value_color);
_add_text(_fix_constant(constants[i].value));
class_desc->pop();
class_desc->pop();
if (constants[i].description != "") {
class_desc->push_font(doc_font);
class_desc->push_indent(1);
class_desc->push_color(comment_color);
_add_text(constants[i].description);
class_desc->pop();
class_desc->pop();
class_desc->pop(); // indent
class_desc->add_newline();
}
class_desc->add_newline();
}
class_desc->pop();
class_desc->add_newline();
}
}
// Class description
if (cd.description != "") {
section_line.push_back(Pair<String, int>(TTR("Class Description"), class_desc->get_line_count() - 2));
description_line = class_desc->get_line_count() - 2;
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Class Description"));
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->push_color(text_color);
class_desc->push_font(doc_font);
class_desc->push_indent(1);
_add_text(cd.description);
class_desc->pop();
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->add_newline();
}
// Online tutorials
{
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Online Tutorials"));
class_desc->pop();
class_desc->pop();
class_desc->push_indent(1);
class_desc->push_font(doc_code_font);
class_desc->add_newline();
// class_desc->add_newline();
if (cd.tutorials.size() != 0) {
for (int i = 0; i < cd.tutorials.size(); i++) {
String link = cd.tutorials[i];
String linktxt = link;
int seppos = linktxt.find("//");
if (seppos != -1) {
linktxt = link.right(seppos + 2);
}
class_desc->push_color(symbol_color);
class_desc->append_bbcode("[url=" + link + "]" + linktxt + "[/url]");
class_desc->pop();
class_desc->add_newline();
}
} else {
class_desc->push_color(comment_color);
class_desc->append_bbcode(TTR("There are currently no tutorials for this class, you can [color=$color][url=$url]contribute one[/url][/color] or [color=$color][url=$url2]request one[/url][/color].").replace("$url2", REQUEST_URL).replace("$url", CONTRIBUTE2_URL).replace("$color", link_color_text));
class_desc->pop();
}
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
}
// Property descriptions
if (property_descr) {
section_line.push_back(Pair<String, int>(TTR("Property Descriptions"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Property Descriptions"));
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
for (int i = 0; i < cd.properties.size(); i++) {
if (cd.properties[i].overridden)
continue;
property_line[cd.properties[i].name] = class_desc->get_line_count() - 2;
class_desc->push_table(2);
class_desc->set_table_column_expand(1, 1);
class_desc->push_cell();
class_desc->push_font(doc_code_font);
_add_type(cd.properties[i].type, cd.properties[i].enumeration);
class_desc->add_text(" ");
class_desc->pop(); // font
class_desc->pop(); // cell
class_desc->push_cell();
class_desc->push_font(doc_code_font);
class_desc->push_color(headline_color);
_add_text(cd.properties[i].name);
class_desc->pop(); // color
if (cd.properties[i].default_value != "") {
class_desc->push_color(symbol_color);
class_desc->add_text(" [default: ");
class_desc->pop(); // color
class_desc->push_color(value_color);
_add_text(_fix_constant(cd.properties[i].default_value));
class_desc->pop(); // color
class_desc->push_color(symbol_color);
class_desc->add_text("]");
class_desc->pop(); // color
}
class_desc->pop(); // font
class_desc->pop(); // cell
if (cd.properties[i].setter != "") {
class_desc->push_cell();
class_desc->pop(); // cell
class_desc->push_cell();
class_desc->push_font(doc_code_font);
class_desc->push_color(text_color);
class_desc->add_text(cd.properties[i].setter + "(value)");
class_desc->pop(); // color
class_desc->push_color(comment_color);
class_desc->add_text(" setter");
class_desc->pop(); // color
class_desc->pop(); // font
class_desc->pop(); // cell
}
if (cd.properties[i].getter != "") {
class_desc->push_cell();
class_desc->pop(); // cell
class_desc->push_cell();
class_desc->push_font(doc_code_font);
class_desc->push_color(text_color);
class_desc->add_text(cd.properties[i].getter + "()");
class_desc->pop(); //color
class_desc->push_color(comment_color);
class_desc->add_text(" getter");
class_desc->pop(); //color
class_desc->pop(); //font
class_desc->pop(); //cell
}
class_desc->pop(); // table
class_desc->add_newline();
class_desc->add_newline();
class_desc->push_color(text_color);
class_desc->push_font(doc_font);
class_desc->push_indent(1);
if (cd.properties[i].description.strip_edges() != String()) {
_add_text(cd.properties[i].description);
} else {
class_desc->add_image(get_icon("Error", "EditorIcons"));
class_desc->add_text(" ");
class_desc->push_color(comment_color);
class_desc->append_bbcode(TTR("There is currently no description for this property. Please help us by [color=$color][url=$url]contributing one[/url][/color]!").replace("$url", CONTRIBUTE_URL).replace("$color", link_color_text));
class_desc->pop();
}
class_desc->pop();
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->add_newline();
}
}
// Method descriptions
if (method_descr) {
section_line.push_back(Pair<String, int>(TTR("Method Descriptions"), class_desc->get_line_count() - 2));
class_desc->push_color(title_color);
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Method Descriptions"));
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
for (int pass = 0; pass < 2; pass++) {
Vector<DocData::MethodDoc> methods_filtered;
for (int i = 0; i < methods.size(); i++) {
const String &q = methods[i].qualifiers;
if ((pass == 0 && q.find("virtual") != -1) || (pass == 1 && q.find("virtual") == -1)) {
methods_filtered.push_back(methods[i]);
}
}
for (int i = 0; i < methods_filtered.size(); i++) {
class_desc->push_font(doc_code_font);
_add_method(methods_filtered[i], false);
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->push_color(text_color);
class_desc->push_font(doc_font);
class_desc->push_indent(1);
if (methods_filtered[i].description.strip_edges() != String()) {
_add_text(methods_filtered[i].description);
} else {
class_desc->add_image(get_icon("Error", "EditorIcons"));
class_desc->add_text(" ");
class_desc->push_color(comment_color);
class_desc->append_bbcode(TTR("There is currently no description for this method. Please help us by [color=$color][url=$url]contributing one[/url][/color]!").replace("$url", CONTRIBUTE_URL).replace("$color", link_color_text));
class_desc->pop();
}
class_desc->pop();
class_desc->pop();
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
class_desc->add_newline();
}
}
}
scroll_locked = false;
}
void EditorHelp::_request_help(const String &p_string) {
Error err = _goto_desc(p_string);
if (err == OK) {
EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT);
}
//100 palabras
}
void EditorHelp::_help_callback(const String &p_topic) {
String what = p_topic.get_slice(":", 0);
String clss = p_topic.get_slice(":", 1);
String name;
if (p_topic.get_slice_count(":") == 3)
name = p_topic.get_slice(":", 2);
_request_help(clss); //first go to class
int line = 0;
if (what == "class_desc") {
line = description_line;
} else if (what == "class_signal") {
if (signal_line.has(name))
line = signal_line[name];
} else if (what == "class_method" || what == "class_method_desc") {
if (method_line.has(name))
line = method_line[name];
} else if (what == "class_property") {
if (property_line.has(name))
line = property_line[name];
} else if (what == "class_enum") {
if (enum_line.has(name))
line = enum_line[name];
} else if (what == "class_theme_item") {
if (theme_property_line.has(name))
line = theme_property_line[name];
} else if (what == "class_constant") {
if (constant_line.has(name))
line = constant_line[name];
} else if (what == "class_global") {
if (constant_line.has(name))
line = constant_line[name];
else {
Map<String, Map<String, int> >::Element *iter = enum_values_line.front();
while (true) {
if (iter->value().has(name)) {
line = iter->value()[name];
break;
} else if (iter == enum_values_line.back())
break;
else
iter = iter->next();
}
}
}
class_desc->call_deferred("scroll_to_line", line);
}
static void _add_text_to_rt(const String &p_bbcode, RichTextLabel *p_rt) {
DocData *doc = EditorHelp::get_doc_data();
String base_path;
Ref<Font> doc_font = p_rt->get_font("doc", "EditorFonts");
Ref<Font> doc_bold_font = p_rt->get_font("doc_bold", "EditorFonts");
Ref<Font> doc_code_font = p_rt->get_font("doc_source", "EditorFonts");
Color font_color_hl = p_rt->get_color("headline_color", "EditorHelp");
Color accent_color = p_rt->get_color("accent_color", "Editor");
Color link_color = accent_color.linear_interpolate(font_color_hl, 0.8);
Color code_color = accent_color.linear_interpolate(font_color_hl, 0.6);
String bbcode = p_bbcode.dedent().replace("\t", "").replace("\r", "").strip_edges();
// remove extra new lines around code blocks
bbcode = bbcode.replace("[codeblock]\n", "[codeblock]");
bbcode = bbcode.replace("\n[/codeblock]", "[/codeblock]");
List<String> tag_stack;
bool code_tag = false;
int pos = 0;
while (pos < bbcode.length()) {
int brk_pos = bbcode.find("[", pos);
if (brk_pos < 0)
brk_pos = bbcode.length();
if (brk_pos > pos) {
String text = bbcode.substr(pos, brk_pos - pos);
if (!code_tag)
text = text.replace("\n", "\n\n");
p_rt->add_text(text);
}
if (brk_pos == bbcode.length())
break; //nothing else to add
int brk_end = bbcode.find("]", brk_pos + 1);
if (brk_end == -1) {
String text = bbcode.substr(brk_pos, bbcode.length() - brk_pos);
if (!code_tag)
text = text.replace("\n", "\n\n");
p_rt->add_text(text);
break;
}
String tag = bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
if (tag.begins_with("/")) {
bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1, tag.length());
if (!tag_ok) {
p_rt->add_text("[");
pos = brk_pos + 1;
continue;
}
tag_stack.pop_front();
pos = brk_end + 1;
if (tag != "/img") {
p_rt->pop();
if (code_tag) {
p_rt->pop();
}
}
code_tag = false;
} else if (code_tag) {
p_rt->add_text("[");
pos = brk_pos + 1;
} else if (tag.begins_with("method ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ")) {
int tag_end = tag.find(" ");
String link_tag = tag.substr(0, tag_end);
String link_target = tag.substr(tag_end + 1, tag.length()).lstrip(" ");
p_rt->push_color(link_color);
p_rt->push_meta("@" + link_tag + " " + link_target);
p_rt->add_text(link_target + (tag.begins_with("method ") ? "()" : ""));
p_rt->pop();
p_rt->pop();
pos = brk_end + 1;
} else if (doc->class_list.has(tag)) {
p_rt->push_color(link_color);
p_rt->push_meta("#" + tag);
p_rt->add_text(tag);
p_rt->pop();
p_rt->pop();
pos = brk_end + 1;
} else if (tag == "b") {
//use bold font
p_rt->push_font(doc_bold_font);
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "i") {
//use italics font
p_rt->push_color(font_color_hl);
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "code" || tag == "codeblock") {
//use monospace font
p_rt->push_font(doc_code_font);
p_rt->push_color(code_color);
code_tag = true;
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "center") {
//align to center
p_rt->push_align(RichTextLabel::ALIGN_CENTER);
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "br") {
//force a line break
p_rt->add_newline();
pos = brk_end + 1;
} else if (tag == "u") {
//use underline
p_rt->push_underline();
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "s") {
//use strikethrough
p_rt->push_strikethrough();
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "url") {
int end = bbcode.find("[", brk_end);
if (end == -1)
end = bbcode.length();
String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
p_rt->push_meta(url);
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag.begins_with("url=")) {
String url = tag.substr(4, tag.length());
p_rt->push_meta(url);
pos = brk_end + 1;
tag_stack.push_front("url");
} else if (tag == "img") {
int end = bbcode.find("[", brk_end);
if (end == -1)
end = bbcode.length();
String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
Ref<Texture> texture = ResourceLoader::load(base_path.plus_file(image), "Texture");
if (texture.is_valid())
p_rt->add_image(texture);
pos = end;
tag_stack.push_front(tag);
} else if (tag.begins_with("color=")) {
String col = tag.substr(6, tag.length());
Color color;
if (col.begins_with("#"))
color = Color::html(col);
else if (col == "aqua")
color = Color(0, 1, 1);
else if (col == "black")
color = Color(0, 0, 0);
else if (col == "blue")
color = Color(0, 0, 1);
else if (col == "fuchsia")
color = Color(1, 0, 1);
else if (col == "gray" || col == "grey")
color = Color(0.5, 0.5, 0.5);
else if (col == "green")
color = Color(0, 0.5, 0);
else if (col == "lime")
color = Color(0, 1, 0);
else if (col == "maroon")
color = Color(0.5, 0, 0);
else if (col == "navy")
color = Color(0, 0, 0.5);
else if (col == "olive")
color = Color(0.5, 0.5, 0);
else if (col == "purple")
color = Color(0.5, 0, 0.5);
else if (col == "red")
color = Color(1, 0, 0);
else if (col == "silver")
color = Color(0.75, 0.75, 0.75);
else if (col == "teal")
color = Color(0, 0.5, 0.5);
else if (col == "white")
color = Color(1, 1, 1);
else if (col == "yellow")
color = Color(1, 1, 0);
else
color = Color(0, 0, 0); //base_color;
p_rt->push_color(color);
pos = brk_end + 1;
tag_stack.push_front("color");
} else if (tag.begins_with("font=")) {
String fnt = tag.substr(5, tag.length());
Ref<Font> font = ResourceLoader::load(base_path.plus_file(fnt), "Font");
if (font.is_valid())
p_rt->push_font(font);
else {
p_rt->push_font(doc_font);
}
pos = brk_end + 1;
tag_stack.push_front("font");
} else {
p_rt->add_text("["); //ignore
pos = brk_pos + 1;
}
}
}
void EditorHelp::_add_text(const String &p_bbcode) {
_add_text_to_rt(p_bbcode, class_desc);
}
void EditorHelp::generate_doc() {
doc = memnew(DocData);
doc->generate(true);
DocData compdoc;
compdoc.load_compressed(_doc_data_compressed, _doc_data_compressed_size, _doc_data_uncompressed_size);
doc->merge_from(compdoc); //ensure all is up to date
}
void EditorHelp::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY:
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
_update_doc();
} break;
case NOTIFICATION_THEME_CHANGED: {
if (is_visible_in_tree()) {
_class_desc_resized();
}
} break;
default: break;
}
}
void EditorHelp::go_to_help(const String &p_help) {
_help_callback(p_help);
}
void EditorHelp::go_to_class(const String &p_class, int p_scroll) {
_goto_desc(p_class, p_scroll);
}
Vector<Pair<String, int> > EditorHelp::get_sections() {
Vector<Pair<String, int> > sections;
for (int i = 0; i < section_line.size(); i++) {
sections.push_back(Pair<String, int>(section_line[i].first, i));
}
return sections;
}
void EditorHelp::scroll_to_section(int p_section_index) {
int line = section_line[p_section_index].second;
class_desc->scroll_to_line(line);
}
void EditorHelp::popup_search() {
find_bar->popup_search();
}
String EditorHelp::get_class() {
return edited_class;
}
void EditorHelp::search_again(bool p_search_previous) {
_search(p_search_previous);
}
int EditorHelp::get_scroll() const {
return class_desc->get_v_scroll()->get_value();
}
void EditorHelp::set_scroll(int p_scroll) {
class_desc->get_v_scroll()->set_value(p_scroll);
}
void EditorHelp::_bind_methods() {
ClassDB::bind_method("_class_list_select", &EditorHelp::_class_list_select);
ClassDB::bind_method("_class_desc_select", &EditorHelp::_class_desc_select);
ClassDB::bind_method("_class_desc_input", &EditorHelp::_class_desc_input);
ClassDB::bind_method("_class_desc_resized", &EditorHelp::_class_desc_resized);
ClassDB::bind_method("_request_help", &EditorHelp::_request_help);
ClassDB::bind_method("_unhandled_key_input", &EditorHelp::_unhandled_key_input);
ClassDB::bind_method("_search", &EditorHelp::_search);
ClassDB::bind_method("_help_callback", &EditorHelp::_help_callback);
ADD_SIGNAL(MethodInfo("go_to_help"));
}
EditorHelp::EditorHelp() {
set_custom_minimum_size(Size2(150 * EDSCALE, 0));
EDITOR_DEF("text_editor/help/sort_functions_alphabetically", true);
class_desc = memnew(RichTextLabel);
add_child(class_desc);
class_desc->set_v_size_flags(SIZE_EXPAND_FILL);
class_desc->add_color_override("selection_color", get_color("accent_color", "Editor") * Color(1, 1, 1, 0.4));
class_desc->connect("meta_clicked", this, "_class_desc_select");
class_desc->connect("gui_input", this, "_class_desc_input");
class_desc->connect("resized", this, "_class_desc_resized");
_class_desc_resized();
// Added second so it opens at the bottom so it won't offset the entire widget.
find_bar = memnew(FindBar);
add_child(find_bar);
find_bar->hide();
find_bar->set_rich_text_label(class_desc);
class_desc->set_selection_enabled(true);
scroll_locked = false;
select_locked = false;
class_desc->hide();
}
EditorHelp::~EditorHelp() {
}
void EditorHelpBit::_go_to_help(String p_what) {
EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT);
ScriptEditor::get_singleton()->goto_help(p_what);
emit_signal("request_hide");
}
void EditorHelpBit::_meta_clicked(String p_select) {
if (p_select.begins_with("$")) { //enum
String select = p_select.substr(1, p_select.length());
String class_name;
if (select.find(".") != -1) {
class_name = select.get_slice(".", 0);
} else {
class_name = "@Global";
}
_go_to_help("class_enum:" + class_name + ":" + select);
return;
} else if (p_select.begins_with("#")) {
_go_to_help("class_name:" + p_select.substr(1, p_select.length()));
return;
} else if (p_select.begins_with("@")) {
String m = p_select.substr(1, p_select.length());
if (m.find(".") != -1)
_go_to_help("class_method:" + m.get_slice(".", 0) + ":" + m.get_slice(".", 0)); //must go somewhere else
}
}
void EditorHelpBit::_bind_methods() {
ClassDB::bind_method("_meta_clicked", &EditorHelpBit::_meta_clicked);
ClassDB::bind_method(D_METHOD("set_text", "text"), &EditorHelpBit::set_text);
ADD_SIGNAL(MethodInfo("request_hide"));
}
void EditorHelpBit::_notification(int p_what) {
switch (p_what) {
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
rich_text->add_color_override("selection_color", get_color("accent_color", "Editor") * Color(1, 1, 1, 0.4));
} break;
default: break;
}
}
void EditorHelpBit::set_text(const String &p_text) {
rich_text->clear();
_add_text_to_rt(p_text, rich_text);
}
EditorHelpBit::EditorHelpBit() {
rich_text = memnew(RichTextLabel);
add_child(rich_text);
rich_text->connect("meta_clicked", this, "_meta_clicked");
rich_text->add_color_override("selection_color", get_color("accent_color", "Editor") * Color(1, 1, 1, 0.4));
rich_text->set_override_selected_font_color(false);
set_custom_minimum_size(Size2(0, 70 * EDSCALE));
}
FindBar::FindBar() {
search_text = memnew(LineEdit);
add_child(search_text);
search_text->set_custom_minimum_size(Size2(100 * EDSCALE, 0));
search_text->set_h_size_flags(SIZE_EXPAND_FILL);
search_text->connect("text_changed", this, "_search_text_changed");
search_text->connect("text_entered", this, "_search_text_entered");
matches_label = memnew(Label);
add_child(matches_label);
matches_label->hide();
find_prev = memnew(ToolButton);
add_child(find_prev);
find_prev->set_focus_mode(FOCUS_NONE);
find_prev->connect("pressed", this, "_search_prev");
find_next = memnew(ToolButton);
add_child(find_next);
find_next->set_focus_mode(FOCUS_NONE);
find_next->connect("pressed", this, "_search_next");
Control *space = memnew(Control);
add_child(space);
space->set_custom_minimum_size(Size2(4, 0) * EDSCALE);
hide_button = memnew(TextureButton);
add_child(hide_button);
hide_button->set_focus_mode(FOCUS_NONE);
hide_button->set_expand(true);
hide_button->set_stretch_mode(TextureButton::STRETCH_KEEP_CENTERED);
hide_button->connect("pressed", this, "_hide_pressed");
}
void FindBar::popup_search() {
show();
bool grabbed_focus = false;
if (!search_text->has_focus()) {
search_text->grab_focus();
grabbed_focus = true;
}
if (!search_text->get_text().empty()) {
search_text->select_all();
search_text->set_cursor_position(search_text->get_text().length());
if (grabbed_focus) {
_search();
}
}
}
void FindBar::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
case NOTIFICATION_THEME_CHANGED: {
find_prev->set_icon(get_icon("MoveUp", "EditorIcons"));
find_next->set_icon(get_icon("MoveDown", "EditorIcons"));
hide_button->set_normal_texture(get_icon("Close", "EditorIcons"));
hide_button->set_hover_texture(get_icon("Close", "EditorIcons"));
hide_button->set_pressed_texture(get_icon("Close", "EditorIcons"));
hide_button->set_custom_minimum_size(hide_button->get_normal_texture()->get_size());
matches_label->add_color_override("font_color", results_count > 0 ? get_color("font_color", "Label") : get_color("error_color", "Editor"));
} break;
case NOTIFICATION_VISIBILITY_CHANGED: {
set_process_unhandled_input(is_visible_in_tree());
} break;
}
}
void FindBar::_bind_methods() {
ClassDB::bind_method("_unhandled_input", &FindBar::_unhandled_input);
ClassDB::bind_method("_search_text_changed", &FindBar::_search_text_changed);
ClassDB::bind_method("_search_text_entered", &FindBar::_search_text_entered);
ClassDB::bind_method("_search_next", &FindBar::search_next);
ClassDB::bind_method("_search_prev", &FindBar::search_prev);
ClassDB::bind_method("_hide_pressed", &FindBar::_hide_bar);
ADD_SIGNAL(MethodInfo("search"));
}
void FindBar::set_rich_text_label(RichTextLabel *p_rich_text_label) {
rich_text_label = p_rich_text_label;
}
bool FindBar::search_next() {
return _search();
}
bool FindBar::search_prev() {
return _search(true);
}
bool FindBar::_search(bool p_search_previous) {
String stext = search_text->get_text();
bool keep = prev_search == stext;
bool ret = rich_text_label->search(stext, keep, p_search_previous);
if (!ret) {
ret = rich_text_label->search(stext, false, p_search_previous);
}
prev_search = stext;
if (ret) {
_update_results_count();
} else {
results_count = 0;
}
_update_matches_label();
return ret;
}
void FindBar::_update_results_count() {
results_count = 0;
String searched = search_text->get_text();
if (searched.empty()) return;
String full_text = rich_text_label->get_text();
int from_pos = 0;
while (true) {
int pos = full_text.find(searched, from_pos);
if (pos == -1)
break;
results_count++;
from_pos = pos + searched.length();
}
}
void FindBar::_update_matches_label() {
if (search_text->get_text().empty() || results_count == -1) {
matches_label->hide();
} else {
matches_label->show();
matches_label->add_color_override("font_color", results_count > 0 ? get_color("font_color", "Label") : get_color("error_color", "Editor"));
matches_label->set_text(vformat(results_count == 1 ? TTR("%d match.") : TTR("%d matches."), results_count));
}
}
void FindBar::_hide_bar() {
if (search_text->has_focus())
rich_text_label->grab_focus();
hide();
}
void FindBar::_unhandled_input(const Ref<InputEvent> &p_event) {
Ref<InputEventKey> k = p_event;
if (k.is_valid()) {
if (k->is_pressed() && (rich_text_label->has_focus() || is_a_parent_of(get_focus_owner()))) {
bool accepted = true;
switch (k->get_scancode()) {
case KEY_ESCAPE: {
_hide_bar();
} break;
default: {
accepted = false;
} break;
}
if (accepted) {
accept_event();
}
}
}
}
void FindBar::_search_text_changed(const String &p_text) {
search_next();
}
void FindBar::_search_text_entered(const String &p_text) {
if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
search_prev();
} else {
search_next();
}
}
| 27.764516 | 300 | 0.656694 | [
"vector"
] |
4f78cca90f89c2a33229f7aa22d34c1802ed455c | 809 | cpp | C++ | tests/dataStructures/segmentTree/BottomUpMaxSegmentTree.cpp | s0rav/spcppl | a17886c9082055490dab09c47a250accfadd8513 | [
"WTFPL"
] | 30 | 2015-04-19T17:04:33.000Z | 2022-03-22T13:26:53.000Z | tests/dataStructures/segmentTree/BottomUpMaxSegmentTree.cpp | s0rav/spcppl | a17886c9082055490dab09c47a250accfadd8513 | [
"WTFPL"
] | 4 | 2018-05-27T18:20:10.000Z | 2021-11-28T15:22:12.000Z | tests/dataStructures/segmentTree/BottomUpMaxSegmentTree.cpp | s0rav/spcppl | a17886c9082055490dab09c47a250accfadd8513 | [
"WTFPL"
] | 8 | 2016-10-28T16:46:05.000Z | 2021-02-24T16:49:20.000Z | #include <spcppl/dataStructures/segmentTree/BottomUpMaxSegmentTree.hpp>
#include <gtest/gtest.h>
#include <vector>
TEST(BottomUpMaxSegmentTree, CreationFromNumber) {
BottomUpMaxSegmentTree<int> tree(5);
EXPECT_EQ(tree.getElement(3), NegativeInfinity<int>()());
}
TEST(BottomUpMaxSegmentTree, CreationFromList) {
BottomUpMaxSegmentTree<int> tree(std::vector<int>{1, 3, 2, 5, 4});
EXPECT_EQ(tree.getResult(1, 3), 3);
EXPECT_EQ(tree.getResult(0, 5), 5);
EXPECT_EQ(tree.getElement(0), 1);
}
TEST(BottomUpMaxSegmentTree, FindFirstMinimum) {
BottomUpMaxSegmentTree<int> tree(std::vector<int>{3, 2, 3, 8, 2});
EXPECT_EQ(tree.getResult(0, 5), 8);
EXPECT_EQ(tree.getFirstMaximum(), 3u);
tree.set(2, 8);
EXPECT_EQ(tree.getFirstMaximum(), 2u);
tree.set(4, 10);
EXPECT_EQ(tree.getFirstMaximum(), 4u);
}
| 28.892857 | 71 | 0.736712 | [
"vector"
] |
4f79544857ae154a2e7a67b26d59674ddca5915c | 19,848 | cpp | C++ | roc_app/Elements/Model/Skeleton.cpp | SDraw/roc_engine | f38b38fc1ff8e48d5e0800941a2cf0d3818b4fcf | [
"MIT"
] | 7 | 2020-11-24T16:10:11.000Z | 2022-02-17T22:39:36.000Z | roc_app/Elements/Model/Skeleton.cpp | SDraw/roc_engine | f38b38fc1ff8e48d5e0800941a2cf0d3818b4fcf | [
"MIT"
] | null | null | null | roc_app/Elements/Model/Skeleton.cpp | SDraw/roc_engine | f38b38fc1ff8e48d5e0800941a2cf0d3818b4fcf | [
"MIT"
] | 2 | 2020-11-24T16:10:12.000Z | 2021-10-02T06:44:43.000Z | #include "stdafx.h"
#include "Elements/Model/Skeleton.h"
#include "Elements/Model/Bone.h"
#include "Elements/Geometry/BoneCollisionData.hpp"
#include "Elements/Geometry/BoneData.hpp"
#include "Elements/Geometry/BoneJointData.hpp"
#include "Elements/Animation/Animation.h"
#include "Elements/Animation/BoneFrameData.h"
#include "Utils/Transformation.h"
namespace ROC
{
extern const glm::mat4 g_identityMatrix;
}
bool ROC::Skeleton::ms_physicsEnabled = false;
ROC::Skeleton::Skeleton(const std::vector<BoneData*> &p_data)
{
for(auto l_boneData : p_data)
{
Bone *l_bone = new Bone(l_boneData->m_name, l_boneData->m_rotation, l_boneData->m_position, l_boneData->m_scale);
m_bones.push_back(l_bone);
}
m_bones.shrink_to_fit();
m_bonesCount = m_bones.size();
for(size_t i = 0; i < m_bonesCount; i++)
{
if(p_data[i]->m_parent != -1)
{
size_t l_parent = static_cast<size_t>(p_data[i]->m_parent);
m_bones[i]->SetParent(m_bones[l_parent]);
m_bones[l_parent]->AddChild(m_bones[i]);
}
}
if(!m_bones.empty())
{
std::vector<Bone*> l_bonesStack;
l_bonesStack.push_back(m_bones.front());
while(!l_bonesStack.empty())
{
Bone *l_bone = l_bonesStack.back();
l_bonesStack.pop_back();
auto &l_boneChildren = l_bone->GetChildren();
l_bonesStack.insert(l_bonesStack.end(), l_boneChildren.rbegin(), l_boneChildren.rend());
m_sortedBones.push_back(l_bone);
l_bone->GenerateBindPose();
}
m_sortedBones.shrink_to_fit();
}
m_poseMatrices.assign(m_bonesCount, g_identityMatrix);
m_poseMatrices.shrink_to_fit();
}
ROC::Skeleton::~Skeleton()
{
for(auto l_bone : m_bones) delete l_bone;
m_bones.clear();
m_poseMatrices.clear();
if(!m_collisions.empty())
{
for(auto l_col : m_collisions)
{
l_col->m_offset.clear();
delete l_col->m_rigidBody->getMotionState();
delete l_col->m_rigidBody;
delete l_col;
}
m_collisions.clear();
}
if(!m_joints.empty())
{
for(auto l_joint : m_joints)
{
for(auto l_part = l_joint->m_parts.rbegin(); l_part != l_joint->m_parts.rend(); ++l_part)
{
SkeletonJointPart *l_jointPart = *l_part;
l_jointPart->m_offset.clear();
l_jointPart->m_constraint->getRigidBodyA().removeConstraintRef(l_jointPart->m_constraint);
l_jointPart->m_constraint->getRigidBodyB().removeConstraintRef(l_jointPart->m_constraint);
delete l_jointPart->m_constraint;
delete l_jointPart->m_rigidBody->getMotionState();
delete l_jointPart->m_rigidBody;
delete l_jointPart;
}
l_joint->m_transform.clear();
l_joint->m_parts.clear();
delete l_joint->m_emptyBody->getMotionState();
delete l_joint->m_emptyBody;
delete l_joint;
}
m_joints.clear();
}
m_sortedBones.clear();
}
bool ROC::Skeleton::HasStaticBoneCollision() const
{
return !m_collisions.empty();
}
void ROC::Skeleton::InitStaticBoneCollision(const std::vector<BoneCollisionData*> &p_vec, void *p_model)
{
if(m_collisions.empty())
{
for(const auto l_colData : p_vec)
{
if(l_colData->m_boneID >= m_bonesCount) continue; // Invalid bone id
SkeletonCollision *l_skeletonCol = new SkeletonCollision();
btCollisionShape *l_shape = nullptr;
switch(l_colData->m_type)
{
case SCT_Sphere:
l_shape = new btSphereShape(l_colData->m_size.x);
break;
case SCT_Box:
l_shape = new btBoxShape(btVector3(l_colData->m_size.x, l_colData->m_size.y, l_colData->m_size.z));
break;
case SCT_Cylinder:
l_shape = new btCylinderShape(btVector3(l_colData->m_size.x, l_colData->m_size.y, l_colData->m_size.z));
break;
case SCT_Capsule:
l_shape = new btCapsuleShape(l_colData->m_size.x, l_colData->m_size.y);
break;
case SCT_Cone:
l_shape = new btConeShape(l_colData->m_size.x, l_colData->m_size.y);
break;
default:
l_shape = new btEmptyShape();
break;
}
btTransform l_boneTransform, l_bodyOffset = btTransform::getIdentity(), l_bodyTransform;
l_boneTransform.setFromOpenGLMatrix(glm::value_ptr(m_bones[static_cast<size_t>(l_colData->m_boneID)]->GetFullMatrix()));
l_bodyOffset.setOrigin(btVector3(l_colData->m_offset.x, l_colData->m_offset.y, l_colData->m_offset.z));
l_bodyOffset.setRotation(btQuaternion(l_colData->m_offsetRotation.x, l_colData->m_offsetRotation.y, l_colData->m_offsetRotation.z, l_colData->m_offsetRotation.w));
l_skeletonCol->m_offset.push_back(l_bodyOffset);
l_bodyTransform.mult(l_boneTransform, l_bodyOffset);
btDefaultMotionState *l_fallMotionState = new btDefaultMotionState(l_bodyTransform);
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(0.f, l_fallMotionState, l_shape);
l_skeletonCol->m_rigidBody = new btRigidBody(fallRigidBodyCI);
l_skeletonCol->m_rigidBody->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT);
l_skeletonCol->m_rigidBody->setActivationState(DISABLE_DEACTIVATION);
l_skeletonCol->m_rigidBody->setUserPointer(p_model);
l_skeletonCol->m_boneID = static_cast<size_t>(l_colData->m_boneID);
m_collisions.push_back(l_skeletonCol);
}
m_collisions.shrink_to_fit();
}
}
const std::vector<ROC::Skeleton::SkeletonCollision*>& ROC::Skeleton::GetCollision() const
{
return m_collisions;
}
bool ROC::Skeleton::HasDynamicBoneCollision() const
{
return !m_joints.empty();
}
void ROC::Skeleton::InitDynamicBoneCollision(const std::vector<BoneJointData*> &p_vec, void *p_model)
{
if(m_joints.empty())
{
for(const auto l_jointData : p_vec)
{
if(l_jointData->m_boneID >= m_bonesCount) continue; // Invalid bone id
SkeletonJoint *l_joint = new SkeletonJoint();
l_joint->m_boneID = static_cast<size_t>(l_jointData->m_boneID);
l_joint->m_transform.push_back(btTransform::getIdentity()); // Local bone transformation
l_joint->m_transform[STT_Main].setFromOpenGLMatrix(glm::value_ptr(m_bones[l_joint->m_boneID]->GetLocalTransformation()->GetMatrix()));
btTransform l_boneTransform;
l_boneTransform.setFromOpenGLMatrix(glm::value_ptr(m_bones[l_joint->m_boneID]->GetFullMatrix()));
btCollisionShape *l_jointShape = new btEmptyShape();
btDefaultMotionState *l_jointFallMotionState = new btDefaultMotionState(l_boneTransform);
btRigidBody::btRigidBodyConstructionInfo l_jointFallRigidBodyCI(0.f, l_jointFallMotionState, l_jointShape);
l_joint->m_emptyBody = new btRigidBody(l_jointFallRigidBodyCI);
l_joint->m_emptyBody->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT);
l_joint->m_emptyBody->setActivationState(DISABLE_DEACTIVATION);
l_joint->m_emptyBody->setUserPointer(p_model);
m_joints.push_back(l_joint);
for(size_t i = 0, j = l_jointData->m_jointParts.size(); i < j; i++)
{
const BoneJointPartData &l_jointPartData = l_jointData->m_jointParts[i];
if(l_jointPartData.m_boneID >= m_bonesCount) continue; // Invalid bone id
SkeletonJointPart *l_jointPart = new SkeletonJointPart();
l_jointPart->m_boneID = static_cast<size_t>(l_jointPartData.m_boneID);
btTransform l_jointPartTransform = btTransform::getIdentity();
l_boneTransform.setFromOpenGLMatrix(glm::value_ptr(m_bones[l_jointPart->m_boneID]->GetFullMatrix()));
l_jointPartTransform.setOrigin(btVector3(l_jointPartData.m_offset.x, l_jointPartData.m_offset.y, l_jointPartData.m_offset.z));
l_jointPartTransform.setRotation(btQuaternion(l_jointPartData.m_rotation.x, l_jointPartData.m_rotation.y, l_jointPartData.m_rotation.z, l_jointPartData.m_rotation.w));
l_jointPart->m_offset.push_back(l_jointPartTransform); // Bone offset transformation
l_jointPart->m_offset.push_back(l_jointPartTransform.inverse()); // Bone offset inversed transformation
l_jointPart->m_offset.push_back(btTransform::getIdentity()); // Bone bind matrix (inversed full bone matrix)
l_jointPart->m_offset[STT_Bind].setFromOpenGLMatrix(glm::value_ptr(m_bones[l_jointPart->m_boneID]->GetBindMatrix()));
btTransform l_jointPartResultTransform;
l_jointPartResultTransform.mult(l_boneTransform, l_jointPartTransform);
btCollisionShape *l_jointPartShape = nullptr;
btVector3 l_jointPartInertia;
switch(l_jointPartData.m_type)
{
case SCT_Sphere:
l_jointPartShape = new btSphereShape(l_jointPartData.m_size.x);
break;
case SCT_Box:
l_jointPartShape = new btBoxShape(btVector3(l_jointPartData.m_size.x, l_jointPartData.m_size.y, l_jointPartData.m_size.z));
break;
case SCT_Cylinder:
l_jointPartShape = new btCylinderShape(btVector3(l_jointPartData.m_size.x, l_jointPartData.m_size.y, l_jointPartData.m_size.z));
break;
case SCT_Capsule:
l_jointPartShape = new btCapsuleShape(l_jointPartData.m_size.x, l_jointPartData.m_size.y);
break;
case SCT_Cone:
l_jointPartShape = new btConeShape(l_jointPartData.m_size.x, l_jointPartData.m_size.y);
break;
default:
l_jointPartShape = new btEmptyShape();
break;
}
l_jointPartShape->calculateLocalInertia(l_jointPartData.m_mass, l_jointPartInertia);
btDefaultMotionState *l_jointPartFallMotionState = new btDefaultMotionState(l_jointPartResultTransform);
btRigidBody::btRigidBodyConstructionInfo l_jointPartFallRigidBodyCI(l_jointPartData.m_mass, l_jointPartFallMotionState, l_jointPartShape, l_jointPartInertia);
l_jointPart->m_rigidBody = new btRigidBody(l_jointPartFallRigidBodyCI);
l_jointPart->m_rigidBody->setActivationState(DISABLE_DEACTIVATION);
l_jointPart->m_rigidBody->setUserPointer(p_model);
l_jointPart->m_rigidBody->setRestitution(l_jointPartData.m_restutition);
l_jointPart->m_rigidBody->setFriction(l_jointPartData.m_friction);
l_jointPart->m_rigidBody->setDamping(l_jointPartData.m_damping.x, l_jointPartData.m_damping.y);
if(i == 0U)
{
// First joint part is connected to joint empty body
const btTransform l_jointConstraintOffset = btTransform::getIdentity();
l_jointPart->m_constraint = new btGeneric6DofSpringConstraint(*l_joint->m_emptyBody, *l_jointPart->m_rigidBody, l_jointConstraintOffset, l_jointPart->m_offset[STT_Inverse], false);
}
else
{
// Joint part is connected to previous joint part body
btRigidBody *l_prevJointRigidBody = l_joint->m_parts.back()->m_rigidBody;
btTransform l_prevJointPartToBoneTransform;
l_prevJointPartToBoneTransform.mult(l_prevJointRigidBody->getCenterOfMassTransform().inverse(), l_boneTransform);
l_jointPart->m_constraint = new btGeneric6DofSpringConstraint(*l_prevJointRigidBody, *l_jointPart->m_rigidBody, l_prevJointPartToBoneTransform, l_jointPart->m_offset[STT_Inverse], false);
}
l_jointPart->m_constraint->setDbgDrawSize(0.5f);
l_jointPart->m_constraint->setLinearLowerLimit(btVector3(l_jointPartData.m_lowerLinearLimit.x, l_jointPartData.m_lowerLinearLimit.y, l_jointPartData.m_lowerLinearLimit.z));
l_jointPart->m_constraint->setLinearUpperLimit(btVector3(l_jointPartData.m_upperLinearLimit.x, l_jointPartData.m_upperLinearLimit.y, l_jointPartData.m_upperLinearLimit.z));
l_jointPart->m_constraint->setAngularLowerLimit(btVector3(l_jointPartData.m_lowerAngularLimit.x, l_jointPartData.m_lowerAngularLimit.y, l_jointPartData.m_lowerAngularLimit.z));
l_jointPart->m_constraint->setAngularUpperLimit(btVector3(l_jointPartData.m_upperAngularLimit.x, l_jointPartData.m_upperAngularLimit.y, l_jointPartData.m_upperAngularLimit.z));
for(int k = 0; k < 3; k++)
{
if(l_jointPartData.m_linearStiffness[k] > 0.f)
{
l_jointPart->m_constraint->enableSpring(k, true);
l_jointPart->m_constraint->setStiffness(k, l_jointPartData.m_linearStiffness[k]);
}
if(l_jointPartData.m_angularStiffness[k] > 0.f)
{
l_jointPart->m_constraint->enableSpring(k + 3, true);
l_jointPart->m_constraint->setStiffness(k + 3, l_jointPartData.m_angularStiffness[k]);
}
}
l_joint->m_parts.push_back(l_jointPart);
// Set bone as dynamic
m_bones[l_jointPart->m_boneID]->SetDynamic(true);
m_bones[l_jointPart->m_boneID]->SetDynamicBody(l_jointPart->m_rigidBody);
}
l_joint->m_parts.shrink_to_fit();
}
m_joints.shrink_to_fit();
}
}
const std::vector<ROC::Skeleton::SkeletonJoint*>& ROC::Skeleton::GetJoints() const
{
return m_joints;
}
bool ROC::Skeleton::HasAnyCollision() const
{
return (!m_collisions.empty() || !m_joints.empty());
}
size_t ROC::Skeleton::GetBonesCount() const
{
return m_bonesCount;
}
const std::vector<ROC::Bone*>& ROC::Skeleton::GetBones() const
{
return m_bones;
}
const std::vector<glm::mat4>& ROC::Skeleton::GetPoseMatrices() const
{
return m_poseMatrices;
}
void ROC::Skeleton::Update(Animation *p_anim, unsigned int p_tick, float p_blend)
{
p_anim->GetData(p_tick, m_bones, p_blend);
for(auto l_bone : m_sortedBones) l_bone->Update();
for(size_t i = 0U; i < m_bonesCount; i++) std::memcpy(&m_poseMatrices[i], &m_bones[i]->GetPoseMatrix(), sizeof(glm::mat4));
}
void ROC::Skeleton::UpdateCollision(SkeletonUpdateStage p_stage, const glm::mat4 &p_model)
{
switch(p_stage)
{
case SUS_Static:
{
if(!m_collisions.empty() || !m_joints.empty())
{
btTransform l_model;
btTransform l_transform1, l_transform2;
l_model.setFromOpenGLMatrix(glm::value_ptr(p_model));
if(!m_collisions.empty())
{
for(auto l_skeletonCol : m_collisions)
{
// BodyGlobal = Model * (Bone * BoneOffset)
l_transform1.setFromOpenGLMatrix(glm::value_ptr(m_bones[l_skeletonCol->m_boneID]->GetFullMatrix()));
l_transform2.mult(l_transform1, l_skeletonCol->m_offset[STT_Main]);
l_transform1.mult(l_model, l_transform2);
ms_physicsEnabled ? l_skeletonCol->m_rigidBody->getMotionState()->setWorldTransform(l_transform1) : l_skeletonCol->m_rigidBody->setCenterOfMassTransform(l_transform1);
}
}
if(!m_joints.empty())
{
for(auto l_joint : m_joints)
{
if(m_bones[l_joint->m_boneID]->GetParent())
{
// BodyGlobal = Model * (ParentBoneFull * Joint)
l_transform1.setFromOpenGLMatrix(glm::value_ptr(m_bones[l_joint->m_boneID]->GetParent()->GetFullMatrix()));
l_transform2.mult(l_transform1, l_joint->m_transform[STT_Main]);
l_transform1.mult(l_model, l_transform2);
}
else
{
// BodyGlobal = Model * Joint
l_transform1.mult(l_model, l_joint->m_transform[STT_Main]);
}
ms_physicsEnabled ? l_joint->m_emptyBody->getMotionState()->setWorldTransform(l_transform1) : l_joint->m_emptyBody->setCenterOfMassTransform(l_transform1);
}
}
}
} break;
case SUS_Dynamic:
{
if(!m_joints.empty())
{
btTransform l_transform1, l_transform2;
if(ms_physicsEnabled)
{
// btTransform works bad with inversion of imported scaled matrices
btTransform l_modelInv = btTransform::getIdentity();
glm::mat4 l_invMat4 = glm::inverse(p_model);
l_modelInv.setFromOpenGLMatrix(glm::value_ptr(l_invMat4));
for(auto l_joint : m_joints)
{
for(auto l_jointPart : l_joint->m_parts)
{
// BoneFull = ((ModelInverse * BodyGlobal) * BodyBoneOffsetInverse)
Bone *l_bone = m_bones[l_jointPart->m_boneID];
l_transform1.mult(l_modelInv, l_jointPart->m_rigidBody->getWorldTransform());
l_transform2.mult(l_transform1, l_jointPart->m_offset[STT_Inverse]);
l_bone->SetFullMatrix(l_transform2);
// BonePose = BoneFull * BoneBind
l_transform1.mult(l_transform2, l_jointPart->m_offset[STT_Bind]);
l_bone->SetPoseMatrix(l_transform1);
std::memcpy(&m_poseMatrices[l_jointPart->m_boneID], &l_bone->GetPoseMatrix(), sizeof(glm::mat4));
}
}
}
else
{
btTransform l_model;
l_model.setFromOpenGLMatrix(glm::value_ptr(p_model));
for(auto l_joint : m_joints)
{
for(auto l_jointPart : l_joint->m_parts)
{
// BodyGlobal = Model * (BoneMatrix * BodyBoneOffset)
l_transform1.setFromOpenGLMatrix(glm::value_ptr(m_bones[l_jointPart->m_boneID]->GetFullMatrix()));
l_transform2.mult(l_transform1, l_jointPart->m_offset[STT_Main]);
l_transform1.mult(l_model, l_transform2);
l_jointPart->m_rigidBody->setCenterOfMassTransform(l_transform1);
}
}
}
}
} break;
}
}
void ROC::Skeleton::SetPhysicsEnabled(bool p_state)
{
ms_physicsEnabled = p_state;
}
| 45.627586 | 207 | 0.606812 | [
"geometry",
"vector",
"model"
] |
4f79f6175603994faa4a2629ec31421c003016ef | 12,869 | cpp | C++ | src/checker.cpp | d-kfmnn/pacheck2 | b3dcee7065b0af1a3ba6ec5ce87524109b4fa709 | [
"MIT"
] | null | null | null | src/checker.cpp | d-kfmnn/pacheck2 | b3dcee7065b0af1a3ba6ec5ce87524109b4fa709 | [
"MIT"
] | null | null | null | src/checker.cpp | d-kfmnn/pacheck2 | b3dcee7065b0af1a3ba6ec5ce87524109b4fa709 | [
"MIT"
] | null | null | null | /*------------------------------------------------------------------------*/
/*! \file checker.cpp
\brief parses and checks the proof
Part of Pacheck 2.0 : PAC proof checker.
Copyright(C) 2020 Daniela Kaufmann, Johannes Kepler University Linz
*/
/*------------------------------------------------------------------------*/
#include <vector>
#include "checker.h"
/*------------------------------------------------------------------------*/
// Global variables
bool check_target = 1;
bool delete_mode = 1;
bool target_polynomial_inferences = 0;
bool constant_one_polynomial_inferences = 0;
/*------------------------------------------------------------------------*/
// Local variables
/// stores the target
static Polynomial * target;
/// counts the number of inference rules
static unsigned num_inference_rules;
/// counts the number of axioms
static unsigned original_inferences;
/// counts the number of extension rules
static unsigned extension_inferences;
/// counts the number of linear combination rules
static unsigned lin_comb_inferences;
/// counts the number of deletion rules
static unsigned deletion_inferences;
/// counts the number of addition operations
static unsigned addition_operations;
/// counts the number of multiplication operations
static unsigned multiplication_operations;
/*------------------------------------------------------------------------*/
/**
Opens the file
@param file_name const char *
*/
static void init_parsing(const char * file_name) {
parse_file_name = file_name;
parse_file = fopen(file_name, "r");
if (!parse_file) die("can not open '%s' for reading", file_name);
lineno = 1;
charno = 0;
}
/*------------------------------------------------------------------------*/
/**
Closes the parse file
*/
static void reset_parsing() {
if (fclose(parse_file))
die("failed to close '%s'", parse_file_name);
msg("read %i bytes from '%s'", charno, parse_file_name);
msg("");
}
/***************************************************************************/
/**
Prints an error message that polynomial with p_index was not found
@param index unsigned
@param p_index unsigned
@param rule_line unsigned
*/
static void polynomial_not_found(
unsigned index, unsigned p_index, unsigned rule_line) {
fflush(stdout);
fprintf(stderr, "*** 'pacheck' error in rule with index %i ", index);
fprintf(stderr, " in '%s' line %i: polynomial with index %i not found",
parse_file_name, rule_line, p_index);
if (delete_mode) {
fputs("\ndelete mode is ON - try '--no-delete'", stderr);
}
fputc('\n', stderr);
fflush(stderr);
exit(1);
}
/*------------------------------------------------------------------------*/
/**
Prints an error message that polynomials 'actual' and 'expected' do not match
@param index unsigned
@param actual const Polynomial *
@param expected const Polynomial *
@param rule_line unsigned
@param polynomial_line unsigned
*/
static void polynomials_do_not_match(
unsigned index, const Polynomial * actual, const Polynomial * expected,
unsigned rule_line, unsigned polynomial_line) {
fflush(stdout);
fprintf(stderr, "*** 'pacheck' error in rule with index %i ", index);
fprintf(stderr,
" in '%s' line %i: conclusion polynomial", parse_file_name, rule_line);
if (rule_line != polynomial_line)
fprintf(stderr, " line %i", polynomial_line);
fputs(":\n", stderr);
actual->print(stderr);
fputs("\ndoes not match expected result:\n", stderr);
expected->print(stderr);
fputc('\n', stderr);
fflush(stderr);
exit(1);
}
/***************************************************************************/
/**
Checks whether p is a single new variable
@param p const Polynomial *
@return true if p is a valid extension variable
*/
static bool check_for_valid_extension_var(const Polynomial * p) {
if (p->get_rest()) return 0;
if (mpz_cmp_si(p->get_lm()->coeff, 1) != 0) return 0;
Term *t = p->get_lt();
if (!t) return 0;
if (t->size() > 1) return 0;
if (t->get_var()->get_count() > 1) return 0;
return 1;
}
/*------------------------------------------------------------------------*/
/**
Checks whether p is a valid extension, i.e. p*p-p=0
@param p const Polynomial *
@param v const Var *
@return true if p is a valid extension polynomial
*/
static bool check_for_valid_extension_poly(
const Polynomial * p, const Var * v) {
if (v->get_count() > 1) return 0;
Polynomial * mult = multiply_poly(p, p);
bool zero = equal_polynomials(mult, p);
delete(mult);
return zero;
}
/***************************************************************************/
/**
Parses an extension rule with starting index 'index'
@param index unsigned
*/
static void parse_extension_rule(unsigned index) {
if (find_inference_index(index))
parse_error("index %i already exists", index);
unsigned line = lineno_at_start_of_last_token;
Polynomial * p1 = parse_polynomial();
if (!check_for_valid_extension_var(p1)) {
fflush(stdout);
fprintf(stderr, "*** 'pacheck' error in EXTENSION_RULE rule with index %i ",
index);
fprintf(stderr, " in '%s' line %i: extension variable is not valid",
parse_file_name, line);
fputc('\n', stderr);
fflush(stderr);
exit(1);
}
const Var * ext = p1->get_lt()->get_var();
assert(is_comma_token());
Polynomial * p2 = parse_polynomial(0);
if (!check_for_valid_extension_poly(p2, ext)) {
fflush(stdout);
fprintf(stderr, "*** 'pacheck' error in EXTENSION_RULE rule with index %i ",
index);
fprintf(stderr, " in '%s' line %i is not a valid extension polynomial",
parse_file_name, line);
fputc('\n', stderr);
fflush(stderr);
exit(1);
}
if (!is_semicolon_token()) parse_error("unexpected %s token", get_token());
Polynomial * p3 = negate_poly(p1);
Polynomial * q = add_poly(p2, p3);
delete(p1);
delete(p2);
delete(p3);
new_inference(index, q);
extension_inferences++;
}
/*------------------------------------------------------------------------*/
/// used to collect the factors of each slice for PAC proofs
static std::vector<const Polynomial*> factor_array;
/*-------------------------------------------------------------------------*/
/**
Adds up products of the linear combination
@return Polynomial *
*/
static const Polynomial * add_up_products() {
if(factor_array.empty()) return zero_poly();
while (factor_array.size() > 1) {
const Polynomial * p = factor_array.back();
factor_array.pop_back();
const Polynomial * q = factor_array.back();
factor_array.pop_back();
Polynomial * add = add_poly(p, q);
delete(p);
delete(q);
factor_array.push_back(add);
}
const Polynomial * res = factor_array.back();
factor_array.pop_back();
return res;
}
/*------------------------------------------------------------------------*/
/**
Merges the products in tree, depth first
*/
static void merge_products() {
unsigned i = factor_array.size();
if (i == 1) return;
const Polynomial * p = factor_array[i-1];
const Polynomial * q = factor_array[i-2];
int p_level = p->get_level();
if (p_level == q->get_level()) {
Polynomial * add = add_poly(p, q);
delete(p);
delete(q);
add->set_level(p_level+1);
factor_array.pop_back();
factor_array.pop_back();
factor_array.push_back(add);
merge_products();
}
}
/*------------------------------------------------------------------------*/
/**
Parses a linear combination rule with starting index 'index'
@param index unsigned
*/
static void parse_lin_combination_rule(int index) {
if (find_inference_index(index))
parse_error("index %i already exists", index);
unsigned rule_line = lineno_at_start_of_last_token;
unsigned p_index;
const Inference * i0;
const Polynomial * tmp, * conclusion = 0;
next_token();
while (!is_comma_token()) {
p_index = parse_index();
i0 = find_inference_index(p_index);
if (!i0) polynomial_not_found(index, p_index, rule_line);
next_token();
if (is_multiply_token()) {
multiplication_operations++;
next_token();
if (!is_open_parenthesis_token()) parse_error("expected '('");
Polynomial * p = parse_polynomial(0);
tmp = multiply_poly(i0->get_conclusion(), p);
delete(p);
assert(is_close_parenthesis_token());
next_token();
} else {
tmp = i0->get_conclusion()->copy();
}
factor_array.push_back(tmp);
merge_products();
if (is_plus_token()) {
addition_operations++;
next_token();
} else if (!is_comma_token()) {
parse_error("unexpected '%s'", get_token());
}
}
conclusion = add_up_products();
unsigned p2_line = lineno_at_start_of_last_token;
Polynomial *p2 = parse_polynomial();
assert(is_semicolon_token());
if (!equal_polynomials(p2, conclusion))
polynomials_do_not_match(index, p2, conclusion, rule_line, p2_line);
delete(p2);
if (check_target && equal_polynomials(target, conclusion)) {
target_polynomial_inferences = 1;
}
new_inference(index, conclusion);
lin_comb_inferences++;
}
/***************************************************************************/
/**
Parses the axioms from file_name
@param file_name const char *
*/
static void parse_original_polynomials(const char * file_name) {
init_parsing(file_name);
msg("reading original polynomials from '%s'", parse_file_name);
int original = 0;
while (!following_token_is_EOF()) {
unsigned line = lineno_at_start_of_last_token;
unsigned index = parse_index();
if (find_inference_index(index))
parse_error("error in line %i index %i already exists", line, index);
Polynomial * p = parse_polynomial();
if (!is_semicolon_token())
parse_error("error in line %i unexpected %s token", line, get_token());
new_inference(index, p);
original_inferences++;
if (check_target && equal_polynomials(p, target)) {
fprintf(stdout, "\n");
msg("WARNING: target polynomial is given as original polynomial.");
msg("Proof rules are obsolet, but will be checked anyway!\n");
target_polynomial_inferences = 1;
}
original++;
}
msg("found %i original polynomials in '%s'", original, parse_file_name);
reset_parsing();
}
/*------------------------------------------------------------------------*/
/**
Parses the proof from file_name
@param file_name const char *
*/
static void parse_and_check_proof_rules(const char * file_name) {
init_parsing(file_name);
msg("reading polynomial algebraic calculus proof from '%s'",
parse_file_name);
unsigned checked = 0, extensions = 0;
while (!following_token_is_EOF()) {
int index = parse_index();
next_token();
if (is_delete_token()) {
deletion_inferences++;
if (delete_mode) delete_inference_by_index(index);
next_token();
if (!is_semicolon_token())
parse_error("unexpected %s token", get_token());
} else if (is_extension_token()) {
parse_extension_rule(index);
extensions++;
num_inference_rules++;
checked++;
} else if (is_lin_combi_token()) {
parse_lin_combination_rule(index);
num_inference_rules++;
checked++;
if (verbose && checked % 1000 == 0)
msg("found and checked %6" PRIu64 " inferences so far", checked);
} else {
parse_error("expected operator 'd', '=' or '%%'");
}
}
msg("found and checked %" PRIu64 " inferences in '%s'",
checked, parse_file_name);
reset_parsing();
}
/*------------------------------------------------------------------------*/
void parse_target_polynomial(const char * file_name) {
init_parsing(file_name);
msg("reading target polynomial from '%s'", parse_file_name);
target = parse_polynomial();
assert(is_semicolon_token());
if (!following_token_is_EOF()) die("unexpected %s token", get_token());
reset_parsing();
}
/*------------------------------------------------------------------------*/
void parse_and_check_proof(const char * polys_file_name,
const char * rule_file_name) {
parse_original_polynomials(polys_file_name);
parse_and_check_proof_rules(rule_file_name);
}
/*------------------------------------------------------------------------*/
void checker_statistics() {
print_statistics(original_inferences, extension_inferences,
lin_comb_inferences, deletion_inferences, num_inference_rules,
addition_operations,
multiplication_operations);
}
/*------------------------------------------------------------------------*/
void reset() {
delete(target);
delete_inferences();
deallocate_mstack();
deallocate_var_list();
deallocate_terms();
deallocate_variables();
deallocate_buffer();
}
| 28.098253 | 81 | 0.595151 | [
"vector"
] |
4f7cd2d72c24985a5dfc9952d14496a49d3e3afc | 65,715 | cc | C++ | content/browser/appcache/appcache_storage_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/appcache/appcache_storage_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/appcache/appcache_storage_impl.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/appcache/appcache_storage_impl.h"
#include <stddef.h>
#include <algorithm>
#include <functional>
#include <limits>
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "content/browser/appcache/appcache.h"
#include "content/browser/appcache/appcache_database.h"
#include "content/browser/appcache/appcache_disk_cache_ops.h"
#include "content/browser/appcache/appcache_entry.h"
#include "content/browser/appcache/appcache_group.h"
#include "content/browser/appcache/appcache_histograms.h"
#include "content/browser/appcache/appcache_quota_client.h"
#include "content/browser/appcache/appcache_response_info.h"
#include "content/browser/appcache/appcache_service_impl.h"
#include "content/public/browser/browser_task_traits.h"
#include "net/base/cache_type.h"
#include "net/base/net_errors.h"
#include "sql/database.h"
#include "sql/transaction.h"
#include "storage/browser/quota/quota_client.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "third_party/blink/public/mojom/appcache/appcache_info.mojom.h"
#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
namespace content {
namespace {
constexpr const int kMB = 1024 * 1024;
// Hard coded default when not using quota management.
constexpr const int kDefaultQuota = 5 * kMB;
constexpr base::FilePath::CharType kDiskCacheDirectoryName[] =
FILE_PATH_LITERAL("Cache");
constexpr base::FilePath::CharType kAppCacheDatabaseName[] =
FILE_PATH_LITERAL("Index");
// Helpers for clearing data from the AppCacheDatabase.
bool DeleteGroupAndRelatedRecords(
AppCacheDatabase* database,
int64_t group_id,
std::vector<int64_t>* deletable_response_ids) {
AppCacheDatabase::CacheRecord cache_record;
bool success = false;
if (database->FindCacheForGroup(group_id, &cache_record)) {
database->FindResponseIdsForCacheAsVector(cache_record.cache_id,
deletable_response_ids);
success =
database->DeleteGroup(group_id) &&
database->DeleteCache(cache_record.cache_id) &&
database->DeleteEntriesForCache(cache_record.cache_id) &&
database->DeleteNamespacesForCache(cache_record.cache_id) &&
database->DeleteOnlineWhiteListForCache(cache_record.cache_id) &&
database->InsertDeletableResponseIds(*deletable_response_ids);
} else {
NOTREACHED() << "A existing group without a cache is unexpected";
success = database->DeleteGroup(group_id);
}
return success;
}
} // namespace
// static
void AppCacheStorageImpl::ClearSessionOnlyOrigins(
std::unique_ptr<AppCacheDatabase> database,
scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy,
bool force_keep_session_state) {
// If saving session state, only delete the database.
if (force_keep_session_state)
return;
bool has_session_only_appcaches =
special_storage_policy.get() &&
special_storage_policy->HasSessionOnlyOrigins();
// Clearning only session-only databases, and there are none.
if (!has_session_only_appcaches)
return;
std::set<url::Origin> origins;
database->FindOriginsWithGroups(&origins);
if (origins.empty())
return; // nothing to delete
sql::Database* connection = database->db_connection();
if (!connection) {
NOTREACHED() << "Missing database connection.";
return;
}
for (const url::Origin& origin : origins) {
if (!special_storage_policy->IsStorageSessionOnly(origin.GetURL()))
continue;
if (special_storage_policy->IsStorageProtected(origin.GetURL()))
continue;
std::vector<AppCacheDatabase::GroupRecord> groups;
database->FindGroupsForOrigin(origin, &groups);
for (const auto& group : groups) {
sql::Transaction transaction(connection);
if (!transaction.Begin()) {
NOTREACHED() << "Failed to start transaction";
return;
}
std::vector<int64_t> deletable_response_ids;
bool success = DeleteGroupAndRelatedRecords(
database.get(), group.group_id, &deletable_response_ids);
success = success && transaction.Commit();
DCHECK(success);
} // for each group
} // for each origin
}
// DatabaseTask -----------------------------------------
class AppCacheStorageImpl::DatabaseTask
: public base::RefCountedThreadSafe<DatabaseTask> {
public:
explicit DatabaseTask(AppCacheStorageImpl* storage)
: storage_(storage),
database_(storage->database_.get()),
io_thread_(base::SequencedTaskRunnerHandle::Get()) {
DCHECK(io_thread_.get());
}
void AddDelegate(DelegateReference* delegate_reference) {
delegates_.push_back(base::WrapRefCounted(delegate_reference));
}
// Schedules a task to be Run() on the DB thread. Tasks
// are run in the order in which they are scheduled.
void Schedule();
// Called on the DB thread.
virtual void Run() = 0;
// Called on the IO thread after Run() has completed.
virtual void RunCompleted() {}
// Once scheduled a task cannot be cancelled, but the
// call to RunCompleted may be. This method should only be
// called on the IO thread. This is used by AppCacheStorageImpl
// to cancel the completion calls when AppCacheStorageImpl is
// destructed. This method may be overriden to release or delete
// additional data associated with the task that is not DB thread
// safe. If overriden, this base class method must be called from
// within the override.
virtual void CancelCompletion();
protected:
friend class base::RefCountedThreadSafe<DatabaseTask>;
virtual ~DatabaseTask() = default;
AppCacheStorageImpl* storage_;
AppCacheDatabase* const database_;
std::vector<scoped_refptr<DelegateReference>> delegates_;
private:
void CallRun();
void CallRunCompleted();
void OnFatalError();
const scoped_refptr<base::SequencedTaskRunner> io_thread_;
};
void AppCacheStorageImpl::DatabaseTask::Schedule() {
DCHECK(storage_);
DCHECK(io_thread_->RunsTasksInCurrentSequence());
if (!storage_->database_)
return;
if (storage_->db_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&DatabaseTask::CallRun, this))) {
storage_->scheduled_database_tasks_.push_back(this);
} else {
NOTREACHED() << "Thread for database tasks is not running.";
}
}
void AppCacheStorageImpl::DatabaseTask::CancelCompletion() {
DCHECK(io_thread_->RunsTasksInCurrentSequence());
delegates_.clear();
storage_ = nullptr;
}
void AppCacheStorageImpl::DatabaseTask::CallRun() {
if (!database_->is_disabled()) {
Run();
if (database_->was_corruption_detected()) {
database_->Disable();
}
if (database_->is_disabled()) {
io_thread_->PostTask(FROM_HERE,
base::BindOnce(&DatabaseTask::OnFatalError, this));
}
}
io_thread_->PostTask(FROM_HERE,
base::BindOnce(&DatabaseTask::CallRunCompleted, this));
}
void AppCacheStorageImpl::DatabaseTask::CallRunCompleted() {
if (storage_) {
DCHECK(io_thread_->RunsTasksInCurrentSequence());
DCHECK(storage_->scheduled_database_tasks_.front() == this);
storage_->scheduled_database_tasks_.pop_front();
RunCompleted();
delegates_.clear();
}
}
void AppCacheStorageImpl::DatabaseTask::OnFatalError() {
if (storage_) {
DCHECK(io_thread_->RunsTasksInCurrentSequence());
storage_->Disable();
storage_->DeleteAndStartOver();
}
}
// InitTask -------
class AppCacheStorageImpl::InitTask : public DatabaseTask {
public:
explicit InitTask(AppCacheStorageImpl* storage)
: DatabaseTask(storage), last_group_id_(0),
last_cache_id_(0), last_response_id_(0),
last_deletable_response_rowid_(0) {
if (!storage->is_incognito_) {
db_file_path_ =
storage->cache_directory_.Append(kAppCacheDatabaseName);
disk_cache_directory_ =
storage->cache_directory_.Append(kDiskCacheDirectoryName);
}
}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~InitTask() override = default;
private:
base::FilePath db_file_path_;
base::FilePath disk_cache_directory_;
int64_t last_group_id_;
int64_t last_cache_id_;
int64_t last_response_id_;
int64_t last_deletable_response_rowid_;
std::map<url::Origin, int64_t> usage_map_;
};
void AppCacheStorageImpl::InitTask::Run() {
// If there is no sql database, ensure there is no disk cache either.
if (!db_file_path_.empty() &&
!base::PathExists(db_file_path_) &&
base::DirectoryExists(disk_cache_directory_)) {
base::DeleteFileRecursively(disk_cache_directory_);
if (base::DirectoryExists(disk_cache_directory_)) {
database_->Disable(); // This triggers OnFatalError handling.
return;
}
}
database_->FindLastStorageIds(
&last_group_id_, &last_cache_id_, &last_response_id_,
&last_deletable_response_rowid_);
database_->GetAllOriginUsage(&usage_map_);
}
void AppCacheStorageImpl::InitTask::RunCompleted() {
storage_->last_group_id_ = last_group_id_;
storage_->last_cache_id_ = last_cache_id_;
storage_->last_response_id_ = last_response_id_;
storage_->last_deletable_response_rowid_ = last_deletable_response_rowid_;
if (!storage_->is_disabled()) {
storage_->usage_map_.swap(usage_map_);
const base::TimeDelta kDelay = base::TimeDelta::FromMinutes(5);
base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(
&AppCacheStorageImpl::DelayedStartDeletingUnusedResponses,
storage_->weak_factory_.GetWeakPtr()),
kDelay);
}
if (storage_->service()->quota_client()) {
base::PostTask(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&AppCacheQuotaClient::NotifyAppCacheReady,
base::RetainedRef(storage_->service()->quota_client())));
}
}
// DisableDatabaseTask -------
class AppCacheStorageImpl::DisableDatabaseTask : public DatabaseTask {
public:
explicit DisableDatabaseTask(AppCacheStorageImpl* storage)
: DatabaseTask(storage) {}
// DatabaseTask:
void Run() override { database_->Disable(); }
protected:
~DisableDatabaseTask() override = default;
};
// GetAllInfoTask -------
class AppCacheStorageImpl::GetAllInfoTask : public DatabaseTask {
public:
explicit GetAllInfoTask(AppCacheStorageImpl* storage)
: DatabaseTask(storage),
info_collection_(base::MakeRefCounted<AppCacheInfoCollection>()) {}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~GetAllInfoTask() override = default;
private:
scoped_refptr<AppCacheInfoCollection> info_collection_;
};
void AppCacheStorageImpl::GetAllInfoTask::Run() {
std::set<url::Origin> origins;
database_->FindOriginsWithGroups(&origins);
for (const url::Origin& origin : origins) {
std::vector<blink::mojom::AppCacheInfo>& infos =
info_collection_->infos_by_origin[origin];
std::vector<AppCacheDatabase::GroupRecord> groups;
database_->FindGroupsForOrigin(origin, &groups);
for (const auto& group : groups) {
AppCacheDatabase::CacheRecord cache_record;
database_->FindCacheForGroup(group.group_id, &cache_record);
blink::mojom::AppCacheInfo info;
info.manifest_url = group.manifest_url;
info.creation_time = group.creation_time;
info.response_sizes = cache_record.cache_size;
info.padding_sizes = cache_record.padding_size;
info.last_access_time = group.last_access_time;
info.last_update_time = cache_record.update_time;
info.token_expires = cache_record.token_expires;
info.cache_id = cache_record.cache_id;
info.group_id = group.group_id;
info.is_complete = true;
info.manifest_parser_version = cache_record.manifest_parser_version;
info.manifest_scope = cache_record.manifest_scope;
infos.push_back(info);
}
}
}
void AppCacheStorageImpl::GetAllInfoTask::RunCompleted() {
DCHECK_EQ(1U, delegates_.size());
AppCacheStorage::ForEachDelegate(
delegates_, [&](AppCacheStorage::Delegate* delegate) {
delegate->OnAllInfo(info_collection_.get());
});
}
// StoreOrLoadTask -------
class AppCacheStorageImpl::StoreOrLoadTask : public DatabaseTask {
protected:
explicit StoreOrLoadTask(AppCacheStorageImpl* storage)
: DatabaseTask(storage) {}
~StoreOrLoadTask() override = default;
bool FindRelatedCacheRecords(int64_t cache_id);
void CreateCacheAndGroupFromRecords(
scoped_refptr<AppCache>* cache, scoped_refptr<AppCacheGroup>* group);
AppCacheDatabase::GroupRecord group_record_;
AppCacheDatabase::CacheRecord cache_record_;
std::vector<AppCacheDatabase::EntryRecord> entry_records_;
std::vector<AppCacheDatabase::NamespaceRecord>
intercept_namespace_records_;
std::vector<AppCacheDatabase::NamespaceRecord>
fallback_namespace_records_;
std::vector<AppCacheDatabase::OnlineWhiteListRecord>
online_whitelist_records_;
};
bool AppCacheStorageImpl::StoreOrLoadTask::FindRelatedCacheRecords(
int64_t cache_id) {
return database_->FindEntriesForCache(cache_id, &entry_records_) &&
database_->FindNamespacesForCache(
cache_id, &intercept_namespace_records_,
&fallback_namespace_records_) &&
database_->FindOnlineWhiteListForCache(
cache_id, &online_whitelist_records_);
}
void AppCacheStorageImpl::StoreOrLoadTask::CreateCacheAndGroupFromRecords(
scoped_refptr<AppCache>* cache, scoped_refptr<AppCacheGroup>* group) {
DCHECK(storage_ && cache && group);
(*cache) = storage_->working_set_.GetCache(cache_record_.cache_id);
if (cache->get()) {
(*group) = cache->get()->owning_group();
DCHECK(group->get());
DCHECK_EQ(group_record_.group_id, group->get()->group_id());
// TODO(pwnall): A removed histogram shows that, very rarely,
// cache->get()->GetEntry(group_record_.manifest_url))
// return null here. This was supposed to help investigate
// https://crbug.com/95101
storage_->NotifyStorageAccessed(group_record_.origin);
return;
}
*cache = base::MakeRefCounted<AppCache>(storage_, cache_record_.cache_id);
cache->get()->InitializeWithDatabaseRecords(
cache_record_, entry_records_,
intercept_namespace_records_,
fallback_namespace_records_,
online_whitelist_records_);
cache->get()->set_complete(true);
*group = storage_->working_set_.GetGroup(group_record_.manifest_url);
if (group->get()) {
DCHECK(group_record_.group_id == group->get()->group_id());
group->get()->AddCache(cache->get());
} else {
*group = base::MakeRefCounted<AppCacheGroup>(
storage_, group_record_.manifest_url, group_record_.group_id);
group->get()->set_creation_time(group_record_.creation_time);
group->get()->set_last_full_update_check_time(
group_record_.last_full_update_check_time);
group->get()->set_first_evictable_error_time(
group_record_.first_evictable_error_time);
group->get()->AddCache(cache->get());
// TODO(pwnall): A removed histogram shows that, very rarely,
// cache->get()->GetEntry(group_record_.manifest_url))
// return null here. This was supposed to help investigate
// https://crbug.com/95101
}
DCHECK(group->get()->newest_complete_cache() == cache->get());
// We have to update foriegn entries if MarkEntryAsForeignTasks
// are in flight.
std::vector<GURL> urls =
storage_->GetPendingForeignMarkingsForCache(cache->get()->cache_id());
for (const auto& url : urls) {
// Skip any entries that were marked as foreign but that don't actually
// exist. This shouldn't happen other than with misbehaving renderers, but
// we've always just ignored these when the cache already exists when
// MarkEntryAsForeign is called, so also ignore them here when the cache
// still had to be created.
// If AppCache wouldn't be in maintenance mode only, we might want to
// (async) ReportBadMessage here and in MarkEntryAsForeign, and deal
// with any resulting crashes, but for now just keep the existing behavior.
if (!cache->get()->GetEntry(url))
continue;
cache->get()->GetEntry(url)->add_types(AppCacheEntry::FOREIGN);
}
storage_->NotifyStorageAccessed(group_record_.origin);
// TODO(michaeln): Maybe verify that the responses we expect to exist
// do actually exist in the disk_cache (and if not then what?)
}
// CacheLoadTask -------
class AppCacheStorageImpl::CacheLoadTask : public StoreOrLoadTask {
public:
CacheLoadTask(int64_t cache_id, AppCacheStorageImpl* storage)
: StoreOrLoadTask(storage), cache_id_(cache_id), success_(false) {}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~CacheLoadTask() override = default;
private:
int64_t cache_id_;
bool success_;
};
void AppCacheStorageImpl::CacheLoadTask::Run() {
success_ =
database_->FindCache(cache_id_, &cache_record_) &&
database_->FindGroup(cache_record_.group_id, &group_record_) &&
FindRelatedCacheRecords(cache_id_);
if (success_)
database_->LazyUpdateLastAccessTime(group_record_.group_id,
base::Time::Now());
}
void AppCacheStorageImpl::CacheLoadTask::RunCompleted() {
storage_->pending_cache_loads_.erase(cache_id_);
scoped_refptr<AppCache> cache;
scoped_refptr<AppCacheGroup> group;
if (success_ && !storage_->is_disabled()) {
storage_->LazilyCommitLastAccessTimes();
DCHECK(cache_record_.cache_id == cache_id_);
CreateCacheAndGroupFromRecords(&cache, &group);
}
AppCacheStorage::ForEachDelegate(
delegates_, [&](AppCacheStorage::Delegate* delegate) {
delegate->OnCacheLoaded(cache.get(), cache_id_);
});
}
// GroupLoadTask -------
class AppCacheStorageImpl::GroupLoadTask : public StoreOrLoadTask {
public:
GroupLoadTask(GURL manifest_url, AppCacheStorageImpl* storage)
: StoreOrLoadTask(storage), manifest_url_(manifest_url),
success_(false) {}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~GroupLoadTask() override = default;
private:
GURL manifest_url_;
bool success_;
};
void AppCacheStorageImpl::GroupLoadTask::Run() {
success_ =
database_->FindGroupForManifestUrl(manifest_url_, &group_record_) &&
database_->FindCacheForGroup(group_record_.group_id, &cache_record_) &&
FindRelatedCacheRecords(cache_record_.cache_id);
if (success_) {
database_->LazyUpdateLastAccessTime(group_record_.group_id,
base::Time::Now());
}
}
void AppCacheStorageImpl::GroupLoadTask::RunCompleted() {
storage_->pending_group_loads_.erase(manifest_url_);
scoped_refptr<AppCacheGroup> group;
scoped_refptr<AppCache> cache;
if (!storage_->is_disabled()) {
if (success_) {
storage_->LazilyCommitLastAccessTimes();
DCHECK(group_record_.manifest_url == manifest_url_);
CreateCacheAndGroupFromRecords(&cache, &group);
} else {
group = storage_->working_set_.GetGroup(manifest_url_);
if (!group.get()) {
group = base::MakeRefCounted<AppCacheGroup>(storage_, manifest_url_,
storage_->NewGroupId());
}
}
}
AppCacheStorage::ForEachDelegate(
delegates_, [&](AppCacheStorage::Delegate* delegate) {
delegate->OnGroupLoaded(group.get(), manifest_url_);
});
}
// StoreGroupAndCacheTask -------
class AppCacheStorageImpl::StoreGroupAndCacheTask : public StoreOrLoadTask {
public:
StoreGroupAndCacheTask(AppCacheStorageImpl* storage, AppCacheGroup* group,
AppCache* newest_cache);
void GetQuotaThenSchedule();
void OnQuotaCallback(blink::mojom::QuotaStatusCode status,
int64_t usage,
int64_t quota);
// DatabaseTask:
void Run() override;
void RunCompleted() override;
void CancelCompletion() override;
protected:
~StoreGroupAndCacheTask() override = default;
private:
scoped_refptr<AppCacheGroup> group_;
scoped_refptr<AppCache> cache_;
bool success_;
bool would_exceed_quota_;
int64_t space_available_;
int64_t new_origin_usage_;
std::vector<int64_t> newly_deletable_response_ids_;
};
AppCacheStorageImpl::StoreGroupAndCacheTask::StoreGroupAndCacheTask(
AppCacheStorageImpl* storage,
AppCacheGroup* group,
AppCache* newest_cache)
: StoreOrLoadTask(storage),
group_(group),
cache_(newest_cache),
success_(false),
would_exceed_quota_(false),
space_available_(-1),
new_origin_usage_(-1) {
group_record_.group_id = group->group_id();
group_record_.manifest_url = group->manifest_url();
group_record_.origin = url::Origin::Create(group_record_.manifest_url);
group_record_.last_full_update_check_time =
group->last_full_update_check_time();
group_record_.first_evictable_error_time =
group->first_evictable_error_time();
newest_cache->ToDatabaseRecords(
group,
&cache_record_, &entry_records_,
&intercept_namespace_records_,
&fallback_namespace_records_,
&online_whitelist_records_);
}
void AppCacheStorageImpl::StoreGroupAndCacheTask::GetQuotaThenSchedule() {
if (!storage_->service()->quota_manager_proxy()) {
if (storage_->service()->special_storage_policy() &&
storage_->service()->special_storage_policy()->IsStorageUnlimited(
group_record_.origin.GetURL()))
space_available_ = std::numeric_limits<int64_t>::max();
Schedule();
return;
}
// We have to ask the quota manager for the value.
storage_->pending_quota_queries_.insert(this);
storage_->service()->quota_manager_proxy()->GetUsageAndQuota(
base::ThreadTaskRunnerHandle::Get().get(), group_record_.origin,
blink::mojom::StorageType::kTemporary,
base::BindOnce(&StoreGroupAndCacheTask::OnQuotaCallback, this));
}
void AppCacheStorageImpl::StoreGroupAndCacheTask::OnQuotaCallback(
blink::mojom::QuotaStatusCode status,
int64_t usage,
int64_t quota) {
if (storage_) {
if (status == blink::mojom::QuotaStatusCode::kOk)
space_available_ = std::max(static_cast<int64_t>(0), quota - usage);
else
space_available_ = 0;
storage_->pending_quota_queries_.erase(this);
Schedule();
}
}
void AppCacheStorageImpl::StoreGroupAndCacheTask::Run() {
DCHECK(!success_);
sql::Database* const connection = database_->db_connection();
if (!connection)
return;
sql::Transaction transaction(connection);
if (!transaction.Begin())
return;
int64_t old_origin_usage = database_->GetOriginUsage(group_record_.origin);
AppCacheDatabase::GroupRecord existing_group;
success_ = database_->FindGroup(group_record_.group_id, &existing_group);
if (!success_) {
group_record_.creation_time = base::Time::Now();
group_record_.last_access_time = base::Time::Now();
success_ = database_->InsertGroup(&group_record_);
} else {
DCHECK(group_record_.group_id == existing_group.group_id);
DCHECK(group_record_.manifest_url == existing_group.manifest_url);
DCHECK(group_record_.origin == existing_group.origin);
database_->UpdateLastAccessTime(group_record_.group_id,
base::Time::Now());
database_->UpdateEvictionTimes(group_record_.group_id,
group_record_.last_full_update_check_time,
group_record_.first_evictable_error_time);
AppCacheDatabase::CacheRecord cache;
if (database_->FindCacheForGroup(group_record_.group_id, &cache)) {
// Get the set of response ids in the old cache.
std::set<int64_t> existing_response_ids;
database_->FindResponseIdsForCacheAsSet(cache.cache_id,
&existing_response_ids);
// Remove those that remain in the new cache.
for (const auto& entry : entry_records_)
existing_response_ids.erase(entry.response_id);
// The rest are deletable.
for (const auto& id : existing_response_ids)
newly_deletable_response_ids_.push_back(id);
success_ =
database_->DeleteCache(cache.cache_id) &&
database_->DeleteEntriesForCache(cache.cache_id) &&
database_->DeleteNamespacesForCache(cache.cache_id) &&
database_->DeleteOnlineWhiteListForCache(cache.cache_id) &&
database_->InsertDeletableResponseIds(newly_deletable_response_ids_);
// TODO(michaeln): store group_id too with deletable ids
} else {
NOTREACHED() << "A existing group without a cache is unexpected";
}
}
success_ =
success_ &&
database_->InsertCache(&cache_record_) &&
database_->InsertEntryRecords(entry_records_) &&
database_->InsertNamespaceRecords(intercept_namespace_records_) &&
database_->InsertNamespaceRecords(fallback_namespace_records_) &&
database_->InsertOnlineWhiteListRecords(online_whitelist_records_);
if (!success_)
return;
new_origin_usage_ = database_->GetOriginUsage(group_record_.origin);
// Only check quota when the new usage exceeds the old usage.
if (new_origin_usage_ <= old_origin_usage) {
success_ = transaction.Commit();
return;
}
// Use a simple hard-coded value when not using quota management.
if (space_available_ == -1) {
if (new_origin_usage_ > kDefaultQuota) {
would_exceed_quota_ = true;
success_ = false;
return;
}
success_ = transaction.Commit();
return;
}
// Check limits based on the space availbable given to us via the
// quota system.
int64_t delta = new_origin_usage_ - old_origin_usage;
if (delta > space_available_) {
would_exceed_quota_ = true;
success_ = false;
return;
}
success_ = transaction.Commit();
}
void AppCacheStorageImpl::StoreGroupAndCacheTask::RunCompleted() {
if (success_) {
storage_->UpdateUsageMapAndNotify(
url::Origin::Create(group_->manifest_url()), new_origin_usage_);
if (cache_.get() != group_->newest_complete_cache()) {
cache_->set_complete(true);
group_->AddCache(cache_.get());
}
if (group_->creation_time().is_null())
group_->set_creation_time(group_record_.creation_time);
group_->AddNewlyDeletableResponseIds(&newly_deletable_response_ids_);
}
AppCacheStorage::ForEachDelegate(
delegates_, [&](AppCacheStorage::Delegate* delegate) {
delegate->OnGroupAndNewestCacheStored(group_.get(), cache_.get(),
success_, would_exceed_quota_);
});
group_ = nullptr;
cache_ = nullptr;
// TODO(michaeln): if (would_exceed_quota_) what if the current usage
// also exceeds the quota? http://crbug.com/83968
}
void AppCacheStorageImpl::StoreGroupAndCacheTask::CancelCompletion() {
// Overriden to safely drop our reference to the group and cache
// which are not thread safe refcounted.
DatabaseTask::CancelCompletion();
group_ = nullptr;
cache_ = nullptr;
}
// FindMainResponseTask -------
// Helpers for FindMainResponseTask::Run()
namespace {
class SortByCachePreference {
public:
SortByCachePreference(int64_t preferred_id,
const std::set<int64_t>& in_use_ids)
: preferred_id_(preferred_id), in_use_ids_(in_use_ids) {}
bool operator()(
const AppCacheDatabase::EntryRecord& lhs,
const AppCacheDatabase::EntryRecord& rhs) {
return compute_value(lhs) > compute_value(rhs);
}
private:
int compute_value(const AppCacheDatabase::EntryRecord& entry) {
if (entry.cache_id == preferred_id_)
return 100;
else if (in_use_ids_.find(entry.cache_id) != in_use_ids_.end())
return 50;
return 0;
}
int64_t preferred_id_;
const std::set<int64_t>& in_use_ids_;
};
bool SortByLength(
const AppCacheDatabase::NamespaceRecord& lhs,
const AppCacheDatabase::NamespaceRecord& rhs) {
return lhs.namespace_.namespace_url.spec().length() >
rhs.namespace_.namespace_url.spec().length();
}
class NetworkNamespaceHelper {
public:
explicit NetworkNamespaceHelper(AppCacheDatabase* database)
: database_(database) {
}
bool IsInNetworkNamespace(const GURL& url, int64_t cache_id) {
std::pair<WhiteListMap::iterator, bool> result = namespaces_map_.insert(
WhiteListMap::value_type(cache_id, std::vector<AppCacheNamespace>()));
if (result.second)
GetOnlineWhiteListForCache(cache_id, &result.first->second);
return AppCache::FindNamespace(result.first->second, url) != nullptr;
}
private:
void GetOnlineWhiteListForCache(int64_t cache_id,
std::vector<AppCacheNamespace>* namespaces) {
DCHECK(namespaces && namespaces->empty());
using WhiteListVector =
std::vector<AppCacheDatabase::OnlineWhiteListRecord>;
WhiteListVector records;
if (!database_->FindOnlineWhiteListForCache(cache_id, &records))
return;
for (const auto& record : records) {
namespaces->push_back(AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE,
record.namespace_url, GURL()));
}
}
// Key is cache id
using WhiteListMap = std::map<int64_t, std::vector<AppCacheNamespace>>;
WhiteListMap namespaces_map_;
AppCacheDatabase* const database_;
};
} // namespace
class AppCacheStorageImpl::FindMainResponseTask : public DatabaseTask {
public:
FindMainResponseTask(AppCacheStorageImpl* storage,
const GURL& url,
const GURL& preferred_manifest_url,
const AppCacheWorkingSet::GroupMap* groups_in_use)
: DatabaseTask(storage),
url_(url),
preferred_manifest_url_(preferred_manifest_url),
cache_id_(blink::mojom::kAppCacheNoCacheId),
group_id_(0) {
if (groups_in_use) {
for (const auto& pair : *groups_in_use) {
AppCacheGroup* group = pair.second;
AppCache* cache = group->newest_complete_cache();
if (group->is_obsolete() || !cache)
continue;
cache_ids_in_use_.insert(cache->cache_id());
}
}
}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~FindMainResponseTask() override = default;
private:
using NamespaceRecordPtrVector =
std::vector<AppCacheDatabase::NamespaceRecord*>;
bool FindExactMatch(int64_t preferred_id);
bool FindNamespaceMatch(int64_t preferred_id);
bool FindNamespaceHelper(int64_t preferred_cache_id,
AppCacheDatabase::NamespaceRecordVector* namespaces,
NetworkNamespaceHelper* network_namespace_helper);
bool FindFirstValidNamespace(const NamespaceRecordPtrVector& namespaces);
GURL url_;
GURL preferred_manifest_url_;
std::set<int64_t> cache_ids_in_use_;
AppCacheEntry entry_;
AppCacheEntry fallback_entry_;
GURL namespace_entry_url_;
int64_t cache_id_;
int64_t group_id_;
GURL manifest_url_;
};
void AppCacheStorageImpl::FindMainResponseTask::Run() {
// NOTE: The heuristics around choosing amoungst multiple candidates
// is underspecified, and just plain not fully understood. This needs
// to be refined.
// The 'preferred_manifest_url' is the url of the manifest associated
// with the page that opened or embedded the page being loaded now.
// We have a strong preference to use resources from that cache.
// We also have a lesser bias to use resources from caches that are currently
// being used by other unrelated pages.
// TODO(michaeln): come up with a 'preferred_manifest_url' in more cases
// - when navigating a frame whose current contents are from an appcache
// - when clicking an href in a frame that is appcached
int64_t preferred_cache_id = blink::mojom::kAppCacheNoCacheId;
if (!preferred_manifest_url_.is_empty()) {
AppCacheDatabase::GroupRecord preferred_group;
AppCacheDatabase::CacheRecord preferred_cache;
if (database_->FindGroupForManifestUrl(
preferred_manifest_url_, &preferred_group) &&
database_->FindCacheForGroup(
preferred_group.group_id, &preferred_cache)) {
preferred_cache_id = preferred_cache.cache_id;
}
}
if (FindExactMatch(preferred_cache_id) ||
FindNamespaceMatch(preferred_cache_id)) {
// We found something.
DCHECK(cache_id_ != blink::mojom::kAppCacheNoCacheId &&
!manifest_url_.is_empty() && group_id_ != 0);
return;
}
// We didn't find anything.
DCHECK(cache_id_ == blink::mojom::kAppCacheNoCacheId &&
manifest_url_.is_empty() && group_id_ == 0);
}
bool AppCacheStorageImpl::FindMainResponseTask::FindExactMatch(
int64_t preferred_cache_id) {
std::vector<AppCacheDatabase::EntryRecord> entries;
if (database_->FindEntriesForUrl(url_, &entries) && !entries.empty()) {
// Sort them in order of preference, from the preferred_cache first,
// followed by hits from caches that are 'in use', then the rest.
std::sort(entries.begin(), entries.end(),
SortByCachePreference(preferred_cache_id, cache_ids_in_use_));
// Take the first with a valid, non-foreign entry.
for (const auto& entry : entries) {
AppCacheDatabase::GroupRecord group_record;
if ((entry.flags & AppCacheEntry::FOREIGN) ||
!database_->FindGroupForCache(entry.cache_id, &group_record)) {
continue;
}
manifest_url_ = group_record.manifest_url;
group_id_ = group_record.group_id;
entry_ = AppCacheEntry(entry.flags, entry.response_id);
cache_id_ = entry.cache_id;
return true; // We found an exact match.
}
}
return false;
}
bool AppCacheStorageImpl::FindMainResponseTask::FindNamespaceMatch(
int64_t preferred_cache_id) {
AppCacheDatabase::NamespaceRecordVector all_intercepts;
AppCacheDatabase::NamespaceRecordVector all_fallbacks;
if (!database_->FindNamespacesForOrigin(url::Origin::Create(url_),
&all_intercepts, &all_fallbacks) ||
(all_intercepts.empty() && all_fallbacks.empty())) {
return false;
}
NetworkNamespaceHelper network_namespace_helper(database_);
if (FindNamespaceHelper(preferred_cache_id,
&all_intercepts,
&network_namespace_helper) ||
FindNamespaceHelper(preferred_cache_id,
&all_fallbacks,
&network_namespace_helper)) {
return true;
}
return false;
}
bool AppCacheStorageImpl::FindMainResponseTask::FindNamespaceHelper(
int64_t preferred_cache_id,
AppCacheDatabase::NamespaceRecordVector* namespaces,
NetworkNamespaceHelper* network_namespace_helper) {
// Sort them by length, longer matches within the same cache/bucket take
// precedence.
std::sort(namespaces->begin(), namespaces->end(), SortByLength);
NamespaceRecordPtrVector preferred_namespaces;
NamespaceRecordPtrVector inuse_namespaces;
NamespaceRecordPtrVector other_namespaces;
for (auto& namespace_record : *namespaces) {
// Skip those that aren't a match.
if (!namespace_record.namespace_.IsMatch(url_))
continue;
// Skip namespaces where the requested url falls into a network
// namespace of its containing appcache.
if (network_namespace_helper->IsInNetworkNamespace(
url_, namespace_record.cache_id))
continue;
// Bin them into one of our three buckets.
if (namespace_record.cache_id == preferred_cache_id)
preferred_namespaces.push_back(&namespace_record);
else if (cache_ids_in_use_.find(namespace_record.cache_id) !=
cache_ids_in_use_.end())
inuse_namespaces.push_back(&namespace_record);
else
other_namespaces.push_back(&namespace_record);
}
if (FindFirstValidNamespace(preferred_namespaces) ||
FindFirstValidNamespace(inuse_namespaces) ||
FindFirstValidNamespace(other_namespaces))
return true; // We found one.
// We didn't find anything.
return false;
}
bool AppCacheStorageImpl::
FindMainResponseTask::FindFirstValidNamespace(
const NamespaceRecordPtrVector& namespaces) {
// Take the first with a valid, non-foreign entry.
for (auto* namespace_record : namespaces) {
AppCacheDatabase::EntryRecord entry_record;
if (database_->FindEntry(namespace_record->cache_id,
namespace_record->namespace_.target_url,
&entry_record)) {
AppCacheDatabase::GroupRecord group_record;
if ((entry_record.flags & AppCacheEntry::FOREIGN) ||
!database_->FindGroupForCache(entry_record.cache_id, &group_record)) {
continue;
}
manifest_url_ = group_record.manifest_url;
group_id_ = group_record.group_id;
cache_id_ = namespace_record->cache_id;
namespace_entry_url_ = namespace_record->namespace_.target_url;
if (namespace_record->namespace_.type == APPCACHE_FALLBACK_NAMESPACE)
fallback_entry_ = AppCacheEntry(entry_record.flags,
entry_record.response_id);
else
entry_ = AppCacheEntry(entry_record.flags, entry_record.response_id);
return true; // We found one.
}
}
return false; // We didn't find a match.
}
void AppCacheStorageImpl::FindMainResponseTask::RunCompleted() {
storage_->CallOnMainResponseFound(
&delegates_, url_, entry_, namespace_entry_url_, fallback_entry_,
cache_id_, group_id_, manifest_url_);
}
// MarkEntryAsForeignTask -------
class AppCacheStorageImpl::MarkEntryAsForeignTask : public DatabaseTask {
public:
MarkEntryAsForeignTask(AppCacheStorageImpl* storage,
const GURL& url,
int64_t cache_id)
: DatabaseTask(storage), cache_id_(cache_id), entry_url_(url) {}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~MarkEntryAsForeignTask() override = default;
private:
int64_t cache_id_;
GURL entry_url_;
};
void AppCacheStorageImpl::MarkEntryAsForeignTask::Run() {
database_->AddEntryFlags(entry_url_, cache_id_, AppCacheEntry::FOREIGN);
}
void AppCacheStorageImpl::MarkEntryAsForeignTask::RunCompleted() {
DCHECK(storage_->pending_foreign_markings_.front().first == entry_url_ &&
storage_->pending_foreign_markings_.front().second == cache_id_);
storage_->pending_foreign_markings_.pop_front();
}
// MakeGroupObsoleteTask -------
class AppCacheStorageImpl::MakeGroupObsoleteTask : public DatabaseTask {
public:
MakeGroupObsoleteTask(AppCacheStorageImpl* storage,
AppCacheGroup* group,
int response_code);
// DatabaseTask:
void Run() override;
void RunCompleted() override;
void CancelCompletion() override;
protected:
~MakeGroupObsoleteTask() override = default;
private:
scoped_refptr<AppCacheGroup> group_;
int64_t group_id_;
url::Origin origin_;
bool success_;
int response_code_;
int64_t new_origin_usage_;
std::vector<int64_t> newly_deletable_response_ids_;
};
AppCacheStorageImpl::MakeGroupObsoleteTask::MakeGroupObsoleteTask(
AppCacheStorageImpl* storage,
AppCacheGroup* group,
int response_code)
: DatabaseTask(storage),
group_(group),
group_id_(group->group_id()),
origin_(url::Origin::Create(group->manifest_url())),
success_(false),
response_code_(response_code),
new_origin_usage_(-1) {}
void AppCacheStorageImpl::MakeGroupObsoleteTask::Run() {
DCHECK(!success_);
sql::Database* connection = database_->db_connection();
if (!connection)
return;
sql::Transaction transaction(connection);
if (!transaction.Begin())
return;
AppCacheDatabase::GroupRecord group_record;
if (!database_->FindGroup(group_id_, &group_record)) {
// This group doesn't exists in the database, nothing todo here.
new_origin_usage_ = database_->GetOriginUsage(origin_);
success_ = true;
return;
}
DCHECK_EQ(group_record.origin, origin_);
success_ = DeleteGroupAndRelatedRecords(database_,
group_id_,
&newly_deletable_response_ids_);
new_origin_usage_ = database_->GetOriginUsage(origin_);
success_ = success_ && transaction.Commit();
}
void AppCacheStorageImpl::MakeGroupObsoleteTask::RunCompleted() {
if (success_) {
group_->set_obsolete(true);
if (!storage_->is_disabled()) {
storage_->UpdateUsageMapAndNotify(origin_, new_origin_usage_);
group_->AddNewlyDeletableResponseIds(&newly_deletable_response_ids_);
// Also remove from the working set, caches for an 'obsolete' group
// may linger in use, but the group itself cannot be looked up by
// 'manifest_url' in the working set any longer.
storage_->working_set()->RemoveGroup(group_.get());
}
}
AppCacheStorage::ForEachDelegate(
delegates_, [&](AppCacheStorage::Delegate* delegate) {
delegate->OnGroupMadeObsolete(group_.get(), success_, response_code_);
});
group_ = nullptr;
}
void AppCacheStorageImpl::MakeGroupObsoleteTask::CancelCompletion() {
// Overriden to safely drop our reference to the group
// which is not thread safe refcounted.
DatabaseTask::CancelCompletion();
group_ = nullptr;
}
// GetDeletableResponseIdsTask -------
class AppCacheStorageImpl::GetDeletableResponseIdsTask : public DatabaseTask {
public:
GetDeletableResponseIdsTask(AppCacheStorageImpl* storage, int64_t max_rowid)
: DatabaseTask(storage), max_rowid_(max_rowid) {}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~GetDeletableResponseIdsTask() override = default;
private:
int64_t max_rowid_;
std::vector<int64_t> response_ids_;
};
void AppCacheStorageImpl::GetDeletableResponseIdsTask::Run() {
const int kSqlLimit = 1000;
database_->GetDeletableResponseIds(&response_ids_, max_rowid_, kSqlLimit);
// TODO(michaeln): retrieve group_ids too
}
void AppCacheStorageImpl::GetDeletableResponseIdsTask::RunCompleted() {
if (!response_ids_.empty())
storage_->StartDeletingResponses(response_ids_);
}
// InsertDeletableResponseIdsTask -------
class AppCacheStorageImpl::InsertDeletableResponseIdsTask
: public DatabaseTask {
public:
explicit InsertDeletableResponseIdsTask(AppCacheStorageImpl* storage)
: DatabaseTask(storage) {}
// DatabaseTask:
void Run() override;
std::vector<int64_t> response_ids_;
protected:
~InsertDeletableResponseIdsTask() override = default;
};
void AppCacheStorageImpl::InsertDeletableResponseIdsTask::Run() {
database_->InsertDeletableResponseIds(response_ids_);
// TODO(michaeln): store group_ids too
}
// DeleteDeletableResponseIdsTask -------
class AppCacheStorageImpl::DeleteDeletableResponseIdsTask
: public DatabaseTask {
public:
explicit DeleteDeletableResponseIdsTask(AppCacheStorageImpl* storage)
: DatabaseTask(storage) {}
// DatabaseTask:
void Run() override;
std::vector<int64_t> response_ids_;
protected:
~DeleteDeletableResponseIdsTask() override = default;
};
void AppCacheStorageImpl::DeleteDeletableResponseIdsTask::Run() {
database_->DeleteDeletableResponseIds(response_ids_);
}
// LazyUpdateLastAccessTimeTask -------
class AppCacheStorageImpl::LazyUpdateLastAccessTimeTask
: public DatabaseTask {
public:
LazyUpdateLastAccessTimeTask(
AppCacheStorageImpl* storage, AppCacheGroup* group, base::Time time)
: DatabaseTask(storage), group_id_(group->group_id()),
last_access_time_(time) {
storage->NotifyStorageAccessed(url::Origin::Create(group->manifest_url()));
}
// DatabaseTask:
void Run() override;
void RunCompleted() override;
protected:
~LazyUpdateLastAccessTimeTask() override = default;
private:
int64_t group_id_;
base::Time last_access_time_;
};
void AppCacheStorageImpl::LazyUpdateLastAccessTimeTask::Run() {
database_->LazyUpdateLastAccessTime(group_id_, last_access_time_);
}
void AppCacheStorageImpl::LazyUpdateLastAccessTimeTask::RunCompleted() {
storage_->LazilyCommitLastAccessTimes();
}
// CommitLastAccessTimesTask -------
class AppCacheStorageImpl::CommitLastAccessTimesTask
: public DatabaseTask {
public:
explicit CommitLastAccessTimesTask(AppCacheStorageImpl* storage)
: DatabaseTask(storage) {}
// DatabaseTask:
void Run() override {
database_->CommitLazyLastAccessTimes();
}
protected:
~CommitLastAccessTimesTask() override = default;
};
// UpdateEvictionTimes -------
class AppCacheStorageImpl::UpdateEvictionTimesTask
: public DatabaseTask {
public:
UpdateEvictionTimesTask(AppCacheStorageImpl* storage, AppCacheGroup* group)
: DatabaseTask(storage),
group_id_(group->group_id()),
last_full_update_check_time_(group->last_full_update_check_time()),
first_evictable_error_time_(group->first_evictable_error_time()) {}
// DatabaseTask:
void Run() override;
protected:
~UpdateEvictionTimesTask() override = default;
private:
int64_t group_id_;
base::Time last_full_update_check_time_;
base::Time first_evictable_error_time_;
};
void AppCacheStorageImpl::UpdateEvictionTimesTask::Run() {
database_->UpdateEvictionTimes(group_id_, last_full_update_check_time_,
first_evictable_error_time_);
}
// AppCacheStorageImpl ---------------------------------------------------
AppCacheStorageImpl::AppCacheStorageImpl(AppCacheServiceImpl* service)
: AppCacheStorage(service),
is_incognito_(false),
is_response_deletion_scheduled_(false),
did_start_deleting_responses_(false),
last_deletable_response_rowid_(0),
database_(nullptr),
is_disabled_(false),
delete_and_start_over_pending_(false),
expecting_cleanup_complete_on_disable_(false) {}
AppCacheStorageImpl::~AppCacheStorageImpl() {
for (StoreGroupAndCacheTask* task : pending_quota_queries_)
task->CancelCompletion();
for (DatabaseTask* task : scheduled_database_tasks_)
task->CancelCompletion();
if (database_ &&
!db_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&ClearSessionOnlyOrigins, std::move(database_),
base::WrapRefCounted(service_->special_storage_policy()),
service()->force_keep_session_state()))) {
}
}
void AppCacheStorageImpl::Initialize(
const base::FilePath& cache_directory,
const scoped_refptr<base::SequencedTaskRunner>& db_task_runner) {
cache_directory_ = cache_directory;
is_incognito_ = cache_directory_.empty();
base::FilePath db_file_path;
if (!is_incognito_)
db_file_path = cache_directory_.Append(kAppCacheDatabaseName);
database_ = std::make_unique<AppCacheDatabase>(db_file_path);
db_task_runner_ = db_task_runner;
auto task = base::MakeRefCounted<InitTask>(this);
task->Schedule();
}
void AppCacheStorageImpl::Disable() {
if (is_disabled_)
return;
VLOG(1) << "Disabling appcache storage.";
is_disabled_ = true;
ClearUsageMapAndNotify();
working_set()->Disable();
if (disk_cache_)
disk_cache_->Disable();
auto task = base::MakeRefCounted<DisableDatabaseTask>(this);
task->Schedule();
}
void AppCacheStorageImpl::GetAllInfo(Delegate* delegate) {
DCHECK(delegate);
auto task = base::MakeRefCounted<GetAllInfoTask>(this);
task->AddDelegate(GetOrCreateDelegateReference(delegate));
task->Schedule();
}
void AppCacheStorageImpl::LoadCache(int64_t id, Delegate* delegate) {
DCHECK(delegate);
if (is_disabled_) {
delegate->OnCacheLoaded(nullptr, id);
return;
}
AppCache* cache = working_set_.GetCache(id);
if (cache) {
delegate->OnCacheLoaded(cache, id);
if (cache->owning_group()) {
auto update_task = base::MakeRefCounted<LazyUpdateLastAccessTimeTask>(
this, cache->owning_group(), base::Time::Now());
update_task->Schedule();
}
return;
}
scoped_refptr<CacheLoadTask> task(GetPendingCacheLoadTask(id));
if (task.get()) {
task->AddDelegate(GetOrCreateDelegateReference(delegate));
return;
}
task = base::MakeRefCounted<CacheLoadTask>(id, this);
task->AddDelegate(GetOrCreateDelegateReference(delegate));
task->Schedule();
pending_cache_loads_[id] = task.get();
}
void AppCacheStorageImpl::LoadOrCreateGroup(
const GURL& manifest_url, Delegate* delegate) {
DCHECK(delegate);
if (is_disabled_) {
delegate->OnGroupLoaded(nullptr, manifest_url);
return;
}
AppCacheGroup* group = working_set_.GetGroup(manifest_url);
if (group) {
delegate->OnGroupLoaded(group, manifest_url);
auto update_task = base::MakeRefCounted<LazyUpdateLastAccessTimeTask>(
this, group, base::Time::Now());
update_task->Schedule();
return;
}
scoped_refptr<GroupLoadTask> task(GetPendingGroupLoadTask(manifest_url));
if (task.get()) {
task->AddDelegate(GetOrCreateDelegateReference(delegate));
return;
}
if (usage_map_.find(url::Origin::Create(manifest_url)) == usage_map_.end()) {
// No need to query the database, return a new group immediately.
auto new_group =
base::MakeRefCounted<AppCacheGroup>(this, manifest_url, NewGroupId());
delegate->OnGroupLoaded(new_group.get(), manifest_url);
return;
}
task = base::MakeRefCounted<GroupLoadTask>(manifest_url, this);
task->AddDelegate(GetOrCreateDelegateReference(delegate));
task->Schedule();
pending_group_loads_[manifest_url] = task.get();
}
void AppCacheStorageImpl::StoreGroupAndNewestCache(
AppCacheGroup* group, AppCache* newest_cache, Delegate* delegate) {
// TODO(michaeln): distinguish between a simple update of an existing
// cache that just adds new master entry(s), and the insertion of a
// whole new cache. The StoreGroupAndCacheTask as written will handle
// the simple update case in a very heavy weight way (delete all and
// the reinsert all over again).
DCHECK(group && delegate && newest_cache);
auto task =
base::MakeRefCounted<StoreGroupAndCacheTask>(this, group, newest_cache);
task->AddDelegate(GetOrCreateDelegateReference(delegate));
task->GetQuotaThenSchedule();
}
void AppCacheStorageImpl::FindResponseForMainRequest(
const GURL& url, const GURL& preferred_manifest_url,
Delegate* delegate) {
DCHECK(delegate);
const GURL* url_ptr = &url;
GURL url_no_ref;
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url_no_ref = url.ReplaceComponents(replacements);
url_ptr = &url_no_ref;
}
const url::Origin origin(url::Origin::Create(url));
// First look in our working set for a direct hit without having to query
// the database.
const AppCacheWorkingSet::GroupMap* groups_in_use =
working_set()->GetGroupsInOrigin(origin);
if (groups_in_use) {
if (!preferred_manifest_url.is_empty()) {
auto found = groups_in_use->find(preferred_manifest_url);
if (found != groups_in_use->end() &&
FindResponseForMainRequestInGroup(
found->second, *url_ptr, delegate)) {
return;
}
} else {
for (const auto& pair : *groups_in_use) {
if (FindResponseForMainRequestInGroup(pair.second, *url_ptr,
delegate)) {
return;
}
}
}
}
if (IsInitTaskComplete() && usage_map_.find(origin) == usage_map_.end()) {
// No need to query the database, return async'ly but without going thru
// the DB thread.
scoped_refptr<AppCacheGroup> no_group;
scoped_refptr<AppCache> no_cache;
ScheduleSimpleTask(base::BindOnce(
&AppCacheStorageImpl::DeliverShortCircuitedFindMainResponse,
weak_factory_.GetWeakPtr(), url, AppCacheEntry(), no_group, no_cache,
base::WrapRefCounted(GetOrCreateDelegateReference(delegate))));
return;
}
// We have to query the database, schedule a database task to do so.
auto task = base::MakeRefCounted<FindMainResponseTask>(
this, *url_ptr, preferred_manifest_url, groups_in_use);
task->AddDelegate(GetOrCreateDelegateReference(delegate));
task->Schedule();
}
bool AppCacheStorageImpl::FindResponseForMainRequestInGroup(
AppCacheGroup* group, const GURL& url, Delegate* delegate) {
AppCache* cache = group->newest_complete_cache();
if (group->is_obsolete() || !cache)
return false;
AppCacheEntry* entry = cache->GetEntry(url);
if (!entry || entry->IsForeign())
return false;
ScheduleSimpleTask(base::BindOnce(
&AppCacheStorageImpl::DeliverShortCircuitedFindMainResponse,
weak_factory_.GetWeakPtr(), url, *entry, base::WrapRefCounted(group),
base::WrapRefCounted(cache),
base::WrapRefCounted(GetOrCreateDelegateReference(delegate))));
return true;
}
void AppCacheStorageImpl::DeliverShortCircuitedFindMainResponse(
const GURL& url,
const AppCacheEntry& found_entry,
scoped_refptr<AppCacheGroup> group,
scoped_refptr<AppCache> cache,
scoped_refptr<DelegateReference> delegate_ref) {
if (delegate_ref->delegate) {
std::vector<scoped_refptr<DelegateReference>> delegates(1, delegate_ref);
CallOnMainResponseFound(
&delegates, url, found_entry, GURL(), AppCacheEntry(),
cache.get() ? cache->cache_id() : blink::mojom::kAppCacheNoCacheId,
group.get() ? group->group_id() : blink::mojom::kAppCacheNoCacheId,
group.get() ? group->manifest_url() : GURL());
}
}
void AppCacheStorageImpl::CallOnMainResponseFound(
std::vector<scoped_refptr<DelegateReference>>* delegates,
const GURL& url,
const AppCacheEntry& entry,
const GURL& namespace_entry_url,
const AppCacheEntry& fallback_entry,
int64_t cache_id,
int64_t group_id,
const GURL& manifest_url) {
AppCacheStorage::ForEachDelegate(
*delegates, [&](AppCacheStorage::Delegate* delegate) {
delegate->OnMainResponseFound(url, entry, namespace_entry_url,
fallback_entry, cache_id, group_id,
manifest_url);
});
}
void AppCacheStorageImpl::FindResponseForSubRequest(
AppCache* cache, const GURL& url,
AppCacheEntry* found_entry, AppCacheEntry* found_fallback_entry,
bool* found_network_namespace) {
DCHECK(cache && cache->is_complete());
// When a group is forcibly deleted, all subresource loads for pages
// using caches in the group will result in a synthesized network errors.
// Forcible deletion is not a function that is covered by the HTML5 spec.
if (cache->owning_group()->is_being_deleted()) {
*found_entry = AppCacheEntry();
*found_fallback_entry = AppCacheEntry();
*found_network_namespace = false;
return;
}
GURL fallback_namespace_not_used;
GURL intercept_namespace_not_used;
cache->FindResponseForRequest(
url, found_entry, &intercept_namespace_not_used,
found_fallback_entry, &fallback_namespace_not_used,
found_network_namespace);
}
void AppCacheStorageImpl::MarkEntryAsForeign(const GURL& entry_url,
int64_t cache_id) {
AppCache* cache = working_set_.GetCache(cache_id);
if (cache) {
AppCacheEntry* entry = cache->GetEntry(entry_url);
if (entry)
entry->add_types(AppCacheEntry::FOREIGN);
}
auto task =
base::MakeRefCounted<MarkEntryAsForeignTask>(this, entry_url, cache_id);
task->Schedule();
pending_foreign_markings_.push_back(std::make_pair(entry_url, cache_id));
}
void AppCacheStorageImpl::MakeGroupObsolete(AppCacheGroup* group,
Delegate* delegate,
int response_code) {
DCHECK(group && delegate);
auto task =
base::MakeRefCounted<MakeGroupObsoleteTask>(this, group, response_code);
task->AddDelegate(GetOrCreateDelegateReference(delegate));
task->Schedule();
}
void AppCacheStorageImpl::StoreEvictionTimes(AppCacheGroup* group) {
auto task = base::MakeRefCounted<UpdateEvictionTimesTask>(this, group);
task->Schedule();
}
std::unique_ptr<AppCacheResponseReader>
AppCacheStorageImpl::CreateResponseReader(const GURL& manifest_url,
int64_t response_id) {
return std::make_unique<AppCacheResponseReader>(
response_id, is_disabled_ ? nullptr : disk_cache()->GetWeakPtr());
}
std::unique_ptr<AppCacheResponseWriter>
AppCacheStorageImpl::CreateResponseWriter(const GURL& manifest_url) {
return std::make_unique<AppCacheResponseWriter>(
NewResponseId(), is_disabled_ ? nullptr : disk_cache()->GetWeakPtr());
}
std::unique_ptr<AppCacheResponseMetadataWriter>
AppCacheStorageImpl::CreateResponseMetadataWriter(int64_t response_id) {
return std::make_unique<AppCacheResponseMetadataWriter>(
response_id, is_disabled_ ? nullptr : disk_cache()->GetWeakPtr());
}
void AppCacheStorageImpl::DoomResponses(
const GURL& manifest_url,
const std::vector<int64_t>& response_ids) {
if (response_ids.empty())
return;
// Start deleting them from the disk cache lazily.
StartDeletingResponses(response_ids);
// Also schedule a database task to record these ids in the
// deletable responses table.
// TODO(michaeln): There is a race here. If the browser crashes
// prior to committing these rows to the database and prior to us
// having deleted them from the disk cache, we'll never delete them.
auto task = base::MakeRefCounted<InsertDeletableResponseIdsTask>(this);
task->response_ids_ = response_ids;
task->Schedule();
}
void AppCacheStorageImpl::DeleteResponses(
const GURL& manifest_url,
const std::vector<int64_t>& response_ids) {
if (response_ids.empty())
return;
StartDeletingResponses(response_ids);
}
bool AppCacheStorageImpl::IsInitialized() {
return IsInitTaskComplete();
}
void AppCacheStorageImpl::DelayedStartDeletingUnusedResponses() {
// Only if we haven't already begun.
if (!did_start_deleting_responses_) {
auto task = base::MakeRefCounted<GetDeletableResponseIdsTask>(
this, last_deletable_response_rowid_);
task->Schedule();
}
}
void AppCacheStorageImpl::StartDeletingResponses(
const std::vector<int64_t>& response_ids) {
DCHECK(!response_ids.empty());
did_start_deleting_responses_ = true;
deletable_response_ids_.insert(
deletable_response_ids_.end(),
response_ids.begin(), response_ids.end());
if (!is_response_deletion_scheduled_)
ScheduleDeleteOneResponse();
}
void AppCacheStorageImpl::ScheduleDeleteOneResponse() {
DCHECK(!is_response_deletion_scheduled_);
const base::TimeDelta kBriefDelay = base::TimeDelta::FromMilliseconds(10);
base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&AppCacheStorageImpl::DeleteOneResponse,
weak_factory_.GetWeakPtr()),
kBriefDelay);
is_response_deletion_scheduled_ = true;
}
void AppCacheStorageImpl::DeleteOneResponse() {
DCHECK(is_response_deletion_scheduled_);
DCHECK(!deletable_response_ids_.empty());
if (is_disabled_) {
deletable_response_ids_.clear();
deleted_response_ids_.clear();
is_response_deletion_scheduled_ = false;
return;
}
// TODO(michaeln): add group_id to DoomEntry args
int64_t id = deletable_response_ids_.front();
int rv = disk_cache()->DoomEntry(
id, base::BindOnce(&AppCacheStorageImpl::OnDeletedOneResponse,
base::Unretained(this)));
if (rv != net::ERR_IO_PENDING)
OnDeletedOneResponse(rv);
}
void AppCacheStorageImpl::OnDeletedOneResponse(int rv) {
is_response_deletion_scheduled_ = false;
if (is_disabled_)
return;
int64_t id = deletable_response_ids_.front();
deletable_response_ids_.pop_front();
if (rv != net::ERR_ABORTED)
deleted_response_ids_.push_back(id);
const size_t kBatchSize = 50U;
if (deleted_response_ids_.size() >= kBatchSize ||
deletable_response_ids_.empty()) {
auto task = base::MakeRefCounted<DeleteDeletableResponseIdsTask>(this);
task->response_ids_.swap(deleted_response_ids_);
task->Schedule();
}
if (deletable_response_ids_.empty()) {
auto task = base::MakeRefCounted<GetDeletableResponseIdsTask>(
this, last_deletable_response_rowid_);
task->Schedule();
return;
}
ScheduleDeleteOneResponse();
}
AppCacheStorageImpl::CacheLoadTask*
AppCacheStorageImpl::GetPendingCacheLoadTask(int64_t cache_id) {
auto found = pending_cache_loads_.find(cache_id);
if (found != pending_cache_loads_.end())
return found->second;
return nullptr;
}
AppCacheStorageImpl::GroupLoadTask*
AppCacheStorageImpl::GetPendingGroupLoadTask(const GURL& manifest_url) {
auto found = pending_group_loads_.find(manifest_url);
if (found != pending_group_loads_.end())
return found->second;
return nullptr;
}
std::vector<GURL> AppCacheStorageImpl::GetPendingForeignMarkingsForCache(
int64_t cache_id) {
std::vector<GURL> urls;
for (const auto& pair : pending_foreign_markings_) {
if (pair.second == cache_id)
urls.push_back(pair.first);
}
return urls;
}
void AppCacheStorageImpl::ScheduleSimpleTask(base::OnceClosure task) {
pending_simple_tasks_.push_back(std::move(task));
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&AppCacheStorageImpl::RunOnePendingSimpleTask,
weak_factory_.GetWeakPtr()));
}
void AppCacheStorageImpl::RunOnePendingSimpleTask() {
DCHECK(!pending_simple_tasks_.empty());
base::OnceClosure task = std::move(pending_simple_tasks_.front());
pending_simple_tasks_.pop_front();
std::move(task).Run();
}
AppCacheDiskCache* AppCacheStorageImpl::disk_cache() {
DCHECK(IsInitTaskComplete());
DCHECK(!is_disabled_);
if (!disk_cache_) {
int rv = net::OK;
disk_cache_ = std::make_unique<AppCacheDiskCache>();
if (is_incognito_) {
rv = disk_cache_->InitWithMemBackend(
0, base::BindOnce(&AppCacheStorageImpl::OnDiskCacheInitialized,
base::Unretained(this)));
} else {
expecting_cleanup_complete_on_disable_ = true;
rv = disk_cache_->InitWithDiskBackend(
cache_directory_.Append(kDiskCacheDirectoryName), false,
base::BindOnce(&AppCacheStorageImpl::OnDiskCacheCleanupComplete,
weak_factory_.GetWeakPtr()),
base::BindOnce(&AppCacheStorageImpl::OnDiskCacheInitialized,
base::Unretained(this)));
}
if (rv != net::ERR_IO_PENDING)
OnDiskCacheInitialized(rv);
}
return disk_cache_.get();
}
void AppCacheStorageImpl::OnDiskCacheInitialized(int rv) {
if (rv != net::OK) {
// We're unable to open the disk cache, this is a fatal error that we can't
// really recover from. We handle it by temporarily disabling the appcache
// deleting the directory on disk and reinitializing the appcache system.
Disable();
if (rv != net::ERR_ABORTED)
DeleteAndStartOver();
}
}
void AppCacheStorageImpl::DeleteAndStartOver() {
DCHECK(is_disabled_);
if (!is_incognito_) {
VLOG(1) << "Deleting existing appcache data and starting over.";
// We can have tasks in flight to close file handles on both the db
// and cache threads, we need to allow those tasks to cycle thru
// prior to deleting the files and calling reinit. We will know that the
// cache ones will be finished once we get into OnDiskCacheCleanupComplete,
// so let that known to synchronize with the DB thread.
delete_and_start_over_pending_ = true;
// Won't get a callback about cleanup being done, so call it ourselves.
if (!expecting_cleanup_complete_on_disable_)
OnDiskCacheCleanupComplete();
}
}
void AppCacheStorageImpl::OnDiskCacheCleanupComplete() {
expecting_cleanup_complete_on_disable_ = false;
if (delete_and_start_over_pending_) {
delete_and_start_over_pending_ = false;
db_task_runner_->PostTaskAndReply(
FROM_HERE,
base::BindOnce(base::IgnoreResult(&base::DeleteFile), cache_directory_,
true),
base::BindOnce(&AppCacheStorageImpl::CallScheduleReinitialize,
weak_factory_.GetWeakPtr()));
}
}
void AppCacheStorageImpl::CallScheduleReinitialize() {
service_->ScheduleReinitialize();
// note: 'this' may be deleted at this point.
}
void AppCacheStorageImpl::LazilyCommitLastAccessTimes() {
if (lazy_commit_timer_.IsRunning())
return;
const base::TimeDelta kDelay = base::TimeDelta::FromMinutes(5);
lazy_commit_timer_.Start(
FROM_HERE, kDelay,
base::BindOnce(&AppCacheStorageImpl::OnLazyCommitTimer,
weak_factory_.GetWeakPtr()));
}
void AppCacheStorageImpl::OnLazyCommitTimer() {
lazy_commit_timer_.Stop();
if (is_disabled())
return;
auto task = base::MakeRefCounted<CommitLastAccessTimesTask>(this);
task->Schedule();
}
} // namespace content
| 33.926174 | 80 | 0.712212 | [
"vector"
] |
4f7d054f724dd2dc8a5d8549c69c55c825d28f21 | 11,247 | cc | C++ | tensorflow/core/kernels/mkl_quantize_op.cc | ouakif/tensorflow | 63c45aacf30e819b00e74b85bd1c9f11b0760cd3 | [
"Apache-2.0"
] | 27 | 2020-02-29T04:13:22.000Z | 2022-02-07T21:54:50.000Z | tensorflow/core/kernels/mkl_quantize_op.cc | top-on/tensorflow | 6efce9a74d4ba2ba2182d92ac1e4f144b5d755d2 | [
"Apache-2.0"
] | 5 | 2020-06-01T18:50:38.000Z | 2021-07-16T07:13:52.000Z | tensorflow/core/kernels/mkl_quantize_op.cc | top-on/tensorflow | 6efce9a74d4ba2ba2182d92ac1e4f144b5d755d2 | [
"Apache-2.0"
] | 10 | 2020-12-15T03:55:24.000Z | 2021-12-17T23:14:11.000Z | /* Copyright 2019 The TensorFlow 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.
==============================================================================*/
#ifdef INTEL_MKL
#define EIGEN_USE_THREADS
#include "mkldnn.h"
#include "mkldnn.hpp"
#include "mkldnn_types.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/type_traits.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/mkl_graph_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/mkl_util.h"
using mkldnn::primitive_attr;
using mkldnn::prop_kind;
using mkldnn::reorder;
using mkldnn::stream;
namespace {
enum {
QUANTIZE_MODE_MIN_COMBINED,
QUANTIZE_MODE_MIN_FIRST,
QUANTIZE_MODE_SCALED,
};
enum {
// Round half away from zero: if the fraction of y is exactly 0.5, then
// round(y) = y + 0.5 if y > 0
// round(y) = y - 0.5 if y < 0
// E.g., -5.5 gets rounded to -6, -5.4 goes to -5,
// 5.4 goes to 5, and 5.5 goes to 6.
ROUND_HALF_AWAY_FROM_ZERO,
// Round half to even: if the fraction of y is exactly 0.5, then round(y) is
// the nearest even integer to y.
// E.g., 23.5 gets rounded to 24, 24.5 gets rounded to 24, while -23.5 becomes
// -24, and -24.5 gets rounded to 24.
ROUND_HALF_TO_EVEN,
};
} // namespace
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
// Quantizes a tensor from float to T, with user-specified min_range and
// max_range.
template <typename Device, typename T>
class MklQuantizeV2Op : public OpKernel {
public:
explicit MklQuantizeV2Op(OpKernelConstruction* ctx) : OpKernel(ctx) {
string mode_string;
OP_REQUIRES_OK(ctx, ctx->GetAttr("mode", &mode_string));
OP_REQUIRES(ctx,
(mode_string == "MIN_COMBINED" || mode_string == "MIN_FIRST" ||
mode_string == "SCALED"),
errors::InvalidArgument("Mode string must be 'MIN_COMBINED',"
" 'MIN_FIRST', or 'SCALED', is '" +
mode_string + "'"));
if (mode_string == "MIN_COMBINED") {
mode_ = QUANTIZE_MODE_MIN_COMBINED;
} else if (mode_string == "MIN_FIRST") {
mode_ = QUANTIZE_MODE_MIN_FIRST;
} else if (mode_string == "SCALED") {
mode_ = QUANTIZE_MODE_SCALED;
}
string round_mode_string;
OP_REQUIRES_OK(ctx, ctx->GetAttr("round_mode", &round_mode_string));
OP_REQUIRES(ctx,
(round_mode_string == "HALF_AWAY_FROM_ZERO" ||
round_mode_string == "HALF_TO_EVEN"),
errors::InvalidArgument("Round mode string must be "
"'HALF_AWAY_FROM_ZERO' or "
"'HALF_TO_EVEN', is '" +
round_mode_string + "'"));
if (round_mode_string == "HALF_AWAY_FROM_ZERO") {
round_mode_ = ROUND_HALF_AWAY_FROM_ZERO;
} else if (round_mode_string == "HALF_TO_EVEN") {
OP_REQUIRES(ctx, mode_string == "SCALED",
errors::InvalidArgument("Round mode 'HALF_TO_EVEN' "
"only supported for mode 'SCALED', "
"but mode is '" +
mode_string + "'."));
round_mode_ = ROUND_HALF_TO_EVEN;
}
OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_));
OP_REQUIRES_OK(
ctx, ctx->GetAttr("ensure_minimum_range", &ensure_minimum_range_));
}
~MklQuantizeV2Op() {}
void Compute(OpKernelContext* ctx) override {
const float input_min_range = ctx->input(1).flat<float>()(0);
const float input_max_range = ctx->input(2).flat<float>()(0);
float min_range = std::min(0.0f, input_min_range);
float max_range;
OP_REQUIRES(ctx, (input_max_range > input_min_range),
errors::InvalidArgument(
"input_max_range must be larger than input_min_range."));
// When the minimum and maximum ranges are too close together, nudge them
// apart by a small value so that they are slightly different. This helps
// us avoid creating ill-formed buffers where all quantized values map to
// the same float number. These kinds of buffers cause problems for
// downstream ops when they need to do calculations on them.
// We pick the value by making sure that zero is not more than 100x the
// overall range from the maximum, so that the value can be easily
// represented when we promote the quantized value to a higher
// intermediate bit depth, since that's a common requirement.
const float epsilon = std::max(1.0f, std::max(fabsf(input_min_range),
fabsf(input_max_range))) *
ensure_minimum_range_;
max_range = std::max(input_max_range, min_range + epsilon);
// Clamping the max_range to zero since max_range can also be negative.
max_range = std::max(0.0f, max_range);
auto cpu_engine = engine(engine::cpu, 0);
const unsigned int src_idx = 0;
const Tensor& src_tensor = MklGetInput(ctx, src_idx);
MklDnnShape src_mkl_shape;
GetMklShape(ctx, src_idx, &src_mkl_shape);
auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape()
: src_tensor.shape();
auto src_dims = src_mkl_shape.IsMklTensor()
? src_mkl_shape.GetSizesAsMklDnnDims()
: TFShapeToMklDnnDims(src_tensor.shape());
auto output_dims = src_dims;
// Set the dst layout to be the best mkl layout based on dims and type.
memory::format dst_layout_type;
switch (src_tf_shape.dims()) {
case 1:
dst_layout_type = memory::format::x;
break;
case 2:
dst_layout_type = memory::format::nc;
break;
case 3:
dst_layout_type = memory::format::tnc;
break;
case 4:
dst_layout_type = memory::format::nhwc;
break;
case 5:
dst_layout_type = memory::format::ndhwc;
break;
default:
OP_REQUIRES_OK(ctx,
errors::Aborted("Input dims must be <= 5 and >= 1"));
return;
}
// Create reorder memory for src, dst: both are defined in mkl_util.h,
// they are wrapper
MklDnnData<float> src(&cpu_engine);
MklDnnData<T> dst(&cpu_engine);
auto src_md =
src_mkl_shape.IsMklTensor()
? src_mkl_shape.GetMklLayout()
: memory::desc(src_dims, MklDnnType<float>(), dst_layout_type);
src.SetUsrMem(src_md, &src_tensor);
memory::desc dst_md =
memory::desc(src_dims, MklDnnType<T>(), dst_layout_type);
auto dst_pd = src.GetUsrMemPrimDesc();
// Standard shape assignments for layout pass
MklDnnShape output_mkl_shape;
TensorShape output_tf_shape;
if (src_mkl_shape.IsMklTensor()) {
output_mkl_shape.SetMklTensor(true);
output_mkl_shape.SetMklLayout(&dst_md);
output_mkl_shape.SetElemType(MklDnnType<T>());
output_mkl_shape.SetTfLayout(src_mkl_shape.GetDimension(),
src_mkl_shape.GetSizesAsMklDnnDims(),
src_mkl_shape.GetTfDataFormat());
output_tf_shape.AddDim(dst_pd.get_size() / sizeof(T));
} else {
output_mkl_shape.SetMklTensor(false);
output_tf_shape = MklDnnDimsToTFShape(output_dims);
}
Tensor* output_tensor = nullptr;
AllocateOutputSetMklShape(ctx, 0, &output_tensor, output_tf_shape,
output_mkl_shape);
TensorShape min_tf_shape = {};
MklDnnShape min_mkl_shape;
min_mkl_shape.SetMklTensor(false);
Tensor* output_min_tensor = nullptr;
AllocateOutputSetMklShape(ctx, 1, &output_min_tensor, min_tf_shape,
min_mkl_shape);
TensorShape max_tf_shape = {};
MklDnnShape max_mkl_shape;
max_mkl_shape.SetMklTensor(false);
Tensor* output_max_tensor = nullptr;
AllocateOutputSetMklShape(ctx, 2, &output_max_tensor, max_tf_shape,
max_mkl_shape);
dst.SetUsrMem(dst_md, output_tensor);
// Estimating scales for quantization.
const int num_bits = sizeof(T) * 8;
const float max_abs = std::max(std::abs(min_range), std::abs(max_range));
const bool is_signed = std::is_signed<T>::value;
float target_range;
if (is_signed) {
max_range = max_abs;
min_range = -max_abs;
// If it is signed, we try to keep 0.0 being 0 and drop one bucket. For
// example, if it is 8 bits, we have the range [-127, 127]. So for input
// range of [-x, x], the scale should be 254/(2*x).
target_range = static_cast<float>((uint64_t{1} << (num_bits - 1)) - 1);
} else {
max_range = max_abs;
min_range = 0.0;
// If it is unsigned and num_bits == 8, the range with 8 bits is [0,
// 255]. If the input range is [0, x], then the scale is 255/x instead
// of 254 as in the case above.
target_range = static_cast<float>((uint64_t{1} << num_bits) - 1);
}
output_min_tensor->flat<float>()(0) = min_range;
output_max_tensor->flat<float>()(0) = max_range;
const float scale_factor = target_range / max_abs;
// Primitive creation and stream submit
std::vector<float> scales{scale_factor};
mkldnn::primitive_attr attr;
attr.set_output_scales(0, scales);
auto reorder_desc = reorder::primitive_desc(src.GetUsrMemPrimDesc(),
dst.GetUsrMemPrimDesc(), attr);
reorder my_reorder = reorder(reorder_desc, primitive::at(*src.GetUsrMem()),
*dst.GetUsrMem());
std::vector<primitive> net{my_reorder};
stream(stream::kind::eager).submit(net).wait();
}
private:
float ensure_minimum_range_;
int mode_;
int round_mode_;
int axis_;
bool narrow_range_;
};
REGISTER_KERNEL_BUILDER(Name("_MklQuantizeV2")
.Device(DEVICE_CPU)
.TypeConstraint<quint8>("T")
.Label(mkl_op_registry::kMklQuantizedOpLabel),
MklQuantizeV2Op<CPUDevice, quint8>);
REGISTER_KERNEL_BUILDER(Name("_MklQuantizeV2")
.Device(DEVICE_CPU)
.TypeConstraint<qint8>("T")
.Label(mkl_op_registry::kMklQuantizedOpLabel),
MklQuantizeV2Op<CPUDevice, qint8>);
} // namespace tensorflow
#endif // INTEL_MKL
| 41.501845 | 80 | 0.628434 | [
"shape",
"vector"
] |
4f7d1ceb498e42c29acadb53f6a46699051d9187 | 1,594 | hpp | C++ | src/Visuals/Shading/visuals-shadow-renderer.hpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | src/Visuals/Shading/visuals-shadow-renderer.hpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | src/Visuals/Shading/visuals-shadow-renderer.hpp | LazyFalcon/TechDemo-v4 | 7b865e20beb7f04fde6e7df66be30f555e0aef5a | [
"MIT"
] | null | null | null | #pragma once
#include "LightSource.hpp"
class Context;
class ShadowPool;
class ShadowRenderer
{
private:
Context& context;
std::unique_ptr<ShadowPool> m_shadowPool;
using Vec = std::vector<LightSource*>;
Vec m_lights;
Vec m_recentlyRemoved;
template<typename T>
auto diffContainers(std::vector<T*>& newData, std::vector<T*>& current) const {
std::vector<T*> added, removed;
std::set_difference(newData.begin(), newData.end(), current.begin(), current.end(),
std::inserter(added, added.begin()));
std::set_difference(current.begin(), current.end(), newData.begin(), newData.end(),
std::inserter(removed, removed.begin()));
return std::make_tuple(added, removed);
}
void freeResources(const Vec& toCleanup);
void sortByImportance(Vec& added) {}
Vec allocateResources(const Vec& toAdd);
Vec whichLightNeedsRefresh(const Vec& lights) const {
Vec result;
for(auto it : lights) {
it->shadow.needsUpdate = false;
result.push_back(it);
}
return result;
}
void renderShadows();
// auto prepareRenderCommandForLight(LightSource* light) {
// RenderCommand renderCommand; // here goes dummy objects, vehicles and
// for(auto it : light->shadow.objectsCastingShadows) { it->addItselfToRenderCommand(renderCommand); }
// return renderCommand;
// }
public:
ShadowRenderer(Context& context);
~ShadowRenderer();
void processVisibleShadows(Vec& lights);
};
| 28.981818 | 110 | 0.63739 | [
"vector"
] |
4f7f28887b5b969094687ac57d6dcaba4f2af4c0 | 16,231 | cc | C++ | tensorflow/contrib/boosted_trees/lib/utils/dropout_utils_test.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/boosted_trees/lib/utils/dropout_utils_test.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/boosted_trees/lib/utils/dropout_utils_test.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 The TensorFlow 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 "tensorflow/contrib/boosted_trees/lib/utils/dropout_utils.h"
#include <sys/types.h>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <unordered_set>
#include <utility>
#include "tensorflow/contrib/boosted_trees/proto/tree_config.pb.h" // NOLINT
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/env.h"
using std::unordered_set;
using tensorflow::boosted_trees::learner::LearningRateDropoutDrivenConfig;
using tensorflow::boosted_trees::trees::DecisionTreeEnsembleConfig;
namespace tensorflow {
namespace boosted_trees {
namespace utils {
namespace {
const uint32 kSeed = 123;
const int32 kNumTrees = 1000;
class DropoutUtilsTest : public ::testing::Test {
public:
void SetUp() override {
// Fill an weights.
for (int i = 0; i < kNumTrees; ++i) {
weights_.push_back(1.1 + 0.4 * i);
}
}
protected:
std::vector<float> weights_;
};
TEST_F(DropoutUtilsTest, DropoutProbabilityTest) {
std::vector<int32> dropped_trees;
std::vector<float> original_weights;
std::unordered_set<int32> trees_not_to_drop;
// Do not drop any trees
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(0.0);
config.set_learning_rate(1.0);
TF_EXPECT_OK(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights));
// Nothing changed
EXPECT_TRUE(dropped_trees.empty());
EXPECT_TRUE(original_weights.empty());
}
// Drop out all trees
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(1.0);
config.set_learning_rate(1.0);
TF_EXPECT_OK(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights));
// No trees left
EXPECT_EQ(kNumTrees, dropped_trees.size());
EXPECT_EQ(kNumTrees, original_weights.size());
EXPECT_EQ(original_weights, weights_);
}
// 50% probability of dropping a tree
{
const int32 kNumRuns = 1000;
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(0.5);
config.set_learning_rate(1.0);
int32 total_num_trees = 0;
for (int i = 0; i < kNumRuns; ++i) {
// draw random seeds
uint random_generator_seed =
static_cast<uint>(Env::Default()->NowMicros());
uint32 seed = rand_r(&random_generator_seed) % 100 + i;
TF_EXPECT_OK(DropoutUtils::DropOutTrees(seed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights));
// We would expect 400-600 trees left
EXPECT_NEAR(500, kNumTrees - dropped_trees.size(), 100);
total_num_trees += kNumTrees - dropped_trees.size();
// Trees dropped are unique
unordered_set<int32> ids;
for (const auto& tree : dropped_trees) {
ids.insert(tree);
}
EXPECT_EQ(ids.size(), dropped_trees.size());
}
EXPECT_NEAR(500, total_num_trees / kNumRuns, 5);
}
}
TEST_F(DropoutUtilsTest, DropoutIgnoresNotToDropTest) {
std::vector<int32> dropped_trees;
std::vector<float> original_weights;
// Empty do not drop set.
{
std::unordered_set<int32> trees_not_to_drop;
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(1.0);
config.set_learning_rate(1.0);
TF_EXPECT_OK(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights));
// No trees left
EXPECT_EQ(kNumTrees, dropped_trees.size());
EXPECT_EQ(kNumTrees, original_weights.size());
EXPECT_EQ(original_weights, weights_);
}
// Do not drop any trees
{
std::unordered_set<int32> trees_not_to_drop;
for (int i = 0; i < kNumTrees; ++i) {
trees_not_to_drop.insert(i);
}
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(1.0);
config.set_learning_rate(1.0);
TF_EXPECT_OK(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights));
// No trees were dropped - they all were in do not drop set.
EXPECT_EQ(0, dropped_trees.size());
EXPECT_EQ(0, original_weights.size());
}
// Do not drop some trees
{
std::unordered_set<int32> trees_not_to_drop;
trees_not_to_drop.insert(0);
trees_not_to_drop.insert(34);
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(1.0);
config.set_learning_rate(1.0);
TF_EXPECT_OK(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights));
// No trees were dropped - they all were in do not drop set.
EXPECT_EQ(kNumTrees - 2, dropped_trees.size());
EXPECT_EQ(kNumTrees - 2, original_weights.size());
EXPECT_TRUE(std::find(dropped_trees.begin(), dropped_trees.end(), 0) ==
dropped_trees.end());
EXPECT_TRUE(std::find(dropped_trees.begin(), dropped_trees.end(), 34) ==
dropped_trees.end());
}
}
TEST_F(DropoutUtilsTest, DropoutSeedTest) {
std::unordered_set<int32> trees_not_to_drop;
// Different seeds remove different trees
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(0.5);
config.set_learning_rate(1.0);
std::vector<int32> dropped_trees_1;
std::vector<float> original_weights_1;
std::vector<int32> dropped_trees_2;
std::vector<float> original_weights_2;
TF_EXPECT_OK(DropoutUtils::DropOutTrees(
kSeed + 1, config, trees_not_to_drop, weights_, &dropped_trees_1,
&original_weights_1));
TF_EXPECT_OK(DropoutUtils::DropOutTrees(
kSeed + 2, config, trees_not_to_drop, weights_, &dropped_trees_2,
&original_weights_2));
EXPECT_FALSE(dropped_trees_1 == dropped_trees_2);
EXPECT_FALSE(original_weights_1 == original_weights_2);
}
// The same seed produces the same result
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(0.5);
config.set_learning_rate(1.0);
std::vector<int32> dropped_trees_1;
std::vector<float> original_weights_1;
std::vector<int32> dropped_trees_2;
std::vector<float> original_weights_2;
TF_EXPECT_OK(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees_1,
&original_weights_1));
TF_EXPECT_OK(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees_2,
&original_weights_2));
EXPECT_TRUE(dropped_trees_1 == dropped_trees_2);
EXPECT_TRUE(original_weights_1 == original_weights_2);
}
}
TEST_F(DropoutUtilsTest, InvalidConfigTest) {
std::vector<int32> dropped_trees;
std::vector<float> original_weights;
std::unordered_set<int32> trees_not_to_drop;
// Negative prob
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(-1.34);
EXPECT_FALSE(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights)
.ok());
}
// Larger than 1 prob of dropping a tree.
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(1.34);
EXPECT_FALSE(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights)
.ok());
}
// Negative probability of skipping dropout.
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(0.5);
config.set_probability_of_skipping_dropout(-10);
EXPECT_FALSE(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights)
.ok());
}
// Larger than 1 probability of skipping dropout.
{
LearningRateDropoutDrivenConfig config;
config.set_dropout_probability(0.5);
config.set_probability_of_skipping_dropout(1.2);
EXPECT_FALSE(DropoutUtils::DropOutTrees(kSeed, config, trees_not_to_drop,
weights_, &dropped_trees,
&original_weights)
.ok());
}
}
namespace {
void ExpectVecsEquiv(const std::vector<float>& vec1,
const std::vector<float>& vec2) {
EXPECT_EQ(vec1.size(), vec2.size());
for (int i = 0; i < vec1.size(); ++i) {
EXPECT_NEAR(vec1[i], vec2[i], 1e-3);
}
}
std::vector<float> GetWeightsByIndex(const std::vector<float>& weights,
const std::vector<int>& indices) {
std::vector<float> res;
res.reserve(indices.size());
for (const int index : indices) {
res.push_back(weights[index]);
}
return res;
}
void MergeLastElements(const int32 last_n, std::vector<float>* weights) {
float sum = 0.0;
for (int i = 0; i < last_n; ++i) {
sum += weights->back();
weights->pop_back();
}
weights->push_back(sum);
}
} // namespace
TEST_F(DropoutUtilsTest, GetTreesWeightsForAddingTreesTest) {
// Adding trees should give the same res in any order
{
std::vector<float> weights = {1.0, 1.0, 1.0, 1.0, 1.0};
std::vector<int32> dropped_1 = {0, 3};
std::vector<int32> dropped_2 = {0};
std::vector<float> res_1;
std::vector<float> res_2;
// Do one order
{
std::vector<float> current_weights = weights;
std::vector<int32> num_updates =
std::vector<int32>(current_weights.size(), 1);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_1, GetWeightsByIndex(current_weights, dropped_1),
current_weights.size(), 1, ¤t_weights, &num_updates);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_2, GetWeightsByIndex(current_weights, dropped_2),
current_weights.size(), 1, ¤t_weights, &num_updates);
res_1 = current_weights;
}
// Do another order
{
std::vector<float> current_weights = weights;
std::vector<int32> num_updates =
std::vector<int32>(current_weights.size(), 1);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_2, GetWeightsByIndex(current_weights, dropped_2),
current_weights.size(), 1, ¤t_weights, &num_updates);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_1, GetWeightsByIndex(current_weights, dropped_1),
current_weights.size(), 1, ¤t_weights, &num_updates);
res_2 = current_weights;
}
// The vectors are the same, but the last two elements have the same sum.
EXPECT_EQ(res_1.size(), 7);
EXPECT_EQ(res_2.size(), 7);
MergeLastElements(2, &res_1);
MergeLastElements(2, &res_2);
EXPECT_EQ(res_1, res_2);
}
// Now when the weights are not all 1s
{
std::vector<float> weights = {1.1, 2.1, 3.1, 4.1, 5.1};
std::vector<int32> dropped_1 = {0, 3};
std::vector<int32> dropped_2 = {0};
std::vector<float> res_1;
std::vector<float> res_2;
// Do one order
{
std::vector<float> current_weights = weights;
std::vector<int32> num_updates =
std::vector<int32>(current_weights.size(), 1);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_1, GetWeightsByIndex(current_weights, dropped_1),
current_weights.size(), 1, ¤t_weights, &num_updates);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_2, GetWeightsByIndex(current_weights, dropped_2),
current_weights.size(), 1, ¤t_weights, &num_updates);
res_1 = current_weights;
}
// Do another order
{
std::vector<float> current_weights = weights;
std::vector<int32> num_updates =
std::vector<int32>(current_weights.size(), 1);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_2, GetWeightsByIndex(current_weights, dropped_2),
current_weights.size(), 1, ¤t_weights, &num_updates);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped_1, GetWeightsByIndex(current_weights, dropped_1),
current_weights.size(), 1, ¤t_weights, &num_updates);
res_2 = current_weights;
}
EXPECT_EQ(res_1.size(), 7);
EXPECT_EQ(res_2.size(), 7);
// The vectors are the same, but the last two elements have the same sum.
MergeLastElements(2, &res_1);
MergeLastElements(2, &res_2);
ExpectVecsEquiv(res_1, res_2);
}
}
TEST_F(DropoutUtilsTest, GetTreesWeightsForAddingTreesIndexTest) {
std::vector<float> weights = {1.0, 1.0, 1.0, 1.0, 1.0};
std::vector<int32> dropped = {0, 3};
std::vector<float> res;
std::vector<float> res_2;
// The tree that is added does not yet have an entry in weights vector.
{
std::vector<float> current_weights = weights;
std::vector<int32> num_updates =
std::vector<int32>(current_weights.size(), 1);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped, GetWeightsByIndex(current_weights, dropped),
current_weights.size(), 1, ¤t_weights, &num_updates);
EXPECT_EQ(current_weights.size(), weights.size() + 1);
EXPECT_EQ(num_updates.size(), weights.size() + 1);
std::vector<int32> expected_num_updates = {2, 1, 1, 2, 1, 1};
std::vector<float> expected_weights = {2.0 / 3, 1, 1, 2.0 / 3, 1, 2.0 / 3};
EXPECT_EQ(expected_weights, current_weights);
EXPECT_EQ(expected_num_updates, num_updates);
}
// The tree that is added has already an entry in weights and updates (batch
// mode).
{
std::vector<float> current_weights = weights;
std::vector<int32> num_updates =
std::vector<int32>(current_weights.size(), 1);
DropoutUtils::GetTreesWeightsForAddingTrees(
dropped, GetWeightsByIndex(current_weights, dropped),
current_weights.size() - 1, 1, ¤t_weights, &num_updates);
EXPECT_EQ(current_weights.size(), weights.size());
EXPECT_EQ(num_updates.size(), weights.size());
std::vector<int32> expected_num_updates = {2, 1, 1, 2, 2};
std::vector<float> expected_weights = {2.0 / 3, 1, 1, 2.0 / 3, 2.0 / 3};
EXPECT_EQ(expected_weights, current_weights);
EXPECT_EQ(expected_num_updates, num_updates);
}
}
} // namespace
} // namespace utils
} // namespace boosted_trees
} // namespace tensorflow
| 36.229911 | 81 | 0.628858 | [
"vector"
] |
4f82a4b105532e2ba0a4132ff2ef092d22016625 | 3,185 | cc | C++ | src/core/analysis/normalized_node_creator_test.cc | wrightak/jumanpp | 49784bac7ee9562f1839aa12c780b019a1cb0e03 | [
"Apache-2.0"
] | 300 | 2016-10-19T02:20:39.000Z | 2022-02-23T19:58:04.000Z | src/core/analysis/normalized_node_creator_test.cc | wrightak/jumanpp | 49784bac7ee9562f1839aa12c780b019a1cb0e03 | [
"Apache-2.0"
] | 130 | 2016-10-17T07:57:14.000Z | 2022-03-20T17:37:13.000Z | src/core/analysis/normalized_node_creator_test.cc | wrightak/jumanpp | 49784bac7ee9562f1839aa12c780b019a1cb0e03 | [
"Apache-2.0"
] | 36 | 2016-10-19T11:47:05.000Z | 2022-01-25T09:36:12.000Z | //
// Created by Arseny Tolmachev on 2017/11/23.
//
#include "charlattice.h"
#include "testing/test_analyzer.h"
#include "util/logging.hpp"
using namespace jumanpp;
using namespace jumanpp::core;
using namespace jumanpp::testing;
namespace {
class NNodeTestEnv {
TestEnv tenv;
StringField fld1, fld2;
dic::DictionaryEntries dic{tenv.dic.entries()};
public:
NNodeTestEnv(StringPiece csvData) {
tenv.spec([](spec::dsl::ModelSpecBuilder& specBldr) {
auto& a = specBldr.field(1, "f1").strings().trieIndex();
auto& f2 = specBldr.field(2, "f2").strings();
auto& ph = specBldr.feature("ph").placeholder();
specBldr.unk("normalize", 1).normalize().outputTo({a}).writeFeatureTo(ph);
specBldr.unigram({a, f2, ph});
});
CHECK(tenv.originalSpec.unkCreators.size() == 1);
tenv.importDic(csvData);
REQUIRE_OK(tenv.analyzer->output().stringField("f1", &fld1));
REQUIRE_OK(tenv.analyzer->output().stringField("f2", &fld2));
}
size_t numNodeSeeds() const {
return tenv.analyzer->latticeBuilder().seeds().size();
}
void printAll() {
auto& output = tenv.analyzer->output();
auto walker = output.nodeWalker();
auto seeds = tenv.analyzer->latticeBuilder().seeds();
for (auto& seed : seeds) {
CHECK(output.locate(seed.entryPtr, &walker));
while (walker.next()) {
LOG_TRACE() << "NODE(" << seed.codepointStart << ","
<< seed.codepointEnd << "):" << fld1[walker] << "||"
<< fld2[walker];
}
}
}
void analyze(StringPiece str) {
CAPTURE(str);
CHECK_OK(tenv.analyzer->resetForInput(str));
CHECK_OK(tenv.analyzer->prepareNodeSeeds());
CHECK_OK(tenv.analyzer->buildLattice());
CHECK_OK(tenv.analyzer->bootstrapAnalysis());
}
charlattice::Modifiers contains(StringPiece str, i32 start,
StringPiece strb) {
CAPTURE(str);
CAPTURE(start);
auto& output = tenv.analyzer->output();
auto walker = output.nodeWalker();
auto seeds = tenv.analyzer->latticeBuilder().seeds();
std::vector<chars::InputCodepoint> cp;
REQUIRE(chars::preprocessRawData(str, &cp));
i32 end = start + cp.size();
for (auto& seed : seeds) {
if (seed.codepointStart == start && seed.codepointEnd == end) {
CHECK(output.locate(seed.entryPtr, &walker));
while (walker.next()) {
auto s1 = fld1[walker];
auto s2 = fld2[walker];
if (s1 == str && s2 == strb && seed.entryPtr.isSpecial()) {
auto val = tenv.analyzer->extraNodesContext()->placeholderData(
seed.entryPtr, 0);
return static_cast<charlattice::Modifiers>(val);
}
}
}
}
return charlattice::Modifiers::EMPTY;
}
~NNodeTestEnv() {
if (!Catch::getResultCapture().lastAssertionPassed()) {
printAll();
}
}
};
} // namespace
using m = charlattice::Modifiers;
using charlattice::ExistFlag;
TEST_CASE("can extract modification from normalized") {
NNodeTestEnv env{"UNK,b\nまあ,a\n"};
env.analyze("まあ〜");
auto v = env.contains("まあ〜", 0, "a");
CHECK(ExistFlag(v, m::DELETE_PROLONG));
}
| 29.766355 | 80 | 0.618838 | [
"vector"
] |
4f840a0b32257193f95a74cf0d45ab7a182c7ddc | 11,895 | cpp | C++ | dev/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorUndo.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 2 | 2020-06-27T12:13:44.000Z | 2020-06-27T12:13:46.000Z | dev/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorUndo.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorUndo.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <AudioControlsEditorUndo.h>
#include <ATLControlsModel.h>
#include <AudioControlsEditorPlugin.h>
#include <QStandardItemModel>
#include <QList>
namespace AudioControls
{
//-------------------------------------------------------------------------------------------//
QStandardItem* GetParent(QATLTreeModel* pTree, const TPath& path)
{
QStandardItem* pParent = pTree->invisibleRootItem();
if (pParent)
{
const size_t size = path.size();
for (size_t i = 0; i < size - 1; ++i)
{
pParent = pParent->child(path[(size - 1) - i]);
}
}
return pParent;
}
//-------------------------------------------------------------------------------------------//
QStandardItem* GetItem(QATLTreeModel* pTree, const TPath& path)
{
QStandardItem* pParent = GetParent(pTree, path);
if (pParent && path.size() > 0)
{
return pParent->child(path[0]);
}
return nullptr;
}
//-------------------------------------------------------------------------------------------//
void UpdatePath(QStandardItem* pItem, TPath& path)
{
if (pItem)
{
path.clear();
path.push_back(pItem->row());
QStandardItem* pParent = pItem->parent();
while (pParent)
{
path.push_back(pParent->row());
pParent = pParent->parent();
}
}
}
//-------------------------------------------------------------------------------------------//
void IUndoControlOperation::AddStoredControl()
{
const CUndoSuspend suspendUndo;
CATLControlsModel* pModel = CAudioControlsEditorPlugin::GetATLModel();
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pModel && pTree)
{
if (m_pStoredControl)
{
pModel->InsertControl(m_pStoredControl);
m_id = m_pStoredControl->GetId();
QStandardItem* pParent = GetParent(pTree, m_path);
if (pParent && m_path.size() > 0)
{
pTree->AddControl(m_pStoredControl.get(), pParent, m_path[0]);
}
}
m_pStoredControl = nullptr;
}
}
//-------------------------------------------------------------------------------------------//
void IUndoControlOperation::RemoveStoredControl()
{
const CUndoSuspend suspendUndo;
CATLControlsModel* pModel = CAudioControlsEditorPlugin::GetATLModel();
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pModel && pTree)
{
m_pStoredControl = pModel->TakeControl(m_id);
QStandardItem* pItem = pTree->GetItemFromControlID(m_id);
if (pItem)
{
UpdatePath(pItem, m_path);
pTree->RemoveItem(pTree->indexFromItem(pItem));
}
}
}
//-------------------------------------------------------------------------------------------//
CUndoControlAdd::CUndoControlAdd(CID id)
{
m_id = id;
}
//-------------------------------------------------------------------------------------------//
void CUndoControlAdd::Undo(bool bUndo)
{
RemoveStoredControl();
}
//-------------------------------------------------------------------------------------------//
void CUndoControlAdd::Redo()
{
AddStoredControl();
}
//-------------------------------------------------------------------------------------------//
CUndoControlRemove::CUndoControlRemove(AZStd::shared_ptr<CATLControl>& pControl)
{
CUndoSuspend suspendUndo;
m_pStoredControl = pControl;
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pTree)
{
QStandardItem* pItem = pTree->GetItemFromControlID(m_pStoredControl->GetId());
if (pItem)
{
UpdatePath(pItem, m_path);
}
}
}
//-------------------------------------------------------------------------------------------//
void CUndoControlRemove::Undo(bool bUndo)
{
AddStoredControl();
}
//-------------------------------------------------------------------------------------------//
void CUndoControlRemove::Redo()
{
RemoveStoredControl();
}
//-------------------------------------------------------------------------------------------//
IUndoFolderOperation::IUndoFolderOperation(QStandardItem* pItem)
{
if (pItem)
{
m_sName = pItem->text();
UpdatePath(pItem, m_path);
}
}
//-------------------------------------------------------------------------------------------//
void IUndoFolderOperation::AddFolderItem()
{
CUndoSuspend suspendUndo;
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pTree)
{
QStandardItem* pParent = GetParent(pTree, m_path);
if (pParent && m_path.size() > 0)
{
pTree->CreateFolder(pParent, m_sName.toUtf8().data(), m_path[0]);
}
}
}
//-------------------------------------------------------------------------------------------//
void IUndoFolderOperation::RemoveItem()
{
CUndoSuspend suspendUndo;
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pTree)
{
QStandardItem* pItem = GetItem(pTree, m_path);
if (pItem)
{
pTree->RemoveItem(pTree->indexFromItem(pItem));
}
}
}
//-------------------------------------------------------------------------------------------//
CUndoFolderRemove::CUndoFolderRemove(QStandardItem* pItem)
: IUndoFolderOperation(pItem)
{
}
//-------------------------------------------------------------------------------------------//
void CUndoFolderRemove::Undo(bool bUndo)
{
AddFolderItem();
}
//-------------------------------------------------------------------------------------------//
void CUndoFolderRemove::Redo()
{
RemoveItem();
}
//-------------------------------------------------------------------------------------------//
CUndoFolderAdd::CUndoFolderAdd(QStandardItem* pItem)
: IUndoFolderOperation(pItem)
{
}
//-------------------------------------------------------------------------------------------//
void CUndoFolderAdd::Undo(bool bUndo)
{
RemoveItem();
}
//-------------------------------------------------------------------------------------------//
void CUndoFolderAdd::Redo()
{
AddFolderItem();
}
//-------------------------------------------------------------------------------------------//
CUndoControlModified::CUndoControlModified(CID id)
: m_id(id)
{
CATLControlsModel* pModel = CAudioControlsEditorPlugin::GetATLModel();
if (pModel)
{
CATLControl* pControl = pModel->GetControlByID(m_id);
if (pControl)
{
m_name = pControl->GetName();
m_scope = pControl->GetScope();
m_bAutoLoad = pControl->IsAutoLoad();
m_groupPerPlatform = pControl->m_groupPerPlatform;
m_connectedControls = pControl->m_connectedControls;
}
}
}
//-------------------------------------------------------------------------------------------//
void CUndoControlModified::Undo(bool bUndo)
{
SwapData();
}
//-------------------------------------------------------------------------------------------//
void CUndoControlModified::Redo()
{
SwapData();
}
//-------------------------------------------------------------------------------------------//
void CUndoControlModified::SwapData()
{
const CUndoSuspend suspendUndo;
CATLControlsModel* pModel = CAudioControlsEditorPlugin::GetATLModel();
if (pModel)
{
CATLControl* pControl = pModel->GetControlByID(m_id);
if (pControl)
{
AZStd::string name = pControl->GetName();
AZStd::string scope = pControl->GetScope();
bool bAutoLoad = pControl->IsAutoLoad();
AZStd::map<AZStd::string, int> groupPerPlatform = pControl->m_groupPerPlatform;
AZStd::vector<TConnectionPtr> connectedControls = pControl->m_connectedControls;
pControl->SetName(m_name);
pControl->SetScope(m_scope);
pControl->SetAutoLoad(m_bAutoLoad);
pControl->m_groupPerPlatform = m_groupPerPlatform;
pControl->m_connectedControls = m_connectedControls;
pModel->OnControlModified(pControl);
m_name = name;
m_scope = scope;
m_bAutoLoad = bAutoLoad;
m_groupPerPlatform = groupPerPlatform;
m_connectedControls = connectedControls;
}
}
}
//-------------------------------------------------------------------------------------------//
void CUndoItemMove::Undo(bool bUndo)
{
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pTree)
{
if (!bModifiedInitialised)
{
Copy(pTree->invisibleRootItem(), m_modified.invisibleRootItem());
bModifiedInitialised = true;
}
pTree->clear();
Copy(m_original.invisibleRootItem(), pTree->invisibleRootItem());
}
}
//-------------------------------------------------------------------------------------------//
void CUndoItemMove::Redo()
{
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pTree)
{
pTree->clear();
Copy(m_modified.invisibleRootItem(), pTree->invisibleRootItem());
}
}
//-------------------------------------------------------------------------------------------//
void CUndoItemMove::Copy(QStandardItem* pSource, QStandardItem* pDest)
{
if (pSource && pDest)
{
for (int i = 0; i < pSource->rowCount(); ++i)
{
QStandardItem* pSourceItem = pSource->child(i);
QStandardItem* pDestItem = pSourceItem->clone();
Copy(pSourceItem, pDestItem);
pDest->appendRow(pDestItem);
}
}
}
//-------------------------------------------------------------------------------------------//
CUndoItemMove::CUndoItemMove()
: bModifiedInitialised(false)
{
QATLTreeModel* pTree = CAudioControlsEditorPlugin::GetControlsTree();
if (pTree)
{
Copy(pTree->invisibleRootItem(), m_original.invisibleRootItem());
}
}
} // namespace AudioControls
| 34.378613 | 99 | 0.434216 | [
"vector"
] |
4f858f9dad295acabe7aac483e1ce3426d4d8f27 | 35,925 | cpp | C++ | source/d3d9/d3d9_device.cpp | Dakraid/reshade | 272dc1b0dafd3e37368c03663324f08d8c2b1920 | [
"BSD-3-Clause"
] | null | null | null | source/d3d9/d3d9_device.cpp | Dakraid/reshade | 272dc1b0dafd3e37368c03663324f08d8c2b1920 | [
"BSD-3-Clause"
] | null | null | null | source/d3d9/d3d9_device.cpp | Dakraid/reshade | 272dc1b0dafd3e37368c03663324f08d8c2b1920 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "dll_log.hpp"
#include "d3d9_device.hpp"
#include "d3d9_swapchain.hpp"
#include "runtime_d3d9.hpp"
extern void dump_and_modify_present_parameters(D3DPRESENT_PARAMETERS &pp, IDirect3D9 *d3d, UINT adapter_index);
extern void dump_and_modify_present_parameters(D3DPRESENT_PARAMETERS &pp, D3DDISPLAYMODEEX &fullscreen_desc, IDirect3D9Ex *d3d, UINT adapter_index);
Direct3DDevice9::Direct3DDevice9(IDirect3DDevice9 *original, bool use_software_rendering) :
_orig(original),
_extended_interface(0),
_use_software_rendering(use_software_rendering),
_buffer_detection(original) {
assert(_orig != nullptr);
}
Direct3DDevice9::Direct3DDevice9(IDirect3DDevice9Ex *original, bool use_software_rendering) :
_orig(original),
_extended_interface(1),
_use_software_rendering(use_software_rendering),
_buffer_detection(original) {
assert(_orig != nullptr);
}
bool Direct3DDevice9::check_and_upgrade_interface(REFIID riid)
{
if (riid == __uuidof(this) ||
riid == __uuidof(IUnknown) ||
riid == __uuidof(IDirect3DDevice9))
return true;
if (riid != __uuidof(IDirect3DDevice9Ex))
return false;
if (!_extended_interface)
{
IDirect3DDevice9Ex *new_interface = nullptr;
if (FAILED(_orig->QueryInterface(IID_PPV_ARGS(&new_interface))))
return false;
#if RESHADE_VERBOSE_LOG
LOG(DEBUG) << "Upgraded IDirect3DDevice9 object " << this << " to IDirect3DDevice9Ex.";
#endif
_orig->Release();
_orig = new_interface;
_extended_interface = true;
}
return true;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::QueryInterface(REFIID riid, void **ppvObj)
{
if (ppvObj == nullptr)
return E_POINTER;
if (check_and_upgrade_interface(riid))
{
AddRef();
*ppvObj = this;
return S_OK;
}
return _orig->QueryInterface(riid, ppvObj);
}
ULONG STDMETHODCALLTYPE Direct3DDevice9::AddRef()
{
_orig->AddRef();
return InterlockedIncrement(&_ref);
}
ULONG STDMETHODCALLTYPE Direct3DDevice9::Release()
{
const ULONG ref = InterlockedDecrement(&_ref);
if (ref != 0)
return _orig->Release(), ref;
// Release remaining references to this device
_buffer_detection.reset(true);
_auto_depthstencil.reset();
_implicit_swapchain->Release();
const ULONG ref_orig = _orig->Release();
if (ref_orig != 0) // Verify internal reference count
LOG(WARN) << "Reference count for IDirect3DDevice9" << (_extended_interface ? "Ex" : "") << " object " << this << " is inconsistent.";
#if RESHADE_VERBOSE_LOG
LOG(DEBUG) << "Destroyed IDirect3DDevice9" << (_extended_interface ? "Ex" : "") << " object " << this << '.';
#endif
delete this;
return 0;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::TestCooperativeLevel()
{
return _orig->TestCooperativeLevel();
}
UINT STDMETHODCALLTYPE Direct3DDevice9::GetAvailableTextureMem()
{
return _orig->GetAvailableTextureMem();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::EvictManagedResources()
{
return _orig->EvictManagedResources();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDirect3D(IDirect3D9 **ppD3D9)
{
return _orig->GetDirect3D(ppD3D9);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDeviceCaps(D3DCAPS9 *pCaps)
{
return _orig->GetDeviceCaps(pCaps);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDisplayMode(UINT iSwapChain, D3DDISPLAYMODE *pMode)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return D3DERR_INVALIDCALL;
}
return _implicit_swapchain->GetDisplayMode(pMode);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters)
{
return _orig->GetCreationParameters(pParameters);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetCursorProperties(UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9 *pCursorBitmap)
{
return _orig->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap);
}
void STDMETHODCALLTYPE Direct3DDevice9::SetCursorPosition(int X, int Y, DWORD Flags)
{
return _orig->SetCursorPosition(X, Y, Flags);
}
BOOL STDMETHODCALLTYPE Direct3DDevice9::ShowCursor(BOOL bShow)
{
return _orig->ShowCursor(bShow);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DSwapChain9 **ppSwapChain)
{
LOG(INFO) << "Redirecting " << "IDirect3DDevice9::CreateAdditionalSwapChain" << '(' << "this = " << this << ", pPresentationParameters = " << pPresentationParameters << ", ppSwapChain = " << ppSwapChain << ')' << " ...";
if (pPresentationParameters == nullptr)
return D3DERR_INVALIDCALL;
com_ptr<IDirect3D9> d3d;
_orig->GetDirect3D(&d3d);
D3DDEVICE_CREATION_PARAMETERS cp = {};
_orig->GetCreationParameters(&cp);
D3DPRESENT_PARAMETERS pp = *pPresentationParameters;
dump_and_modify_present_parameters(pp, d3d.get(), cp.AdapterOrdinal);
d3d.reset();
const HRESULT hr = _orig->CreateAdditionalSwapChain(&pp, ppSwapChain);
// Update output values (see https://docs.microsoft.com/windows/win32/api/d3d9/nf-d3d9-idirect3ddevice9-createadditionalswapchain)
pPresentationParameters->BackBufferWidth = pp.BackBufferWidth;
pPresentationParameters->BackBufferHeight = pp.BackBufferHeight;
pPresentationParameters->BackBufferFormat = pp.BackBufferFormat;
pPresentationParameters->BackBufferCount = pp.BackBufferCount;
if (FAILED(hr))
{
LOG(WARN) << "IDirect3DDevice9::CreateAdditionalSwapChain" << " failed with error code " << hr << '!';
return hr;
}
IDirect3DDevice9 *const device = _orig;
IDirect3DSwapChain9 *const swapchain = *ppSwapChain;
assert(swapchain != nullptr);
// Retrieve present parameters here again, to get correct values for 'BackBufferWidth' and 'BackBufferHeight'
// They may otherwise still be set to zero (which is valid for creation)
swapchain->GetPresentParameters(&pp);
const auto runtime = std::make_shared<reshade::d3d9::runtime_d3d9>(device, swapchain, &_buffer_detection);
if (!runtime->on_init(pp))
LOG(ERROR) << "Failed to initialize Direct3D 9 runtime environment on runtime " << runtime.get() << '.';
AddRef(); // Add reference which is released when the swap chain is destroyed (see 'Direct3DSwapChain9::Release')
const auto swapchain_proxy = new Direct3DSwapChain9(this, swapchain, runtime);
_additional_swapchains.push_back(swapchain_proxy);
*ppSwapChain = swapchain_proxy;
#if RESHADE_VERBOSE_LOG
LOG(INFO) << "Returning IDirect3DSwapChain9 object: " << swapchain_proxy << '.';
#endif
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetSwapChain(UINT iSwapChain, IDirect3DSwapChain9 **ppSwapChain)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return D3DERR_INVALIDCALL;
}
if (ppSwapChain == nullptr)
return D3DERR_INVALIDCALL;
_implicit_swapchain->AddRef();
*ppSwapChain = _implicit_swapchain;
return D3D_OK;
}
UINT STDMETHODCALLTYPE Direct3DDevice9::GetNumberOfSwapChains()
{
return 1;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::Reset(D3DPRESENT_PARAMETERS *pPresentationParameters)
{
LOG(INFO) << "Redirecting " << "IDirect3DDevice9::Reset" << '(' << "this = " << this << ", pPresentationParameters = " << pPresentationParameters << ')' << " ...";
if (pPresentationParameters == nullptr)
return D3DERR_INVALIDCALL;
com_ptr<IDirect3D9> d3d;
_orig->GetDirect3D(&d3d);
D3DDEVICE_CREATION_PARAMETERS cp = {};
_orig->GetCreationParameters(&cp);
D3DPRESENT_PARAMETERS pp = *pPresentationParameters;
dump_and_modify_present_parameters(pp, d3d.get(), cp.AdapterOrdinal);
d3d.reset();
const auto runtime = _implicit_swapchain->_runtime;
runtime->on_reset();
_buffer_detection.reset(true);
_auto_depthstencil.reset();
const HRESULT hr = _orig->Reset(&pp);
// Update output values (see https://docs.microsoft.com/windows/win32/api/d3d9/nf-d3d9-idirect3ddevice9-reset)
pPresentationParameters->BackBufferWidth = pp.BackBufferWidth;
pPresentationParameters->BackBufferHeight = pp.BackBufferHeight;
pPresentationParameters->BackBufferFormat = pp.BackBufferFormat;
pPresentationParameters->BackBufferCount = pp.BackBufferCount;
if (FAILED(hr))
{
LOG(ERROR) << "IDirect3DDevice9::Reset" << " failed with error code " << hr << '!';
return hr;
}
_implicit_swapchain->GetPresentParameters(&pp);
if (!runtime->on_init(pp))
LOG(ERROR) << "Failed to recreate Direct3D 9 runtime environment on runtime " << runtime.get() << '.';
// Reload auto depth-stencil surface
if (pp.EnableAutoDepthStencil)
{
_orig->GetDepthStencilSurface(&_auto_depthstencil);
SetDepthStencilSurface(_auto_depthstencil.get());
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion)
{
// Only call into runtime if the entire surface is presented, to avoid partial updates messing up effects and the GUI
if (Direct3DSwapChain9::is_presenting_entire_surface(pSourceRect, hDestWindowOverride))
_implicit_swapchain->_runtime->on_present();
_buffer_detection.reset(false);
return _orig->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetBackBuffer(UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9 **ppBackBuffer)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return D3DERR_INVALIDCALL;
}
return _implicit_swapchain->GetBackBuffer(iBackBuffer, Type, ppBackBuffer);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRasterStatus(UINT iSwapChain, D3DRASTER_STATUS *pRasterStatus)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return D3DERR_INVALIDCALL;
}
return _implicit_swapchain->GetRasterStatus(pRasterStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetDialogBoxMode(BOOL bEnableDialogs)
{
return _orig->SetDialogBoxMode(bEnableDialogs);
}
void STDMETHODCALLTYPE Direct3DDevice9::SetGammaRamp(UINT iSwapChain, DWORD Flags, const D3DGAMMARAMP *pRamp)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return;
}
return _orig->SetGammaRamp(0, Flags, pRamp);
}
void STDMETHODCALLTYPE Direct3DDevice9::GetGammaRamp(UINT iSwapChain, D3DGAMMARAMP *pRamp)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return;
}
return _orig->GetGammaRamp(0, pRamp);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateTexture(UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9 **ppTexture, HANDLE *pSharedHandle)
{
return _orig->CreateTexture(Width, Height, Levels, Usage, Format, Pool, ppTexture, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVolumeTexture(UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9 **ppVolumeTexture, HANDLE *pSharedHandle)
{
return _orig->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateCubeTexture(UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9 **ppCubeTexture, HANDLE *pSharedHandle)
{
return _orig->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexBuffer(UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9 **ppVertexBuffer, HANDLE *pSharedHandle)
{
// Need to allow buffer for use in software vertex processing, since application uses software and not hardware processing, but device was created with both
if (_use_software_rendering)
Usage |= D3DUSAGE_SOFTWAREPROCESSING;
return _orig->CreateVertexBuffer(Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9 **ppIndexBuffer, HANDLE *pSharedHandle)
{
if (_use_software_rendering)
Usage |= D3DUSAGE_SOFTWAREPROCESSING;
return _orig->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateRenderTarget(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle)
{
return _orig->CreateRenderTarget(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateDepthStencilSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle)
{
return _orig->CreateDepthStencilSurface(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::UpdateSurface(IDirect3DSurface9 *pSourceSurface, const RECT *pSourceRect, IDirect3DSurface9 *pDestinationSurface, const POINT *pDestPoint)
{
return _orig->UpdateSurface(pSourceSurface, pSourceRect, pDestinationSurface, pDestPoint);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::UpdateTexture(IDirect3DBaseTexture9 *pSourceTexture, IDirect3DBaseTexture9 *pDestinationTexture)
{
return _orig->UpdateTexture(pSourceTexture, pDestinationTexture);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderTargetData(IDirect3DSurface9 *pRenderTarget, IDirect3DSurface9 *pDestSurface)
{
return _orig->GetRenderTargetData(pRenderTarget, pDestSurface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetFrontBufferData(UINT iSwapChain, IDirect3DSurface9 *pDestSurface)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return D3DERR_INVALIDCALL;
}
return _implicit_swapchain->GetFrontBufferData(pDestSurface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::StretchRect(IDirect3DSurface9 *pSourceSurface, const RECT *pSourceRect, IDirect3DSurface9 *pDestSurface, const RECT *pDestRect, D3DTEXTUREFILTERTYPE Filter)
{
return _orig->StretchRect(pSourceSurface, pSourceRect, pDestSurface, pDestRect, Filter);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ColorFill(IDirect3DSurface9 *pSurface, const RECT *pRect, D3DCOLOR color)
{
return _orig->ColorFill(pSurface, pRect, color);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateOffscreenPlainSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle)
{
return _orig->CreateOffscreenPlainSurface(Width, Height, Format, Pool, ppSurface, pSharedHandle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 *pRenderTarget)
{
return _orig->SetRenderTarget(RenderTargetIndex, pRenderTarget);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderTarget(DWORD RenderTargetIndex, IDirect3DSurface9 **ppRenderTarget)
{
return _orig->GetRenderTarget(RenderTargetIndex, ppRenderTarget);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetDepthStencilSurface(IDirect3DSurface9 *pNewZStencil)
{
#if RESHADE_DEPTH
_buffer_detection.on_set_depthstencil(pNewZStencil);
#endif
return _orig->SetDepthStencilSurface(pNewZStencil);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDepthStencilSurface(IDirect3DSurface9 **ppZStencilSurface)
{
const HRESULT hr = _orig->GetDepthStencilSurface(ppZStencilSurface);
#if RESHADE_DEPTH
if (SUCCEEDED(hr))
{
assert(ppZStencilSurface != nullptr);
_buffer_detection.on_get_depthstencil(*ppZStencilSurface);
}
#endif
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::BeginScene()
{
return _orig->BeginScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::EndScene()
{
return _orig->EndScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::Clear(DWORD Count, const D3DRECT *pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil)
{
#if RESHADE_DEPTH
_buffer_detection.on_clear_depthstencil(Flags);
#endif
return _orig->Clear(Count, pRects, Flags, Color, Z, Stencil);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return _orig->SetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTransform(D3DTRANSFORMSTATETYPE State, D3DMATRIX *pMatrix)
{
return _orig->GetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::MultiplyTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return _orig->MultiplyTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetViewport(const D3DVIEWPORT9 *pViewport)
{
return _orig->SetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetViewport(D3DVIEWPORT9 *pViewport)
{
return _orig->GetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetMaterial(const D3DMATERIAL9 *pMaterial)
{
return _orig->SetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetMaterial(D3DMATERIAL9 *pMaterial)
{
return _orig->GetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetLight(DWORD Index, const D3DLIGHT9 *pLight)
{
return _orig->SetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetLight(DWORD Index, D3DLIGHT9 *pLight)
{
return _orig->GetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::LightEnable(DWORD Index, BOOL Enable)
{
return _orig->LightEnable(Index, Enable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetLightEnable(DWORD Index, BOOL *pEnable)
{
return _orig->GetLightEnable(Index, pEnable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetClipPlane(DWORD Index, const float *pPlane)
{
return _orig->SetClipPlane(Index, pPlane);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetClipPlane(DWORD Index, float *pPlane)
{
return _orig->GetClipPlane(Index, pPlane);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetRenderState(D3DRENDERSTATETYPE State, DWORD Value)
{
return _orig->SetRenderState(State, Value);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetRenderState(D3DRENDERSTATETYPE State, DWORD *pValue)
{
return _orig->GetRenderState(State, pValue);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateStateBlock(D3DSTATEBLOCKTYPE Type, IDirect3DStateBlock9 **ppSB)
{
return _orig->CreateStateBlock(Type, ppSB);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::BeginStateBlock()
{
return _orig->BeginStateBlock();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::EndStateBlock(IDirect3DStateBlock9 **ppSB)
{
return _orig->EndStateBlock(ppSB);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetClipStatus(const D3DCLIPSTATUS9 *pClipStatus)
{
return _orig->SetClipStatus(pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetClipStatus(D3DCLIPSTATUS9 *pClipStatus)
{
return _orig->GetClipStatus(pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTexture(DWORD Stage, IDirect3DBaseTexture9 **ppTexture)
{
return _orig->GetTexture(Stage, ppTexture);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTexture(DWORD Stage, IDirect3DBaseTexture9 *pTexture)
{
return _orig->SetTexture(Stage, pTexture);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD *pValue)
{
return _orig->GetTextureStageState(Stage, Type, pValue);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
return _orig->SetTextureStageState(Stage, Type, Value);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD *pValue)
{
return _orig->GetSamplerState(Sampler, Type, pValue);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetSamplerState(DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value)
{
return _orig->SetSamplerState(Sampler, Type, Value);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ValidateDevice(DWORD *pNumPasses)
{
return _orig->ValidateDevice(pNumPasses);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPaletteEntries(UINT PaletteNumber, const PALETTEENTRY *pEntries)
{
return _orig->SetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPaletteEntries(UINT PaletteNumber, PALETTEENTRY *pEntries)
{
return _orig->GetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetCurrentTexturePalette(UINT PaletteNumber)
{
return _orig->SetCurrentTexturePalette(PaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetCurrentTexturePalette(UINT *PaletteNumber)
{
return _orig->GetCurrentTexturePalette(PaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetScissorRect(const RECT *pRect)
{
return _orig->SetScissorRect(pRect);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetScissorRect(RECT *pRect)
{
return _orig->GetScissorRect(pRect);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetSoftwareVertexProcessing(BOOL bSoftware)
{
return _orig->SetSoftwareVertexProcessing(bSoftware);
}
BOOL STDMETHODCALLTYPE Direct3DDevice9::GetSoftwareVertexProcessing()
{
return _orig->GetSoftwareVertexProcessing();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetNPatchMode(float nSegments)
{
return _orig->SetNPatchMode(nSegments);
}
float STDMETHODCALLTYPE Direct3DDevice9::GetNPatchMode()
{
return _orig->GetNPatchMode();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount)
{
_buffer_detection.on_draw(PrimitiveType, PrimitiveCount);
return _orig->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT StartIndex, UINT PrimitiveCount)
{
_buffer_detection.on_draw(PrimitiveType, PrimitiveCount);
return _orig->DrawIndexedPrimitive(PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, StartIndex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
_buffer_detection.on_draw(PrimitiveType, PrimitiveCount);
return _orig->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, const void *pIndexData, D3DFORMAT IndexDataFormat, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
_buffer_detection.on_draw(PrimitiveType, PrimitiveCount);
return _orig->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9 *pDestBuffer, IDirect3DVertexDeclaration9 *pVertexDecl, DWORD Flags)
{
return _orig->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer, pVertexDecl, Flags);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexDeclaration(const D3DVERTEXELEMENT9 *pVertexElements, IDirect3DVertexDeclaration9 **ppDecl)
{
return _orig->CreateVertexDeclaration(pVertexElements, ppDecl);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexDeclaration(IDirect3DVertexDeclaration9 *pDecl)
{
return _orig->SetVertexDeclaration(pDecl);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexDeclaration(IDirect3DVertexDeclaration9 **ppDecl)
{
return _orig->GetVertexDeclaration(ppDecl);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetFVF(DWORD FVF)
{
return _orig->SetFVF(FVF);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetFVF(DWORD *pFVF)
{
return _orig->GetFVF(pFVF);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateVertexShader(const DWORD *pFunction, IDirect3DVertexShader9 **ppShader)
{
return _orig->CreateVertexShader(pFunction, ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShader(IDirect3DVertexShader9 *pShader)
{
return _orig->SetVertexShader(pShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShader(IDirect3DVertexShader9 **ppShader)
{
return _orig->GetVertexShader(ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount)
{
return _orig->SetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount)
{
return _orig->GetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount)
{
return _orig->SetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount)
{
return _orig->GetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetVertexShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount)
{
return _orig->SetVertexShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetVertexShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount)
{
return _orig->GetVertexShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 *pStreamData, UINT OffsetInBytes, UINT Stride)
{
return _orig->SetStreamSource(StreamNumber, pStreamData, OffsetInBytes, Stride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetStreamSource(UINT StreamNumber, IDirect3DVertexBuffer9 **ppStreamData, UINT *OffsetInBytes, UINT *pStride)
{
return _orig->GetStreamSource(StreamNumber, ppStreamData, OffsetInBytes, pStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetStreamSourceFreq(UINT StreamNumber, UINT Divider)
{
return _orig->SetStreamSourceFreq(StreamNumber, Divider);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetStreamSourceFreq(UINT StreamNumber, UINT *Divider)
{
return _orig->GetStreamSourceFreq(StreamNumber, Divider);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetIndices(IDirect3DIndexBuffer9 *pIndexData)
{
return _orig->SetIndices(pIndexData);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetIndices(IDirect3DIndexBuffer9 **ppIndexData)
{
return _orig->GetIndices(ppIndexData);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreatePixelShader(const DWORD *pFunction, IDirect3DPixelShader9 **ppShader)
{
return _orig->CreatePixelShader(pFunction, ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShader(IDirect3DPixelShader9 *pShader)
{
return _orig->SetPixelShader(pShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShader(IDirect3DPixelShader9 **ppShader)
{
return _orig->GetPixelShader(ppShader);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantF(UINT StartRegister, const float *pConstantData, UINT Vector4fCount)
{
return _orig->SetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantF(UINT StartRegister, float *pConstantData, UINT Vector4fCount)
{
return _orig->GetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantI(UINT StartRegister, const int *pConstantData, UINT Vector4iCount)
{
return _orig->SetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantI(UINT StartRegister, int *pConstantData, UINT Vector4iCount)
{
return _orig->GetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetPixelShaderConstantB(UINT StartRegister, const BOOL *pConstantData, UINT BoolCount)
{
return _orig->SetPixelShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetPixelShaderConstantB(UINT StartRegister, BOOL *pConstantData, UINT BoolCount)
{
return _orig->GetPixelShaderConstantB(StartRegister, pConstantData, BoolCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawRectPatch(UINT Handle, const float *pNumSegs, const D3DRECTPATCH_INFO *pRectPatchInfo)
{
return _orig->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DrawTriPatch(UINT Handle, const float *pNumSegs, const D3DTRIPATCH_INFO *pTriPatchInfo)
{
return _orig->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::DeletePatch(UINT Handle)
{
return _orig->DeletePatch(Handle);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateQuery(D3DQUERYTYPE Type, IDirect3DQuery9 **ppQuery)
{
return _orig->CreateQuery(Type, ppQuery);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetConvolutionMonoKernel(UINT width, UINT height, float *rows, float *columns)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->SetConvolutionMonoKernel(width, height, rows, columns);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ComposeRects(IDirect3DSurface9 *pSrc, IDirect3DSurface9 *pDst, IDirect3DVertexBuffer9 *pSrcRectDescs, UINT NumRects, IDirect3DVertexBuffer9 *pDstRectDescs, D3DCOMPOSERECTSOP Operation, int Xoffset, int Yoffset)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->ComposeRects(pSrc, pDst, pSrcRectDescs, NumRects, pDstRectDescs, Operation, Xoffset, Yoffset);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::PresentEx(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion, DWORD dwFlags)
{
if (Direct3DSwapChain9::is_presenting_entire_surface(pSourceRect, hDestWindowOverride))
_implicit_swapchain->_runtime->on_present();
_buffer_detection.reset(false);
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->PresentEx(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetGPUThreadPriority(INT *pPriority)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->GetGPUThreadPriority(pPriority);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetGPUThreadPriority(INT Priority)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->SetGPUThreadPriority(Priority);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::WaitForVBlank(UINT iSwapChain)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return D3DERR_INVALIDCALL;
}
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->WaitForVBlank(0);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CheckResourceResidency(IDirect3DResource9 **pResourceArray, UINT32 NumResources)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->CheckResourceResidency(pResourceArray, NumResources);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::SetMaximumFrameLatency(UINT MaxLatency)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->SetMaximumFrameLatency(MaxLatency);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetMaximumFrameLatency(UINT *pMaxLatency)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->GetMaximumFrameLatency(pMaxLatency);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CheckDeviceState(HWND hDestinationWindow)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->CheckDeviceState(hDestinationWindow);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateRenderTargetEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->CreateRenderTargetEx(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle, Usage);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateOffscreenPlainSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->CreateOffscreenPlainSurfaceEx(Width, Height, Format, Pool, ppSurface, pSharedHandle, Usage);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::CreateDepthStencilSurfaceEx(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9 **ppSurface, HANDLE *pSharedHandle, DWORD Usage)
{
assert(_extended_interface);
return static_cast<IDirect3DDevice9Ex *>(_orig)->CreateDepthStencilSurfaceEx(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle, Usage);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::ResetEx(D3DPRESENT_PARAMETERS *pPresentationParameters, D3DDISPLAYMODEEX *pFullscreenDisplayMode)
{
LOG(INFO) << "Redirecting " << "IDirect3DDevice9Ex::ResetEx" << '(' << "this = " << this << ", pPresentationParameters = " << pPresentationParameters << ", pFullscreenDisplayMode = " << pFullscreenDisplayMode << ')' << " ...";
if (pPresentationParameters == nullptr)
return D3DERR_INVALIDCALL;
com_ptr<IDirect3D9> d3d;
_orig->GetDirect3D(&d3d);
com_ptr<IDirect3D9Ex> d3dex;
d3d->QueryInterface(IID_PPV_ARGS(&d3dex));
D3DDEVICE_CREATION_PARAMETERS cp = {};
_orig->GetCreationParameters(&cp);
D3DPRESENT_PARAMETERS pp = *pPresentationParameters;
D3DDISPLAYMODEEX fullscreen_mode = { sizeof(fullscreen_mode) };
if (pFullscreenDisplayMode != nullptr)
fullscreen_mode = *pFullscreenDisplayMode;
dump_and_modify_present_parameters(pp, fullscreen_mode, d3dex.get(), cp.AdapterOrdinal);
d3d.reset();
d3dex.reset();
const auto runtime = _implicit_swapchain->_runtime;
runtime->on_reset();
_buffer_detection.reset(true);
_auto_depthstencil.reset();
assert(_extended_interface);
const HRESULT hr = static_cast<IDirect3DDevice9Ex *>(_orig)->ResetEx(&pp, pp.Windowed ? nullptr : &fullscreen_mode);
pPresentationParameters->BackBufferWidth = pp.BackBufferWidth;
pPresentationParameters->BackBufferHeight = pp.BackBufferHeight;
pPresentationParameters->BackBufferFormat = pp.BackBufferFormat;
pPresentationParameters->BackBufferCount = pp.BackBufferCount;
if (FAILED(hr))
{
LOG(ERROR) << "IDirect3DDevice9Ex::ResetEx" << " failed with error code " << hr << '!';
return hr;
}
_implicit_swapchain->GetPresentParameters(&pp);
if (!runtime->on_init(pp))
LOG(ERROR) << "Failed to recreate Direct3D 9 runtime environment on runtime " << runtime.get() << '.';
// Reload auto depth-stencil surface
if (pp.EnableAutoDepthStencil)
{
_orig->GetDepthStencilSurface(&_auto_depthstencil);
SetDepthStencilSurface(_auto_depthstencil.get());
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice9::GetDisplayModeEx(UINT iSwapChain, D3DDISPLAYMODEEX *pMode, D3DDISPLAYROTATION *pRotation)
{
if (iSwapChain != 0)
{
LOG(WARN) << "Access to multi-head swap chain at index " << iSwapChain << " is unsupported.";
return D3DERR_INVALIDCALL;
}
assert(_extended_interface);
assert(_implicit_swapchain->_extended_interface);
return static_cast<IDirect3DSwapChain9Ex *>(_implicit_swapchain)->GetDisplayModeEx(pMode, pRotation);
}
| 40.823864 | 272 | 0.808796 | [
"object"
] |
4f8b51682be2e6eff3aa9715f1797560b86ddcbd | 34,390 | cpp | C++ | Source/Engine/UI/ListView.cpp | 1vanK/Urho3DQuake2 | 6b166c55414cb55a81bd777a735d0ddae0b0451a | [
"Apache-2.0"
] | 7 | 2016-05-13T02:07:22.000Z | 2022-02-13T20:34:10.000Z | Source/Engine/UI/ListView.cpp | 1vanK/Urho3DQuake2 | 6b166c55414cb55a81bd777a735d0ddae0b0451a | [
"Apache-2.0"
] | null | null | null | Source/Engine/UI/ListView.cpp | 1vanK/Urho3DQuake2 | 6b166c55414cb55a81bd777a735d0ddae0b0451a | [
"Apache-2.0"
] | 3 | 2016-11-20T14:47:00.000Z | 2019-01-19T15:07:44.000Z | //
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 "Precompiled.h"
#include "CheckBox.h"
#include "Context.h"
#include "InputEvents.h"
#include "ListView.h"
#include "Log.h"
#include "Sort.h"
#include "Text.h"
#include "UI.h"
#include "UIEvents.h"
#include "DebugNew.h"
namespace Urho3D
{
static const char* highlightModes[] =
{
"Never",
"Focus",
"Always",
0
};
template<> HighlightMode Variant::Get<HighlightMode>() const
{
return (HighlightMode)GetInt();
}
static const ShortStringHash expandedHash("Expanded");
extern const char* UI_CATEGORY;
bool GetItemExpanded(UIElement* item)
{
return item ? item->GetVar(expandedHash).GetBool() : false;
}
void SetItemExpanded(UIElement* item, bool enable)
{
item->SetVar(expandedHash, enable);
}
static const ShortStringHash hierarchyParentHash("HierarchyParent");
bool GetItemHierarchyParent(UIElement* item)
{
return item ? item->GetVar(hierarchyParentHash).GetBool() : false;
}
void SetItemHierarchyParent(UIElement* item, bool enable)
{
item->SetVar(hierarchyParentHash, enable);
}
/// Hierarchy container (used by ListView internally when in hierarchy mode).
class HierarchyContainer : public UIElement
{
OBJECT(HierarchyContainer);
public:
/// Construct.
HierarchyContainer(Context* context, ListView* listView, UIElement* overlayContainer) :
UIElement(context),
listView_(listView),
overlayContainer_(overlayContainer)
{
SubscribeToEvent(this, E_LAYOUTUPDATED, HANDLER(HierarchyContainer, HandleLayoutUpdated));
SubscribeToEvent(overlayContainer->GetParent(), E_VIEWCHANGED, HANDLER(HierarchyContainer, HandleViewChanged));
SubscribeToEvent(E_UIMOUSECLICK, HANDLER(HierarchyContainer, HandleUIMouseClick));
}
/// Handle layout updated by adjusting the position of the overlays.
void HandleLayoutUpdated(StringHash eventType, VariantMap& eventData)
{
// Adjust the container size for child clipping effect
overlayContainer_->SetSize(GetParent()->GetSize());
for (unsigned i = 0; i < children_.Size(); ++i)
{
const IntVector2& position = children_[i]->GetPosition();
CheckBox* overlay = static_cast<CheckBox*>(overlayContainer_->GetChild(i));
bool visible = children_[i]->IsVisible() && GetItemHierarchyParent(children_[i]);
overlay->SetVisible(visible);
if (visible)
{
overlay->SetPosition(position.x_, position.y_);
overlay->SetChecked(GetItemExpanded(children_[i]));
}
}
}
/// Handle view changed by scrolling the overlays in tandem.
void HandleViewChanged(StringHash eventType, VariantMap& eventData)
{
using namespace ViewChanged;
int x = eventData[P_X].GetInt();
int y = eventData[P_Y].GetInt();
IntRect panelBorder = GetParent()->GetClipBorder();
overlayContainer_->SetChildOffset(IntVector2(-x + panelBorder.left_, -y + panelBorder.top_));
}
/// Handle mouse click on overlays by toggling the expansion state of the corresponding item
void HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
{
using namespace UIMouseClick;
UIElement* overlay = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
if (overlay)
{
const Vector<SharedPtr<UIElement> >& children = overlayContainer_->GetChildren();
Vector<SharedPtr<UIElement> >::ConstIterator i = children.Find(SharedPtr<UIElement>(overlay));
if (i != children.End())
listView_->ToggleExpand(i - children.Begin());
}
}
/// Insert a child element into a specific position in the child list.
void InsertChild(unsigned index, UIElement* element)
{
// Insert the overlay at the same index position to the overlay container
CheckBox* overlay = static_cast<CheckBox*>(overlayContainer_->CreateChild(CheckBox::GetTypeStatic(), String::EMPTY, index));
overlay->SetStyle("HierarchyListViewOverlay");
int baseIndent = listView_->GetBaseIndent();
int indent = element->GetIndent() - baseIndent - 1;
overlay->SetIndent(indent);
overlay->SetFixedWidth((indent + 1) * element->GetIndentSpacing());
// Then insert the element as child as per normal
UIElement::InsertChild(index, element);
}
private:
// Parent list view.
ListView* listView_;
// Container for overlay checkboxes.
UIElement* overlayContainer_;
};
ListView::ListView(Context* context) :
ScrollView(context),
highlightMode_(HM_FOCUS),
multiselect_(false),
hierarchyMode_(true), // Init to true here so that the setter below takes effect
baseIndent_(0),
clearSelectionOnDefocus_(false),
selectOnClickEnd_(false)
{
resizeContentWidth_ = true;
// By default list view is set to non-hierarchy mode
SetHierarchyMode(false);
SubscribeToEvent(E_UIMOUSEDOUBLECLICK, HANDLER(ListView, HandleUIMouseDoubleClick));
SubscribeToEvent(E_FOCUSCHANGED, HANDLER(ListView, HandleItemFocusChanged));
SubscribeToEvent(this, E_DEFOCUSED, HANDLER(ListView, HandleFocusChanged));
SubscribeToEvent(this, E_FOCUSED, HANDLER(ListView, HandleFocusChanged));
UpdateUIClickSubscription();
}
ListView::~ListView()
{
}
void ListView::RegisterObject(Context* context)
{
context->RegisterFactory<ListView>(UI_CATEGORY);
COPY_BASE_ATTRIBUTES(HierarchyContainer, UIElement);
COPY_BASE_ATTRIBUTES(ListView, ScrollView);
ENUM_ACCESSOR_ATTRIBUTE(ListView, "Highlight Mode", GetHighlightMode, SetHighlightMode, HighlightMode, highlightModes, HM_FOCUS, AM_FILE);
ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Multiselect", GetMultiselect, SetMultiselect, bool, false, AM_FILE);
ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Hierarchy Mode", GetHierarchyMode, SetHierarchyMode, bool, false, AM_FILE);
ACCESSOR_ATTRIBUTE(ListView, VAR_INT, "Base Indent", GetBaseIndent, SetBaseIndent, int, 0, AM_FILE);
ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Clear Sel. On Defocus", GetClearSelectionOnDefocus, SetClearSelectionOnDefocus, bool, false, AM_FILE);
ACCESSOR_ATTRIBUTE(ListView, VAR_BOOL, "Select On Click End", GetSelectOnClickEnd, SetSelectOnClickEnd, bool, false, AM_FILE);
}
void ListView::OnKey(int key, int buttons, int qualifiers)
{
// If no selection, can not move with keys
unsigned numItems = GetNumItems();
unsigned selection = GetSelection();
// If either shift or ctrl held down, add to selection if multiselect enabled
bool additive = multiselect_ && qualifiers & (QUAL_SHIFT | QUAL_CTRL);
int delta = M_MAX_INT;
int pageDirection = 1;
if (numItems)
{
if (selection != M_MAX_UNSIGNED && qualifiers & QUAL_CTRL && key == KEY_C)
{
CopySelectedItemsToClipboard();
return;
}
switch (key)
{
case KEY_LEFT:
case KEY_RIGHT:
if (selection != M_MAX_UNSIGNED && hierarchyMode_)
{
Expand(selection, key == KEY_RIGHT);
return;
}
break;
case KEY_RETURN:
case KEY_RETURN2:
case KEY_KP_ENTER:
if (selection != M_MAX_UNSIGNED && hierarchyMode_)
{
ToggleExpand(selection);
return;
}
break;
case KEY_UP:
delta = -1;
break;
case KEY_DOWN:
delta = 1;
break;
case KEY_PAGEUP:
pageDirection = -1;
// Fallthru
case KEY_PAGEDOWN:
{
// Convert page step to pixels and see how many items have to be skipped to reach that many pixels
if (selection == M_MAX_UNSIGNED)
selection = 0; // Assume as if first item is selected
int stepPixels = ((int)(pageStep_ * scrollPanel_->GetHeight())) - contentElement_->GetChild(selection)->GetHeight();
unsigned newSelection = selection;
unsigned okSelection = selection;
unsigned invisible = 0;
while (newSelection < numItems)
{
UIElement* item = GetItem(newSelection);
int height = 0;
if (item->IsVisible())
{
height = item->GetHeight();
okSelection = newSelection;
}
else
++invisible;
if (stepPixels < height)
break;
stepPixels -= height;
newSelection += pageDirection;
}
delta = okSelection - selection - pageDirection * invisible;
}
break;
case KEY_HOME:
delta = -(int)GetNumItems();
break;
case KEY_END:
delta = GetNumItems();
break;
}
}
if (delta != M_MAX_INT)
{
ChangeSelection(delta, additive);
return;
}
using namespace UnhandledKey;
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
eventData[P_KEY] = key;
eventData[P_BUTTONS] = buttons;
eventData[P_QUALIFIERS] = qualifiers;
SendEvent(E_UNHANDLEDKEY, eventData);
}
void ListView::OnResize()
{
ScrollView::OnResize();
// When in hierarchy mode also need to resize the overlay container
if (hierarchyMode_)
overlayContainer_->SetSize(scrollPanel_->GetSize());
}
void ListView::AddItem(UIElement* item)
{
InsertItem(M_MAX_UNSIGNED, item);
}
void ListView::InsertItem(unsigned index, UIElement* item, UIElement* parentItem)
{
if (!item || item->GetParent() == contentElement_)
return;
// Enable input so that clicking the item can be detected
item->SetEnabled(true);
item->SetSelected(false);
unsigned numItems = contentElement_->GetNumChildren();
if (hierarchyMode_)
{
int baseIndent = baseIndent_;
if (parentItem)
{
baseIndent = parentItem->GetIndent();
SetItemHierarchyParent(parentItem, true);
// Adjust the index to ensure it is within the children index limit of the parent item
unsigned indexLimit = FindItem(parentItem);
if (index <= indexLimit)
index = indexLimit + 1;
else
{
while (++indexLimit < numItems)
{
if (contentElement_->GetChild(indexLimit)->GetIndent() <= baseIndent)
break;
}
if (index > indexLimit)
index = indexLimit;
}
}
item->SetIndent(baseIndent + 1);
SetItemExpanded(item, item->IsVisible());
// Use the 'overrided' version to insert the child item
static_cast<HierarchyContainer*>(contentElement_.Get())->InsertChild(index, item);
}
else
{
if (index > numItems)
index = numItems;
contentElement_->InsertChild(index, item);
}
// If necessary, shift the following selections
if (!selections_.Empty())
{
for (unsigned i = 0; i < selections_.Size(); ++i)
{
if (selections_[i] >= index)
++selections_[i];
}
UpdateSelectionEffect();
}
}
void ListView::RemoveItem(UIElement* item, unsigned index)
{
if (!item)
return;
unsigned numItems = GetNumItems();
for (unsigned i = index; i < numItems; ++i)
{
if (GetItem(i) == item)
{
item->SetSelected(false);
selections_.Remove(i);
unsigned removed = 1;
if (hierarchyMode_)
{
// Remove any child items in hierarchy mode
if (GetItemHierarchyParent(item))
{
int baseIndent = item->GetIndent();
for (unsigned j = i + 1; ; ++j)
{
UIElement* childItem = GetItem(i + 1);
if (!childItem)
break;
if (childItem->GetIndent() > baseIndent)
{
childItem->SetSelected(false);
selections_.Erase(j);
contentElement_->RemoveChildAtIndex(i + 1);
overlayContainer_->RemoveChildAtIndex(i + 1);
++removed;
}
else
break;
}
}
// Check if the parent of removed item still has other children
if (i > 0)
{
int baseIndent = item->GetIndent();
UIElement* prevKin = GetItem(i - 1); // Could be parent or sibling
if (prevKin->GetIndent() < baseIndent)
{
UIElement* nextKin = GetItem(i + 1); // Could be sibling or parent-sibling or 0 if index out of bound
if (!nextKin || nextKin->GetIndent() < baseIndent)
{
// If we reach here then the parent has no other children
SetItemHierarchyParent(prevKin, false);
}
}
}
// Remove the overlay at the same index
overlayContainer_->RemoveChildAtIndex(i);
}
// If necessary, shift the following selections
if (!selections_.Empty())
{
for (unsigned j = 0; j < selections_.Size(); ++j)
{
if (selections_[j] > i)
selections_[j] -= removed;
}
UpdateSelectionEffect();
}
contentElement_->RemoveChildAtIndex(i);
break;
}
}
}
void ListView::RemoveItem(unsigned index)
{
RemoveItem(GetItem(index), index);
}
void ListView::RemoveAllItems()
{
contentElement_->DisableLayoutUpdate();
ClearSelection();
contentElement_->RemoveAllChildren();
if (hierarchyMode_)
overlayContainer_->RemoveAllChildren();
contentElement_->EnableLayoutUpdate();
contentElement_->UpdateLayout();
}
void ListView::SetSelection(unsigned index)
{
PODVector<unsigned> indices;
indices.Push(index);
SetSelections(indices);
EnsureItemVisibility(index);
}
void ListView::SetSelections(const PODVector<unsigned>& indices)
{
// Make a weak pointer to self to check for destruction as a response to events
WeakPtr<ListView> self(this);
unsigned numItems = GetNumItems();
// Remove first items that should no longer be selected
for (PODVector<unsigned>::Iterator i = selections_.Begin(); i != selections_.End();)
{
unsigned index = *i;
if (!indices.Contains(index))
{
i = selections_.Erase(i);
using namespace ItemSelected;
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
eventData[P_SELECTION] = index;
SendEvent(E_ITEMDESELECTED, eventData);
if (self.Expired())
return;
}
else
++i;
}
bool added = false;
// Then add missing items
for (PODVector<unsigned>::ConstIterator i = indices.Begin(); i != indices.End(); ++i)
{
unsigned index = *i;
if (index < numItems)
{
// In singleselect mode, resend the event even for the same selection
bool duplicate = selections_.Contains(index);
if (!duplicate || !multiselect_)
{
if (!duplicate)
{
selections_.Push(index);
added = true;
}
using namespace ItemSelected;
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
eventData[P_SELECTION] = *i;
SendEvent(E_ITEMSELECTED, eventData);
if (self.Expired())
return;
}
}
// If no multiselect enabled, allow setting only one item
if (!multiselect_)
break;
}
// Re-sort selections if necessary
if (added)
Sort(selections_.Begin(), selections_.End());
UpdateSelectionEffect();
SendEvent(E_SELECTIONCHANGED);
}
void ListView::AddSelection(unsigned index)
{
// Make a weak pointer to self to check for destruction as a response to events
WeakPtr<ListView> self(this);
if (!multiselect_)
SetSelection(index);
else
{
if (index >= GetNumItems())
return;
if (!selections_.Contains(index))
{
selections_.Push(index);
using namespace ItemSelected;
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
eventData[P_SELECTION] = index;
SendEvent(E_ITEMSELECTED, eventData);
if (self.Expired())
return;
Sort(selections_.Begin(), selections_.End());
}
EnsureItemVisibility(index);
UpdateSelectionEffect();
SendEvent(E_SELECTIONCHANGED);
}
}
void ListView::RemoveSelection(unsigned index)
{
if (index >= GetNumItems())
return;
if (selections_.Remove(index))
{
using namespace ItemSelected;
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
eventData[P_SELECTION] = index;
SendEvent(E_ITEMDESELECTED, eventData);
}
EnsureItemVisibility(index);
UpdateSelectionEffect();
SendEvent(E_SELECTIONCHANGED);
}
void ListView::ToggleSelection(unsigned index)
{
unsigned numItems = GetNumItems();
if (index >= numItems)
return;
if (selections_.Contains(index))
RemoveSelection(index);
else
AddSelection(index);
}
void ListView::ChangeSelection(int delta, bool additive)
{
unsigned numItems = GetNumItems();
if (selections_.Empty())
{
// Select first item if there is no selection yet
if (numItems > 0)
SetSelection(0);
if (abs(delta) == 1)
return;
}
if (!multiselect_)
additive = false;
// If going downwards, use the last selection as a base. Otherwise use first
unsigned selection = delta > 0 ? selections_.Back() : selections_.Front();
int direction = delta > 0 ? 1 : -1;
unsigned newSelection = selection;
unsigned okSelection = selection;
PODVector<unsigned> indices = selections_;
while (delta != 0)
{
newSelection += direction;
if (newSelection >= numItems)
break;
UIElement* item = GetItem(newSelection);
if (item->IsVisible())
{
indices.Push(okSelection = newSelection);
delta -= direction;
}
}
if (!additive)
SetSelection(okSelection);
else
SetSelections(indices);
}
void ListView::ClearSelection()
{
SetSelections(PODVector<unsigned>());
}
void ListView::SetHighlightMode(HighlightMode mode)
{
highlightMode_ = mode;
UpdateSelectionEffect();
}
void ListView::SetMultiselect(bool enable)
{
multiselect_ = enable;
}
void ListView::SetHierarchyMode(bool enable)
{
if (enable == hierarchyMode_)
return;
hierarchyMode_ = enable;
UIElement* container;
if (enable)
{
overlayContainer_ = new UIElement(context_);
overlayContainer_->SetName("LV_OverlayContainer");
overlayContainer_->SetInternal(true);
AddChild(overlayContainer_);
overlayContainer_->SetSortChildren(false);
overlayContainer_->SetClipChildren(true);
container = new HierarchyContainer(context_, this, overlayContainer_);
}
else
{
if (overlayContainer_)
{
RemoveChild(overlayContainer_);
overlayContainer_.Reset();
}
container = new UIElement(context_);
}
container->SetName("LV_ItemContainer");
container->SetInternal(true);
SetContentElement(container);
container->SetEnabled(true);
container->SetSortChildren(false);
}
void ListView::SetBaseIndent(int baseIndent)
{
baseIndent_ = baseIndent;
UpdateLayout();
}
void ListView::SetClearSelectionOnDefocus(bool enable)
{
if (enable != clearSelectionOnDefocus_)
{
clearSelectionOnDefocus_ = enable;
if (clearSelectionOnDefocus_ && !HasFocus())
ClearSelection();
}
}
void ListView::SetSelectOnClickEnd(bool enable)
{
if (enable != selectOnClickEnd_)
{
selectOnClickEnd_ = enable;
UpdateUIClickSubscription();
}
}
void ListView::Expand(unsigned index, bool enable, bool recursive)
{
if (!hierarchyMode_)
return;
unsigned numItems = GetNumItems();
if (index >= numItems)
return;
UIElement* item = GetItem(index++);
SetItemExpanded(item, enable);
int baseIndent = item->GetIndent();
PODVector<bool> expanded(baseIndent + 1);
expanded[baseIndent] = enable;
contentElement_->DisableLayoutUpdate();
while (index < numItems)
{
item = GetItem(index++);
int indent = item->GetIndent();
if (indent <= baseIndent)
break;
// Propagate the state to children when it is recursive
if (recursive)
SetItemExpanded(item, enable);
// Use the parent expanded flag to influence the visibility of its children
bool visible = enable && expanded[indent - 1];
item->SetVisible(visible);
if (indent >= (int)expanded.Size())
expanded.Resize(indent + 1);
expanded[indent] = visible && GetItemExpanded(item);
}
contentElement_->EnableLayoutUpdate();
contentElement_->UpdateLayout();
}
void ListView::ToggleExpand(unsigned index, bool recursive)
{
if (!hierarchyMode_)
return;
unsigned numItems = GetNumItems();
if (index >= numItems)
return;
UIElement* item = GetItem(index);
Expand(index, !GetItemExpanded(item), recursive);
}
unsigned ListView::GetNumItems() const
{
return contentElement_->GetNumChildren();
}
UIElement* ListView::GetItem(unsigned index) const
{
return contentElement_->GetChild(index);
}
PODVector<UIElement*> ListView::GetItems() const
{
PODVector<UIElement*> items;
contentElement_->GetChildren(items);
return items;
}
unsigned ListView::FindItem(UIElement* item) const
{
if (!item)
return M_MAX_UNSIGNED;
// Early-out by checking if the item belongs to the listview hierarchy at all
if (item->GetParent() != contentElement_)
return M_MAX_UNSIGNED;
const Vector<SharedPtr<UIElement> >& children = contentElement_->GetChildren();
// Binary search for list item based on screen coordinate Y
if (contentElement_->GetLayoutMode() == LM_VERTICAL && item->GetHeight())
{
int itemY = item->GetScreenPosition().y_;
int left = 0;
int right = children.Size() - 1;
while (right >= left)
{
int mid = (left + right) / 2;
if (children[mid] == item)
return mid;
if (itemY < children[mid]->GetScreenPosition().y_)
right = mid - 1;
else
left = mid + 1;
}
}
// Fallback to linear search in case the coordinates/sizes were not yet initialized
for (unsigned i = 0; i < children.Size(); ++i)
{
if (children[i] == item)
return i;
}
return M_MAX_UNSIGNED;
}
unsigned ListView::GetSelection() const
{
if (selections_.Empty())
return M_MAX_UNSIGNED;
else
return GetSelections().Front();
}
UIElement* ListView::GetSelectedItem() const
{
return contentElement_->GetChild(GetSelection());
}
PODVector<UIElement*> ListView::GetSelectedItems() const
{
PODVector<UIElement*> ret;
for (PODVector<unsigned>::ConstIterator i = selections_.Begin(); i != selections_.End(); ++i)
{
UIElement* item = GetItem(*i);
if (item)
ret.Push(item);
}
return ret;
}
void ListView::CopySelectedItemsToClipboard() const
{
String selectedText;
for (PODVector<unsigned>::ConstIterator i = selections_.Begin(); i != selections_.End(); ++i)
{
// Only handle Text UI element
Text* text = dynamic_cast<Text*>(GetItem(*i));
if (text)
selectedText.Append(text->GetText()).Append("\n");
}
GetSubsystem<UI>()->SetClipboardText(selectedText);
}
bool ListView::IsSelected(unsigned index) const
{
return selections_.Contains(index);
}
bool ListView::IsExpanded(unsigned index) const
{
return GetItemExpanded(contentElement_->GetChild(index));
}
bool ListView::FilterImplicitAttributes(XMLElement& dest) const
{
if (!ScrollView::FilterImplicitAttributes(dest))
return false;
XMLElement childElem = dest.GetChild("element"); // Horizontal scroll bar
if (!childElem)
return false;
childElem = childElem.GetNext("element"); // Vertical scroll bar
if (!childElem)
return false;
childElem = childElem.GetNext("element"); // Scroll panel
if (!childElem)
return false;
XMLElement containerElem = childElem.GetChild("element"); // Item container
if (!containerElem)
return false;
if (!RemoveChildXML(containerElem, "Name", "LV_ItemContainer"))
return false;
if (!RemoveChildXML(containerElem, "Is Enabled", "true"))
return false;
if (!RemoveChildXML(containerElem, "Layout Mode", "Vertical"))
return false;
if (!RemoveChildXML(containerElem, "Size"))
return false;
if (hierarchyMode_)
{
containerElem = childElem.GetNext("element"); // Overlay container
if (!containerElem)
return false;
if (!RemoveChildXML(containerElem, "Name", "LV_OverlayContainer"))
return false;
if (!RemoveChildXML(containerElem, "Clip Children", "true"))
return false;
if (!RemoveChildXML(containerElem, "Size"))
return false;
}
return true;
}
void ListView::UpdateSelectionEffect()
{
unsigned numItems = GetNumItems();
bool highlighted = highlightMode_ == HM_ALWAYS || HasFocus();
for (unsigned i = 0; i < numItems; ++i)
{
UIElement* item = GetItem(i);
if (highlightMode_ != HM_NEVER && selections_.Contains(i))
item->SetSelected(highlighted);
else
item->SetSelected(false);
}
}
void ListView::EnsureItemVisibility(unsigned index)
{
EnsureItemVisibility(GetItem(index));
}
void ListView::EnsureItemVisibility(UIElement* item)
{
if (!item || !item->IsVisible())
return;
IntVector2 newView = GetViewPosition();
IntVector2 currentOffset = item->GetPosition() - newView;
const IntRect& clipBorder = scrollPanel_->GetClipBorder();
IntVector2 windowSize(scrollPanel_->GetWidth() - clipBorder.left_ - clipBorder.right_, scrollPanel_->GetHeight() -
clipBorder.top_ - clipBorder.bottom_);
if (currentOffset.y_ < 0)
newView.y_ += currentOffset.y_;
if (currentOffset.y_ + item->GetHeight() > windowSize.y_)
newView.y_ += currentOffset.y_ + item->GetHeight() - windowSize.y_;
SetViewPosition(newView);
}
void ListView::HandleUIMouseClick(StringHash eventType, VariantMap& eventData)
{
// Disregard the click end if a drag is going on
if (selectOnClickEnd_ && GetSubsystem<UI>()->GetDragElement())
return;
int button = eventData[UIMouseClick::P_BUTTON].GetInt();
int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
// Check if the clicked element belongs to the list
unsigned i = FindItem(element);
if (i >= GetNumItems())
return;
// If not editable, repeat the previous selection. This will send an event and allow eg. a dropdownlist to close
if (!editable_)
{
SetSelections(selections_);
return;
}
if (button == MOUSEB_LEFT)
{
// Single selection
if (!multiselect_ || !qualifiers)
SetSelection(i);
// Check multiselect with shift & ctrl
if (multiselect_)
{
if (qualifiers & QUAL_SHIFT)
{
if (selections_.Empty())
SetSelection(i);
else
{
unsigned first = selections_.Front();
unsigned last = selections_.Back();
PODVector<unsigned> newSelections = selections_;
if (i == first || i == last)
{
for (unsigned j = first; j <= last; ++j)
newSelections.Push(j);
}
else if (i < first)
{
for (unsigned j = i; j <= first; ++j)
newSelections.Push(j);
}
else if (i < last)
{
if ((abs((int)i - (int)first)) <= (abs((int)i - (int)last)))
{
for (unsigned j = first; j <= i; ++j)
newSelections.Push(j);
}
else
{
for (unsigned j = i; j <= last; ++j)
newSelections.Push(j);
}
}
else if (i > last)
{
for (unsigned j = last; j <= i; ++j)
newSelections.Push(j);
}
SetSelections(newSelections);
}
}
else if (qualifiers & QUAL_CTRL)
ToggleSelection(i);
}
}
// Propagate the click as an event. Also include right-clicks
VariantMap& clickEventData = GetEventDataMap();
clickEventData[ItemClicked::P_ELEMENT] = this;
clickEventData[ItemClicked::P_ITEM] = element;
clickEventData[ItemClicked::P_SELECTION] = i;
clickEventData[ItemClicked::P_BUTTON] = button;
clickEventData[ItemClicked::P_BUTTONS] = buttons;
clickEventData[ItemClicked::P_QUALIFIERS] = qualifiers;
SendEvent(E_ITEMCLICKED, clickEventData);
}
void ListView::HandleUIMouseDoubleClick(StringHash eventType, VariantMap& eventData)
{
int button = eventData[UIMouseClick::P_BUTTON].GetInt();
int buttons = eventData[UIMouseClick::P_BUTTONS].GetInt();
int qualifiers = eventData[UIMouseClick::P_QUALIFIERS].GetInt();
UIElement* element = static_cast<UIElement*>(eventData[UIMouseClick::P_ELEMENT].GetPtr());
// Check if the clicked element belongs to the list
unsigned i = FindItem(element);
if (i >= GetNumItems())
return;
VariantMap& clickEventData = GetEventDataMap();
clickEventData[ItemDoubleClicked::P_ELEMENT] = this;
clickEventData[ItemDoubleClicked::P_ITEM] = element;
clickEventData[ItemDoubleClicked::P_SELECTION] = i;
clickEventData[ItemDoubleClicked::P_BUTTON] = button;
clickEventData[ItemDoubleClicked::P_BUTTONS] = buttons;
clickEventData[ItemDoubleClicked::P_QUALIFIERS] = qualifiers;
SendEvent(E_ITEMDOUBLECLICKED, clickEventData);
}
void ListView::HandleItemFocusChanged(StringHash eventType, VariantMap& eventData)
{
using namespace FocusChanged;
UIElement* element = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
while (element)
{
// If the focused element or its parent is in the list, scroll the list to make the item visible
UIElement* parent = element->GetParent();
if (parent == contentElement_)
{
EnsureItemVisibility(element);
return;
}
element = parent;
}
}
void ListView::HandleFocusChanged(StringHash eventType, VariantMap& eventData)
{
scrollPanel_->SetSelected(eventType == E_FOCUSED);
if (clearSelectionOnDefocus_ && eventType == E_DEFOCUSED)
ClearSelection();
else if (highlightMode_ == HM_FOCUS)
UpdateSelectionEffect();
}
void ListView::UpdateUIClickSubscription()
{
UnsubscribeFromEvent(E_UIMOUSECLICK);
UnsubscribeFromEvent(E_UIMOUSECLICKEND);
SubscribeToEvent(selectOnClickEnd_ ? E_UIMOUSECLICKEND : E_UIMOUSECLICK, HANDLER(ListView, HandleUIMouseClick));
}
}
| 30.299559 | 146 | 0.602588 | [
"object",
"vector"
] |
4f9329c48af4b83363d9719254e875e598c2fdc8 | 5,244 | hpp | C++ | tests/stubs/infrastructure_connection_stub.hpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 15 | 2016-01-28T16:54:57.000Z | 2021-04-16T08:28:21.000Z | tests/stubs/infrastructure_connection_stub.hpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | null | null | null | tests/stubs/infrastructure_connection_stub.hpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 3 | 2016-07-16T05:22:11.000Z | 2020-04-03T08:59:26.000Z | #ifndef INFRASTRUCTURE_CONNECTION_STUB_HPP
#define INFRASTRUCTURE_CONNECTION_STUB_HPP
#include <iostream>
#include <fstream>
#include "../source/infrastructure/asio_tcp_connection.hpp"
#include "../source/infrastructure/asio_tcp_connection_manager.hpp"
/**
* @brief The infrastrustructure_timer_stub does nothing
*/
class infrastrustructure_timer_stub : public Iinfrastructure_timeout_connection
{
// Iinfrastructure_timeout_connection interface
public:
void cancel() override
{
}
void wait_async() override
{
}
};
/**
* @brief The infrastructure_read_connection_stub reads predefined data and
* returns it as canned response -> writing to it does not do anything.
*/
class infrastructure_read_connection_stub : public Iinfrastructure_upperlayer_connection
{
private:
std::unique_ptr<std::ifstream> in;
boost::system::error_code ec;
const boost::system::error_code success_ec;
std::size_t error_after_bytecount;
std::function<void(std::size_t)> write_handler;
public:
infrastructure_read_connection_stub():
in {nullptr},
ec {},
success_ec {},
error_after_bytecount {0},
write_handler {nullptr}
{
}
void set_write_handler(decltype(write_handler) on_write)
{
write_handler = on_write;
}
void set_next_segment(std::string file)
{
in = std::unique_ptr<std::ifstream> {new std::ifstream{file, std::ios::binary}};
}
void set_error_on_next(boost::system::errc::errc_t error = boost::system::errc::broken_pipe)
{
ec.assign(error, boost::system::generic_category());
}
void set_error_after_bytecount(std::size_t bytes = 0, boost::system::errc::errc_t error = boost::system::errc::broken_pipe)
{
set_error_on_next(error);
error_after_bytecount = bytes;
}
// Iinfrastructure_upperlayer_connection interface
void write_data(std::shared_ptr<std::vector<unsigned char>> buffer,
std::function<void(const boost::system::error_code&, std::size_t)> on_complete) override
{
if (write_handler) {
write_handler(buffer->size());
}
if (error_after_bytecount == 0) {
on_complete(ec, buffer->size());
} else {
if (buffer->size() <= error_after_bytecount) {
on_complete(success_ec, buffer->size());
} else {
on_complete(ec, error_after_bytecount);
}
}
set_error_on_next(boost::system::errc::success);
}
void write_data(void*, std::size_t len,
std::function<void (const boost::system::error_code&, std::size_t)> on_complete) override
{
if (write_handler) {
write_handler(len);
}
if (error_after_bytecount == 0) {
on_complete(ec, len);
} else {
if (len <= error_after_bytecount) {
on_complete(success_ec, len);
} else {
on_complete(ec, error_after_bytecount);
}
}
set_error_on_next(boost::system::errc::success);
}
void read_data(std::shared_ptr<std::vector<unsigned char>> buffer,
std::size_t len, std::function<void(const boost::system::error_code&, std::size_t)> on_complete) override
{
std::istreambuf_iterator<char> instream {*in};
std::copy_n(instream, len, std::begin(*buffer));
std::advance(instream, 1);
if (error_after_bytecount == 0) {
on_complete(ec, len);
} else {
if (len <= error_after_bytecount) {
on_complete(success_ec, len);
} else {
on_complete(ec, error_after_bytecount);
}
}
set_error_on_next(boost::system::errc::success);
}
void read_data(std::shared_ptr<std::vector<unsigned char>> buffer,
std::function<void (const boost::system::error_code&, std::size_t)> on_complete) override
{
auto size = buffer->size();
std::istreambuf_iterator<char> instream {*in};
//std::copy(instream, std::istreambuf_iterator<char>(), std::begin(*buffer));
std::copy_n(instream, size, std::begin(*buffer));
std::advance(instream, 1);
if (error_after_bytecount == 0) {
on_complete(ec, size);
} else {
if (buffer->size() <= error_after_bytecount) {
on_complete(success_ec, buffer->size());
} else {
on_complete(ec, error_after_bytecount);
}
}
set_error_on_next(boost::system::errc::success);
}
std::unique_ptr<Iinfrastructure_timeout_connection> timeout_timer(std::chrono::duration<int>, std::function<void ()>) override
{
return std::unique_ptr<Iinfrastructure_timeout_connection> {new infrastrustructure_timer_stub{}};
}
bool is_stopped() const override
{
return false;
}
void close() override
{
}
};
#endif // INFRASTRUCTURE_CONNECTION_STUB_HPP
| 31.029586 | 132 | 0.601449 | [
"vector"
] |
4f948261b6a701b98dd3bd5fd407de4beca780a7 | 32,871 | cc | C++ | compiler/Passes/Lowerings.cc | KaanOzkan/sorbet | 9866ac9757a0ec75e4effe1e0fced0ada4246de7 | [
"Apache-2.0"
] | null | null | null | compiler/Passes/Lowerings.cc | KaanOzkan/sorbet | 9866ac9757a0ec75e4effe1e0fced0ada4246de7 | [
"Apache-2.0"
] | null | null | null | compiler/Passes/Lowerings.cc | KaanOzkan/sorbet | 9866ac9757a0ec75e4effe1e0fced0ada4246de7 | [
"Apache-2.0"
] | null | null | null | // These violate our poisons so have to happen first
#include "llvm/IR/DerivedTypes.h" // FunctionType
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "Passes.h"
#include "compiler/Core/OptimizerException.h"
#include "core/core.h"
#include <string>
using namespace std;
namespace sorbet::compiler {
namespace {
class IRIntrinsic {
public:
virtual vector<llvm::StringRef> implementedFunctionCall() const = 0;
// The contract you're expected to implement here is basically:
//
// - You're given an llvm::CallInst (which is a subclass of llvm::Value) that corresponds to the
// `call` instruction matching one of the names in implementedFunctionCall()
// - You can look at that instruction and all the rest of the `module` to do literally anything
// LLVM allows you to do.
// - You return a new `llvm::Value *` (like a cfg::Binding in Sorbet--contains the instruction and
// the variable to write that instruction into)
// - The framework will then update all reads from the variable of the `instr` assigns to to
// instead read from the variable of the `llvm::Value *` you just returned.
// - The frameowrk will delete `instr` from the module. This might unlock further optimization
// opportunities in later phases.
//
// You cannot (currently at least):
//
// - return `nullptr`
// - return `instr` unchanged
//
// We might change this (I don't know if this decision was intentional or accidental).
virtual llvm::Value *replaceCall(llvm::LLVMContext &lctx, llvm::Module &module, llvm::CallInst *instr) const = 0;
virtual ~IRIntrinsic() = default;
};
// TODO: add more from https://git.corp.stripe.com/stripe-internal/ruby/blob/48bf9833/include/ruby/ruby.h#L1962. Will
// need to modify core sorbet for it.
const vector<pair<llvm::StringRef, llvm::StringRef>> knownSymbolMapping = {
{"Array", "rb_cArray"},
{"BasicObject", "rb_cBasicObject"},
{"Class", "rb_cClass"},
{"Comparable", "rb_mComparable"},
{"Enumerable", "rb_mEnumerable"},
{"FalseClass", "rb_cFalseClass"},
{"Float", "rb_cFloat"},
{"Hash", "rb_cHash"},
{"Integer", "rb_cInteger"},
{"Kernel", "rb_mKernel"},
{"Method", "rb_cMethod"},
{"Module", "rb_cModule"},
{"NameError", "rb_eNameError"},
{"NilClass", "rb_cNilClass"},
{"NoMethodError", "rb_eNoMethodError"},
{"Numeric", "rb_cNumeric"},
{"Object", "rb_cObject"},
{"Proc", "rb_cProc"},
{"Range", "rb_cRange"},
{"Rational", "rb_cRational"},
{"Regexp", "rb_cRegexp"},
{"StandardError", "rb_eStandardError"},
{"String", "rb_cString"},
{"Struct", "rb_cStruct"},
{"Symbol", "rb_cSymbol"},
{"Thread", "rb_cThread"},
{"TrueClass", "rb_cTrueClass"},
};
class ClassAndModuleLoading : public IRIntrinsic {
public:
virtual vector<llvm::StringRef> implementedFunctionCall() const override {
return {"sorbet_i_getRubyClass", "sorbet_i_getRubyConstant"};
}
virtual llvm::Value *replaceCall(llvm::LLVMContext &lctx, llvm::Module &module,
llvm::CallInst *instr) const override {
auto elemPtr = llvm::dyn_cast<llvm::GEPOperator>(instr->getArgOperand(0));
if (elemPtr == nullptr) {
throw OptimizerException("Unexpected argument to intrinsic");
}
auto global = llvm::dyn_cast<llvm::GlobalVariable>(elemPtr->getOperand(0));
if (global == nullptr) {
throw OptimizerException("Unexpected argument to intrinsic");
}
auto initializer = llvm::dyn_cast<llvm::ConstantDataArray>(global->getInitializer());
if (initializer == nullptr) {
throw OptimizerException("Unexpected argument to intrinsic");
}
llvm::IRBuilder<> builder(instr);
auto symName = initializer->getAsCString();
auto tp = llvm::Type::getInt64Ty(lctx);
for (const auto &[rubySourceName, rubyCApiName] : knownSymbolMapping) {
if (symName == rubySourceName) {
auto &nm = rubyCApiName; // C++ bindings don't play well with captures
auto globalDeclaration = module.getOrInsertGlobal(rubyCApiName, tp, [&] {
auto isConstant = true;
llvm::Constant *initializer = nullptr;
auto ret = new llvm::GlobalVariable(module, tp, isConstant, llvm::GlobalVariable::ExternalLinkage,
initializer, nm);
return ret;
});
return builder.CreateLoad(globalDeclaration);
}
}
string str(symName);
ENFORCE(str.length() < 2 || (str[0] != ':'), "implementation assumes that strings dont start with ::");
auto loaderName = "const_load" + str;
auto guardEpochName = "guard_epoch_" + str;
auto guardedConstName = "guarded_const_" + str;
auto guardEpochDeclaration = module.getOrInsertGlobal(guardEpochName, tp, [&] {
auto isConstant = false;
auto ret = new llvm::GlobalVariable(module, tp, isConstant, llvm::GlobalVariable::LinkOnceAnyLinkage,
llvm::ConstantInt::get(tp, 0), guardEpochName);
return ret;
});
auto guardedConstDeclaration = module.getOrInsertGlobal(guardedConstName, tp, [&] {
auto isConstant = false;
auto ret = new llvm::GlobalVariable(module, tp, isConstant, llvm::GlobalVariable::LinkOnceAnyLinkage,
llvm::ConstantInt::get(tp, 0), guardedConstName);
return ret;
});
auto needTakeSlowPath =
builder.CreateICmpNE(builder.CreateLoad(guardEpochDeclaration),
builder.CreateCall(module.getFunction("sorbet_getConstantEpoch")), "needTakeSlowPath");
auto splitPoint = builder.CreateLoad(guardedConstDeclaration);
builder.CreateIntrinsic(
llvm::Intrinsic::IndependentIntrinsics::assume, {},
{builder.CreateICmpEQ(builder.CreateLoad(guardEpochDeclaration),
builder.CreateCall(module.getFunction("sorbet_getConstantEpoch")), "guardUpdated")}
);
auto slowPathTerm = llvm::SplitBlockAndInsertIfThen(needTakeSlowPath, splitPoint, false,
llvm::MDBuilder(lctx).createBranchWeights(1, 10000));
builder.SetInsertPoint(slowPathTerm);
auto recomputeFunName = "const_recompute_" + str;
auto recomputeFun = module.getFunction(recomputeFunName);
if (!recomputeFun) {
// generate something logically similar to
// VALUE const_load_FOO() {
// if (const_guard == constant_epoch()) {
// return guarded_const;
// } else {
// guardedConst = sorbet_getConstant("FOO");
// const_guard = constant_epoch();
// return guarded_const;
// }
//
// It's not exactly this as I'm doing some tunnings, more specifically, the "else" branch will be marked
// cold and shared across all modules
auto recomputeFunT = llvm::FunctionType::get(llvm::Type::getVoidTy(lctx), {}, false /*not varargs*/);
recomputeFun = llvm::Function::Create(recomputeFunT, llvm::Function::LinkOnceAnyLinkage,
llvm::Twine("const_recompute_") + str, module);
llvm::IRBuilder<> functionBuilder(lctx);
functionBuilder.SetInsertPoint(llvm::BasicBlock::Create(lctx, "", recomputeFun));
auto zero = llvm::ConstantInt::get(lctx, llvm::APInt(64, 0));
llvm::Constant *indicesString[] = {zero, zero};
functionBuilder.CreateStore(
functionBuilder.CreateCall(
module.getFunction("sorbet_getConstant"),
{llvm::ConstantExpr::getInBoundsGetElementPtr(global->getValueType(), global, indicesString),
llvm::ConstantInt::get(lctx, llvm::APInt(64, str.length()))}),
guardedConstDeclaration);
functionBuilder.CreateStore(functionBuilder.CreateCall(module.getFunction("sorbet_getConstantEpoch")),
guardEpochDeclaration);
functionBuilder.CreateRetVoid();
}
builder.CreateCall(recomputeFun);
return splitPoint;
}
} ClassAndModuleLoading;
class ObjIsKindOf : public IRIntrinsic {
llvm::Value *fallbackToVM(llvm::Module &module, llvm::CallInst *instr) const {
llvm::IRBuilder<> builder(instr);
return builder.CreateCall(module.getFunction("rb_obj_is_kind_of"),
{instr->getArgOperand(0), instr->getArgOperand(1)});
}
public:
virtual vector<llvm::StringRef> implementedFunctionCall() const override {
return {"sorbet_i_objIsKindOf"};
}
// Detects code that looks like this:
//
// %44 = load i64, i64* @rb_cNilClass, align 8, !dbg !14
// %45 = load i64, i64* @rb_cModule, align 8, !dbg !14
// %46 = call i64 @sorbet_i_objIsKindOf(i64 %44, i64 %45) #1, !dbg !14
//
// and returns an instruction that looks like this:
//
// %47 = call i64 @sorbet_rubyTrue()
//
// Then the LowerIntrinsicsPass harness below will update all reads from %46 to read from %47
// instead and then delete the write to %46 entirely (which might unlock other optimizations).
virtual llvm::Value *replaceCall(llvm::LLVMContext &lctx, llvm::Module &module,
llvm::CallInst *instr) const override {
auto valueLoad = llvm::dyn_cast<llvm::LoadInst>(instr->getArgOperand(0));
auto kindLoad = llvm::dyn_cast<llvm::LoadInst>(instr->getArgOperand(1));
if (valueLoad == nullptr || kindLoad == nullptr) {
return this->fallbackToVM(module, instr);
}
auto value = llvm::dyn_cast<llvm::GlobalVariable>(valueLoad->getPointerOperand());
auto kind = llvm::dyn_cast<llvm::GlobalVariable>(kindLoad->getPointerOperand());
if (value == nullptr || kind == nullptr) {
return this->fallbackToVM(module, instr);
}
llvm::IRBuilder<> builder(instr);
auto kindName = kind->getName();
if (kindName != "rb_cModule") {
return this->fallbackToVM(module, instr);
}
auto valueName = value->getName();
for (const auto &[_rubySourceName, rubyCApiName] : knownSymbolMapping) {
if (valueName == rubyCApiName) {
// We could use Payload::rubyTrue, but it takes a CompilerState which we don't have.
auto fn = module.getFunction("sorbet_rubyTrue");
ENFORCE(fn != nullptr);
return builder.CreateCall(fn, {}, "trueValueRaw");
}
}
return this->fallbackToVM(module, instr);
}
} ObjIsKindOf;
class TypeTest : public IRIntrinsic {
static const vector<pair<llvm::StringRef, llvm::StringRef>> intrinsicMap;
public:
virtual vector<llvm::StringRef> implementedFunctionCall() const override {
vector<llvm::StringRef> methods;
for (auto &[intrinsic, realMethod] : intrinsicMap) {
methods.emplace_back(intrinsic);
}
return methods;
}
virtual llvm::Value *replaceCall(llvm::LLVMContext &lctx, llvm::Module &module,
llvm::CallInst *instr) const override {
llvm::IRBuilder<> builder(instr);
auto *arg = instr->getArgOperand(0);
auto name = instr->getCalledFunction()->getName();
auto realMethod = absl::c_find_if(intrinsicMap, [&name](const auto &pair) { return pair.first == name; });
ENFORCE(realMethod != intrinsicMap.end());
return builder.CreateCall(module.getFunction(realMethod->second), {arg});
}
} TypeTest;
const vector<pair<llvm::StringRef, llvm::StringRef>> TypeTest::intrinsicMap{
{"sorbet_i_isa_Array", "sorbet_isa_Array"},
{"sorbet_i_isa_Integer", "sorbet_isa_Integer"},
{"sorbet_i_isa_TrueClass", "sorbet_isa_TrueClass"},
{"sorbet_i_isa_FalseClass", "sorbet_isa_FalseClass"},
{"sorbet_i_isa_NilClass", "sorbet_isa_NilClass"},
{"sorbet_i_isa_Symbol", "sorbet_isa_Symbol"},
{"sorbet_i_isa_Float", "sorbet_isa_Float"},
{"sorbet_i_isa_Untyped", "sorbet_isa_Untyped"},
{"sorbet_i_isa_Hash", "sorbet_isa_Hash"},
{"sorbet_i_isa_Array", "sorbet_isa_Array"},
{"sorbet_i_isa_Regexp", "sorbet_isa_Regexp"},
{"sorbet_i_isa_String", "sorbet_isa_String"},
{"sorbet_i_isa_Proc", "sorbet_isa_Proc"},
{"sorbet_i_isa_Thread", "sorbet_isa_Thread"},
{"sorbet_i_isa_RootSingleton", "sorbet_isa_RootSingleton"},
};
class SorbetSend : public IRIntrinsic {
public:
virtual vector<llvm::StringRef> implementedFunctionCall() const override {
return {"sorbet_i_send"};
}
// Original ruby code:
// puts "a"
//
// Detects code that looks like this:
//
// %3 = call ... @sorbet_i_send(%struct.FunctionInlineCache* @ic_puts,
// i1 false,
// i64 (i64, i64, i32, i64*, i64)* null,
// i32 0, i32 0,
// %struct.rb_control_frame_struct* %cfp,
// i64 %selfRaw,
// i64 %rubyStr_a
// ), !dbg !121
//
// and replaces it with:
//
// (disabling clang-format here because it will otherwise remove all the newlines)
// clang-format off
// (1) %18 = getelementptr inbounds %struct.rb_control_frame_struct, %struct.rb_control_frame_struct* %11, i64 0, i32 1, !dbg !8
// (2) %19 = load i64*, i64** %18, align 8, !dbg !8
// (3) store i64 %8, i64* %19, align 8, !dbg !8, !tbaa !4
// (4) %20 = getelementptr inbounds i64, i64* %19, i64 1, !dbg !8
// (5) store i64 %rubyStr_a.i, i64* %20, align 8, !dbg !8, !tbaa !4
// (6) %21 = getelementptr inbounds i64, i64* %20, i64 1, !dbg !8
// (7) store i64* %21, i64** %18, align 8, !dbg !8
// (8) %send = call i64 @sorbet_callFuncWithCache(%struct.FunctionInlineCache* @ic_puts, i64 0), !dbg !8
// clang-format on
//
// Lines 1 & 2 correspond to the sorbet_get_sp call, and the sp load from spPtr
// Lines 3 & 4 correspond to the sorbet_pushValueStack call for self, while 5 & 6 correspond to the
// sorbet_pushValueStack call for "a".
// Line 7 corresponds to the store to spPtr.
// Line 8 corresponds to the sorbet_callFuncWithCache call.
virtual llvm::Value *replaceCall(llvm::LLVMContext &lctx, llvm::Module &module,
llvm::CallInst *instr) const override {
// Make sure cache, blk, closure, cfp and self are passed in.
ENFORCE(instr->arg_size() >= 5);
llvm::IRBuilder<> builder(instr);
auto *cache = instr->getArgOperand(0);
auto *blk = instr->getArgOperand(2);
auto *blkMinArgs = instr->getArgOperand(3);
auto *blkMaxArgs = instr->getArgOperand(4);
auto *closure = instr->getArgOperand(5);
auto *cfp = instr->getArgOperand(6);
auto *spPtr = builder.CreateCall(module.getFunction("sorbet_get_sp"), {cfp});
auto spPtrType = llvm::dyn_cast<llvm::PointerType>(spPtr->getType());
llvm::Value *sp = builder.CreateLoad(spPtrType->getElementType(), spPtr);
for (auto iter = std::next(instr->arg_begin(), 7); iter < instr->arg_end(); ++iter) {
sp = builder.CreateCall(module.getFunction("sorbet_pushValueStack"), {sp, iter->get()});
}
builder.CreateStore(sp, spPtr);
if (llvm::isa<llvm::ConstantPointerNull>(blk)) {
auto *blockHandler =
builder.CreateCall(module.getFunction("sorbet_vmBlockHandlerNone"), {}, "VM_BLOCK_HANDLER_NONE");
return builder.CreateCall(module.getFunction("sorbet_callFuncWithCache"), {cache, blockHandler}, "send");
} else {
auto *blkUsesBreak = llvm::dyn_cast<llvm::ConstantInt>(instr->getArgOperand(1));
ENFORCE(blkUsesBreak);
auto *callImpl = blkUsesBreak->equalsInt(1) ? module.getFunction("sorbet_callFuncBlockWithCache")
: module.getFunction("sorbet_callFuncBlockWithCache_noBreak");
return builder.CreateCall(callImpl, {cache, blk, blkMinArgs, blkMaxArgs, closure}, "sendWithBlock");
}
}
} SorbetSend;
vector<IRIntrinsic *> getIRIntrinsics() {
vector<IRIntrinsic *> irIntrinsics{
&ClassAndModuleLoading,
&ObjIsKindOf,
&TypeTest,
&SorbetSend,
};
return irIntrinsics;
}
static const vector<IRIntrinsic *> irIntrinsics = getIRIntrinsics();
class LowerIntrinsicsPass : public llvm::ModulePass {
public:
// The contents of this variable don't matter; LLVM just uses the pointer address of it as an ID.
static char ID;
LowerIntrinsicsPass() : llvm::ModulePass(ID){};
struct CallInstVisitor : public llvm::InstVisitor<CallInstVisitor> {
vector<llvm::CallInst *> result;
UnorderedSet<llvm::Function *> lookups;
void visitCallInst(llvm::CallInst &ci) {
auto maybeFunc = ci.getCalledFunction();
if (maybeFunc == nullptr) {
return;
}
auto fnd = lookups.find(maybeFunc);
if (fnd == lookups.end()) {
return;
}
// We're taking the address of a llvm::CallInst & here to avoid having to deal with a
// vector of references.
//
// This lives at least long enough (owned by the llvm::Module) to let the visitor finish
// and also run the replaceCall callback.
//
// An alternative here would be to run the replaceCall callback and do the replacements
// right here, but it's probably not great to have a visitor that simultaneously mutates
// the structure it's visiting, which is why we accumulate a to-do list of results.
result.emplace_back(&ci);
}
};
virtual bool runOnModule(llvm::Module &mod) override {
vector<llvm::Function *> functionsToRemove;
for (auto &fn : mod.functions()) {
if (fn.getName().startswith("sorbet_exists_to_keep_alive_")) {
functionsToRemove.emplace_back(&fn);
}
}
for (auto *fn : functionsToRemove) {
fn->eraseFromParent();
}
// We run each lowering pass in sequence. Each does a full visit on the module.
// We don't have that many lowering passes right now, so this cost is small.
//
// When we get around to optimizing compile-time performance in the future, this might need to change.
// At the very least, it should be easy enough to schedule `ClassAndModuleLoading` and `ObjIsKindOf`
// to run in sequence **at each call site**, but still in one `llvm::ModulePass`.
for (const auto *intrinsic : irIntrinsics) {
CallInstVisitor visitor;
for (const auto &name : intrinsic->implementedFunctionCall()) {
if (auto fun = mod.getFunction(name)) {
visitor.lookups.insert(fun);
}
}
visitor.visit(mod);
for (const auto &callInst : visitor.result) {
auto newRes = intrinsic->replaceCall(mod.getContext(), mod, callInst);
callInst->replaceAllUsesWith(newRes);
callInst->eraseFromParent();
}
}
return true;
};
virtual ~LowerIntrinsicsPass() = default;
} LowerInrinsicsPass;
char LowerIntrinsicsPass::ID = 0;
static llvm::RegisterPass<LowerIntrinsicsPass> X("lowerSorbetIntrinsics", "Lower Sorbet Intrinsics",
false, // Only looks at CFG
false // Analysis Pass
);
// This pass is kind of a hack. There are certain calls that we eagerly generate
// because it makes code generation simpler. But after code generation, those
// calls may not actually be used and we know -- but LLVM doesn't -- that the
// calls are safe to delete. There's not an LLVM attribute to describe this sort
// of behavior, so we have to write our own pass.
class DeleteUnusedSorbetIntrinsicsPass : public llvm::ModulePass {
public:
static char ID;
DeleteUnusedSorbetIntrinsicsPass() : llvm::ModulePass(ID) {}
struct CallInstVisitor : public llvm::InstVisitor<CallInstVisitor> {
vector<llvm::CallInst *> callsToDelete;
UnorderedSet<llvm::Function *> functionsToDelete;
CallInstVisitor(llvm::Module &m) {
auto f = m.getFunction("sorbet_getMethodBlockAsProc");
ENFORCE(f);
functionsToDelete.insert(f);
}
void visitCallInst(llvm::CallInst &ci) {
auto maybeFunc = ci.getCalledFunction();
if (!maybeFunc) {
return;
}
if (!functionsToDelete.contains(maybeFunc)) {
return;
}
if (!ci.use_empty()) {
return;
}
callsToDelete.emplace_back(&ci);
}
};
virtual bool runOnModule(llvm::Module &mod) override {
CallInstVisitor visitor(mod);
ENFORCE(!visitor.functionsToDelete.empty());
visitor.visit(mod);
if (visitor.callsToDelete.empty()) {
return false;
}
for (auto inst : visitor.callsToDelete) {
inst->eraseFromParent();
}
return true;
}
};
char DeleteUnusedSorbetIntrinsicsPass::ID = 0;
static llvm::RegisterPass<DeleteUnusedSorbetIntrinsicsPass> Y("deleteUnusuedSorbetIntrinsics",
"Delete Unused Sorbet Intrinsics",
false, // Only looks at CFG
false // Analysis Pass
);
// When through optimization llvm is able to prune out sends that go through the VM, the inline cache that they
// allocated will still be initialized during the module's Init function, and the global will persist. This pass detects
// this case by finding globals whose type is `struct FunctionInlineCache`, and that only have a single user which is a
// call to the `sorbet_setupFunctionInlineCache` function.
class DeleteUnusedInlineCachesPass : public llvm::ModulePass {
public:
static char ID;
DeleteUnusedInlineCachesPass() : llvm::ModulePass(ID) {}
virtual bool runOnModule(llvm::Module &mod) override {
auto *setupInlineCacheFun = mod.getFunction("sorbet_setupFunctionInlineCache");
if (setupInlineCacheFun == nullptr) {
// Unlikely, but this would mean that there were no uses of the function, and that it was removed. If this
// function is missing, there would be no inline caches allocated in this module.
return false;
}
auto *inlineCacheType = llvm::StructType::getTypeByName(mod.getContext(), "struct.FunctionInlineCache");
ENFORCE(inlineCacheType != nullptr);
std::vector<llvm::Instruction *> toRemove;
for (auto &global : mod.globals()) {
if (global.getValueType() != inlineCacheType) {
continue;
}
int numUses = std::distance(global.user_begin(), global.user_end());
if (numUses != 1) {
continue;
}
auto *inst = llvm::dyn_cast<llvm::CallInst>(global.user_back());
if (inst == nullptr || inst->getCalledFunction() != setupInlineCacheFun) {
continue;
}
toRemove.emplace_back(inst);
}
if (toRemove.empty()) {
return false;
}
for (auto *inst : toRemove) {
inst->eraseFromParent();
}
return true;
}
};
char DeleteUnusedInlineCachesPass::ID = 0;
static llvm::RegisterPass<DeleteUnusedInlineCachesPass> Z("deleteUnusuedInlineCaches", "Delete Unused Inline Caches",
false, // Only looks at CFG
false // Analysis Pass
);
class RemoveUnnecessaryHashDupsPass : public llvm::ModulePass {
public:
static char ID;
RemoveUnnecessaryHashDupsPass() : llvm::ModulePass(ID) {}
bool detectLiteralHash(llvm::Module &mod, llvm::Function *sorbetGlobalConstDupHashFn, llvm::CallInst *toHashCall) {
// Checks that the argument to rb_to_hash_type is the result of a sorbet_globalConstDupHash,
// and that it only has one user.
// This is the case for code written as follows:
// args = { a: 1 }
// foo(**args)
ENFORCE(toHashCall->getNumArgOperands() == 1);
auto *constDupCall = llvm::dyn_cast<llvm::CallInst>(toHashCall->getOperand(0));
if (constDupCall == nullptr || constDupCall->getCalledFunction() != sorbetGlobalConstDupHashFn ||
constDupCall->getParent() != toHashCall->getParent() || !constDupCall->hasOneUser()) {
return false;
}
return true;
}
bool detectPassThroughCase(llvm::Module &mod, llvm::Function *rbHashDupFn, llvm::Function *rbHashNewFn,
llvm::CallInst *toHashCall) {
// Checks that the argument to rb_to_hash_type is the result of a phi,
// where one branch is a call to rb_hash_new, and the other is a call to
// rb_hash_dup on the result of a load from the arg array.
// This is the case for code written as follows:
// def foo(**args)
// bar(**args)
// end
auto *phiNode = llvm::dyn_cast<llvm::PHINode>(toHashCall->getOperand(0));
if (phiNode == nullptr || phiNode->getParent() != toHashCall->getParent() || !phiNode->hasOneUser()) {
return false;
}
for (auto &u : phiNode->incoming_values()) {
auto *phiArg = llvm::dyn_cast<llvm::CallInst>(u);
if (phiArg == nullptr) {
return false;
}
// If we see a Hash.new, we can skip processing this branch of the phi, since there's nothing else to follow
// backwards.
if (phiArg->getCalledFunction() == rbHashNewFn) {
continue;
}
// If we see a function other than Hash.new or rb_hash_dup, we should abort, and not do anything,
// because the expected phi node only has calls to those 2.
if (phiArg->getCalledFunction() != rbHashDupFn) {
return false;
}
ENFORCE(phiArg->getNumArgOperands() == 1);
auto *loadInst = llvm::dyn_cast<llvm::LoadInst>(phiArg->getOperand(0));
if (loadInst == nullptr) {
return false;
}
auto *gepInst = llvm::dyn_cast<llvm::GetElementPtrInst>(loadInst->getOperand(0));
if (gepInst == nullptr) {
return false;
}
// Check that the operand to the GEP is the 2nd arg to the function.
// gepInst->getParent() returns the basic block the GEP is part of,
// and ->getParent() of that returns the function.
if (gepInst->getOperand(0) != gepInst->getParent()->getParent()->getArg(1)) {
return false;
}
}
return true;
}
bool runOnModule(llvm::Module &mod) override {
bool modifiedCode = false;
auto *rbHashDupFn = mod.getFunction("rb_hash_dup");
auto *rbHashNewFn = mod.getFunction("rb_hash_new");
auto *rbToHashTypeFn = mod.getFunction("rb_to_hash_type");
auto *sorbetGlobalConstDupHashFn = mod.getFunction("sorbet_globalConstDupHash");
auto *sorbetSendFn = mod.getFunction("sorbet_i_send");
if (rbHashDupFn == nullptr || rbToHashTypeFn == nullptr || sorbetSendFn == nullptr) {
return false;
}
for (auto &function : mod) {
for (auto &block : function) {
for (auto insn_iter = block.begin(); insn_iter != block.end();) {
llvm::Instruction *insn = &*insn_iter;
// This increment needs to happen outside of the loop header, because we are
// potentially deleting this instruction in this loop body, so incrementing at
// the end of the loop body could fail.
insn_iter++;
// Look for the following instructions:
// %2 = call i64 @rb_to_hash_type(i64 %1)
// %3 = call i64 @rb_hash_dup(i64 %2)
// And ensure that both %2 and %3 have exactly one user, and are in the same basic block.
auto *hashDupCall = llvm::dyn_cast<llvm::CallInst>(insn);
if (hashDupCall == nullptr || hashDupCall->getCalledFunction() != rbHashDupFn ||
!hashDupCall->hasOneUser()) {
continue;
}
ENFORCE(hashDupCall->getNumArgOperands() == 1);
auto *toHashCall = llvm::dyn_cast<llvm::CallInst>(hashDupCall->getOperand(0));
if (toHashCall == nullptr || toHashCall->getCalledFunction() != rbToHashTypeFn ||
toHashCall->getParent() != hashDupCall->getParent() || !toHashCall->hasOneUser()) {
continue;
}
// Get the use for the rb_hash_dup value, and ensure that it is a send, in the same basic block.
auto use = hashDupCall->use_begin();
llvm::User *user = use->getUser();
auto *sendCall = llvm::dyn_cast<llvm::CallInst>(user);
if (sendCall == nullptr || sendCall->getCalledFunction() != sorbetSendFn ||
sendCall->getParent() != hashDupCall->getParent()) {
continue;
}
// Check that the rb_hash_dup is the last arg to send,
// The last operand is the definition,
// which means that getNumOperands - getOperandNo == 2
if (user->getNumOperands() - use->getOperandNo() != 2) {
continue;
}
bool shouldRemoveDup = false;
if (sorbetGlobalConstDupHashFn && detectLiteralHash(mod, sorbetGlobalConstDupHashFn, toHashCall)) {
shouldRemoveDup = true;
}
if (rbHashNewFn && detectPassThroughCase(mod, rbHashDupFn, rbHashNewFn, toHashCall)) {
shouldRemoveDup = true;
}
if (!shouldRemoveDup) {
continue;
}
user->setOperand(use->getOperandNo(), toHashCall);
hashDupCall->eraseFromParent();
modifiedCode = true;
}
}
}
return modifiedCode;
}
};
char RemoveUnnecessaryHashDupsPass::ID = 0;
static llvm::RegisterPass<RemoveUnnecessaryHashDupsPass> AA("removeUnnecessaryHashDupsPass",
"Remove Unnecessary Hash Dups",
false, // Only looks at CFG
false // Analysis Pass
);
} // namespace
const std::vector<llvm::ModulePass *> Passes::standardLowerings() {
// LLVM pass manager is going to destuct them, so we need to allocate them every time
return {new LowerIntrinsicsPass()};
};
llvm::ModulePass *Passes::createDeleteUnusedSorbetIntrinsticsPass() {
return new DeleteUnusedSorbetIntrinsicsPass();
}
llvm::ModulePass *Passes::createDeleteUnusedInlineCachesPass() {
return new DeleteUnusedInlineCachesPass();
}
llvm::ModulePass *Passes::createRemoveUnnecessaryHashDupsPass() {
return new RemoveUnnecessaryHashDupsPass();
}
} // namespace sorbet::compiler
| 43.024869 | 134 | 0.591038 | [
"object",
"vector"
] |
4f9539db12e73c1d37200a7564f1cca572df44c7 | 1,829 | cpp | C++ | benchmarks/bench_sort.cpp | timsort/cpp-TimSort | 552d9e587a7a38b28519be9cc100d5ce7854c670 | [
"MIT"
] | 124 | 2019-09-17T12:18:21.000Z | 2022-03-30T19:39:14.000Z | benchmarks/bench_sort.cpp | timsort/cpp-TimSort | 552d9e587a7a38b28519be9cc100d5ce7854c670 | [
"MIT"
] | 15 | 2019-09-17T11:36:02.000Z | 2022-01-30T13:25:09.000Z | benchmarks/bench_sort.cpp | timsort/cpp-TimSort | 552d9e587a7a38b28519be9cc100d5ce7854c670 | [
"MIT"
] | 17 | 2019-10-06T15:27:16.000Z | 2022-03-29T08:57:20.000Z | /*
* Copyright (c) 2011 Fuji, Goro (gfx) <gfuji@cpan.org>.
* Copyright (c) 2019 Morwenn.
*
* SPDX-License-Identifier: MIT
*/
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <vector>
#include <gfx/timsort.hpp>
#include "benchmarker.hpp"
template <typename value_t>
struct Bench {
void operator()(const std::vector<value_t> &a) const {
{
std::vector<value_t> b(a);
std::clock_t start = std::clock();
for (int i = 0; i < 100; ++i) {
std::copy(a.begin(), a.end(), b.begin());
std::sort(b.begin(), b.end());
}
std::clock_t stop = std::clock();
std::cerr << "std::sort " << (double(stop - start) / CLOCKS_PER_SEC) << std::endl;
}
{
std::vector<value_t> b(a);
std::clock_t start = std::clock();
for (int i = 0; i < 100; ++i) {
std::copy(a.begin(), a.end(), b.begin());
std::stable_sort(b.begin(), b.end());
}
std::clock_t stop = clock();
std::cerr << "std::stable_sort " << (double(stop - start) / CLOCKS_PER_SEC) << std::endl;
}
{
std::vector<value_t> b(a);
std::clock_t start = std::clock();
for (int i = 0; i < 100; ++i) {
std::copy(a.begin(), a.end(), b.begin());
gfx::timsort(b.begin(), b.end());
}
std::clock_t stop = std::clock();
std::cerr << "timsort " << (double(stop - start) / CLOCKS_PER_SEC) << std::endl;
}
}
};
int main(int argc, const char *argv[]) {
const int size = argc > 1 ? std::atoi(argv[1]) : 100 * 1000;
Benchmarker<Bench> benchmarker(size);
benchmarker.run();
}
| 28.578125 | 101 | 0.484418 | [
"vector"
] |
4f9563a5724b1b0b0b236d744cd97ad9a1e56033 | 652 | hpp | C++ | src/tests/ie_test_utils/unit_test_utils/mocks/cpp_interfaces/interface/mock_ivariable_state_internal.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/tests/ie_test_utils/unit_test_utils/mocks/cpp_interfaces/interface/mock_ivariable_state_internal.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/tests/ie_test_utils/unit_test_utils/mocks/cpp_interfaces/interface/mock_ivariable_state_internal.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"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
//
#pragma once
#include <gmock/gmock.h>
#include <string>
#include <vector>
#include <cpp_interfaces/interface/ie_ivariable_state_internal.hpp>
class MockIVariableStateInternal : public InferenceEngine::IVariableStateInternal {
public:
MockIVariableStateInternal() : InferenceEngine::IVariableStateInternal{"MockIVariableStateInternal"} {}
MOCK_CONST_METHOD0(GetName, std::string());
MOCK_METHOD0(Reset, void());
MOCK_METHOD1(SetState, void(const InferenceEngine::Blob::Ptr&));
MOCK_CONST_METHOD0(GetState, InferenceEngine::Blob::CPtr());
};
| 29.636364 | 107 | 0.768405 | [
"vector"
] |
4f95d00ec3894665d73617e8de3e53d2e44b0a79 | 23,326 | cpp | C++ | model/Task_attributes.cpp | ProcessMaker/pmio-sdk-cpprest | 4c8408571837995dceebbb119454b81cd2dff995 | [
"Apache-2.0"
] | null | null | null | model/Task_attributes.cpp | ProcessMaker/pmio-sdk-cpprest | 4c8408571837995dceebbb119454b81cd2dff995 | [
"Apache-2.0"
] | null | null | null | model/Task_attributes.cpp | ProcessMaker/pmio-sdk-cpprest | 4c8408571837995dceebbb119454b81cd2dff995 | [
"Apache-2.0"
] | 2 | 2017-08-06T12:56:32.000Z | 2018-09-06T05:09:47.000Z | /**
* ProcessMaker API
* This ProcessMaker I/O API provides access to a BPMN 2.0 compliant workflow engine api that is designed to be used as a microservice to support enterprise cloud applications. The current Alpha 1.0 version supports most of the descriptive class of the BPMN 2.0 specification.
*
* OpenAPI spec version: 1.0.0
* Contact: support@processmaker.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* 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 "Task_attributes.h"
namespace io {
namespace processmaker {
namespace pmio {
namespace model {
Task_attributes::Task_attributes()
{
m_Name = U("");
m_Description = U("");
m_DescriptionIsSet = false;
m_Process_id = U("");
m_Type = U("");
m_Assign_type = U("");
m_Priority_variable = U("");
m_Priority_variableIsSet = false;
m_Assign_variable = U("");
m_Assign_variableIsSet = false;
m_Group_variable = U("");
m_Group_variableIsSet = false;
m_Mi_instance_variable = U("");
m_Mi_instance_variableIsSet = false;
m_Mi_complete_variable = U("");
m_Mi_complete_variableIsSet = false;
m_Transfer_fly = false;
m_Can_upload = false;
m_View_upload = false;
m_View_additional_documentation = false;
m_Start = false;
m_Send_last_email = false;
m_Derivation_screen_tpl = U("");
m_Derivation_screen_tplIsSet = false;
m_Selfservice_timeout = nullptr;
m_Selfservice_time = U("");
m_Selfservice_timeIsSet = false;
m_Selfservice_time_unit = U("");
m_Selfservice_time_unitIsSet = false;
m_Selfservice_execution = U("");
m_Selfservice_executionIsSet = false;
m_Last_assigned_user_id = U("");
m_Last_assigned_user_idIsSet = false;
m_Script = U("");
m_ScriptIsSet = false;
m_Created_at = U("");
m_Created_atIsSet = false;
m_Updated_at = U("");
m_Updated_atIsSet = false;
}
Task_attributes::~Task_attributes()
{
}
void Task_attributes::validate()
{
// TODO: implement validation
}
web::json::value Task_attributes::toJson() const
{
web::json::value val = web::json::value::object();
val[U("name")] = ModelBase::toJson(m_Name);
if(m_DescriptionIsSet)
{
val[U("description")] = ModelBase::toJson(m_Description);
}
val[U("process_id")] = ModelBase::toJson(m_Process_id);
val[U("type")] = ModelBase::toJson(m_Type);
val[U("assign_type")] = ModelBase::toJson(m_Assign_type);
if(m_Priority_variableIsSet)
{
val[U("priority_variable")] = ModelBase::toJson(m_Priority_variable);
}
if(m_Assign_variableIsSet)
{
val[U("assign_variable")] = ModelBase::toJson(m_Assign_variable);
}
if(m_Group_variableIsSet)
{
val[U("group_variable")] = ModelBase::toJson(m_Group_variable);
}
if(m_Mi_instance_variableIsSet)
{
val[U("mi_instance_variable")] = ModelBase::toJson(m_Mi_instance_variable);
}
if(m_Mi_complete_variableIsSet)
{
val[U("mi_complete_variable")] = ModelBase::toJson(m_Mi_complete_variable);
}
val[U("transfer_fly")] = ModelBase::toJson(m_Transfer_fly);
val[U("can_upload")] = ModelBase::toJson(m_Can_upload);
val[U("view_upload")] = ModelBase::toJson(m_View_upload);
val[U("view_additional_documentation")] = ModelBase::toJson(m_View_additional_documentation);
val[U("start")] = ModelBase::toJson(m_Start);
val[U("send_last_email")] = ModelBase::toJson(m_Send_last_email);
if(m_Derivation_screen_tplIsSet)
{
val[U("derivation_screen_tpl")] = ModelBase::toJson(m_Derivation_screen_tpl);
}
val[U("selfservice_timeout")] = ModelBase::toJson(m_Selfservice_timeout);
if(m_Selfservice_timeIsSet)
{
val[U("selfservice_time")] = ModelBase::toJson(m_Selfservice_time);
}
if(m_Selfservice_time_unitIsSet)
{
val[U("selfservice_time_unit")] = ModelBase::toJson(m_Selfservice_time_unit);
}
if(m_Selfservice_executionIsSet)
{
val[U("selfservice_execution")] = ModelBase::toJson(m_Selfservice_execution);
}
if(m_Last_assigned_user_idIsSet)
{
val[U("last_assigned_user_id")] = ModelBase::toJson(m_Last_assigned_user_id);
}
if(m_ScriptIsSet)
{
val[U("script")] = ModelBase::toJson(m_Script);
}
if(m_Created_atIsSet)
{
val[U("created_at")] = ModelBase::toJson(m_Created_at);
}
if(m_Updated_atIsSet)
{
val[U("updated_at")] = ModelBase::toJson(m_Updated_at);
}
return val;
}
void Task_attributes::fromJson(web::json::value& val)
{
setName(ModelBase::stringFromJson(val[U("name")]));
if(val.has_field(U("description")))
{
setDescription(ModelBase::stringFromJson(val[U("description")]));
}
setProcessId(ModelBase::stringFromJson(val[U("process_id")]));
setType(ModelBase::stringFromJson(val[U("type")]));
setAssignType(ModelBase::stringFromJson(val[U("assign_type")]));
if(val.has_field(U("priority_variable")))
{
setPriorityVariable(ModelBase::stringFromJson(val[U("priority_variable")]));
}
if(val.has_field(U("assign_variable")))
{
setAssignVariable(ModelBase::stringFromJson(val[U("assign_variable")]));
}
if(val.has_field(U("group_variable")))
{
setGroupVariable(ModelBase::stringFromJson(val[U("group_variable")]));
}
if(val.has_field(U("mi_instance_variable")))
{
setMiInstanceVariable(ModelBase::stringFromJson(val[U("mi_instance_variable")]));
}
if(val.has_field(U("mi_complete_variable")))
{
setMiCompleteVariable(ModelBase::stringFromJson(val[U("mi_complete_variable")]));
}
setTransferFly(ModelBase::boolFromJson(val[U("transfer_fly")]));
setCanUpload(ModelBase::boolFromJson(val[U("can_upload")]));
setViewUpload(ModelBase::boolFromJson(val[U("view_upload")]));
setViewAdditionalDocumentation(ModelBase::boolFromJson(val[U("view_additional_documentation")]));
setStart(ModelBase::boolFromJson(val[U("start")]));
setSendLastEmail(ModelBase::boolFromJson(val[U("send_last_email")]));
if(val.has_field(U("derivation_screen_tpl")))
{
setDerivationScreenTpl(ModelBase::stringFromJson(val[U("derivation_screen_tpl")]));
}
setSelfserviceTimeout(ModelBase::int32_tFromJson(val[U("selfservice_timeout")]));
if(val.has_field(U("selfservice_time")))
{
setSelfserviceTime(ModelBase::stringFromJson(val[U("selfservice_time")]));
}
if(val.has_field(U("selfservice_time_unit")))
{
setSelfserviceTimeUnit(ModelBase::stringFromJson(val[U("selfservice_time_unit")]));
}
if(val.has_field(U("selfservice_execution")))
{
setSelfserviceExecution(ModelBase::stringFromJson(val[U("selfservice_execution")]));
}
if(val.has_field(U("last_assigned_user_id")))
{
setLastAssignedUserId(ModelBase::stringFromJson(val[U("last_assigned_user_id")]));
}
if(val.has_field(U("script")))
{
setScript(ModelBase::stringFromJson(val[U("script")]));
}
if(val.has_field(U("created_at")))
{
setCreatedAt(ModelBase::stringFromJson(val[U("created_at")]));
}
if(val.has_field(U("updated_at")))
{
setUpdatedAt(ModelBase::stringFromJson(val[U("updated_at")]));
}
}
void Task_attributes::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name));
if(m_DescriptionIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("description"), m_Description));
}
multipart->add(ModelBase::toHttpContent(namePrefix + U("process_id"), m_Process_id));
multipart->add(ModelBase::toHttpContent(namePrefix + U("type"), m_Type));
multipart->add(ModelBase::toHttpContent(namePrefix + U("assign_type"), m_Assign_type));
if(m_Priority_variableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("priority_variable"), m_Priority_variable));
}
if(m_Assign_variableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("assign_variable"), m_Assign_variable));
}
if(m_Group_variableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("group_variable"), m_Group_variable));
}
if(m_Mi_instance_variableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("mi_instance_variable"), m_Mi_instance_variable));
}
if(m_Mi_complete_variableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("mi_complete_variable"), m_Mi_complete_variable));
}
multipart->add(ModelBase::toHttpContent(namePrefix + U("transfer_fly"), m_Transfer_fly));
multipart->add(ModelBase::toHttpContent(namePrefix + U("can_upload"), m_Can_upload));
multipart->add(ModelBase::toHttpContent(namePrefix + U("view_upload"), m_View_upload));
multipart->add(ModelBase::toHttpContent(namePrefix + U("view_additional_documentation"), m_View_additional_documentation));
multipart->add(ModelBase::toHttpContent(namePrefix + U("start"), m_Start));
multipart->add(ModelBase::toHttpContent(namePrefix + U("send_last_email"), m_Send_last_email));
if(m_Derivation_screen_tplIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("derivation_screen_tpl"), m_Derivation_screen_tpl));
}
multipart->add(ModelBase::toHttpContent(namePrefix + U("selfservice_timeout"), m_Selfservice_timeout));
if(m_Selfservice_timeIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("selfservice_time"), m_Selfservice_time));
}
if(m_Selfservice_time_unitIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("selfservice_time_unit"), m_Selfservice_time_unit));
}
if(m_Selfservice_executionIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("selfservice_execution"), m_Selfservice_execution));
}
if(m_Last_assigned_user_idIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("last_assigned_user_id"), m_Last_assigned_user_id));
}
if(m_ScriptIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("script"), m_Script));
}
if(m_Created_atIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("created_at"), m_Created_at));
}
if(m_Updated_atIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("updated_at"), m_Updated_at));
}
}
void Task_attributes::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name"))));
if(multipart->hasContent(U("description")))
{
setDescription(ModelBase::stringFromHttpContent(multipart->getContent(U("description"))));
}
setProcessId(ModelBase::stringFromHttpContent(multipart->getContent(U("process_id"))));
setType(ModelBase::stringFromHttpContent(multipart->getContent(U("type"))));
setAssignType(ModelBase::stringFromHttpContent(multipart->getContent(U("assign_type"))));
if(multipart->hasContent(U("priority_variable")))
{
setPriorityVariable(ModelBase::stringFromHttpContent(multipart->getContent(U("priority_variable"))));
}
if(multipart->hasContent(U("assign_variable")))
{
setAssignVariable(ModelBase::stringFromHttpContent(multipart->getContent(U("assign_variable"))));
}
if(multipart->hasContent(U("group_variable")))
{
setGroupVariable(ModelBase::stringFromHttpContent(multipart->getContent(U("group_variable"))));
}
if(multipart->hasContent(U("mi_instance_variable")))
{
setMiInstanceVariable(ModelBase::stringFromHttpContent(multipart->getContent(U("mi_instance_variable"))));
}
if(multipart->hasContent(U("mi_complete_variable")))
{
setMiCompleteVariable(ModelBase::stringFromHttpContent(multipart->getContent(U("mi_complete_variable"))));
}
setTransferFly(ModelBase::boolFromHttpContent(multipart->getContent(U("transfer_fly"))));
setCanUpload(ModelBase::boolFromHttpContent(multipart->getContent(U("can_upload"))));
setViewUpload(ModelBase::boolFromHttpContent(multipart->getContent(U("view_upload"))));
setViewAdditionalDocumentation(ModelBase::boolFromHttpContent(multipart->getContent(U("view_additional_documentation"))));
setStart(ModelBase::boolFromHttpContent(multipart->getContent(U("start"))));
setSendLastEmail(ModelBase::boolFromHttpContent(multipart->getContent(U("send_last_email"))));
if(multipart->hasContent(U("derivation_screen_tpl")))
{
setDerivationScreenTpl(ModelBase::stringFromHttpContent(multipart->getContent(U("derivation_screen_tpl"))));
}
setSelfserviceTimeout(ModelBase::int32_tFromHttpContent(multipart->getContent(U("selfservice_timeout"))));
if(multipart->hasContent(U("selfservice_time")))
{
setSelfserviceTime(ModelBase::stringFromHttpContent(multipart->getContent(U("selfservice_time"))));
}
if(multipart->hasContent(U("selfservice_time_unit")))
{
setSelfserviceTimeUnit(ModelBase::stringFromHttpContent(multipart->getContent(U("selfservice_time_unit"))));
}
if(multipart->hasContent(U("selfservice_execution")))
{
setSelfserviceExecution(ModelBase::stringFromHttpContent(multipart->getContent(U("selfservice_execution"))));
}
if(multipart->hasContent(U("last_assigned_user_id")))
{
setLastAssignedUserId(ModelBase::stringFromHttpContent(multipart->getContent(U("last_assigned_user_id"))));
}
if(multipart->hasContent(U("script")))
{
setScript(ModelBase::stringFromHttpContent(multipart->getContent(U("script"))));
}
if(multipart->hasContent(U("created_at")))
{
setCreatedAt(ModelBase::stringFromHttpContent(multipart->getContent(U("created_at"))));
}
if(multipart->hasContent(U("updated_at")))
{
setUpdatedAt(ModelBase::stringFromHttpContent(multipart->getContent(U("updated_at"))));
}
}
utility::string_t Task_attributes::getName() const
{
return m_Name;
}
void Task_attributes::setName(utility::string_t value)
{
m_Name = value;
}
utility::string_t Task_attributes::getDescription() const
{
return m_Description;
}
void Task_attributes::setDescription(utility::string_t value)
{
m_Description = value;
m_DescriptionIsSet = true;
}
bool Task_attributes::descriptionIsSet() const
{
return m_DescriptionIsSet;
}
void Task_attributes::unsetDescription()
{
m_DescriptionIsSet = false;
}
utility::string_t Task_attributes::getProcessId() const
{
return m_Process_id;
}
void Task_attributes::setProcessId(utility::string_t value)
{
m_Process_id = value;
}
utility::string_t Task_attributes::getType() const
{
return m_Type;
}
void Task_attributes::setType(utility::string_t value)
{
m_Type = value;
}
utility::string_t Task_attributes::getAssignType() const
{
return m_Assign_type;
}
void Task_attributes::setAssignType(utility::string_t value)
{
m_Assign_type = value;
}
utility::string_t Task_attributes::getPriorityVariable() const
{
return m_Priority_variable;
}
void Task_attributes::setPriorityVariable(utility::string_t value)
{
m_Priority_variable = value;
m_Priority_variableIsSet = true;
}
bool Task_attributes::priority_variableIsSet() const
{
return m_Priority_variableIsSet;
}
void Task_attributes::unsetPriority_variable()
{
m_Priority_variableIsSet = false;
}
utility::string_t Task_attributes::getAssignVariable() const
{
return m_Assign_variable;
}
void Task_attributes::setAssignVariable(utility::string_t value)
{
m_Assign_variable = value;
m_Assign_variableIsSet = true;
}
bool Task_attributes::assign_variableIsSet() const
{
return m_Assign_variableIsSet;
}
void Task_attributes::unsetAssign_variable()
{
m_Assign_variableIsSet = false;
}
utility::string_t Task_attributes::getGroupVariable() const
{
return m_Group_variable;
}
void Task_attributes::setGroupVariable(utility::string_t value)
{
m_Group_variable = value;
m_Group_variableIsSet = true;
}
bool Task_attributes::group_variableIsSet() const
{
return m_Group_variableIsSet;
}
void Task_attributes::unsetGroup_variable()
{
m_Group_variableIsSet = false;
}
utility::string_t Task_attributes::getMiInstanceVariable() const
{
return m_Mi_instance_variable;
}
void Task_attributes::setMiInstanceVariable(utility::string_t value)
{
m_Mi_instance_variable = value;
m_Mi_instance_variableIsSet = true;
}
bool Task_attributes::mi_instance_variableIsSet() const
{
return m_Mi_instance_variableIsSet;
}
void Task_attributes::unsetMi_instance_variable()
{
m_Mi_instance_variableIsSet = false;
}
utility::string_t Task_attributes::getMiCompleteVariable() const
{
return m_Mi_complete_variable;
}
void Task_attributes::setMiCompleteVariable(utility::string_t value)
{
m_Mi_complete_variable = value;
m_Mi_complete_variableIsSet = true;
}
bool Task_attributes::mi_complete_variableIsSet() const
{
return m_Mi_complete_variableIsSet;
}
void Task_attributes::unsetMi_complete_variable()
{
m_Mi_complete_variableIsSet = false;
}
bool Task_attributes::getTransferFly() const
{
return m_Transfer_fly;
}
void Task_attributes::setTransferFly(bool value)
{
m_Transfer_fly = value;
}
bool Task_attributes::getCanUpload() const
{
return m_Can_upload;
}
void Task_attributes::setCanUpload(bool value)
{
m_Can_upload = value;
}
bool Task_attributes::getViewUpload() const
{
return m_View_upload;
}
void Task_attributes::setViewUpload(bool value)
{
m_View_upload = value;
}
bool Task_attributes::getViewAdditionalDocumentation() const
{
return m_View_additional_documentation;
}
void Task_attributes::setViewAdditionalDocumentation(bool value)
{
m_View_additional_documentation = value;
}
bool Task_attributes::getStart() const
{
return m_Start;
}
void Task_attributes::setStart(bool value)
{
m_Start = value;
}
bool Task_attributes::getSendLastEmail() const
{
return m_Send_last_email;
}
void Task_attributes::setSendLastEmail(bool value)
{
m_Send_last_email = value;
}
utility::string_t Task_attributes::getDerivationScreenTpl() const
{
return m_Derivation_screen_tpl;
}
void Task_attributes::setDerivationScreenTpl(utility::string_t value)
{
m_Derivation_screen_tpl = value;
m_Derivation_screen_tplIsSet = true;
}
bool Task_attributes::derivation_screen_tplIsSet() const
{
return m_Derivation_screen_tplIsSet;
}
void Task_attributes::unsetDerivation_screen_tpl()
{
m_Derivation_screen_tplIsSet = false;
}
int32_t Task_attributes::getSelfserviceTimeout() const
{
return m_Selfservice_timeout;
}
void Task_attributes::setSelfserviceTimeout(int32_t value)
{
m_Selfservice_timeout = value;
}
utility::string_t Task_attributes::getSelfserviceTime() const
{
return m_Selfservice_time;
}
void Task_attributes::setSelfserviceTime(utility::string_t value)
{
m_Selfservice_time = value;
m_Selfservice_timeIsSet = true;
}
bool Task_attributes::selfservice_timeIsSet() const
{
return m_Selfservice_timeIsSet;
}
void Task_attributes::unsetSelfservice_time()
{
m_Selfservice_timeIsSet = false;
}
utility::string_t Task_attributes::getSelfserviceTimeUnit() const
{
return m_Selfservice_time_unit;
}
void Task_attributes::setSelfserviceTimeUnit(utility::string_t value)
{
m_Selfservice_time_unit = value;
m_Selfservice_time_unitIsSet = true;
}
bool Task_attributes::selfservice_time_unitIsSet() const
{
return m_Selfservice_time_unitIsSet;
}
void Task_attributes::unsetSelfservice_time_unit()
{
m_Selfservice_time_unitIsSet = false;
}
utility::string_t Task_attributes::getSelfserviceExecution() const
{
return m_Selfservice_execution;
}
void Task_attributes::setSelfserviceExecution(utility::string_t value)
{
m_Selfservice_execution = value;
m_Selfservice_executionIsSet = true;
}
bool Task_attributes::selfservice_executionIsSet() const
{
return m_Selfservice_executionIsSet;
}
void Task_attributes::unsetSelfservice_execution()
{
m_Selfservice_executionIsSet = false;
}
utility::string_t Task_attributes::getLastAssignedUserId() const
{
return m_Last_assigned_user_id;
}
void Task_attributes::setLastAssignedUserId(utility::string_t value)
{
m_Last_assigned_user_id = value;
m_Last_assigned_user_idIsSet = true;
}
bool Task_attributes::last_assigned_user_idIsSet() const
{
return m_Last_assigned_user_idIsSet;
}
void Task_attributes::unsetLast_assigned_user_id()
{
m_Last_assigned_user_idIsSet = false;
}
utility::string_t Task_attributes::getScript() const
{
return m_Script;
}
void Task_attributes::setScript(utility::string_t value)
{
m_Script = value;
m_ScriptIsSet = true;
}
bool Task_attributes::scriptIsSet() const
{
return m_ScriptIsSet;
}
void Task_attributes::unsetScript()
{
m_ScriptIsSet = false;
}
utility::string_t Task_attributes::getCreatedAt() const
{
return m_Created_at;
}
void Task_attributes::setCreatedAt(utility::string_t value)
{
m_Created_at = value;
m_Created_atIsSet = true;
}
bool Task_attributes::created_atIsSet() const
{
return m_Created_atIsSet;
}
void Task_attributes::unsetCreated_at()
{
m_Created_atIsSet = false;
}
utility::string_t Task_attributes::getUpdatedAt() const
{
return m_Updated_at;
}
void Task_attributes::setUpdatedAt(utility::string_t value)
{
m_Updated_at = value;
m_Updated_atIsSet = true;
}
bool Task_attributes::updated_atIsSet() const
{
return m_Updated_atIsSet;
}
void Task_attributes::unsetUpdated_at()
{
m_Updated_atIsSet = false;
}
}
}
}
}
| 30.020592 | 277 | 0.706808 | [
"object",
"model"
] |
4f9731494ebf191527e58a1de9b2d8405dad9167 | 3,625 | cpp | C++ | src/mame/audio/socrates.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/audio/socrates.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/audio/socrates.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Jonathan Gevaryahu
/***************************************************************************
audio/socrates.c
Copyright (C) 2010-2011 Jonathan Gevaryahu AKA Lord Nightmare
This handles the two squarewaves (plus the one weird wave) channels
on the V-tech Socrates system 27-0769 ASIC.
****************************************************************************/
#include "emu.h"
#include "socrates.h"
// device type definition
DEFINE_DEVICE_TYPE(SOCRATES_SOUND, socrates_snd_device, "socrates_snd", "Socrates Sound")
//-------------------------------------------------
// socrates_snd_device - constructor
//-------------------------------------------------
socrates_snd_device::socrates_snd_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, SOCRATES_SOUND, tag, owner, clock)
, device_sound_interface(mconfig, *this)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void socrates_snd_device::device_start()
{
m_freq[0] = m_freq[1] = 0xff; /* channel 1,2 frequency */
m_vol[0] = m_vol[1] = 0x07; /* channel 1,2 volume */
m_enable[0] = m_enable[1] = 0x01; /* channel 1,2 enable */
m_channel3 = 0x00; /* channel 3 weird register */
m_DAC_output = 0x00; /* output */
m_state[0] = m_state[1] = m_state[2] = 0;
m_accum[0] = m_accum[1] = m_accum[2] = 0xFF;
m_stream = stream_alloc(0, 1, clock() ? clock() : machine().sample_rate());
}
//-------------------------------------------------
// sound_stream_update - handle a stream update
//-------------------------------------------------
void socrates_snd_device::sound_stream_update(sound_stream &stream, std::vector<read_stream_view> const &inputs, std::vector<write_stream_view> &outputs)
{
for (int i = 0; i < outputs[0].samples(); i++)
{
snd_clock();
outputs[0].put_int(i, (int)m_DAC_output, 32768 >> 4);
}
}
const uint8_t socrates_snd_device::s_volumeLUT[16] =
{
0, 61, 100, 132, 158, 183, 201, 218,
233, 242, 253, 255, 250, 240, 224, 211
}; // this table is actually quite weird on the real console.
// 0, 0.033, 0.055, 0.07175, 0.086, 0.1, 0.11, 0.119, 0.127, 0.132, 0.138, 0.139, 0.136, 0.131, 0.122, 0.115 are the voltage amplitudes for the steps on channel 2. the last four are particularly bizarre, probably caused by some sort of internal clipping.
void socrates_snd_device::snd_clock() /* called once per clock */
{
for (int channel = 0; channel < 2; channel++)
{
if ((m_accum[channel] == 0) && m_enable[channel])
{
m_state[channel] = (m_state[channel]^0x1);
m_accum[channel] = m_freq[channel];
}
else if (m_enable[channel])
{
m_accum[channel]--;
}
else
{
m_accum[channel] = 0; // channel is disabled
m_state[channel] = 0;
}
}
// handle channel 3 here
m_DAC_output = (m_state[0]?(s_volumeLUT[m_vol[0]]*9.4):0); // channel 1 is ~2.4 times as loud as channel 2
m_DAC_output += (m_state[1]?(s_volumeLUT[m_vol[1]]<<2):0);
// add channel 3 to dac output here
}
void socrates_snd_device::reg0_w(int data)
{
m_stream->update();
m_freq[0] = data;
}
void socrates_snd_device::reg1_w(int data)
{
m_stream->update();
m_freq[1] = data;
}
void socrates_snd_device::reg2_w(int data)
{
m_stream->update();
m_vol[0] = data&0xF;
m_enable[0] = (data&0x10)>>4;
}
void socrates_snd_device::reg3_w(int data)
{
m_stream->update();
m_vol[1] = data&0xF;
m_enable[1] = (data&0x10)>>4;
}
void socrates_snd_device::reg4_w(int data)
{
m_stream->update();
m_channel3 = data;
}
| 28.320313 | 254 | 0.600276 | [
"vector"
] |
4f97c16c0c3c8b0a1e15240acce662f2acf19334 | 15,084 | cpp | C++ | pir/cpp/server_test.cpp | libratiger/PIR | 4bbadafefc6f6b359b37c24d915e939dc7e9c016 | [
"Apache-2.0"
] | 25 | 2020-05-13T09:07:32.000Z | 2022-01-18T18:23:40.000Z | pir/cpp/server_test.cpp | libratiger/PIR | 4bbadafefc6f6b359b37c24d915e939dc7e9c016 | [
"Apache-2.0"
] | 25 | 2020-05-14T06:21:31.000Z | 2022-03-24T01:59:29.000Z | pir/cpp/server_test.cpp | libratiger/PIR | 4bbadafefc6f6b359b37c24d915e939dc7e9c016 | [
"Apache-2.0"
] | 10 | 2020-05-25T14:11:49.000Z | 2022-02-18T03:41:45.000Z | //
// Copyright 2020 the authors listed in CONTRIBUTORS.md
//
// 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 "pir/cpp/server.h"
#include <algorithm>
#include <iostream>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "pir/cpp/client.h"
#include "pir/cpp/ct_reencoder.h"
#include "pir/cpp/status_asserts.h"
#include "pir/cpp/test_base.h"
#include "pir/cpp/utils.h"
namespace pir {
namespace {
using std::cout;
using std::endl;
using std::get;
using std::make_tuple;
using std::make_unique;
using std::shared_ptr;
using std::string;
using std::tuple;
using std::unique_ptr;
using std::vector;
using seal::Ciphertext;
using seal::GaloisKeys;
using seal::Plaintext;
using seal::RelinKeys;
using namespace seal;
using namespace ::testing;
using std::int64_t;
using std::vector;
#ifdef TEST_DEBUG
#define DEBUG_OUT(x) std::cout << x << std::endl
#else
#define DEBUG_OUT(x)
#endif // TEST_DEBUG
constexpr uint32_t POLY_MODULUS_DEGREE = 4096;
constexpr uint32_t ELEM_SIZE = 7680;
class PIRServerTestBase : public PIRTestingBase {
protected:
void SetUpDBImpl(size_t dbsize, size_t dimensions = 1,
size_t elem_size = ELEM_SIZE,
uint32_t plain_mod_bit_size = 20,
bool use_ciphertext_multiplication = false) {
SetUpParams(dbsize, elem_size, dimensions, POLY_MODULUS_DEGREE,
plain_mod_bit_size, 0, use_ciphertext_multiplication);
GenerateIntDB();
SetUpSealTools();
gal_keys_ =
keygen_->galois_keys_local(generate_galois_elts(POLY_MODULUS_DEGREE));
relin_keys_ = keygen_->relin_keys_local();
server_ = *(PIRServer::Create(pir_db_, pir_params_));
ASSERT_THAT(server_, NotNull());
}
unique_ptr<PIRServer> server_;
GaloisKeys gal_keys_;
RelinKeys relin_keys_;
};
class PIRServerTest : public ::testing::TestWithParam<bool>,
public PIRServerTestBase {
protected:
void SetUp() { SetUpDB(10); }
void SetUpDB(size_t dbsize, size_t dimensions = 1,
size_t elem_size = ELEM_SIZE, uint32_t plain_mod_bit_size = 20) {
SetUpDBImpl(dbsize, dimensions, elem_size, plain_mod_bit_size, GetParam());
}
};
TEST_P(PIRServerTest, TestProcessRequest_SingleCT) {
const size_t desired_index = 7;
Plaintext pt(POLY_MODULUS_DEGREE);
pt.set_zero();
pt[desired_index] = 1;
vector<Ciphertext> query(1);
encryptor_->encrypt(pt, query[0]);
Request request_proto;
SaveRequest({query}, gal_keys_, relin_keys_, &request_proto);
ASSIGN_OR_FAIL(auto result_raw, server_->ProcessRequest(request_proto));
ASSERT_EQ(result_raw.reply_size(), 1);
ASSIGN_OR_FAIL(auto result, LoadCiphertexts(server_->Context()->SEALContext(),
result_raw.reply(0)));
ASSERT_THAT(result, SizeIs(1));
Plaintext result_pt;
decryptor_->decrypt(result[0], result_pt);
auto encoder = server_->Context()->Encoder();
ASSERT_THAT(encoder->decode_int64(result_pt),
Eq(int_db_[desired_index] * next_power_two(db_size_)));
}
TEST_P(PIRServerTest, TestProcessRequest_MultiCT) {
SetUpDB(5000);
const size_t desired_index = 4200;
Plaintext pt(POLY_MODULUS_DEGREE);
pt.set_zero();
vector<Ciphertext> query(2);
encryptor_->encrypt(pt, query[0]);
pt[desired_index - POLY_MODULUS_DEGREE] = 1;
encryptor_->encrypt(pt, query[1]);
Request request_proto;
SaveRequest({query}, gal_keys_, relin_keys_, &request_proto);
ASSIGN_OR_FAIL(auto result_raw, server_->ProcessRequest(request_proto));
ASSERT_EQ(result_raw.reply_size(), 1);
ASSIGN_OR_FAIL(auto result, LoadCiphertexts(server_->Context()->SEALContext(),
result_raw.reply(0)));
ASSERT_THAT(result, SizeIs(1));
Plaintext result_pt;
decryptor_->decrypt(result[0], result_pt);
auto encoder = server_->Context()->Encoder();
DEBUG_OUT("Expected DB value " << int_db_[desired_index]);
DEBUG_OUT("Expected m " << next_power_two(db_size_ - POLY_MODULUS_DEGREE));
ASSERT_THAT(encoder->decode_int64(result_pt),
Eq(int_db_[desired_index] *
next_power_two(db_size_ - POLY_MODULUS_DEGREE)));
}
TEST_P(PIRServerTest, TestProcessBatchRequest) {
const vector<size_t> indexes = {3, 4, 5};
vector<vector<Ciphertext>> queries(indexes.size());
for (size_t idx = 0; idx < indexes.size(); ++idx) {
Plaintext pt(POLY_MODULUS_DEGREE);
pt.set_zero();
pt[indexes[idx]] = 1;
vector<Ciphertext> query(1);
encryptor_->encrypt(pt, query[0]);
queries[idx] = query;
}
Request request_proto;
SaveRequest(queries, gal_keys_, relin_keys_, &request_proto);
ASSIGN_OR_FAIL(auto response, server_->ProcessRequest(request_proto));
for (size_t idx = 0; idx < indexes.size(); ++idx) {
ASSIGN_OR_FAIL(auto result,
LoadCiphertexts(server_->Context()->SEALContext(),
response.reply(idx)));
ASSERT_THAT(result, SizeIs(1));
Plaintext result_pt;
decryptor_->decrypt(result[0], result_pt);
auto encoder = server_->Context()->Encoder();
ASSERT_THAT(encoder->decode_int64(result_pt),
Eq(int_db_[indexes[idx]] * next_power_two(db_size_)));
}
}
// Make sure that if we get a weird request from client nothing explodes.
TEST_P(PIRServerTest, TestProcessRequestZeroInput) {
Plaintext pt(POLY_MODULUS_DEGREE);
pt.set_zero();
vector<Ciphertext> query(1);
encryptor_->encrypt(pt, query[0]);
Request request_proto;
SaveRequest({query}, gal_keys_, relin_keys_, &request_proto);
ASSIGN_OR_FAIL(auto result_raw, server_->ProcessRequest(request_proto));
ASSERT_EQ(result_raw.reply_size(), 1);
ASSIGN_OR_FAIL(auto result, LoadCiphertexts(server_->Context()->SEALContext(),
result_raw.reply(0)));
ASSERT_THAT(result, SizeIs(1));
Plaintext result_pt;
decryptor_->decrypt(result[0], result_pt);
auto encoder = server_->Context()->Encoder();
ASSERT_THAT(encoder->decode_int64(result_pt), 0);
}
TEST_P(PIRServerTest, TestProcessRequest_2Dim) {
SetUpDB(82, 2);
const size_t desired_index = 42;
uint64_t m_inv;
ASSERT_TRUE(seal::util::try_invert_uint_mod(
next_power_two(server_->Context()->DimensionsSum()),
server_->Context()->EncryptionParams().plain_modulus().value(), m_inv));
Plaintext pt(POLY_MODULUS_DEGREE);
pt.set_zero();
// select 4th row
pt[4] = m_inv;
// select 6th column (after 10-item selection vector for rows)
pt[16] = m_inv;
vector<Ciphertext> query(1);
encryptor_->encrypt(pt, query[0]);
Request request_proto;
SaveRequest({query}, gal_keys_, relin_keys_, &request_proto);
ASSIGN_OR_FAIL(auto response, server_->ProcessRequest(request_proto));
ASSERT_EQ(response.reply_size(), 1);
ASSIGN_OR_FAIL(auto reply, LoadCiphertexts(server_->Context()->SEALContext(),
response.reply(0)));
Plaintext result_pt;
if (GetParam()) {
// CT Multiplication
ASSERT_THAT(reply, SizeIs(1));
EXPECT_THAT(reply[0].size(), Eq(2))
<< "Ciphertext larger than expected. Were relin keys used?";
decryptor_->decrypt(reply[0], result_pt);
} else {
ASSIGN_OR_FAIL(auto ct_reencoder, CiphertextReencoder::Create(
server_->Context()->SEALContext()));
ASSERT_THAT(reply,
SizeIs(ct_reencoder->ExpansionRatio() * query[0].size()));
vector<Plaintext> reply_pts(reply.size());
for (size_t i = 0; i < reply_pts.size(); ++i) {
decryptor_->decrypt(reply[i], reply_pts[i]);
}
auto result_ct = ct_reencoder->Decode(reply_pts);
EXPECT_EQ(result_ct.size(), query[0].size());
decryptor_->decrypt(result_ct, result_pt);
}
auto encoder = server_->Context()->Encoder();
ASSERT_THAT(encoder->decode_int64(result_pt), Eq(int_db_[desired_index]));
}
INSTANTIATE_TEST_SUITE_P(PIRServerTests, PIRServerTest,
testing::Values(false, true));
class SubstituteOperatorTest
: public PIRServerTestBase,
public testing::TestWithParam<tuple<string, uint32_t, string>> {
void SetUp() { SetUpDBImpl(10); }
};
TEST_P(SubstituteOperatorTest, SubstituteExamples) {
Plaintext input_pt(get<0>(GetParam()));
DEBUG_OUT("Input PT: " << input_pt.to_string());
Ciphertext ct;
encryptor_->encrypt(input_pt, ct);
auto k = get<1>(GetParam());
GaloisKeys gal_keys = keygen_->galois_keys_local(vector<uint32_t>({k}));
server_->substitute_power_x_inplace(ct, k, gal_keys);
Plaintext result_pt;
decryptor_->decrypt(ct, result_pt);
DEBUG_OUT("Result PT: " << result_pt.to_string());
Plaintext expected_pt(get<2>(GetParam()));
DEBUG_OUT("Expected PT: " << expected_pt.to_string());
ASSERT_THAT(result_pt, Eq(expected_pt));
}
INSTANTIATE_TEST_SUITE_P(
Substitutions, SubstituteOperatorTest,
testing::Values(make_tuple("42", 3, "42"), make_tuple("1x^1", 5, "1x^5"),
make_tuple("6x^2", 3, "6x^6"),
make_tuple("1x^1", POLY_MODULUS_DEGREE + 1, "FC000x^1"),
make_tuple("1x^4", POLY_MODULUS_DEGREE + 1, "1x^4"),
make_tuple("1x^8", POLY_MODULUS_DEGREE / 2 + 1, "1x^8"),
make_tuple("1x^8", POLY_MODULUS_DEGREE / 4 + 1, "1x^8"),
make_tuple("1x^8", POLY_MODULUS_DEGREE / 8 + 1, "FC000x^8"),
make_tuple("77x^4095", 3, "77x^4093"),
make_tuple("1x^4095", POLY_MODULUS_DEGREE + 1,
"FC000x^4095"),
make_tuple("4x^4 + 33x^3 + 222x^2 + 19x^1 + 42",
POLY_MODULUS_DEGREE + 1,
"4x^4 + FBFCEx^3 + 222x^2 + FBFE8x^1 + 42")));
class MultiplyInversePowerXTest
: public PIRServerTestBase,
public testing::TestWithParam<tuple<string, uint32_t, string>> {
void SetUp() { SetUpDBImpl(10); }
};
TEST_P(MultiplyInversePowerXTest, MultiplyInversePowerXExamples) {
Plaintext input_pt(get<0>(GetParam()));
DEBUG_OUT("Input PT: " << input_pt.to_string());
Ciphertext ct;
encryptor_->encrypt(input_pt, ct);
auto k = get<1>(GetParam());
Ciphertext result_ct;
server_->multiply_inverse_power_of_x(ct, k, result_ct);
Plaintext result_pt;
decryptor_->decrypt(result_ct, result_pt);
DEBUG_OUT("Result PT: " << result_pt.to_string());
Plaintext expected_pt(get<2>(GetParam()));
DEBUG_OUT("Expected PT: " << expected_pt.to_string());
ASSERT_THAT(result_pt, Eq(expected_pt));
}
INSTANTIATE_TEST_SUITE_P(InversePowersOfX, MultiplyInversePowerXTest,
testing::Values(make_tuple("42x^1", 1, "42"),
make_tuple("42x^42", 41, "42x^1"),
make_tuple("1x^4 + 1x^3 + 1x^1", 1,
"1x^3 + 1x^2 + 1"),
make_tuple("1x^16 + 1x^12 + 1x^8", 4,
"1x^12 + 1x^8 + 1x^4")));
class ObliviousExpansionTest
: public PIRServerTestBase,
public testing::TestWithParam<tuple<string, vector<string>>> {
void SetUp() { SetUpDBImpl(10); }
};
TEST_P(ObliviousExpansionTest, ObliviousExpansionExamples) {
Plaintext input_pt(get<0>(GetParam()));
DEBUG_OUT("Input PT: " << input_pt.to_string());
Ciphertext ct;
encryptor_->encrypt(input_pt, ct);
auto expected = get<1>(GetParam());
ASSIGN_OR_FAIL(auto results,
server_->oblivious_expansion(
ct, expected.size(),
keygen_->galois_keys_local(
generate_galois_elts(POLY_MODULUS_DEGREE))));
vector<Plaintext> results_pt(results.size());
for (size_t i = 0; i < results.size(); ++i) {
decryptor_->decrypt(results[i], results_pt[i]);
DEBUG_OUT("Result PT[" << i << "]: " << results_pt[i].to_string());
}
vector<Plaintext> expected_pt(expected.size());
for (size_t i = 0; i < expected_pt.size(); ++i) {
expected_pt[i] = Plaintext(expected[i]);
DEBUG_OUT("Expected PT[" << i << "]: " << expected_pt[i].to_string());
}
ASSERT_THAT(results_pt, ContainerEq(expected_pt));
}
INSTANTIATE_TEST_SUITE_P(
ObliviousExpansion, ObliviousExpansionTest,
testing::Values(make_tuple("1", vector<string>({"2", "0"})),
make_tuple("1x^1", vector<string>({"0", "2"})),
make_tuple("3x^3 + 2x^2 + 1x^1 + 42",
vector<string>({"108", "4", "8", "C"})),
make_tuple("1x^5", vector<string>({"0", "0", "0", "0", "0",
"8"}))));
class ObliviousExpansionTestMultiCT
: public PIRServerTestBase,
public testing::TestWithParam<tuple<size_t, size_t, uint64_t>> {
void SetUp() { SetUpDBImpl(10); }
};
TEST_P(ObliviousExpansionTestMultiCT, MultiCTExamples) {
const auto num_items = get<0>(GetParam());
const auto index = get<1>(GetParam());
const auto expected_value = get<2>(GetParam());
vector<Plaintext> input_pt(num_items / POLY_MODULUS_DEGREE + 1,
Plaintext(POLY_MODULUS_DEGREE));
input_pt[index / POLY_MODULUS_DEGREE][index % POLY_MODULUS_DEGREE] = 1;
vector<Ciphertext> input_ct(input_pt.size());
for (size_t i = 0; i < input_pt.size(); ++i) {
DEBUG_OUT("Input PT[" << i << "]: " << input_pt[i].to_string());
encryptor_->encrypt(input_pt[i], input_ct[i]);
}
ASSIGN_OR_FAIL(auto results,
server_->oblivious_expansion(
input_ct, num_items,
keygen_->galois_keys_local(
generate_galois_elts(POLY_MODULUS_DEGREE))));
ASSERT_THAT(results, SizeIs(num_items));
for (size_t i = 0; i < results.size(); ++i) {
Plaintext result_pt;
decryptor_->decrypt(results[i], result_pt);
const auto exp = (i == index) ? expected_value : 0;
EXPECT_THAT(result_pt.coeff_count(), Eq(1))
<< "i = " << i << ", pt = " << result_pt.to_string();
EXPECT_THAT(result_pt[0], Eq(exp))
<< "i = " << i << ", pt = " << result_pt.to_string();
}
}
INSTANTIATE_TEST_SUITE_P(
ObliviousExpansionMultiCT, ObliviousExpansionTestMultiCT,
testing::Values(make_tuple(100, 42, 128), make_tuple(100, 0, 128),
make_tuple(100, 99, 128), make_tuple(4096, 3007, 4096),
make_tuple(5000, 4095, 4096),
make_tuple(5000, 4200, 1024)));
} // namespace
} // namespace pir
| 34.916667 | 80 | 0.645717 | [
"vector"
] |
4f980d4ee258acac4558323ca7bd71ccdf3beeb1 | 19,387 | cpp | C++ | 3rdparty/webkit/Source/WebKit/UIProcess/API/glib/WebKitFindController.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2021-05-27T07:29:31.000Z | 2021-05-27T07:29:31.000Z | WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/UIProcess/API/glib/WebKitFindController.cpp | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | null | null | null | WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/UIProcess/API/glib/WebKitFindController.cpp | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | /*
* Copyright (C) 2012 Igalia S.L.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2,1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "WebKitFindController.h"
#include "APIFindClient.h"
#include "WebKitEnumTypes.h"
#include "WebKitWebViewPrivate.h"
#include <glib/gi18n-lib.h>
#include <wtf/glib/GRefPtr.h>
#include <wtf/glib/WTFGType.h>
#include <wtf/text/CString.h>
using namespace WebKit;
using namespace WebCore;
/**
* SECTION: WebKitFindController
* @Short_description: Controls text search in a #WebKitWebView
* @Title: WebKitFindController
*
* A #WebKitFindController is used to search text in a #WebKitWebView. You
* can get a #WebKitWebView<!-- -->'s #WebKitFindController with
* webkit_web_view_get_find_controller(), and later use it to search
* for text using webkit_find_controller_search(), or get the
* number of matches using webkit_find_controller_count_matches(). The
* operations are asynchronous and trigger signals when ready, such as
* #WebKitFindController::found-text,
* #WebKitFindController::failed-to-find-text or
* #WebKitFindController::counted-matches<!-- -->.
*
*/
enum {
FOUND_TEXT,
FAILED_TO_FIND_TEXT,
COUNTED_MATCHES,
LAST_SIGNAL
};
enum {
PROP_0,
PROP_TEXT,
PROP_OPTIONS,
PROP_MAX_MATCH_COUNT,
PROP_WEB_VIEW
};
typedef enum {
FindOperation,
FindNextPrevOperation,
CountOperation
} WebKitFindControllerOperation;
struct _WebKitFindControllerPrivate {
CString searchText;
// Interpreted as WebKit::FindOptions.
uint32_t findOptions;
unsigned maxMatchCount;
WebKitWebView* webView;
};
static guint signals[LAST_SIGNAL] = { 0, };
WEBKIT_DEFINE_TYPE(WebKitFindController, webkit_find_controller, G_TYPE_OBJECT)
static inline WebKit::FindOptions toWebFindOptions(uint32_t findOptions)
{
return static_cast<WebKit::FindOptions>((findOptions & WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE ? FindOptionsCaseInsensitive : 0)
| (findOptions & WEBKIT_FIND_OPTIONS_AT_WORD_STARTS ? FindOptionsAtWordStarts : 0)
| (findOptions & WEBKIT_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START ? FindOptionsTreatMedialCapitalAsWordStart : 0)
| (findOptions & WEBKIT_FIND_OPTIONS_BACKWARDS ? FindOptionsBackwards : 0)
| (findOptions & WEBKIT_FIND_OPTIONS_WRAP_AROUND ? FindOptionsWrapAround : 0));
}
static inline WebKitFindOptions toWebKitFindOptions(uint32_t findOptions)
{
return static_cast<WebKitFindOptions>((findOptions & FindOptionsCaseInsensitive ? WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE : 0)
| (findOptions & FindOptionsAtWordStarts ? WEBKIT_FIND_OPTIONS_AT_WORD_STARTS : 0)
| (findOptions & FindOptionsTreatMedialCapitalAsWordStart ? WEBKIT_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START : 0)
| (findOptions & FindOptionsBackwards ? WEBKIT_FIND_OPTIONS_BACKWARDS : 0)
| (findOptions & FindOptionsWrapAround ? WEBKIT_FIND_OPTIONS_WRAP_AROUND : 0));
}
static inline WebPageProxy& getPage(WebKitFindController* findController)
{
return webkitWebViewGetPage(findController->priv->webView);
}
class FindClient final : public API::FindClient {
public:
explicit FindClient(WebKitFindController* findController)
: m_findController(findController)
{
}
private:
void didCountStringMatches(WebPageProxy*, const String&, uint32_t matchCount) override
{
g_signal_emit(m_findController, signals[COUNTED_MATCHES], 0, matchCount);
}
void didFindString(WebPageProxy*, const String&, const Vector<IntRect>&, uint32_t matchCount, int32_t, bool /*didWrapAround*/) override
{
g_signal_emit(m_findController, signals[FOUND_TEXT], 0, matchCount);
}
void didFailToFindString(WebPageProxy*, const String&) override
{
g_signal_emit(m_findController, signals[FAILED_TO_FIND_TEXT], 0);
}
WebKitFindController* m_findController;
};
static void webkitFindControllerConstructed(GObject* object)
{
G_OBJECT_CLASS(webkit_find_controller_parent_class)->constructed(object);
WebKitFindController* findController = WEBKIT_FIND_CONTROLLER(object);
getPage(findController).setFindClient(std::make_unique<FindClient>(findController));
}
static void webkitFindControllerGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec)
{
WebKitFindController* findController = WEBKIT_FIND_CONTROLLER(object);
switch (propId) {
case PROP_TEXT:
g_value_set_string(value, webkit_find_controller_get_search_text(findController));
break;
case PROP_OPTIONS:
g_value_set_uint(value, webkit_find_controller_get_options(findController));
break;
case PROP_MAX_MATCH_COUNT:
g_value_set_uint(value, webkit_find_controller_get_max_match_count(findController));
break;
case PROP_WEB_VIEW:
g_value_set_object(value, webkit_find_controller_get_web_view(findController));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
}
}
static void webkitFindControllerSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec)
{
WebKitFindController* findController = WEBKIT_FIND_CONTROLLER(object);
switch (propId) {
case PROP_WEB_VIEW:
findController->priv->webView = WEBKIT_WEB_VIEW(g_value_get_object(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
}
}
static void webkit_find_controller_class_init(WebKitFindControllerClass* findClass)
{
GObjectClass* gObjectClass = G_OBJECT_CLASS(findClass);
gObjectClass->constructed = webkitFindControllerConstructed;
gObjectClass->get_property = webkitFindControllerGetProperty;
gObjectClass->set_property = webkitFindControllerSetProperty;
/**
* WebKitFindController:text:
*
* The current search text for this #WebKitFindController.
*/
g_object_class_install_property(gObjectClass,
PROP_TEXT,
g_param_spec_string("text",
_("Search text"),
_("Text to search for in the view"),
0,
WEBKIT_PARAM_READABLE));
/**
* WebKitFindController:options:
*
* The options to be used in the search operation.
*/
g_object_class_install_property(gObjectClass,
PROP_OPTIONS,
g_param_spec_flags("options",
_("Search Options"),
_("Search options to be used in the search operation"),
WEBKIT_TYPE_FIND_OPTIONS,
WEBKIT_FIND_OPTIONS_NONE,
WEBKIT_PARAM_READABLE));
/**
* WebKitFindController:max-match-count:
*
* The maximum number of matches to report for a given search.
*/
g_object_class_install_property(gObjectClass,
PROP_MAX_MATCH_COUNT,
g_param_spec_uint("max-match-count",
_("Maximum matches count"),
_("The maximum number of matches in a given text to report"),
0, G_MAXUINT, 0,
WEBKIT_PARAM_READABLE));
/**
* WebKitFindController:web-view:
*
* The #WebKitWebView this controller is associated to.
*/
g_object_class_install_property(gObjectClass,
PROP_WEB_VIEW,
g_param_spec_object("web-view",
_("WebView"),
_("The WebView associated with this find controller"),
WEBKIT_TYPE_WEB_VIEW,
static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)));
/**
* WebKitFindController::found-text:
* @find_controller: the #WebKitFindController
* @match_count: the number of matches found of the search text
*
* This signal is emitted when a given text is found in the web
* page text. It will be issued if the text is found
* asynchronously after a call to webkit_find_controller_search(),
* webkit_find_controller_search_next() or
* webkit_find_controller_search_previous().
*/
signals[FOUND_TEXT] =
g_signal_new("found-text",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
0, 0, 0,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
/**
* WebKitFindController::failed-to-find-text:
* @find_controller: the #WebKitFindController
*
* This signal is emitted when a search operation does not find
* any result for the given text. It will be issued if the text
* is not found asynchronously after a call to
* webkit_find_controller_search(), webkit_find_controller_search_next()
* or webkit_find_controller_search_previous().
*/
signals[FAILED_TO_FIND_TEXT] =
g_signal_new("failed-to-find-text",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
0, 0, 0,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
/**
* WebKitFindController::counted-matches:
* @find_controller: the #WebKitFindController
* @match_count: the number of matches of the search text
*
* This signal is emitted when the #WebKitFindController has
* counted the number of matches for a given text after a call
* to webkit_find_controller_count_matches().
*/
signals[COUNTED_MATCHES] =
g_signal_new("counted-matches",
G_TYPE_FROM_CLASS(gObjectClass),
G_SIGNAL_RUN_LAST,
0, 0, 0,
g_cclosure_marshal_VOID__UINT,
G_TYPE_NONE, 1, G_TYPE_UINT);
}
/**
* webkit_find_controller_get_search_text:
* @find_controller: the #WebKitFindController
*
* Gets the text that @find_controller is currently searching
* for. This text is passed to either
* webkit_find_controller_search() or
* webkit_find_controller_count_matches().
*
* Returns: the text to look for in the #WebKitWebView.
*/
const char* webkit_find_controller_get_search_text(WebKitFindController* findController)
{
g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), 0);
return findController->priv->searchText.data();
}
/**
* webkit_find_controller_get_options:
* @find_controller: the #WebKitFindController
*
* Gets a bitmask containing the #WebKitFindOptions associated with
* the current search.
*
* Returns: a bitmask containing the #WebKitFindOptions associated
* with the current search.
*/
guint32 webkit_find_controller_get_options(WebKitFindController* findController)
{
g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), WEBKIT_FIND_OPTIONS_NONE);
return toWebKitFindOptions(findController->priv->findOptions);
}
/**
* webkit_find_controller_get_max_match_count:
* @find_controller: the #WebKitFindController
*
* Gets the maximum number of matches to report during a text
* lookup. This number is passed as the last argument of
* webkit_find_controller_search() or
* webkit_find_controller_count_matches().
*
* Returns: the maximum number of matches to report.
*/
guint webkit_find_controller_get_max_match_count(WebKitFindController* findController)
{
g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), 0);
return findController->priv->maxMatchCount;
}
/**
* webkit_find_controller_get_web_view:
* @find_controller: the #WebKitFindController
*
* Gets the #WebKitWebView this find controller is associated to. Do
* not dereference the returned instance as it belongs to the
* #WebKitFindController.
*
* Returns: (transfer none): the #WebKitWebView.
*/
WebKitWebView* webkit_find_controller_get_web_view(WebKitFindController* findController)
{
g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), 0);
return findController->priv->webView;
}
static void webKitFindControllerPerform(WebKitFindController* findController, WebKitFindControllerOperation operation)
{
WebKitFindControllerPrivate* priv = findController->priv;
if (operation == CountOperation) {
getPage(findController).countStringMatches(String::fromUTF8(priv->searchText.data()),
static_cast<WebKit::FindOptions>(priv->findOptions), priv->maxMatchCount);
return;
}
uint32_t findOptions = priv->findOptions;
if (operation == FindOperation)
// Unconditionally highlight text matches when the search
// starts. WK1 API was forcing clients to enable/disable
// highlighting. Since most of them (all?) where using that
// feature we decided to simplify the WK2 API and
// unconditionally show highlights. Both search_next() and
// search_prev() should not enable highlighting to avoid an
// extra unmarkAllTextMatches() + markAllTextMatches()
findOptions |= FindOptionsShowHighlight;
getPage(findController).findString(String::fromUTF8(priv->searchText.data()), static_cast<WebKit::FindOptions>(findOptions), priv->maxMatchCount);
}
static inline void webKitFindControllerSetSearchData(WebKitFindController* findController, const gchar* searchText, guint32 findOptions, guint maxMatchCount)
{
findController->priv->searchText = searchText;
findController->priv->findOptions = findOptions;
findController->priv->maxMatchCount = maxMatchCount;
}
/**
* webkit_find_controller_search:
* @find_controller: the #WebKitFindController
* @search_text: the text to look for
* @find_options: a bitmask with the #WebKitFindOptions used in the search
* @max_match_count: the maximum number of matches allowed in the search
*
* Looks for @search_text in the #WebKitWebView associated with
* @find_controller since the beginning of the document highlighting
* up to @max_match_count matches. The outcome of the search will be
* asynchronously provided by the #WebKitFindController::found-text
* and #WebKitFindController::failed-to-find-text signals.
*
* To look for the next or previous occurrences of the same text
* with the same find options use webkit_find_controller_search_next()
* and/or webkit_find_controller_search_previous(). The
* #WebKitFindController will use the same text and options for the
* following searches unless they are modified by another call to this
* method.
*
* Note that if the number of matches is higher than @max_match_count
* then #WebKitFindController::found-text will report %G_MAXUINT matches
* instead of the actual number.
*
* Callers should call webkit_find_controller_search_finish() to
* finish the current search operation.
*/
void webkit_find_controller_search(WebKitFindController* findController, const gchar* searchText, guint findOptions, guint maxMatchCount)
{
g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController));
g_return_if_fail(searchText);
webKitFindControllerSetSearchData(findController, searchText, toWebFindOptions(findOptions), maxMatchCount);
webKitFindControllerPerform(findController, FindOperation);
}
/**
* webkit_find_controller_search_next:
* @find_controller: the #WebKitFindController
*
* Looks for the next occurrence of the search text.
*
* Calling this method before webkit_find_controller_search() or
* webkit_find_controller_count_matches() is a programming error.
*/
void webkit_find_controller_search_next(WebKitFindController* findController)
{
g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController));
findController->priv->findOptions &= ~FindOptionsBackwards;
findController->priv->findOptions &= ~FindOptionsShowHighlight;
webKitFindControllerPerform(findController, FindNextPrevOperation);
}
/**
* webkit_find_controller_search_previous:
* @find_controller: the #WebKitFindController
*
* Looks for the previous occurrence of the search text.
*
* Calling this method before webkit_find_controller_search() or
* webkit_find_controller_count_matches() is a programming error.
*/
void webkit_find_controller_search_previous(WebKitFindController* findController)
{
g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController));
findController->priv->findOptions |= FindOptionsBackwards;
findController->priv->findOptions &= ~FindOptionsShowHighlight;
webKitFindControllerPerform(findController, FindNextPrevOperation);
}
/**
* webkit_find_controller_count_matches:
* @find_controller: the #WebKitFindController
* @search_text: the text to look for
* @find_options: a bitmask with the #WebKitFindOptions used in the search
* @max_match_count: the maximum number of matches allowed in the search
*
* Counts the number of matches for @search_text found in the
* #WebKitWebView with the provided @find_options. The number of
* matches will be provided by the
* #WebKitFindController::counted-matches signal.
*/
void webkit_find_controller_count_matches(WebKitFindController* findController, const gchar* searchText, guint32 findOptions, guint maxMatchCount)
{
g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController));
g_return_if_fail(searchText);
webKitFindControllerSetSearchData(findController, searchText, toWebFindOptions(findOptions), maxMatchCount);
webKitFindControllerPerform(findController, CountOperation);
}
/**
* webkit_find_controller_search_finish:
* @find_controller: a #WebKitFindController
*
* Finishes a find operation started by
* webkit_find_controller_search(). It will basically unhighlight
* every text match found.
*
* This method will be typically called when the search UI is
* closed/hidden by the client application.
*/
void webkit_find_controller_search_finish(WebKitFindController* findController)
{
g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController));
getPage(findController).hideFindUI();
}
| 38.619522 | 157 | 0.70506 | [
"object",
"vector"
] |
4f99124384ca64dcc9f3929d819607f804ec439c | 20,528 | cpp | C++ | iOS/G3MiOSSDK/Commons/Basic/PlanetTileTessellator.cpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/Basic/PlanetTileTessellator.cpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/Basic/PlanetTileTessellator.cpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | //
// PlanetTileTessellator.cpp
// G3MiOSSDK
//
// Created by Agustin Trujillo Pino on 12/07/12.
// Copyright (c) 2012 IGO Software SL. All rights reserved.
//
#include "PlanetTileTessellator.hpp"
#include "Tile.hpp"
#include "Context.hpp"
#include "IndexedMesh.hpp"
#include "TextureMapping.hpp"
#include "TexturedMesh.hpp"
#include "ShortBufferBuilder.hpp"
#include "FloatBufferBuilderFromGeodetic.hpp"
#include "GLConstants.hpp"
#include "Color.hpp"
#include "Planet.hpp"
#include "IFloatBuffer.hpp"
#include "ElevationData.hpp"
#include "MercatorUtils.hpp"
#include "FloatBufferBuilderFromCartesian2D.hpp"
#include "IndexedGeometryMesh.hpp"
#include "IShortBuffer.hpp"
#include "NormalsUtils.hpp"
PlanetTileTessellator::PlanetTileTessellator(const bool skirted, const Sector& sector):
_skirted(skirted),
_renderedSector(sector.isEquals(Sector::fullSphere())? NULL : new Sector(sector))
{
}
PlanetTileTessellator::~PlanetTileTessellator() {
delete _renderedSector;
#ifdef JAVA_CODE
super.dispose();
#endif
}
Vector2I PlanetTileTessellator::getTileMeshResolution(const Planet* planet,
const Vector2I& rawResolution,
const Tile* tile,
bool debug) const {
Sector sector = getRenderedSectorForTile(tile); // tile->getSector();
return calculateResolution(rawResolution, tile, sector);
}
Vector2I PlanetTileTessellator::calculateResolution(const Vector2I& resolution,
const Tile* tile,
const Sector& renderedSector) const {
Sector sector = tile->_sector;
const double latRatio = sector._deltaLatitude._degrees / renderedSector._deltaLatitude._degrees;
const double lonRatio = sector._deltaLongitude._degrees / renderedSector._deltaLongitude._degrees;
const IMathUtils* mu = IMathUtils::instance();
int resX = (int) mu->ceil((resolution._x / lonRatio));
if (resX < 2) {
resX = 2;
}
int resY = (int) mu->ceil((resolution._y / latRatio) );
if (resY < 2) {
resY = 2;
}
const Vector2I meshRes = Vector2I(resX, resY);
return meshRes;
// return rawResolution;
// /* testing for dynamic latitude-resolution */
// const double cos = sector._center._latitude.cosinus();
//
// int resolutionY = (int) (rawResolution._y * cos);
// if (resolutionY < 8) {
// resolutionY = 8;
// }
//
// int resolutionX = (int) (rawResolution._x * cos);
// if (resolutionX < 8) {
// resolutionX = 8;
// }
//
// return Vector2I(resolutionX, resolutionY);
}
double PlanetTileTessellator::skirtDepthForSector(const Planet* planet, const Sector& sector){
const Vector3D se = planet->toCartesian(sector.getSE());
const Vector3D nw = planet->toCartesian(sector.getNW());
const double diagonalLength = nw.sub(se).length();
const double sideLength = diagonalLength * 0.70710678118;
//0.707 = 1 / SQRT(2) -> diagonalLength => estimated side length
return sideLength / 20.0;
}
Mesh* PlanetTileTessellator::createTileMesh(const Planet* planet,
const Vector2I& rawResolution,
Tile* tile,
const ElevationData* elevationData,
float verticalExaggeration,
bool renderDebug,
TileTessellatorMeshData& data) const {
const Sector tileSector = tile->_sector;
const Sector meshSector = getRenderedSectorForTile(tile); // tile->getSector();
const Vector2I meshResolution = calculateResolution(rawResolution, tile, meshSector);
FloatBufferBuilderFromGeodetic* vertices = FloatBufferBuilderFromGeodetic::builderWithGivenCenter(planet, meshSector._center);
ShortBufferBuilder indices;
FloatBufferBuilderFromCartesian2D* textCoords = new FloatBufferBuilderFromCartesian2D();
const double minElevation = createSurface(tileSector,
meshSector,
meshResolution,
elevationData,
verticalExaggeration,
tile->_mercator,
vertices,
indices,
*textCoords,
data);
if (_skirted) {
const double relativeSkirtHeight = minElevation - skirtDepthForSector(planet, tileSector);
double absoluteSkirtHeight = 0;
if (_renderedSector != NULL) {
#ifdef C_CODE
absoluteSkirtHeight = -skirtDepthForSector(planet, *_renderedSector);
#endif
#ifdef JAVA_CODE
absoluteSkirtHeight = -skirtDepthForSector(planet, _renderedSector);
#endif
}
createEastSkirt(planet,
tileSector,
meshSector,
meshResolution,
needsEastSkirt(tileSector) ? relativeSkirtHeight : absoluteSkirtHeight,
vertices,
indices,
*textCoords);
createNorthSkirt(planet,
tileSector,
meshSector,
meshResolution,
needsNorthSkirt(tileSector) ? relativeSkirtHeight : absoluteSkirtHeight,
vertices,
indices,
*textCoords);
createWestSkirt(planet,
tileSector,
meshSector,
meshResolution,
needsWestSkirt(tileSector) ? relativeSkirtHeight : absoluteSkirtHeight,
vertices,
indices,
*textCoords);
createSouthSkirt(planet,
tileSector,
meshSector,
meshResolution,
needsSouthSkirt(tileSector) ? relativeSkirtHeight : absoluteSkirtHeight,
vertices,
indices,
*textCoords);
}
//Storing textCoords in Tile
tile->setTessellatorData(new PlanetTileTessellatorData(textCoords));
IFloatBuffer* verticesB = vertices->create();
IShortBuffer* indicesB = indices.create();
IFloatBuffer* normals = NULL;
//#warning Testing_Terrain_Normals;
// IFloatBuffer* normals = NormalsUtils::createTriangleStripSmoothNormals(verticesB, indicesB);
Mesh* result = new IndexedGeometryMesh(GLPrimitive::triangleStrip(),
vertices->getCenter(),
verticesB, true,
normals, true,
indicesB, true);
delete vertices;
return result;
}
const Vector2F PlanetTileTessellator::getTextCoord(const Tile* tile,
const Angle& latitude,
const Angle& longitude) const {
const Sector sector = tile->_sector;
const Vector2F linearUV = sector.getUVCoordinatesF(latitude, longitude);
if (!tile->_mercator) {
return linearUV;
}
const double lowerGlobalV = MercatorUtils::getMercatorV(sector._lower._latitude);
const double upperGlobalV = MercatorUtils::getMercatorV(sector._upper._latitude);
const double deltaGlobalV = lowerGlobalV - upperGlobalV;
const double globalV = MercatorUtils::getMercatorV(latitude);
const double localV = (globalV - upperGlobalV) / deltaGlobalV;
return Vector2F(linearUV._x, (float) localV);
}
IFloatBuffer* PlanetTileTessellator::createTextCoords(const Vector2I& rawResolution,
const Tile* tile) const {
PlanetTileTessellatorData* data = (PlanetTileTessellatorData*) tile->getTessellatorData();
if (data == NULL || data->_textCoords == NULL) {
ILogger::instance()->logError("Logic error on PlanetTileTessellator::createTextCoord");
return NULL;
}
return data->_textCoords->create();
}
Mesh* PlanetTileTessellator::createTileDebugMesh(const Planet* planet,
const Vector2I& rawResolution,
const Tile* tile) const {
const Sector sector = getRenderedSectorForTile(tile); // tile->getSector();
const int resolutionXMinus1 = rawResolution._x - 1;
const int resolutionYMinus1 = rawResolution._y - 1;
short posS = 0;
// compute offset for vertices
const Vector3D sw = planet->toCartesian(sector.getSW());
const Vector3D nw = planet->toCartesian(sector.getNW());
const double offset = nw.sub(sw).length() * 1e-3;
FloatBufferBuilderFromGeodetic* vertices = FloatBufferBuilderFromGeodetic::builderWithGivenCenter(planet, sector._center);
ShortBufferBuilder indices;
// west side
for (int j = 0; j < resolutionYMinus1; j++) {
vertices->add(sector.getInnerPoint(0, (double)j/resolutionYMinus1),
offset);
indices.add(posS++);
}
// south side
for (int i = 0; i < resolutionXMinus1; i++) {
vertices->add(sector.getInnerPoint((double)i/resolutionXMinus1, 1),
offset);
indices.add(posS++);
}
// east side
for (int j = resolutionYMinus1; j > 0; j--) {
vertices->add(sector.getInnerPoint(1, (double)j/resolutionYMinus1),
offset);
indices.add(posS++);
}
// north side
for (int i = resolutionXMinus1; i > 0; i--) {
vertices->add(sector.getInnerPoint((double)i/resolutionXMinus1, 0),
offset);
indices.add(posS++);
}
Color *color = Color::newFromRGBA((float) 1.0, (float) 0.0, (float) 0, (float) 1.0);
Mesh* result = new IndexedMesh(GLPrimitive::lineLoop(),
true,
vertices->getCenter(),
vertices->create(),
indices.create(),
1,
1,
color,
NULL, // colors
0, // colorsIntensity
false);
delete vertices;
return result;
}
Sector PlanetTileTessellator::getRenderedSectorForTile(const Tile* tile) const {
if (_renderedSector == NULL) {
return tile->_sector;
}
#ifdef C_CODE
return tile->_sector.intersection(*_renderedSector);
#endif
#ifdef JAVA_CODE
return tile._sector.intersection(_renderedSector);
#endif
}
double PlanetTileTessellator::createSurface(const Sector& tileSector,
const Sector& meshSector,
const Vector2I& meshResolution,
const ElevationData* elevationData,
float verticalExaggeration,
bool mercator,
FloatBufferBuilderFromGeodetic* vertices,
ShortBufferBuilder& indices,
FloatBufferBuilderFromCartesian2D& textCoords,
TileTessellatorMeshData& data) const {
const int rx = meshResolution._x;
const int ry = meshResolution._y;
const double mercatorLowerGlobalV = MercatorUtils::getMercatorV(tileSector._lower._latitude);
const double mercatorUpperGlobalV = MercatorUtils::getMercatorV(tileSector._upper._latitude);
const double mercatorDeltaGlobalV = mercatorLowerGlobalV - mercatorUpperGlobalV;
//VERTICES///////////////////////////////////////////////////////////////
IMathUtils* mu = IMathUtils::instance();
double minElevation = mu->maxDouble();
double maxElevation = mu->minDouble();
double averageElevation = 0;
for (int j = 0; j < ry; j++) {
const double v = (double) j / (ry - 1);
for (int i = 0; i < rx; i++) {
const double u = (double) i / (rx - 1);
const Geodetic2D position = meshSector.getInnerPoint(u, v);
double elevation = 0;
if (elevationData != NULL) {
const double rawElevation = elevationData->getElevationAt(position);
elevation = ISNAN(rawElevation)? 0 : rawElevation * verticalExaggeration;
//MIN
if (elevation < minElevation) {
minElevation = elevation;
}
//MAX
if (elevation > maxElevation) {
maxElevation = elevation;
}
//AVERAGE
averageElevation += elevation;
}
vertices->add( position, elevation );
//TEXT COORDS
if (mercator) {
//U
const double m_u = tileSector.getUCoordinate(position._longitude);
//V
const double mercatorGlobalV = MercatorUtils::getMercatorV(position._latitude);
const double m_v = (mercatorGlobalV - mercatorUpperGlobalV) / mercatorDeltaGlobalV;
textCoords.add((float)m_u, (float)m_v);
}
else {
Vector2D uv = tileSector.getUVCoordinates(position);
textCoords.add(uv);
}
}
}
if (minElevation == mu->maxDouble()) {
minElevation = 0;
}
if (maxElevation == mu->minDouble()) {
maxElevation = 0;
}
data._minHeight = minElevation;
data._maxHeight = maxElevation;
data._averageHeight = averageElevation / (rx * ry);
//INDEX///////////////////////////////////////////////////////////////
for (short j = 0; j < (ry-1); j++) {
const short jTimesResolution = (short) (j*rx);
if (j > 0) {
indices.add(jTimesResolution);
}
for (short i = 0; i < rx; i++) {
indices.add((short) (jTimesResolution + i));
indices.add((short) (jTimesResolution + i + rx));
}
indices.add((short) (jTimesResolution + 2*rx - 1));
}
return minElevation;
}
void PlanetTileTessellator::createEastSkirt(const Planet* planet,
const Sector& tileSector,
const Sector& meshSector,
const Vector2I& meshResolution,
double skirtHeight,
FloatBufferBuilderFromGeodetic* vertices,
ShortBufferBuilder& indices,
FloatBufferBuilderFromCartesian2D& textCoords) const {
//VERTICES///////////////////////////////////////////////////////////////
const short firstSkirtVertex = (short) (vertices->size() / 3);
const short rx = (short) meshResolution._x;
const short ry = (short) meshResolution._y;
const short southEastCorner = (short)((rx * ry) - 1);
short skirtIndex = firstSkirtVertex;
short surfaceIndex = southEastCorner;
// east side
for (int j = ry-1; j >= 0; j--) {
const double x = 1;
const double y = (double)j/(ry-1);
const Geodetic2D g = meshSector.getInnerPoint(x, y);
vertices->add(g, skirtHeight);
//TEXTURE COORDS/////////////////////////////
Vector2D uv = textCoords.getVector2D(surfaceIndex);
textCoords.add(uv);
//INDEX///////////////////////////////////////////////////////////////
indices.add(surfaceIndex);
indices.add(skirtIndex);
skirtIndex++;
surfaceIndex -= rx;
}
indices.add((short)(surfaceIndex + rx));
indices.add((short)(surfaceIndex + rx));
}
void PlanetTileTessellator::createNorthSkirt(const Planet* planet,
const Sector& tileSector,
const Sector& meshSector,
const Vector2I& meshResolution,
double skirtHeight,
FloatBufferBuilderFromGeodetic* vertices,
ShortBufferBuilder& indices,
FloatBufferBuilderFromCartesian2D& textCoords) const {
//VERTICES///////////////////////////////////////////////////////////////
const short firstSkirtVertex = (short) (vertices->size() / 3);
const short rx = (short) meshResolution._x;
// const short ry = (short) meshResolution._y;
const short northEastCorner = (short) (rx - 1);
short skirtIndex = firstSkirtVertex;
short surfaceIndex = northEastCorner;
indices.add(surfaceIndex);
for (int i = rx-1; i >= 0; i--) {
const double x = (double)i/(rx-1);
const double y = 0;
const Geodetic2D g = meshSector.getInnerPoint(x, y);
vertices->add(g, skirtHeight);
//TEXTURE COORDS/////////////////////////////
Vector2D uv = textCoords.getVector2D(surfaceIndex);
textCoords.add(uv);
//INDEX///////////////////////////////////////////////////////////////
indices.add(surfaceIndex);
indices.add(skirtIndex);
skirtIndex++;
surfaceIndex -= 1;
}
indices.add((short)(surfaceIndex + 1));
indices.add((short)(surfaceIndex + 1));
}
void PlanetTileTessellator::createWestSkirt(const Planet* planet,
const Sector& tileSector,
const Sector& meshSector,
const Vector2I& meshResolution,
double skirtHeight,
FloatBufferBuilderFromGeodetic* vertices,
ShortBufferBuilder& indices,
FloatBufferBuilderFromCartesian2D& textCoords) const {
//VERTICES///////////////////////////////////////////////////////////////
const short firstSkirtVertex = (short) (vertices->size() / 3);
const short rx = (short) meshResolution._x;
const short ry = (short) meshResolution._y;
const short northWestCorner = (short)0;
short skirtIndex = firstSkirtVertex;
short surfaceIndex = northWestCorner;
indices.add(surfaceIndex);
for (int j = 0; j < ry; j++) {
const double x = 0;
const double y = (double)j/(ry-1);
const Geodetic2D g = meshSector.getInnerPoint(x, y);
vertices->add(g, skirtHeight);
//TEXTURE COORDS/////////////////////////////
Vector2D uv = textCoords.getVector2D(surfaceIndex);
textCoords.add(uv);
//INDEX///////////////////////////////////////////////////////////////
indices.add(surfaceIndex);
indices.add(skirtIndex);
skirtIndex++;
surfaceIndex += rx;
}
indices.add((short)(surfaceIndex - rx));
indices.add((short)(surfaceIndex - rx));
}
void PlanetTileTessellator::createSouthSkirt(const Planet* planet,
const Sector& tileSector,
const Sector& meshSector,
const Vector2I& meshResolution,
double skirtHeight,
FloatBufferBuilderFromGeodetic* vertices,
ShortBufferBuilder& indices,
FloatBufferBuilderFromCartesian2D& textCoords) const {
//VERTICES///////////////////////////////////////////////////////////////
const short firstSkirtVertex = (short) (vertices->size() / 3);
const short rx = (short) meshResolution._x;
const short ry = (short) meshResolution._y;
const short southWestCorner = (short) (rx * (ry-1));
short skirtIndex = firstSkirtVertex;
short surfaceIndex = southWestCorner;
indices.add(surfaceIndex);
for (int i = 0; i < rx; i++) {
const double x = (double)i/(rx-1);
const double y = 1;
const Geodetic2D g = meshSector.getInnerPoint(x, y);
vertices->add(g, skirtHeight);
//TEXTURE COORDS/////////////////////////////
Vector2D uv = textCoords.getVector2D(surfaceIndex);
textCoords.add((float)uv._x, (float)uv._y);
//INDEX///////////////////////////////////////////////////////////////
indices.add(surfaceIndex);
indices.add((short) skirtIndex++);
surfaceIndex += 1;
}
indices.add((short)(surfaceIndex - 1));
indices.add((short)(surfaceIndex - 1));
}
| 35.454231 | 128 | 0.553196 | [
"mesh"
] |
4f994485c3dea62a3fcc0991066689bf0f85b2ea | 2,088 | cpp | C++ | core/jsonfile.cpp | granitepenguin/wwiv | 30669b21f45c5f534014a251f55568c86904f87e | [
"Apache-2.0"
] | 157 | 2015-07-08T18:29:22.000Z | 2022-03-10T10:22:58.000Z | core/jsonfile.cpp | granitepenguin/wwiv | 30669b21f45c5f534014a251f55568c86904f87e | [
"Apache-2.0"
] | 1,037 | 2015-07-18T03:09:12.000Z | 2022-03-13T17:39:55.000Z | core/jsonfile.cpp | granitepenguin/wwiv | 30669b21f45c5f534014a251f55568c86904f87e | [
"Apache-2.0"
] | 74 | 2015-07-08T19:42:19.000Z | 2021-12-22T06:15:46.000Z | /**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)2016-2021, WWIV Software Services */
/* */
/* 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 "core/jsonfile.h"
#include "deps/cereal/include/cereal/external/rapidjson/document.h"
namespace wwiv::core {
std::optional<std::string> read_json_file(const std::filesystem::path& p) {
TextFile file(p, "r");
if (!file.IsOpen()) {
return std::nullopt;
}
const auto text = file.ReadFileIntoString();
if (text.empty()) {
return std::nullopt;
}
return { text };
}
int json_file_version(const std::filesystem::path& p) {
if (auto o = read_json_file(p)) {
rapidjson::Document doc;
doc.Parse(o.value().c_str());
if (!doc.IsObject()) {
LOG(WARNING) << "document is not an object: " << p.string();
return 0;
}
}
return 0;
}
} // namespace
| 40.153846 | 76 | 0.435345 | [
"object"
] |
4f9c32930117488174b49a6402e40ca4177e3256 | 45,283 | cc | C++ | services/network/public/cpp/content_security_policy/csp_source_list_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | services/network/public/cpp/content_security_policy/csp_source_list_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | services/network/public/cpp/content_security_policy/csp_source_list_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.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 "services/network/public/cpp/content_security_policy/csp_source_list.h"
#include "base/strings/stringprintf.h"
#include "net/http/http_response_headers.h"
#include "services/network/public/cpp/content_security_policy/content_security_policy.h"
#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/origin.h"
namespace network {
namespace {
// Allow() is an abbreviation of CheckCSPSourceList. Useful for writing
// test expectations on one line.
bool Allow(const mojom::CSPSourceListPtr& source_list,
const GURL& url,
const mojom::CSPSource& self,
bool is_redirect = false,
bool is_response_check = false) {
return CheckCSPSourceList(*source_list, url, self, is_redirect,
is_response_check);
}
std::vector<mojom::ContentSecurityPolicyPtr> Parse(
const std::vector<std::string>& policies) {
auto headers =
base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK");
for (const auto& policy : policies) {
headers->AddHeader("Content-Security-Policy", policy);
}
std::vector<mojom::ContentSecurityPolicyPtr> parsed_policies;
AddContentSecurityPolicyFromHeaders(*headers, GURL("https://example.com/"),
&parsed_policies);
return parsed_policies;
}
mojom::CSPSourceListPtr ParseToSourceList(mojom::CSPDirectiveName directive,
const std::string& value) {
return std::move(
Parse({ToString(directive) + " " + value})[0]->directives[directive]);
}
std::vector<mojom::CSPSourceListPtr> ParseToVectorOfSourceLists(
mojom::CSPDirectiveName directive,
const std::vector<std::string>& values) {
std::vector<std::string> csp_values(values.size());
std::transform(values.begin(), values.end(), csp_values.begin(),
[directive](const std::string& s) -> std::string {
return ToString(directive) + " " + s;
});
std::vector<mojom::ContentSecurityPolicyPtr> policies = Parse(csp_values);
std::vector<mojom::CSPSourceListPtr> sources(policies.size());
std::transform(policies.begin(), policies.end(), sources.begin(),
[directive](mojom::ContentSecurityPolicyPtr& p)
-> mojom::CSPSourceListPtr {
return std::move(p->directives[directive]);
});
return sources;
}
std::vector<const mojom::CSPSourceList*> ToRawPointers(
const std::vector<mojom::CSPSourceListPtr>& list) {
std::vector<const mojom::CSPSourceList*> out(list.size());
std::transform(
list.begin(), list.end(), out.begin(),
[](const mojom::CSPSourceListPtr& item) -> const mojom::CSPSourceList* {
return item.get();
});
return out;
}
} // namespace
TEST(CSPSourceList, MultipleSource) {
auto self = network::mojom::CSPSource::New("http", "example.com", 80, "",
false, false);
std::vector<mojom::CSPSourcePtr> sources;
sources.push_back(mojom::CSPSource::New("", "a.com", url::PORT_UNSPECIFIED,
"", false, false));
sources.push_back(mojom::CSPSource::New("", "b.com", url::PORT_UNSPECIFIED,
"", false, false));
auto source_list = mojom::CSPSourceList::New();
source_list->sources = std::move(sources);
EXPECT_TRUE(Allow(source_list, GURL("http://a.com"), *self));
EXPECT_TRUE(Allow(source_list, GURL("http://b.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("http://c.com"), *self));
}
TEST(CSPSourceList, AllowStar) {
auto self = network::mojom::CSPSource::New("http", "example.com", 80, "",
false, false);
auto source_list = mojom::CSPSourceList::New();
source_list->allow_star = true;
EXPECT_TRUE(Allow(source_list, GURL("http://not-example.com"), *self));
EXPECT_TRUE(Allow(source_list, GURL("https://not-example.com"), *self));
EXPECT_TRUE(Allow(source_list, GURL("ws://not-example.com"), *self));
EXPECT_TRUE(Allow(source_list, GURL("wss://not-example.com"), *self));
EXPECT_TRUE(Allow(source_list, GURL("ftp://not-example.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("file://not-example.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("applewebdata://a.test"), *self));
{
// With a protocol of 'file', '*' allow 'file:'
auto self = network::mojom::CSPSource::New(
"file", "example.com", url::PORT_UNSPECIFIED, "", false, false);
EXPECT_TRUE(Allow(source_list, GURL("file://not-example.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("applewebdata://a.test"), *self));
}
}
TEST(CSPSourceList, AllowSelf) {
auto self = network::mojom::CSPSource::New("http", "example.com", 80, "",
false, false);
auto source_list = mojom::CSPSourceList::New();
source_list->allow_self = true;
EXPECT_TRUE(Allow(source_list, GURL("http://example.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("http://not-example.com"), *self));
EXPECT_TRUE(Allow(source_list, GURL("https://example.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("ws://example.com"), *self));
}
TEST(CSPSourceList, AllowStarAndSelf) {
auto self =
network::mojom::CSPSource::New("https", "a.com", 443, "", false, false);
auto source_list = mojom::CSPSourceList::New();
// If the request is allowed by {*} and not by {'self'} then it should be
// allowed by the union {*,'self'}.
source_list->allow_self = true;
source_list->allow_star = false;
EXPECT_FALSE(Allow(source_list, GURL("http://b.com"), *self));
source_list->allow_self = false;
source_list->allow_star = true;
EXPECT_TRUE(Allow(source_list, GURL("http://b.com"), *self));
source_list->allow_self = true;
source_list->allow_star = true;
EXPECT_TRUE(Allow(source_list, GURL("http://b.com"), *self));
}
TEST(CSPSourceList, AllowSelfWithUnspecifiedPort) {
auto self = network::mojom::CSPSource::New("https", "example.com", 443, "",
false, false);
auto source_list = mojom::CSPSourceList::New();
source_list->allow_self = true;
EXPECT_TRUE(Allow(source_list, GURL("https://example.com/print.pdf"), *self));
}
TEST(CSPSourceList, AllowNone) {
auto self = network::mojom::CSPSource::New("http", "example.com", 80, "",
false, false);
auto source_list = mojom::CSPSourceList::New();
EXPECT_FALSE(Allow(source_list, GURL("http://example.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("https://example.test/"), *self));
}
TEST(CSPSourceTest, SelfIsUnique) {
// Policy: 'self'
auto source_list = mojom::CSPSourceList::New();
source_list->allow_self = true;
auto self =
network::mojom::CSPSource::New("http", "a.com", 80, "", false, false);
EXPECT_TRUE(Allow(source_list, GURL("http://a.com"), *self));
EXPECT_FALSE(Allow(source_list, GURL("data:text/html,hello"), *self));
// Self doesn't match anything.
auto no_self_source = network::mojom::CSPSource::New(
"", "", url::PORT_UNSPECIFIED, "", false, false);
EXPECT_FALSE(Allow(source_list, GURL("http://a.com"), *no_self_source));
EXPECT_FALSE(
Allow(source_list, GURL("data:text/html,hello"), *no_self_source));
}
TEST(CSPSourceList, Subsume) {
std::string required =
"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/";
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(mojom::CSPDirectiveName::ScriptSrc, required);
struct TestCase {
std::vector<std::string> response_csp;
bool expected;
} cases[] = {
// Non-intersecting source lists give an effective policy of 'none', which
// is always subsumed.
{{"http://example1.com/bar/", "http://*.example3.com:*/bar/"}, true},
{{"http://example1.com/bar/",
"http://*.example3.com:*/bar/ https://*.example2.com/bar/"},
true},
// Lists that intersect into one of the required sources are subsumed.
{{"http://example1.com/foo/"}, true},
{{"https://*.example2.com/bar/"}, true},
{{"http://*.example3.com:*/bar/"}, true},
{{"https://example1.com/foo/",
"http://*.example1.com/foo/ https://*.example2.com/bar/"},
true},
{{"https://example2.com/bar/",
"http://*.example3.com:*/bar/ https://*.example2.com/bar/"},
true},
{{"http://example3.com:100/bar/",
"http://*.example3.com:*/bar/ https://*.example2.com/bar/"},
true},
// Lists that intersect into two of the required sources are subsumed.
{{"http://example1.com/foo/ https://*.example2.com/bar/"}, true},
{{"http://example1.com/foo/ https://a.example2.com/bar/",
"https://a.example2.com/bar/ http://example1.com/foo/"},
true},
{{"http://example1.com/foo/ https://a.example2.com/bar/",
"http://*.example2.com/bar/ http://example1.com/foo/"},
true},
// Ordering should not matter.
{{"https://example1.com/foo/ https://a.example2.com/bar/",
"http://a.example2.com/bar/ http://example1.com/foo/"},
true},
// Lists that intersect into a policy identical to the required list are
// subsumed.
{{"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ http://example1.com/foo/"},
true},
{{"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/"},
true},
{{"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/",
"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ http://example4.com/foo/"},
true},
{{"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/",
"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ http://example1.com/foo/"},
true},
// Lists that include sources which are not subsumed by the required list
// are not subsumed.
{{"http://example1.com/foo/ https://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ http://*.example4.com:*/bar/"},
false},
{{"http://example1.com/foo/ http://example2.com/foo/"}, false},
{{"http://*.com/bar/", "http://example1.com/bar/"}, false},
{{"http://*.example1.com/bar/"}, false},
{{"http://example1.com/bar/"}, false},
{{"http://*.example1.com/foo/"}, false},
{{"wss://example2.com/bar/"}, false},
{{"http://*.non-example3.com:*/bar/"}, false},
{{"http://example3.com/foo/"}, false},
{{"http://not-example1.com", "http://not-example1.com"}, false},
// Lists that intersect into sources which are not subsumed by the
// required
// list are not subsumed.
{{"http://not-example1.com/foo/", "https:"}, false},
{{"http://not-example1.com/foo/ http://example1.com/foo/", "https:"},
false},
{{"http://*", "http://*.com http://*.example3.com:*/bar/"}, false},
};
auto origin_b =
mojom::CSPSource::New("https", "frame.test", 443, "", false, false);
for (const auto& test : cases) {
auto response_sources = ParseToVectorOfSourceLists(
mojom::CSPDirectiveName::ScriptSrc, test.response_csp);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(
*required_sources, ToRawPointers(response_sources),
mojom::CSPDirectiveName::ScriptSrc, origin_b.get()))
<< required << " should " << (test.expected ? "" : "not ") << "subsume "
<< base::JoinString(test.response_csp, ", ");
}
}
TEST(CSPSourceList, SubsumeWithSelf) {
std::string required =
"http://example1.com/foo/ http://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ 'self'";
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(mojom::CSPDirectiveName::ScriptSrc, required);
struct TestCase {
std::vector<std::string> response_csp;
const char* origin;
bool expected;
} cases[] = {
// "https://example.test/" is a secure origin for both `required` and
// `response_csp`.
{{"'self'"}, "https://example.test/", true},
{{"https://example.test"}, "https://example.test/", true},
{{"https://example.test/"}, "https://example.test/", true},
{{"'self' 'self' 'self'"}, "https://example.test/", true},
{{"'self'", "'self'", "'self'"}, "https://example.test/", true},
{{"'self'", "'self'", "https://*.example.test/"},
"https://example.test/",
true},
{{"'self'", "'self'", "https://*.example.test/bar/"},
"https://example.test/",
true},
{{"'self' https://another.test/bar", "'self' http://*.example.test/bar",
"https://*.example.test/bar/"},
"https://example.test/",
true},
{{"http://example1.com/foo/ 'self'"}, "https://example.test/", true},
{{"http://example1.com/foo/ https://example.test/"},
"https://example.test/",
true},
{{"http://example1.com/foo/ http://*.example2.com/bar/"},
"https://example.test/",
true},
{{"http://example1.com/foo/ http://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ https://example.test/"},
"https://example.test/",
true},
{{"http://example1.com/foo/ http://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ 'self'"},
"https://example.test/",
true},
{{"'self'", "'self'", "https://example.test/"},
"https://example.test/",
true},
{{"'self'", "https://example.test/folder/"},
"https://example.test/",
true},
{{"'self'", "http://example.test/folder/"},
"https://example.test/",
true},
{{"'self' https://example.com/", "https://example.com/"},
"https://example.test/",
false},
{{"http://example1.com/foo/ http://*.example2.com/bar/",
"http://example1.com/foo/ http://*.example2.com/bar/ 'self'"},
"https://example.test/",
true},
{{"http://*.example1.com/foo/", "http://*.example1.com/foo/ 'self'"},
"https://example.test/",
false},
{{"https://*.example.test/", "https://*.example.test/ 'self'"},
"https://example.test/",
false},
{{"http://example.test/"}, "https://example.test/", false},
{{"https://example.test/"}, "https://example.test/", true},
// Origins of `required` and `response_csp` do not match.
{{"https://example.test/"}, "https://other-origin.test/", false},
{{"'self'"}, "https://other-origin.test/", true},
{{"http://example1.com/foo/ http://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ 'self'"},
"https://other-origin.test/",
true},
{{"http://example1.com/foo/ http://*.example2.com/bar/ "
"http://*.example3.com:*/bar/ https://other-origin.test/"},
"https://other-origin.test/",
true},
{{"http://example1.com/foo/ 'self'"}, "https://other-origin.test/", true},
{{"'self'", "https://example.test/"}, "https://other-origin.test/", true},
{{"'self' https://example.test/", "https://example.test/"},
"https://other-origin.test/",
false},
{{"https://example.test/", "http://example.test/"},
"https://other-origin.test/",
false},
{{"'self'", "http://other-origin.test/"},
"https://other-origin.test/",
true},
{{"'self'", "https://non-example.test/"},
"https://other-origin.test/",
true},
// `response_csp`'s origin matches one of the sources in the source list
// of `required`.
{{"'self'", "http://*.example1.com/foo/"}, "http://example1.com/", true},
{{"http://*.example2.com/bar/", "'self'"},
"http://example2.com/bar/",
true},
{{"'self' http://*.example1.com/foo/", "http://*.example1.com/foo/"},
"http://example1.com/",
false},
{{"http://*.example2.com/bar/ http://example1.com/",
"'self' http://example1.com/"},
"http://example2.com/bar/",
false},
};
for (const auto& test : cases) {
auto response_sources = ParseToVectorOfSourceLists(
mojom::CSPDirectiveName::ScriptSrc, test.response_csp);
GURL parsed_test_origin(test.origin);
auto origin_b = mojom::CSPSource::New(
parsed_test_origin.scheme(), parsed_test_origin.host(),
parsed_test_origin.EffectiveIntPort(), "", false, false);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(
*required_sources, ToRawPointers(response_sources),
mojom::CSPDirectiveName::ScriptSrc, origin_b.get()))
<< required << "from origin " << test.origin << " should "
<< (test.expected ? "" : "not ") << "subsume "
<< base::JoinString(test.response_csp, ", ");
}
}
TEST(CSPSourceList, SubsumeAllowAllInline) {
struct TestCase {
mojom::CSPDirectiveName directive;
std::string required;
std::vector<std::string> response_csp;
bool expected;
} cases[] = {
// `required` allows all inline behavior.
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"'unsafe-inline' http://example1.com/foo/bar.html"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"http://example1.com/foo/ 'unsafe-inline'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"'unsafe-inline' 'nonce-yay'", "'unsafe-inline'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"'unsafe-inline' 'nonce-yay'", "'unsafe-inline'", "'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"'unsafe-inline' 'nonce-yay'", "'unsafe-inline'",
"'strict-dynamic' 'nonce-yay'"},
true},
// `required` does not allow all inline behavior.
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'strict-dynamic'",
{"'unsafe-inline' http://example1.com/foo/bar.html"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self'",
{"'unsafe-inline'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"'unsafe-inline' 'nonce-yay'", "'nonce-abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self'",
{"'unsafe-inline' https://example.test/"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"'unsafe-inline' https://example.test/"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"'unsafe-inline' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'nonce-yay'",
{"'unsafe-inline' 'nonce-yay'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic' "
"'nonce-yay'",
{"'unsafe-inline' 'nonce-yay'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic' "
"'nonce-yay'",
{"http://example1.com/foo/ 'unsafe-inline' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba' "
"'strict-dynamic'",
{"'unsafe-inline' 'sha512-321cba'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic' "
"'sha512-321cba'",
{"http://example1.com/foo/ 'unsafe-inline' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba'",
{"http://example1.com/foo/ 'unsafe-inline'",
"http://example1.com/foo/ 'sha512-321cba'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba'",
{"http://example1.com/foo/ 'unsafe-inline'",
"http://example1.com/foo/ 'unsafe-inline' 'sha512-321cba'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba'",
{"http://example1.com/foo/ 'unsafe-inline' 'nonce-yay'",
"http://example1.com/foo/ 'unsafe-inline' 'sha512-321cba'"},
true},
};
auto origin_b =
mojom::CSPSource::New("https", "frame.test", 443, "", false, false);
for (const auto& test : cases) {
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(test.directive, test.required);
auto response_sources =
ParseToVectorOfSourceLists(test.directive, test.response_csp);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(*required_sources,
ToRawPointers(response_sources),
test.directive, origin_b.get()))
<< test.required << " should " << (test.expected ? "" : "not ")
<< "subsume " << base::JoinString(test.response_csp, ", ");
}
}
TEST(CSPSourceList, SubsumeUnsafeAttributes) {
struct TestCase {
mojom::CSPDirectiveName directive;
std::string required;
std::vector<std::string> response_csp;
bool expected;
} cases[] = {
// `required` or `response_csp` contain `unsafe-eval`.
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic' "
"'unsafe-eval'",
{"http://example1.com/foo/bar.html 'unsafe-eval'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-eval'",
{"http://example1.com/foo/ 'unsafe-inline'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-eval'",
{"http://example1.com/foo/ 'unsafe-inline' 'unsafe-eval'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-eval'",
{"http://example1.com/foo/ 'unsafe-eval'",
"http://example1.com/foo/bar 'self' unsafe-eval'",
"http://non-example.com/foo/ 'unsafe-eval' 'self'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self'",
{"http://example1.com/foo/ 'unsafe-eval'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"http://example1.com/foo/ 'unsafe-eval'",
"http://example1.com/foo/bar 'self' 'unsafe-eval'",
"http://non-example.com/foo/ 'unsafe-eval' 'self'"},
false},
// `required` or `response_csp` contain `unsafe-hashes`.
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'unsafe-eval' "
"'strict-dynamic' "
"'unsafe-hashes'",
{"http://example1.com/foo/bar.html 'unsafe-hashes'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-hashes'",
{"http://example1.com/foo/ 'unsafe-inline'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-hashes'",
{"http://example1.com/foo/ 'unsafe-inline' 'unsafe-hashes'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-eval' "
"'unsafe-hashes'",
{"http://example1.com/foo/ 'unsafe-eval' 'unsafe-hashes'",
"http://example1.com/foo/bar 'self' 'unsafe-hashes'",
"http://non-example.com/foo/ 'unsafe-hashes' 'self'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self'",
{"http://example1.com/foo/ 'unsafe-hashes'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"http://example1.com/foo/ 'unsafe-hashes'",
"http://example1.com/foo/bar 'self' 'unsafe-hashes'",
"https://example1.com/foo/bar 'unsafe-hashes' 'self'"},
false},
};
auto origin_b =
mojom::CSPSource::New("https", "frame.test", 443, "", false, false);
for (const auto& test : cases) {
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(test.directive, test.required);
auto response_sources =
ParseToVectorOfSourceLists(test.directive, test.response_csp);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(*required_sources,
ToRawPointers(response_sources),
test.directive, origin_b.get()))
<< test.required << " should " << (test.expected ? "" : "not ")
<< "subsume " << base::JoinString(test.response_csp, ", ");
}
}
TEST(CSPSourceList, SubsumeNoncesAndHashes) {
// For |required| to subsume |response_csp|:
// - If |response_csp| enforces some nonce, then |required| must contain some
// nonce, but they do not need to match.
// - On the other side, all hashes enforced by |response_csp| must be
// contained in |required|.
struct TestCase {
mojom::CSPDirectiveName directive;
std::string required;
std::vector<std::string> response_csp;
bool expected;
} cases[] = {
// Check nonces.
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'unsafe-inline' 'nonce-abc'",
{"'unsafe-inline'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'nonce-abc'",
{"'nonce-abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"'unsafe-inline' 'nonce-yay'", "'nonce-yay'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-yay'",
{"'unsafe-inline' 'nonce-yay'", "'nonce-yay'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-abc' 'nonce-yay'",
{"'unsafe-inline' https://example.test/"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-abc' 'nonce-yay'",
{"'nonce-abc' https://example1.com/foo/"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'nonce-yay' "
"'strict-dynamic'",
{"https://example.test/ 'nonce-yay'"},
false},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'nonce-yay' "
"'strict-dynamic'",
{"'nonce-yay' https://example1.com/foo/"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'nonce-abc'",
{"http://example1.com/foo/ 'nonce-xyz'"},
true},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'nonce-abc'",
{"http://example1.com/foo/ 'nonce-xyz'"},
true},
// Check hashes.
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba'",
{"http://example1.com/foo/page.html 'strict-dynamic'",
"https://example1.com/foo/ 'sha512-321cba'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba'",
{"http://some-other.com/ 'strict-dynamic' 'sha512-321cba'",
"http://example1.com/foo/ 'unsafe-inline' 'sha512-321cba'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba'",
{"http://example1.com/foo/ 'sha512-321abc' 'sha512-321cba'",
"http://example1.com/foo/ 'sha512-321abc' 'sha512-321cba'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321cba'",
{"http://example1.com/foo/ 'unsafe-inline'",
"http://example1.com/foo/ 'sha512-321cba'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc'",
{"http://example1.com/foo/ 'unsafe-inline' 'sha512-321abc'",
"http://example1.com/foo/ 'sha512-321abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc'",
{"'unsafe-inline' 'sha512-321abc'",
"http://example1.com/foo/ 'sha512-321abc'"},
true},
// Nonces and hashes together.
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc' "
"'nonce-abc'",
{"'unsafe-inline' 'sha512-321abc' 'self'",
"'unsafe-inline''sha512-321abc' https://example.test/"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc' "
"'nonce-abc'",
{"'unsafe-inline' 'sha512-321abc' 'self' 'nonce-abc'",
"'sha512-321abc' https://example.test/"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc' "
"'nonce-abc'",
{"'unsafe-inline' 'sha512-321abc' 'self'",
" 'sha512-321abc' https://example.test/ 'nonce-abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc' "
"'nonce-abc'",
{"'unsafe-inline' 'sha512-321abc' 'self' 'nonce-xyz'",
"unsafe-inline' 'sha512-321abc' https://example.test/ 'nonce-xyz'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc' "
"'nonce-abc'",
{"'unsafe-inline' 'sha512-321abc' 'self' 'sha512-xyz'",
"unsafe-inline' 'sha512-321abc' https://example.test/ 'sha512-xyz'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'nonce-abc' 'sha512-321abc'",
{"http://example1.com/foo/ 'nonce-xyz' 'sha512-321abc'"},
true},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'nonce-abc' 'sha512-321abc'",
{"http://example1.com/foo/ 'nonce-xyz' 'sha512-321abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'nonce-abc' 'sha512-321abc'",
{"http://example1.com/foo/ 'nonce-xyz' 'sha512-xyz'"},
false},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'nonce-abc' 'sha512-321abc'",
{"http://example1.com/foo/ 'nonce-xyz' 'sha512-xyz'",
"http://example1.com/foo/ 'nonce-zyx' 'nonce-xyz' 'sha512-xyz'"},
false},
};
auto origin_b =
mojom::CSPSource::New("https", "frame.test", 443, "", false, false);
for (const auto& test : cases) {
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(test.directive, test.required);
auto response_sources =
ParseToVectorOfSourceLists(test.directive, test.response_csp);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(*required_sources,
ToRawPointers(response_sources),
test.directive, origin_b.get()))
<< test.required << " should " << (test.expected ? "" : "not ")
<< "subsume " << base::JoinString(test.response_csp, ", ");
}
}
TEST(CSPSourceList, SubsumeStrictDynamic) {
struct TestCase {
mojom::CSPDirectiveName directive;
std::string required;
std::vector<std::string> response_csp;
bool expected;
} cases[] = {
// Neither `required` nor effective policy of `response_csp` has
// `strict-dynamic`.
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'nonce-yay' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay'", "'nonce-yay' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'nonce-yay' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay'", "'nonce-abc' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc'",
{"'strict-dynamic' 'nonce-yay' 'sha512-321abc'",
"'sha512-321abc' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc'",
{"'strict-dynamic' 'nonce-yay' 'sha512-321abc'",
"'sha512-321abc' 'strict-dynamic'", "'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::StyleSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc'",
{"'strict-dynamic' 'nonce-yay' http://example1.com/",
"http://example1.com/ 'strict-dynamic'"},
false},
// `required` has `strict-dynamic`, effective policy of `response_csp`
// does not.
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-yay' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay'", "'nonce-yay'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"'strict-dynamic' 'sha512-321abc'", "'unsafe-inline' 'sha512-321abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"'sha512-321abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"http://example1.com/foo/ 'sha512-321abc'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"'self' 'sha512-321abc'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay'", "'nonce-yay'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"http://example1.com/ 'sha512-321abc'",
"http://example1.com/ 'sha512-321abc'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'sha512-321abc' 'strict-dynamic'",
{"https://example1.com/foo/ 'sha512-321abc'",
"http://example1.com/foo/ 'sha512-321abc'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-yay' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay'", "'nonce-yay'", "'sha512-321abc'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-hashes' "
"'strict-dynamic'",
{"'strict-dynamic' 'unsafe-hashes'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-yay' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay' 'unsafe-hashes'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-eval' 'strict-dynamic'",
{"'strict-dynamic' 'unsafe-eval'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-yay' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay' 'unsafe-eval'"},
false},
// `required` does not have `strict-dynamic`, but effective policy of
// `response_csp` does.
// Note that any subsumption in this set-up should be `false`.
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'nonce-yay'",
{"'strict-dynamic' 'nonce-yay'", "'sha512-321abc' 'strict-dynamic'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc'",
{"'strict-dynamic' 'sha512-321abc'", "'strict-dynamic' 'sha512-321abc'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline'",
{"'strict-dynamic'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'sha512-321abc'",
{"'strict-dynamic'"},
false},
// Both `required` and effective policy of `response_csp` has
// `strict-dynamic`.
{mojom::CSPDirectiveName::ScriptSrc,
"'strict-dynamic'",
{"'strict-dynamic'", "'strict-dynamic'", "'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"'strict-dynamic'",
{"'strict-dynamic'", "'strict-dynamic' 'nonce-yay'",
"'strict-dynamic' 'nonce-yay'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"'strict-dynamic' 'nonce-yay'",
{"http://example.com 'strict-dynamic' 'nonce-yay'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"'strict-dynamic' 'nonce-yay'", "'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"'strict-dynamic' http://another.com/",
"http://another.com/ 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'unsafe-inline' 'strict-dynamic'",
{"'self' 'sha512-321abc' 'strict-dynamic'",
"'self' 'strict-dynamic' 'sha512-321abc'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'sha512-321abc' 'strict-dynamic'",
{"'self' 'sha512-321abc' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"'unsafe-inline' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"'unsafe-inline' 'sha512-123xyz' 'strict-dynamic'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"'unsafe-eval' 'self' 'sha512-321abc' 'strict-dynamic'",
{"'unsafe-eval' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"'unsafe-eval' 'strict-dynamic'"},
false},
{mojom::CSPDirectiveName::ScriptSrc,
"'unsafe-hashes' 'self' 'sha512-321abc' 'strict-dynamic'",
{"'unsafe-hashes' 'strict-dynamic'"},
true},
{mojom::CSPDirectiveName::ScriptSrc,
"http://example1.com/foo/ 'self' 'sha512-321abc' 'strict-dynamic'",
{"'unsafe-hashes' 'strict-dynamic'"},
false},
};
auto origin_b =
mojom::CSPSource::New("https", "frame.test", 443, "", false, false);
for (const auto& test : cases) {
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(test.directive, test.required);
auto response_sources =
ParseToVectorOfSourceLists(test.directive, test.response_csp);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(*required_sources,
ToRawPointers(response_sources),
test.directive, origin_b.get()))
<< test.required << " should " << (test.expected ? "" : "not ")
<< "subsume " << base::JoinString(test.response_csp, ", ");
}
}
TEST(CSPSourceList, SubsumeListWildcard) {
struct TestCase {
std::string required;
std::vector<std::string> response_csp;
bool expected;
} cases[] = {
// `required` subsumes `response_csp`.
{"*", {""}, true},
{"*", {"'none'"}, true},
{"*", {"*"}, true},
{"*", {"*", "*", "*"}, true},
{"*", {"*", "* https: http: ftp: ws: wss:"}, true},
{"*", {"*", "https: http: ftp: ws: wss:"}, true},
{"https: http: ftp: ws: wss:", {"*", "https: http: ftp: ws: wss:"}, true},
{"http: ftp: ws:", {"*", "https: http: ftp: ws: wss:"}, true},
{"http: ftp: ws:", {"*", "https: 'strict-dynamic'"}, true},
{"http://another.test", {"*", "'self'"}, true},
{"http://another.test/", {"*", "'self'"}, true},
{"http://another.test", {"https:", "'self'"}, true},
{"'self'", {"*", "'self'"}, true},
{"'unsafe-eval' * ", {"'unsafe-eval'"}, true},
{"'unsafe-hashes' * ", {"'unsafe-hashes'"}, true},
{"'unsafe-inline' * ", {"'unsafe-inline'"}, true},
{"*", {"*", "http://a.com ws://b.com ftp://c.com"}, true},
{"*", {"* data: blob:", "http://a.com ws://b.com ftp://c.com"}, true},
{"*", {"data: blob:", "http://a.com ws://b.com ftp://c.com"}, true},
{"*", {"*", "data://a.com ws://b.com ftp://c.com"}, true},
{"* data:",
{"data: blob: *", "data://a.com ws://b.com ftp://c.com"},
true},
{"http://a.com ws://b.com ftp://c.com",
{"*", "http://a.com ws://b.com ftp://c.com"},
true},
// `required` does not subsume `response_csp`.
{"*", std::vector<std::string>(), false},
{"", {"*"}, false},
{"'none'", {"*"}, false},
{"*", {"data:"}, false},
{"*", {"blob:"}, false},
{"http: ftp: ws:",
{"* 'strict-dynamic'", "https: 'strict-dynamic'"},
false},
{"https://another.test", {"*"}, false},
{"*", {"* 'unsafe-eval'"}, false},
{"*", {"* 'unsafe-hashes'"}, false},
{"*", {"* 'unsafe-inline'"}, false},
{"'unsafe-eval'", {"* 'unsafe-eval'"}, false},
{"'unsafe-hashes'", {"* 'unsafe-hashes'"}, false},
{"'unsafe-inline'", {"* 'unsafe-inline'"}, false},
{"*", {"data: blob:", "data://a.com ws://b.com ftp://c.com"}, false},
{"* data:",
{"data: blob:", "blob://a.com ws://b.com ftp://c.com"},
false},
};
auto origin_b =
mojom::CSPSource::New("https", "another.test", 443, "", false, false);
for (const auto& test : cases) {
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(mojom::CSPDirectiveName::ScriptSrc, test.required);
auto response_sources = ParseToVectorOfSourceLists(
mojom::CSPDirectiveName::ScriptSrc, test.response_csp);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(
*required_sources, ToRawPointers(response_sources),
mojom::CSPDirectiveName::ScriptSrc, origin_b.get()))
<< test.required << " should " << (test.expected ? "" : "not ")
<< "subsume " << base::JoinString(test.response_csp, ", ");
}
}
TEST(CSPSourceList, SubsumeListNoScheme) {
auto origin_http =
mojom::CSPSource::New("http", "example.org", 80, "", false, false);
auto origin_https =
mojom::CSPSource::New("https", "example.org", 443, "", false, false);
struct TestCase {
std::string required;
std::vector<std::string> response_csp;
mojom::CSPSource* origin;
bool expected;
} cases[] = {
{"http://a.com", {"a.com"}, origin_https.get(), true},
{"https://a.com", {"a.com"}, origin_https.get(), true},
{"https://a.com", {"a.com"}, origin_http.get(), false},
{"data://a.com", {"a.com"}, origin_https.get(), false},
{"a.com", {"a.com"}, origin_https.get(), true},
{"a.com", {"a.com"}, origin_http.get(), true},
{"a.com", {"https://a.com"}, origin_http.get(), true},
{"a.com", {"https://a.com"}, origin_https.get(), true},
{"a.com", {"http://a.com"}, origin_https.get(), false},
{"https:", {"a.com"}, origin_http.get(), false},
{"http:", {"a.com"}, origin_http.get(), true},
{"https:", {"a.com", "https:"}, origin_http.get(), true},
{"https:", {"a.com"}, origin_https.get(), true},
};
for (const auto& test : cases) {
mojom::CSPSourceListPtr required_sources =
ParseToSourceList(mojom::CSPDirectiveName::ScriptSrc, test.required);
auto response_sources = ParseToVectorOfSourceLists(
mojom::CSPDirectiveName::ScriptSrc, test.response_csp);
EXPECT_EQ(test.expected,
CSPSourceListSubsumes(
*required_sources, ToRawPointers(response_sources),
mojom::CSPDirectiveName::ScriptSrc, test.origin))
<< test.required << " on origin with scheme " << test.origin->scheme
<< " should " << (test.expected ? "" : "not ") << "subsume "
<< base::JoinString(test.response_csp, ", ");
}
}
} // namespace network
| 42.881629 | 88 | 0.585871 | [
"vector",
"transform"
] |
4f9cd578b337c04f069e68e4aa5e90c135e78b46 | 2,549 | cpp | C++ | lib/params/Transform.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | null | null | null | lib/params/Transform.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | null | null | null | lib/params/Transform.cpp | RemiLacroix-IDRIS/VAPOR | 33c787b6089ad845f6f989176d839e117fcdb03f | [
"BSD-3-Clause"
] | 1 | 2021-12-04T15:35:46.000Z | 2021-12-04T15:35:46.000Z | //************************************************************************
// *
// Copyright (C) 2004 *
// University Corporation for Atmospheric Research *
// All Rights Reserved *
// *
//************************************************************************/
//
// File: Transform.cpp
//
// Author: Scott Pearse
// National Center for Atmospheric Research
// PO 3000, Boulder, Colorado
//
// Date: May 2017
//
// Description: Implements the Transform class
// This class contains the translation, rotation, and scale
// parameters associated with a loaded data set
//
#ifdef WIN32
//Annoying unreferenced formal parameter warning
#pragma warning( disable : 4100 )
#endif
#include <iostream>
#include <vapor/Transform.h>
using namespace VAPoR;
using namespace Wasp;
const string Transform::_translationTag = "Translation";
const string Transform::_rotationTag = "Rotation";
const string Transform::_scaleTag = "Scale";
const string Transform::_originTag = "Origin";
const string Transform::_originInitializedTag = "OriginInitialized";
//
// Register class with object factory!!!
//
static ParamsRegistrar<Transform> registrar(Transform::GetClassType());
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
Transform::Transform(
ParamsBase::StateSave *ssave
) : ParamsBase(ssave, Transform::GetClassType())
{
}
Transform::Transform(
ParamsBase::StateSave *ssave, XmlNode *node
) : ParamsBase(ssave, node)
{
}
//----------------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------------
Transform::~Transform()
{
MyBase::SetDiagMsg("Transform::~Transform() this=%p", this);
}
void Transform::SetScales(const vector<double> scale) {
SetValueDoubleVec(_scaleTag, "Set scale transform", scale);
}
vector<double> Transform::GetOrigin() const {
vector <double> defaultv(3,0.0);
vector<double> origin = GetValueDoubleVec(_originTag, defaultv);
return origin;
}
void Transform::SetOrigin(const vector<double> origin) {
SetValueDoubleVec(_originTag, "Set origin for transforms", origin);
SetOriginInitialized(true);
}
bool Transform::IsOriginInitialized() const
{
return GetValueLong(_originInitializedTag, false);
}
void Transform::SetOriginInitialized(bool value)
{
SetValueLong(_originInitializedTag, "Set is origin initialized for transforms", value);
}
| 28.010989 | 88 | 0.597882 | [
"object",
"vector",
"transform"
] |
4f9d975c4daf7faea0ed873235c27fb0843f6666 | 18,149 | cpp | C++ | utils/stats.cpp | ndvbd/tongrams | a301022cd01a21f542757c22b6738ff647887e00 | [
"Apache-2.0"
] | null | null | null | utils/stats.cpp | ndvbd/tongrams | a301022cd01a21f542757c22b6738ff647887e00 | [
"Apache-2.0"
] | null | null | null | utils/stats.cpp | ndvbd/tongrams | a301022cd01a21f542757c22b6738ff647887e00 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "mph_count_lm.hpp"
#include "mph_prob_lm.hpp"
#include "trie_count_lm.hpp"
#include "trie_prob_lm.hpp"
#include <unordered_map>
namespace tongrams
{
template<typename Values,
typename KeyRankSequence,
typename BaseHasher>
void mph_count_lm<Values,
KeyRankSequence,
BaseHasher>::print_stats(size_t bytes) const
{
util::logger("========= MPH_COUNT_LM statistics =========");
uint64_t num_grams = size();
std::cout << "order: " << order() << "\n";
std::cout << "num. of grams: " << num_grams << "\n";
std::cout << "tot. bytes: " << bytes << "\n";
std::cout << "bytes per gram: " << double(bytes) / num_grams << "\n";
std::cout << "unique values bytes: " << m_distinct_counts.bytes() << "\n";
uint64_t i = 1;
size_t data_bytes = m_distinct_counts.bytes();
for (auto const& t: m_tables) {
std::cout << i << "-grams stats:\n";
std::cout << "\tdistinct frequency counters: "
<< m_distinct_counts.size(i - 1) << "\n";
size_t x = t.data_bytes();
std::cout << "\tdata table bytes: " << x << std::endl;
std::cout << "\t(does NOT include hash function bytes)\n";
data_bytes += x;
++i;
}
uint64_t hash_key_bytes = KeyRankSequence::hash_bits / 8;
std::cout << "hash keys bytes: " << hash_key_bytes * num_grams
<< " (" << hash_key_bytes * num_grams * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(hash_key_bytes) / num_grams << std::endl;
uint64_t counts_bytes = data_bytes - hash_key_bytes * num_grams;
std::cout << "counts bytes: " << counts_bytes
<< " (" << counts_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(counts_bytes) / num_grams << std::endl;
uint64_t hash_function_bytes = bytes - data_bytes;
std::cout << "hash functions bytes: " << hash_function_bytes
<< " (" << hash_function_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(hash_function_bytes) / num_grams << std::endl;
std::cout << "hash functions bits per gram: "
<< hash_function_bytes * 8.0 / num_grams << std::endl;
}
template<typename Values,
typename KeyRankSequence,
typename BaseHasher>
void mph_prob_lm<Values,
KeyRankSequence,
BaseHasher>::print_stats(size_t bytes) const
{
util::logger("========= MPH_PROB_LM statistics =========");
uint64_t num_grams = size();
std::cout << "order: " << order() << "\n";
std::cout << "num. of grams: " << num_grams << "\n";
std::cout << "tot. bytes: " << bytes << "\n";
std::cout << "bytes per gram: " << double(bytes) / num_grams << "\n";
std::cout << "quantized probs bytes: " << m_probs_averages.bytes() << "\n";
std::cout << "quantized backoffs bytes: " << m_backoffs_averages.bytes() << "\n";
uint64_t i = 1;
size_t data_bytes = m_probs_averages.bytes()
+ m_backoffs_averages.bytes();
for (auto const& t: m_tables) {
std::cout << i << "-grams stats:\n";
size_t x = t.data_bytes();
std::cout << "\tdata table bytes: " << x << std::endl;
std::cout << "\t(does NOT include hash function bytes)\n";
data_bytes += x;
++i;
}
uint64_t hash_key_bytes = KeyRankSequence::hash_bits / 8;
std::cout << "hash keys bytes: " << hash_key_bytes * num_grams
<< " (" << hash_key_bytes * num_grams * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(hash_key_bytes) / num_grams << std::endl;
uint64_t ranks_bytes = data_bytes - hash_key_bytes * num_grams;
std::cout << "ranks bytes: " << ranks_bytes
<< " (" << ranks_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(ranks_bytes) / num_grams << std::endl;
uint64_t hash_function_bytes = bytes - data_bytes;
std::cout << "hash functions bytes: " << hash_function_bytes
<< " (" << hash_function_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(hash_function_bytes) / num_grams << std::endl;
std::cout << "hash functions bits per gram: "
<< hash_function_bytes * 8.0 / num_grams << std::endl;
}
struct topk_queue {
topk_queue(size_t size) {
m_data.reserve(size);
}
void add(uint64_t x) {
if (m_data.size() < k()) {
m_data.push_back(x);
std::push_heap(m_data.begin(),
m_data.end(),
std::greater<uint64_t>());
return;
}
if (x > m_data.front()) {
std::pop_heap(m_data.begin(),
m_data.end(), std::greater<uint64_t>());
m_data.back() = x;
std::push_heap(m_data.begin(),
m_data.end(), std::greater<uint64_t>());
}
}
size_t k() const {
return m_data.capacity();
}
void finalize() {
std::sort(m_data.begin(),
m_data.end(),
std::greater<uint64_t>());
}
void print() const {
for (auto v: m_data) {
std::cout << v << " ";
}
std::cout << std::endl;
}
private:
std::vector<uint64_t> m_data;
};
template<typename Grams,
typename Ranks,
typename Pointers>
void sorted_array<Grams,
Ranks,
Pointers>::print_stats(uint8_t order, pointer_sequence<Pointers> const* ranges) const
{
uint64_t n = size();
std::cout << "\tnum grams: " << n << "\n";
if (m_grams.size()) {
uint64_t u = m_grams.universe();
std::cout << "\tuniverse: " << u << "\n";
double avg_gap = double(u) / n;
std::cout << "\tavg gap: " << avg_gap << "\n";
// std::cout << "\tEF_single bytes: "
// << uint64_t(double(n * (util::ceil_log2(avg_gap) + 2)) / 8) << "\n";
}
auto m = m_pointers.size();
if (m) {
uint64_t sum = 0;
uint64_t max = 0;
uint64_t min = uint64_t(-1);
uint64_t non_null_ranges = 0;
{
topk_queue top_k(5);
auto it = m_pointers.begin();
uint64_t begin = it.next();
std::cout << "\tnum ptrs.: " << m << "\n";
for (uint64_t i = 0; i < m - 1; ++i) {
uint64_t end = it.next();
uint64_t range = end - begin;
if (range) {
if (range < min) {
min = range;
}
if (range > max) {
max = range;
}
sum += range;
++non_null_ranges;
top_k.add(range);
}
begin = end;
}
std::cout << "\tnon-empty ranges: " << non_null_ranges << "\n";
std::cout << "\tdensity: " << non_null_ranges * 100.0 / m << "%\n";
std::cout << "\tmin range: " << min << "\n";
std::cout << "\tmax range: " << max << "\n";
std::cout << "\tavg range: " << double(sum) / non_null_ranges << std::endl;
std::cout << "\ttop-" << top_k.k() << " ranges: ";
top_k.finalize();
top_k.print();
}
// {
// auto it = m_pointers.begin();
// uint64_t begin = it.next();
// double percs[5] = {0.01, 0.1, 1, 10, 20};
// uint64_t leq_range_sizes[5] = {0, 0, 0, 0, 0};
// uint64_t geq_range_sizes[5] = {0, 0, 0, 0, 0};
// uint64_t leq_ints[5] = {0, 0, 0, 0, 0};
// uint64_t geq_ints[5] = {0, 0, 0, 0, 0};
// for (uint64_t i = 0; i < m - 1; ++i) {
// uint64_t end = it.next();
// uint64_t range = end - begin;
// if (range) {
// for (uint32_t i = 0; i < 5; ++i) {
// if (range <= max * percs[i] / 100) {
// ++leq_range_sizes[i];
// leq_ints[i] += range;
// } else {
// ++geq_range_sizes[i];
// geq_ints[i] += range;
// }
// }
// }
// begin = end;
// }
// for (uint32_t i = 0; i < 5; ++i) {
// std::cout << "\t=========================================================================" << std::endl;
// std::cout << "\tnum of ranges whose length is <= " << percs[i]
// << "% of max range (" << max * percs[i] / 100 << ") = "
// << leq_range_sizes[i] << " (" << leq_range_sizes[i] * 100.0 / non_null_ranges << "%)" << std::endl;
// std::cout << "\tnumber of ints belonging to such ranges = " << leq_ints[i]
// << " (" << leq_ints[i] * 100.0 / next_order_num_grams << "%)" << std::endl;
// std::cout << "\tnum of ranges whose length is > " << percs[i]
// << "% of max range (" << max * percs[i] / 100 << ") = "
// << geq_range_sizes[i] << " (" << geq_range_sizes[i] * 100.0 / non_null_ranges << "%)" << std::endl;
// std::cout << "\tnumber of ints belonging to such ranges = " << geq_ints[i]
// << " (" << geq_ints[i] * 100.0 / next_order_num_grams << "%)" << std::endl;
// }
// }
}
if (order == 2 || order == 3)
{
std::unordered_map<uint32_t, uint32_t> occs;
auto pointers_it = ranges->begin();
uint64_t m = ranges->size();
uint64_t begin = pointers_it.next();
uint64_t prev_upper = 0;
auto grams_it = m_grams.begin();
auto occs_end = occs.end();
double H_1 = 0.0;
for (uint64_t i = 0; i < m - 1; ++i) {
uint64_t end = pointers_it.next();
uint64_t range = end - begin;
if (range) {
H_1 += range * std::log2(range);
}
for (uint64_t j = 0; j < range; ++j) {
uint64_t v = grams_it.next();
uint64_t original_v = v - prev_upper;
if (occs.find(original_v) != occs_end) {
++occs[original_v];
} else {
occs.emplace(original_v, 1);
}
if (j == range - 1) {
prev_upper = v;
}
}
begin = end;
}
H_1 /= n;
double H_0 = 0.0;
for (auto const& pair: occs) {
uint32_t occ = pair.second;
H_0 += occ * std::log2(double(n) / occ);
}
H_0 /= n;
if (order == 2) {
std::cout << "\tH_0 = " << H_0 / 8 << " bytes" << std::endl;
std::cout << "\tH_1 = " << H_1 / 8 << " bytes" << std::endl;
}
if (order == 3) {
std::cout << "\tH_2 = " << H_1 / 8 << " bytes" << std::endl;
}
}
}
template<typename Vocabulary,
typename Mapper,
typename Values,
typename Ranks,
typename Grams,
typename Pointers>
void trie_count_lm<Vocabulary,
Mapper,
Values,
Ranks,
Grams,
Pointers>::print_stats(size_t bytes) const
{
util::logger("========= TRIE_COUNT_LM statistics =========");
uint64_t i = 1;
uint64_t grams_bytes = 0;
uint64_t counts_ranks_bytes = 0;
uint64_t pointers_bytes = 0;
for (auto const& a: m_arrays) {
std::cout << i << "-grams bytes:\n";
uint64_t x = a.grams_bytes();
uint64_t y = a.counts_ranks_bytes();
uint64_t z = a.pointers_bytes();
uint64_t n = a.size();
if (i != 1) {
std::cout << "\tgrams: " << x << " (" << double(x) / n << " per gram)\n";
}
std::cout << "\tranks: " << y << " (" << double(y) / n << " per gram)\n";
if (i != order()) {
std::cout << "\tpointers: " << z << " (" << double(z) / n << " per gram)" << std::endl;
}
++i;
grams_bytes += x;
counts_ranks_bytes += y;
pointers_bytes += z;
}
uint64_t num_grams = size();
std::cout << "order: " << order() << "\n";
std::cout << "num. of grams: " << num_grams << "\n";
std::cout << "tot. bytes: " << bytes << "\n";
std::cout << "bytes per gram: " << double(bytes) / num_grams << "\n";
std::cout << "vocabulary data bytes: " << m_vocab.data_bytes() << "\n";
std::cout << "\t(does NOT include hash function bytes)\n";
std::cout << "unique values bytes: " << m_distinct_counts.bytes() << "\n";
std::cout << "tot. grams bytes: " << grams_bytes << " (" << grams_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(grams_bytes) / num_grams << "\n";
std::cout << "tot. ranks bytes: " << counts_ranks_bytes << " (" << counts_ranks_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(counts_ranks_bytes) / num_grams << "\n";
std::cout << "tot. pointers bytes: " << pointers_bytes << " (" << pointers_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(pointers_bytes) / num_grams << std::endl;
std::cout << "number of unique values:\n";
for (uint8_t i = 0; i < m_order; ++i) {
std::cout << "\t" << i + 1 << "-grams: " << m_distinct_counts.size(i) << std::endl;
}
std::cout << std::endl;
std::cout << "trie level statistics:\n";
for (uint8_t i = 0; i < m_order; ++i) {
uint8_t order = i + 1;
std::cout << "\t" << uint32_t(order) << "-grams:\n";
m_arrays[i].print_stats(order, i ? m_arrays[i - 1].ptrs() : nullptr);
std::cout << std::endl;
}
}
template<typename Vocabulary,
typename Mapper,
typename Values,
typename Ranks,
typename Grams,
typename Pointers>
void trie_prob_lm<Vocabulary,
Mapper,
Values,
Ranks,
Grams,
Pointers>::print_stats(size_t bytes) const
{
util::logger("========= TRIE_PROB_LM statistics =========");
uint64_t i = 1;
uint64_t grams_bytes = 0;
uint64_t probs_backoffs_ranks_bytes = 0;
uint64_t pointers_bytes = 0;
for (auto const& a: m_arrays) {
std::cout << i << "-grams bytes:\n";
uint64_t x = a.grams_bytes();
uint64_t y = a.probs_backoffs_ranks_bytes();
uint64_t z = a.pointers_bytes();
std::cout << "\tgrams: " << x << "\n";
std::cout << "\tprob/backoff ranks: " << y << "\n";
std::cout << "\tpointers: " << z << std::endl;
++i;
grams_bytes += x;
probs_backoffs_ranks_bytes += y;
pointers_bytes += z;
}
uint64_t num_grams = size();
std::cout << "order: " << order() << "\n";
std::cout << "num. of grams: " << num_grams << "\n";
std::cout << "tot. bytes: " << bytes << "\n";
std::cout << "bytes per gram: " << double(bytes) / num_grams << "\n";
std::cout << "vocabulary data bytes: " << m_vocab.data_bytes() << "\n";
std::cout << "\t(does NOT include hash function bytes)\n";
std::cout << "probs averages bytes: " << m_probs_averages.bytes() << "\n";
std::cout << "probs backoffs bytes: " << m_backoffs_averages.bytes() << "\n";
std::cout << "tot. grams bytes: " << grams_bytes << " (" << grams_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(grams_bytes) / num_grams << "\n";
std::cout << "tot. probs/backoffs bytes: " << probs_backoffs_ranks_bytes << " (" << probs_backoffs_ranks_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(probs_backoffs_ranks_bytes) / num_grams << "\n";
std::cout << "tot. pointers bytes: " << pointers_bytes << " (" << pointers_bytes * 100.0 / bytes << "%)\n"
<< "\tper gram: " << double(pointers_bytes) / num_grams << std::endl;
std::cout << "trie level statistics:\n";
for (uint8_t i = 0; i < m_order; ++i) {
uint8_t order = i + 1;
std::cout << "\t" << uint32_t(order) << "-grams:\n";
m_arrays[i].print_stats(order, i ? m_arrays[i - 1].ptrs() : nullptr);
std::cout << std::endl;
}
}
}
| 41.530892 | 144 | 0.432421 | [
"vector"
] |
4f9f9a5f1c32e5ecaa93eca88f930f5f83325e26 | 26,659 | cpp | C++ | drape_frontend/route_renderer.cpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | null | null | null | drape_frontend/route_renderer.cpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | 1 | 2018-06-27T11:44:23.000Z | 2018-06-28T10:51:48.000Z | drape_frontend/route_renderer.cpp | Barysman/omim | 469632c879027ec38278ebda699415c28dbd79e0 | [
"Apache-2.0"
] | null | null | null | #include "drape_frontend/route_renderer.hpp"
#include "drape_frontend/message_subclasses.hpp"
#include "drape_frontend/shader_def.hpp"
#include "drape_frontend/shape_view_params.hpp"
#include "drape_frontend/visual_params.hpp"
#include "drape/glsl_func.hpp"
#include "drape/utils/projection.hpp"
#include "drape/vertex_array_buffer.hpp"
#include "indexer/scales.hpp"
#include "base/logging.hpp"
#include <algorithm>
#include <cmath>
namespace df
{
std::string const kRouteColor = "Route";
std::string const kRouteOutlineColor = "RouteOutline";
std::string const kRoutePedestrian = "RoutePedestrian";
std::string const kRouteBicycle = "RouteBicycle";
std::string const kRoutePreview = "RoutePreview";
std::string const kRouteMaskCar = "RouteMaskCar";
std::string const kRouteArrowsMaskCar = "RouteArrowsMaskCar";
std::string const kRouteMaskBicycle = "RouteMaskBicycle";
std::string const kRouteArrowsMaskBicycle = "RouteArrowsMaskBicycle";
std::string const kRouteMaskPedestrian = "RouteMaskPedestrian";
// TODO(@darina) Use separate colors.
std::string const kTransitOutlineColor = "RouteMarkPrimaryTextOutline";
namespace
{
std::vector<float> const kPreviewPointRadiusInPixel =
{
// 1 2 3 4 5 6 7 8 9 10
0.8f, 0.8f, 0.8f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f,
//11 12 13 14 15 16 17 18 19 20
2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 3.5f, 4.5f, 4.5f, 4.5f, 5.5f
};
int const kArrowAppearingZoomLevel = 14;
int const kInvalidGroup = -1;
uint32_t const kPreviewPointsCount = 512;
double const kInvalidDistance = -1.0;
void InterpolateByZoom(SubrouteConstPtr const & subroute, ScreenBase const & screen,
float & halfWidth, double & zoom)
{
int index = 0;
float lerpCoef = 0.0f;
ExtractZoomFactors(screen, zoom, index, lerpCoef);
std::vector<float> const * halfWidthInPixel = &kRouteHalfWidthInPixelOthers;
if (subroute->m_routeType == RouteType::Car || subroute->m_routeType == RouteType::Taxi)
halfWidthInPixel = &kRouteHalfWidthInPixelCar;
else if (subroute->m_routeType == RouteType::Transit)
halfWidthInPixel = &kRouteHalfWidthInPixelTransit;
halfWidth = InterpolateByZoomLevels(index, lerpCoef, *halfWidthInPixel);
halfWidth *= static_cast<float>(df::VisualParams::Instance().GetVisualScale());
}
float CalculateRadius(ScreenBase const & screen)
{
double zoom = 0.0;
int index = 0;
float lerpCoef = 0.0f;
ExtractZoomFactors(screen, zoom, index, lerpCoef);
float const radius = InterpolateByZoomLevels(index, lerpCoef, kPreviewPointRadiusInPixel);
return radius * static_cast<float>(VisualParams::Instance().GetVisualScale());
}
void ClipBorders(std::vector<ArrowBorders> & borders)
{
auto invalidBorders = [](ArrowBorders const & arrowBorders)
{
return arrowBorders.m_groupIndex == kInvalidGroup;
};
borders.erase(std::remove_if(borders.begin(), borders.end(), invalidBorders), borders.end());
}
void MergeAndClipBorders(std::vector<ArrowBorders> & borders)
{
// Initial clipping.
ClipBorders(borders);
if (borders.empty())
return;
// Mark groups.
for (size_t i = 0; i + 1 < borders.size(); i++)
{
if (borders[i].m_endDistance >= borders[i + 1].m_startDistance)
borders[i + 1].m_groupIndex = borders[i].m_groupIndex;
}
// Merge groups.
int lastGroup = borders.front().m_groupIndex;
size_t lastGroupIndex = 0;
for (size_t i = 1; i < borders.size(); i++)
{
if (borders[i].m_groupIndex != lastGroup)
{
borders[lastGroupIndex].m_endDistance = borders[i - 1].m_endDistance;
lastGroupIndex = i;
lastGroup = borders[i].m_groupIndex;
}
else
{
borders[i].m_groupIndex = kInvalidGroup;
}
}
borders[lastGroupIndex].m_endDistance = borders.back().m_endDistance;
// Clip groups.
ClipBorders(borders);
}
bool AreEqualArrowBorders(std::vector<ArrowBorders> const & borders1,
std::vector<ArrowBorders> const & borders2)
{
if (borders1.size() != borders2.size())
return false;
for (size_t i = 0; i < borders1.size(); i++)
{
if (borders1[i].m_groupIndex != borders2[i].m_groupIndex)
return false;
}
double const kDistanceEps = 1e-5;
for (size_t i = 0; i < borders1.size(); i++)
{
if (fabs(borders1[i].m_startDistance - borders2[i].m_startDistance) > kDistanceEps)
return false;
if (fabs(borders1[i].m_endDistance - borders2[i].m_endDistance) > kDistanceEps)
return false;
}
return true;
}
std::vector<ArrowBorders> CalculateArrowBorders(ScreenBase const & screen, float currentHalfWidth,
RouteRenderer::SubrouteInfo const & subrouteInfo,
double distanceFromBegin)
{
auto const & turns = subrouteInfo.m_subroute->m_turns;
if (turns.empty())
return {};
// Calculate arrow mercator length.
double glbHalfLen = 0.5 * kArrowSize;
double const glbHalfTextureWidth = currentHalfWidth * kArrowHeightFactor * screen.GetScale();
double const glbHalfTextureLen = glbHalfTextureWidth * kArrowAspect;
if (glbHalfLen < glbHalfTextureLen)
glbHalfLen = glbHalfTextureLen;
double const glbArrowHead = 2.0 * kArrowHeadSize * glbHalfTextureLen;
double const glbArrowTail = 2.0 * kArrowTailSize * glbHalfTextureLen;
double const glbMinArrowSize = glbArrowHead + glbArrowTail;
double const kExtendCoef = 1.1;
m2::RectD screenRect = screen.ClipRect();
screenRect.Scale(kExtendCoef);
// Calculate arrow borders.
std::vector<ArrowBorders> newArrowBorders;
newArrowBorders.reserve(turns.size());
auto const & polyline = subrouteInfo.m_subroute->m_polyline;
for (size_t i = 0; i < turns.size(); i++)
{
ArrowBorders arrowBorders;
arrowBorders.m_groupIndex = static_cast<int>(i);
arrowBorders.m_startDistance = std::max(0.0, turns[i] - glbHalfLen * 0.8);
arrowBorders.m_endDistance = std::min(subrouteInfo.m_length, turns[i] + glbHalfLen * 1.2);
if ((arrowBorders.m_endDistance - arrowBorders.m_startDistance) < glbMinArrowSize ||
arrowBorders.m_startDistance < distanceFromBegin)
{
continue;
}
m2::PointD pt = polyline.GetPointByDistance(arrowBorders.m_startDistance);
if (screenRect.IsPointInside(pt))
{
newArrowBorders.push_back(arrowBorders);
continue;
}
pt = polyline.GetPointByDistance(arrowBorders.m_endDistance);
if (screenRect.IsPointInside(pt))
{
newArrowBorders.push_back(arrowBorders);
continue;
}
}
// Merge intersected borders and clip them.
MergeAndClipBorders(newArrowBorders);
// Process head and tail.
for (ArrowBorders & borders : newArrowBorders)
{
borders.m_startDistance += glbArrowTail;
borders.m_endDistance -= glbArrowHead;
}
return newArrowBorders;
}
void BuildBuckets(RouteRenderProperty const & renderProperty, ref_ptr<dp::GpuProgramManager> mng)
{
for (auto const & bucket : renderProperty.m_buckets)
bucket->GetBuffer()->Build(mng->GetProgram(renderProperty.m_state.GetProgramIndex()));
}
RouteRenderer::Subroutes::iterator FindSubroute(RouteRenderer::Subroutes & subroutes,
dp::DrapeID subrouteId)
{
return std::find_if(subroutes.begin(), subroutes.end(),
[&subrouteId](RouteRenderer::SubrouteInfo const & info)
{
return info.m_subrouteId == subrouteId;
});
}
float GetCurrentHalfWidth(df::RouteRenderer::SubrouteInfo const & subrouteInfo)
{
if (subrouteInfo.m_subroute->m_maxPixelWidth < 0.0f)
return subrouteInfo.m_baseHalfWidth;
return std::min(subrouteInfo.m_baseHalfWidth, subrouteInfo.m_subroute->m_maxPixelWidth * 0.5f);
}
} // namespace
RouteRenderer::RouteRenderer(PreviewPointsRequestCallback && previewPointsRequest)
: m_distanceFromBegin(kInvalidDistance)
, m_followingEnabled(false)
, m_previewPointsRequest(std::move(previewPointsRequest))
, m_waitForPreviewRenderData(false)
{
ASSERT(m_previewPointsRequest != nullptr, ());
}
void RouteRenderer::UpdateRoute(ScreenBase const & screen, CacheRouteArrowsCallback const & callback)
{
ASSERT(callback != nullptr, ());
for (auto & subrouteInfo : m_subroutes)
{
// Interpolate values by zoom level.
double zoom = 0.0;
float halfWidth = 0.0;
InterpolateByZoom(subrouteInfo.m_subroute, screen, halfWidth, zoom);
subrouteInfo.m_baseHalfWidth = halfWidth;
if (zoom < kArrowAppearingZoomLevel)
{
subrouteInfo.m_arrowsData.reset();
subrouteInfo.m_arrowBorders.clear();
continue;
}
// Calculate arrow borders.
double dist = kInvalidDistance;
if (m_followingEnabled)
dist = m_distanceFromBegin - subrouteInfo.m_subroute->m_baseDistance;
auto newArrowBorders = CalculateArrowBorders(screen, halfWidth, subrouteInfo, dist);
if (newArrowBorders.empty())
{
// Clear arrows.
subrouteInfo.m_arrowsData.reset();
subrouteInfo.m_arrowBorders.clear();
}
else if (!AreEqualArrowBorders(newArrowBorders, subrouteInfo.m_arrowBorders))
{
subrouteInfo.m_arrowBorders = std::move(newArrowBorders);
callback(subrouteInfo.m_subrouteId, subrouteInfo.m_arrowBorders);
}
}
}
void RouteRenderer::UpdatePreview(ScreenBase const & screen)
{
// Check if there are preview render data.
if (m_previewRenderData.empty() && !m_waitForPreviewRenderData)
{
m_previewPointsRequest(kPreviewPointsCount);
m_waitForPreviewRenderData = true;
}
if (m_waitForPreviewRenderData)
return;
float previewCircleRadius = 0.0;
if (!m_previewSegments.empty())
{
ClearPreviewHandles();
m_previewPivot = screen.GlobalRect().Center();
previewCircleRadius = CalculateRadius(screen);
}
double const currentScaleGtoP = 1.0 / screen.GetScale();
double const radiusMercator = previewCircleRadius / currentScaleGtoP;
double const diameterMercator = 2.0 * radiusMercator;
double const gapMercator = diameterMercator;
dp::Color const circleColor = df::GetColorConstant(kRoutePreview);
for (auto const & previewSegment : m_previewSegments)
{
auto const & info = previewSegment.second;
m2::PolylineD polyline = {info.m_startPoint, info.m_finishPoint};
double const segmentLen = polyline.GetLength();
auto circlesCount = static_cast<size_t>(segmentLen / (diameterMercator + gapMercator));
if (circlesCount == 0)
circlesCount = 1;
double const distDelta = segmentLen / circlesCount;
for (double d = distDelta * 0.5; d < segmentLen; d += distDelta)
{
m2::PointD const pt = polyline.GetPointByDistance(d);
m2::RectD const circleRect(pt.x - radiusMercator, pt.y - radiusMercator,
pt.x + radiusMercator, pt.y + radiusMercator);
if (!screen.ClipRect().IsIntersect(circleRect))
continue;
size_t pointIndex;
CirclesPackHandle * h = GetPreviewHandle(pointIndex);
if (h == nullptr)
{
// There is no any available handle.
m_previewPointsRequest(kPreviewPointsCount);
m_waitForPreviewRenderData = true;
return;
}
m2::PointD const convertedPt = MapShape::ConvertToLocal(pt, m_previewPivot, kShapeCoordScalar);
h->SetPoint(pointIndex, convertedPt, previewCircleRadius, circleColor);
}
}
}
void RouteRenderer::ClearPreviewHandles()
{
for (auto & handle : m_previewHandlesCache)
{
handle.first->Clear();
handle.second = 0;
}
}
CirclesPackHandle * RouteRenderer::GetPreviewHandle(size_t & index)
{
for (auto & handle : m_previewHandlesCache)
{
if (handle.second < handle.first->GetPointsCount())
{
index = handle.second++;
return handle.first;
}
}
index = 0;
return nullptr;
}
dp::Color RouteRenderer::GetMaskColor(RouteType routeType, double baseDistance,
bool arrows) const
{
if (baseDistance != 0.0 && m_distanceFromBegin < baseDistance)
{
if (routeType == RouteType::Car)
return GetColorConstant(arrows ? kRouteArrowsMaskCar : kRouteMaskCar);
if (routeType == RouteType::Bicycle)
return GetColorConstant(arrows ? kRouteArrowsMaskBicycle : kRouteMaskBicycle);
if (routeType == RouteType::Pedestrian)
return GetColorConstant(kRouteMaskPedestrian);
}
return {0, 0, 0, 0};
}
void RouteRenderer::RenderSubroute(SubrouteInfo const & subrouteInfo, size_t subrouteDataIndex,
ScreenBase const & screen, bool trafficShown,
ref_ptr<dp::GpuProgramManager> mng,
dp::UniformValuesStorage const & commonUniforms)
{
ASSERT_LESS(subrouteDataIndex, subrouteInfo.m_subrouteData.size(), ());
if (subrouteInfo.m_subrouteData[subrouteDataIndex]->m_renderProperty.m_buckets.empty())
return;
// Skip rendering of hidden subroutes.
if (m_hiddenSubroutes.find(subrouteInfo.m_subrouteId) != m_hiddenSubroutes.end())
return;
auto const & subrouteData = subrouteInfo.m_subrouteData[subrouteDataIndex];
float const currentHalfWidth = GetCurrentHalfWidth(subrouteInfo);
auto const screenHalfWidth = static_cast<float>(currentHalfWidth * screen.GetScale());
auto dist = static_cast<float>(kInvalidDistance);
if (m_followingEnabled)
{
auto const distanceOffset = subrouteInfo.m_subroute->m_baseDistance + subrouteData->m_distanceOffset;
dist = static_cast<float>(m_distanceFromBegin - distanceOffset);
}
dp::GLState const & state = subrouteData->m_renderProperty.m_state;
size_t const styleIndex = subrouteData->m_styleIndex;
ASSERT_LESS(styleIndex, subrouteInfo.m_subroute->m_style.size(), ());
auto const & style = subrouteInfo.m_subroute->m_style[styleIndex];
// Set up uniforms.
dp::UniformValuesStorage uniforms = commonUniforms;
math::Matrix<float, 4, 4> mv = screen.GetModelView(subrouteData->m_pivot, kShapeCoordScalar);
uniforms.SetMatrix4x4Value("modelView", mv.m_data);
glsl::vec4 const color = glsl::ToVec4(df::GetColorConstant(style.m_color));
uniforms.SetFloatValue("u_color", color.r, color.g, color.b, color.a);
uniforms.SetFloatValue("u_routeParams", currentHalfWidth, screenHalfWidth, dist,
trafficShown ? 1.0f : 0.0f);
glsl::vec4 const maskColor = glsl::ToVec4(GetMaskColor(subrouteData->m_subroute->m_routeType,
subrouteData->m_subroute->m_baseDistance,
false /* arrows */));
uniforms.SetFloatValue("u_maskColor", maskColor.r, maskColor.g, maskColor.b, maskColor.a);
if (style.m_pattern.m_isDashed)
{
uniforms.SetFloatValue("u_pattern",
static_cast<float>(screenHalfWidth * style.m_pattern.m_dashLength),
static_cast<float>(screenHalfWidth * style.m_pattern.m_gapLength));
}
else
{
glsl::vec4 const outlineColor = glsl::ToVec4(df::GetColorConstant(style.m_outlineColor));
uniforms.SetFloatValue("u_outlineColor", outlineColor.r, outlineColor.g,
outlineColor.b, outlineColor.a);
}
// Set up shaders and apply uniforms.
ref_ptr<dp::GpuProgram> prg = mng->GetProgram(style.m_pattern.m_isDashed ?
gpu::ROUTE_DASH_PROGRAM : gpu::ROUTE_PROGRAM);
prg->Bind();
dp::ApplyState(state, prg);
dp::ApplyUniforms(uniforms, prg);
// Render buckets.
for (auto const & bucket : subrouteData->m_renderProperty.m_buckets)
bucket->Render(state.GetDrawAsLine());
}
void RouteRenderer::RenderSubrouteArrows(SubrouteInfo const & subrouteInfo,
ScreenBase const & screen,
ref_ptr<dp::GpuProgramManager> mng,
dp::UniformValuesStorage const & commonUniforms)
{
if (subrouteInfo.m_arrowsData == nullptr ||
subrouteInfo.m_arrowsData->m_renderProperty.m_buckets.empty() ||
m_hiddenSubroutes.find(subrouteInfo.m_subrouteId) != m_hiddenSubroutes.end())
{
return;
}
dp::GLState const & state = subrouteInfo.m_arrowsData->m_renderProperty.m_state;
float const currentHalfWidth = GetCurrentHalfWidth(subrouteInfo);
// Set up shaders and apply common uniforms.
dp::UniformValuesStorage uniforms = commonUniforms;
math::Matrix<float, 4, 4> mv = screen.GetModelView(subrouteInfo.m_arrowsData->m_pivot,
kShapeCoordScalar);
uniforms.SetMatrix4x4Value("modelView", mv.m_data);
auto const arrowHalfWidth = static_cast<float>(currentHalfWidth * kArrowHeightFactor);
uniforms.SetFloatValue("u_arrowHalfWidth", arrowHalfWidth);
uniforms.SetFloatValue("u_opacity", 1.0f);
glsl::vec4 const maskColor = glsl::ToVec4(GetMaskColor(subrouteInfo.m_subroute->m_routeType,
subrouteInfo.m_subroute->m_baseDistance,
true /* arrows */));
uniforms.SetFloatValue("u_maskColor", maskColor.r, maskColor.g, maskColor.b, maskColor.a);
ref_ptr<dp::GpuProgram> prg = mng->GetProgram(gpu::ROUTE_ARROW_PROGRAM);
prg->Bind();
dp::ApplyState(state, prg);
dp::ApplyUniforms(uniforms, prg);
for (auto const & bucket : subrouteInfo.m_arrowsData->m_renderProperty.m_buckets)
bucket->Render(state.GetDrawAsLine());
}
void RouteRenderer::RenderSubrouteMarkers(SubrouteInfo const & subrouteInfo, ScreenBase const & screen,
ref_ptr<dp::GpuProgramManager> mng,
dp::UniformValuesStorage const & commonUniforms)
{
if (subrouteInfo.m_markersData == nullptr ||
subrouteInfo.m_markersData->m_renderProperty.m_buckets.empty() ||
m_hiddenSubroutes.find(subrouteInfo.m_subrouteId) != m_hiddenSubroutes.end())
{
return;
}
auto dist = static_cast<float>(kInvalidDistance);
if (m_followingEnabled)
dist = static_cast<float>(m_distanceFromBegin - subrouteInfo.m_subroute->m_baseDistance);
dp::GLState const & state = subrouteInfo.m_markersData->m_renderProperty.m_state;
float const currentHalfWidth = GetCurrentHalfWidth(subrouteInfo);
// Set up shaders and apply common uniforms.
dp::UniformValuesStorage uniforms = commonUniforms;
math::Matrix<float, 4, 4> mv = screen.GetModelView(subrouteInfo.m_markersData->m_pivot,
kShapeCoordScalar);
uniforms.SetMatrix4x4Value("modelView", mv.m_data);
uniforms.SetFloatValue("u_routeParams", currentHalfWidth, dist);
uniforms.SetFloatValue("u_opacity", 1.0f);
uniforms.SetFloatValue("u_angleCosSin",
static_cast<float>(cos(screen.GetAngle())),
static_cast<float>(sin(screen.GetAngle())));
glsl::vec4 const maskColor = glsl::ToVec4(GetMaskColor(subrouteInfo.m_subroute->m_routeType,
subrouteInfo.m_subroute->m_baseDistance,
false /* arrows */));
uniforms.SetFloatValue("u_maskColor", maskColor.r, maskColor.g, maskColor.b, maskColor.a);
ref_ptr<dp::GpuProgram> prg = mng->GetProgram(gpu::ROUTE_MARKER_PROGRAM);
prg->Bind();
dp::ApplyState(state, prg);
dp::ApplyUniforms(uniforms, prg);
for (auto const & bucket : subrouteInfo.m_markersData->m_renderProperty.m_buckets)
bucket->Render(state.GetDrawAsLine());
}
void RouteRenderer::RenderPreviewData(ScreenBase const & screen, ref_ptr<dp::GpuProgramManager> mng,
dp::UniformValuesStorage const & commonUniforms)
{
if (m_waitForPreviewRenderData || m_previewSegments.empty() || m_previewRenderData.empty())
return;
dp::UniformValuesStorage uniforms = commonUniforms;
math::Matrix<float, 4, 4> mv = screen.GetModelView(m_previewPivot, kShapeCoordScalar);
uniforms.SetMatrix4x4Value("modelView", mv.m_data);
uniforms.SetFloatValue("u_opacity", 1.0f);
ref_ptr<dp::GpuProgram> program = mng->GetProgram(gpu::CIRCLE_POINT_PROGRAM);
program->Bind();
dp::GLState const & state = m_previewRenderData.front()->m_state;
dp::ApplyState(state, program);
dp::ApplyUniforms(uniforms, program);
ASSERT_EQUAL(m_previewRenderData.size(), m_previewHandlesCache.size(), ());
for (size_t i = 0; i < m_previewRenderData.size(); i++)
{
if (m_previewHandlesCache[i].second != 0)
m_previewRenderData[i]->m_bucket->Render(state.GetDrawAsLine());
}
}
void RouteRenderer::RenderRoute(ScreenBase const & screen, bool trafficShown,
ref_ptr<dp::GpuProgramManager> mng,
dp::UniformValuesStorage const & commonUniforms)
{
for (auto const & subroute : m_subroutes)
{
// Render subroutes.
for (size_t i = 0; i < subroute.m_subrouteData.size(); ++i)
RenderSubroute(subroute, i, screen, trafficShown, mng, commonUniforms);
// Render markers.
RenderSubrouteMarkers(subroute, screen, mng, commonUniforms);
// Render arrows.
RenderSubrouteArrows(subroute, screen, mng, commonUniforms);
}
// Render preview.
RenderPreviewData(screen, mng, commonUniforms);
}
void RouteRenderer::AddSubrouteData(drape_ptr<SubrouteData> && subrouteData,
ref_ptr<dp::GpuProgramManager> mng)
{
auto const it = FindSubroute(m_subroutes, subrouteData->m_subrouteId);
if (it != m_subroutes.end())
{
if (!it->m_subrouteData.empty())
{
int const recacheId = it->m_subrouteData.front()->m_recacheId;
if (recacheId < subrouteData->m_recacheId)
{
// Remove obsolete subroute data.
it->m_subrouteData.clear();
it->m_markersData.reset();
it->m_arrowsData.reset();
it->m_arrowBorders.clear();
it->m_subroute = subrouteData->m_subroute;
it->m_subrouteId = subrouteData->m_subrouteId;
it->m_length = subrouteData->m_subroute->m_polyline.GetLength();
}
else if (recacheId > subrouteData->m_recacheId)
{
return;
}
}
it->m_subrouteData.push_back(std::move(subrouteData));
BuildBuckets(it->m_subrouteData.back()->m_renderProperty, mng);
}
else
{
// Add new subroute.
SubrouteInfo info;
info.m_subroute = subrouteData->m_subroute;
info.m_subrouteId = subrouteData->m_subrouteId;
info.m_length = subrouteData->m_subroute->m_polyline.GetLength();
info.m_subrouteData.push_back(std::move(subrouteData));
BuildBuckets(info.m_subrouteData.back()->m_renderProperty, mng);
m_subroutes.push_back(std::move(info));
std::sort(m_subroutes.begin(), m_subroutes.end(),
[](SubrouteInfo const & info1, SubrouteInfo const & info2)
{
return info1.m_subroute->m_baseDistance > info2.m_subroute->m_baseDistance;
});
}
}
void RouteRenderer::AddSubrouteArrowsData(drape_ptr<SubrouteArrowsData> && routeArrowsData,
ref_ptr<dp::GpuProgramManager> mng)
{
auto const it = FindSubroute(m_subroutes, routeArrowsData->m_subrouteId);
if (it != m_subroutes.end())
{
it->m_arrowsData = std::move(routeArrowsData);
BuildBuckets(it->m_arrowsData->m_renderProperty, mng);
}
}
void RouteRenderer::AddSubrouteMarkersData(drape_ptr<SubrouteMarkersData> && subrouteMarkersData,
ref_ptr<dp::GpuProgramManager> mng)
{
auto const it = FindSubroute(m_subroutes, subrouteMarkersData->m_subrouteId);
if (it != m_subroutes.end())
{
it->m_markersData = std::move(subrouteMarkersData);
BuildBuckets(it->m_markersData->m_renderProperty, mng);
}
}
RouteRenderer::Subroutes const & RouteRenderer::GetSubroutes() const
{
return m_subroutes;
}
void RouteRenderer::RemoveSubrouteData(dp::DrapeID subrouteId)
{
auto const it = FindSubroute(m_subroutes, subrouteId);
if (it != m_subroutes.end())
m_subroutes.erase(it);
}
void RouteRenderer::AddPreviewRenderData(drape_ptr<CirclesPackRenderData> && renderData,
ref_ptr<dp::GpuProgramManager> mng)
{
drape_ptr<CirclesPackRenderData> data = std::move(renderData);
ref_ptr<dp::GpuProgram> program = mng->GetProgram(gpu::CIRCLE_POINT_PROGRAM);
program->Bind();
data->m_bucket->GetBuffer()->Build(program);
m_previewRenderData.push_back(std::move(data));
m_waitForPreviewRenderData = false;
// Save handle in the cache.
auto & bucket = m_previewRenderData.back()->m_bucket;
ASSERT_EQUAL(bucket->GetOverlayHandlesCount(), 1, ());
auto handle = static_cast<CirclesPackHandle *>(bucket->GetOverlayHandle(0).get());
handle->Clear();
m_previewHandlesCache.emplace_back(std::make_pair(handle, 0));
}
void RouteRenderer::ClearObsoleteData(int currentRecacheId)
{
auto const functor = [¤tRecacheId](SubrouteInfo const & subrouteInfo)
{
return !subrouteInfo.m_subrouteData.empty() &&
subrouteInfo.m_subrouteData.front()->m_recacheId < currentRecacheId;
};
m_subroutes.erase(std::remove_if(m_subroutes.begin(), m_subroutes.end(), functor),
m_subroutes.end());
}
void RouteRenderer::Clear()
{
m_subroutes.clear();
m_distanceFromBegin = kInvalidDistance;
}
void RouteRenderer::ClearGLDependentResources()
{
// Here we clear only GL-dependent part of subroute data.
for (auto & subroute : m_subroutes)
{
subroute.m_subrouteData.clear();
subroute.m_markersData.reset();
subroute.m_arrowsData.reset();
subroute.m_arrowBorders.clear();
}
m_previewRenderData.clear();
m_previewHandlesCache.clear();
m_waitForPreviewRenderData = false;
}
void RouteRenderer::UpdateDistanceFromBegin(double distanceFromBegin)
{
m_distanceFromBegin = distanceFromBegin;
}
void RouteRenderer::SetFollowingEnabled(bool enabled)
{
m_followingEnabled = enabled;
}
void RouteRenderer::AddPreviewSegment(dp::DrapeID id, PreviewInfo && info)
{
m_previewSegments.insert(std::make_pair(id, std::move(info)));
}
void RouteRenderer::RemovePreviewSegment(dp::DrapeID id)
{
m_previewSegments.erase(id);
}
void RouteRenderer::RemoveAllPreviewSegments()
{
m_previewSegments.clear();
}
void RouteRenderer::SetSubrouteVisibility(dp::DrapeID id, bool isVisible)
{
if (isVisible)
m_hiddenSubroutes.erase(id);
else
m_hiddenSubroutes.insert(id);
}
bool RouteRenderer::HasTransitData() const
{
for (auto const & subroute : m_subroutes)
{
if (subroute.m_subroute->m_routeType == RouteType::Transit)
return true;
}
return false;
}
} // namespace df
| 35.309934 | 105 | 0.689786 | [
"render",
"vector"
] |
4fa11394bf379895a85d41790d37593e55430feb | 1,938 | hpp | C++ | search-generic/search/generic/debug.hpp | webis-de/heuristic-authorship-obfuscation | e98e976e931f3b7d739996f414fdcf9d58958dc1 | [
"Apache-2.0"
] | null | null | null | search-generic/search/generic/debug.hpp | webis-de/heuristic-authorship-obfuscation | e98e976e931f3b7d739996f414fdcf9d58958dc1 | [
"Apache-2.0"
] | null | null | null | search-generic/search/generic/debug.hpp | webis-de/heuristic-authorship-obfuscation | e98e976e931f3b7d739996f414fdcf9d58958dc1 | [
"Apache-2.0"
] | 1 | 2021-02-17T16:19:57.000Z | 2021-02-17T16:19:57.000Z | // debug.hpp -*- C++ -*-
// Copyright (C) 2014 Martin Trenkmann
#ifndef SEARCH_GENERIC_DEBUG_HPP
#define SEARCH_GENERIC_DEBUG_HPP
#include <algorithm>
#include <iostream>
#include <iterator>
#include <chrono>
#include <string>
namespace search {
namespace generic {
inline void Pause()
{
std::cout << "Press any key to continue" << std::endl;
std::cin.get();
}
template<typename T>
void Print(const T& object)
{
std::cout << "DEBUG " << object << '\n';
}
template<typename T>
void Print(const std::string& message, const T& object)
{
std::cout << "DEBUG " << message << " -> " << object << '\n';
}
inline void PrintNewline()
{
std::cout << '\n';
}
template<typename Sequence>
void PrintSequence(const std::string& message, const Sequence& sequence)
{
std::cout << "DEBUG " << message << " -> ";
const auto first = std::begin(sequence);
std::copy(first, std::end(sequence),
std::ostream_iterator<decltype(*first)>(std::cout, " "));
std::cout << '\n';
}
inline std::size_t timestamp()
{
return static_cast<std::size_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count());
}
} // namespace generic
} // namespace search
#ifdef DEBUG_OUTPUT_ENABLED
#define DEBUG_PAUSE() search::generic::Pause()
#define DEBUG_PRINT(MESSAGE) search::generic::Print(MESSAGE)
#define DEBUG_PRINT2(MESSAGE, OBJECT) search::generic::Print(MESSAGE, OBJECT)
#define DEBUG_PRINT_NEWLINE() search::generic::PrintNewline()
#define DEBUG_PRINT_SEQUENCE(MESSAGE, SEQUENCE) \
search::generic::PrintSequence(MESSAGE, SEQUENCE)
#else
#define DEBUG_PAUSE() ((void)0)
#define DEBUG_PRINT(MESSAGE) ((void)0)
#define DEBUG_PRINT2(MESSAGE, OBJECT) ((void)0)
#define DEBUG_PRINT_NEWLINE() ((void)0)
#define DEBUG_PRINT_SEQUENCE(MESSAGE, SEQUENCE) ((void)0)
#endif // DEBUG_OUTPUT_ENABLED
#endif // SEARCH_GENERIC_DEBUG_HPP
| 25.168831 | 85 | 0.688338 | [
"object"
] |
4fa461691be4e7402a57bb128d3d8bc8194ef581 | 12,531 | cc | C++ | tests/sfm/gtest_pose.cc | lemony-fresh/mve | d90cc2c813fef026f7732c5a26f6c15973a36042 | [
"BSD-3-Clause"
] | 1 | 2019-05-30T13:19:21.000Z | 2019-05-30T13:19:21.000Z | tests/sfm/gtest_pose.cc | MasterShockwave/mve | 7a96751db098bb6f5c0b4075921b0e8e43a69bb6 | [
"BSD-3-Clause"
] | null | null | null | tests/sfm/gtest_pose.cc | MasterShockwave/mve | 7a96751db098bb6f5c0b4075921b0e8e43a69bb6 | [
"BSD-3-Clause"
] | null | null | null | // Test cases for pose estimation.
// Written by Simon Fuhrmann.
#include <gtest/gtest.h>
#include "math/matrix_tools.h"
#include "math/matrix_svd.h"
#include "sfm/camera_pose.h"
#include "sfm/fundamental.h"
#include "sfm/ransac.h"
#include "sfm/ransac_fundamental.h"
#include "sfm/triangulate.h"
#include "sfm/correspondence.h"
TEST(PoseTest, PointNormalization1)
{
// Normalization of 3 points.
math::Matrix<float, 3, 3> set;
set(0,0) = 5.0f; set(1,0) = 5.0f; set(2,0) = 1.0f;
set(0,1) = -5.0f; set(1,1) = -1.0f; set(2,1) = 1.0f;
set(0,2) = 0.0f; set(1,2) = 0.0f; set(2,2) = 1.0f;
math::Matrix<float, 3, 3> trans;
sfm::compute_normalization(set, &trans);
EXPECT_NEAR(trans[0], 0.1f, 1e-6f);
EXPECT_NEAR(trans[1], 0.0f, 1e-6f);
EXPECT_NEAR(trans[2], 0.0f, 1e-6f);
EXPECT_NEAR(trans[3], 0.0f, 1e-6f);
EXPECT_NEAR(trans[4], 0.1f, 1e-6f);
EXPECT_NEAR(trans[5], -(5.0f + -1.0f + 0.0f)/3.0f/10.0f, 1e-6f);
EXPECT_NEAR(trans[6], 0.0f, 1e-6f);
EXPECT_NEAR(trans[7], 0.0f, 1e-6f);
EXPECT_NEAR(trans[8], 1.0f, 1e-6f);
}
TEST(PoseTest, PointNormalization2)
{
// Normalization of 2 points.
math::Matrix<double, 3, 2> set;
set(0,0) = -4.0; set(1,0) = 8.0; set(2,0) = 1.0f;
set(0,1) = -5.0; set(1,1) = 10.0f; set(2,1) = 1.0f;
math::Matrix<double, 3, 3> trans;
sfm::compute_normalization(set, &trans);
EXPECT_NEAR(trans[0], 0.5, 1e-6);
EXPECT_NEAR(trans[1], 0.0, 1e-6);
EXPECT_NEAR(trans[2], 4.5/2.0, 1e-6);
EXPECT_NEAR(trans[3], 0.0, 1e-6);
EXPECT_NEAR(trans[4], 0.5, 1e-6);
EXPECT_NEAR(trans[5], -9.0/2.0, 1e-6);
EXPECT_NEAR(trans[6], 0.0, 1e-6);
EXPECT_NEAR(trans[7], 0.0, 1e-6);
EXPECT_NEAR(trans[8], 1.0, 1e-6);
}
namespace
{
void
fill_golden_correspondences(sfm::Eight2DPoints& p1,
sfm::Eight2DPoints& p2, sfm::FundamentalMatrix& F)
{
p1(0, 0) = 45; p1(1, 0) = 210; p1(2, 0) = 1;
p1(0, 1) = 253; p1(1, 1) = 211; p1(2, 1) = 1;
p1(0, 2) = 154; p1(1, 2) = 188; p1(2, 2) = 1;
p1(0, 3) = 27; p1(1, 3) = 37; p1(2, 3) = 1;
p1(0, 4) = 209; p1(1, 4) = 164; p1(2, 4) = 1;
p1(0, 5) = 33; p1(1, 5) = 77; p1(2, 5) = 1;
p1(0, 6) = 93; p1(1, 6) = 58; p1(2, 6) = 1;
p1(0, 7) = 66; p1(1, 7) = 75; p1(2, 7) = 1;
p2(0, 0) = 87; p2(1, 0) = 216; p2(2, 0) = 1;
p2(0, 1) = 285; p2(1, 1) = 216; p2(2, 1) = 1;
p2(0, 2) = 188; p2(1, 2) = 194; p2(2, 2) = 1;
p2(0, 3) = 51; p2(1, 3) = 49; p2(2, 3) = 1;
p2(0, 4) = 234; p2(1, 4) = 171; p2(2, 4) = 1;
p2(0, 5) = 56; p2(1, 5) = 88; p2(2, 5) = 1;
p2(0, 6) = 114; p2(1, 6) = 69; p2(2, 6) = 1;
p2(0, 7) = 87; p2(1, 7) = 86; p2(2, 7) = 1;
F(0,0) = 0.000000014805557;
F(0,1) = 0.000002197550186;
F(0,2) = 0.001632934316777;
F(1,0) = -0.000002283909471;
F(1,1) = -0.000001354336179;
F(1,2) = 0.008734421917905;
F(2,0) = -0.001472308151103;
F(2,1) = -0.008375559378962;
F(2,2) = -0.160734037191207;
}
} // namespace
TEST(PoseTest, Test8Point)
{
/* Obtain golden correspondences and correct solution from Matlab. */
sfm::Eight2DPoints p1, p2;
sfm::FundamentalMatrix F2;
fill_golden_correspondences(p1, p2, F2);
/* The normalized 8-point algorithm (Hartley, Zisserman, 11.2):
* - Point set normalization (scaling, offset)
* - Matrix computation
* - Rank constraint enforcement
* - De-normalization of matrix
*/
math::Matrix<double, 3, 3> T1, T2;
sfm::compute_normalization(p1, &T1);
sfm::compute_normalization(p2, &T2);
p1 = T1 * p1;
p2 = T2 * p2;
sfm::FundamentalMatrix F(0.0);
sfm::fundamental_8_point(p1, p2, &F);
sfm::enforce_fundamental_constraints(&F);
F = T2.transposed() * F * T1;
// Force Fundamental matrices to the same scale.
F /= F(2,2);
F2 /= F2(2,2);
for (int i = 0; i < 9; ++i)
EXPECT_NEAR((F[i] - F2[i]) / (F[i] + F2[i]), 0.0, 0.05);
}
TEST(PoseTest, TestLeastSquaresPose)
{
/* Obtain golden correspondences and correct solution from Matlab. */
sfm::Eight2DPoints p1, p2;
sfm::FundamentalMatrix F2;
fill_golden_correspondences(p1, p2, F2);
math::Matrix<double, 3, 3> T1, T2;
sfm::compute_normalization(p1, &T1);
sfm::compute_normalization(p2, &T2);
p1 = T1 * p1;
p2 = T2 * p2;
sfm::Correspondences2D2D points(8);
for (int i = 0; i < 8; ++i)
{
points[i].p1[0] = p1(0, i);
points[i].p1[1] = p1(1, i);
points[i].p2[0] = p2(0, i);
points[i].p2[1] = p2(1, i);
}
sfm::FundamentalMatrix F(0.0);
sfm::fundamental_least_squares(points, &F);
sfm::enforce_fundamental_constraints(&F);
F = T2.transposed() * F * T1;
// Force Fundamental matrices to the same scale.
F /= F(2,2);
F2 /= F2(2,2);
for (int i = 0; i < 9; ++i)
EXPECT_NEAR((F[i] - F2[i]) / (F[i] + F2[i]), 0.0, 0.1);
}
namespace
{
void
fill_ground_truth_pose (sfm::CameraPose* pose1, sfm::CameraPose* pose2)
{
// Calibration with focal lenght 1 and 800x600 image.
// The first camera looks straight along the z axis.
if (pose1 != nullptr)
{
pose1->set_k_matrix(800, 800 / 2, 600 / 2);
math::matrix_set_identity(*pose1->R, 3);
pose1->t.fill(0.0);
}
// The second camera is at (1,0,0) and rotated 45deg to the left.
if (pose2 != nullptr)
{
pose2->set_k_matrix(800, 800 / 2, 600 / 2);
pose2->R.fill(0.0);
double const angle = MATH_PI / 4;
pose2->R(0,0) = std::cos(angle); pose2->R(0,2) = std::sin(angle);
pose2->R(1,1) = 1.0;
pose2->R(2,0) = -std::sin(angle); pose2->R(2,2) = std::cos(angle);
pose2->t.fill(0.0); pose2->t[0] = 1.0;
pose2->t = pose2->R * -pose2->t;
}
}
void
fill_eight_random_points (std::vector<math::Vec3d>* points)
{
points->push_back(math::Vec3d(-0.31, -0.42, 1.41));
points->push_back(math::Vec3d( 0.04, 0.01, 0.82));
points->push_back(math::Vec3d(-0.25, -0.24, 1.25));
points->push_back(math::Vec3d( 0.47, 0.22, 0.66));
points->push_back(math::Vec3d( 0.13, 0.03, 0.89));
points->push_back(math::Vec3d(-0.13, -0.46, 1.15));
points->push_back(math::Vec3d( 0.21, -0.23, 1.33));
points->push_back(math::Vec3d(-0.42, 0.38, 0.62));
}
} // namespace
TEST(PoseTest, SyntheticPoseTest1)
{
// This test computes from a given pose the fundamental matrix,
// then the essential matrix, then recovers the original pose.
sfm::CameraPose pose1, pose2;
fill_ground_truth_pose(&pose1, &pose2);
// Compute fundamental for pose.
sfm::FundamentalMatrix F;
sfm::fundamental_from_pose(pose1, pose2, &F);
// Compute essential from fundamental.
sfm::EssentialMatrix E = pose2.K.transposed() * F * pose1.K;
// Compute pose from essential.
std::vector<sfm::CameraPose> poses;
pose_from_essential(E, &poses);
// Check if one of the poses is the solution.
int num_equal_cameras = 0;
for (std::size_t i = 0; i < poses.size(); ++i)
{
bool equal = poses[i].R.is_similar(pose2.R, 1e-14)
&& poses[i].t.is_similar(pose2.t, 1e-14);
num_equal_cameras += equal;
}
EXPECT_EQ(num_equal_cameras, 1);
}
TEST(PoseTest, SyntheticPoseTest2)
{
// This test computes from a given pose eight corresponding pairs
// of 2D projections in the images. These correspondences are used
// to compute a fundamental matrix, then the essential matrix, then
// recovers the original pose.
sfm::CameraPose pose1, pose2;
fill_ground_truth_pose(&pose1, &pose2);
// Eight "random" 3D points.
std::vector<math::Vec3d> points3d;
fill_eight_random_points(&points3d);
// Re-project in images using ground truth pose.
math::Matrix<double, 3, 8> points2d_v1, points2d_v2;
for (int i = 0; i < 8; ++i)
{
math::Vec3d p1 = pose1.K * (pose1.R * points3d[i] + pose1.t);
math::Vec3d p2 = pose2.K * (pose2.R * points3d[i] + pose2.t);
p1 /= p1[2];
p2 /= p2[2];
for (int j = 0; j < 3; ++j)
{
points2d_v1(j, i) = p1[j];
points2d_v2(j, i) = p2[j];
}
}
// Compute fundamental using normalized 8-point algorithm.
math::Matrix<double, 3, 3> T1, T2;
sfm::compute_normalization(points2d_v1, &T1);
sfm::compute_normalization(points2d_v2, &T2);
points2d_v1 = T1 * points2d_v1;
points2d_v2 = T2 * points2d_v2;
sfm::FundamentalMatrix F;
sfm::fundamental_8_point(points2d_v1, points2d_v2, &F);
sfm::enforce_fundamental_constraints(&F);
F = T2.transposed() * F * T1;
// Compute essential from fundamental.
sfm::EssentialMatrix E = pose2.K.transposed() * F * pose1.K;
// Compute pose from essential.
std::vector<sfm::CameraPose> poses;
pose_from_essential(E, &poses);
// Check if one of the poses is the solution.
int num_equal_cameras = 0;
for (std::size_t i = 0; i < poses.size(); ++i)
{
bool equal = poses[i].R.is_similar(pose2.R, 1e-13)
&& poses[i].t.is_similar(pose2.t, 1e-13);
num_equal_cameras += equal;
}
EXPECT_EQ(num_equal_cameras, 1);
}
TEST(PostTest, TriangulateTest1)
{
// Fill the ground truth pose.
sfm::CameraPose pose1, pose2;
fill_ground_truth_pose(&pose1, &pose2);
math::Vec3d x_gt(0.0, 0.0, 1.0);
math::Vec3d x1 = pose1.K * (pose1.R * x_gt + pose1.t);
math::Vec3d x2 = pose2.K * (pose2.R * x_gt + pose2.t);
sfm::Correspondence2D2D match;
match.p1[0] = x1[0] / x1[2];
match.p1[1] = x1[1] / x1[2];
match.p2[0] = x2[0] / x2[2];
match.p2[1] = x2[1] / x2[2];
math::Vec3d x = sfm::triangulate_match(match, pose1, pose2);
EXPECT_NEAR(x[0], x_gt[0], 1e-14);
EXPECT_NEAR(x[1], x_gt[1], 1e-14);
EXPECT_NEAR(x[2], x_gt[2], 1e-14);
EXPECT_TRUE(sfm::is_consistent_pose(match, pose1, pose2));
}
TEST(PoseTest, ComputeRANSACIterations)
{
double inlier_ratio = 0.5;
double success_rate = 0.99;
int num_samples = 8;
EXPECT_EQ(1177, sfm::compute_ransac_iterations(
inlier_ratio, num_samples, success_rate));
}
#if 0 // This test case is disabled because it is not deterministic.
TEST(PoseRansacFundamental, TestRansac1)
{
// This test computes from a given pose eight corresponding pairs
// of 2D projections in the images. These correspondences are used
// to compute a fundamental matrix, then the essential matrix, then
// recovers the original pose.
sfm::CameraPose pose1, pose2;
fill_ground_truth_pose(&pose1, &pose2);
// Some "random" 3D points.
std::vector<math::Vec3d> points3d;
points3d.push_back(math::Vec3d(-0.31, -0.42, 1.41));
points3d.push_back(math::Vec3d( 0.04, 0.01, 0.82));
points3d.push_back(math::Vec3d(-0.25, -0.24, 1.25));
points3d.push_back(math::Vec3d( 0.47, 0.22, 0.66));
points3d.push_back(math::Vec3d( 0.13, 0.03, 0.89));
points3d.push_back(math::Vec3d(-0.13, -0.46, 1.15));
points3d.push_back(math::Vec3d( 0.21, -0.23, 1.33));
points3d.push_back(math::Vec3d(-0.42, 0.38, 0.62));
points3d.push_back(math::Vec3d(-0.22, -0.38, 0.52));
//points3d.push_back(math::Vec3d( 0.15, 0.12, 1.12));
// Re-project in images using ground truth pose.
sfm::Correspondences matches;
for (int i = 0; i < points3d.size(); ++i)
{
math::Vec3d p1 = pose1.K * (pose1.R * points3d[i] + pose1.t);
math::Vec3d p2 = pose2.K * (pose2.R * points3d[i] + pose2.t);
p1 /= p1[2];
p2 /= p2[2];
sfm::Correspondence match;
match.p1[0] = p1[0] / p1[2];
match.p1[1] = p1[1] / p1[2];
match.p2[0] = p2[0] / p2[2];
match.p2[1] = p2[1] / p2[2];
matches.push_back(match);
}
matches[points3d.size()-1].p2[0] -= 15.0;
matches[points3d.size()-1].p2[1] += 33.0;
//matches[points3d.size()-2].p1[0] += 25.0;
//matches[points3d.size()-2].p1[1] -= 13.0;
sfm::RansacFundamental::Options opts;
opts.max_iterations = 50;
opts.threshold = 1.0;
opts.already_normalized = false;
sfm::RansacFundamental ransac(opts);
sfm::RansacFundamental::Result result;
std::srand(std::time(0));
ransac.estimate(matches, &result);
EXPECT_EQ(8, result.inliers.size());
}
#endif
| 34.144414 | 78 | 0.5808 | [
"vector",
"3d"
] |
4fa8909e61a297f83317dd74ef3ff07ee4a22ed2 | 7,932 | cpp | C++ | Nana.Cpp03/source/paint/gadget.cpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | 1 | 2018-02-09T21:25:13.000Z | 2018-02-09T21:25:13.000Z | Nana.Cpp03/source/paint/gadget.cpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | null | null | null | Nana.Cpp03/source/paint/gadget.cpp | gfannes/nana | 3b8d33f9a98579684ea0440b6952deabe61bd978 | [
"BSL-1.0"
] | null | null | null | /*
* Graphics Gadget Implementation
* Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com)
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file: nana/paint/gadget.cpp
*/
#include <nana/paint/graphics.hpp>
#include <nana/paint/gadget.hpp>
namespace nana
{
namespace paint
{
namespace gadget
{
namespace detail
{
typedef nana::paint::graphics& graph_reference;
void hollow_triangle(graph_reference graph, int x, int y, nana::color_t color, uint32_t direction)
{
x += 3;
y += 3;
switch(direction)
{
case directions::to_east:
graph.line(x + 3, y + 1, x + 3, y + 9, color);
graph.line(x + 4, y + 2 , x + 7, y + 5, color);
graph.line(x + 6, y + 6, x + 4, y + 8, color);
break;
case directions::to_southeast:
graph.line(x + 2, y + 7, x + 7, y + 7, color);
graph.line(x + 7, y + 2, x + 7, y + 6, color);
graph.line(x + 3, y + 6, x + 6, y + 3, color);
break;
case directions::to_south:
y += 3;
graph.line(x, y, x + 8, y, color);
graph.line(x + 1, y + 1, x + 4, y + 4, color);
graph.line(x + 7, y + 1, x + 5, y + 3, color);
break;
case directions::to_west:
x += 5;
y += 1;
graph.line(x, y, x, y + 8, color);
graph.line(x - 4, y + 4, x - 1, y + 1, color);
graph.line(x - 3, y + 5, x - 1, y + 7, color);
break;
case directions::to_north:
y += 7;
graph.line(x, y, x + 8, y, color);
graph.line(x + 1, y - 1, x + 4, y - 4, color);
graph.line(x + 5, y - 3, x + 7, y - 1, color);
break;
}
}
void solid_triangle(graph_reference graph, int x, int y, nana::color_t color, uint32_t dir)
{
x += 3;
y += 3;
switch(dir)
{
case directions::to_east:
for(int i = 0; i < 5; ++i)
graph.line(x + 3 + i, y + 1 + i, x + 3 + i, y + 9 - i, color);
break;
case directions::to_southeast:
for(int i = 0; i < 6; ++i)
graph.line(x + 2 + i, y + 7 - i, x + 7, y + 7 - i, color);
break;
case directions::to_south:
y += 3;
for(int i = 0; i < 5; ++i)
graph.line(x + i, y + i, x + 8 - i, y + i, color);
break;
case directions::to_west:
x += 5;
y += 1;
for(int i = 0; i < 5; ++i)
graph.line(x - i, y + i, x - i, y + 8 - i, color);
break;
case directions::to_north:
y += 7;
for(int i = 0; i < 5; ++i)
graph.line(x + i, y - i, x + 8 - i, y - i, color);
break;
}
}
void direction_arrow(graph_reference graph, int x, int y, nana::color_t color, uint32_t dir)
{
y += 5;
switch(dir)
{
case directions::to_north:
{
x += 3;
int pixels = 1;
for(int l = 0; l < 4; ++l)
{
for(int i = 0; i < pixels; ++i)
{
if(l ==3 && i == 3)
{}
else
graph.set_pixel(x + i, y, 0x262);
}
x--;
y++;
pixels += 2;
}
graph.set_pixel(x + 1, y, 0x262);
graph.set_pixel(x + 2, y, 0x262);
graph.set_pixel(x + 6, y, 0x262);
graph.set_pixel(x + 7, y, 0x262);
}
break;
case directions::to_south:
{
graph.set_pixel(x, y, 0x262);
graph.set_pixel(x + 1, y, 0x262);
graph.set_pixel(x + 5, y, 0x262);
graph.set_pixel(x + 6, y, 0x262);
++y;
int pixels = 7;
for(int l = 0; l < 4; ++l)
{
for(int i = 0; i < pixels; ++i)
{
if(l == 0 && i == 3){}
else
graph.set_pixel(x + i, y, 0x262);
}
x++;
y++;
pixels -= 2;
}
}
break;
}
}
void double_arrow_line(nana::paint::graphics & graph, int x, int y, color_t color, bool horizontal)
{
graph.set_pixel(x, y, color);
if(horizontal)
{
graph.set_pixel(x + 1, y, color);
graph.set_pixel(x + 4, y, color);
graph.set_pixel(x + 5, y, color);
}
else
{
graph.set_pixel(x, y + 1, color);
graph.set_pixel(x, y + 4, color);
graph.set_pixel(x, y + 5, color);
}
}
void double_arrow(nana::paint::graphics& graph, int x, int y, color_t color, directions::t dir)
{
switch(dir)
{
case directions::to_east:
double_arrow_line(graph, x + 4, y + 6, color, true);
double_arrow_line(graph, x + 5, y + 7, color, true);
double_arrow_line(graph, x + 6, y + 8, color, true);
double_arrow_line(graph, x + 5, y + 9, color, true);
double_arrow_line(graph, x + 4, y + 10, color, true);
break;
case directions::to_west:
double_arrow_line(graph, x + 5, y + 6, color, true);
double_arrow_line(graph, x + 4, y + 7, color, true);
double_arrow_line(graph, x + 3, y + 8, color, true);
double_arrow_line(graph, x + 4, y + 9, color, true);
double_arrow_line(graph, x + 5, y + 10, color, true);
break;
case directions::to_south:
double_arrow_line(graph, x + 5, y + 4, color, false);
double_arrow_line(graph, x + 6, y + 5, color, false);
double_arrow_line(graph, x + 7, y + 6, color, false);
double_arrow_line(graph, x + 8, y + 5, color, false);
double_arrow_line(graph, x + 9, y + 4, color, false);
break;
case directions::to_north:
double_arrow_line(graph, x + 5, y + 6, color, false);
double_arrow_line(graph, x + 6, y + 5, color, false);
double_arrow_line(graph, x + 7, y + 4, color, false);
double_arrow_line(graph, x + 8, y + 5, color, false);
double_arrow_line(graph, x + 9, y + 6, color, false);
break;
default: break;
}
}
}//end namespace detail
//arrow_16_pixels
//param@style: 0 = hollow, 1 = solid
void arrow_16_pixels(nana::paint::graphics& graph, int x, int y, unsigned color, uint32_t style, directions::t dir)
{
switch(style)
{
case 1:
detail::solid_triangle(graph, x, y, color, dir);
break;
case 2:
detail::direction_arrow(graph, x, y, color, dir);
break;
case 3:
detail::double_arrow(graph, x, y, color, dir);
break;
case 0:
default:
detail::hollow_triangle(graph, x, y, color, dir);
break;
}
}
void close_16_pixels(nana::paint::graphics& graph, int x, int y, uint32_t style, uint32_t color)
{
if(0 == style)
{
x += 3;
y += 3;
graph.line(x, y, x + 9, y + 9, color);
graph.line(x + 1, y, x + 9, y + 8, color);
graph.line(x, y + 1, x + 8, y + 9, color);
graph.line(x + 9, y, x , y + 9, color);
graph.line(x + 8, y, x, y + 8, color);
graph.line(x + 9, y + 1, x + 1, y + 9, color);
}
else
{
x += 4;
y += 4;
graph.line(x, y, x + 7, y + 7, color);
graph.line(x + 1, y, x + 7, y + 6, color);
graph.line(x, y + 1, x + 6, y + 7, color);
graph.line(x + 7, y, x , y + 7, color);
graph.line(x + 6, y, x, y + 6, color);
graph.line(x + 7, y + 1, x + 1, y + 7, color);
}
}
void cross(graphics& graph, int x, int y, uint32_t size, uint32_t thickness, nana::color_t color)
{
if(thickness + 2 <= size)
{
int gap = (size - thickness) / 2;
nana::point ps[12];
ps[0].x = x + gap;
ps[1].x = ps[0].x + thickness - 1;
ps[1].y = ps[0].y = y;
ps[2].x = ps[1].x;
ps[2].y = y + gap;
ps[3].x = ps[2].x + gap;
ps[3].y = ps[2].y;
ps[4].x = ps[3].x;
ps[4].y = ps[3].y + thickness - 1;
ps[5].x = ps[1].x;
ps[5].y = ps[4].y;
ps[6].x = ps[5].x;
ps[6].y = ps[5].y + gap;
ps[7].x = x + gap;
ps[7].y = ps[6].y;
ps[8].x = ps[7].x;
ps[8].y = ps[4].y;
ps[9].x = x;
ps[9].y = ps[4].y;
ps[10].x = x;
ps[10].y = y + gap;
ps[11].x = x + gap;
ps[11].y = y + gap;
nana::color_t dkcolor = graph.mix(color, 0x0, 0.5);
for(int i = 0; i < 11; ++i)
graph.line(ps[i], ps[i + 1], dkcolor);
graph.line(ps[11], ps[0], dkcolor);
graph.rectangle(ps[10].x + 1, ps[10].y + 1, (gap << 1) + thickness - 2, thickness - 2, color, true);
graph.rectangle(ps[0].x + 1, ps[0].y + 1, thickness - 2, (gap << 1) + thickness - 2, color, true);
}
}
}//end namespace gadget
}//end namespace paint
}//end namespace nana
| 25.101266 | 116 | 0.534418 | [
"solid"
] |
4faa72547df4f0ec3e921b6231916c6b1a1161ff | 45,539 | cxx | C++ | Modules/IO/IOGDAL/src/otbOGRIOHelper.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/IO/IOGDAL/src/otbOGRIOHelper.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/IO/IOGDAL/src/otbOGRIOHelper.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbOGRIOHelper.h"
#include "otbMacro.h"
#include "ogrsf_frmts.h"
#include "otbOGR.h"
#include "otbStopwatch.h"
namespace otb
{
void OGRIOHelper::ConvertGeometryToPointNode(const OGRGeometry* ogrGeometry, DataNodePointerType node) const
{
OGRPoint* ogrPoint = (OGRPoint*)ogrGeometry;
if (ogrPoint == nullptr)
{
itkGenericExceptionMacro(<< "Failed to convert OGRGeometry to OGRPoint");
}
PointType otbPoint;
otbPoint.Fill(0);
otbPoint[0] = static_cast<DataNodeType::PrecisionType>(ogrPoint->getX());
otbPoint[1] = static_cast<DataNodeType::PrecisionType>(ogrPoint->getY());
if (DataNodeType::Dimension > 2)
{
if (PointType::PointDimension != 3)
{
itkGenericExceptionMacro(<< "OTB vector data can't contain the OGR information (2D instead of 2.5D)");
}
otbPoint[2] = static_cast<DataNodeType::PrecisionType>(ogrPoint->getZ());
}
node->SetPoint(otbPoint);
}
void OGRIOHelper::ConvertGeometryToLineNode(const OGRGeometry* ogrGeometry, DataNodePointerType node) const
{
OGRLineString* ogrLine = (OGRLineString*)ogrGeometry;
if (ogrLine == nullptr)
{
itkGenericExceptionMacro(<< "Failed to convert OGRGeometry to OGRLine");
}
LinePointerType line = LineType::New();
OGRPoint* ogrTmpPoint = (OGRPoint*)OGRGeometryFactory::createGeometry(wkbPoint);
for (int pIndex = 0; pIndex < ogrLine->getNumPoints(); ++pIndex)
{
ogrLine->getPoint(pIndex, ogrTmpPoint);
LineType::VertexType vertex;
vertex[0] = ogrTmpPoint->getX();
vertex[1] = ogrTmpPoint->getY();
if (DataNodeType::Dimension > 2)
{
if (LineType::VertexType::PointDimension != 3)
{
itkGenericExceptionMacro(<< "OTB vector data can't contain the OGR information (2D instead of 2.5D)");
}
vertex[2] = ogrTmpPoint->getZ();
}
line->AddVertex(vertex);
}
OGRGeometryFactory::destroyGeometry(ogrTmpPoint);
node->SetLine(line);
}
void OGRIOHelper::ConvertGeometryToPolygonNode(const OGRGeometry* ogrGeometry, DataNodePointerType node) const
{
OGRPolygon* ogrPolygon = (OGRPolygon*)ogrGeometry;
if (ogrPolygon == nullptr)
{
itkGenericExceptionMacro(<< "Failed to convert OGRGeometry to OGRPolygon");
}
OGRPoint* ogrTmpPoint = (OGRPoint*)OGRGeometryFactory::createGeometry(wkbPoint);
OGRLinearRing* ogrRing = ogrPolygon->getExteriorRing();
PolygonPointerType extRing = PolygonType::New();
for (int pIndex = 0; pIndex < ogrRing->getNumPoints(); ++pIndex)
{
ogrRing->getPoint(pIndex, ogrTmpPoint);
PolygonType::VertexType vertex;
vertex[0] = ogrTmpPoint->getX();
vertex[1] = ogrTmpPoint->getY();
if (DataNodeType::Dimension > 2)
{
if (PolygonType::VertexType::PointDimension != 3)
{
itkGenericExceptionMacro(<< "OTB vector data can't contain the OGR information (2D instead of 2.5D)");
}
vertex[2] = ogrTmpPoint->getZ();
}
extRing->AddVertex(vertex);
}
PolygonListPointerType intRings = PolygonListType::New();
for (int intRingIndex = 0; intRingIndex < ogrPolygon->getNumInteriorRings(); ++intRingIndex)
{
PolygonPointerType ring = PolygonType::New();
ogrRing = ogrPolygon->getInteriorRing(intRingIndex);
for (int pIndex = 0; pIndex < ogrRing->getNumPoints(); ++pIndex)
{
ogrRing->getPoint(pIndex, ogrTmpPoint);
PolygonType::VertexType vertex;
vertex[0] = ogrTmpPoint->getX();
vertex[1] = ogrTmpPoint->getY();
if (DataNodeType::Dimension > 2)
{
if (PolygonType::VertexType::PointDimension != 3)
{
itkGenericExceptionMacro(<< "OTB vector data can't contain the OGR information (2D instead of 2.5D)");
}
vertex[2] = ogrTmpPoint->getZ();
}
ring->AddVertex(vertex);
}
intRings->PushBack(ring);
}
OGRGeometryFactory::destroyGeometry(ogrTmpPoint);
node->SetPolygonExteriorRing(extRing);
node->SetPolygonInteriorRings(intRings);
}
OGRIOHelper::OGRIOHelper()
{
otb::ogr::Drivers::Init();
}
OGRIOHelper::~OGRIOHelper()
{
}
void OGRIOHelper::ConvertOGRLayerToDataTreeNode(OGRLayer* layer, InternalTreeNodeType* documentPtr) const
{
/** Temporary pointer to store the feature */
OGRFeature* feature;
layer->ResetReading();
// Warn user that 3D data are not supported for reading/writing
auto geomType = layer->GetGeomType();
if (geomType == wkbPoint25D || geomType == wkbLineString25D || geomType == wkbPolygon25D || geomType == wkbMultiPoint25D ||
geomType == wkbMultiLineString25D || geomType == wkbMultiPolygon25D || geomType == wkbGeometryCollection25D)
{
otbLogMacro(Warning, << "OGRVectorDataIO does not support 3D data. " << OGRGeometryTypeToName(geomType) << " will be converted to 2D upon reading.");
}
unsigned int counter = 0;
otb::Stopwatch chrono = otb::Stopwatch::StartNew();
while ((feature = layer->GetNextFeature()) != nullptr)
{
// A pointer to the current multi-geometry
InternalTreeNodeType::Pointer multiPtr;
/** Temporary geometry container */
OGRGeometry* geometry = feature->GetGeometryRef();
if (geometry == nullptr)
{
OGRFeature::DestroyFeature(feature);
++counter;
continue;
}
otb::VectorDataKeywordlist kwl;
for (int fieldNum = 0; fieldNum < feature->GetFieldCount(); ++fieldNum)
{
if (ogr::IsFieldSetAndNotNull(feature, fieldNum))
{
kwl.AddField(feature->GetFieldDefnRef(fieldNum), feature->GetRawFieldRef(fieldNum));
}
}
switch (geometry->getGeometryType())
{
case wkbPoint:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(geometry, dataNode);
newNode->Set(dataNode);
// Reach the DataNode inside the tree node
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
documentPtr->AddChild(newNode);
break;
}
case wkbPoint25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(geometry, dataNode);
newNode->Set(dataNode);
// Reach the DataNode inside the tree node
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
documentPtr->AddChild(newNode);
break;
}
case wkbLineString:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(geometry, dataNode);
newNode->Set(dataNode);
// Reach the DataNode inside the tree node
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
documentPtr->AddChild(newNode);
break;
}
case wkbLineString25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(geometry, dataNode);
newNode->Set(dataNode);
// Reach the DataNode inside the tree node
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
documentPtr->AddChild(newNode);
break;
}
case wkbPolygon:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(geometry, dataNode);
newNode->Set(dataNode);
// Reach the DataNode inside the tree node
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
documentPtr->AddChild(newNode);
break;
}
case wkbPolygon25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(geometry, dataNode);
newNode->Set(dataNode);
// Reach the DataNode inside the tree node
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
documentPtr->AddChild(newNode);
break;
}
case wkbMultiPoint:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_MULTIPOINT);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRMultiPoint* ogrMulti = (OGRMultiPoint*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
}
break;
}
case wkbMultiPoint25D:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_MULTIPOINT);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRMultiPoint* ogrMulti = (OGRMultiPoint*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
}
break;
}
case wkbMultiLineString:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_MULTILINE);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRMultiLineString* ogrMulti = (OGRMultiLineString*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
}
break;
}
case wkbMultiLineString25D:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_MULTILINE);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRMultiLineString* ogrMulti = (OGRMultiLineString*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
}
break;
}
case wkbMultiPolygon:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_MULTIPOLYGON);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRMultiPolygon* ogrMulti = (OGRMultiPolygon*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
}
break;
}
case wkbMultiPolygon25D:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_MULTIPOLYGON);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRMultiPolygon* ogrMulti = (OGRMultiPolygon*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
}
break;
}
case wkbGeometryCollection:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_COLLECTION);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRGeometryCollection* ogrMulti = (OGRGeometryCollection*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
switch (ogrMulti->getGeometryRef(geoIndex)->getGeometryType())
{
case wkbPoint:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
break;
}
case wkbPoint25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
break;
}
case wkbLineString:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
break;
}
case wkbLineString25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
break;
}
case wkbPolygon:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
break;
}
case wkbPolygon25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
itk::MetaDataDictionary& dict = newNode->Get()->GetMetaDataDictionary();
itk::EncapsulateMetaData<VectorDataKeywordlist>(dict, MetaDataKey::VectorDataKeywordlistKey, kwl);
multiPtr->AddChild(newNode);
break;
}
default:
{
otbWarningMacro(<< "Geometry type not found: " << ogrMulti->getGeometryRef(geoIndex)->getGeometryType());
break;
}
}
}
break;
}
case wkbGeometryCollection25D:
{
DataNodePointerType multi = DataNodeType::New();
multi->SetNodeType(FEATURE_COLLECTION);
multiPtr = InternalTreeNodeType::New();
multiPtr->Set(multi);
documentPtr->AddChild(multiPtr);
OGRGeometryCollection* ogrMulti = (OGRGeometryCollection*)geometry;
for (int geoIndex = 0; geoIndex < ogrMulti->getNumGeometries(); ++geoIndex)
{
switch (ogrMulti->getGeometryRef(geoIndex)->getGeometryType())
{
case wkbPoint:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
multiPtr->AddChild(newNode);
break;
}
case wkbPoint25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPointNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
multiPtr->AddChild(newNode);
break;
}
case wkbLineString:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
multiPtr->AddChild(newNode);
break;
}
case wkbLineString25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToLineNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
multiPtr->AddChild(newNode);
break;
}
case wkbPolygon:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
multiPtr->AddChild(newNode);
break;
}
case wkbPolygon25D:
{
InternalTreeNodeType::Pointer newNode = InternalTreeNodeType::New();
DataNodePointerType dataNode = DataNodeType::New();
ConvertGeometryToPolygonNode(ogrMulti->getGeometryRef(geoIndex), dataNode);
newNode->Set(dataNode);
multiPtr->AddChild(newNode);
break;
}
default:
{
otbWarningMacro(<< "Geometry type not found: " << ogrMulti->getGeometryRef(geoIndex)->getGeometryType());
break;
}
}
}
break;
}
default:
{
otbWarningMacro("Geometry not handled: " << geometry->getGeometryName());
break;
}
}
OGRFeature::DestroyFeature(feature);
++counter;
} // end While feature
chrono.Stop();
otbMsgDevMacro(<< layer->GetFeatureCount() << " features read, total processing time " << chrono.GetElapsedMilliseconds() << " ms");
}
unsigned int OGRIOHelper::ProcessNodeWrite(InternalTreeNodeType* source, GDALDataset* m_DataSource, OGRGeometryCollection* ogrCollection,
OGRLayer* ogrCurrentLayer, OGRSpatialReference* oSRS)
{
unsigned int kept = 0;
bool fieldsAddedToOGRLayer = false;
// Get the children list from the input node
typedef InternalTreeNodeType::ChildrenListType ChildrenListType;
ChildrenListType children = source->GetChildrenList();
// For each child
for (ChildrenListType::iterator it = children.begin(); it != children.end(); ++it)
{
DataNodePointerType dataNode = (*it)->Get();
// otbMsgDevMacro(<< "Type of node " << dataNode->GetNodeType() << " id " << dataNode->GetNodeId());
++kept;
// Get the kwl
otb::VectorDataKeywordlist kwl;
itk::ExposeMetaData<VectorDataKeywordlist>(dataNode->GetMetaDataDictionary(), MetaDataKey::VectorDataKeywordlistKey, kwl);
// Create the field once
if (ogrCurrentLayer != nullptr && !fieldsAddedToOGRLayer)
{
// Take into account the fields stored in the
// vectordatakeywordlist
for (unsigned int fieldIdx = 0; fieldIdx < kwl.GetNumberOfFields(); fieldIdx++)
{
if (std::string(kwl.GetNthField(fieldIdx).first->GetNameRef()) != "FID")
{
otbMsgDevMacro(<< " CreateField '" << kwl.GetNthField(fieldIdx).first->GetNameRef() << "'");
if (ogrCurrentLayer->CreateField(kwl.GetNthField(fieldIdx).first) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create Field " << kwl.GetNthField(fieldIdx).first->GetNameRef());
}
}
else
{
otbMsgDevMacro(<< "WARNING: Skipping OGR field 'FID'");
}
}
// While no feature are added to the layer (in case of multiple
// folders added to the document) continue test for adding
// fields to the ogrCurrentLayer
if (kwl.GetNumberOfFields() > 0 || ogrCurrentLayer->GetFeatureCount() > 0)
{
fieldsAddedToOGRLayer = true;
}
}
switch (dataNode->GetNodeType())
{
case ROOT:
{
break;
}
case DOCUMENT:
{
ogrCurrentLayer = m_DataSource->CreateLayer(dataNode->GetNodeId(), oSRS, wkbUnknown, nullptr);
if (ogrCurrentLayer == nullptr)
{
itkExceptionMacro(<< "Failed to create layer " << dataNode->GetNodeId());
}
else
{
// New OGRLayer, set the flag to false
fieldsAddedToOGRLayer = false;
}
ProcessNodeWrite(*it, m_DataSource, ogrCollection, ogrCurrentLayer, oSRS);
break;
}
case FOLDER:
{
ProcessNodeWrite(*it, m_DataSource, ogrCollection, ogrCurrentLayer, oSRS);
break;
}
case FEATURE_POINT:
{
// Build the ogrObject
OGRPoint ogrPoint;
ogrPoint.setX(dataNode->GetPoint()[0]);
ogrPoint.setY(dataNode->GetPoint()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(dataNode->GetPoint()[2]);
}
// Save it in the structure
if (ogrCollection == nullptr)
{
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// Add the fields to the features
for (unsigned int i = 0; i < kwl.GetNumberOfFields(); ++i)
{
// Get the key of the Nth OGRFieldRefn
const char* key = kwl.GetNthField(i).first->GetNameRef();
if (std::string(key) != "FID")
{
// Edit the value of the field and add it to the current feature
int fIndex = ogrFeature->GetFieldIndex(key);
if (fIndex >= 0)
ogrFeature->SetField(fIndex, kwl.GetFieldAsString(key).c_str());
}
}
// ogrFeature->SetField("Name", dataNode->GetNodeId());
ogrFeature->SetGeometry(&ogrPoint);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
OGRFeature::DestroyFeature(ogrFeature);
}
else
{
ogrCollection->addGeometry(&ogrPoint);
}
break;
}
case FEATURE_LINE:
{
// Build the ogrObject
OGRLineString ogrLine;
VertexListConstPointerType vertexList = dataNode->GetLine()->GetVertexList();
VertexListType::ConstIterator vIt = vertexList->Begin();
while (vIt != vertexList->End())
{
OGRPoint ogrPoint;
ogrPoint.setX(vIt.Value()[0]);
ogrPoint.setY(vIt.Value()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(vIt.Value()[2]);
}
ogrLine.addPoint(&ogrPoint);
++vIt;
}
// Save it in the structure
if (ogrCollection == nullptr)
{
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// Add the fields to the features
for (unsigned int i = 0; i < kwl.GetNumberOfFields(); ++i)
{
// Get the key of the Nth OGRFieldRefn
const char* key = kwl.GetNthField(i).first->GetNameRef();
// Edit the value of the field and add it to the current feature
if (std::string(key) != "FID")
{
int fIndex = ogrFeature->GetFieldIndex(key);
if (fIndex >= 0)
ogrFeature->SetField(fIndex, kwl.GetFieldAsString(key).c_str());
}
}
// ogrFeature->SetField("Name", dataNode->GetNodeId());
ogrFeature->SetGeometry(&ogrLine);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
OGRFeature::DestroyFeature(ogrFeature);
}
else
{
ogrCollection->addGeometry(&ogrLine);
}
break;
}
case FEATURE_POLYGON:
{
// Build the ogrObject
OGRPolygon* ogrPolygon = (OGRPolygon*)OGRGeometryFactory::createGeometry(wkbPolygon);
OGRLinearRing* ogrExternalRing = (OGRLinearRing*)OGRGeometryFactory::createGeometry(wkbLinearRing);
VertexListConstPointerType vertexList = dataNode->GetPolygonExteriorRing()->GetVertexList();
VertexListType::ConstIterator vIt = vertexList->Begin();
while (vIt != vertexList->End())
{
OGRPoint ogrPoint;
ogrPoint.setX(vIt.Value()[0]);
ogrPoint.setY(vIt.Value()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(vIt.Value()[2]);
}
ogrExternalRing->addPoint(&ogrPoint);
++vIt;
}
ogrPolygon->addRing(ogrExternalRing);
// Close the polygon
ogrPolygon->closeRings();
OGRGeometryFactory::destroyGeometry(ogrExternalRing);
// Retrieving internal rings as well
for (PolygonListType::Iterator pIt = dataNode->GetPolygonInteriorRings()->Begin(); pIt != dataNode->GetPolygonInteriorRings()->End(); ++pIt)
{
OGRLinearRing* ogrInternalRing = (OGRLinearRing*)OGRGeometryFactory::createGeometry(wkbLinearRing);
vertexList = pIt.Get()->GetVertexList();
vIt = vertexList->Begin();
while (vIt != vertexList->End())
{
OGRPoint ogrPoint;
ogrPoint.setX(vIt.Value()[0]);
ogrPoint.setY(vIt.Value()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(vIt.Value()[2]);
}
ogrInternalRing->addPoint(&ogrPoint);
++vIt;
}
ogrPolygon->addRing(ogrInternalRing);
OGRGeometryFactory::destroyGeometry(ogrInternalRing);
}
// Save it in the structure
if (ogrCollection == nullptr)
{
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// Add the fields to the features
for (unsigned int i = 0; i < kwl.GetNumberOfFields(); ++i)
{
// Get the key of the Nth OGRFieldRefn
const char* key = kwl.GetNthField(i).first->GetNameRef();
// Edit the value of the field and add it to the current feature
int fIndex = ogrFeature->GetFieldIndex(key);
if (std::string(key) != "FID")
{
if (fIndex >= 0)
ogrFeature->SetField(fIndex, kwl.GetFieldAsString(key).c_str());
}
}
ogrFeature->SetGeometry(ogrPolygon);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
OGRFeature::DestroyFeature(ogrFeature);
}
else
{
ogrCollection->addGeometry(ogrPolygon);
}
OGRGeometryFactory::destroyGeometry(ogrPolygon);
break;
}
case FEATURE_MULTIPOINT:
{
OGRMultiPoint* ogrMultiPoint = (OGRMultiPoint*)OGRGeometryFactory::createGeometry(wkbMultiPoint);
OGRFeature* ogrFeature;
ProcessNodeWrite(*it, m_DataSource, ogrMultiPoint, ogrCurrentLayer, oSRS);
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// ogrFeature->SetField("Name", dataNode->GetNodeId());
ogrFeature->GetDefnRef()->SetGeomType(wkbMultiPoint);
ogrFeature->SetGeometry(ogrMultiPoint);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
break;
}
case FEATURE_MULTILINE:
{
// Instantiate a new ogrMultiLineString feature
OGRMultiLineString* ogrMultiLineString = (OGRMultiLineString*)OGRGeometryFactory::createGeometry(wkbMultiLineString);
OGRFeature* ogrFeature;
ProcessNodeWrite(*it, m_DataSource, ogrMultiLineString, ogrCurrentLayer, oSRS);
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// ogrFeature->SetField("Name", dataNode->GetNodeId());
ogrFeature->GetDefnRef()->SetGeomType(wkbMultiLineString);
ogrFeature->SetGeometry(ogrMultiLineString);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
break;
}
case FEATURE_MULTIPOLYGON:
{
// Instantiate a new multipolygon feature
OGRMultiPolygon* ogrMultiPolygon = (OGRMultiPolygon*)OGRGeometryFactory::createGeometry(wkbMultiPolygon);
OGRFeature* ogrFeature;
ProcessNodeWrite(*it, m_DataSource, ogrMultiPolygon, ogrCurrentLayer, oSRS);
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// ogrFeature->SetField("Name", dataNode->GetNodeId());
ogrFeature->GetDefnRef()->SetGeomType(wkbMultiPolygon);
ogrFeature->SetGeometry(ogrMultiPolygon);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
break;
}
case FEATURE_COLLECTION:
{
OGRGeometryCollection* ogrCollectionGeometry = (OGRGeometryCollection*)OGRGeometryFactory::createGeometry(wkbGeometryCollection);
OGRFeature* ogrFeature;
ProcessNodeWrite(*it, m_DataSource, ogrCollection, ogrCurrentLayer, oSRS);
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// ogrFeature->SetField("Name", dataNode->GetNodeId());
ogrFeature->GetDefnRef()->SetGeomType(wkbGeometryCollection);
ogrFeature->SetGeometry(ogrCollectionGeometry);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
break;
}
}
}
return kept;
}
/**
* They may be several OGRLayers in this tree node.
* Return a vector of OGRLayer
**/
std::vector<OGRLayer*> OGRIOHelper::ConvertDataTreeNodeToOGRLayers(InternalTreeNodeType* source, GDALDataset* inMemoryDataSource, OGRLayer* ogrCurrentLayer,
OGRSpatialReference* oSRS)
{
// Create the in memory datasource if NULL
if (inMemoryDataSource == nullptr)
{
const char* driverName = "Memory";
GDALDriver* ogrDriver = GetGDALDriverManager()->GetDriverByName(driverName);
inMemoryDataSource = ogrDriver->Create("tempDataSource", 0, 0, 0, GDT_Unknown, 0);
}
std::vector<OGRLayer*> ogrLayerVector;
// unsigned int kept = 0;
bool fieldsAddedToOGRLayer = false;
// Get the children list from the input node
typedef InternalTreeNodeType::ChildrenListType ChildrenListType;
ChildrenListType children = source->GetChildrenList();
// For each child
for (ChildrenListType::iterator it = children.begin(); it != children.end(); ++it)
{
DataNodePointerType dataNode = (*it)->Get();
// Get the kwl
otb::VectorDataKeywordlist kwl;
itk::ExposeMetaData<VectorDataKeywordlist>(dataNode->GetMetaDataDictionary(), MetaDataKey::VectorDataKeywordlistKey, kwl);
// Create the field once
if (ogrCurrentLayer != nullptr && !fieldsAddedToOGRLayer)
{
// Take into account the fields stored in the
// vectordatakeywordlist
for (unsigned int fieldIdx = 0; fieldIdx < kwl.GetNumberOfFields(); fieldIdx++)
{
if (std::string(kwl.GetNthField(fieldIdx).first->GetNameRef()) != "FID")
{
otbMsgDevMacro(<< " CreateField '" << kwl.GetNthField(fieldIdx).first->GetNameRef() << "'");
if (ogrCurrentLayer->CreateField(kwl.GetNthField(fieldIdx).first) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create Field " << kwl.GetNthField(fieldIdx).first->GetNameRef());
}
}
else
{
otbMsgDevMacro(<< "WARNING: Skipping OGR field 'FID'");
}
}
fieldsAddedToOGRLayer = true;
}
switch (dataNode->GetNodeType())
{
case ROOT:
{
break;
}
case DOCUMENT:
{
ogrCurrentLayer = inMemoryDataSource->CreateLayer(dataNode->GetNodeId(), oSRS, wkbUnknown, nullptr);
if (ogrCurrentLayer == nullptr)
{
itkExceptionMacro(<< "Failed to create layer " << dataNode->GetNodeId());
}
else
{
// New OGRLayer, set the flag to false
fieldsAddedToOGRLayer = false;
}
ogrLayerVector.push_back(ogrCurrentLayer);
ConvertDataTreeNodeToOGRLayers(*it, inMemoryDataSource, ogrCurrentLayer, oSRS);
break;
}
case FOLDER:
{
ConvertDataTreeNodeToOGRLayers(*it, inMemoryDataSource, ogrCurrentLayer, oSRS);
break;
}
case FEATURE_POINT:
{
// Build the ogrObject
OGRPoint ogrPoint;
ogrPoint.setX(dataNode->GetPoint()[0]);
ogrPoint.setY(dataNode->GetPoint()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(dataNode->GetPoint()[2]);
}
// Save it in the structure
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// Add the fields to the features
for (unsigned int i = 0; i < kwl.GetNumberOfFields(); ++i)
{
// Get the key of the Nth OGRFieldRefn
const char* key = kwl.GetNthField(i).first->GetNameRef();
if (std::string(key) != "FID")
{
// Edit the value of the field and add it to the current feature
ogrFeature->SetField(ogrFeature->GetFieldIndex(key), kwl.GetFieldAsString(key).c_str());
}
}
ogrFeature->SetGeometry(&ogrPoint);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
OGRFeature::DestroyFeature(ogrFeature);
break;
}
case FEATURE_LINE:
{
// Build the ogrObject
OGRLineString ogrLine;
VertexListConstPointerType vertexList = dataNode->GetLine()->GetVertexList();
VertexListType::ConstIterator vIt = vertexList->Begin();
while (vIt != vertexList->End())
{
OGRPoint ogrPoint;
ogrPoint.setX(vIt.Value()[0]);
ogrPoint.setY(vIt.Value()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(vIt.Value()[2]);
}
ogrLine.addPoint(&ogrPoint);
++vIt;
}
// Save it in the structure
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// Add the fields to the features
for (unsigned int i = 0; i < kwl.GetNumberOfFields(); ++i)
{
// Get the key of the Nth OGRFieldRefn
const char* key = kwl.GetNthField(i).first->GetNameRef();
// Edit the value of the field and add it to the current feature
if (std::string(key) != "FID")
{
// Edit the value of the field and add it to the current feature
ogrFeature->SetField(ogrFeature->GetFieldIndex(key), kwl.GetFieldAsString(key).c_str());
}
}
ogrFeature->SetGeometry(&ogrLine);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
OGRFeature::DestroyFeature(ogrFeature);
break;
}
case FEATURE_POLYGON:
{
// Build the ogrObject
OGRPolygon* ogrPolygon = (OGRPolygon*)OGRGeometryFactory::createGeometry(wkbPolygon);
OGRLinearRing* ogrExternalRing = (OGRLinearRing*)OGRGeometryFactory::createGeometry(wkbLinearRing);
VertexListConstPointerType vertexList = dataNode->GetPolygonExteriorRing()->GetVertexList();
VertexListType::ConstIterator vIt = vertexList->Begin();
while (vIt != vertexList->End())
{
OGRPoint ogrPoint;
ogrPoint.setX(vIt.Value()[0]);
ogrPoint.setY(vIt.Value()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(vIt.Value()[2]);
}
ogrExternalRing->addPoint(&ogrPoint);
++vIt;
}
ogrPolygon->addRing(ogrExternalRing);
// Close the polygon
ogrPolygon->closeRings();
OGRGeometryFactory::destroyGeometry(ogrExternalRing);
// Retrieving internal rings as well
for (PolygonListType::Iterator pIt = dataNode->GetPolygonInteriorRings()->Begin(); pIt != dataNode->GetPolygonInteriorRings()->End(); ++pIt)
{
OGRLinearRing* ogrInternalRing = (OGRLinearRing*)OGRGeometryFactory::createGeometry(wkbLinearRing);
vertexList = pIt.Get()->GetVertexList();
vIt = vertexList->Begin();
while (vIt != vertexList->End())
{
OGRPoint ogrPoint;
ogrPoint.setX(vIt.Value()[0]);
ogrPoint.setY(vIt.Value()[1]);
if (DataNodeType::Dimension > 2)
{
ogrPoint.setZ(vIt.Value()[2]);
}
ogrInternalRing->addPoint(&ogrPoint);
++vIt;
}
ogrPolygon->addRing(ogrInternalRing);
OGRGeometryFactory::destroyGeometry(ogrInternalRing);
}
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
// Add the fields to the features
for (unsigned int i = 0; i < kwl.GetNumberOfFields(); ++i)
{
// Get the key of the Nth OGRFieldRefn
const char* key = kwl.GetNthField(i).first->GetNameRef();
if (std::string(key) != "FID")
{
// Edit the value of the field and add it to the current feature
ogrFeature->SetField(ogrFeature->GetFieldIndex(key), kwl.GetFieldAsString(key).c_str());
}
}
ogrFeature->SetGeometry(ogrPolygon);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
OGRFeature::DestroyFeature(ogrFeature);
OGRGeometryFactory::destroyGeometry(ogrPolygon);
break;
}
case FEATURE_MULTIPOINT:
{
OGRMultiPoint* ogrMultiPoint = (OGRMultiPoint*)OGRGeometryFactory::createGeometry(wkbMultiPoint);
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
ogrFeature->GetDefnRef()->SetGeomType(wkbMultiPoint);
ogrFeature->SetGeometry(ogrMultiPoint);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
ConvertDataTreeNodeToOGRLayers(*it, inMemoryDataSource, ogrCurrentLayer, oSRS);
break;
}
case FEATURE_MULTILINE:
{
// Instantiate a new ogrMultiLineString feature
OGRMultiLineString* ogrMultiLineString = (OGRMultiLineString*)OGRGeometryFactory::createGeometry(wkbMultiLineString);
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
ogrFeature->GetDefnRef()->SetGeomType(wkbMultiLineString);
ogrFeature->SetGeometry(ogrMultiLineString);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
ConvertDataTreeNodeToOGRLayers(*it, inMemoryDataSource, ogrCurrentLayer, oSRS);
break;
}
case FEATURE_MULTIPOLYGON:
{
// Instantiate a new multipolygon feature
OGRMultiPolygon* ogrMultiPolygon = (OGRMultiPolygon*)OGRGeometryFactory::createGeometry(wkbMultiPolygon);
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
ogrFeature->GetDefnRef()->SetGeomType(wkbMultiPolygon);
ogrFeature->SetGeometry(ogrMultiPolygon);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
ConvertDataTreeNodeToOGRLayers(*it, inMemoryDataSource, ogrCurrentLayer, oSRS);
break;
}
case FEATURE_COLLECTION:
{
OGRGeometryCollection* ogrCollectionGeometry = (OGRGeometryCollection*)OGRGeometryFactory::createGeometry(wkbGeometryCollection);
OGRFeature* ogrFeature;
ogrFeature = OGRFeature::CreateFeature(ogrCurrentLayer->GetLayerDefn());
ogrFeature->GetDefnRef()->SetGeomType(wkbGeometryCollection);
ogrFeature->SetGeometry(ogrCollectionGeometry);
if (ogrCurrentLayer->CreateFeature(ogrFeature) != OGRERR_NONE)
{
itkExceptionMacro(<< "Failed to create feature in shapefile.");
}
ConvertDataTreeNodeToOGRLayers(*it, inMemoryDataSource, ogrCurrentLayer, oSRS);
break;
}
}
}
return ogrLayerVector;
}
} // end namespace otb
| 35.192427 | 156 | 0.645491 | [
"geometry",
"vector",
"3d"
] |
4fab8b8d0fc8265a003242b161737e44e5b09f6b | 833,101 | cpp | C++ | CppCollection/r8lib.cpp | huoyongkai/Wireless360 | 20b458809b16aa05316cbbe98d2aebc10b4ba19f | [
"MIT"
] | 1 | 2020-06-25T05:36:23.000Z | 2020-06-25T05:36:23.000Z | CppCollection/r8lib.cpp | huoyongkai/Wireless360 | 20b458809b16aa05316cbbe98d2aebc10b4ba19f | [
"MIT"
] | null | null | null | CppCollection/r8lib.cpp | huoyongkai/Wireless360 | 20b458809b16aa05316cbbe98d2aebc10b4ba19f | [
"MIT"
] | null | null | null | # include <cmath>
# include <complex>
# include <cstdlib>
# include <ctime>
# include <cstring>
# include <fstream>
# include <iomanip>
# include <iostream>
using namespace std;
# include "r8lib.hpp"
//****************************************************************************80
void gamma_values ( int &n_data, double &x, double &fx )
//****************************************************************************80
//
// Purpose:
//
// GAMMA_VALUES returns some values of the Gamma function.
//
// Discussion:
//
// The Gamma function is defined as:
//
// Gamma(Z) = Integral ( 0 <= T < +oo ) T^(Z-1) exp(-T) dT
//
// It satisfies the recursion:
//
// Gamma(X+1) = X * Gamma(X)
//
// Gamma is undefined for nonpositive integral X.
// Gamma(0.5) = sqrt(PI)
// For N a positive integer, Gamma(N+1) = N!, the standard factorial.
//
// In Mathematica, the function can be evaluated by:
//
// Gamma[x]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 May 2007
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Milton Abramowitz, Irene Stegun,
// Handbook of Mathematical Functions,
// National Bureau of Standards, 1964,
// ISBN: 0-486-61272-4,
// LC: QA47.A34.
//
// Stephen Wolfram,
// The Mathematica Book,
// Fourth Edition,
// Cambridge University Press, 1999,
// ISBN: 0-521-64314-7,
// LC: QA76.95.W65.
//
// Parameters:
//
// Input/output, int &N_DATA. The user sets N_DATA to 0 before the
// first call. On each call, the routine increments N_DATA by 1, and
// returns the corresponding data; when there is no more data, the
// output value of N_DATA will be 0 again.
//
// Output, double &X, the argument of the function.
//
// Output, double &FX, the value of the function.
//
{
# define N_MAX 25
static double fx_vec[N_MAX] = {
-0.3544907701811032E+01,
-0.1005871979644108E+03,
0.9943258511915060E+02,
0.9513507698668732E+01,
0.4590843711998803E+01,
0.2218159543757688E+01,
0.1772453850905516E+01,
0.1489192248812817E+01,
0.1164229713725303E+01,
0.1000000000000000E+01,
0.9513507698668732E+00,
0.9181687423997606E+00,
0.8974706963062772E+00,
0.8872638175030753E+00,
0.8862269254527580E+00,
0.8935153492876903E+00,
0.9086387328532904E+00,
0.9313837709802427E+00,
0.9617658319073874E+00,
0.1000000000000000E+01,
0.2000000000000000E+01,
0.6000000000000000E+01,
0.3628800000000000E+06,
0.1216451004088320E+18,
0.8841761993739702E+31 };
static double x_vec[N_MAX] = {
-0.50E+00,
-0.01E+00,
0.01E+00,
0.10E+00,
0.20E+00,
0.40E+00,
0.50E+00,
0.60E+00,
0.80E+00,
1.00E+00,
1.10E+00,
1.20E+00,
1.30E+00,
1.40E+00,
1.50E+00,
1.60E+00,
1.70E+00,
1.80E+00,
1.90E+00,
2.00E+00,
3.00E+00,
4.00E+00,
10.00E+00,
20.00E+00,
30.00E+00 };
if ( n_data < 0 )
{
n_data = 0;
}
n_data = n_data + 1;
if ( N_MAX < n_data )
{
n_data = 0;
x = 0.0;
fx = 0.0;
}
else
{
x = x_vec[n_data-1];
fx = fx_vec[n_data-1];
}
return;
# undef N_MAX
}
//****************************************************************************80
void gamma_log_values ( int &n_data, double &x, double &fx )
//****************************************************************************80
//
// Purpose:
//
// GAMMA_LOG_VALUES returns some values of the Log Gamma function.
//
// Discussion:
//
// In Mathematica, the function can be evaluated by:
//
// Log[Gamma[x]]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 August 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Milton Abramowitz, Irene Stegun,
// Handbook of Mathematical Functions,
// National Bureau of Standards, 1964,
// ISBN: 0-486-61272-4,
// LC: QA47.A34.
//
// Stephen Wolfram,
// The Mathematica Book,
// Fourth Edition,
// Cambridge University Press, 1999,
// ISBN: 0-521-64314-7,
// LC: QA76.95.W65.
//
// Parameters:
//
// Input/output, int &N_DATA. The user sets N_DATA to 0 before the
// first call. On each call, the routine increments N_DATA by 1, and
// returns the corresponding data; when there is no more data, the
// output value of N_DATA will be 0 again.
//
// Output, double &X, the argument of the function.
//
// Output, double &FX, the value of the function.
//
{
# define N_MAX 20
static double fx_vec[N_MAX] = {
0.1524063822430784E+01,
0.7966778177017837E+00,
0.3982338580692348E+00,
0.1520596783998375E+00,
0.0000000000000000E+00,
-0.4987244125983972E-01,
-0.8537409000331584E-01,
-0.1081748095078604E+00,
-0.1196129141723712E+00,
-0.1207822376352452E+00,
-0.1125917656967557E+00,
-0.9580769740706586E-01,
-0.7108387291437216E-01,
-0.3898427592308333E-01,
0.00000000000000000E+00,
0.69314718055994530E+00,
0.17917594692280550E+01,
0.12801827480081469E+02,
0.39339884187199494E+02,
0.71257038967168009E+02 };
static double x_vec[N_MAX] = {
0.20E+00,
0.40E+00,
0.60E+00,
0.80E+00,
1.00E+00,
1.10E+00,
1.20E+00,
1.30E+00,
1.40E+00,
1.50E+00,
1.60E+00,
1.70E+00,
1.80E+00,
1.90E+00,
2.00E+00,
3.00E+00,
4.00E+00,
10.00E+00,
20.00E+00,
30.00E+00 };
if ( n_data < 0 )
{
n_data = 0;
}
n_data = n_data + 1;
if ( N_MAX < n_data )
{
n_data = 0;
x = 0.0;
fx = 0.0;
}
else
{
x = x_vec[n_data-1];
fx = fx_vec[n_data-1];
}
return;
# undef N_MAX
}
//****************************************************************************80
int i4_log_10 ( int i )
//****************************************************************************80
//
// Purpose:
//
// I4_LOG_10 returns the integer part of the logarithm base 10 of an I4.
//
// Example:
//
// I I4_LOG_10
// ----- --------
// 0 0
// 1 0
// 2 0
// 9 0
// 10 1
// 11 1
// 99 1
// 100 2
// 101 2
// 999 2
// 1000 3
// 1001 3
// 9999 3
// 10000 4
//
// Discussion:
//
// I4_LOG_10 ( I ) + 1 is the number of decimal digits in I.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, the number whose logarithm base 10 is desired.
//
// Output, int I4_LOG_10, the integer part of the logarithm base 10 of
// the absolute value of X.
//
{
int i_abs;
int ten_pow;
int value;
if ( i == 0 )
{
value = 0;
}
else
{
value = 0;
ten_pow = 10;
i_abs = abs ( i );
while ( ten_pow <= i_abs )
{
value = value + 1;
ten_pow = ten_pow * 10;
}
}
return value;
}
//****************************************************************************80
int i4_max ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MAX returns the maximum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, are two integers to be compared.
//
// Output, int I4_MAX, the larger of I1 and I2.
//
{
int value;
if ( i2 < i1 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4_min ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MIN returns the minimum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, two integers to be compared.
//
// Output, int I4_MIN, the smaller of I1 and I2.
//
{
int value;
if ( i1 < i2 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4_modp ( int i, int j )
//****************************************************************************80
//
// Purpose:
//
// I4_MODP returns the nonnegative remainder of I4 division.
//
// Discussion:
//
// If
// NREM = I4_MODP ( I, J )
// NMULT = ( I - NREM ) / J
// then
// I = J * NMULT + NREM
// where NREM is always nonnegative.
//
// The MOD function computes a result with the same sign as the
// quantity being divided. Thus, suppose you had an angle A,
// and you wanted to ensure that it was between 0 and 360.
// Then mod(A,360) would do, if A was positive, but if A
// was negative, your result would be between -360 and 0.
//
// On the other hand, I4_MODP(A,360) is between 0 and 360, always.
//
// I J MOD I4_MODP I4_MODP Factorization
//
// 107 50 7 7 107 = 2 * 50 + 7
// 107 -50 7 7 107 = -2 * -50 + 7
// -107 50 -7 43 -107 = -3 * 50 + 43
// -107 -50 -7 43 -107 = 3 * -50 + 43
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 May 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, the number to be divided.
//
// Input, int J, the number that divides I.
//
// Output, int I4_MODP, the nonnegative remainder when I is
// divided by J.
//
{
int value;
if ( j == 0 )
{
cerr << "\n";
cerr << "I4_MODP - Fatal error!\n";
cerr << " I4_MODP ( I, J ) called with J = " << j << "\n";
exit ( 1 );
}
value = i % j;
if ( value < 0 )
{
value = value + abs ( j );
}
return value;
}
//****************************************************************************80
int i4_power ( int i, int j )
//****************************************************************************80
//
// Purpose:
//
// I4_POWER returns the value of I^J.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, J, the base and the power. J should be nonnegative.
//
// Output, int I4_POWER, the value of I^J.
//
{
int k;
int value;
if ( j < 0 )
{
if ( i == 1 )
{
value = 1;
}
else if ( i == 0 )
{
cerr << "\n";
cerr << "I4_POWER - Fatal error!\n";
cerr << " I^J requested, with I = 0 and J negative.\n";
exit ( 1 );
}
else
{
value = 0;
}
}
else if ( j == 0 )
{
if ( i == 0 )
{
cerr << "\n";
cerr << "I4_POWER - Fatal error!\n";
cerr << " I^J requested, with I = 0 and J = 0.\n";
exit ( 1 );
}
else
{
value = 1;
}
}
else if ( j == 1 )
{
value = i;
}
else
{
value = 1;
for ( k = 1; k <= j; k++ )
{
value = value * i;
}
}
return value;
}
//****************************************************************************80
int i4_sign ( int i )
//****************************************************************************80
//
// Purpose:
//
// I4_SIGN returns the sign of an I4.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 March 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, the integer whose sign is desired.
//
// Output, int I4_SIGN, the sign of I.
{
int value;
if ( i < 0 )
{
value = -1;
}
else
{
value = 1;
}
return value;
}
//****************************************************************************80
int i4_uniform_ab ( int a, int b, int &seed )
//****************************************************************************80
//
// Purpose:
//
// I4_UNIFORM_AB returns a scaled pseudorandom I4 between A and B.
//
// Discussion:
//
// The pseudorandom number should be uniformly distributed
// between A and B.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 October 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int A, B, the limits of the interval.
//
// Input/output, int &SEED, the "seed" value, which should NOT be 0.
// On output, SEED has been updated.
//
// Output, int I4_UNIFORM, a number between A and B.
//
{
int c;
const int i4_huge = 2147483647;
int k;
float r;
int value;
if ( seed == 0 )
{
cerr << "\n";
cerr << "I4_UNIFORM_AB - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
//
// Guarantee A <= B.
//
if ( b < a )
{
c = a;
a = b;
b = c;
}
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r = ( float ) ( seed ) * 4.656612875E-10;
//
// Scale R to lie between A-0.5 and B+0.5.
//
r = ( 1.0 - r ) * ( ( float ) a - 0.5 )
+ r * ( ( float ) b + 0.5 );
//
// Use rounding to convert R to an integer between A and B.
//
value = round ( r );
//
// Guarantee A <= VALUE <= B.
//
if ( value < a )
{
value = a;
}
if ( b < value )
{
value = b;
}
return value;
}
//****************************************************************************80
int i4_wrap ( int ival, int ilo, int ihi )
//****************************************************************************80
//
// Purpose:
//
// I4_WRAP forces an I4 to lie between given limits by wrapping.
//
// Example:
//
// ILO = 4, IHI = 8
//
// I Value
//
// -2 8
// -1 4
// 0 5
// 1 6
// 2 7
// 3 8
// 4 4
// 5 5
// 6 6
// 7 7
// 8 8
// 9 4
// 10 5
// 11 6
// 12 7
// 13 8
// 14 4
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int IVAL, an integer value.
//
// Input, int ILO, IHI, the desired bounds for the integer value.
//
// Output, int I4_WRAP, a "wrapped" version of IVAL.
//
{
int jhi;
int jlo;
int value;
int wide;
jlo = i4_min ( ilo, ihi );
jhi = i4_max ( ilo, ihi );
wide = jhi + 1 - jlo;
if ( wide == 1 )
{
value = jlo;
}
else
{
value = jlo + i4_modp ( ival - jlo, wide );
}
return value;
}
//****************************************************************************80
double i4int_to_r8int ( int imin, int imax, int i, double rmin, double rmax )
//****************************************************************************80
//
// Purpose:
//
// I4INT_TO_R8INT maps an I4 interval to an R8 interval.
//
// Discussion:
//
// The formula is
//
// R := RMIN + ( RMAX - RMIN ) * ( I - IMIN ) / ( IMAX - IMIN )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int IMIN, IMAX, the range.
//
// Input, int I, the integer to be converted.
//
// Input, double RMIN, RMAX, the range.
//
// Output, double R, the corresponding value in [RMIN,RMAX].
//
{
double r;
if ( imax == imin )
{
r = 0.5 * ( rmin + rmax );
}
else
{
r = ( ( double ) ( imax - i ) * rmin
+ ( double ) ( i - imin ) * rmax )
/ ( double ) ( imax - imin );
}
return r;
}
//****************************************************************************80
void i4mat_print ( int m, int n, int a[], string title )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_PRINT prints an I4MAT.
//
// Discussion:
//
// An I4MAT is an MxN array of I4's, stored by (I,J) -> [I+J*M].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, int A[M*N], the M by N matrix.
//
// Input, string TITLE, a title.
//
{
i4mat_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
//****************************************************************************80
void i4mat_print_some ( int m, int n, int a[], int ilo, int jlo, int ihi,
int jhi, string title )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_PRINT_SOME prints some of an I4MAT.
//
// Discussion:
//
// An I4MAT is an MxN array of I4's, stored by (I,J) -> [I+J*M].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 August 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows of the matrix.
// M must be positive.
//
// Input, int N, the number of columns of the matrix.
// N must be positive.
//
// Input, int A[M*N], the matrix.
//
// Input, int ILO, JLO, IHI, JHI, designate the first row and
// column, and the last row and column to be printed.
//
// Input, string TITLE, a title.
//
{
# define INCX 10
int i;
int i2hi;
int i2lo;
int j;
int j2hi;
int j2lo;
cout << "\n";
cout << title << "\n";
if ( m <= 0 || n <= 0 )
{
cout << "\n";
cout << " (None)\n";
return;
}
//
// Print the columns of the matrix, in strips of INCX.
//
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
if ( n < j2hi )
{
j2hi = n;
}
if ( jhi < j2hi )
{
j2hi = jhi;
}
cout << "\n";
//
// For each column J in the current range...
//
// Write the header.
//
cout << " Col:";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << " " << setw(6) << j - 1;
}
cout << "\n";
cout << " Row\n";
cout << "\n";
//
// Determine the range of the rows in this strip.
//
if ( 1 < ilo )
{
i2lo = ilo;
}
else
{
i2lo = 1;
}
if ( ihi < m )
{
i2hi = ihi;
}
else
{
i2hi = m;
}
for ( i = i2lo; i <= i2hi; i++ )
{
//
// Print out (up to INCX) entries in row I, that lie in the current strip.
//
cout << setw(5) << i - 1 << ":";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << " " << setw(6) << a[i-1+(j-1)*m];
}
cout << "\n";
}
}
return;
# undef INCX
}
//****************************************************************************80
void i4vec_copy ( int n, int a1[], int a2[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_COPY copies an I4VEC.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 April 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, int A1[N], the vector to be copied.
//
// Output, int A2[N], the copy of A1.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a2[i] = a1[i];
}
return;
}
//****************************************************************************80
int *i4vec_indicator0_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_INDICATOR0_NEW sets an I4VEC to the indicator vector (0,1,2,...).
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Output, int I4VEC_INDICATOR0_NEW[N], the array.
//
{
int *a;
int i;
a = new int[n];
for ( i = 0; i < n; i++ )
{
a[i] = i;
}
return a;
}
//****************************************************************************80
int *i4vec_indicator1_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_INDICATOR1_NEW sets an I4VEC to the indicator vector (1,2,3,...).
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Output, int I4VEC_INDICATOR1_NEW[N], the array.
//
{
int *a;
int i;
a = new int[n];
for ( i = 0; i < n; i++ )
{
a[i] = i + 1;
}
return a;
}
//****************************************************************************80
void i4vec_permute ( int n, int p[], int a[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_PERMUTE permutes an I4VEC in place.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// This routine permutes an array of integer "objects", but the same
// logic can be used to permute an array of objects of any arithmetic
// type, or an array of objects of any complexity. The only temporary
// storage required is enough to store a single object. The number
// of data movements made is N + the number of cycles of order 2 or more,
// which is never more than N + N/2.
//
// Example:
//
// Input:
//
// N = 5
// P = ( 1, 3, 4, 0, 2 )
// A = ( 1, 2, 3, 4, 5 )
//
// Output:
//
// A = ( 2, 4, 5, 1, 3 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 October 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of objects.
//
// Input, int P[N], the permutation. P(I) = J means
// that the I-th element of the output array should be the J-th
// element of the input array.
//
// Input/output, int A[N], the array to be permuted.
//
{
int a_temp;
int i;
int iget;
int iput;
int istart;
if ( !perm0_check ( n, p ) )
{
cerr << "\n";
cerr << "I4VEC_PERMUTE - Fatal error!\n";
cerr << " PERM0_CHECK rejects permutation.\n";
exit ( 1 );
}
//
// In order for the sign negation trick to work, we need to assume that the
// entries of P are strictly positive. Presumably, the lowest number is 0.
// So temporarily add 1 to each entry to force positivity.
//
for ( i = 0; i < n; i++ )
{
p[i] = p[i] + 1;
}
//
// Search for the next element of the permutation that has not been used.
//
for ( istart = 1; istart <= n; istart++ )
{
if ( p[istart-1] < 0 )
{
continue;
}
else if ( p[istart-1] == istart )
{
p[istart-1] = - p[istart-1];
continue;
}
else
{
a_temp = a[istart-1];
iget = istart;
//
// Copy the new value into the vacated entry.
//
for ( ; ; )
{
iput = iget;
iget = p[iget-1];
p[iput-1] = - p[iput-1];
if ( iget < 1 || n < iget )
{
cerr << "\n";
cerr << "I4VEC_PERMUTE - Fatal error!\n";
cerr << " Entry IPUT = " << iput << " of the permutation has\n";
cerr << " an illegal value IGET = " << iget << ".\n";
exit ( 1 );
}
if ( iget == istart )
{
a[iput-1] = a_temp;
break;
}
a[iput-1] = a[iget-1];
}
}
}
//
// Restore the signs of the entries.
//
for ( i = 0; i < n; i++ )
{
p[i] = - p[i];
}
//
// Restore the entries.
//
for ( i = 0; i < n; i++ )
{
p[i] = p[i] - 1;
}
return;
}
//****************************************************************************80
void i4vec_print ( int n, int a[], string title )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_PRINT prints an I4VEC.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 November 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, int A[N], the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(8) << a[i] << "\n";
}
return;
}
//****************************************************************************80
void i4vec_transpose_print ( int n, int a[], string title )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_TRANSPOSE_PRINT prints an I4VEC "transposed".
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Example:
//
// A = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }
// TITLE = "My vector: "
//
// My vector: 1 2 3 4 5
// 6 7 8 9 10
// 11
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 July 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, int A[N], the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
int ihi;
int ilo;
int title_len;
title_len = title.length ( );
for ( ilo = 1; ilo <= n; ilo = ilo + 5 )
{
ihi = ilo + 5 - 1;
if ( n < ihi )
{
ihi = n;
}
if ( ilo == 1 )
{
cout << title;
}
else
{
for ( i = 1; i <= title_len; i++ )
{
cout << " ";
}
}
for ( i = ilo; i <= ihi; i++ )
{
cout << setw(12) << a[i-1];
}
cout << "\n";
}
return;
}
//****************************************************************************80
void i4vec_zeros ( int n, int a[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_ZEROS zeroes an I4VEC.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, int A[N], a vector of zeroes.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = 0;
}
return;
}
//****************************************************************************80
int *i4vec_zeros_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_ZEROS_NEW creates and zeroes an I4VEC.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, int I4VEC_ZEROS_NEW[N], a vector of zeroes.
//
{
int *a;
int i;
a = new int[n];
for ( i = 0; i < n; i++ )
{
a[i] = 0;
}
return a;
}
//****************************************************************************80
double *legendre_zeros ( int order )
//****************************************************************************80
//
// Purpose:
//
// LEGENDRE_ZEROS returns the zeros of the Legendre polynomial of degree N.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 June 2011
//
// Author:
//
// Original FORTRAN77 version by Philip Davis, Philip Rabinowitz.
// C++ version by John Burkardt.
//
// Reference:
//
// Philip Davis, Philip Rabinowitz,
// Methods of Numerical Integration,
// Second Edition,
// Dover, 2007,
// ISBN: 0486453391,
// LC: QA299.3.D28.
//
// Parameters:
//
// Input, int ORDER, the order.
// ORDER must be greater than 0.
//
// Output, double LEGENDRE_ZEROS[ORDER], the zeros.
//
{
double d1;
double d2pn;
double d3pn;
double d4pn;
double dp;
double dpn;
double e1;
double fx;
double h;
int i;
int iback;
int k;
int m;
int mp1mi;
int ncopy;
int nmove;
double p;
double pk;
double pkm1;
double pkp1;
const double r8_pi = 3.141592653589793;
double t;
double u;
double v;
double x0;
double *xtab;
double xtemp;
xtab = new double[order];
e1 = ( double ) ( order * ( order + 1 ) );
m = ( order + 1 ) / 2;
for ( i = 1; i <= m; i++ )
{
mp1mi = m + 1 - i;
t = ( double ) ( 4 * i - 1 ) * r8_pi / ( double ) ( 4 * order + 2 );
x0 = cos ( t ) * ( 1.0 - ( 1.0 - 1.0 / ( double ) ( order ) )
/ ( double ) ( 8 * order * order ) );
pkm1 = 1.0;
pk = x0;
for ( k = 2; k <= order; k++ )
{
pkp1 = 2.0 * x0 * pk - pkm1 - ( x0 * pk - pkm1 ) / ( double ) ( k );
pkm1 = pk;
pk = pkp1;
}
d1 = ( double ) ( order ) * ( pkm1 - x0 * pk );
dpn = d1 / ( 1.0 - x0 * x0 );
d2pn = ( 2.0 * x0 * dpn - e1 * pk ) / ( 1.0 - x0 * x0 );
d3pn = ( 4.0 * x0 * d2pn + ( 2.0 - e1 ) * dpn ) / ( 1.0 - x0 * x0 );
d4pn = ( 6.0 * x0 * d3pn + ( 6.0 - e1 ) * d2pn ) / ( 1.0 - x0 * x0 );
u = pk / dpn;
v = d2pn / dpn;
//
// Initial approximation H:
//
h = -u * ( 1.0 + 0.5 * u * ( v + u * ( v * v - d3pn / ( 3.0 * dpn ) ) ) );
//
// Refine H using one step of Newton's method:
//
p = pk + h * ( dpn + 0.5 * h * ( d2pn + h / 3.0
* ( d3pn + 0.25 * h * d4pn ) ) );
dp = dpn + h * ( d2pn + 0.5 * h * ( d3pn + h * d4pn / 3.0 ) );
h = h - p / dp;
xtemp = x0 + h;
xtab[mp1mi-1] = xtemp;
fx = d1 - h * e1 * ( pk + 0.5 * h * ( dpn + h / 3.0
* ( d2pn + 0.25 * h * ( d3pn + 0.2 * h * d4pn ) ) ) );
}
if ( ( order % 2 ) == 1 )
{
xtab[0] = 0.0;
}
//
// Shift the data up.
//
nmove = ( order + 1 ) / 2;
ncopy = order - nmove;
for ( i = 1; i <= nmove; i++ )
{
iback = order + 1 - i;
xtab[iback-1] = xtab[iback-ncopy-1];
}
//
// Reflect values for the negative abscissas.
//
for ( i = 1; i <= order - nmove; i++ )
{
xtab[i-1] = - xtab[order-i];
}
return xtab;
}
//****************************************************************************80
bool perm0_check ( int n, int p[] )
//****************************************************************************80
//
// Purpose:
//
// PERM0_CHECK checks a permutation of ( 0, ..., N-1 ).
//
// Discussion:
//
// The routine verifies that each of the integers from 0 to
// to N-1 occurs among the N entries of the permutation.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 May 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, int P[N], the array to check.
//
// Output, bool PERM0_CHECK, is
// TRUE if P is a legal permutation of 0,...,N-1.
// FALSE if P is not a legal permuation of 0,...,N-1.
//
{
bool check;
int location;
int value;
check = true;
for ( value = 0; value < n; value++ )
{
check = false;
for ( location = 0; location < n; location++ )
{
if ( p[location] == value )
{
check = true;
break;
}
}
if ( ! check )
{
cout << "\n";
cout << "PERM0_CHECK - Fatal error!\n";
cout << " Permutation is missing value " << value << "\n";
break;
}
}
return check;
}
//****************************************************************************80
int *perm0_uniform_new ( int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// PERM0_UNIFORM_NEW selects a random permutation of 0,...,N-1.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 May 2015
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the number of objects to be permuted.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, int PERM0_UNIFORM_NEW[N], a permutation of
// (0, 1, ..., N-1).
//
{
int i;
int j;
int k;
int *p;
p = new int[n];
for ( i = 0; i < n; i++ )
{
p[i] = i;
}
for ( i = 0; i < n; i++ )
{
j = i4_uniform_ab ( i, n - 1, seed );
k = p[i];
p[i] = p[j];
p[j] = k;
}
return p;
}
//****************************************************************************80
bool perm1_check ( int n, int p[] )
//****************************************************************************80
//
// Purpose:
//
// PERM1_CHECK checks a permutation of (1, ..., N ).
//
// Discussion:
//
// The routine verifies that each of the integers from 0 to
// to N-1 occurs among the N entries of the permutation.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 May 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, int P[N], the array to check.
//
// Output, bool PERM1_CHECK, is
// TRUE if P is a legal permutation of 1,...,N.
// FALSE if P is not a legal permuation of 1,...,N.
//
{
bool check;
int location;
int value;
check = true;
for ( value = 1; value <= n; value++ )
{
check = false;
for ( location = 0; location < n; location++ )
{
if ( p[location] == value )
{
check = true;
break;
}
}
if ( ! check )
{
cout << "\n";
cout << "PERM1_CHECK - Fatal error!\n";
cout << " Permutation is missing value " << value << "\n";
break;
}
}
return check;
}
//****************************************************************************80
int *perm1_uniform_new ( int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// PERM1_UNIFORM_NEW selects a random permutation of 1,...,N.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 May 2015
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the number of objects to be permuted.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, int PERM1_UNIFORM_NEW[N], a permutation of
// (1, ..., N).
//
{
int i;
int j;
int k;
int *p;
p = new int[n];
for ( i = 0; i < n; i++ )
{
p[i] = i + 1;
}
for ( i = 0; i < n; i++ )
{
j = i4_uniform_ab ( i, n - 1, seed );
k = p[i];
p[i] = p[j];
p[j] = k;
}
return p;
}
//****************************************************************************80
double r8_abs ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ABS returns the absolute value of an R8.
//
// Discussion:
//
// The C++ math library provides the function fabs() which is preferred.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 November 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the quantity whose absolute value is desired.
//
// Output, double R8_ABS, the absolute value of X.
//
{
double value;
if ( 0.0 <= x )
{
value = + x;
}
else
{
value = - x;
}
return value;
}
//****************************************************************************80
double r8_acos ( double c )
//****************************************************************************80
//
// Purpose:
//
// R8_ACOS computes the arc cosine function, with argument truncation.
//
// Discussion:
//
// If you call your system ACOS routine with an input argument that is
// outside the range [-1.0, 1.0 ], you may get an unpleasant surprise.
// This routine truncates arguments outside the range.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 June 2002
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double C, the argument, the cosine of an angle.
//
// Output, double R8_ACOS, an angle whose cosine is C.
//
{
const double r8_pi = 3.141592653589793;
double value;
if ( c <= -1.0 )
{
value = r8_pi;
}
else if ( 1.0 <= c )
{
value = 0.0;
}
else
{
value = acos ( c );
}
return value;
}
//****************************************************************************80
double r8_acosh ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ACOSH returns the inverse hyperbolic cosine of a number.
//
// Discussion:
//
// Applying the inverse function
//
// Y = R8_ACOSH(X)
//
// implies that
//
// X = COSH(Y) = 0.5 * ( EXP(Y) + EXP(-Y) ).
//
// For every X greater than or equal to 1, there are two possible
// choices Y such that X = COSH(Y), differing only in sign. It
// is usual to resolve this choice by taking the value of ACOSH(X)
// to be nonnegative.
//
// Method:
//
// One formula is:
//
// R8_ACOSH = LOG ( X + SQRT ( X^2 - 1.0 ) )
//
// but this formula suffers from roundoff and overflow problems.
// The formula used here was recommended by W Kahan, as discussed
// by Moler.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 May 2003
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Cleve Moler,
// Trigonometry is a Complex Subject,
// MATLAB News and Notes,
// Summer 1998.
//
// Parameters:
//
// Input, double X, the number whose inverse hyperbolic cosine is desired.
// X should be greater than or equal to 1.
//
// Output, double R8_ACOSH, the inverse hyperbolic cosine of X. The
// principal value (that is, the positive value of the two ) is returned.
//
{
double value;
if ( x < 1.0 )
{
cerr << "\n";
cerr << "R8_ACOSH - Fatal error!\n";
cerr << " Argument X must satisfy 1 <= X.\n";
cerr << " The input X = " << x << "\n";
exit ( 1 );
}
value = 2.0 * log (
sqrt ( 0.5 * ( x + 1.0 ) ) + sqrt ( 0.5 * ( x - 1.0 ) ) );
return value;
}
//****************************************************************************80
double r8_add ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_ADD adds two R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 August 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the numbers to be added.
//
// Output, double R8_ADD, the sum of X and Y.
//
{
double value;
value = x + y;
return value;
}
//****************************************************************************80
double r8_agm ( double a, double b )
//****************************************************************************80
//
// Purpose:
//
// R8_AGM computes the arithmetic-geometric mean of A and B.
//
// Discussion:
//
// The AGM is defined for nonnegative A and B.
//
// The AGM of numbers A and B is defined by setting
//
// A(0) = A,
// B(0) = B
//
// A(N+1) = ( A(N) + B(N) ) / 2
// B(N+1) = sqrt ( A(N) * B(N) )
//
// The two sequences both converge to AGM(A,B).
//
// In Mathematica, the AGM can be evaluated by
//
// ArithmeticGeometricMean [ a, b ]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 July 2014
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Stephen Wolfram,
// The Mathematica Book,
// Fourth Edition,
// Cambridge University Press, 1999,
// ISBN: 0-521-64314-7,
// LC: QA76.95.W65.
//
// Parameters:
//
// Input, double A, B, the arguments whose AGM is to be computed.
// 0 <= A, 0 <= B.
//
// Output, double R8_AGM, the arithmetic-geometric mean of A and B.
//
{
double a1;
double a2;
double b1;
double b2;
int it;
int it_max = 1000;
double tol;
double value;
if ( a < 0.0 )
{
cerr << "\n";
cerr << "R8_AGM - Fatal error!\n";
cerr << " A < 0.\n";
exit ( 1 );
}
if ( b < 0.0 )
{
cerr << "\n";
cerr << "R8_AGM - Fatal error!\n";
cerr << " B < 0.\n";
exit ( 1 );
}
if ( a == 0.0 || b == 0.0 )
{
value = 0.0;
return value;
}
if ( a == b )
{
value = a;
return value;
}
a1 = a;
b1 = b;
it = 0;
tol = 100.0 * r8_epsilon ( );
for ( ; ; )
{
it = it + 1;
a2 = ( a1 + b1 ) / 2.0;
b2 = sqrt ( a1 * b1 );
if ( fabs ( a2 - b2 ) <= tol * ( a2 + b2 ) )
{
break;
}
if ( it_max < it )
{
break;
}
a1 = a2;
b1 = b2;
}
value = a2;
return value;
}
//****************************************************************************80
double r8_aint ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_AINT truncates an R8 argument to an integer.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 1 September 2011
//
// Author:
//
// John Burkardt.
//
// Parameters:
//
// Input, double X, the argument.
//
// Output, double R8_AINT, the truncated version of X.
//
{
double value;
if ( x < 0.0 )
{
value = - ( double ) ( ( int ) ( fabs ( x ) ) );
}
else
{
value = ( double ) ( ( int ) ( fabs ( x ) ) );
}
return value;
}
//****************************************************************************80
double r8_asin ( double s )
//****************************************************************************80
//
// Purpose:
//
// R8_ASIN computes the arc sine function, with argument truncation.
//
// Discussion:
//
// If you call your system ASIN routine with an input argument that is
// outside the range [-1.0, 1.0 ], you may get an unpleasant surprise.
// This routine truncates arguments outside the range.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 June 2002
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double S, the argument, the sine of an angle.
//
// Output, double R8_ASIN, an angle whose sine is S.
//
{
double angle;
const double r8_pi = 3.141592653589793;
if ( s <= -1.0 )
{
angle = - r8_pi / 2.0;
}
else if ( 1.0 <= s )
{
angle = r8_pi / 2.0;
}
else
{
angle = asin ( s );
}
return angle;
}
//****************************************************************************80
double r8_asinh ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ASINH returns the inverse hyperbolic sine of a number.
//
// Discussion:
//
// The assertion that:
//
// Y = R8_ASINH ( X )
//
// implies that
//
// X = SINH(Y) = 0.5 * ( EXP(Y) - EXP(-Y) ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 November 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose inverse hyperbolic
// sine is desired.
//
// Output, double R8_ASINH, the inverse hyperbolic sine of X.
//
{
double value;
value = log ( x + sqrt ( x * x + 1.0 ) );
return value;
}
//****************************************************************************80
double r8_atan ( double y, double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ATAN computes the inverse tangent of the ratio Y / X.
//
// Discussion:
//
// R8_ATAN returns an angle whose tangent is ( Y / X ), a job which
// the built in functions ATAN and ATAN2 already do.
//
// However:
//
// * R8_ATAN always returns a positive angle, between 0 and 2 PI,
// while ATAN and ATAN2 return angles in the interval [-PI/2,+PI/2]
// and [-PI,+PI] respectively;
//
// * R8_ATAN accounts for the signs of X and Y, (as does ATAN2). The ATAN
// function by contrast always returns an angle in the first or fourth
// quadrants.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 August 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double Y, X, two quantities which represent the tangent of
// an angle. If Y is not zero, then the tangent is (Y/X).
//
// Output, double R8_ATAN, an angle between 0 and 2 * PI, whose tangent is
// (Y/X), and which lies in the appropriate quadrant so that the signs
// of its cosine and sine match those of X and Y.
//
{
double abs_x;
double abs_y;
const double r8_pi = 3.141592653589793;
double theta;
double theta_0;
//
// Special cases:
//
if ( x == 0.0 )
{
if ( 0.0 < y )
{
theta = r8_pi / 2.0;
}
else if ( y < 0.0 )
{
theta = 3.0 * r8_pi / 2.0;
}
else if ( y == 0.0 )
{
theta = 0.0;
}
}
else if ( y == 0.0 )
{
if ( 0.0 < x )
{
theta = 0.0;
}
else if ( x < 0.0 )
{
theta = r8_pi;
}
}
//
// We assume that ATAN2 is correct when both arguments are positive.
//
else
{
abs_y = fabs ( y );
abs_x = fabs ( x );
theta_0 = atan2 ( abs_y, abs_x );
if ( 0.0 < x && 0.0 < y )
{
theta = theta_0;
}
else if ( x < 0.0 && 0.0 < y )
{
theta = r8_pi - theta_0;
}
else if ( x < 0.0 && y < 0.0 )
{
theta = r8_pi + theta_0;
}
else if ( 0.0 < x && y < 0.0 )
{
theta = 2.0 * r8_pi - theta_0;
}
}
return theta;
}
//****************************************************************************80
double r8_atanh ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ATANH returns the inverse hyperbolic tangent of a number.
//
// Discussion:
//
// Y = R8_ATANH ( X )
//
// implies that
//
// X = TANH(Y) = ( EXP(Y) - EXP(-Y) ) / ( EXP(Y) + EXP(-Y) )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 November 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose inverse hyperbolic
// tangent is desired. The absolute value of X should be less than
// or equal to 1.
//
// Output, double R8_ATANH, the inverse hyperbolic tangent of X.
//
{
const double r8_huge = 1.79769313486231571E+308;
double value;
if ( x <= -1.0 )
{
value = - r8_huge;
}
else if ( 1.0 <= x )
{
value = + r8_huge;
}
else
{
value = 0.5 * log ( ( 1.0 + x ) / ( 1.0 - x ) );
}
return value;
}
//****************************************************************************80
double r8_big ( )
//****************************************************************************80
//
// Purpose:
//
// R8_BIG returns a "big" R8.
//
// Discussion:
//
// The value returned by this function is NOT required to be the
// maximum representable R8.
// We simply want a "very large" but non-infinite number.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_BIG, a "big" R8 value.
//
{
double value;
value = 1.0E+30;
return value;
}
//****************************************************************************80
double r8_cas ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_CAS returns the "casine" of an R8.
//
// Discussion:
//
// The "casine", used in the discrete Hartley transform, is abbreviated
// CAS(X), and defined by:
//
// CAS(X) = cos ( X ) + sin( X )
// = sqrt ( 2 ) * sin ( X + pi/4 )
// = sqrt ( 2 ) * cos ( X - pi/4 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose casine is desired.
//
// Output, double R8_CAS, the casine of X, which will be between
// plus or minus the square root of 2.
//
{
double value;
value = cos ( x ) + sin ( x );
return value;
}
//****************************************************************************80
double r8_ceiling ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_CEILING rounds an R8 up to the nearest integral R8.
//
// Example:
//
// X R8_CEILING(X)
//
// -1.1 -1.0
// -1.0 -1.0
// -0.9 0.0
// -0.1 0.0
// 0.0 0.0
// 0.1 1.0
// 0.9 1.0
// 1.0 1.0
// 1.1 2.0
// 2.9 3.0
// 3.0 3.0
// 3.14159 4.0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose ceiling is desired.
//
// Output, double R8_CEILING, the ceiling of X.
//
{
double value;
value = ( double ) ( ( int ) x );
if ( value < x )
{
value = value + 1.0;
}
return value;
}
//****************************************************************************80
double r8_choose ( int n, int k )
//****************************************************************************80
//
// Purpose:
//
// R8_CHOOSE computes the combinatorial coefficient C(N,K).
//
// Discussion:
//
// Real arithmetic is used, and C(N,K) is computed directly, via
// Gamma functions, rather than recursively.
//
// C(N,K) is the number of distinct combinations of K objects
// chosen from a set of N distinct objects. A combination is
// like a set, in that order does not matter.
//
// C(N,K) = N! / ( (N-K)! * K! )
//
// Example:
//
// The number of combinations of 2 things chosen from 5 is 10.
//
// C(5,2) = ( 5 * 4 * 3 * 2 * 1 ) / ( ( 3 * 2 * 1 ) * ( 2 * 1 ) ) = 10.
//
// The actual combinations may be represented as:
//
// (1,2), (1,3), (1,4), (1,5), (2,3),
// (2,4), (2,5), (3,4), (3,5), (4,5).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 July 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the value of N.
//
// Input, int K, the value of K.
//
// Output, double R8_CHOOSE, the value of C(N,K)
//
{
double arg;
double fack;
double facn;
double facnmk;
double value;
if ( n < 0 )
{
value = 0.0;
}
else if ( k == 0 )
{
value = 1.0;
}
else if ( k == 1 )
{
value = ( double ) ( n );
}
else if ( 1 < k && k < n - 1 )
{
arg = ( double ) ( n + 1 );
facn = r8_gamma_log ( arg );
arg = ( double ) ( k + 1 );
fack = r8_gamma_log ( arg );
arg = ( double ) ( n - k + 1 );
facnmk = r8_gamma_log ( arg );
value = r8_nint ( exp ( facn - fack - facnmk ) );
}
else if ( k == n - 1 )
{
value = ( double ) ( n );
}
else if ( k == n )
{
value = 1.0;
}
else
{
value = 0.0;
}
return value;
}
//****************************************************************************80
double r8_chop ( int place, double x )
//****************************************************************************80
//
// Purpose:
//
// R8_CHOP chops an R8 to a given number of binary places.
//
// Example:
//
// 3.875 = 2 + 1 + 1/2 + 1/4 + 1/8.
//
// The following values would be returned for the 'chopped' value of
// 3.875:
//
// PLACE Value
//
// 1 2
// 2 3 = 2 + 1
// 3 3.5 = 2 + 1 + 1/2
// 4 3.75 = 2 + 1 + 1/2 + 1/4
// 5+ 3.875 = 2 + 1 + 1/2 + 1/4 + 1/8
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int PLACE, the number of binary places to preserve.
// PLACE = 0 means return the integer part of X.
// PLACE = 1 means return the value of X, correct to 1/2.
// PLACE = 2 means return the value of X, correct to 1/4.
// PLACE = -1 means return the value of X, correct to 2.
//
// Input, double X, the number to be chopped.
//
// Output, double R8_CHOP, the chopped number.
//
{
double fac;
int temp;
double value;
temp = ( int ) ( r8_log_2 ( x ) );
fac = pow ( 2.0, ( temp - place + 1 ) );
value = ( double ) ( ( int ) ( x / fac ) ) * fac;
return value;
}
//****************************************************************************80
double r8_cosd ( double degrees )
//****************************************************************************80
//
// Purpose:
//
// R8_COSD returns the cosine of an angle given in degrees.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 July 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double DEGREES, the angle in degrees.
//
// Output, double R8_COSD, the cosine of the angle.
//
{
const double r8_pi = 3.141592653589793;
double radians;
double value;
radians = r8_pi * ( degrees / 180.0 );
value = cos ( radians );
return value;
}
//****************************************************************************80
double r8_cot ( double angle )
//****************************************************************************80
//
// Purpose:
//
// R8_COT returns the cotangent of an angle.
//
// Discussion:
//
// R8_COT ( THETA ) = COS ( THETA ) / SIN ( THETA )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 May 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double ANGLE, the angle, in radians.
//
// Output, double R8_COT, the cotangent of the angle.
//
{
double value;
value = cos ( angle ) / sin ( angle );
return value;
}
//****************************************************************************80
double r8_cotd ( double degrees )
//****************************************************************************80
//
// Purpose:
//
// R8_COTD returns the cotangent of an angle given in degrees.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 July 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double DEGREES, the angle in degrees.
//
// Output, double R8_COTD, the cotangent of the angle.
//
{
const double r8_pi = 3.141592653589793;
double radians;
double value;
radians = r8_pi * ( degrees / 180.0 );
value = cos ( radians ) / sin ( radians );
return value;
}
//****************************************************************************80
double r8_csc ( double theta )
//****************************************************************************80
//
// Purpose:
//
// R8_CSC returns the cosecant of X.
//
// Discussion:
//
// R8_CSC ( THETA ) = 1.0 / SIN ( THETA )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 March 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double THETA, the angle, in radians, whose cosecant is desired.
// It must be the case that SIN ( THETA ) is not zero.
//
// Output, double R8_CSC, the cosecant of THETA.
//
{
double value;
value = sin ( theta );
if ( value == 0.0 )
{
cerr << " \n";
cerr << "R8_CSC - Fatal error!\n";
cerr << " Cosecant undefined for THETA = " << theta << "\n";
exit ( 1 );
}
value = 1.0 / value;
return value;
}
//****************************************************************************80
double r8_cscd ( double degrees )
//****************************************************************************80
//
// Purpose:
//
// R8_CSCD returns the cosecant of an angle given in degrees.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 July 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double DEGREES, the angle in degrees.
//
// Output, double R8_CSCD, the cosecant of the angle.
//
{
const double r8_pi = 3.141592653589793;
double radians;
double value;
radians = r8_pi * ( degrees / 180.0 );
value = 1.0 / sin ( radians );
return value;
}
//****************************************************************************80
double r8_cube_root ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_CUBE_ROOT returns the cube root of an R8.
//
// Discussion:
//
// This routine is designed to avoid the possible problems that can occur
// when formulas like 0.0^(1/3) or (-1.0)^(1/3) are to be evaluated.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input double X, the number whose cube root is desired.
//
// Output, double R8_CUBE_ROOT, the cube root of X.
//
{
double value;
if ( 0.0 < x )
{
value = pow ( ( double ) x, ( 1.0 / 3.0 ) );
}
else if ( x == 0.0 )
{
value = 0.0;
}
else
{
value = - pow ( ( double ) ( fabs ( x ) ), ( 1.0 / 3.0 ) );
}
return value;
}
//****************************************************************************80
double r8_degrees ( double radians )
//****************************************************************************80
//
// Purpose:
//
// R8_DEGREES converts an angle from radian to degree measure.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 May 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double RADIANS, the angle measurement in radians.
//
// Output, double R8_DEGREES, the angle measurement in degrees.
//
{
const double r8_pi = 3.1415926535897932384626434;
double value;
value = radians * 180.0 / r8_pi;
return value;
}
//****************************************************************************80
double r8_diff ( double x, double y, int n )
//****************************************************************************80
//
// Purpose:
//
// R8_DIFF computes (X-Y) to a specified accuracy.
//
// Discussion:
//
// The user controls how many binary digits of accuracy
// are to be used.
//
// N determines the accuracy of the value. If N = 10,
// for example, only 11 binary places will be used in the arithmetic.
// In general, only N+1 binary places will be used.
//
// N may be zero. However, a negative value of N should
// not be used, since this will cause both X and Y to look like 0.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the two values whose difference is desired.
//
// Input, int N, the number of binary digits to use.
//
// Output, double R8_DIFF, the value of X-Y.
//
{
double cx;
double cy;
double pow2;
double size;
double value;
if ( x == y )
{
value = 0.0;
return value;
}
pow2 = pow ( 2.0, n );
//
// Compute the magnitude of X and Y, and take the larger of the
// two. At least one of the two values is not zero//
//
size = r8_max ( fabs ( x ), fabs ( y ) );
//
// Make normalized copies of X and Y. One of the two values will
// actually be equal to 1.
//
cx = x / size;
cy = y / size;
//
// Here's where rounding comes in. We know that the larger of the
// the two values equals 1. We multiply both values by 2^N,
// where N+1 is the number of binary digits of accuracy we want
// to use, truncate the values, and divide back by 2^N.
//
cx = ( double ) ( ( int ) ( cx * pow2 + 0.5 * r8_sign ( cx ) ) ) / pow2;
cy = ( double ) ( ( int ) ( cy * pow2 + 0.5 * r8_sign ( cy ) ) ) / pow2;
//
// Take the difference now.
//
value = cx - cy;
//
// Undo the scaling.
//
value = value * size;
return value;
}
//****************************************************************************80
int r8_digit ( double x, int idigit )
//****************************************************************************80
//
// Purpose:
//
// R8_DIGIT returns a particular decimal digit of an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose IDIGIT-th decimal digit is desired.
// Note that if X is zero, all digits will be returned as 0.
//
// Input, int IDIGIT, the position of the desired decimal digit.
// A value of 1 means the leading digit, a value of 2 the second digit
// and so on.
//
// Output, int R8_DIGIT, the value of the IDIGIT-th decimal digit of X.
//
{
int digit;
int i;
int ival;
if ( x == 0.0 )
{
digit = 0;
return digit;
}
if ( idigit <= 0 )
{
digit = 0;
return digit;
}
//
// Force X to lie between 1 and 10.
//
x = fabs ( x );
while ( x < 1.0 )
{
x = x * 10.0;
}
while ( 10.0 <= x )
{
x = x / 10.0;
}
for ( i = 1; i <= idigit; i++ )
{
ival = ( int ) ( x );
x = ( x - ( double ) ival ) * 10.0;
}
digit = ival;
return digit;
}
//****************************************************************************80
double r8_divide_i4 ( int i, int j )
//****************************************************************************80
//
// Purpose:
//
// R8_DIVIDE_I4 returns an I4 fraction as an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 June 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, J, the numerator and denominator.
//
// Output, double R8_DIVIDE_I4, the value of (I/J).
//
{
double value;
value = ( double ) ( i ) / ( double ) ( j );
return value;
}
//****************************************************************************80
double r8_e ( )
//****************************************************************************80
//
// Purpose:
//
// R8_E returns the value of the base of the natural logarithm system.
//
// Definition:
//
// E = Limit ( N -> +oo ) ( 1 + 1 / N )^N
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 May 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_E, the base of the natural logarithm system.
//
{
const double r8_e_save = 2.718281828459045235360287;
double value;
value = r8_e_save;
return value;
}
//****************************************************************************80
double r8_epsilon ( )
//****************************************************************************80
//
// Purpose:
//
// R8_EPSILON returns the R8 roundoff unit.
//
// Discussion:
//
// The roundoff unit is a number R which is a power of 2 with the
// property that, to the precision of the computer's arithmetic,
// 1 < 1 + R
// but
// 1 = ( 1 + R / 2 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_EPSILON, the R8 round-off unit.
//
{
const double value = 2.220446049250313E-016;
return value;
}
//****************************************************************************80
double r8_epsilon_compute ( )
//****************************************************************************80
//
// Purpose:
//
// R8_EPSILON_COMPUTE computes the R8 roundoff unit.
//
// Discussion:
//
// The roundoff unit is a number R which is a power of 2 with the
// property that, to the precision of the computer's arithmetic,
// 1 < 1 + R
// but
// 1 = ( 1 + R / 2 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_EPSILON_COMPUTE, the R8 round-off unit.
//
{
double one;
double temp;
double test;
static double value = 0.0;
if ( value == 0.0 )
{
one = ( double ) ( 1 );
value = one;
temp = value / 2.0;
test = r8_add ( one, temp );
while ( one < test )
{
value = temp;
temp = value / 2.0;
test = r8_add ( one, temp );
}
}
return value;
}
//****************************************************************************80
double r8_exp ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_EXP computes the exponential function, avoiding overflow and underflow.
//
// Discussion:
//
// For arguments of very large magnitude, the evaluation of the
// exponential function can cause computational problems. Some languages
// and compilers may return an infinite value or a "Not-a-Number".
// An alternative, when dealing with a wide range of inputs, is simply
// to truncate the calculation for arguments whose magnitude is too large.
// Whether this is the right or convenient approach depends on the problem
// you are dealing with, and whether or not you really need accurate
// results for large magnitude inputs, or you just want your code to
// stop crashing.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the argument of the exponential function.
//
// Output, double R8_EXP, the value of exp ( X ).
//
{
const double r8_big = 1.0E+30;
const double r8_log_max = +69.0776;
const double r8_log_min = -69.0776;
double value;
if ( x <= r8_log_min )
{
value = 0.0;
}
else if ( x < r8_log_max )
{
value = exp ( x );
}
else
{
value = r8_big;
}
return value;
}
//****************************************************************************80
double r8_factorial ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8_FACTORIAL computes the factorial of N.
//
// Discussion:
//
// factorial ( N ) = product ( 1 <= I <= N ) I
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 January 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the argument of the factorial function.
// If N is less than 1, the function value is returned as 1.
//
// Output, double R8_FACTORIAL, the factorial of N.
//
{
int i;
double value;
value = 1.0;
for ( i = 1; i <= n; i++ )
{
value = value * ( double ) ( i );
}
return value;
}
//****************************************************************************80
void r8_factorial_values ( int &n_data, int &n, double &fn )
//****************************************************************************80
//
// Purpose:
//
// R8_FACTORIAL_VALUES returns values of the real factorial function.
//
// Discussion:
//
// 0! = 1
// I! = Product ( 1 <= J <= I ) J
//
// Although the factorial is an int *valued function, it quickly
// becomes too large for an int *to hold. This routine still accepts
// an int *as the input argument, but returns the function value
// as a real number.
//
// In Mathematica, the function can be evaluated by:
//
// n!
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Milton Abramowitz, Irene Stegun,
// Handbook of Mathematical Functions,
// National Bureau of Standards, 1964,
// ISBN: 0-486-61272-4,
// LC: QA47.A34.
//
// Stephen Wolfram,
// The Mathematica Book,
// Fourth Edition,
// Cambridge University Press, 1999,
// ISBN: 0-521-64314-7,
// LC: QA76.95.W65.
//
// Parameters:
//
// Input/output, int &N_DATA. The user sets N_DATA to 0 before the
// first call. On each call, the routine increments N_DATA by 1, and
// returns the corresponding data; when there is no more data, the
// output value of N_DATA will be 0 again.
//
// Output, int &N, the argument of the function.
//
// Output, double &FN, the value of the function.
//
{
# define N_MAX 25
static double fn_vec[N_MAX] = {
0.1000000000000000E+01,
0.1000000000000000E+01,
0.2000000000000000E+01,
0.6000000000000000E+01,
0.2400000000000000E+02,
0.1200000000000000E+03,
0.7200000000000000E+03,
0.5040000000000000E+04,
0.4032000000000000E+05,
0.3628800000000000E+06,
0.3628800000000000E+07,
0.3991680000000000E+08,
0.4790016000000000E+09,
0.6227020800000000E+10,
0.8717829120000000E+11,
0.1307674368000000E+13,
0.2092278988800000E+14,
0.3556874280960000E+15,
0.6402373705728000E+16,
0.1216451004088320E+18,
0.2432902008176640E+19,
0.1551121004333099E+26,
0.3041409320171338E+65,
0.9332621544394415E+158,
0.5713383956445855E+263 };
static int n_vec[N_MAX] = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
25,
50,
100,
150 };
if ( n_data < 0 )
{
n_data = 0;
}
n_data = n_data + 1;
if ( N_MAX < n_data )
{
n_data = 0;
n = 0;
fn = 0.0;
}
else
{
n = n_vec[n_data-1];
fn = fn_vec[n_data-1];
}
return;
# undef N_MAX
}
//****************************************************************************80
double r8_factorial2 ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8_FACTORIAL2 computes the double factorial function.
//
// Discussion:
//
// FACTORIAL2( N ) = Product ( N * (N-2) * (N-4) * ... * 2 ) (N even)
// = Product ( N * (N-2) * (N-4) * ... * 1 ) (N odd)
//
// Example:
//
// N Value
//
// 0 1
// 1 1
// 2 2
// 3 3
// 4 8
// 5 15
// 6 48
// 7 105
// 8 384
// 9 945
// 10 3840
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 January 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the argument of the double factorial
// function. If N is less than 1, R8_FACTORIAL2 is returned as 1.0.
//
// Output, double R8_FACTORIAL2, the value of Factorial2(N).
//
{
int n_copy;
double value;
value = 1.0;
if ( n < 1 )
{
return value;
}
n_copy = n;
while ( 1 < n_copy )
{
value = value * ( double ) n_copy;
n_copy = n_copy - 2;
}
return value;
}
//****************************************************************************80
void r8_factorial2_values ( int &n_data, int &n, double &f )
//****************************************************************************80
//
// Purpose:
//
// R8_FACTORIAL2_VALUES returns values of the double factorial function.
//
// Formula:
//
// FACTORIAL2( N ) = Product ( N * (N-2) * (N-4) * ... * 2 ) (N even)
// = Product ( N * (N-2) * (N-4) * ... * 1 ) (N odd)
//
// In Mathematica, the function can be evaluated by:
//
// n!!
//
// Example:
//
// N N!!
//
// 0 1
// 1 1
// 2 2
// 3 3
// 4 8
// 5 15
// 6 48
// 7 105
// 8 384
// 9 945
// 10 3840
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 February 2015
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Milton Abramowitz, Irene Stegun,
// Handbook of Mathematical Functions,
// National Bureau of Standards, 1964,
// ISBN: 0-486-61272-4,
// LC: QA47.A34.
//
// Stephen Wolfram,
// The Mathematica Book,
// Fourth Edition,
// Cambridge University Press, 1999,
// ISBN: 0-521-64314-7,
// LC: QA76.95.W65.
//
// Daniel Zwillinger,
// CRC Standard Mathematical Tables and Formulae,
// 30th Edition,
// CRC Press, 1996, page 16.
//
// Parameters:
//
// Input/output, int &N_DATA. The user sets N_DATA to 0 before the
// first call. On each call, the routine increments N_DATA by 1, and
// returns the corresponding data; when there is no more data, the
// output value of N_DATA will be 0 again.
//
// Output, int &N, the argument of the function.
//
// Output, double &F, the value of the function.
//
{
# define N_MAX 16
static double f_vec[N_MAX] = {
1.0,
1.0,
2.0,
3.0,
8.0,
15.0,
48.0,
105.0,
384.0,
945.0,
3840.0,
10395.0,
46080.0,
135135.0,
645120.0,
2027025.0 };
static int n_vec[N_MAX] = {
0,
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15 };
if ( n_data < 0 )
{
n_data = 0;
}
n_data = n_data + 1;
if ( N_MAX < n_data )
{
n_data = 0;
n = 0;
f = 0.0;
}
else
{
n = n_vec[n_data-1];
f = f_vec[n_data-1];
}
return;
# undef N_MAX
}
//****************************************************************************80
double r8_fall ( double x, int n )
//****************************************************************************80
//
// Purpose:
//
// R8_FALL computes the falling factorial function [X]_N.
//
// Discussion:
//
// Note that the number of "injections" or 1-to-1 mappings from
// a set of N elements to a set of M elements is [M]_N.
//
// The number of permutations of N objects out of M is [M]_N.
//
// Moreover, the Stirling numbers of the first kind can be used
// to convert a falling factorial into a polynomial, as follows:
//
// [X]_N = S^0_N + S^1_N * X + S^2_N * X^2 + ... + S^N_N X^N.
//
// The formula is:
//
// [X]_N = X * ( X - 1 ) * ( X - 2 ) * ... * ( X - N + 1 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 May 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the argument of the falling factorial function.
//
// Input, int N, the order of the falling factorial function.
// If N = 0, FALL = 1, if N = 1, FALL = X. Note that if N is
// negative, a "rising" factorial will be computed.
//
// Output, double R8_FALL, the value of the falling factorial function.
//
{
int i;
double value;
value = 1.0;
if ( 0 < n )
{
for ( i = 1; i <= n; i++ )
{
value = value * x;
x = x - 1.0;
}
}
else if ( n < 0 )
{
for ( i = -1; n <= i; i-- )
{
value = value * x;
x = x + 1.0;
}
}
return value;
}
//****************************************************************************80
void r8_fall_values ( int &n_data, double &x, int &n, double &f )
//****************************************************************************80
//
// Purpose:
//
// R8_FALL_VALUES returns some values of the falling factorial function.
//
// Discussion:
//
// In Mathematica, the function can be evaluated by:
//
// FactorialPower[X,Y]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 December 2014
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Milton Abramowitz, Irene Stegun,
// Handbook of Mathematical Functions,
// National Bureau of Standards, 1964,
// ISBN: 0-486-61272-4,
// LC: QA47.A34.
//
// Stephen Wolfram,
// The Mathematica Book,
// Fourth Edition,
// Cambridge University Press, 1999,
// ISBN: 0-521-64314-7,
// LC: QA76.95.W65.
//
// Parameters:
//
// Input/output, int &N_DATA. The user sets N_DATA to 0 before the
// first call. On each call, the routine increments N_DATA by 1, and
// returns the corresponding data; when there is no more data, the
// output value of N_DATA will be 0 again.
//
// Output, double &X, int &N, the arguments of the function.
//
// Output, double &F, the value of the function.
//
{
# define N_MAX 15
static double f_vec[N_MAX] = {
120.0000000000000,
163.1601562500000,
216.5625000000000,
281.6601562500000,
360.0000000000000,
1.000000000000000,
7.500000000000000,
48.75000000000000,
268.1250000000000,
1206.562500000000,
4222.968750000000,
10557.42187500000,
15836.13281250000,
7918.066406250000,
-3959.03320312500 };
static int n_vec[N_MAX] = {
4,
4,
4,
4,
4,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9 };
static double x_vec[N_MAX] = {
5.00,
5.25,
5.50,
5.75,
6.00,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50 };
if ( n_data < 0 )
{
n_data = 0;
}
n_data = n_data + 1;
if ( N_MAX < n_data )
{
n_data = 0;
x = 0.0;
n = 0;
f = 0.0;
}
else
{
x = x_vec[n_data-1];
n = n_vec[n_data-1];
f = f_vec[n_data-1];
}
return;
# undef N_MAX
}
//****************************************************************************80
double r8_floor ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_FLOOR rounds an R8 down to the nearest integral R8.
//
// Example:
//
// X R8_FLOOR(X)
//
// -1.1 -2.0
// -1.0 -1.0
// -0.9 -1.0
// -0.1 -1.0
// 0.0 0.0
// 0.1 0.0
// 0.9 0.0
// 1.0 1.0
// 1.1 1.0
// 2.9 2.0
// 3.0 3.0
// 3.14159 3.0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 April 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose floor is desired.
//
// Output, double R8_FLOOR, the floor of X.
//
{
double value;
value = ( double ) ( ( int ) x );
if ( x < value )
{
value = value - 1.0;
}
return value;
}
//****************************************************************************80
double r8_fraction ( int i, int j )
//****************************************************************************80
//
// Purpose:
//
// R8_FRACTION uses real arithmetic on an integer ratio.
//
// Discussion:
//
// Given integer variables I and J, both FORTRAN and C will evaluate
// an expression such as "I/J" using what is called "integer division",
// with the result being an integer. It is often convenient to express
// the parts of a fraction as integers but expect the result to be computed
// using real arithmetic. This function carries out that operation.
//
// Example:
//
// I J I/J R8_FRACTION
//
// 1 2 0 0.5
// 7 4 1 1.75
// 8 4 2 2.00
// 9 4 2 2.25
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, J, the arguments.
//
// Output, double R8_FRACTION, the value of the ratio.
//
{
double value;
value = ( double ) ( i ) / ( double ) ( j );
return value;
}
//****************************************************************************80
double r8_fractional ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_FRACTIONAL returns the fractional part of an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the argument.
//
// Output, double R8_FRACTIONAL, the fractional part of X.
//
{
double value;
value = fabs ( x ) - ( double ) ( ( int ) fabs ( x ) );
return value;
}
//****************************************************************************80
double r8_gamma ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_GAMMA evaluates Gamma(X) for an R8.
//
// Discussion:
//
// The C MATH library includes a function GAMMA ( X ) which should be
// invoked instead of this function.
//
// This routine calculates the gamma function for a real argument X.
//
// Computation is based on an algorithm outlined in reference 1.
// The program uses rational functions that approximate the gamma
// function to at least 20 significant decimal digits. Coefficients
// for the approximation over the interval (1,2) are unpublished.
// Those for the approximation for 12 <= X are from reference 2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 January 2008
//
// Author:
//
// Original FORTRAN77 version by William Cody, Laura Stoltz.
// C++ version by John Burkardt.
//
// Reference:
//
// William Cody,
// An Overview of Software Development for Special Functions,
// in Numerical Analysis Dundee, 1975,
// edited by GA Watson,
// Lecture Notes in Mathematics 506,
// Springer, 1976.
//
// John Hart, Ward Cheney, Charles Lawson, Hans Maehly,
// Charles Mesztenyi, John Rice, Henry Thatcher,
// Christoph Witzgall,
// Computer Approximations,
// Wiley, 1968,
// LC: QA297.C64.
//
// Parameters:
//
// Input, double X, the argument of the function.
//
// Output, double R8_GAMMA, the value of the function.
//
{
double c[7] = {
-1.910444077728E-03,
8.4171387781295E-04,
-5.952379913043012E-04,
7.93650793500350248E-04,
-2.777777777777681622553E-03,
8.333333333333333331554247E-02,
5.7083835261E-03 };
double eps = 2.22E-16;
double fact;
int i;
int n;
double p[8] = {
-1.71618513886549492533811E+00,
2.47656508055759199108314E+01,
-3.79804256470945635097577E+02,
6.29331155312818442661052E+02,
8.66966202790413211295064E+02,
-3.14512729688483675254357E+04,
-3.61444134186911729807069E+04,
6.64561438202405440627855E+04 };
bool parity;
double q[8] = {
-3.08402300119738975254353E+01,
3.15350626979604161529144E+02,
-1.01515636749021914166146E+03,
-3.10777167157231109440444E+03,
2.25381184209801510330112E+04,
4.75584627752788110767815E+03,
-1.34659959864969306392456E+05,
-1.15132259675553483497211E+05 };
const double r8_pi = 3.1415926535897932384626434;
double res;
const double sqrtpi = 0.9189385332046727417803297;
double sum;
double value;
double xbig = 171.624;
double xden;
double xinf = 1.79E+308;
double xminin = 2.23E-308;
double xnum;
double y;
double y1;
double ysq;
double z;
parity = false;
fact = 1.0;
n = 0;
y = x;
//
// Argument is negative.
//
if ( y <= 0.0 )
{
y = - x;
y1 = ( double ) ( int ) ( y );
res = y - y1;
if ( res != 0.0 )
{
if ( y1 != ( double ) ( int ) ( y1 * 0.5 ) * 2.0 )
{
parity = true;
}
fact = - r8_pi / sin ( r8_pi * res );
y = y + 1.0;
}
else
{
res = xinf;
value = res;
return value;
}
}
//
// Argument is positive.
//
if ( y < eps )
{
//
// Argument < EPS.
//
if ( xminin <= y )
{
res = 1.0 / y;
}
else
{
res = xinf;
value = res;
return value;
}
}
else if ( y < 12.0 )
{
y1 = y;
//
// 0.0 < argument < 1.0.
//
if ( y < 1.0 )
{
z = y;
y = y + 1.0;
}
//
// 1.0 < argument < 12.0.
// Reduce argument if necessary.
//
else
{
n = ( int ) ( y ) - 1;
y = y - ( double ) ( n );
z = y - 1.0;
}
//
// Evaluate approximation for 1.0 < argument < 2.0.
//
xnum = 0.0;
xden = 1.0;
for ( i = 0; i < 8; i++ )
{
xnum = ( xnum + p[i] ) * z;
xden = xden * z + q[i];
}
res = xnum / xden + 1.0;
//
// Adjust result for case 0.0 < argument < 1.0.
//
if ( y1 < y )
{
res = res / y1;
}
//
// Adjust result for case 2.0 < argument < 12.0.
//
else if ( y < y1 )
{
for ( i = 1; i <= n; i++ )
{
res = res * y;
y = y + 1.0;
}
}
}
else
{
//
// Evaluate for 12.0 <= argument.
//
if ( y <= xbig )
{
ysq = y * y;
sum = c[6];
for ( i = 0; i < 6; i++ )
{
sum = sum / ysq + c[i];
}
sum = sum / y - y + sqrtpi;
sum = sum + ( y - 0.5 ) * log ( y );
res = exp ( sum );
}
else
{
res = xinf;
value = res;
return value;
}
}
//
// Final adjustments and return.
//
if ( parity )
{
res = - res;
}
if ( fact != 1.0 )
{
res = fact / res;
}
value = res;
return value;
}
//****************************************************************************80
double r8_gamma_log ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_GAMMA_LOG evaluates the logarithm of the gamma function.
//
// Discussion:
//
// This routine calculates the LOG(GAMMA) function for a positive real
// argument X. Computation is based on an algorithm outlined in
// references 1 and 2. The program uses rational functions that
// theoretically approximate LOG(GAMMA) to at least 18 significant
// decimal digits. The approximation for X > 12 is from reference
// 3, while approximations for X < 12.0 are similar to those in
// reference 1, but are unpublished.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 April 2013
//
// Author:
//
// Original FORTRAN77 version by William Cody, Laura Stoltz.
// C++ version by John Burkardt.
//
// Reference:
//
// William Cody, Kenneth Hillstrom,
// Chebyshev Approximations for the Natural Logarithm of the
// Gamma Function,
// Mathematics of Computation,
// Volume 21, Number 98, April 1967, pages 198-203.
//
// Kenneth Hillstrom,
// ANL/AMD Program ANLC366S, DGAMMA/DLGAMA,
// May 1969.
//
// John Hart, Ward Cheney, Charles Lawson, Hans Maehly,
// Charles Mesztenyi, John Rice, Henry Thatcher,
// Christoph Witzgall,
// Computer Approximations,
// Wiley, 1968,
// LC: QA297.C64.
//
// Parameters:
//
// Input, double X, the argument of the function.
//
// Output, double R8_GAMMA_LOG, the value of the function.
//
{
double c[7] = {
-1.910444077728E-03,
8.4171387781295E-04,
-5.952379913043012E-04,
7.93650793500350248E-04,
-2.777777777777681622553E-03,
8.333333333333333331554247E-02,
5.7083835261E-03 };
double corr;
const double d1 = -5.772156649015328605195174E-01;
const double d2 = 4.227843350984671393993777E-01;
const double d4 = 1.791759469228055000094023;
const double frtbig = 2.25E+76;
int i;
double p1[8] = {
4.945235359296727046734888,
2.018112620856775083915565E+02,
2.290838373831346393026739E+03,
1.131967205903380828685045E+04,
2.855724635671635335736389E+04,
3.848496228443793359990269E+04,
2.637748787624195437963534E+04,
7.225813979700288197698961E+03 };
double p2[8] = {
4.974607845568932035012064,
5.424138599891070494101986E+02,
1.550693864978364947665077E+04,
1.847932904445632425417223E+05,
1.088204769468828767498470E+06,
3.338152967987029735917223E+06,
5.106661678927352456275255E+06,
3.074109054850539556250927E+06 };
double p4[8] = {
1.474502166059939948905062E+04,
2.426813369486704502836312E+06,
1.214755574045093227939592E+08,
2.663432449630976949898078E+09,
2.940378956634553899906876E+10,
1.702665737765398868392998E+11,
4.926125793377430887588120E+11,
5.606251856223951465078242E+11 };
double q1[8] = {
6.748212550303777196073036E+01,
1.113332393857199323513008E+03,
7.738757056935398733233834E+03,
2.763987074403340708898585E+04,
5.499310206226157329794414E+04,
6.161122180066002127833352E+04,
3.635127591501940507276287E+04,
8.785536302431013170870835E+03 };
double q2[8] = {
1.830328399370592604055942E+02,
7.765049321445005871323047E+03,
1.331903827966074194402448E+05,
1.136705821321969608938755E+06,
5.267964117437946917577538E+06,
1.346701454311101692290052E+07,
1.782736530353274213975932E+07,
9.533095591844353613395747E+06 };
double q4[8] = {
2.690530175870899333379843E+03,
6.393885654300092398984238E+05,
4.135599930241388052042842E+07,
1.120872109616147941376570E+09,
1.488613728678813811542398E+10,
1.016803586272438228077304E+11,
3.417476345507377132798597E+11,
4.463158187419713286462081E+11 };
double res;
const double sqrtpi = 0.9189385332046727417803297;
const double xbig = 2.55E+305;
double xden;
const double xinf = 1.79E+308;
double xm1;
double xm2;
double xm4;
double xnum;
double y;
double ysq;
y = x;
if ( 0.0 < y && y <= xbig )
{
if ( y <= r8_epsilon ( ) )
{
res = - log ( y );
}
//
// EPS < X <= 1.5.
//
else if ( y <= 1.5 )
{
if ( y < 0.6796875 )
{
corr = -log ( y );
xm1 = y;
}
else
{
corr = 0.0;
xm1 = ( y - 0.5 ) - 0.5;
}
if ( y <= 0.5 || 0.6796875 <= y )
{
xden = 1.0;
xnum = 0.0;
for ( i = 0; i < 8; i++ )
{
xnum = xnum * xm1 + p1[i];
xden = xden * xm1 + q1[i];
}
res = corr + ( xm1 * ( d1 + xm1 * ( xnum / xden ) ) );
}
else
{
xm2 = ( y - 0.5 ) - 0.5;
xden = 1.0;
xnum = 0.0;
for ( i = 0; i < 8; i++ )
{
xnum = xnum * xm2 + p2[i];
xden = xden * xm2 + q2[i];
}
res = corr + xm2 * ( d2 + xm2 * ( xnum / xden ) );
}
}
//
// 1.5 < X <= 4.0.
//
else if ( y <= 4.0 )
{
xm2 = y - 2.0;
xden = 1.0;
xnum = 0.0;
for ( i = 0; i < 8; i++ )
{
xnum = xnum * xm2 + p2[i];
xden = xden * xm2 + q2[i];
}
res = xm2 * ( d2 + xm2 * ( xnum / xden ) );
}
//
// 4.0 < X <= 12.0.
//
else if ( y <= 12.0 )
{
xm4 = y - 4.0;
xden = -1.0;
xnum = 0.0;
for ( i = 0; i < 8; i++ )
{
xnum = xnum * xm4 + p4[i];
xden = xden * xm4 + q4[i];
}
res = d4 + xm4 * ( xnum / xden );
}
//
// Evaluate for 12 <= argument.
//
else
{
res = 0.0;
if ( y <= frtbig )
{
res = c[6];
ysq = y * y;
for ( i = 0; i < 6; i++ )
{
res = res / ysq + c[i];
}
}
res = res / y;
corr = log ( y );
res = res + sqrtpi - 0.5 * corr;
res = res + y * ( corr - 1.0 );
}
}
//
// Return for bad arguments.
//
else
{
res = xinf;
}
//
// Final adjustments and return.
//
return res;
}
//****************************************************************************80
double r8_huge ( )
//****************************************************************************80
//
// Purpose:
//
// R8_HUGE returns a "huge" R8.
//
// Discussion:
//
// The value returned by this function is intended to be the largest
// representable real value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_HUGE, a "huge" R8 value.
//
{
double value;
value = 1.79769313486231571E+308;
return value;
}
//****************************************************************************80
double r8_hypot ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_HYPOT returns the value of sqrt ( X^2 + Y^2 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 March 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the arguments.
//
// Output, double R8_HYPOT, the value of sqrt ( X^2 + Y^2 ).
//
{
double a;
double b;
double value;
if ( fabs ( x ) < fabs ( y ) )
{
a = fabs ( y );
b = fabs ( x );
}
else
{
a = fabs ( x );
b = fabs ( y );
}
//
// A contains the larger value.
//
if ( a == 0.0 )
{
value = 0.0;
}
else
{
value = a * sqrt ( 1.0 + ( b / a ) * ( b / a ) );
}
return value;
}
//****************************************************************************80
bool r8_in_01 ( double a )
//****************************************************************************80
//
// Purpose:
//
// R8_IN_01 is TRUE if an R8 is in the range [0,1].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A, the value.
//
// Output, bool R8_IN_01, is TRUE if A is between 0 and 1.
//
{
bool value;
value = ( 0.0 <= a && a <= 1.0 );
return value;
}
//****************************************************************************80
bool r8_insignificant ( double r, double s )
//****************************************************************************80
//
// Purpose:
//
// R8_INSIGNIFICANT determines if an R8 is insignificant.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, the number to be compared against.
//
// Input, double S, the number to be compared.
//
// Output, bool R8_INSIGNIFICANT, is TRUE if S is insignificant
// compared to R.
//
{
double t;
double tol;
bool value;
value = true;
t = r + s;
tol = r8_epsilon ( ) * fabs ( r );
if ( tol < fabs ( r - t ) )
{
value = false;
}
return value;
}
//****************************************************************************80
bool r8_is_int ( double r )
//****************************************************************************80
//
// Purpose:
//
// R8_IS_INT determines if an R8 represents an integer value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, the number to be checked.
//
// Output, bool R8_IS_INT, is TRUE if R is an integer value.
//
{
const int i4_huge = 2147483647;
bool value;
if ( ( double ) ( i4_huge ) < r )
{
value = false;
}
else if ( r < - ( double ) ( i4_huge ) )
{
value = false;
}
else if ( r == ( double ) ( ( int ) ( r ) ) )
{
value = true;
}
else
{
value = false;
}
return value;
}
//****************************************************************************80
double r8_log_10 ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_LOG_10 returns the logarithm base 10 of the absolute value of an R8.
//
// Discussion:
//
// value = Log10 ( |X| )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 March 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose base 2 logarithm is desired.
// X should not be 0.
//
// Output, double R8_LOG_10, the logarithm base 10 of the absolute
// value of X. It should be true that |X| = 10^R_LOG_10.
//
{
double value;
if ( x == 0.0 )
{
value = - r8_big ( );
}
else
{
value = log10 ( fabs ( x ) );
}
return value;
}
//****************************************************************************80
double r8_log_2 ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_LOG_2 returns the logarithm base 2 of the absolute value of an R8.
//
// Discussion:
//
// value = Log ( |X| ) / Log ( 2.0 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 March 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose base 2 logarithm is desired.
// X should not be 0.
//
// Output, double R8_LOG_2, the logarithm base 2 of the absolute
// value of X. It should be true that |X| = 2^R_LOG_2.
//
{
double value;
if ( x == 0.0 )
{
value = - r8_big ( );
}
else
{
value = log ( fabs ( x ) ) / log ( 2.0 );
}
return value;
}
//****************************************************************************80
double r8_log_b ( double x, double b )
//****************************************************************************80
//
// Purpose:
//
// R8_LOG_B returns the logarithm base B of an R8.
//
// Discussion:
//
// value = log ( |X| ) / log ( |B| )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 April 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose base B logarithm is desired.
// X should not be 0.
//
// Input, double B, the base, which should not be 0, 1 or -1.
//
// Output, double R8_LOG_B, the logarithm base B of the absolute
// value of X. It should be true that |X| = |B|^R_LOG_B.
//
{
double value;
if ( b == 0.0 || b == 1.0 || b == -1.0 )
{
value = - r8_big ( );
}
else if ( fabs ( x ) == 0.0 )
{
value = - r8_big ( );
}
else
{
value = log ( fabs ( x ) ) / log ( fabs ( b ) );
}
return value;
}
//****************************************************************************80
void r8_mant ( double x, int &s, double &r, int &l )
//****************************************************************************80
//
// Purpose:
//
// R8_MANT computes the "mantissa" or "fraction part" of an R8.
//
// Discussion:
//
// X = S * R * 2^L
//
// S is +1 or -1,
// R is a real between 1.0 and 2.0,
// L is an integer.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 January 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the real number to be decomposed.
//
// Output, int &S, the "sign" of the number.
// S will be -1 if X is less than 0, and +1 if X is greater
// than or equal to zero.
//
// Output, double &R, the mantissa of X. R will be greater
// than or equal to 1, and strictly less than 2. The one
// exception occurs if X is zero, in which case R will also
// be zero.
//
// Output, int &L, the integer part of the logarithm (base 2) of X.
//
{
//
// Determine the sign.
//
if ( x < 0.0 )
{
s = -1;
}
else
{
s = 1;
}
//
// Set R to the absolute value of X, and L to zero.
// Then force R to lie between 1 and 2.
//
if ( x < 0.0 )
{
r = -x;
}
else
{
r = x;
}
l = 0;
//
// Time to bail out if X is zero.
//
if ( x == 0.0 )
{
return;
}
while ( 2.0 <= r )
{
r = r / 2.0;
l = l + 1;
}
while ( r < 1.0 )
{
r = r * 2.0;
l = l - 1;
}
return;
}
//****************************************************************************80
double r8_max ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_MAX returns the maximum of two R8's.
//
// Discussion:
//
// The C++ math library provides the function fmax() which is preferred.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the quantities to compare.
//
// Output, double R8_MAX, the maximum of X and Y.
//
{
double value;
if ( y < x )
{
value = x;
}
else
{
value = y;
}
return value;
}
//****************************************************************************80
double r8_min ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_MIN returns the minimum of two R8's.
//
// Discussion:
//
// The C++ math library provides the function fmin() which is preferred.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 31 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the quantities to compare.
//
// Output, double R8_MIN, the minimum of X and Y.
//
{
double value;
if ( y < x )
{
value = y;
}
else
{
value = x;
}
return value;
}
//****************************************************************************80
double r8_mod ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_MOD returns the remainder of R8 division.
//
// Discussion:
//
// If
// REM = R8_MOD ( X, Y )
// RMULT = ( X - REM ) / Y
// then
// X = Y * RMULT + REM
// where REM has the same sign as X, and abs ( REM ) < Y.
//
// Example:
//
// X Y R8_MOD R8_MOD Factorization
//
// 107 50 7 107 = 2 * 50 + 7
// 107 -50 7 107 = -2 * -50 + 7
// -107 50 -7 -107 = -2 * 50 - 7
// -107 -50 -7 -107 = 2 * -50 - 7
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 June 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number to be divided.
//
// Input, double Y, the number that divides X.
//
// Output, double R8_MOD, the remainder when X is divided by Y.
//
{
double value;
if ( y == 0.0 )
{
cerr << "\n";
cerr << "R8_MOD - Fatal error!\n";
cerr << " R8_MOD ( X, Y ) called with Y = " << y << "\n";
exit ( 1 );
}
value = x - ( ( double ) ( ( int ) ( x / y ) ) ) * y;
if ( x < 0.0 && 0.0 < value )
{
value = value - fabs ( y );
}
else if ( 0.0 < x && value < 0.0 )
{
value = value + fabs ( y );
}
return value;
}
//****************************************************************************80
double r8_modp ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_MODP returns the nonnegative remainder of R8 division.
//
// Discussion:
//
// The MOD function computes a result with the same sign as the
// quantity being divided. Thus, suppose you had an angle A,
// and you wanted to ensure that it was between 0 and 360.
// Then mod(A,360.0) would do, if A was positive, but if A
// was negative, your result would be between -360 and 0.
//
// On the other hand, R8_MODP(A,360.0) is between 0 and 360, always.
//
// If
// REM = R8_MODP ( X, Y )
// RMULT = ( X - REM ) / Y
// then
// X = Y * RMULT + REM
// where REM is always nonnegative.
//
// Example:
//
// I J MOD R8_MODP R8_MODP Factorization
//
// 107 50 7 7 107 = 2 * 50 + 7
// 107 -50 7 7 107 = -2 * -50 + 7
// -107 50 -7 43 -107 = -3 * 50 + 43
// -107 -50 -7 43 -107 = 3 * -50 + 43
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number to be divided.
//
// Input, double Y, the number that divides X.
//
// Output, double R8_MODP, the nonnegative remainder when X is divided by Y.
//
{
double value;
if ( y == 0.0 )
{
cerr << "\n";
cerr << "R8_MODP - Fatal error!\n";
cerr << " R8_MODP ( X, Y ) called with Y = " << y << "\n";
exit ( 1 );
}
value = x - ( ( double ) ( ( int ) ( x / y ) ) ) * y;
if ( value < 0.0 )
{
value = value + fabs ( y );
}
return value;
}
//****************************************************************************80
double r8_mop ( int i )
//****************************************************************************80
//
// Purpose:
//
// R8_MOP returns the I-th power of -1 as an R8 value.
//
// Discussion:
//
// An R8 is an double value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 November 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, the power of -1.
//
// Output, double R8_MOP, the I-th power of -1.
//
{
double value;
if ( ( i % 2 ) == 0 )
{
value = 1.0;
}
else
{
value = -1.0;
}
return value;
}
//****************************************************************************80
int r8_nint ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_NINT returns the nearest integer to an R8.
//
// Example:
//
// X Value
//
// 1.3 1
// 1.4 1
// 1.5 1 or 2
// 1.6 2
// 0.0 0
// -0.7 -1
// -1.1 -1
// -1.6 -2
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the value.
//
// Output, int R8_NINT, the nearest integer to X.
//
{
int value;
if ( x < 0.0 )
{
value = - ( int ) ( fabs ( x ) + 0.5 );
}
else
{
value = ( int ) ( fabs ( x ) + 0.5 );
}
return value;
}
//****************************************************************************80
double r8_normal_01 ( int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8_NORMAL_01 samples the standard normal probability distribution.
//
// Discussion:
//
// The standard normal probability distribution function (PDF) has
// mean 0 and standard deviation 1.
//
// The Box-Muller method is used.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 August 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input/output, int SEED, a seed for the random number generator.
//
// Output, double R8_NORMAL_01, a normally distributed random value.
//
{
double r1;
double r2;
const double r8_pi = 3.141592653589793;
double x;
r1 = r8_uniform_01 ( seed );
r2 = r8_uniform_01 ( seed );
x = sqrt ( -2.0 * log ( r1 ) ) * cos ( 2.0 * r8_pi * r2 );
return x;
}
//****************************************************************************80
double r8_normal_ab ( double a, double b, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8_NORMAL_AB returns a scaled pseudonormal R8.
//
// Discussion:
//
// The normal probability distribution function (PDF) is sampled,
// with mean A and standard deviation B.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 November 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A, the mean of the PDF.
//
// Input, double B, the standard deviation of the PDF.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8_NORMAL_AB, a sample of the normal PDF.
//
{
double value;
value = a + b * r8_normal_01 ( seed );
return value;
}
//****************************************************************************80
double r8_pi ( )
//****************************************************************************80
//
// Purpose:
//
// R8_PI returns the value of PI as an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_PI, the value of PI.
//
{
const double value = 3.141592653589793;
return value;
}
//****************************************************************************80
double r8_pi_sqrt ( )
//****************************************************************************80
//
// Purpose:
//
// R8_PI_SQRT returns the square root of PI as an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_PI_SQRT, the square root of PI.
//
{
const double value = 1.7724538509055160273;
return value;
}
//****************************************************************************80
double r8_power ( double r, int p )
//****************************************************************************80
//
// Purpose:
//
// R8_POWER computes an integer power of an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, the base.
//
// Input, int P, the power, which may be negative.
//
// Output, double R8_POWER, the value of R^P.
//
{
double value;
//
// Special case. R^0 = 1.
//
if ( p == 0 )
{
value = 1.0;
}
//
// Special case. Positive powers of 0 are 0.
// We go ahead and compute negative powers, relying on the software to complain.
//
else if ( r == 0.0 )
{
if ( 0 < p )
{
value = 0.0;
}
else
{
value = pow ( r, p );
}
}
else if ( 1 <= p )
{
value = pow ( r, p );
}
else
{
value = pow ( r, p );
}
return value;
}
//****************************************************************************80
double r8_power_fast ( double r, int p, int &mults )
//****************************************************************************80
//
// Purpose:
//
// R8_POWER_FAST computes the P-th power of R, for real R and integer P.
//
// Discussion:
//
// Obviously, R^P can be computed using P-1 multiplications.
//
// However, R^P can also be computed using at most 2*LOG2(P) multiplications.
// To do the calculation this way, let N = LOG2(P).
// Compute A, A^2, A^4, ..., A^N by N-1 successive squarings.
// Start the value of R^P at A, and each time that there is a 1 in
// the binary expansion of P, multiply by the current result of the squarings.
//
// This algorithm is not optimal. For small exponents, and for special
// cases, the result can be computed even more quickly.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 January 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, the base.
//
// Input, int P, the power, which may be negative.
//
// Output, int &MULTS, the number of multiplications and divisions.
//
// Output, double R8_POWER_FAST, the value of R^P.
//
{
int p_mag;
int p_sign;
double r2;
double value;
mults = 0;
//
// Special bases.
//
if ( r == 1.0 )
{
value = 1.0;
return value;
}
if ( r == -1.0 )
{
if ( ( p % 2 ) == 1 )
{
value = -1.0;
}
else
{
value = 1.0;
}
return value;
}
if ( r == 0.0 )
{
if ( p <= 0 )
{
cerr << "\n";
cerr << "R8_POWER_FAST - Fatal error!\n";
cerr << " Base is zero, and exponent is negative.\n";
exit ( 1 );
}
value = 0.0;
return value;
}
//
// Special powers.
//
if ( p == -1 )
{
value = 1.0 / r;
mults = mults + 1;
return value;
}
else if ( p == 0 )
{
value = 1.0;
return value;
}
else if ( p == 1 )
{
value = r;
return value;
}
//
// Some work to do.
//
p_mag = abs ( p );
p_sign = i4_sign ( p );
value = 1.0;
r2 = r;
while ( 0 < p_mag )
{
if ( ( p_mag % 2 ) == 1 )
{
value = value * r2;
mults = mults + 1;
}
p_mag = p_mag / 2;
r2 = r2 * r2;
mults = mults + 1;
}
if ( p_sign == -1 )
{
value = 1.0 / value;
mults = mults + 1;
}
return value;
}
//****************************************************************************80
void r8_print ( double r, string title )
//****************************************************************************80
//
// Purpose:
//
// R8_PRINT prints an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 August 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, the value to print.
//
// Input, string TITLE, a title.
//
{
cout << title << " "
<< r << "\n";
return;
}
//****************************************************************************80
double r8_pythag ( double a, double b )
//****************************************************************************80
//
// Purpose:
//
// R8_PYTHAG computes sqrt ( A*A + B*B ), avoiding overflow and underflow.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 January 2002
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A, B, the values for which sqrt ( A*A + B*B ) is desired.
//
// Output, double R8_PYTHAG, the value of sqrt ( A*A + B*B ).
//
{
double a_abs;
double b_abs;
double result;
a_abs = fabs ( a );
b_abs = fabs ( b );
if ( b_abs < a_abs )
{
result = a_abs * sqrt ( 1.0 + pow ( b_abs / a_abs, 2 ) );
}
else if ( b_abs == 0.0 )
{
result = 0.0;
}
else if ( a_abs <= b_abs )
{
result = b_abs * sqrt ( 1.0 + pow ( a_abs / b_abs, 2 ) );
}
return result;
}
//****************************************************************************80
double r8_radians ( double degrees )
//****************************************************************************80
//
// Purpose:
//
// R8_RADIANS converts an angle from degree to radian measure.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 May 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double DEGREES, the angle measurement in degrees.
//
// Output, double R8_RADIANS, the angle measurement in radians.
//
{
const double r8_pi = 3.1415926535897932384626434;
double value;
value = degrees * r8_pi / 180.0;
return value;
}
//****************************************************************************80
double r8_reverse_bytes ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_REVERSE_BYTES reverses the bytes in an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 May 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, a value whose bytes are to be reversed.
//
// Output, R8_REVERSE_BYTES, a value with bytes in reverse order;
//
{
char c;
union
{
double ydouble;
char ychar[8];
} y;
y.ydouble = x;
c = y.ychar[0];
y.ychar[0] = y.ychar[7];
y.ychar[7] = c;
c = y.ychar[1];
y.ychar[1] = y.ychar[6];
y.ychar[6] = c;
c = y.ychar[2];
y.ychar[2] = y.ychar[5];
y.ychar[5] = c;
c = y.ychar[3];
y.ychar[3] = y.ychar[4];
y.ychar[4] = c;
return ( y.ydouble );
}
//****************************************************************************80
double r8_rise ( double x, int n )
//****************************************************************************80
//
// Purpose:
//
// R8_RISE computes the rising factorial function [X]^N.
//
// Discussion:
//
// [X}^N = X * ( X + 1 ) * ( X + 2 ) * ... * ( X + N - 1 ).
//
// Note that the number of ways of arranging N objects in M ordered
// boxes is [M}^N. (Here, the ordering in each box matters). Thus,
// 2 objects in 2 boxes have the following 6 possible arrangements:
//
// -/12, 1/2, 12/-, -/21, 2/1, 21/-.
//
// Moreover, the number of non-decreasing maps from a set of
// N to a set of M ordered elements is [M]^N / N!. Thus the set of
// nondecreasing maps from (1,2,3) to (a,b,c,d) is the 20 elements:
//
// aaa, abb, acc, add, aab, abc, acd, aac, abd, aad
// bbb, bcc, bdd, bbc, bcd, bbd, ccc, cdd, ccd, ddd.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 May 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the argument of the rising factorial function.
//
// Input, int N, the order of the rising factorial function.
// If N = 0, RISE = 1, if N = 1, RISE = X. Note that if N is
// negative, a "falling" factorial will be computed.
//
// Output, double R8_RISE, the value of the rising factorial function.
//
{
int i;
double value;
value = 1.0;
if ( 0 < n )
{
for ( i = 1; i <= n; i++ )
{
value = value * x;
x = x + 1.0;
}
}
else if ( n < 0 )
{
for ( i = -1; n <= i; i-- )
{
value = value * x;
x = x - 1.0;
}
}
return value;
}
//****************************************************************************80
void r8_rise_values ( int &n_data, double &x, int &n, double &f )
//****************************************************************************80
//
// Purpose:
//
// R8_RISE_VALUES returns some values of the rising factorial function.
//
// Discussion:
//
// Pochhammer(X,Y) = Gamma(X+Y) / Gamma(X)
//
// For integer arguments, Pochhammer(M,N) = ( M + N - 1 )! / ( N - 1 )!
//
// In Mathematica, the function can be evaluated by:
//
// Pochhammer[X,Y]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 December 2014
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Milton Abramowitz, Irene Stegun,
// Handbook of Mathematical Functions,
// National Bureau of Standards, 1964,
// ISBN: 0-486-61272-4,
// LC: QA47.A34.
//
// Stephen Wolfram,
// The Mathematica Book,
// Fourth Edition,
// Cambridge University Press, 1999,
// ISBN: 0-521-64314-7,
// LC: QA76.95.W65.
//
// Parameters:
//
// Input/output, int &N_DATA. The user sets N_DATA to 0 before the
// first call. On each call, the routine increments N_DATA by 1, and
// returns the corresponding data; when there is no more data, the
// output value of N_DATA will be 0 again.
//
// Output, double &X, int &N, the arguments of the function.
//
// Output, double &F, the value of the function.
//
{
# define N_MAX 15
static double f_vec[N_MAX] = {
1680.000000000000,
1962.597656250000,
2279.062500000000,
2631.972656250000,
3024.000000000000,
1.000000000000000,
7.500000000000000,
63.75000000000000,
605.6250000000000,
6359.062500000000,
73129.21875000000,
914115.2343750000,
1.234055566406250E+07,
1.789380571289063E+08,
2.773539885498047E+09 };
static int n_vec[N_MAX] = {
4,
4,
4,
4,
4,
0,
1,
2,
3,
4,
5,
6,
7,
8,
9 };
static double x_vec[N_MAX] = {
5.00,
5.25,
5.50,
5.75,
6.00,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50,
7.50 };
if ( n_data < 0 )
{
n_data = 0;
}
n_data = n_data + 1;
if ( N_MAX < n_data )
{
n_data = 0;
x = 0.0;
n = 0;
f = 0.0;
}
else
{
x = x_vec[n_data-1];
n = n_vec[n_data-1];
f = f_vec[n_data-1];
}
return;
# undef N_MAX
}
//****************************************************************************80
double r8_round ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ROUND rounds an R8 to the nearest integral value.
//
// Example:
//
// X Value
//
// 1.3 1.0
// 1.4 1.0
// 1.5 1.0 or 2.0
// 1.6 2.0
// 0.0 0.0
// -0.7 -1.0
// -1.1 -1.0
// -1.6 -2.0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 March 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the value.
//
// Output, double R8_ROUND, the rounded value.
//
{
double value;
if ( x < 0.0 )
{
value = - ( double ) floor ( - x + 0.5 );
}
else
{
value = ( double ) floor ( x + 0.5 );
}
return value;
}
//****************************************************************************80
int r8_round_i4 ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ROUND_I4 rounds an R8, returning an I4.
//
// Example:
//
// X Value
//
// 1.3 1
// 1.4 1
// 1.5 1 or 2
// 1.6 2
// 0.0 0
// -0.7 -1
// -1.1 -1
// -1.6 -2
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 March 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the value.
//
// Output, int R8_ROUND_I4, the rounded value.
//
{
int value;
if ( x < 0.0 )
{
value = - floor ( - x + 0.5 );
}
else
{
value = floor ( x + 0.5 );
}
return value;
}
//****************************************************************************80
double r8_round2 ( int nplace, double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ROUND2 rounds an R8 in base 2.
//
// Discussion:
//
// Assume that the input quantity X has the form
//
// X = S * J * 2^L
//
// where S is plus or minus 1, L is an integer, and J is a binary
// mantissa which is either exactly zero, or greater than or equal
// to 0.5 and less than 1.0.
//
// Then on return, XROUND = R8_ROUND2 ( NPLACE, X ) will satisfy
//
// XROUND = S * K * 2^L
//
// where S and L are unchanged, and K is a binary mantissa which
// agrees with J in the first NPLACE binary digits and is zero
// thereafter.
//
// If NPLACE is 0, XROUND will always be zero.
//
// If NPLACE is 1, the mantissa of XROUND will be 0 or 0.5.
//
// If NPLACE is 2, the mantissa of XROUND will be 0, 0.25, 0.50,
// or 0.75.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPLACE, the number of binary digits to
// preserve. NPLACE should be 0 or positive.
//
// Input, double X, the real number to be decomposed.
//
// Output, double R8_ROUND2, the rounded value of X.
//
{
int iplace;
int l;
int s;
double xmant;
double xtemp;
double value;
value = 0.0;
//
// 1: Handle the special case of 0.
//
if ( x == 0.0 )
{
return value;
}
if ( nplace <= 0 )
{
return value;
}
//
// 2: Determine the sign S.
//
if ( 0.0 < x )
{
s = 1;
xtemp = x;
}
else
{
s = -1;
xtemp = -x;
}
//
// 3: Force XTEMP to lie between 1 and 2, and compute the
// logarithm L.
//
l = 0;
while ( 2.0 <= xtemp )
{
xtemp = xtemp / 2.0;
l = l + 1;
}
while ( xtemp < 1.0 )
{
xtemp = xtemp * 2.0;
l = l - 1;
}
//
// 4: Strip out the digits of the mantissa as XMANT, and decrease L.
//
xmant = 0.0;
iplace = 0;
for ( ; ; )
{
xmant = 2.0 * xmant;
if ( 1.0 <= xtemp )
{
xmant = xmant + 1.0;
xtemp = xtemp - 1.0;
}
iplace = iplace + 1;
if ( xtemp == 0.0 || nplace <= iplace )
{
value = s * xmant * pow ( 2.0, l );
break;
}
l = l - 1;
xtemp = xtemp * 2.0;
}
return value;
}
//****************************************************************************80
double r8_roundb ( int base, int nplace, double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ROUNDB rounds an R8 in a given base.
//
// Discussion:
//
// The code does not seem to do a good job of rounding when
// the base is negative.
//
// Assume that the input quantity X has the form
//
// X = S * J * BASE^L
//
// where S is plus or minus 1, L is an integer, and J is a
// mantissa base BASE which is either exactly zero, or greater
// than or equal to (1/BASE) and less than 1.0.
//
// Then on return, XROUND will satisfy
//
// XROUND = S * K * BASE^L
//
// where S and L are unchanged, and K is a mantissa base BASE
// which agrees with J in the first NPLACE digits and is zero
// thereafter.
//
// Note that because of rounding, for most bases, most numbers
// with a fractional quantities cannot be stored exactly in the
// computer, and hence will have trailing "bogus" digits.
//
// If NPLACE is 0, XROUND will always be zero.
//
// If NPLACE is 1, the mantissa of XROUND will be 0,
// 1/BASE, 2/BASE, ..., (BASE-1)/BASE.
//
// If NPLACE is 2, the mantissa of XROUND will be 0,
// BASE/BASE^2, (BASE+1)/BASE^2, ...,
// BASE^2-2/BASE^2, BASE^2-1/BASE^2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 November 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int BASE, the base of the arithmetic.
// BASE must not be zero. Theoretically, BASE may be negative.
//
// Input, int NPLACE, the number of digits base BASE to
// preserve. NPLACE should be 0 or positive.
//
// Input, double X, the number to be decomposed.
//
// Output, double R8_ROUNDB, the rounded value of X.
//
{
int iplace;
int is;
int js;
int l;
double r8_base;
double value;
double xmant;
double xtemp;
value = 0.0;
r8_base = ( double ) base;
//
// 0: Error checks.
//
if ( base == 0 )
{
cerr << "\n";
cerr << "R8_ROUNDB - Fatal error!\n";
cerr << " The base BASE cannot be zero.\n";
exit ( 1 );
}
//
// 1: Handle the special case of 0.
//
if ( x == 0.0 )
{
return value;
}
if ( nplace <= 0 )
{
return value;
}
//
// 2: Determine the sign IS.
//
if ( 0.0 < x )
{
is = 1;
xtemp = x;
}
else
{
is = -1;
xtemp = -x;
}
//
// 3: Force XTEMP to lie between 1 and ABS(BASE), and compute the
// logarithm L.
//
l = 0;
while ( fabs ( r8_base ) <= fabs ( xtemp ) )
{
xtemp = xtemp / r8_base;
if ( xtemp < 0.0 )
{
is = -is;
xtemp = -xtemp;
}
l = l + 1;
}
while ( fabs ( xtemp ) < 1.0 )
{
xtemp = xtemp * r8_base;
if ( xtemp < 0.0 )
{
is = -is;
xtemp = -xtemp;
}
l = l - 1;
}
//
// 4: Now strip out the digits of the mantissa as XMANT, and
// decrease L.
//
xmant = 0.0;
iplace = 0;
js = is;
for ( ; ; )
{
xmant = r8_base * xmant;
if ( xmant < 0.0 )
{
js = -js;
xmant = -xmant;
}
if ( 1.0 <= xtemp )
{
xmant = xmant + ( int ) ( xtemp );
xtemp = xtemp - ( int ) ( xtemp );
}
iplace = iplace + 1;
if ( xtemp == 0.0 || nplace <= iplace )
{
value = ( double ) js * xmant * pow ( r8_base, l );
break;
}
l = l - 1;
xtemp = xtemp * r8_base;
if ( xtemp < 0.0 )
{
is = -is;
xtemp = -xtemp;
}
}
return value;
}
//****************************************************************************80
double r8_roundx ( int nplace, double x )
//****************************************************************************80
//
// Purpose:
//
// R8_ROUNDX rounds an R8 in base 10.
//
// Discussion:
//
// Assume that the input quantity X has the form
//
// X = S * J * 10^L
//
// where S is plus or minus 1, L is an integer, and J is a decimal
// mantissa which is either exactly zero, or greater than or equal
// to 0.1 and less than 1.0.
//
// Then on return, XROUND will satisfy
//
// XROUND = S * K * 10^L
//
// where S and L are unchanged, and K is a decimal mantissa which
// agrees with J in the first NPLACE decimal digits and is zero
// thereafter.
//
// Note that because of rounding, most decimal fraction quantities
// cannot be stored exactly in the computer, and hence will have
// trailing "bogus" digits.
//
// If NPLACE is 0, XROUND will always be zero.
//
// If NPLACE is 1, the mantissa of XROUND will be 0, 0.1,
// 0.2, ..., or 0.9.
//
// If NPLACE is 2, the mantissa of XROUND will be 0, 0.01, 0.02,
// 0.03, ..., 0.98, 0.99.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPLACE, the number of decimal digits to
// preserve. NPLACE should be 0 or positive.
//
// Input, double X, the number to be decomposed.
//
// Output, double R8_ROUNDX, the rounded value of X.
//
{
int iplace;
int is;
int l;
double xmant;
double xround;
double xtemp;
xround = 0.0;
//
// 1: Handle the special case of 0.
//
if ( x == 0.0 )
{
return xround;
}
if ( nplace <= 0 )
{
return xround;
}
//
// 2: Determine the sign IS.
//
if ( 0.0 < x )
{
is = 1;
xtemp = x;
}
else
{
is = -1;
xtemp = -x;
}
//
// 3: Force XTEMP to lie between 1 and 10, and compute the
// logarithm L.
//
l = 0;
while ( 10.0 <= x )
{
xtemp = xtemp / 10.0;
l = l + 1;
}
while ( xtemp < 1.0 )
{
xtemp = xtemp * 10.0;
l = l - 1;
}
//
// 4: Now strip out the digits of the mantissa as XMANT, and
// decrease L.
//
xmant = 0.0;
iplace = 0;
for ( ; ; )
{
xmant = 10.0 * xmant;
if ( 1.0 <= xtemp )
{
xmant = xmant + ( int ) xtemp;
xtemp = xtemp - ( int ) xtemp;
}
iplace = iplace + 1;
if ( xtemp == 0.0 || nplace <= iplace )
{
xround = is * xmant * pow ( 10.0, l );
break;
}
l = l - 1;
xtemp = xtemp * 10.0;
}
return xround;
}
//****************************************************************************80
double r8_secd ( double degrees )
//****************************************************************************80
//
// Purpose:
//
// R8_SECD returns the secant of an angle given in degrees.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 July 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double DEGREES, the angle in degrees.
//
// Output, double R8_SECD, the secant of the angle.
//
{
const double r8_pi = 3.141592653589793;
double radians;
double value;
radians = r8_pi * ( degrees / 180.0 );
value = 1.0 / cos ( radians );
return value;
}
//****************************************************************************80
double r8_sech ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_SECH evaluates the hyperbolic secant, while avoiding COSH overflow.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the argument of the function.
//
// Output, double R8_SECH, the value of the function.
//
{
const double log_huge = 80.0;
double value;
if ( log_huge < fabs ( x ) )
{
value = 0.0;
}
else
{
value = 1.0 / cosh ( x );
}
return value;
}
//****************************************************************************80
double r8_sign ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN returns the sign of an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose sign is desired.
//
// Output, double R8_SIGN, the sign of X.
//
{
double value;
if ( x < 0.0 )
{
value = -1.0;
}
else
{
value = 1.0;
}
return value;
}
//****************************************************************************80
double r8_sign3 ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN3 returns the three-way sign of an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose sign is desired.
//
// Output, double R8_SIGN3, the sign of X.
//
{
double value;
if ( x < 0.0 )
{
value = -1.0;
}
else if ( x == 0.0 )
{
value = 0.0;
}
else
{
value = 1.0;
}
return value;
}
//****************************************************************************80
char r8_sign_char ( double x )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN_CHAR returns a character indicating the sign of an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the number whose sign is desired.
//
// Output, char R8_SIGN_CHAR, the sign of X, '-', '0' or '+'.
//
{
char value;
if ( x < 0.0 )
{
value = '-';
}
else if ( x == 0.0 )
{
value = '0';
}
else
{
value = '+';
}
return value;
}
//****************************************************************************80
bool r8_sign_match ( bool r1, bool r2 )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN_MATCH is TRUE if two R8's are of the same sign.
//
// Discussion:
//
// This test could be coded numerically as
//
// if ( 0 <= r1 * r2 ) then ...
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R1, R2, the values to check.
//
// Output, bool R8_SIGN_MATCH, is TRUE if ( R1 <= 0 and R2 <= 0 )
// or ( 0 <= R1 and 0 <= R2 ).
//
{
bool value;
value = ( r1 <= 0.0 && r2 <= 0.0 ) || ( 0.0 <= r1 && 0.0 <= r2 );
return value;
}
//****************************************************************************80
bool r8_sign_match_strict ( bool r1, bool r2 )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN_MATCH_STRICT is TRUE if two R8's are of the same strict sign.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R1, R2, the values to check.
//
// Output, bool R8_SIGN_MATCH_STRICT, is TRUE if the signs match.
//
{
bool value;
value = ( r1 < 0.0 && r2 < 0.0 ) ||
( r1 == 0.0 && r2 == 0.0 ) ||
( 0.0 < r1 && 0.0 < r2 );
return value;
}
//****************************************************************************80
bool r8_sign_opposite ( double r1, double r2 )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN_OPPOSITE is TRUE if two R8's are not of the same sign.
//
// Discussion:
//
// This test could be coded numerically as
//
// if ( r1 * r2 <= 0.0 ) ...
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 June 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R1, R2, the values to check.
//
// Output, bool R8_SIGN_OPPOSITE, is TRUE if ( R1 <= 0 and 0 <= R2 )
// or ( R2 <= 0 and 0 <= R1 ).
//
{
bool value;
value = ( r1 <= 0.0 && 0.0 <= r2 ) || ( r2 <= 0.0 && 0.0 <= r1 );
return value;
}
//****************************************************************************80
bool r8_sign_opposite_strict ( double r1, double r2 )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN_OPPOSITE_STRICT is TRUE if two R8's are strictly of opposite sign.
//
// Discussion:
//
// This test could be coded numerically as
//
// if ( r1 * r2 < 0.0 ) ...
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 June 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R1, R2, the values to check.
//
// Output, bool R8_SIGN_OPPOSITE_STRICT, is TRUE if ( R1 < 0 and 0 < R2 )
// or ( R2 < 0 and 0 < R1 ).
//
{
bool value;
value = ( r1 < 0.0 && 0.0 < r2 ) || ( r2 < 0.0 && 0.0 < r1 );
return value;
}
//****************************************************************************80
double r8_sign2 ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_SIGN2 returns the first argument with the sign of the second.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 January 2002
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the input arguments.
//
// Output, double R8_SIGN2, is equal to the absolute value of X, and
// has the sign of Y.
//
{
double value;
if ( 0.0 <= y )
{
value = fabs ( x );
}
else
{
value = - fabs ( x );
}
return value;
}
//****************************************************************************80
void r8_sincos_sum ( double a, double b, double &d, double &e, double &f )
//****************************************************************************80
//
// Purpose:
//
// R8_SINCOS_SUM simplifies a*sin(cx)+b*cos(cx).
//
// Discussion:
//
// The expression
// a * sin ( c * x ) + b * cos ( c * x )
// can be rewritten as
// d * sin ( c * x + e )
// or
// d * cos ( c * x + f )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 January 2016
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A, B, the coefficients in the linear combination.
//
// Output, double &D, &E, &F, the new coefficient, and the shift for
// sine or for cosine.
//
{
const double r8_pi = 3.141592653589793E+00;
d = sqrt ( a * a + b * b );
e = atan2 ( b, a );
f = atan2 ( b, a ) - r8_pi / 2.0E+00;
if ( f < - r8_pi )
{
f = f + 2.0E+00 * r8_pi;
}
return;
}
//****************************************************************************80
double r8_sind ( double degrees )
//****************************************************************************80
//
// Purpose:
//
// R8_SIND returns the sine of an angle given in degrees.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 July 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double DEGREES, the angle in degrees.
//
// Output, double R8_SIND, the sine of the angle.
//
{
const double r8_pi = 3.141592653589793;
double radians;
double value;
radians = r8_pi * ( degrees / 180.0 );
value = sin ( radians );
return value;
}
//****************************************************************************80
double r8_sqrt_i4 ( int i )
//****************************************************************************80
//
// Purpose:
//
// R8_SQRT_I4 returns the square root of an I4 as an R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 June 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I, the number whose square root is desired.
//
// Output, double R8_SQRT_I4, the value of sqrt(I).
//
{
double value;
value = sqrt ( ( double ) ( i ) );
return value;
}
//****************************************************************************80
double r8_sum ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_SUM returns the sum of two R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 April 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the quantities to add.
//
// Output, double R8_SUM, the sum of X and Y.
//
{
double value;
value = x + y;
return value;
}
//****************************************************************************80
void r8_swap ( double &x, double &y )
//****************************************************************************80
//
// Purpose:
//
// R8_SWAP switches two R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input/output, double &X, &Y. On output, the values of X and
// Y have been interchanged.
//
{
double z;
z = x;
x = y;
y = z;
return;
}
//****************************************************************************80
void r8_swap3 ( double &x, double &y, double &z )
//****************************************************************************80
//
// Purpose:
//
// R8_SWAP3 swaps three R8's.
//
// Example:
//
// Input:
//
// X = 1, Y = 2, Z = 3
//
// Output:
//
// X = 2, Y = 3, Z = 1
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 January 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input/output, double &X, &Y, &Z, three values to be swapped.
//
{
double w;
w = x;
x = y;
y = z;
z = w;
return;
}
//****************************************************************************80
double r8_tand ( double degrees )
//****************************************************************************80
//
// Purpose:
//
// R8_TAND returns the tangent of an angle given in degrees.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 July 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double DEGREES, the angle in degrees.
//
// Output, double R8_TAND, the tangent of the angle.
//
{
const double r8_pi = 3.141592653589793;
double radians;
double value;
radians = r8_pi * ( degrees / 180.0 );
value = sin ( radians ) / cos ( radians );
return value;
}
//****************************************************************************80
double r8_tiny ( )
//****************************************************************************80
//
// Purpose:
//
// R8_TINY returns a "tiny" R8.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 March 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_TINY, a "tiny" R8 value.
//
{
const double value = 0.4450147717014E-307;
return value;
}
//****************************************************************************80
void r8_to_dhms ( double r, int &d, int &h, int &m, int &s )
//****************************************************************************80
//
// Purpose:
//
// R8_TO_DHMS converts an R8 day value into days, hours, minutes, seconds.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, a real number representing a time period measured in days.
//
// Output, int &D, &H, &M, &S, the equivalent number of days, hours,
// minutes and seconds.
//
{
int sign;
if ( 0.0 <= r )
{
sign = 1;
}
else if ( r < 0.0 )
{
sign = -1;
r = -r;
}
d = ( int ) r;
r = r - ( double ) d;
r = 24.0 * r;
h = ( int ) r;
r = r - ( double ) h;
r = 60.0 * r;
m = ( int ) r;
r = r - ( double ) m;
r = 60.0 * r;
s = ( int ) r;
if ( sign == -1 )
{
d = -d;
h = -h;
m = -m;
s = -s;
}
return;
}
//****************************************************************************80
int r8_to_i4 ( double xmin, double xmax, double x, int ixmin, int ixmax )
//****************************************************************************80
//
// Purpose:
//
// R8_TO_I4 maps real X in [XMIN, XMAX] to integer IX in [IXMIN, IXMAX].
//
// Discussion:
//
// IX := IXMIN + ( IXMAX - IXMIN ) * ( X - XMIN ) / ( XMAX - XMIN )
// IX := min ( IX, max ( IXMIN, IXMAX ) )
// IX := max ( IX, min ( IXMIN, IXMAX ) )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 April 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double XMIN, XMAX, the real range. XMAX and XMIN must not be
// equal. It is not necessary that XMIN be less than XMAX.
//
// Input, double X, the real number to be converted.
//
// Input, int IXMIN, IXMAX, the allowed range of the output
// variable. IXMAX corresponds to XMAX, and IXMIN to XMIN.
// It is not necessary that IXMIN be less than IXMAX.
//
// Output, int R8_TO_I4, the value in the range [IXMIN,IXMAX] that
// corresponds to X.
//
{
int ix;
double temp;
if ( xmax == xmin )
{
cerr << "\n";
cerr << "R8_TO_I4 - Fatal error!\n";
cerr << " XMAX = XMIN, making a zero divisor.\n";
cerr << " XMAX = " << xmax << "\n";
cerr << " XMIN = " << xmin << "\n";
exit ( 1 );
}
temp =
( ( xmax - x ) * ( double ) ixmin
+ ( x - xmin ) * ( double ) ixmax )
/ ( xmax - xmin );
if ( 0.0 <= temp )
{
temp = temp + 0.5;
}
else
{
temp = temp - 0.5;
}
ix = ( int ) temp;
return ix;
}
//****************************************************************************80
double r8_to_r8_discrete ( double r, double rmin, double rmax, int nr )
//****************************************************************************80
//
// Purpose:
//
// R8_TO_R8_DISCRETE maps R to RD in [RMIN, RMAX] with NR possible values.
//
// Discussion:
//
// if ( R < RMIN ) then
// RD = RMIN
// else if ( RMAX < R ) then
// RD = RMAX
// else
// T = nint ( ( NR - 1 ) * ( R - RMIN ) / ( RMAX - RMIN ) )
// RD = RMIN + T * ( RMAX - RMIN ) / real ( NR - 1 )
//
// In the special case where NR = 1, when
//
// XD = 0.5 * ( RMAX + RMIN )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, the number to be converted.
//
// Input, double RMAX, RMIN, the maximum and minimum
// values for RD.
//
// Input, int NR, the number of allowed values for XD.
// NR should be at least 1.
//
// Output, double RD, the corresponding discrete value.
//
{
int f;
double rd;
//
// Check for errors.
//
if ( nr < 1 )
{
cerr << "\n";
cerr << "R8_TO_R8_DISCRETE - Fatal error!\n";
cerr << " NR = " << nr << "\n";
cerr << " but NR must be at least 1.\n";
exit ( 1 );
}
if ( nr == 1 )
{
rd = 0.5 * ( rmin + rmax );
return rd;
}
if ( rmax == rmin )
{
rd = rmax;
return rd;
}
f = r8_nint ( ( double ) ( nr ) * ( rmax - r ) / ( rmax - rmin ) );
f = i4_max ( f, 0 );
f = i4_min ( f, nr );
rd = ( ( double ) ( f ) * rmin
+ ( double ) ( nr - f ) * rmax )
/ ( double ) ( nr );
return rd;
}
//****************************************************************************80
double r8_uniform_01 ( int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8_UNIFORM_01 returns a unit pseudorandom R8.
//
// Discussion:
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// If the initial seed is 12345, then the first three computations are
//
// Input Output R8_UNIFORM_01
// SEED SEED
//
// 12345 207482415 0.096616
// 207482415 1790989824 0.833995
// 1790989824 2035175616 0.947702
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has been updated.
//
// Output, double R8_UNIFORM_01, a new pseudorandom variate,
// strictly between 0 and 1.
//
{
const int i4_huge = 2147483647;
int k;
double r;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8_UNIFORM_01 - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r = ( double ) ( seed ) * 4.656612875E-10;
return r;
}
//****************************************************************************80
double r8_uniform_ab ( double a, double b, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8_UNIFORM_AB returns a scaled pseudorandom R8.
//
// Discussion:
//
// The pseudorandom number should be uniformly distributed
// between A and B.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A, B, the limits of the interval.
//
// Input/output, int &SEED, the "seed" value, which should NOT be 0.
// On output, SEED has been updated.
//
// Output, double R8_UNIFORM_AB, a number strictly between A and B.
//
{
const int i4_huge = 2147483647;
int k;
double value;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8_UNIFORM_AB - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
value = ( double ) ( seed ) * 4.656612875E-10;
value = a + ( b - a ) * value;
return value;
}
//****************************************************************************80
void r8_unswap3 ( double &x, double &y, double &z )
//****************************************************************************80
//
// Purpose:
//
// R8_UNSWAP3 unswaps three R8's.
//
// Example:
//
// Input:
//
// X = 2, Y = 3, Z = 1
//
// Output:
//
// X = 1, Y = 2, Z = 3
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input/output, double &X, &Y, &Z, three values to be swapped.
//
{
double w;
w = z;
z = y;
y = x;
x = w;
return;
}
//****************************************************************************80
double r8_walsh_1d ( double x, int digit )
//****************************************************************************80
//
// Purpose:
//
// R8_WALSH_1D evaluates the Walsh function of a real scalar argument.
//
// Discussion:
//
// Consider the binary representation of X, and number the digits
// in descending order, from leading to lowest, with the units digit
// being numbered 0.
//
// The Walsh function W(J)(X) is equal to the J-th binary digit of X.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, the argument of the Walsh function.
//
// Input, int DIGIT, the index of the Walsh function.
//
// Output, double R8_WALSH_1D, the value of the Walsh function.
//
{
int n;
double value;
//
// Hide the effect of the sign of X.
//
x = fabs ( x );
//
// If DIGIT is positive, divide by 2 DIGIT times.
// If DIGIT is negative, multiply by 2 (-DIGIT) times.
//
x = x / pow ( 2.0, digit );
//
// Make it an integer.
// Because it's positive, and we're using INT, we don't change the
// units digit.
//
n = ( int ) x;
//
// Is the units digit odd or even?
//
if ( ( n % 2 ) == 0 )
{
value = 0.0;
}
else
{
value = 1.0;
}
return value;
}
//****************************************************************************80
double r8_wrap ( double r, double rlo, double rhi )
//****************************************************************************80
//
// Purpose:
//
// R8_WRAP forces an R8 to lie between given limits by wrapping.
//
// Discussion:
//
// An R8 is a double value.
//
// Example:
//
// RLO = 4.0, RHI = 8.0
//
// R Value
//
// -2 8
// -1 4
// 0 5
// 1 6
// 2 7
// 3 8
// 4 4
// 5 5
// 6 6
// 7 7
// 8 8
// 9 4
// 10 5
// 11 6
// 12 7
// 13 8
// 14 4
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 July 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, a value.
//
// Input, double RLO, RHI, the desired bounds.
//
// Output, double R8_WRAP, a "wrapped" version of the value.
//
{
int n;
double rhi2;
double rlo2;
double rwide;
double value;
//
// Guarantee RLO2 < RHI2.
//
rlo2 = r8_min ( rlo, rhi );
rhi2 = r8_max ( rlo, rhi );
//
// Find the width.
//
rwide = rhi2 - rlo2;
//
// Add enough copies of (RHI2-RLO2) to R so that the
// result ends up in the interval RLO2 - RHI2.
//
if ( rwide == 0.0 )
{
value = rlo;
}
else if ( r < rlo2 )
{
n = ( int ) ( ( rlo2 - r ) / rwide ) + 1;
value = r + n * rwide;
if ( value == rhi )
{
value = rlo;
}
}
else
{
n = ( int ) ( ( r - rlo2 ) / rwide );
value = r - n * rwide;
if ( value == rlo )
{
value = rhi;
}
}
return value;
}
//****************************************************************************80
double r8_zeta ( double p )
//****************************************************************************80
//
// Purpose:
//
// R8_ZETA estimates the Riemann Zeta function.
//
// Discussion:
//
// For 1 < P, the Riemann Zeta function is defined as:
//
// ZETA ( P ) = Sum ( 1 <= N < oo ) 1 / N^P
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 October 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Daniel Zwillinger, editor,
// CRC Standard Mathematical Tables and Formulae,
// 30th Edition,
// CRC Press, 1996.
//
// Parameters:
//
// Input, double P, the power to which the integers are raised.
// P must be greater than 1. For integral P up to 20, a
// precomputed value is returned; otherwise the infinite
// sum is approximated.
//
// Output, double R8_ZETA, an approximation to the Riemann
// Zeta function.
//
{
int n;
const double r8_huge = 1.0E+30;
const double r8_pi = 3.14159265358979323;
double value;
double zsum;
double zsum_old;
if ( p <= 1.0 )
{
value = r8_huge;
}
else if ( p == 2.0 )
{
value = pow ( r8_pi, 2 ) / 6.0;
}
else if ( p == 3.0 )
{
value = 1.2020569032;
}
else if ( p == 4.0 )
{
value = pow ( r8_pi, 4 ) / 90.0;
}
else if ( p == 5.0 )
{
value = 1.0369277551;
}
else if ( p == 6.0 )
{
value = pow ( r8_pi, 6 ) / 945.0;
}
else if ( p == 7.0 )
{
value = 1.0083492774;
}
else if ( p == 8.0 )
{
value = pow ( r8_pi, 8 ) / 9450.0;
}
else if ( p == 9.0 )
{
value = 1.0020083928;
}
else if ( p == 10.0 )
{
value = pow ( r8_pi, 10 ) / 93555.0;
}
else if ( p == 11.0 )
{
value = 1.0004941886;
}
else if ( p == 12.0 )
{
value = 1.0002460866;
}
else if ( p == 13.0 )
{
value = 1.0001227133;
}
else if ( p == 14.0 )
{
value = 1.0000612482;
}
else if ( p == 15.0 )
{
value = 1.0000305882;
}
else if ( p == 16.0 )
{
value = 1.0000152823;
}
else if ( p == 17.0 )
{
value = 1.0000076372;
}
else if ( p == 18.0 )
{
value = 1.0000038173;
}
else if ( p == 19.0 )
{
value = 1.0000019082;
}
else if ( p == 20.0 )
{
value = 1.0000009540;
}
else
{
zsum = 0.0;
n = 0;
for ( ; ; )
{
n = n + 1;
zsum_old = zsum;
zsum = zsum + 1.0 / pow ( ( double ) n, p );
if ( zsum <= zsum_old )
{
break;
}
}
value = zsum;
}
return value;
}
//****************************************************************************80
double r82_dist_l2 ( double a1[2], double a2[2] )
//****************************************************************************80
//
// Purpose:
//
// R82_DIST_L2 returns the L2 distance between a pair of R82's.
//
// Discussion:
//
// An R82 is a vector of type R8, with two entries.
//
// The vector L2 norm is defined as:
//
// sqrt ( sum ( 1 <= I <= N ) A(I) * A(I) ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A1[2], A2[2], the vectors.
//
// Output, double R82_DIST_L2, the L2 norm of A1 - A2.
//
{
double value;
value = sqrt ( pow ( a1[0] - a2[0], 2 )
+ pow ( a1[1] - a2[1], 2 ) );
return value;
}
//****************************************************************************80
void r82_print ( double a[2], string title )
//****************************************************************************80
//
// Purpose:
//
// R82_PRINT prints an R82.
//
// Discussion:
//
// An R82 is an R8VEC with two entries.
//
// A format is used which suggests a coordinate pair:
//
// Example:
//
// Center : ( 1.23, 7.45 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[2], the coordinates of the vector.
//
// Input, string TITLE, a title.
//
{
cout << " " << title << " : ";
cout << ": ( " << setw(12) << a[0]
<< ", " << setw(12) << a[1] << " )\n";
return;
}
//****************************************************************************80
void r82_uniform_ab ( double b, double c, int &seed, double r[] )
//****************************************************************************80
//
// Purpose:
//
// R82_UNIFORM_AB returns a random R82 value in a given range.
//
// Discussion:
//
// An R82 is an R8VEC with two entries.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double B, C, the minimum and maximum values.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R[2], the randomly chosen value.
//
{
int i;
for ( i = 0; i < 2; i++ )
{
r[i] = r8_uniform_ab ( b, c, seed );
}
return;
}
//****************************************************************************80
void r82col_print_part ( int n, double a[], int max_print, string title )
//****************************************************************************80
//
// Purpose:
//
// R82COL_PRINT_PART prints "part" of an R82COL.
//
// Discussion:
//
// An R82COL is an (N,2) array of R8's.
//
// The user specifies MAX_PRINT, the maximum number of lines to print.
//
// If N, the size of the vector, is no more than MAX_PRINT, then
// the entire vector is printed, one entry per line.
//
// Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
// followed by a line of periods suggesting an omission,
// and the last entry.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 April 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vector.
//
// Input, double A[N*2], the vector to be printed.
//
// Input, int MAX_PRINT, the maximum number of lines
// to print.
//
// Input, string TITLE, a title.
//
{
int i;
if ( max_print <= 0 )
{
return;
}
if ( n <= 0 )
{
return;
}
cout << "\n";
cout << title << "\n";
cout << "\n";
if ( n <= max_print )
{
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< " " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n] << "\n";
}
}
else if ( 3 <= max_print )
{
for ( i = 0; i < max_print - 2; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n] << "\n";
}
cout << " ........ .............. ..............\n";
i = n - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n] << "\n";
}
else
{
for ( i = 0; i < max_print - 1; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n] << "\n";
}
i = max_print - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n]
<< " " << "...more entries...\n";
}
return;
}
//****************************************************************************80
void r82poly2_print ( double a, double b, double c, double d, double e,
double f )
//****************************************************************************80
//
// Purpose:
//
// R82POLY2_PRINT prints a second order polynomial in two variables.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A, B, C, D, E, F, the coefficients.
//
{
cout << " " << setw(8) << a
<< " * x^2 + " << setw(8) << b
<< " * y^2 + " << setw(8) << c
<< " * xy + " << "\n";
cout << " " << setw(8) << d
<< " * x + " << setw(8) << e
<< " * y + " << setw(8) << f << "\n";
return;
}
//****************************************************************************80
int r82poly2_type ( double a, double b, double c, double d, double e, double f )
//****************************************************************************80
//
// Purpose:
//
// R82POLY2_TYPE analyzes a second order polynomial in two variables.
//
// Discussion:
//
// The polynomial has the form
//
// A x^2 + B y^2 + C xy + Dx + Ey + F = 0
//
// The possible types of the solution set are:
//
// 1: a hyperbola;
// 9x^2 - 4y^2 -36x - 24y - 36 = 0
// 2: a parabola;
// 4x^2 + 1y^2 - 4xy + 3x - 4y + 1 = 0;
// 3: an ellipse;
// 9x^2 + 16y^2 +36x - 32y - 92 = 0;
// 4: an imaginary ellipse (no real solutions);
// x^2 + y^2 - 6x - 10y + 115 = 0;
// 5: a pair of intersecting lines;
// xy + 3x - y - 3 = 0
// 6: one point;
// x^2 + 2y^2 - 2x + 16y + 33 = 0;
// 7: a pair of distinct parallel lines;
// y^2 - 6y + 8 = 0
// 8: a pair of imaginary parallel lines (no real solutions);
// y^2 - 6y + 10 = 0
// 9: a pair of coincident lines.
// y^2 - 2y + 1 = 0
// 10: a single line;
// 2x - y + 1 = 0;
// 11; all space;
// 0 = 0;
// 12; no solutions;
// 1 = 0;
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 September 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Daniel Zwillinger, editor,
// CRC Standard Mathematical Tables and Formulae,
// CRC Press, 30th Edition, 1996, pages 282-284.
//
// Parameters:
//
// Input, double A, B, C, D, E, F, the coefficients.
//
// Output, int TYPE, indicates the type of the solution set.
//
{
double delta;
double j;
double k;
int type;
//
// Handle the degenerate case.
//
if ( a == 0.0 && b == 0.0 && c == 0.0 )
{
if ( d == 0.0 && e == 0.0 )
{
if ( f == 0.0 )
{
type = 11;
}
else
{
type = 12;
}
}
else
{
type = 10;
}
return type;
}
delta =
8.0 * a * b * f
+ 2.0 * c * e * d
- 2.0 * a * e * e
- 2.0 * b * d * d
- 2.0 * f * c * c;
j = 4.0 * a * b - c * c;
if ( delta != 0.0 )
{
if ( j < 0.0 )
{
type = 1;
}
else if ( j == 0.0 )
{
type = 2;
}
else if ( 0.0 < j )
{
if ( r8_sign ( delta ) != r8_sign ( a + b ) )
{
type = 3;
}
else if ( r8_sign ( delta ) == r8_sign ( a + b ) )
{
type = 4;
}
}
}
else if ( delta == 0.0 )
{
if ( j < 0.0 )
{
type = 5;
}
else if ( 0.0 < j )
{
type = 6;
}
else if ( j == 0.0 )
{
k = 4.0 * ( a + b ) * f - d * d - e * e;
if ( k < 0.0 )
{
type = 7;
}
else if ( 0.0 < k )
{
type = 8;
}
else if ( k == 0.0 )
{
type = 9;
}
}
}
return type;
}
//****************************************************************************80
void r82poly2_type_print ( int type )
//****************************************************************************80
//
// Purpose:
//
// R82POLY2_TYPE_PRINT prints the meaning of the output from R82POLY2_TYPE.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int TYPE, the type index returned by R82POLY2_TYPE.
//
{
if ( type == 1 )
{
cout << " The set of solutions forms a hyperbola.\n";
}
else if ( type == 2 )
{
cout << " The set of solutions forms a parabola.\n";
}
else if ( type == 3 )
{
cout << " The set of solutions forms an ellipse.\n";
}
else if ( type == 4 )
{
cout << " The set of solutions forms an imaginary ellipse.\n";
cout << " (There are no real solutions).\n";
}
else if ( type == 5 )
{
cout << " The set of solutions forms a pair of intersecting lines.\n";
}
else if ( type == 6 )
{
cout << " The set of solutions is a single point.\n";
}
else if ( type == 7 )
{
cout << " The set of solutions form a pair of distinct parallel lines.\n";
}
else if ( type == 8 )
{
cout << " The set of solutions forms a pair of imaginary parallel lines.\n";
cout << " (There are no real solutions).\n";
}
else if ( type == 9 )
{
cout << " The set of solutions forms a pair of coincident lines.\n";
}
else if ( type == 10 )
{
cout << " The set of solutions forms a single line.\n";
}
else if ( type == 11 )
{
cout << " The set of solutions is all space.\n";
}
else if ( type == 12 )
{
cout << " The set of solutions is empty.\n";
}
else
{
cout << " This type index is unknown.\n";
}
return;
}
//****************************************************************************80
double *r82row_max ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_MAX returns the maximum value in an R82ROW.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 July 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[2*N], the array.
//
// Output, double R82ROW_MAX[2]; the largest entries in each row.
//
{
# define DIM_NUM 2
double *amax = NULL;
int i;
int j;
if ( n <= 0 )
{
return NULL;
}
amax = new double[DIM_NUM];
for ( i = 0; i < DIM_NUM; i++ )
{
amax[i] = a[i+0*DIM_NUM];
for ( j = 1; j < n; j++ )
{
if ( amax[i] < a[0+j*DIM_NUM] )
{
amax[i] = a[0+j*DIM_NUM];
}
}
}
return amax;
# undef DIM_NUM
}
//****************************************************************************80
double *r82row_min ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_MIN returns the minimum value in an R82ROW.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 July 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[2*N], the array.
//
// Output, double R82ROW_MIN[2]; the smallest entries in each row.
//
{
# define DIM_NUM 2
double *amin = NULL;
int i;
int j;
if ( n <= 0 )
{
return NULL;
}
amin = new double[DIM_NUM];
for ( i = 0; i < DIM_NUM; i++ )
{
amin[i] = a[i+0*DIM_NUM];
for ( j = 1; j < n; j++ )
{
if ( a[0+j*DIM_NUM] < amin[i] )
{
amin[i] = a[0+j*DIM_NUM];
}
}
}
return amin;
# undef DIM_NUM
}
//****************************************************************************80
int r82row_order_type ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_ORDER_TYPE finds if an R82ROW is (non)strictly ascending/descending.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// The dictionary or lexicographic ordering is used.
//
// (X1,Y1) < (X2,Y2) <=> X1 < X2 or ( X1 = X2 and Y1 < Y2).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the array.
//
// Input, double A[2*N], the array to be checked.
//
// Output, int R82ROW_ORDER_TYPE, order indicator:
// -1, no discernable order;
// 0, all entries are equal;
// 1, ascending order;
// 2, strictly ascending order;
// 3, descending order;
// 4, strictly descending order.
//
{
int i;
int order;
//
// Search for the first value not equal to A(1,1).
//
i = 0;
for ( ; ; )
{
i = i + 1;
if ( n <= i )
{
order = 0;
return order;
}
if ( a[0+0*2] < a[0+i*2] || ( a[0+0*2] == a[0+i*2] && a[1+0*2] < a[1+i*2] ) )
{
if ( i == 2 )
{
order = 2;
}
else
{
order = 1;
}
break;
}
else if ( a[0+i*2] < a[0+0*2] ||
( a[0+i*2] == a[0+0*2] && a[1+i*2] < a[1+0*2] ) )
{
if ( i == 2 )
{
order = 4;
}
else
{
order = 3;
}
break;
}
}
//
// Now we have a "direction". Examine subsequent entries.
//
for ( ; ; )
{
i = i + 1;
if ( n <= i )
{
break;
}
if ( order == 1 )
{
if ( a[0+i*2] < a[0+(i-1)*2] ||
( a[0+i*2] == a[0+(i-1)*2] && a[1+i*2] < a[1+(i-1)*2] ) )
{
order = -1;
break;
}
}
else if ( order == 2 )
{
if ( a[0+i*2] < a[0+(i-1)*2] ||
( a[0+i*2] == a[0+(i-1)*2] && a[1+i*2] < a[1+(i-1)*2] ) )
{
order = -1;
break;
}
else if ( a[0+i*2] == a[0+(i-1)*2] && a[1+i*2] == a[1+(i-1)*2] )
{
order = 1;
}
}
else if ( order == 3 )
{
if ( a[0+(i-1)*2] < a[0+i*2] ||
( a[0+(i-1)*2] == a[0+i*2] && a[1+(i-1)*2] < a[1+i*2] ) )
{
order = -1;
break;
}
}
else if ( order == 4 )
{
if ( a[0+(i-1)*2] < a[0+i*2] ||
( a[0+(i-1)*2] == a[0+i*2] && a[1+(i-1)*2] < a[1+i*2] ) )
{
order = -1;
break;
}
else if ( a[0+i*2] == a[0+(i-1)*2] && a[1+i*2] == a[1+(i-1)*2] )
{
order = 3;
}
}
}
return order;
}
//****************************************************************************80
void r82row_part_quick_a ( int n, double a[], int &l, int &r )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_PART_QUICK_A reorders an R82ROW as part of a quick sort.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// The routine reorders the entries of A. Using A(1:2,1) as a
// key, all entries of A that are less than or equal to the key will
// precede the key, which precedes all entries that are greater than the key.
//
// Example:
//
// Input:
//
// N = 8
//
// A = ( (2,4), (8,8), (6,2), (0,2), (10,6), (10,0), (0,6), (4,8) )
//
// Output:
//
// L = 2, R = 4
//
// A = ( (0,2), (0,6), (2,4), (8,8), (6,2), (10,6), (10,0), (4,8) )
// ----------- ----------------------------------
// LEFT KEY RIGHT
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of A.
//
// Input/output, double A[N*2]. On input, the array to be checked.
// On output, A has been reordered as described above.
//
// Output, int &L, &R, the indices of A that define the three segments.
// Let KEY = the input value of A(1:2,1). Then
// I <= L A(1:2,I) < KEY;
// L < I < R A(1:2,I) = KEY;
// R <= I A(1:2,I) > KEY.
//
{
int i;
int j;
double key[2];
int ll;
int m;
int rr;
//
if ( n < 1 )
{
cerr << "\n";
cerr << "R82ROW_PART_QUICK_A - Fatal error!\n";
cerr << " N < 1.\n";
exit ( 1 );
}
if ( n == 1 )
{
l = 0;
r = 2;
return;
}
key[0] = a[2*0+0];
key[1] = a[2*0+1];
m = 1;
//
// The elements of unknown size have indices between L+1 and R-1.
//
ll = 1;
rr = n + 1;
for ( i = 2; i <= n; i++ )
{
if ( r8vec_gt ( 2, a+2*ll, key ) )
{
rr = rr - 1;
r8vec_swap ( 2, a+2*(rr-1), a+2*ll );
}
else if ( r8vec_eq ( 2, a+2*ll, key ) )
{
m = m + 1;
r8vec_swap ( 2, a+2*(m-1), a+2*ll );
ll = ll + 1;
}
else if ( r8vec_lt ( 2, a+2*ll, key ) )
{
ll = ll + 1;
}
}
//
// Now shift small elements to the left, and KEY elements to center.
//
for ( i = 0; i < ll - m; i++ )
{
for ( j = 0; j < 2; j++ )
{
a[2*i+j] = a[2*(i+m)+j];
}
}
ll = ll - m;
for ( i = ll; i < ll+m; i++ )
{
for ( j = 0; j < 2; j++ )
{
a[2*i+j] = key[j];
}
}
l = ll;
r = rr;
return;
}
//****************************************************************************80
void r82row_permute ( int n, int p[], double a[] )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_PERMUTE permutes an R82ROW in place.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// This routine permutes an array of real "objects", but the same
// logic can be used to permute an array of objects of any arithmetic
// type, or an array of objects of any complexity. The only temporary
// storage required is enough to store a single object. The number
// of data movements made is N + the number of cycles of order 2 or more,
// which is never more than N + N/2.
//
// Example:
//
// Input:
//
// N = 5
// P = ( 2, 4, 5, 1, 3 )
// A = ( 1.0, 2.0, 3.0, 4.0, 5.0 )
// (11.0, 22.0, 33.0, 44.0, 55.0 )
//
// Output:
//
// A = ( 2.0, 4.0, 5.0, 1.0, 3.0 )
// ( 22.0, 44.0, 55.0, 11.0, 33.0 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 October 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of objects.
//
// Input, int P[N], the permutation. P(I) = J means
// that the I-th element of the output array should be the J-th
// element of the input array.
//
// Input/output, double A[2*N], the array to be permuted.
//
{
double a_temp[2];
int i;
int iget;
int iput;
int istart;
if ( !perm0_check ( n, p ) )
{
cerr << "\n";
cerr << "R82ROW_PERMUTE - Fatal error!\n";
cerr << " PERM0_CHECK rejects permutation.\n";
exit ( 1 );
}
//
// In order for the sign negation trick to work, we need to assume that the
// entries of P are strictly positive. Presumably, the lowest number is 0.
// So temporarily add 1 to each entry to force positivity.
//
for ( i = 0; i < n; i++ )
{
p[i] = p[i] + 1;
}
//
// Search for the next element of the permutation that has not been used.
//
for ( istart = 1; istart <= n; istart++ )
{
if ( p[istart-1] < 0 )
{
continue;
}
else if ( p[istart-1] == istart )
{
p[istart-1] = - p[istart-1];
continue;
}
else
{
a_temp[0] = a[0+(istart-1)*2];
a_temp[1] = a[1+(istart-1)*2];
iget = istart;
//
// Copy the new value into the vacated entry.
//
for ( ; ; )
{
iput = iget;
iget = p[iget-1];
p[iput-1] = - p[iput-1];
if ( iget < 1 || n < iget )
{
cerr << "\n";
cerr << "R82ROW_PERMUTE - Fatal error!\n";
cerr << " Entry IPUT = " << iput << " of the permutation has\n";
cerr << " an illegal value IGET = " << iget << ".\n";
exit ( 1 );
}
if ( iget == istart )
{
a[0+(iput-1)*2] = a_temp[0];
a[1+(iput-1)*2] = a_temp[1];
break;
}
a[0+(iput-1)*2] = a[0+(iget-1)*2];
a[1+(iput-1)*2] = a[1+(iget-1)*2];
}
}
}
//
// Restore the signs of the entries.
//
for ( i = 0; i < n; i++ )
{
p[i] = - p[i];
}
//
// Restore the entries.
//
for ( i = 0; i < n; i++ )
{
p[i] = p[i] - 1;
}
return;
}
//****************************************************************************80
void r82row_print ( int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_PRINT prints an R82ROW.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 November 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A[2*N], the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int j;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( j = 0; j < n; j++ )
{
cout << " " << setw(8) << j
<< ": " << setw(14) << a[0+j*2]
<< " " << setw(14) << a[1+j*2] << "\n";
}
return;
}
//****************************************************************************80
void r82row_print_part ( int n, double a[], int max_print, string title )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_PRINT_PART prints "part" of an R82ROW.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// The user specifies MAX_PRINT, the maximum number of lines to print.
//
// If N, the size of the vector, is no more than MAX_PRINT, then
// the entire vector is printed, one entry per line.
//
// Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
// followed by a line of periods suggesting an omission,
// and the last entry.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vector.
//
// Input, double A[2*N], the vector to be printed.
//
// Input, int MAX_PRINT, the maximum number of lines
// to print.
//
// Input, string TITLE, a title.
//
{
int i;
if ( max_print <= 0 )
{
return;
}
if ( n <= 0 )
{
return;
}
cout << "\n";
cout << title << "\n";
cout << "\n";
if ( n <= max_print )
{
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< " " << setw(14) << a[0+i*2]
<< " " << setw(14) << a[1+i*2] << "\n";
}
}
else if ( 3 <= max_print )
{
for ( i = 0; i < max_print - 2; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*2]
<< " " << setw(14) << a[1+i*2] << "\n";
}
cout << " ........ .............. ..............\n";
i = n - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*2]
<< " " << setw(14) << a[1+i*2] << "\n";
}
else
{
for ( i = 0; i < max_print - 1; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*2]
<< " " << setw(14) << a[1+i*2] << "\n";
}
i = max_print - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*2]
<< " " << setw(14) << a[1+i*2]
<< " " << "...more entries...\n";
}
return;
}
//****************************************************************************80
int *r82row_sort_heap_index_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_SORT_HEAP_INDEX_A does an indexed heap ascending sort of an R82ROW.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// The sorting is not actually carried out. Rather an index array is
// created which defines the sorting. This array may be used to sort
// or index the array, or to sort or index related arrays keyed on the
// original array.
//
// Once the index array is computed, the sorting can be carried out
// "implicitly:
//
// a(*,indx(*))
//
// or explicitly, by the call
//
// r82row_permute ( n, indx, a )
//
// after which a(*,*) is sorted.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[2*N], an array to be index-sorted.
//
// Output, int R82ROW_SORT_HEAP_INDEX_A[N], the sort index. The
// I-th element of the sorted array is A(0:1,R82ROW_SORT_HEAP_INDEX_A(I)).
//
{
double aval[2];
int i;
int *indx;
int indxt;
int ir;
int j;
int l;
if ( n < 1 )
{
return NULL;
}
indx = new int[n];
for ( i = 0; i < n; i++ )
{
indx[i] = i;
}
if ( n == 1 )
{
indx[0] = indx[0];
return indx;
}
l = n / 2 + 1;
ir = n;
for ( ; ; )
{
if ( 1 < l )
{
l = l - 1;
indxt = indx[l-1];
aval[0] = a[0+indxt*2];
aval[1] = a[1+indxt*2];
}
else
{
indxt = indx[ir-1];
aval[0] = a[0+indxt*2];
aval[1] = a[1+indxt*2];
indx[ir-1] = indx[0];
ir = ir - 1;
if ( ir == 1 )
{
indx[0] = indxt;
break;
}
}
i = l;
j = l + l;
while ( j <= ir )
{
if ( j < ir )
{
if ( a[0+indx[j-1]*2] < a[0+indx[j]*2] ||
( a[0+indx[j-1]*2] == a[0+indx[j]*2] &&
a[1+indx[j-1]*2] < a[1+indx[j]*2] ) )
{
j = j + 1;
}
}
if ( aval[0] < a[0+indx[j-1]*2] ||
( aval[0] == a[0+indx[j-1]*2] &&
aval[1] < a[1+indx[j-1]*2] ) )
{
indx[i-1] = indx[j-1];
i = j;
j = j + j;
}
else
{
j = ir + 1;
}
}
indx[i-1] = indxt;
}
return indx;
}
//****************************************************************************80
void r82row_sort_quick_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R82ROW_SORT_QUICK_A ascending sorts an R82ROW using quick sort.
//
// Discussion:
//
// An R82ROW is a (2,N) array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input/output, double A[2*N].
// On input, the array to be sorted.
// On output, the array has been sorted.
//
{
# define LEVEL_MAX 30
int base;
int l_segment;
int level;
int n_segment;
int rsave[LEVEL_MAX];
int r_segment;
if ( n < 1 )
{
cerr << "\n";
cerr << "R82ROW_SORT_QUICK_A - Fatal error!\n";
cerr << " N < 1.\n";
exit ( 1 );
}
if ( n == 1 )
{
return;
}
level = 1;
rsave[level-1] = n + 1;
base = 1;
n_segment = n;
while ( 0 < n_segment )
{
//
// Partition the segment.
//
r82row_part_quick_a ( n_segment, a+2*(base-1)+0, l_segment, r_segment );
//
// If the left segment has more than one element, we need to partition it.
//
if ( 1 < l_segment )
{
if ( LEVEL_MAX < level )
{
cerr << "\n";
cerr<< "R82ROW_SORT_QUICK_A - Fatal error!\n";
cerr << " Exceeding recursion maximum of " << LEVEL_MAX << "\n";
exit ( 1 );
}
level = level + 1;
n_segment = l_segment;
rsave[level-1] = r_segment + base - 1;
}
//
// The left segment and the middle segment are sorted.
// Must the right segment be partitioned?
//
else if ( r_segment < n_segment )
{
n_segment = n_segment + 1 - r_segment;
base = base + r_segment - 1;
}
//
// Otherwise, we back up a level if there is an earlier one.
//
else
{
for ( ; ; )
{
if ( level <= 1 )
{
n_segment = 0;
break;
}
base = rsave[level-1];
n_segment = rsave[level-2] - rsave[level-1];
level = level - 1;
if ( 0 < n_segment )
{
break;
}
}
}
}
return;
# undef LEVEL_MAX
}
//****************************************************************************80
double r83_norm ( double x, double y, double z )
//****************************************************************************80
//
// Purpose:
//
// R83_NORM returns the Euclidean norm of an R83.
//
// Discussion:
//
// An R83 is a vector of 3 R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, Z, the vector.
//
// Output, double R83_NORM, the norm of the vector.
//
{
double value;
value = sqrt ( x * x + y * y + z * z );
return value;
}
//****************************************************************************80
void r83col_print_part ( int n, double a[], int max_print, string title )
//****************************************************************************80
//
// Purpose:
//
// R83COL_PRINT_PART prints "part" of an R83COL.
//
// Discussion:
//
// An R83COL is an (N,3) array of R8's.
//
// The user specifies MAX_PRINT, the maximum number of lines to print.
//
// If N, the size of the vector, is no more than MAX_PRINT, then
// the entire vector is printed, one entry per line.
//
// Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
// followed by a line of periods suggesting an omission,
// and the last entry.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 April 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vector.
//
// Input, double A[N*3], the vector to be printed.
//
// Input, int MAX_PRINT, the maximum number of lines
// to print.
//
// Input, string TITLE, a title.
//
{
int i;
if ( max_print <= 0 )
{
return;
}
if ( n <= 0 )
{
return;
}
cout << "\n";
cout << title << "\n";
cout << "\n";
if ( n <= max_print )
{
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< " " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n]
<< " " << setw(14) << a[i+2*n] << "\n";
}
}
else if ( 3 <= max_print )
{
for ( i = 0; i < max_print - 2; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n]
<< " " << setw(14) << a[i+2*n] << "\n";
}
cout << " ........ .............. .............. ..............\n";
i = n - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n]
<< " " << setw(14) << a[i+2*n] << "\n";
}
else
{
for ( i = 0; i < max_print - 1; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n]
<< " " << setw(14) << a[i+2*n] << "\n";
}
i = max_print - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i+0*n]
<< " " << setw(14) << a[i+1*n]
<< " " << setw(14) << a[i+2*n]
<< " " << "...more entries...\n";
}
return;
}
//****************************************************************************80
double *r83row_max ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R83ROW_MAX returns the maximum value in an R83ROW.
//
// Discussion:
//
// An R83ROW is a (3,N) array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 January 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[3*N], the array.
//
// Output, double R83ROW_MAX[3]; the largest entries in each row.
//
{
# define DIM_NUM 3
double *amax = NULL;
int i;
int j;
if ( n <= 0 )
{
return NULL;
}
amax = new double[DIM_NUM];
for ( i = 0; i < DIM_NUM; i++ )
{
amax[i] = a[i+0*DIM_NUM];
for ( j = 1; j < n; j++ )
{
if ( amax[i] < a[i+j*DIM_NUM] )
{
amax[i] = a[i+j*DIM_NUM];
}
}
}
return amax;
# undef DIM_NUM
}
//****************************************************************************80
double *r83row_min ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R83ROW_MIN returns the minimum value in an R83ROW.
//
// Discussion:
//
// An R83ROW is a (3,N) array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 January 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[3*N], the array.
//
// Output, double R83ROW_MIN[3]; the smallest entries in each row.
//
{
# define DIM_NUM 3
double *amin = NULL;
int i;
int j;
if ( n <= 0 )
{
return NULL;
}
amin = new double[DIM_NUM];
for ( i = 0; i < DIM_NUM; i++ )
{
amin[i] = a[i+0*DIM_NUM];
for ( j = 1; j < n; j++ )
{
if ( a[i+j*DIM_NUM] < amin[i] )
{
amin[i] = a[i+j*DIM_NUM];
}
}
}
return amin;
# undef DIM_NUM
}
//****************************************************************************80
void r83row_part_quick_a ( int n, double a[], int &l, int &r )
//****************************************************************************80
//
// Purpose:
//
// R83ROW_PART_QUICK_A reorders an R83ROW as part of a quick sort.
//
// Discussion:
//
// An R83ROW is a (3,N) array of R8's.
//
// The routine reorders the entries of A. Using A(1:3,1) as a
// key, all entries of A that are less than or equal to the key will
// precede the key, which precedes all entries that are greater than the key.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of A.
//
// Input/output, double A[3*N]. On input, the array to be checked.
// On output, A has been reordered as described above.
//
// Output, int &L, &R, the indices of A that define the three segments.
// Let KEY = the input value of A(1:3,1). Then
// I <= L A(1:3,I) < KEY;
// L < I < R A(1:3,I) = KEY;
// R <= I A(1:3,I) > KEY.
//
{
int i;
int j;
double key[3];
int ll;
int m;
int rr;
if ( n < 1 )
{
cerr << "\n";
cerr << "R83ROW_PART_QUICK_A - Fatal error!\n";
cerr << " N < 1.\n";
exit ( 1 );
}
if ( n == 1 )
{
l = 0;
r = 2;
return;
}
key[0] = a[3*0+0];
key[1] = a[3*0+1];
key[2] = a[3*0+2];
m = 1;
//
// The elements of unknown size have indices between L+1 and R-1.
//
ll = 1;
rr = n + 1;
for ( i = 2; i <= n; i++ )
{
if ( r8vec_gt ( 3, a+3*ll, key ) )
{
rr = rr - 1;
r8vec_swap ( 3, a+3*(rr-1), a+3*ll );
}
else if ( r8vec_eq ( 3, a+3*ll, key ) )
{
m = m + 1;
r8vec_swap ( 3, a+3*(m-1), a+3*ll );
ll = ll + 1;
}
else if ( r8vec_lt ( 3, a+3*ll, key ) )
{
ll = ll + 1;
}
}
//
// Now shift small elements to the left, and KEY elements to center.
//
for ( i = 0; i < ll - m; i++ )
{
for ( j = 0; j < 3; j++ )
{
a[3*i+j] = a[3*(i+m)+j];
}
}
ll = ll - m;
for ( i = ll; i < ll+m; i++ )
{
for ( j = 0; j < 3; j++ )
{
a[3*i+j] = key[j];
}
}
l = ll;
r = rr;
return;
}
//****************************************************************************80
void r83row_print_part ( int n, double a[], int max_print, string title )
//****************************************************************************80
//
// Purpose:
//
// R83ROW_PRINT_PART prints "part" of an R83ROW.
//
// Discussion:
//
// An R83ROW is a (3,N) array of R8's.
//
// The user specifies MAX_PRINT, the maximum number of lines to print.
//
// If N, the size of the vector, is no more than MAX_PRINT, then
// the entire vector is printed, one entry per line.
//
// Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
// followed by a line of periods suggesting an omission,
// and the last entry.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vector.
//
// Input, double A[3*N], the vector to be printed.
//
// Input, int MAX_PRINT, the maximum number of lines
// to print.
//
// Input, string TITLE, a title.
//
{
int i;
if ( max_print <= 0 )
{
return;
}
if ( n <= 0 )
{
return;
}
cout << "\n";
cout << title << "\n";
cout << "\n";
if ( n <= max_print )
{
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< " " << setw(14) << a[0+i*3]
<< " " << setw(14) << a[1+i*3]
<< " " << setw(14) << a[2+i*3] << "\n";
}
}
else if ( 3 <= max_print )
{
for ( i = 0; i < max_print - 2; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*3]
<< " " << setw(14) << a[1+i*3]
<< " " << setw(14) << a[2+i*3] << "\n";
}
cout << " ........ .............. .............. ..............\n";
i = n - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*3]
<< " " << setw(14) << a[1+i*3]
<< " " << setw(14) << a[2+i*3] << "\n";
}
else
{
for ( i = 0; i < max_print - 1; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*3]
<< " " << setw(14) << a[1+i*3]
<< " " << setw(14) << a[2+i*3] << "\n";
}
i = max_print - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[0+i*3]
<< " " << setw(14) << a[1+i*3]
<< " " << setw(14) << a[2+i*3]
<< " " << "...more entries...\n";
}
return;
}
//****************************************************************************80
void r83row_sort_quick_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R83ROW_SORT_QUICK_A ascending sorts an R83ROW using quick sort.
//
// Discussion:
//
// An R83ROW is a (3,N) array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input/output, double A[3*N].
// On input, the array to be sorted.
// On output, the array has been sorted.
//
{
# define LEVEL_MAX 30
int base;
int l_segment;
int level;
int n_segment;
int rsave[LEVEL_MAX];
int r_segment;
if ( n < 1 )
{
cerr << "\n";
cerr << "R83ROW_SORT_QUICK_A - Fatal error!\n";
cerr << " N < 1.\n";
exit ( 1 );
}
if ( n == 1 )
{
return;
}
level = 1;
rsave[level-1] = n + 1;
base = 1;
n_segment = n;
while ( 0 < n_segment )
{
//
// Partition the segment.
//
r83row_part_quick_a ( n_segment, a+3*(base-1)+0, l_segment, r_segment );
//
// If the left segment has more than one element, we need to partition it.
//
if ( 1 < l_segment )
{
if ( LEVEL_MAX < level )
{
cerr << "\n";
cerr << "R83ROW_SORT_QUICK_A - Fatal error!\n";
cerr << " Exceeding recursion maximum of " << LEVEL_MAX << "\n";
exit ( 1 );
}
level = level + 1;
n_segment = l_segment;
rsave[level-1] = r_segment + base - 1;
}
//
// The left segment and the middle segment are sorted.
// Must the right segment be partitioned?
//
else if ( r_segment < n_segment )
{
n_segment = n_segment + 1 - r_segment;
base = base + r_segment - 1;
}
//
// Otherwise, we back up a level if there is an earlier one.
//
else
{
for ( ; ; )
{
if ( level <= 1 )
{
n_segment = 0;
break;
}
base = rsave[level-1];
n_segment = rsave[level-2] - rsave[level-1];
level = level - 1;
if ( 0 < n_segment )
{
break;
}
}
}
}
return;
# undef LEVEL_MAX
}
//****************************************************************************80
void r8block_delete ( int l, int m, int n, double ***a )
//****************************************************************************80
//
// Purpose:
//
// R8BLOCK_DELETE frees memory associated with an R8BLOCK.
//
// Discussion:
//
// This function releases the memory associated with an array that was
// created by a command like
// double ***a;
// a = r8block_new ( l, m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int L, M, N, the number of rows, columns, and layers in the array.
//
// Input, double ***A, the pointer to the data.
//
{
int i;
int j;
for ( i = 0; i < l; i++ )
{
for ( j = 0; j < m; j++ )
{
delete [] a[i][j];
}
}
for ( i = 0; i < l; i++ )
{
delete [] a[i];
}
delete [] a;
return;
}
//****************************************************************************80
double *r8block_expand_linear ( int l, int m, int n, double x[], int lfat,
int mfat, int nfat )
//****************************************************************************80
//
// Purpose:
//
// R8BLOCK_EXPAND_LINEAR linearly interpolates new data into a 3D block.
//
// Discussion:
//
// In this routine, the expansion is specified by giving the number
// of intermediate values to generate between each pair of original
// data rows and columns.
//
// The interpolation is not actually linear. It uses the functions
//
// 1, x, y, z, xy, xz, yz, xyz.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int L, M, N, the dimensions of the input data.
//
// Input, double X[L*M*N], the original data.
//
// Input, int LFAT, MFAT, NFAT, the number of data values to interpolate
// original data values in the first, second and third dimensions.
//
// Output, double XFAT[L2*M2*N2], the fattened data, where
// L2 = (L-1)*(LFAT+1)+1,
// M2 = (M-1)*(MFAT+1)+1,
// N2 = (N-1)*(NFAT+1)+1.
//
{
int i;
int ihi;
int ii;
int iii;
int ip1;
int j;
int jhi;
int jj;
int jjj;
int jp1;
int k;
int khi;
int kk;
int kkk;
int kp1;
int l2;
int m2;
int n2;
double r;
double s;
double t;
double x000;
double x001;
double x010;
double x011;
double x100;
double x101;
double x110;
double x111;
double *xfat;
l2 = ( l - 1 ) * ( lfat + 1 ) + 1;
m2 = ( m - 1 ) * ( mfat + 1 ) + 1;
n2 = ( n - 1 ) * ( nfat + 1 ) + 1;
xfat = new double[l2*m2*n2];
for ( i = 1; i <= l; i++ )
{
if ( i < l )
{
ihi = lfat;
}
else
{
ihi = 0;
}
for ( j = 1; j <= m; j++ )
{
if ( j < m )
{
jhi = mfat;
}
else
{
jhi = 0;
}
for ( k = 1; k <= n; k++ )
{
if ( k < n )
{
khi = nfat;
}
else
{
khi = 0;
}
if ( i < l )
{
ip1 = i + 1;
}
else
{
ip1 = i;
}
if ( j < m )
{
jp1 = j + 1;
}
else
{
jp1 = j;
}
if ( k < n )
{
kp1 = k + 1;
}
else
{
kp1 = k;
}
x000 = x[i-1+(j-1)*l+(k-1)*l*m];
x001 = x[i-1+(j-1)*l+(kp1-1)*l*m];
x100 = x[ip1-1+(j-1)*l+(k-1)*l*m];
x101 = x[ip1-1+(j-1)*l+(kp1-1)*l*m];
x010 = x[i-1+(jp1-1)*l+(k-1)*l*m];
x011 = x[i-1+(jp1-1)*l+(kp1-1)*l*m];
x110 = x[ip1-1+(jp1-1)*l+(k-1)*l*m];
x111 = x[ip1-1+(jp1-1)*l+(kp1-1)*l*m];
for ( ii = 0; ii <= ihi; ii++ )
{
r = ( double ) ( ii ) / ( double ) ( ihi + 1 );
for ( jj = 0; jj <= jhi; jj++ )
{
s = ( double ) ( jj ) / ( double ) ( jhi + 1 );
for ( kk = 0; kk <= khi; kk++ )
{
t = ( double ) ( kk ) / ( double ) ( khi + 1 );
iii = 1 + ( i - 1 ) * ( lfat + 1 ) + ii;
jjj = 1 + ( j - 1 ) * ( mfat + 1 ) + jj;
kkk = 1 + ( k - 1 ) * ( nfat + 1 ) + kk;
xfat[iii-1+(jjj-1)*l2+(kkk-1)*l2*m2] =
x000 * ( 1.0 - r ) * ( 1.0 - s ) * ( 1.0 - t )
+ x001 * ( 1.0 - r ) * ( 1.0 - s ) * ( t )
+ x010 * ( 1.0 - r ) * ( s ) * ( 1.0 - t )
+ x011 * ( 1.0 - r ) * ( s ) * ( t )
+ x100 * ( r ) * ( 1.0 - s ) * ( 1.0 - t )
+ x101 * ( r ) * ( 1.0 - s ) * ( t )
+ x110 * ( r ) * ( s ) * ( 1.0 - t )
+ x111 * ( r ) * ( s ) * ( t );
}
}
}
}
}
}
return xfat;
}
//****************************************************************************80
double ***r8block_new ( int l, int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8BLOCK_NEW allocates a new R8BLOCK.
//
// Discussion:
//
// A declaration of the form
// double ***a;
// is necesary. Then an assignment of the form:
// a = r8block_new ( l, m, n );
// allows the user to assign entries to the matrix using typical
// 3D array notation:
// a[2][3][4] = 17.0;
// y = a[1][0][3];
// and so on.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int L, M, N, the number of rows, columns and layers.
//
// Output, double R8BLOCK_NEW[L][M][N], a new block.
//
{
double ***a;
int i;
int j;
a = new double **[l];
if ( a == NULL )
{
cerr << "\n";
cerr << "R8BLOCK_NEW - Fatal error!\n";
cerr << " Unable to allocate row pointer array.\n";
exit ( 1 );
}
for ( i = 0; i < l; i++ )
{
a[i] = new double *[m];
if ( a[i] == NULL )
{
cerr << "\n";
cerr << "R8BLOCK_NEW - Fatal error!\n";
cerr << " Unable to allocate column pointer array.\n";
exit ( 1 );
}
}
for ( i = 0; i < l; i++ )
{
for ( j = 0; j < m; j++ )
{
a[i][j] = new double[n];
if ( a[i][j] == NULL )
{
cerr << "\n";
cerr << "R8BLOCK_NEW - Fatal error!\n";
cerr << " Unable to allocate layer array.\n";
exit ( 1 );
}
}
}
return a;
}
//****************************************************************************80
void r8block_print ( int l, int m, int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8BLOCK_PRINT prints an R8BLOCK block (a 3D matrix).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int L, M, N, the dimensions of the block.
//
// Input, double A[L*M*N], the matrix to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
int j;
int jhi;
int jlo;
int k;
cout << "\n";
cout << title << "\n";
for ( k = 1; k <= n; k++ )
{
cout << "\n";
cout << " K = " << k << "\n";
cout << "\n";
for ( jlo = 1; jlo <= m; jlo = jlo + 5 )
{
jhi = i4_min ( jlo + 4, m );
cout << "\n";
cout << " ";
for ( j = jlo; j <= jhi; j++ )
{
cout << setw(7) << j << " ";
}
cout << "\n";
cout << "\n";
for ( i = 1; i <= l; i++ )
{
cout << setw(5) << i << ":";
for ( j = jlo; j <= jhi; j++ )
{
cout << " " << setw(12) << a[i-1+(j-1)*l+(k-1)*l*m];
}
cout << "\n";
}
}
}
return;
}
//****************************************************************************80
double *r8block_zeros_new ( int l, int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8BLOCK_ZEROS_NEW returns a new zeroed R8BLOCK.
//
// Discussion:
//
// An R8BLOCK is a triple dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 April 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int L, M, N, the number of rows and columns.
//
// Output, double R8BLOCK_ZEROS_NEW[L*M*N], the new zeroed matrix.
//
{
double *a;
int i;
int j;
int k;
a = new double[l*m*n];
for ( k = 0; k < n; k++ )
{
for ( j = 0; j < m; j++ )
{
for ( i = 0; i < l; i++ )
{
a[i+j*l+k*l*m] = 0.0;
}
}
}
return a;
}
//****************************************************************************80
void r8cmat_delete ( int m, int n, double **a )
//****************************************************************************80
//
// Purpose:
//
// R8CMAT_DELETE frees memory associated with an R8CMAT.
//
// Discussion:
//
// This function releases the memory associated with an R8CMAT.
//
// An R8CMAT is a column-major array, storing element (I,J)
// as A[J][I], and can be created by a command like:
// double **a;
// a = r8cmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 September 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the array.
//
// Input, double **A, the pointer to the array.
//
{
int j;
for ( j = 0; j < n; j++ )
{
delete [] a[j];
}
delete [] a;
return;
}
//****************************************************************************80
double **r8cmat_new ( int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8CMAT_NEW allocates a new R8CMAT.
//
// Discussion:
//
// An R8CMAT is a column-major array, storing element (I,J)
// as A[J][I], and can be created by a command like:
// double **a;
// a = r8cmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 September 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the matrix.
//
// Output, double **R8CMAT_NEW, a new matrix.
//
{
double **a;
int j;
a = new double *[n];
if ( a == NULL )
{
cerr << "\n";
cerr << "R8CMAT_NEW - Fatal error!\n";
cerr << " Unable to allocate row pointer array.\n";
exit ( 1 );
}
for ( j = 0; j < n; j++ )
{
a[j] = new double[m];
if ( a[j] == NULL )
{
cerr << "\n";
cerr << "R8CMAT_NEW - Fatal error!\n";
cerr << " Unable to allocate row array.\n";
exit ( 1 );
}
}
return a;
}
//****************************************************************************80
void r8cmat_print ( int m, int n, double **a, string title )
//****************************************************************************80
//
// Purpose:
//
// R8CMAT_PRINT prints an R8CMAT.
//
// Discussion:
//
// An R8CMAT is a column-major array, storing element (I,J)
// as A[J][I], and can be created by a command like:
// double **a;
// a = r8cmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double **A = A[M][N], the M by N matrix.
//
// Input, string TITLE, a title.
//
{
r8cmat_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
//****************************************************************************80
void r8cmat_print_some ( int m, int n, double **a, int ilo, int jlo, int ihi,
int jhi, string title )
//****************************************************************************80
//
// Purpose:
//
// R8CMAT_PRINT_SOME prints some of an R8CMAT.
//
// Discussion:
//
// An R8CMAT is a column-major array, storing element (I,J)
// as A[J][I], and can be created by a command like:
// double **a;
// a = r8cmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 June 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows of the matrix.
// M must be positive.
//
// Input, int N, the number of columns of the matrix.
// N must be positive.
//
// Input, double **A = A[M][N], the matrix.
//
// Input, int ILO, JLO, IHI, JHI, designate the first row and
// column, and the last row and column to be printed.
//
// Input, string TITLE, a title.
//
{
# define INCX 5
int i;
int i2hi;
int i2lo;
int j;
int j2hi;
int j2lo;
cout << "\n";
cout << title << "\n";
if ( m <= 0 || n <= 0 )
{
cout << "\n";
cout << " (None)\n";
return;
}
//
// Print the columns of the matrix, in strips of 5.
//
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
if ( n < j2hi )
{
j2hi = n;
}
if ( jhi < j2hi )
{
j2hi = jhi;
}
cout << "\n";
//
// For each column J in the current range...
//
// Write the header.
//
cout << " Col: ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(7) << j - 1 << " ";
}
cout << "\n";
cout << " Row\n";
cout << "\n";
//
// Determine the range of the rows in this strip.
//
if ( 1 < ilo )
{
i2lo = ilo;
}
else
{
i2lo = 1;
}
if ( ihi < m )
{
i2hi = ihi;
}
else
{
i2hi = m;
}
for ( i = i2lo; i <= i2hi; i++ )
{
//
// Print out (up to) 5 entries in row I, that lie in the current strip.
//
cout << setw(5) << i - 1 << ": ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(12) << a[j-1][i-1] << " ";
}
cout << "\n";
}
}
return;
# undef INCX
}
//****************************************************************************80
double *r8cmat_to_r8mat_new ( int m, int n, double **a )
//****************************************************************************80
//
// Purpose:
//
// R8CMAT_TO_R8MAT_NEW copies data from an R8CMAT to an R8MAT.
//
// Discussion:
//
// An R8CMAT is a column-major array, storing element (I,J)
// as A[J][I], and can be created by a command like:
// double **a;
// a = r8cmat_new ( m, n );
//
// An R8MAT is a column-major array stored as a vector, so
// that element (I,J) of the M by N array is stored in location
// I+J*M.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 January 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double **A = double A[M][N], the data, stored as an R8CMAT.
//
// Output, double R8CMAT_TO_R8MAT_NEW[M*N], the data, stored as an R8MAT.
//
{
double *b;
int i;
int j;
b = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
b[i+j*m] = a[j][i];
}
}
return b;
}
//****************************************************************************80
double **r8cmat_zeros_new ( int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8CMAT_ZEROS_NEW allocates and zeros a new R8CMAT.
//
// Discussion:
//
// An R8CMAT is a column-major array, storing element (I,J)
// as A[J][I], and can be created by a command like:
// double **a;
// a = r8cmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 September 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the matrix.
//
// Output, double **R8CMAT_ZEROS_NEW, a new matrix.
//
{
double **a;
int i;
int j;
a = new double *[n];
if ( a == NULL )
{
cerr << "\n";
cerr << "R8CMAT_ZEROS_NEW - Fatal error!\n";
cerr << " Unable to allocate row pointer array.\n";
exit ( 1 );
}
for ( j = 0; j < n; j++ )
{
a[j] = new double[m];
if ( a[j] == NULL )
{
cerr << "\n";
cerr << "R8CMAT_ZEROS_NEW - Fatal error!\n";
cerr << " Unable to allocate row array.\n";
exit ( 1 );
}
}
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
a[j][i] = 0.0;
}
}
return a;
}
//****************************************************************************80
double r8int_to_r8int ( double rmin, double rmax, double r, double r2min,
double r2max )
//****************************************************************************80
//
// Purpose:
//
// R8INT_TO_R8INT maps one R8 interval to another.
//
// Discussion:
//
// The formula used is
//
// R2 := R2MIN + ( R2MAX - R2MIN ) * ( R - RMIN ) / ( RMAX - RMIN )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 January 2001
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double RMIN, RMAX, the first range.
//
// Input, double R, the number to be converted.
//
// Input, double R2MAX, R2MIN, the second range.
//
// Output, double R8INT_TO_R8INT, the corresponding value in
// the range [R2MIN,R2MAX].
//
{
double r2;
if ( rmax == rmin )
{
r2 = ( r2max + r2min ) / 2.0;
}
else
{
r2 = ( ( ( rmax - r ) * r2min
+ ( r - rmin ) * r2max )
/ ( rmax - rmin ) );
}
return r2;
}
//****************************************************************************80
int r8int_to_i4int ( double rmin, double rmax, double r, int imin, int imax )
//****************************************************************************80
//
// Purpose:
//
// R8INT_TO_I4INT maps an R8 interval to an integer interval.
//
// Discussion:
//
// The formula used is
//
// I := IMIN + ( IMAX - IMIN ) * ( R - RMIN ) / ( RMAX - RMIN )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 January 2001
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double RMIN, RMAX, the range.
//
// Input, double R, the number to be converted.
//
// Input, int IMAX, IMIN, the integer range.
//
// Output, int R8INT_TO_I4INT, the corresponding value in the range [IMIN,IMAX].
//
{
int i;
if ( rmax == rmin )
{
i = ( imax + imin ) / 2;
}
else
{
i = r8_nint (
( ( rmax - r ) * ( double ) ( imin )
+ ( r - rmin ) * ( double ) ( imax ) )
/ ( rmax - rmin ) );
}
return i;
}
//****************************************************************************80
void r8mat_add ( int m, int n, double alpha, double a[], double beta,
double b[], double c[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_ADD computes C = alpha * A + beta * B for R8MAT's.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 November 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double ALPHA, the multiplier for A.
//
// Input, double A[M*N], the first matrix.
//
// Input, double BETA, the multiplier for A.
//
// Input, double B[M*N], the second matrix.
//
// Output, double C[M*N], the sum of alpha*A+beta*B.
//
{
int i;
int j;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = alpha * a[i+j*m] + beta * b[i+j*m];
}
}
return;
}
//****************************************************************************80
double *r8mat_add_new ( int m, int n, double alpha, double a[], double beta,
double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_ADD_NEW computes C = alpha * A + beta * B for R8MAT's.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double ALPHA, the multiplier for A.
//
// Input, double A[M*N], the first matrix.
//
// Input, double BETA, the multiplier for A.
//
// Input, double B[M*N], the second matrix.
//
// Output, double R8MAT_ADD_NEW[M*N], the sum of alpha*A+beta*B.
//
{
double *c;
int i;
int j;
c = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = alpha * a[i+j*m] + beta * b[i+j*m];
}
}
return c;
}
//****************************************************************************80
double r8mat_amax ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_AMAX returns the maximum absolute value entry of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix.
//
// Output, double R8MAT_AMAX, the maximum absolute value entry of A.
//
{
int i;
int j;
double value;
value = fabs ( a[0+0*m] );
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = r8_max ( value, fabs ( a[i+j*m] ) );
}
}
return value;
}
//****************************************************************************80
double *r8mat_border_add ( int m, int n, double table[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_BORDER_ADD adds a "border" to an R8MAT.
//
// Discussion:
//
// We suppose the input data gives values of a quantity on nodes
// in the interior of a 2D grid, and we wish to create a new table
// with additional positions for the nodes that would be on the
// border of the 2D grid.
//
// 0 0 0 0 0 0
// * * * * 0 * * * * 0
// * * * * --> 0 * * * * 0
// * * * * 0 * * * * 0
// 0 0 0 0 0 0
//
// The illustration suggests the situation in which a 3 by 4 array
// is input, and a 5 by 6 array is to be output.
//
// The old data is shifted to its correct positions in the new array.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 January 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the spatial dimension.
//
// Input, int N, the number of points.
//
// Input, double TABLE[M*N], the table data.
//
// Output, double TABLE2[(M+2)*(N+2)], the augmented table data.
//
{
int i;
int j;
double *table2;
table2 = new double[(m+2)*(n+2)];
for ( j = 0; j < n+2; j++ )
{
for ( i = 0; i < m+2; i++ )
{
if ( i == 0 || i == m+1 || j == 0 || j == n+1 )
{
table2[i+j*(m+2)] = 0.0;
}
else
{
table2[i+j*(m+2)] = table[(i-1)+(j-1)*m];
}
}
}
return table2;
}
//****************************************************************************80
double *r8mat_border_cut ( int m, int n, double table[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_BORDER_CUT cuts the "border" of an R8MAT.
//
// Discussion:
//
// We suppose the input data gives values of a quantity on nodes
// on a 2D grid, and we wish to create a new table corresponding only
// to those nodes in the interior of the 2D grid.
//
// 0 0 0 0 0 0
// 0 * * * * 0 * * * *
// 0 * * * * 0 -> * * * *
// 0 * * * * 0 * * * *
// 0 0 0 0 0 0
//
// The illustration suggests the situation in which a 5 by 6 array
// is input, and a 3 by 4 array is to be output.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 January 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the spatial dimension.
//
// Input, int N, the number of points.
//
// Input, double TABLE[M*N], the table data.
//
// Output, double TABLE2[(M-2)*(N-2)], the "interior" table data.
//
{
int i;
int j;
double *table2;
if ( m <= 2 || n <= 2 )
{
return NULL;
}
table2 = new double[(m-2)*(n-2)];
for ( j = 0; j < n-2; j++ )
{
for ( i = 0; i < m-2; i++ )
{
table2[i+j*(m-2)] = table[(i+1)+(j+1)*m];
}
}
return table2;
}
//****************************************************************************80
double *r8mat_cholesky_factor ( int n, double a[], int &flag )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_CHOLESKY_FACTOR computes the Cholesky factor of a symmetric R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The matrix must be symmetric and positive semidefinite.
//
// For a positive semidefinite symmetric matrix A, the Cholesky factorization
// is a lower triangular matrix L such that:
//
// A = L * L'
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 November 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix A.
//
// Input, double A[N*N], the N by N matrix.
//
// Output, int &FLAG, an error flag.
// 0, no error occurred.
// 1, the matrix is not positive definite.
// 2, the matrix is not nonnegative definite.
//
// Output, double R8MAT_CHOLESKY_FACTOR[N*N], the N by N lower triangular
// Cholesky factor.
//
{
double *c;
int i;
int j;
int k;
double sum2;
double tol;
flag = 0;
tol = sqrt ( r8_epsilon ( ) );
c = r8mat_copy_new ( n, n, a );
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < j; i++ )
{
c[i+j*n] = 0.0;
}
for ( i = j; i < n; i++ )
{
sum2 = c[j+i*n];
for ( k = 0; k < j; k++ )
{
sum2 = sum2 - c[j+k*n] * c[i+k*n];
}
if ( i == j )
{
if ( 0.0 < sum2 )
{
c[i+j*n] = sqrt ( sum2 );
}
else if ( sum2 < - tol )
{
flag = 2;
cerr << "\n";
cerr << "R8MAT_CHOLESKY_FACTOR - Fatal error!\n";
cerr << " Matrix is not nonnegative definite.\n";
cerr << " Diagonal I = " << i << "\n";
cerr << " SUM2 = " << sum2 << "\n";
exit ( 1 );
}
else
{
flag = 1;
c[i+j*n] = 0.0;
}
}
else
{
if ( c[j+j*n] != 0.0 )
{
c[i+j*n] = sum2 / c[j+j*n];
}
else
{
c[i+j*n] = 0.0;
}
}
}
}
return c;
}
//****************************************************************************80
double *r8mat_cholesky_factor_upper ( int n, double a[], int &flag )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_CHOLESKY_FACTOR_UPPER: upper Cholesky factor of a symmetric R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The matrix must be symmetric and positive semidefinite.
//
// For a positive semidefinite symmetric matrix A, the Cholesky factorization
// is an upper triangular matrix R such that:
//
// A = R' * R
//
// Note that the usual Cholesky factor is a LOWER triangular matrix L
// such that
//
// A = L * L'
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 August 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix A.
//
// Input, double A[N*N], the N by N matrix.
//
// Output, int &FLAG, an error flag.
// 0, no error occurred.
// 1, the matrix is not positive definite. A NULL factor is returned.
//
// Output, double R8MAT_CHOLESKY_FACTOR[N*N], the N by N upper triangular
// Cholesky factor.
//
{
double *c;
int i;
int j;
int k;
double sum2;
flag = 0;
c = r8mat_copy_new ( n, n, a );
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < j; i++ )
{
c[j+i*n] = 0.0;
}
for ( i = j; i < n; i++ )
{
sum2 = c[i+j*n];
for ( k = 0; k < j; k++ )
{
sum2 = sum2 - c[k+j*n] * c[k+i*n];
}
if ( i == j )
{
if ( sum2 <= 0.0 )
{
flag = 1;
return NULL;
}
c[j+i*n] = sqrt ( sum2 );
}
else
{
if ( c[j+j*n] != 0.0 )
{
c[j+i*n] = sum2 / c[j+j*n];
}
else
{
c[j+i*n] = 0.0;
}
}
}
}
return c;
}
//****************************************************************************80
void r8mat_cholesky_inverse ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_CHOLESKY_INVERSE computes the inverse of a symmetric matrix.
//
// Discussion:
//
// The matrix must be symmetric and positive semidefinite.
//
// The upper triangular Cholesky factorization R is computed, so that:
//
// A = R' * R
//
// Then the inverse B is computed by
//
// B = inv ( A ) = inv ( R ) * inv ( R' )
//
// An R8MAT is an MxN array of R8's, stored by (I,J) -> [I+J*M].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 October 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of
// the matrix A.
//
// Input/output, double A[N*N]. On input, the matrix.
// On output, the inverse of the matrix.
//
{
int i;
int j;
int k;
double s;
double t;
for ( j = 0; j < n; j++ )
{
s = 0.0;
for ( k = 0; k < j; k++ )
{
t = a[k+j*n];
for ( i = 0; i < k; i++ )
{
t = t - a[i+k*n] * a[i+j*n];
}
t = t / a[k+k*n];
a[k+j*n] = t;
s = s + t * t;
}
s = a[j+j*n] - s;
if ( s <= 0.0 )
{
cerr << "\n";
cerr << "R8MAT_CHOLESKY_INVERSE - Fatal error!\n";
cerr << " The matrix is singular.\n";
exit ( 1 );
}
a[j+j*n] = sqrt ( s );
for ( i = j + 1; i < n; i++ )
{
a[i+j*n] = 0.0;
}
}
//
// Compute inverse(R).
//
for ( k = 0; k < n; k++ )
{
a[k+k*n] = 1.0 / a[k+k*n];
for ( i = 0; i < k; i++ )
{
a[i+k*n] = - a[i+k*n] * a[k+k*n];
}
for ( j = k + 1; j < n; j++ )
{
t = a[k+j*n];
a[k+j*n] = 0.0;
for ( i = 0; i <= k; i++ )
{
a[i+j*n] = a[i+j*n] + t * a[i+k*n];
}
}
}
//
// Form inverse(R) * (inverse(R))'.
//
for ( j = 0; j < n; j++ )
{
for ( k = 0; k < j; k++ )
{
t = a[k+j*n];
for ( i = 0; i <= k; i++ )
{
a[i+k*n] = a[i+k*n] + t * a[i+j*n];
}
}
t = a[j+j*n];
for ( i = 0; i <= j; i++ )
{
a[i+j*n] = a[i+j*n] * t;
}
}
//
// Use reflection.
//
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < i; j++ )
{
a[i+j*n] = a[j+i*n];
}
}
return;
}
//****************************************************************************80
double *r8mat_cholesky_solve ( int n, double l[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_CHOLESKY_SOLVE solves a Cholesky factored linear system A * x = b.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix A.
//
// Input, double L[N*N], the N by N Cholesky factor of the
// system matrix A.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double R8MAT_CHOLESKY_SOLVE[N], the solution of the linear system.
//
{
double *x;
double *y;
//
// Solve L * y = b.
//
y = r8mat_l_solve ( n, l, b );
//
// Solve L' * x = y.
//
x = r8mat_lt_solve ( n, l, y );
delete [] y;
return x;
}
//****************************************************************************80
double *r8mat_cholesky_solve_upper ( int n, double r[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_CHOLESKY_SOLVE_UPPER solves Cholesky factored linear system A * x = b.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 October 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix A.
//
// Input, double R[N*N], the N by N Cholesky factor of the
// system matrix A.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double R8MAT_CHOLESKY_SOLVE_UPPER[N], the solution of the linear system.
//
{
double *x;
double *y;
//
// Solve U' * y = b.
//
y = r8mat_ut_solve ( n, r, b );
//
// Solve U * x = y.
//
x = r8mat_u_solve ( n, r, y );
delete [] y;
return x;
}
//****************************************************************************80
void r8mat_copy ( int m, int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_COPY copies one R8MAT to another.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A1[M*N], the matrix to be copied.
//
// Output, double A2[M*N], the copy of A1.
//
{
int i;
int j;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
a2[i+j*m] = a1[i+j*m];
}
}
return;
}
//****************************************************************************80
double *r8mat_copy_new ( int m, int n, double a1[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_COPY_NEW copies one R8MAT to a "new" R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8's, which
// may be stored as a vector in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A1[M*N], the matrix to be copied.
//
// Output, double R8MAT_COPY_NEW[M*N], the copy of A1.
//
{
double *a2;
int i;
int j;
a2 = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
a2[i+j*m] = a1[i+j*m];
}
}
return a2;
}
//****************************************************************************80
double *r8mat_covariance ( int m, int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_COVARIANCE computes the sample covariance of a set of vector data.
//
// Discussion:
//
// An R8MAT is an MxN array of R8's, stored by (I,J) -> [I+J*M].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 June 2013
//
// Author:
//
// John Burkardt.
//
// Parameters:
//
// Input, int M, the size of a single data vectors.
//
// Input, int N, the number of data vectors.
// N should be greater than 1.
//
// Input, double X[M*N], an array of N data vectors, each
// of length M.
//
// Output, double C[M*M], the covariance matrix for the data.
//
{
double *c;
int i;
int j;
int k;
double *x_mean;
c = new double[m*m];
for ( j = 0; j < m; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = 0.0;
}
}
//
// Special case of N = 1.
//
if ( n == 1 )
{
for ( i = 0; i < m; i++ )
{
c[i+i*m] = 1.0;
}
return c;
}
//
// Determine the sample means.
//
x_mean = new double[m];
for ( i = 0; i < m; i++ )
{
x_mean[i] = 0.0;
for ( j = 0; j < n; j++ )
{
x_mean[i] = x_mean[i] + x[i+j*m];
}
x_mean[i] = x_mean[i] / ( double ) ( n );
}
//
// Determine the sample covariance.
//
for ( j = 0; j < m; j++ )
{
for ( i = 0; i < m; i++ )
{
for ( k = 0; k < n; k++ )
{
c[i+j*m] = c[i+j*m]
+ ( x[i+k*m] - x_mean[i] ) * ( x[j+k*m] - x_mean[j] );
}
}
}
for ( j = 0; j < m; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = c[i+j*m] / ( double ) ( n - 1 );
}
}
delete [] x_mean;
return c;
}
//****************************************************************************80
double r8mat_det ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DET computes the determinant of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2005
//
// Author:
//
// Original FORTRAN77 version by Helmut Spaeth
// C++ version by John Burkardt
//
// Reference:
//
// Helmut Spaeth,
// Cluster Analysis Algorithms
// for Data Reduction and Classification of Objects,
// Ellis Horwood, 1980, page 125-127.
//
// Parameters:
//
// Input, int N, the order of the matrix.
//
// Input, double A[N*N], the matrix whose determinant is desired.
//
// Output, double R8MAT_DET, the determinant of the matrix.
//
{
double *b;
double det;
int i;
int j;
int k;
int kk;
int m;
double temp;
b = new double[n*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
b[i+j*n] = a[i+j*n];
}
}
det = 1.0;
for ( k = 1; k <= n; k++ )
{
m = k;
for ( kk = k+1; kk <= n; kk++ )
{
if ( fabs ( b[m-1+(k-1)*n] ) < fabs ( b[kk-1+(k-1)*n] ) )
{
m = kk;
}
}
if ( m != k )
{
det = -det;
temp = b[m-1+(k-1)*n];
b[m-1+(k-1)*n] = b[k-1+(k-1)*n];
b[k-1+(k-1)*n] = temp;
}
det = det * b[k-1+(k-1)*n];
if ( b[k-1+(k-1)*n] != 0.0 )
{
for ( i = k+1; i <= n; i++ )
{
b[i-1+(k-1)*n] = -b[i-1+(k-1)*n] / b[k-1+(k-1)*n];
}
for ( j = k+1; j <= n; j++ )
{
if ( m != k )
{
temp = b[m-1+(j-1)*n];
b[m-1+(j-1)*n] = b[k-1+(j-1)*n];
b[k-1+(j-1)*n] = temp;
}
for ( i = k+1; i <= n; i++ )
{
b[i-1+(j-1)*n] = b[i-1+(j-1)*n] + b[i-1+(k-1)*n] * b[k-1+(j-1)*n];
}
}
}
}
delete [] b;
return det;
}
//****************************************************************************80
double r8mat_det_2d ( double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DET_2D computes the determinant of a 2 by 2 R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Discussion:
//
// The determinant of a 2 by 2 matrix is
//
// a11 * a22 - a12 * a21.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[2*2], the matrix whose determinant is desired.
//
// Output, double R8MAT_DET_2D, the determinant of the matrix.
//
{
double det;
det = a[0+0*2] * a[1+1*2] - a[0+1*2] * a[1+0*2];
return det;
}
//****************************************************************************80
double r8mat_det_3d ( double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DET_3D computes the determinant of a 3 by 3 R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The determinant of a 3 by 3 matrix is
//
// a11 * a22 * a33 - a11 * a23 * a32
// + a12 * a23 * a31 - a12 * a21 * a33
// + a13 * a21 * a32 - a13 * a22 * a31
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[3*3], the matrix whose determinant is desired.
//
// Output, double R8MAT_DET_3D, the determinant of the matrix.
//
{
double det;
det =
a[0+0*3] * ( a[1+1*3] * a[2+2*3] - a[1+2*3] * a[2+1*3] )
+ a[0+1*3] * ( a[1+2*3] * a[2+0*3] - a[1+0*3] * a[2+2*3] )
+ a[0+2*3] * ( a[1+0*3] * a[2+1*3] - a[1+1*3] * a[2+0*3] );
return det;
}
//****************************************************************************80
double r8mat_det_4d ( double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DET_4D computes the determinant of a 4 by 4 R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[4*4], the matrix whose determinant is desired.
//
// Output, double R8MAT_DET_4D, the determinant of the matrix.
//
{
double det;
det =
a[0+0*4] * (
a[1+1*4] * ( a[2+2*4] * a[3+3*4] - a[2+3*4] * a[3+2*4] )
- a[1+2*4] * ( a[2+1*4] * a[3+3*4] - a[2+3*4] * a[3+1*4] )
+ a[1+3*4] * ( a[2+1*4] * a[3+2*4] - a[2+2*4] * a[3+1*4] ) )
- a[0+1*4] * (
a[1+0*4] * ( a[2+2*4] * a[3+3*4] - a[2+3*4] * a[3+2*4] )
- a[1+2*4] * ( a[2+0*4] * a[3+3*4] - a[2+3*4] * a[3+0*4] )
+ a[1+3*4] * ( a[2+0*4] * a[3+2*4] - a[2+2*4] * a[3+0*4] ) )
+ a[0+2*4] * (
a[1+0*4] * ( a[2+1*4] * a[3+3*4] - a[2+3*4] * a[3+1*4] )
- a[1+1*4] * ( a[2+0*4] * a[3+3*4] - a[2+3*4] * a[3+0*4] )
+ a[1+3*4] * ( a[2+0*4] * a[3+1*4] - a[2+1*4] * a[3+0*4] ) )
- a[0+3*4] * (
a[1+0*4] * ( a[2+1*4] * a[3+2*4] - a[2+2*4] * a[3+1*4] )
- a[1+1*4] * ( a[2+0*4] * a[3+2*4] - a[2+2*4] * a[3+0*4] )
+ a[1+2*4] * ( a[2+0*4] * a[3+1*4] - a[2+1*4] * a[3+0*4] ) );
return det;
}
//****************************************************************************80
double r8mat_det_5d ( double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DET_5D computes the determinant of a 5 by 5 R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[5*5], the matrix whose determinant is desired.
//
// Output, double R8MAT_DET_5D, the determinant of the matrix.
//
{
double b[4*4];
double det;
int i;
int inc;
int j;
int k;
double sign;
//
// Expand the determinant into the sum of the determinants of the
// five 4 by 4 matrices created by dropping row 1, and column k.
//
det = 0.0;
sign = 1.0;
for ( k = 0; k < 5; k++ )
{
for ( i = 0; i < 4; i++ )
{
for ( j = 0; j < 4; j++ )
{
if ( j < k )
{
inc = 0;
}
else
{
inc = 1;
}
b[i+j*4] = a[i+1+(j+inc)*5];
}
}
det = det + sign * a[0+k*5] * r8mat_det_4d ( b );
sign = - sign;
}
return det;
}
//****************************************************************************80
void r8mat_diag_add_scalar ( int n, double a[], double s )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIAG_ADD_SCALAR adds a scalar to the diagonal of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix.
//
// Input/output, double A[N*N], the N by N matrix to be modified.
//
// Input, double S, the value to be added to the diagonal
// of the matrix.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i+i*n] = a[i+i*n] + s;
}
return;
}
//****************************************************************************80
void r8mat_diag_add_vector ( int n, double a[], double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIAG_ADD_VECTOR adds a vector to the diagonal of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix.
//
// Input/output, double A[N*N], the N by N matrix.
//
// Input, double V[N], the vector to be added to the diagonal of A.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i+i*n] = a[i+i*n] + v[i];
}
return;
}
//****************************************************************************80
void r8mat_diag_get_vector ( int n, double a[], double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIAG_GET_VECTOR gets the value of the diagonal of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 July 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix.
//
// Input, double A[N*N], the N by N matrix.
//
// Output, double V[N], the diagonal entries
// of the matrix.
//
{
int i;
for ( i = 0; i < n; i++ )
{
v[i] = a[i+i*n];
}
return;
}
//****************************************************************************80
double *r8mat_diag_get_vector_new ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIAG_GET_VECTOR_NEW gets the value of the diagonal of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 July 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix.
//
// Input, double A[N*N], the N by N matrix.
//
// Output, double R8MAT_DIAG_GET_VECTOR_NEW[N], the diagonal entries
// of the matrix.
//
{
int i;
double *v;
v = new double[n];
for ( i = 0; i < n; i++ )
{
v[i] = a[i+i*n];
}
return v;
}
//****************************************************************************80
void r8mat_diag_set_scalar ( int n, double a[], double s )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIAG_SET_SCALAR sets the diagonal of an R8MAT to a scalar value.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix.
//
// Input/output, double A[N*N], the N by N matrix to be modified.
//
// Input, double S, the value to be assigned to the diagonal
// of the matrix.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i+i*n] = s;
}
return;
}
//****************************************************************************80
void r8mat_diag_set_vector ( int n, double a[], double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIAG_SET_VECTOR sets the diagonal of an R8MAT to a vector.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix.
//
// Input/output, double A[N*N], the N by N matrix.
//
// Input, double V[N], the vector to be assigned to the
// diagonal of A.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i+i*n] = v[i];
}
return;
}
//****************************************************************************80
double *r8mat_diagonal_new ( int n, double diag[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIAGONAL_NEW returns a diagonal matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 31 July 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input, double DIAG[N], the diagonal entries.
//
// Output, double R8MAT_DIAGONAL_NEW[N*N], the N by N identity matrix.
//
{
double *a;
int i;
int j;
a = new double[n*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
if ( i == j )
{
a[i+j*n] = diag[i];
}
else
{
a[i+j*n] = 0.0;
}
}
}
return a;
}
//****************************************************************************80
double r8mat_diff_frobenius ( int m, int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DIFF_FROBENIUS returns the Frobenius norm of the difference of R8MAT's.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of double precision values, which
// may be stored as a vector in column-major order.
//
// The Frobenius norm is defined as
//
// R8MAT_NORM_FRO = sqrt (
// sum ( 1 <= I <= M ) sum ( 1 <= j <= N ) A(I,J)^2 )
//
// The matrix Frobenius norm is not derived from a vector norm, but
// is compatible with the vector L2 norm, so that:
//
// r8vec_norm_l2 ( A * x ) <= r8mat_norm_fro ( A ) * r8vec_norm_l2 ( x ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 September 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], double B[M*N], the matrices for which we
// want the Frobenius norm of the difference.
//
// Output, double R8MAT_DIFF_FROBENIUS, the Frobenius norm of ( A - B ).
//
{
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + pow ( a[i+j*m] - b[i+j*m], 2 );
}
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
double *r8mat_expand_linear ( int m, int n, double x[], int mfat, int nfat )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_EXPAND_LINEAR linearly interpolates new data into an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// In this routine, the expansion is specified by giving the number
// of intermediate values to generate between each pair of original
// data rows and columns.
//
// The interpolation is not actually linear. It uses the functions
//
// 1, x, y, and xy.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of input data.
//
// Input, double X[M*N], the original data.
//
// Input, int MFAT, NFAT, the number of data values to interpolate
// between each row, and each column, of original data values.
//
// Output, double XFAT[M2*N2], the fattened data, where
// M2 = (M-1)*(MFAT+1)+1,
// N2 = (N-1)*(NFAT+1)+1.
//
{
int i;
int ihi;
int ii;
int iii;
int ip1;
int j;
int jhi;
int jj;
int jjj;
int jp1;
int m2;
int n2;
double s;
double t;
double x00;
double x01;
double x10;
double x11;
double *xfat;
m2 = ( m - 1 ) * ( mfat + 1 ) + 1;
n2 = ( n - 1 ) * ( nfat + 1 ) + 1;
xfat = new double[m2*n2];
for ( i = 1; i <= m; i++ )
{
if ( i < m )
{
ihi = mfat;
}
else
{
ihi = 0;
}
for ( j = 1; j <= n; j++ )
{
if ( j < n )
{
jhi = nfat;
}
else
{
jhi = 0;
}
if ( i < m )
{
ip1 = i + 1;
}
else
{
ip1 = i;
}
if ( j < n )
{
jp1 = j + 1;
}
else
{
jp1 = j;
}
x00 = x[i-1+(j-1)*m];
x10 = x[ip1-1+(j-1)*m];
x01 = x[i-1+(jp1-1)*m];
x11 = x[ip1-1+(jp1-1)*m];
for ( ii = 0; ii <= ihi; ii++ )
{
s = ( double ) ( ii ) / ( double ) ( ihi + 1 );
for ( jj = 0; jj <= jhi; jj++ )
{
t = ( double ) ( jj ) / ( double ) ( jhi + 1 );
iii = 1 + ( i - 1 ) * ( mfat + 1 ) + ii;
jjj = 1 + ( j - 1 ) * ( nfat + 1 ) + jj;
xfat[iii-1+(jjj-1)*m2] =
x00
+ s * ( x10 - x00 )
+ t * ( x01 - x00 )
+ s * t * ( x11 - x10 - x01 + x00 );
}
}
}
}
return xfat;
}
//****************************************************************************80
double *r8mat_expand_linear2 ( int m, int n, double a[], int m2, int n2 )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_EXPAND_LINEAR2 expands an R8MAT by linear interpolation.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// In this version of the routine, the expansion is indicated
// by specifying the dimensions of the expanded array.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in A.
//
// Input, double A(M,N), a "small" M by N array.
//
// Input, int M2, N2, the number of rows and columns in A2.
//
// Output, double R8MAT_EXPAND_LINEAR2[M2*N2], the expanded array,
// which contains an interpolated version of the data in A.
//
{
double *a2;
int i;
int i1;
int i2;
int j;
int j1;
int j2;
double r;
double r1;
double r2;
double s;
double s1;
double s2;
a2 = new double[m2*n2];
for ( i = 1; i <= m2; i++ )
{
if ( m2 == 1 )
{
r = 0.5;
}
else
{
r = ( double ) ( i - 1 ) / ( double ) ( m2 - 1 );
}
i1 = 1 + ( int ) ( r * ( double ) ( m - 1 ) );
i2 = i1 + 1;
if ( m < i2 )
{
i1 = m - 1;
i2 = m;
}
r1 = ( double ) ( i1 - 1 ) / ( double ) ( m - 1 );
r2 = ( double ) ( i2 - 1 ) / ( double ) ( m - 1 );
for ( j = 1; j <= n2; j++ )
{
if ( n2 == 1 )
{
s = 0.5;
}
else
{
s = ( double ) ( j - 1 ) / ( double ) ( n2 - 1 );
}
j1 = 1 + ( int ) ( s * ( double ) ( n - 1 ) );
j2 = j1 + 1;
if ( n < j2 )
{
j1 = n - 1;
j2 = n;
}
s1 = ( double ) ( j1 - 1 ) / ( double ) ( n - 1 );
s2 = ( double ) ( j2 - 1 ) / ( double ) ( n - 1 );
a2[i-1+(j-1)*m2] =
( ( r2 - r ) * ( s2 - s ) * a[i1-1+(j1-1)*m]
+ ( r - r1 ) * ( s2 - s ) * a[i2-1+(j1-1)*m]
+ ( r2 - r ) * ( s - s1 ) * a[i1-1+(j2-1)*m]
+ ( r - r1 ) * ( s - s1 ) * a[i2-1+(j2-1)*m] )
/ ( ( r2 - r1 ) * ( s2 - s1 ) );
}
}
return a2;
}
//****************************************************************************80
double *r8mat_flip_cols_new ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_FLIP_COLS_NEW makes a new copy of an R8MAT with reversed column order.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 November 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], the matrix to be copied.
//
// Output, double R8MAT_FLIP_COLS_NEW[M*N], the reversed-column-order copy.
//
{
double *b;
int i;
int j;
b = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
b[i+(n-1-j)*m] = a[i+j*m];
}
}
return b;
}
//****************************************************************************80
double *r8mat_flip_rows_new ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_FLIP_ROWS_NEW makes a new copy of an R8MAT with reversed row order.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 November 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], the matrix to be copied.
//
// Output, double R8MAT_FLIP_ROWS_NEW[M*N], the reversed-rows-order copy.
//
{
double *b;
int i;
int j;
b = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
b[(m-1-i)+j*m] = a[i+j*m];
}
}
return b;
}
//****************************************************************************80
void r8mat_fs ( int n, double a[], double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_FS factors and solves a system with one right hand side.
//
// Discussion:
//
// This routine differs from R8MAT_FSS in two ways:
// * only one right hand side is allowed;
// * the input matrix A is not modified.
//
// This routine uses partial pivoting, but no pivot vector is required.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 January 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, double A[N*N], the coefficient matrix of the linear system.
//
// Input/output, double X[N], on input, the right hand side of the
// linear system. On output, the solution of the linear system.
//
{
double *a2;
int i;
int ipiv;
int j;
int jcol;
double piv;
double t;
a2 = new double[n*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
a2[i+j*n] = a[i+j*n];
}
}
for ( jcol = 1; jcol <= n; jcol++ )
{
//
// Find the maximum element in column I.
//
piv = fabs ( a2[jcol-1+(jcol-1)*n] );
ipiv = jcol;
for ( i = jcol+1; i <= n; i++ )
{
if ( piv < fabs ( a2[i-1+(jcol-1)*n] ) )
{
piv = fabs ( a2[i-1+(jcol-1)*n] );
ipiv = i;
}
}
if ( piv == 0.0 )
{
cerr << "\n";
cerr << "R8MAT_FS - Fatal error!\n";
cerr << " Zero pivot on step " << jcol << "\n";
exit ( 1 );
}
//
// Switch rows JCOL and IPIV, and X.
//
if ( jcol != ipiv )
{
for ( j = 1; j <= n; j++ )
{
t = a2[jcol-1+(j-1)*n];
a2[jcol-1+(j-1)*n] = a2[ipiv-1+(j-1)*n];
a2[ipiv-1+(j-1)*n] = t;
}
t = x[jcol-1];
x[jcol-1] = x[ipiv-1];
x[ipiv-1] = t;
}
//
// Scale the pivot row.
//
t = a2[jcol-1+(jcol-1)*n];
a2[jcol-1+(jcol-1)*n] = 1.0;
for ( j = jcol+1; j <= n; j++ )
{
a2[jcol-1+(j-1)*n] = a2[jcol-1+(j-1)*n] / t;
}
x[jcol-1] = x[jcol-1] / t;
//
// Use the pivot row to eliminate lower entries in that column.
//
for ( i = jcol+1; i <= n; i++ )
{
if ( a2[i-1+(jcol-1)*n] != 0.0 )
{
t = - a2[i-1+(jcol-1)*n];
a2[i-1+(jcol-1)*n] = 0.0;
for ( j = jcol+1; j <= n; j++ )
{
a2[i-1+(j-1)*n] = a2[i-1+(j-1)*n] + t * a2[jcol-1+(j-1)*n];
}
x[i-1] = x[i-1] + t * x[jcol-1];
}
}
}
//
// Back solve.
//
for ( jcol = n; 2 <= jcol; jcol-- )
{
for ( i = 1; i < jcol; i++ )
{
x[i-1] = x[i-1] - a2[i-1+(jcol-1)*n] * x[jcol-1];
}
}
delete [] a2;
return;
}
//****************************************************************************80
double *r8mat_fs_new ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_FS_NEW factors and solves a system with one right hand side.
//
// Discussion:
//
// This routine differs from R8MAT_FSS_NEW in two ways:
// * only one right hand side is allowed;
// * the input matrix A is not modified.
//
// This routine uses partial pivoting, but no pivot vector is required.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 January 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, double A[N*N], the coefficient matrix of the linear system.
// On output, A is in unit upper triangular form, and
// represents the U factor of an LU factorization of the
// original coefficient matrix.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double X[N], the solution of the linear system.
//
{
double *a2;
int i;
int ipiv;
int j;
int jcol;
double piv;
double t;
double *x;
a2 = new double[n*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
a2[i+j*n] = a[i+j*n];
}
}
x = new double[n];
for ( i = 0; i < n; i++ )
{
x[i] = b[i];
}
for ( jcol = 1; jcol <= n; jcol++ )
{
//
// Find the maximum element in column I.
//
piv = fabs ( a2[jcol-1+(jcol-1)*n] );
ipiv = jcol;
for ( i = jcol+1; i <= n; i++ )
{
if ( piv < fabs ( a2[i-1+(jcol-1)*n] ) )
{
piv = fabs ( a2[i-1+(jcol-1)*n] );
ipiv = i;
}
}
if ( piv == 0.0 )
{
cerr << "\n";
cerr << "R8MAT_FS_NEW - Fatal error!\n";
cerr << " Zero pivot on step " << jcol << "\n";
exit ( 1 );
}
//
// Switch rows JCOL and IPIV, and X.
//
if ( jcol != ipiv )
{
for ( j = 1; j <= n; j++ )
{
t = a2[jcol-1+(j-1)*n];
a2[jcol-1+(j-1)*n] = a2[ipiv-1+(j-1)*n];
a2[ipiv-1+(j-1)*n] = t;
}
t = x[jcol-1];
x[jcol-1] = x[ipiv-1];
x[ipiv-1] = t;
}
//
// Scale the pivot row.
//
t = a2[jcol-1+(jcol-1)*n];
a2[jcol-1+(jcol-1)*n] = 1.0;
for ( j = jcol+1; j <= n; j++ )
{
a2[jcol-1+(j-1)*n] = a2[jcol-1+(j-1)*n] / t;
}
x[jcol-1] = x[jcol-1] / t;
//
// Use the pivot row to eliminate lower entries in that column.
//
for ( i = jcol+1; i <= n; i++ )
{
if ( a2[i-1+(jcol-1)*n] != 0.0 )
{
t = - a2[i-1+(jcol-1)*n];
a2[i-1+(jcol-1)*n] = 0.0;
for ( j = jcol+1; j <= n; j++ )
{
a2[i-1+(j-1)*n] = a2[i-1+(j-1)*n] + t * a2[jcol-1+(j-1)*n];
}
x[i-1] = x[i-1] + t * x[jcol-1];
}
}
}
//
// Back solve.
//
for ( jcol = n; 2 <= jcol; jcol-- )
{
for ( i = 1; i < jcol; i++ )
{
x[i-1] = x[i-1] - a2[i-1+(jcol-1)*n] * x[jcol-1];
}
}
delete [] a2;
return x;
}
//****************************************************************************80
void r8mat_fss ( int n, double a[], int nb, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_FSS factors and solves a system with multiple right hand sides.
//
// Discussion:
//
// This routine uses partial pivoting, but no pivot vector is required.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input/output, double A[N*N].
// On input, A is the coefficient matrix of the linear system.
// On output, A is in unit upper triangular form, and
// represents the U factor of an LU factorization of the
// original coefficient matrix.
//
// Input, int NB, the number of right hand sides.
//
// Input/output, double X[N*NB], on input, the right hand sides of the
// linear systems. On output, the solutions of the linear systems.
//
{
int i;
int ipiv;
int j;
int jcol;
double piv;
double t;
for ( jcol = 1; jcol <= n; jcol++ )
{
//
// Find the maximum element in column I.
//
piv = fabs ( a[jcol-1+(jcol-1)*n] );
ipiv = jcol;
for ( i = jcol+1; i <= n; i++ )
{
if ( piv < fabs ( a[i-1+(jcol-1)*n] ) )
{
piv = fabs ( a[i-1+(jcol-1)*n] );
ipiv = i;
}
}
if ( piv == 0.0 )
{
cerr << "\n";
cerr << "R8MAT_FSS - Fatal error!\n";
cerr << " Zero pivot on step " << jcol << "\n";
exit ( 1 );
}
//
// Switch rows JCOL and IPIV, and X.
//
if ( jcol != ipiv )
{
for ( j = 1; j <= n; j++ )
{
t = a[jcol-1+(j-1)*n];
a[jcol-1+(j-1)*n] = a[ipiv-1+(j-1)*n];
a[ipiv-1+(j-1)*n] = t;
}
for ( j = 0; j < nb; j++ )
{
t = x[jcol-1+j*n];
x[jcol-1+j*n] = x[ipiv-1+j*n];
x[ipiv-1+j*n] = t;
}
}
//
// Scale the pivot row.
//
t = a[jcol-1+(jcol-1)*n];
a[jcol-1+(jcol-1)*n] = 1.0;
for ( j = jcol+1; j <= n; j++ )
{
a[jcol-1+(j-1)*n] = a[jcol-1+(j-1)*n] / t;
}
for ( j = 0; j < nb; j++ )
{
x[jcol-1+j*n] = x[jcol-1+j*n] / t;
}
//
// Use the pivot row to eliminate lower entries in that column.
//
for ( i = jcol+1; i <= n; i++ )
{
if ( a[i-1+(jcol-1)*n] != 0.0 )
{
t = - a[i-1+(jcol-1)*n];
a[i-1+(jcol-1)*n] = 0.0;
for ( j = jcol+1; j <= n; j++ )
{
a[i-1+(j-1)*n] = a[i-1+(j-1)*n] + t * a[jcol-1+(j-1)*n];
}
for ( j = 0; j < nb; j++ )
{
x[i-1+j*n] = x[i-1+j*n] + t * x[jcol-1+j*n];
}
}
}
}
//
// Back solve.
//
for ( jcol = n; 2 <= jcol; jcol-- )
{
for ( i = 1; i < jcol; i++ )
{
for ( j = 0; j < nb; j++ )
{
x[i-1+j*n] = x[i-1+j*n] - a[i-1+(jcol-1)*n] * x[jcol-1+j*n];
}
}
}
return;
}
//****************************************************************************80
double *r8mat_fss_new ( int n, double a[], int nb, double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_FSS_NEW factors and solves a system with multiple right hand sides.
//
// Discussion:
//
// This routine uses partial pivoting, but no pivot vector is required.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input/output, double A[N*N].
// On input, A is the coefficient matrix of the linear system.
// On output, A is in unit upper triangular form, and
// represents the U factor of an LU factorization of the
// original coefficient matrix.
//
// Input, int NB, the number of right hand sides.
//
// Input, double B[N*NB], the right hand sides of the linear systems.
//
// Output, double R8MAT_FSS_NEW[N*NB], the solutions of the linear systems.
//
{
int i;
int ipiv;
int j;
int jcol;
double piv;
double t;
double *x;
x = new double[n*nb];
for ( j = 0; j < nb; j++ )
{
for ( i = 0; i < n; i++ )
{
x[i+j*n] = b[i+j*n];
}
}
for ( jcol = 1; jcol <= n; jcol++ )
{
//
// Find the maximum element in column I.
//
piv = fabs ( a[jcol-1+(jcol-1)*n] );
ipiv = jcol;
for ( i = jcol + 1; i <= n; i++ )
{
if ( piv < fabs ( a[i-1+(jcol-1)*n] ) )
{
piv = fabs ( a[i-1+(jcol-1)*n] );
ipiv = i;
}
}
if ( piv == 0.0 )
{
cerr << "\n";
cerr << "R8MAT_FSS_NEW - Fatal error!\n";
cerr << " Zero pivot on step " << jcol << "\n";
exit ( 1 );
}
//
// Switch rows JCOL and IPIV, and X.
//
if ( jcol != ipiv )
{
for ( j = 1; j <= n; j++ )
{
t = a[jcol-1+(j-1)*n];
a[jcol-1+(j-1)*n] = a[ipiv-1+(j-1)*n];
a[ipiv-1+(j-1)*n] = t;
}
for ( j = 0; j < nb; j++ )
{
t = x[jcol-1+j*n];
x[jcol-1+j*n] = x[ipiv-1+j*n];
x[ipiv-1+j*n] = t;
}
}
//
// Scale the pivot row.
//
t = a[jcol-1+(jcol-1)*n];
a[jcol-1+(jcol-1)*n] = 1.0;
for ( j = jcol+1; j <= n; j++ )
{
a[jcol-1+(j-1)*n] = a[jcol-1+(j-1)*n] / t;
}
for ( j = 0; j < nb; j++ )
{
x[jcol-1+j*n] = x[jcol-1+j*n] / t;
}
//
// Use the pivot row to eliminate lower entries in that column.
//
for ( i = jcol+1; i <= n; i++ )
{
if ( a[i-1+(jcol-1)*n] != 0.0 )
{
t = - a[i-1+(jcol-1)*n];
a[i-1+(jcol-1)*n] = 0.0;
for ( j = jcol+1; j <= n; j++ )
{
a[i-1+(j-1)*n] = a[i-1+(j-1)*n] + t * a[jcol-1+(j-1)*n];
}
for ( j = 0; j < nb; j++ )
{
x[i-1+j*n] = x[i-1+j*n] + t * x[jcol-1+j*n];
}
}
}
}
//
// Back solve.
//
for ( jcol = n; 2 <= jcol; jcol-- )
{
for ( i = 1; i < jcol; i++ )
{
for ( j = 0; j < nb; j++ )
{
x[i-1+j*n] = x[i-1+j*n] - a[i-1+(jcol-1)*n] * x[jcol-1+j*n];
}
}
}
return x;
}
//****************************************************************************80
double *r8mat_givens_post ( int n, double a[], int row, int col )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_GIVENS_POST computes the Givens postmultiplier rotation matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The Givens post-multiplier matrix G(ROW,COL) has the property that
// the (ROW,COL)-th entry of A*G is zero.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrices A and G.
//
// Input, double A[N*N], the matrix to be operated upon.
//
// Input, int ROW, COL, the row and column of the
// entry of A*G which is to be zeroed out.
//
// Output, double R8MAT_GIVENS_POST[N*N], the Givens rotation matrix.
// G is an orthogonal matrix, that is, the inverse of
// G is the transpose of G.
//
{
double *g;
double theta;
g = r8mat_identity_new ( n );
theta = atan2 ( a[row-1+(col-1)*n], a[row-1+(row-1)*n] );
g[row-1+(row-1)*n] = cos ( theta );
g[row-1+(col-1)*n] = -sin ( theta );
g[col-1+(row-1)*n] = sin ( theta );
g[col-1+(col-1)*n] = cos ( theta );
return g;
}
//****************************************************************************80
double *r8mat_givens_pre ( int n, double a[], int row, int col )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_GIVENS_PRE computes the Givens premultiplier rotation matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The Givens premultiplier rotation matrix G(ROW,COL) has the
// property that the (ROW,COL)-th entry of G*A is zero.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrices A and G.
//
// Input, double A[N*N], the matrix to be operated upon.
//
// Input, int ROW, COL, the row and column of the
// entry of the G*A which is to be zeroed out.
//
// Output, double R8MAT_GIVENS_PRE[N*N], the Givens rotation matrix.
// G is an orthogonal matrix, that is, the inverse of
// G is the transpose of G.
//
{
double *g;
double theta;
g = r8mat_identity_new ( n );
theta = atan2 ( a[row-1+(col-1)*n], a[col-1+(col-1)*n] );
g[row-1+(row-1)*n] = cos ( theta );
g[row-1+(col-1)*n] = -sin ( theta );
g[col-1+(row-1)*n] = sin ( theta );
g[col-1+(col-1)*n] = cos ( theta );
return g;
}
//****************************************************************************80
double *r8mat_hess ( double (*fx) ( int n, double x[] ), int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HESS approximates a Hessian matrix via finite differences.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// H(I,J) = d2 F / d X(I) d X(J)
//
// The values returned by this routine will be only approximate.
// In some cases, they will be so poor that they are useless.
// However, one of the best applications of this routine is for
// checking your own Hessian calculations, since as Heraclitus
// said, you'll never get the same result twice when you differentiate
// a complicated expression by hand.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 August 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double *FX ( int N, double X[] ), the name of the user
// function routine.
//
// Input, int N, the number of variables.
//
// Input, double X[N], the values of the variables.
//
// Output, double H[N*N], the approximated N by N Hessian matrix.
//
{
double eps;
double f00;
double fmm;
double fmp;
double fpm;
double fpp;
double *h;
int i;
int j;
double *s;
double xi;
double xj;
//
// Choose the stepsizes.
//
s = new double[n];
eps = pow ( r8_epsilon ( ), 0.33 );
for ( i = 0; i < n; i++ )
{
s[i] = eps * r8_max ( fabs ( x[i] ), 1.0 );
}
//
// Calculate the diagonal elements.
//
h = new double[n*n];
for ( i = 0; i < n; i++ )
{
xi = x[i];
f00 = fx ( n, x );
x[i] = xi + s[i];
fpp = fx ( n, x );
x[i] = xi - s[i];
fmm = fx ( n, x );
h[i+i*n] = ( ( fpp - f00 ) + ( fmm - f00 ) ) / s[i] / s[i];
x[i] = xi;
}
//
// Calculate the off diagonal elements.
//
for ( i = 0; i < n; i++ )
{
xi = x[i];
for ( j = i+1; j < n; j++ )
{
xj = x[j];
x[i] = xi + s[i];
x[j] = xj + s[j];
fpp = fx ( n, x );
x[i] = xi + s[i];
x[j] = xj - s[j];
fpm = fx ( n, x );
x[i] = xi - s[i];
x[j] = xj + s[j];
fmp = fx ( n, x );
x[i] = xi - s[i];
x[j] = xj - s[j];
fmm = fx ( n, x );
h[j+i*n] = ( ( fpp - fpm ) + ( fmm - fmp ) ) / ( 4.0 * s[i] * s[j] );
h[i+j*n] = h[j+i*n];
x[j] = xj;
}
x[i] = xi;
}
delete [] s;
return h;
}
//****************************************************************************80
void r8mat_house_axh ( int n, double a[], double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HOUSE_AXH computes A*H where H is a compact Householder matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of double precision values, which
// may be stored as a vector in column-major order.
//
// The Householder matrix H(V) is defined by
//
// H(V) = I - 2 * v * v' / ( v' * v )
//
// This routine is not particularly efficient.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 July 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input/output, double A[N*N], on input, the matrix to be postmultiplied.
// On output, A has been replaced by A*H.
//
// Input, double V[N], a vector defining a Householder matrix.
//
{
double *ah;
int i;
int j;
int k;
double v_normsq;
v_normsq = 0.0;
for ( i = 0; i < n; i++ )
{
v_normsq = v_normsq + v[i] * v[i];
}
//
// Compute A*H' = A*H
//
ah = new double[n*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
ah[i+j*n] = a[i+j*n];
for ( k = 0; k < n; k++ )
{
ah[i+j*n] = ah[i+j*n] - 2.0 * a[i+k*n] * v[k] * v[j] / v_normsq;
}
}
}
//
// Copy A = AH;
//
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
a[i+j*n] = ah[i+j*n];
}
}
delete [] ah;
return;
}
//****************************************************************************80
double *r8mat_house_axh_new ( int n, double a[], double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HOUSE_AXH_NEW computes A*H where H is a compact Householder matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The Householder matrix H(V) is defined by
//
// H(V) = I - 2 * v * v' / ( v' * v )
//
// This routine is not particularly efficient.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input, double A[N*N], the matrix to be postmultiplied.
//
// Input, double V[N], a vector defining a Householder matrix.
//
// Output, double R8MAT_HOUSE_AXH[N*N], the product A*H.
//
{
double *ah;
int i;
int j;
int k;
double v_normsq;
v_normsq = 0.0;
for ( i = 0; i < n; i++ )
{
v_normsq = v_normsq + v[i] * v[i];
}
//
// Compute A*H' = A*H
//
ah = new double[n*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
ah[i+j*n] = a[i+j*n];
for ( k = 0; k < n; k++ )
{
ah[i+j*n] = ah[i+j*n] - 2.0 * a[i+k*n] * v[k] * v[j] / v_normsq;
}
}
}
return ah;
}
//****************************************************************************80
double *r8mat_house_form ( int n, double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HOUSE_FORM constructs a Householder matrix from its compact form.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// H(v) = I - 2 * v * v' / ( v' * v )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
//
// Input, double V[N], the vector defining the Householder matrix.
//
// Output, double R8MAT_HOUSE_FORM[N*N], the Householder matrix.
//
{
double beta;
double *h;
int i;
int j;
//
// Compute the L2 norm of V.
//
beta = 0.0;
for ( i = 0; i < n; i++ )
{
beta = beta + v[i] * v[i];
}
//
// Form the matrix H.
//
h = r8mat_identity_new ( n );
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < n; j++ )
{
h[i+j*n] = h[i+j*n] - 2.0 * v[i] * v[j] / beta;
}
}
return h;
}
//****************************************************************************80
double *r8mat_house_hxa ( int n, double a[], double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HOUSE_HXA computes H*A where H is a compact Householder matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The Householder matrix H(V) is defined by
//
// H(V) = I - 2 * v * v' / ( v' * v )
//
// This routine is not particularly efficient.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input, double A[N*N], the matrix to be premultiplied.
//
// Input, double V[N], a vector defining a Householder matrix.
//
// Output, double R8MAT_HOUSE_HXA[N*N], the product H*A.
//
{
double *ha;
int i;
int j;
int k;
double v_normsq;
v_normsq = 0.0;
for ( i = 0; i < n; i++ )
{
v_normsq = v_normsq + v[i] * v[i];
}
//
// Compute A*H' = A*H
//
ha = new double[n*n];
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < n; j++ )
{
ha[i+j*n] = a[i+j*n];
for ( k = 0; k < n; k++ )
{
ha[i+j*n] = ha[i+j*n] - 2.0 * v[i] * v[k] * a[k+j*n] / v_normsq;
}
}
}
return ha;
}
//****************************************************************************80
double *r8mat_house_post ( int n, double a[], int row, int col )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HOUSE_POST computes a Householder post-multiplier matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// H(ROW,COL) has the property that the ROW-th column of
// A*H(ROW,COL) is zero from entry COL+1 to the end.
//
// In the most common case, where a QR factorization is being computed,
// ROW = COL.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrices.
//
// Input, double A[N*N], the matrix whose Householder matrix
// is to be computed.
//
// Input, int ROW, COL, specify the location of the
// entry of the matrix A which is to be preserved. The entries in
// the same row, but higher column, will be zeroed out if
// A is postmultiplied by H.
//
// Output, double R8MAT_HOUSE_POST[N*N], the Householder matrix.
//
{
double *a_row;
double *h;
int j;
double *v;
//
// Extract the ROW-th row of A.
//
a_row = new double[n];
for ( j = 0; j < col-1; j++ )
{
a_row[j] = 0.0;
}
for ( j = col - 1; j < n; j++ )
{
a_row[j] = a[row+j*n];
}
//
// Set up the vector V.
//
v = r8vec_house_column ( n, a_row, col );
//
// Form the matrix H(V).
//
h = r8mat_house_form ( n, v );
//
// Free memory.
//
delete [] a_row;
delete [] v;
return h;
}
//****************************************************************************80
double *r8mat_house_pre ( int n, double a[], int row, int col )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HOUSE_PRE computes a Householder pre-multiplier matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// H(ROW,COL) has the property that the COL-th column of
// H(ROW,COL)*A is zero from entry ROW+1 to the end.
//
// In the most common case, where a QR factorization is being computed,
// ROW = COL.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrices.
//
// Input, double A[N*N], the matrix whose Householder matrix
// is to be computed.
//
// Input, int ROW, COL, specify the location of the
// entry of the matrix A which is to be preserved. The entries in
// the same column, but higher rows, will be zeroed out if A is
// premultiplied by H.
//
// Output, double R8MAT_HOUSE_PRE[N*N], the Householder matrix.
//
{
double *a_col;
double *h;
int i;
double *v;
double *w;
//
// Extract the COL-th column of A.
//
a_col = new double[n];
for ( i = 0; i < row-1; i++ )
{
a_col[i] = 0.0;
}
for ( i = row-1; i < n; i++ )
{
a_col[i] = a[i+col*n];
}
//
// Set up the vector V.
//
v = r8vec_house_column ( n, a_col, row );
//
// Form the matrix H(V).
//
h = r8mat_house_form ( n, v );
//
// Free memory.
//
delete [] a_col;
delete [] v;
return h;
}
//****************************************************************************80
void r8mat_identity ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_IDENTITY sets the square matrix A to the identity.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Output, double A[N*N], the N by N identity matrix.
//
{
int i;
int j;
int k;
k = 0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
if ( i == j )
{
a[k] = 1.0;
}
else
{
a[k] = 0.0;
}
k = k + 1;
}
}
return;
}
//****************************************************************************80
double *r8mat_identity_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_IDENTITY_NEW returns an identity matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Output, double R8MAT_IDENTITY_NEW[N*N], the N by N identity matrix.
//
{
double *a;
int i;
int j;
int k;
a = new double[n*n];
k = 0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
if ( i == j )
{
a[k] = 1.0;
}
else
{
a[k] = 0.0;
}
k = k + 1;
}
}
return a;
}
//****************************************************************************80
bool r8mat_in_01 ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_IN_01 is TRUE if the entries of an R8MAT are in the range [0,1].
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix.
//
// Output, bool R8MAT_IN_01, is TRUE if every entry of A is
// between 0 and 1.
//
{
int i;
int j;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
if ( a[i+j*m] < 0.0 || 1.0 < a[i+j*m] )
{
return false;
}
}
}
return true;
}
//****************************************************************************80
double *r8mat_indicator_new ( int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_INDICATOR_NEW sets up an "indicator" R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The value of each entry suggests its location, as in:
//
// 11 12 13 14
// 21 22 23 24
// 31 32 33 34
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 January 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows of the matrix.
// M must be positive.
//
// Input, int N, the number of columns of the matrix.
// N must be positive.
//
// Output, double R8MAT_INDICATOR_NEW[M*N], the table.
//
{
double *a;
int fac;
int i;
int j;
a = new double[m*n];
fac = i4_power ( 10, i4_log_10 ( n ) + 1 );
for ( i = 1; i <= m; i++ )
{
for ( j = 1; j <= n; j++ )
{
a[i-1+(j-1)*m] = ( double ) ( fac * i + j );
}
}
return a;
}
//****************************************************************************80
bool r8mat_insignificant ( int m, int n, double r[], double s[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_INSIGNIFICANT determines if an R8MAT is insignificant.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the dimension of the matrices.
//
// Input, double R[M*N], the vector to be compared against.
//
// Input, double S[M*N], the vector to be compared.
//
// Output, bool R8MAT_INSIGNIFICANT, is TRUE if S is insignificant
// compared to R.
//
{
int i;
int j;
double t;
double tol;
bool value;
value = true;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
t = r[i+j*m] + s[i+j*m];
tol = r8_epsilon ( ) * fabs ( r[i+j*m] );
if ( tol < fabs ( r[i+j*m] - t ) )
{
value = false;
break;
}
}
}
return value;
}
//****************************************************************************80
double *r8mat_inverse_2d ( double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_INVERSE_2D inverts a 2 by 2 matrix using Cramer's rule.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[2*2], the matrix to be inverted.
//
// Output, double R8MAT_INVERSE_2D[2*2], the inverse of the matrix A.
//
{
double *b;
double det;
//
// Compute the determinant of A.
//
det = a[0+0*2] * a[1+1*2] - a[0+1*2] * a[1+0*2];
//
// If the determinant is zero, bail out.
//
if ( det == 0.0 )
{
return NULL;
}
//
// Compute the entries of the inverse matrix using an explicit formula.
//
b = new double[2*2];
b[0+0*2] = + a[1+1*2] / det;
b[0+1*2] = - a[0+1*2] / det;
b[1+0*2] = - a[1+0*2] / det;
b[1+1*2] = + a[0+0*2] / det;
return b;
}
//****************************************************************************80
double *r8mat_inverse_3d ( double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_INVERSE_3D inverts a 3 by 3 matrix using Cramer's rule.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// If the determinant is zero, A is singular, and does not have an
// inverse. In that case, the output is set to NULL.
//
// If the determinant is nonzero, its value is an estimate
// of how nonsingular the matrix A is.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[3*3], the matrix to be inverted.
//
// Output, double R8MAT_INVERSE_3D[3*3], the inverse of the matrix A.
//
{
double *b;
double det;
//
// Compute the determinant of A.
//
det =
a[0+0*3] * ( a[1+1*3] * a[2+2*3] - a[1+2*3] * a[2+1*3] )
+ a[0+1*3] * ( a[1+2*3] * a[2+0*3] - a[1+0*3] * a[2+2*3] )
+ a[0+2*3] * ( a[1+0*3] * a[2+1*3] - a[1+1*3] * a[2+0*3] );
if ( det == 0.0 )
{
return NULL;
}
b = new double[3*3];
b[0+0*3] = ( a[1+1*3] * a[2+2*3] - a[1+2*3] * a[2+1*3] ) / det;
b[0+1*3] = - ( a[0+1*3] * a[2+2*3] - a[0+2*3] * a[2+1*3] ) / det;
b[0+2*3] = ( a[0+1*3] * a[1+2*3] - a[0+2*3] * a[1+1*3] ) / det;
b[1+0*3] = - ( a[1+0*3] * a[2+2*3] - a[1+2*3] * a[2+0*3] ) / det;
b[1+1*3] = ( a[0+0*3] * a[2+2*3] - a[0+2*3] * a[2+0*3] ) / det;
b[1+2*3] = - ( a[0+0*3] * a[1+2*3] - a[0+2*3] * a[1+0*3] ) / det;
b[2+0*3] = ( a[1+0*3] * a[2+1*3] - a[1+1*3] * a[2+0*3] ) / det;
b[2+1*3] = - ( a[0+0*3] * a[2+1*3] - a[0+1*3] * a[2+0*3] ) / det;
b[2+2*3] = ( a[0+0*3] * a[1+1*3] - a[0+1*3] * a[1+0*3] ) / det;
return b;
}
//****************************************************************************80
double *r8mat_inverse_4d ( double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_INVERSE_4D inverts a 4 by 4 matrix using Cramer's rule.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[4][4], the matrix to be inverted.
//
// Output, double R8MAT_INVERSE_4D[4][4], the inverse of the matrix A.
//
{
double *b;
double det;
//
// Compute the determinant of A.
//
det = r8mat_det_4d ( a );
//
// If the determinant is zero, bail out.
//
if ( det == 0.0 )
{
return NULL;
}
//
// Compute the entries of the inverse matrix using an explicit formula.
//
b = new double[4*4];
b[0+0*4] =
+(
+ a[1+1*4] * ( a[2+2*4] * a[3+3*4] - a[2+3*4] * a[3+2*4] )
+ a[1+2*4] * ( a[2+3*4] * a[3+1*4] - a[2+1*4] * a[3+3*4] )
+ a[1+3*4] * ( a[2+1*4] * a[3+2*4] - a[2+2*4] * a[3+1*4] )
) / det;
b[1+0*4] =
-(
+ a[1+0*4] * ( a[2+2*4] * a[3+3*4] - a[2+3*4] * a[3+2*4] )
+ a[1+2*4] * ( a[2+3*4] * a[3+0*4] - a[2+0*4] * a[3+3*4] )
+ a[1+3*4] * ( a[2+0*4] * a[3+2*4] - a[2+2*4] * a[3+0*4] )
) / det;
b[2+0*4] =
+(
+ a[1+0*4] * ( a[2+1*4] * a[3+3*4] - a[2+3*4] * a[3+1*4] )
+ a[1+1*4] * ( a[2+3*4] * a[3+0*4] - a[2+0*4] * a[3+3*4] )
+ a[1+3*4] * ( a[2+0*4] * a[3+1*4] - a[2+1*4] * a[3+0*4] )
) / det;
b[3+0*4] =
-(
+ a[1+0*4] * ( a[2+1*4] * a[3+2*4] - a[2+2*4] * a[3+1*4] )
+ a[1+1*4] * ( a[2+2*4] * a[3+0*4] - a[2+0*4] * a[3+2*4] )
+ a[1+2*4] * ( a[2+0*4] * a[3+1*4] - a[2+1*4] * a[3+0*4] )
) / det;
b[0+1*4] =
-(
+ a[0+1*4] * ( a[2+2*4] * a[3+3*4] - a[2+3*4] * a[3+2*4] )
+ a[0+2*4] * ( a[2+3*4] * a[3+1*4] - a[2+1*4] * a[3+3*4] )
+ a[0+3*4] * ( a[2+1*4] * a[3+2*4] - a[2+2*4] * a[3+1*4] )
) / det;
b[1+1*4] =
+(
+ a[0+0*4] * ( a[2+2*4] * a[3+3*4] - a[2+3*4] * a[3+2*4] )
+ a[0+2*4] * ( a[2+3*4] * a[3+0*4] - a[2+0*4] * a[3+3*4] )
+ a[0+3*4] * ( a[2+0*4] * a[3+2*4] - a[2+2*4] * a[3+0*4] )
) / det;
b[2+1*4] =
-(
+ a[0+0*4] * ( a[2+1*4] * a[3+3*4] - a[2+3*4] * a[3+1*4] )
+ a[0+1*4] * ( a[2+3*4] * a[3+0*4] - a[2+0*4] * a[3+3*4] )
+ a[0+3*4] * ( a[2+0*4] * a[3+1*4] - a[2+1*4] * a[3+0*4] )
) / det;
b[3+1*4] =
+(
+ a[0+0*4] * ( a[2+1*4] * a[3+2*4] - a[2+2*4] * a[3+1*4] )
+ a[0+1*4] * ( a[2+2*4] * a[3+0*4] - a[2+0*4] * a[3+2*4] )
+ a[0+2*4] * ( a[2+0*4] * a[3+1*4] - a[2+1*4] * a[3+0*4] )
) / det;
b[0+2*4] =
+(
+ a[0+1*4] * ( a[1+2*4] * a[3+3*4] - a[1+3*4] * a[3+2*4] )
+ a[0+2*4] * ( a[1+3*4] * a[3+1*4] - a[1+1*4] * a[3+3*4] )
+ a[0+3*4] * ( a[1+1*4] * a[3+2*4] - a[1+2*4] * a[3+1*4] )
) / det;
b[1+2*4] =
-(
+ a[0+0*4] * ( a[1+2*4] * a[3+3*4] - a[1+3*4] * a[3+2*4] )
+ a[0+2*4] * ( a[1+3*4] * a[3+0*4] - a[1+0*4] * a[3+3*4] )
+ a[0+3*4] * ( a[1+0*4] * a[3+2*4] - a[1+2*4] * a[3+0*4] )
) / det;
b[2+2*4] =
+(
+ a[0+0*4] * ( a[1+1*4] * a[3+3*4] - a[1+3*4] * a[3+1*4] )
+ a[0+1*4] * ( a[1+3*4] * a[3+0*4] - a[1+0*4] * a[3+3*4] )
+ a[0+3*4] * ( a[1+0*4] * a[3+1*4] - a[1+1*4] * a[3+0*4] )
) / det;
b[3+2*4] =
-(
+ a[0+0*4] * ( a[1+1*4] * a[3+2*4] - a[1+2*4] * a[3+1*4] )
+ a[0+1*4] * ( a[1+2*4] * a[3+0*4] - a[1+0*4] * a[3+2*4] )
+ a[0+2*4] * ( a[1+0*4] * a[3+1*4] - a[1+1*4] * a[3+0*4] )
) / det;
b[0+3*4] =
-(
+ a[0+1*4] * ( a[1+2*4] * a[2+3*4] - a[1+3*4] * a[2+2*4] )
+ a[0+2*4] * ( a[1+3*4] * a[2+1*4] - a[1+1*4] * a[2+3*4] )
+ a[0+3*4] * ( a[1+1*4] * a[2+2*4] - a[1+2*4] * a[2+1*4] )
) / det;
b[1+3*4] =
+(
+ a[0+0*4] * ( a[1+2*4] * a[2+3*4] - a[1+3*4] * a[2+2*4] )
+ a[0+2*4] * ( a[1+3*4] * a[2+0*4] - a[1+0*4] * a[2+3*4] )
+ a[0+3*4] * ( a[1+0*4] * a[2+2*4] - a[1+2*4] * a[2+0*4] )
) / det;
b[2+3*4] =
-(
+ a[0+0*4] * ( a[1+1*4] * a[2+3*4] - a[1+3*4] * a[2+1*4] )
+ a[0+1*4] * ( a[1+3*4] * a[2+0*4] - a[1+0*4] * a[2+3*4] )
+ a[0+3*4] * ( a[1+0*4] * a[2+1*4] - a[1+1*4] * a[2+0*4] )
) / det;
b[3+3*4] =
+(
+ a[0+0*4] * ( a[1+1*4] * a[2+2*4] - a[1+2*4] * a[2+1*4] )
+ a[0+1*4] * ( a[1+2*4] * a[2+0*4] - a[1+0*4] * a[2+2*4] )
+ a[0+2*4] * ( a[1+0*4] * a[2+1*4] - a[1+1*4] * a[2+0*4] )
) / det;
return b;
}
//****************************************************************************80
double r8mat_is_identity ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_IS_IDENTITY determines if an R8MAT is the identity.
//
// Discussion:
//
// An R8MAT is a matrix of real ( kind = 8 ) values.
//
// The routine returns the Frobenius norm of A - I.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 July 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
//
// Input, double A[N*N], the matrix.
//
// Output, double R8MAT_IS_IDENTITY, the Frobenius norm
// of the difference matrix A - I, which would be exactly zero
// if A were the identity matrix.
//
{
double error_frobenius;
int i;
int j;
double t;
error_frobenius = 0.0;
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < n; j++ )
{
if ( i == j )
{
t = a[i+j*n] - 1.0;
}
else
{
t = a[i+j*n];
}
error_frobenius = error_frobenius + t * t;
}
}
error_frobenius = sqrt ( error_frobenius );
return error_frobenius;
}
//****************************************************************************80
double r8mat_is_symmetric ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_IS_SYMMETRIC checks an R8MAT for symmetry.
//
// Discussion:
//
// An R8MAT is a matrix of double precision real values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the order of the matrix.
//
// Input, double A[M*N], the matrix.
//
// Output, double RMAT_IS_SYMMETRIC, measures the
// Frobenius norm of ( A - A' ), which would be zero if the matrix
// were exactly symmetric.
//
{
int i;
int j;
const double r8_huge = 1.79769313486231571E+308;
double value;
if ( m != n )
{
value = r8_huge;
return value;
}
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + pow ( a[i+j*m] - a[j+i*m], 2 );
}
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
double *r8mat_jac ( int m, int n, double eps,
double *(*fx) ( int m, int n, double x[] ), double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_JAC estimates a dense jacobian matrix of the function FX.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// FPRIME(I,J) = d F(I) / d X(J).
//
// The jacobian is assumed to be dense, and the LINPACK/LAPACK
// double precision general matrix storage mode ("DGE") is used.
//
// Forward differences are used, requiring N+1 function evaluations.
//
// Values of EPS have typically been chosen between
// sqrt ( EPSMCH ) and sqrt ( sqrt ( EPSMCH ) ) where EPSMCH is the
// machine tolerance.
//
// If EPS is too small, then F(X+EPS) will be the same as
// F(X), and the jacobian will be full of zero entries.
//
// If EPS is too large, the finite difference estimate will
// be inaccurate.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of functions.
//
// Input, int N, the number of variables.
//
// Input, double EPS, a tolerance to be used for shifting the
// X values during the finite differencing. No single value
// of EPS will be reliable for all vectors X and functions FX.
//
// Input, double *(*FX) ( int m, int n, double x[] ), the name of
// the user written routine which evaluates the M-dimensional
// function at a given N-dimensional point X.
//
// Input, double X[N], the point where the jacobian
// is to be estimated.
//
// Output, double R8MAT_JAC[M*N], the estimated jacobian matrix.
//
{
double del;
double *fprime;
int i;
int j;
double xsave;
double *work1;
double *work2;
fprime = new double[m*n];
//
// Evaluate the function at the base point, X.
//
work2 = fx ( m, n, x );
//
// Now, one by one, vary each component J of the base point X, and
// estimate DF(I)/DX(J) = ( F(X+) - F(X) )/ DEL.
//
for ( j = 0; j < n; j++ )
{
xsave = x[j];
del = eps * ( 1.0 + fabs ( x[j] ) );
x[j] = x[j] + del;
work1 = fx ( m, n, x );
x[j] = xsave;
for ( i = 0; i < m; i++ )
{
fprime[i+j*m] = ( work1[i] - work2[i] ) / del;
}
delete [] work1;
}
delete [] work2;
return fprime;
}
//****************************************************************************80
double *r8mat_kronecker ( int m1, int n1, double a[], int m2, int n2,
double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_KRONECKER computes the Kronecker product of two R8MAT's.
//
// Discussion:
//
// An R8MAT is an MxN array of R8's, stored by (I,J) -> [I+J*M].
//
// If A is an M1 by N1 array, and B is an M2 by N2 array, then
// the Kronecker product of A and B is an M1*M2 by N1*N2 array
// C(I,J) = A(I1,J1) * B(I2,J2)
// where
// I1 = I / M2
// I2 = mod ( I, M2 )
// J1 = J / N2
// J2 = mod ( J, N2 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M1, N1, the order of the first matrix.
//
// Input, double A[M1*N1], the first matrix.
//
// Input, int M2, N2, the order of the second matrix.
//
// Input, double B[M2*N2], the second matrix.
//
// Output, double R8MAT_KRONECKER[(M1*M2)*(N1*N2)], the Kronecker product.
//
{
double *c;
int i;
int i0;
int i1;
int i2;
int j;
int j0;
int j1;
int j2;
int m;
int n;
m = m1 * m2;
n = n1 * n2;
c = new double[m*n];
for ( j1 = 0; j1 < n1; j1++ )
{
for ( i1 = 0; i1 < m1; i1++ )
{
i0 = i1 * m2;
j0 = j1 * n2;
j = j0;
for ( j2 = 0; j2 < n2; j2++ )
{
i = i0;
for ( i2 = 0; i2 < m2; i2++ )
{
c[i+j*m] = a[i1+j1*m1] * b[i2+j2*m2];
i = i + 1;
}
j = j + 1;
}
}
}
return c;
}
//****************************************************************************80
double *r8mat_l_inverse ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_L_INVERSE inverts a lower triangular R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// A lower triangular matrix is a matrix whose only nonzero entries
// occur on or below the diagonal.
//
// The inverse of a lower triangular matrix is a lower triangular matrix.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 September 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, number of rows and columns in the matrix.
//
// Input, double A[N*N], the lower triangular matrix.
//
// Output, double R8MAT_L_INVERSE[N*N], the inverse matrix.
//
{
double *b;
int i;
int j;
int k;
double temp;
b = new double[n*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
if ( i < j )
{
b[i+j*n] = 0.0;
}
else if ( j == i )
{
b[i+j*n] = 1.0 / a[i+j*n];
}
else
{
temp = 0.0;
for ( k = 0; k < i; k++ )
{
temp = temp + a[i+k*n] * b[k+j*n];
}
b[i+j*n] = -temp / a[i+i*n];
}
}
}
return b;
}
//****************************************************************************80
void r8mat_l_print ( int m, int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_L_PRINT prints a lower triangular R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Example:
//
// M = 5, N = 5
// A = (/ 11, 21, 31, 41, 51, 22, 32, 42, 52, 33, 43, 53, 44, 54, 55 /)
//
// 11
// 21 22
// 31 32 33
// 41 42 43 44
// 51 52 53 54 55
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 January 2016
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[*], the M by N matrix. Only the lower
// triangular elements are stored, in column major order.
//
// Input, string TITLE, a title.
//
{
int i;
int indx[10];
int j;
int jhi;
int jlo;
int jmax;
int nn;
int size;
cout << "\n";
cout << title << "\n";
jmax = i4_min ( n, m );
if ( m <= n )
{
size = ( m * ( m + 1 ) ) / 2;
}
else if ( n < m )
{
size = ( n * ( n + 1 ) ) / 2 + ( m - n ) * n;
}
if ( r8vec_is_int ( size, a ) )
{
nn = 10;
for ( jlo = 1; jlo <= jmax; jlo = jlo + nn )
{
jhi = i4_min ( jlo + nn - 1, i4_min ( m, jmax ) );
cout << "\n";
cout << " Col ";
for ( j = jlo; j <= jhi; j++ )
{
cout << setw(6) << j;
}
cout << "\n";
cout << " Row \n";
for ( i = jlo; i <= m; i++ )
{
jhi = i4_min ( jlo + nn - 1, i4_min ( i, jmax ) );
for ( j = jlo; j <= jhi; j++ )
{
indx[j-jlo] = ( j - 1 ) * m + i - ( j * ( j - 1 ) ) / 2;
}
cout << " " << setw(6) << i;
for ( j = 0; j <= jhi-jlo; j++ )
{
cout << setw(6) << a[indx[j]-1];
}
cout << "\n";
}
}
}
else if ( r8vec_amax ( size, a ) < 1000000.0 )
{
nn = 5;
for ( jlo = 1; jlo <= jmax; jlo = jlo + nn )
{
jhi = i4_min ( jlo + nn - 1, i4_min ( m - 1, jmax ) );
cout << "\n";
cout << " Col ";
for ( j = jlo; j <= jhi; j++ )
{
cout << setw(14) << j;
}
cout << "\n";
cout << " Row \n";
for ( i = jlo; i <= m; i++ )
{
jhi = i4_min ( jlo + nn - 1, i4_min ( i, jmax ) );
for ( j = jlo; j <= jhi; j++ )
{
indx[j-jlo] = ( j - 1 ) * m + i - ( j * ( j - 1 ) ) / 2;
}
cout << " " << setw(6) << i;
for ( j = 0; j <= jhi-jlo; j++ )
{
cout << setw(14) << a[indx[j]-1];
}
cout << "\n";
}
}
}
else
{
nn = 5;
for ( jlo = 1; jlo <= jmax; jlo = jlo + nn )
{
jhi = i4_min ( jlo + nn - 1, i4_min ( m - 1, jmax ) );
cout << "\n";
cout << " Col ";
for ( j = jlo; j <= jhi; j++ )
{
cout << setw(7) << j << " ";
}
cout << "\n";
cout << " Row \n";
for ( i = jlo; i <= m; i++ )
{
jhi = i4_min ( jlo + nn - 1, i4_min ( i, jmax ) );
for ( j = jlo; j <= jhi; j++ )
{
indx[j-jlo] = ( j - 1 ) * m + i - ( j * ( j - 1 ) ) / 2;
}
cout << setw(6) << i;
for ( j = 0; j <= jhi-jlo; j++ )
{
cout << setw(14) << a[indx[j]-1];
}
}
}
}
return;
}
//****************************************************************************80
double *r8mat_l_solve ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_L_SOLVE solves a lower triangular linear system.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix A.
//
// Input, double A[N*N], the N by N lower triangular matrix.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double R8MAT_L_SOLVE[N], the solution of the linear system.
//
{
int i;
int j;
double temp;
double *x;
x = new double[n];
//
// Solve L * x = b.
//
for ( i = 0; i < n; i++ )
{
temp = 0.0;
for ( j = 0; j < i; j++ )
{
temp = temp + a[i+j*n] * x[j];
}
x[i] = ( b[i] - temp ) / a[i+i*n];
}
return x;
}
//****************************************************************************80
double *r8mat_l1_inverse ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_L1_INVERSE inverts a unit lower triangular R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// A unit lower triangular matrix is a matrix with only 1's on the main
// diagonal, and only 0's above the main diagonal.
//
// The inverse of a unit lower triangular matrix is also
// a unit lower triangular matrix.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 September 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, number of rows and columns in the matrix.
//
// Input, double A[N*N], the unit lower triangular matrix.
//
// Output, double R8MAT_L1_INVERSE[N*N], the inverse matrix.
//
{
double *b;
int i;
int j;
int k;
b = new double[n*n];
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < n; j++ )
{
if ( i < j )
{
b[i+j*n] = 0.0;
}
else if ( j == i )
{
b[i+j*n] = 1.0;
}
else
{
b[i+j*n] = 0.0;
for ( k = 0; k < i; k++ )
{
b[i+j*n] = b[i+j*n] - a[i+k*n] * b[k+j*n];
}
}
}
}
return b;
}
//****************************************************************************80
double *r8mat_lt_solve ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_LT_SOLVE solves a transposed lower triangular linear system.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Given the lower triangular matrix A, the linear system to be solved is:
//
// A' * x = b
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix A.
//
// Input, double A[N*N], the N by N lower triangular matrix.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double R8MAT_LT_SOLVE[N], the solution of the linear system.
//
{
int i;
int j;
double *x;
x = new double[n];
for ( j = n-1; 0 <= j; j-- )
{
x[j] = b[j];
for ( i = j+1; i < n; i++ )
{
x[j] = x[j] - x[i] * a[i+j*n];
}
x[j] = x[j] / a[j+j*n];
}
return x;
}
//****************************************************************************80
void r8mat_lu ( int m, int n, double a[], double l[], double p[], double u[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_LU computes the LU factorization of a rectangular R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The routine is given an M by N matrix A, and produces
//
// L, an M by M unit lower triangular matrix,
// U, an M by N upper triangular matrix, and
// P, an M by M permutation matrix P,
//
// so that
//
// A = P' * L * U.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 November 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix to be factored.
//
// Output, double L[M*M], the M by M unit lower triangular factor.
//
// Output, double P[M*M], the M by M permutation matrix.
//
// Output, double U[M*N], the M by N upper triangular factor.
//
{
int i;
int ipiv;
int j;
int k;
double pivot;
double t;
//
// Initialize:
//
// U:=A
// L:=Identity
// P:=Identity
//
r8mat_copy ( m, n, a, u );
r8mat_zeros ( m, m, l );
r8mat_zeros ( m, m, p );
for ( i = 0; i < m; i++ )
{
l[i+i*m] = 1.0;
p[i+i*m] = 1.0;
}
//
// On step J, find the pivot row, IPIV, and the pivot value PIVOT.
//
for ( j = 0; j < i4_min ( m - 1, n ); j++ )
{
pivot = 0.0;
ipiv = -1;
for ( i = j; i < m; i++ )
{
if ( pivot < fabs ( u[i+j*m] ) )
{
pivot = fabs ( u[i+j*m] );
ipiv = i;
}
}
//
// Unless IPIV is zero, swap rows J and IPIV.
//
if ( ipiv != -1 )
{
for ( k = 0; k < n; k++ )
{
t = u[j+k*m];
u[j+k*m] = u[ipiv+j*m];
u[ipiv+k*m] = t;
t = l[j+k*m];
l[j+k*m] = l[ipiv+j*m];
l[ipiv+k*m] = t;
t = p[j+k*m];
p[j+k*m] = p[ipiv+j*m];
p[ipiv+k*m] = t;
}
//
// Zero out the entries in column J, from row J+1 to M.
//
for ( i = j+1; i < m; i++ )
{
if ( u[i+j*m] != 0.0 )
{
l[i+j*m] = u[i+j*m] / u[j+j*m];
u[i+j*m] = 0.0;
for ( k = j+1; k < n; k++ )
{
u[i+k*m] = u[i+k*m] - l[i+j*m] * u[j+k*m];
}
}
}
}
}
return;
}
//****************************************************************************80
double r8mat_max ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MAX returns the maximum entry of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 May 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix.
//
// Output, double R8MAT_MAX, the maximum entry of A.
//
{
int i;
int j;
double value;
value = a[0+0*m];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
if ( value < a[i+j*m] )
{
value = a[i+j*m];
}
}
}
return value;
}
//****************************************************************************80
void r8mat_max_index ( int m, int n, double a[], int &i_max, int &j_max )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MAX_INDEX returns the location of the maximum entry of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix.
//
// Output, int &I_MAX, &J_MAX, the indices of the maximum entry of A.
//
{
int i;
int i2;
int j;
int j2;
i2 = -1;
j2 = -1;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
if ( i2 == -1 && j2 == -1 )
{
i2 = i;
j2 = j;
}
else if ( a[i2+j2*m] < a[i+j*m] )
{
i2 = i;
j2 = j;
}
}
}
i_max = i2 + 1;
j_max = j2 + 1;
return;
}
//****************************************************************************80
double r8mat_maxcol_minrow ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MAXCOL_MINROW gets the maximum column minimum row of an M by N matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// R8MAT_MAXCOL_MINROW = max ( 1 <= I <= N ) ( min ( 1 <= J <= M ) A(I,J) )
//
// For a given matrix, R8MAT_MAXCOL_MINROW <= R8MAT_MINROW_MAXCOL.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix.
//
// Output, double R8MAT_MAXCOL_MINROW, the maximum column
// minimum row entry of A.
//
{
int i;
int j;
double minrow;
const double r8_huge = 1.79769313486231571E+308;
double value;
value = - r8_huge;
for ( i = 0; i < m; i++ )
{
minrow = r8_huge;
for ( j = 0; j < n; j++ )
{
minrow = r8_min ( minrow, a[i+j*m] );
}
value = r8_max ( value, minrow );
}
return value;
}
//****************************************************************************80
double r8mat_maxrow_mincol ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MAXROW_MINCOL gets the maximum row minimum column of an M by N matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// R8MAT_MAXROW_MINCOL = max ( 1 <= J <= N ) ( min ( 1 <= I <= M ) A(I,J) )
//
// For a given matrix, R8MAT_MAXROW_MINCOL <= R8MAT_MINCOL_MAXROW.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix.
//
// Output, double R8MAT_MAXROW_MINCOL, the maximum row
// minimum column entry of A.
//
{
int i;
int j;
double mincol;
const double r8_huge = 1.79769313486231571E+308;
double value;
value = - r8_huge;
for ( j = 0; j < n; j++ )
{
mincol = r8_huge;
for ( i = 0; i < m; i++ )
{
mincol = r8_min ( mincol, a[i+j*m] );
}
value = r8_max ( value, mincol );
}
return value;
}
//****************************************************************************80
double r8mat_mean ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MEAN returns the mean of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 September 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix.
//
// Output, double R8MAT_MEAN, the mean of A.
//
{
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + a[i+j*m];
}
}
value = value / ( double ) ( m * n );
return value;
}
//****************************************************************************80
double r8mat_min ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MIN returns the minimum entry of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 May 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix.
//
// Output, double R8MAT_MIN, the minimum entry of A.
//
{
int i;
int j;
double value;
value = a[0+0*m];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
if ( a[i+j*m] < value )
{
value = a[i+j*m];
}
}
}
return value;
}
//****************************************************************************80
void r8mat_min_index ( int m, int n, double a[], int &i_min, int &j_min )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MIN_INDEX returns the location of the minimum entry of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix.
//
// Output, int &I_MIN, &J_MIN, the indices of the minimum entry of A.
//
{
int i;
int i2;
int j;
int j2;
i2 = -1;
j2 = -1;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
if ( i2 == -1 && j2 == -1 )
{
i2 = i;
j2 = j;
}
else if ( a[i+j*m] < a[i2+j2*m] )
{
i2 = i;
j2 = j;
}
}
}
i_min = i2 + 1;
j_min = j2 + 1;
return;
}
//****************************************************************************80
double r8mat_mincol_maxrow ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MINCOL_MAXROW gets the minimum column maximum row of an M by N matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// R8MAT_MINCOL_MAXROW = min ( 1 <= I <= N ) ( max ( 1 <= J <= M ) A(I,J) )
//
// For a given matrix, R8MAT_MAXROW_MINCOL <= R8MAT_MINCOL_MAXROW.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A(M,N), the matrix.
//
// Output, double R8MAT_MINCOL_MAXROW, the minimum column
// maximum row entry of A.
//
{
int i;
int j;
double maxrow;
const double r8_huge = 1.79769313486231571E+308;
double value;
value = r8_huge;
for ( i = 0; i < m; i++ )
{
maxrow = - r8_huge;
for ( j = 0; j < n; j++ )
{
maxrow = r8_max ( maxrow, a[i+j*m] );
}
value = r8_min ( value, maxrow );
}
return value;
}
//****************************************************************************80
double r8mat_minrow_maxcol ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MINROW_MAXCOL gets the minimum row maximum column of an M by N matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// R8MAT_MINROW_MAXCOL = min ( 1 <= J <= N ) ( max ( 1 <= I <= M ) A(I,J) )
//
// For a given matrix, R8MAT_MAXCOL_MINROW <= R8MAT_MINROW_MAXCOL.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix.
//
// Output, double R8MAT_MINROW_MAXCOL, the minimum row
// maximum column entry of A.
//
{
int i;
int j;
double maxcol;
const double r8_huge = 1.79769313486231571E+308;
double value;
value = r8_huge;
for ( j = 0; j < n; j++ )
{
maxcol = - r8_huge;
for ( i = 0; i < m; i++ )
{
maxcol = r8_max ( maxcol, a[i+j*m] );
}
value = r8_min ( value, maxcol );
}
return value;
}
//****************************************************************************80
void r8mat_minvm ( int n1, int n2, double a[], double b[], double c[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MINVM computes inverse(A) * B for R8MAT's.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, N2, the order of the matrices.
//
// Input, double A[N1*N1], B[N1*N2], the matrices.
//
// Output, double C[N1*N2], the result, C = inverse(A) * B.
//
{
double *alu;
double *d;
alu = r8mat_copy_new ( n1, n1, a );
d = r8mat_fss_new ( n1, alu, n2, b );
r8mat_copy ( n1, n2, d, c );
delete [] alu;
delete [] d;
return;
}
//****************************************************************************80
double *r8mat_minvm_new ( int n1, int n2, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MINVM_NEW returns inverse(A) * B for R8MAT's.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, N2, the order of the matrices.
//
// Input, double A[N1*N1], B[N1*N2], the matrices.
//
// Output, double R8MAT_MINVM_NEW[N1*N2], the result, C = inverse(A) * B.
//
{
double *alu;
double *c;
alu = r8mat_copy_new ( n1, n1, a );
c = r8mat_fss_new ( n1, alu, n2, b );
delete [] alu;
return c;
}
//****************************************************************************80
void r8mat_mm ( int n1, int n2, int n3, double a[], double b[], double c[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MM multiplies two matrices.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as the function value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, N2, N3, the order of the matrices.
//
// Input, double A[N1*N2], double B[N2*N3], the matrices to multiply.
//
// Output, double C[N1*N3], the product matrix C = A * B.
//
{
double *c1;
int i;
int j;
int k;
c1 = new double[n1*n3];
for ( i = 0; i < n1; i++ )
{
for ( j = 0; j < n3; j++ )
{
c1[i+j*n1] = 0.0;
for ( k = 0; k < n2; k++ )
{
c1[i+j*n1] = c1[i+j*n1] + a[i+k*n1] * b[k+j*n2];
}
}
}
r8mat_copy ( n1, n3, c1, c );
delete [] c1;
return;
}
//****************************************************************************80
double *r8mat_mm_new ( int n1, int n2, int n3, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MM_NEW multiplies two matrices.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as the function value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, N2, N3, the order of the matrices.
//
// Input, double A[N1*N2], double B[N2*N3], the matrices to multiply.
//
// Output, double R8MAT_MM_NEW[N1*N3], the product matrix C = A * B.
//
{
double *c;
int i;
int j;
int k;
c = new double[n1*n3];
for ( i = 0; i < n1; i++ )
{
for ( j = 0; j < n3; j++ )
{
c[i+j*n1] = 0.0;
for ( k = 0; k < n2; k++ )
{
c[i+j*n1] = c[i+j*n1] + a[i+k*n1] * b[k+j*n2];
}
}
}
return c;
}
//****************************************************************************80
double *r8mat_mmt_new ( int n1, int n2, int n3, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MMT_NEW computes C = A * B'.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as the function value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 November 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, N2, N3, the order of the matrices.
//
// Input, double A[N1*N2], double B[N3*N2], the matrices to multiply.
//
// Output, double R8MAT_MMT_NEW[N1*N3], the product matrix C = A * B'.
//
{
double *c;
int i;
int j;
int k;
c = new double[n1*n3];
for ( i = 0; i < n1; i++ )
{
for ( j = 0; j < n3; j++ )
{
c[i+j*n1] = 0.0;
for ( k = 0; k < n2; k++ )
{
c[i+j*n1] = c[i+j*n1] + a[i+k*n1] * b[j+k*n3];
}
}
}
return c;
}
//****************************************************************************80
double *r8mat_mtm_new ( int n1, int n2, int n3, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MTM_NEW computes C = A' * B.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as the function value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, N2, N3, the order of the matrices.
//
// Input, double A[N2*N1], double B[N2*N3], the matrices to multiply.
//
// Output, double R8MAT_MTM_NEW[N1*N3], the product matrix C = A' * B.
//
{
double *c;
int i;
int j;
int k;
c = new double[n1*n3];
for ( i = 0; i < n1; i++ )
{
for ( j = 0; j < n3; j++ )
{
c[i+j*n1] = 0.0;
for ( k = 0; k < n2; k++ )
{
c[i+j*n1] = c[i+j*n1] + a[k+i*n2] * b[k+j*n2];
}
}
}
return c;
}
//****************************************************************************80
void r8mat_mtv ( int m, int n, double a[], double x[], double atx[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MTV multiplies a transposed matrix times a vector.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as an argument.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 April 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of the matrix.
//
// Input, double A[M,N], the M by N matrix.
//
// Input, double X[M], the vector to be multiplied by A.
//
// Output, double ATX[N], the product A'*X.
//
{
int i;
int j;
double *y;
y = new double[n];
for ( j = 0; j < n; j++ )
{
y[j] = 0.0;
for ( i = 0; i < m; i++ )
{
y[j] = y[j] + a[i+j*m] * x[i];
}
}
r8vec_copy ( n, y, atx );
free ( y );
return;
}
//****************************************************************************80
double *r8mat_mtv_new ( int m, int n, double a[], double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MTV_NEW multiplies a transposed matrix times a vector.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as the function value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 April 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of the matrix.
//
// Input, double A[M,N], the M by N matrix.
//
// Input, double X[M], the vector to be multiplied by A.
//
// Output, double R8MAT_MTV_NEW[N], the product A'*X.
//
{
int i;
int j;
double *y;
y = new double[n];
for ( j = 0; j < n; j++ )
{
y[j] = 0.0;
for ( i = 0; i < m; i++ )
{
y[j] = y[j] + a[i+j*m] * x[i];
}
}
return y;
}
//****************************************************************************80
void r8mat_mv ( int m, int n, double a[], double x[], double ax[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MV multiplies a matrix times a vector.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as an argument.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 April 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of the matrix.
//
// Input, double A[M,N], the M by N matrix.
//
// Input, double X[N], the vector to be multiplied by A.
//
// Output, double AX[M], the product A*X.
//
{
int i;
int j;
double *y;
y = ( double * ) malloc ( m * sizeof ( double ) );
for ( i = 0; i < m; i++ )
{
y[i] = 0.0;
for ( j = 0; j < n; j++ )
{
y[i] = y[i] + a[i+j*m] * x[j];
}
}
r8vec_copy ( m, y, ax );
free ( y );
return;
}
//****************************************************************************80
double *r8mat_mv_new ( int m, int n, double a[], double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MV_NEW multiplies a matrix times a vector.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as the function value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 April 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of the matrix.
//
// Input, double A[M,N], the M by N matrix.
//
// Input, double X[N], the vector to be multiplied by A.
//
// Output, double R8MAT_MV_NEW[M], the product A*X.
//
{
int i;
int j;
double *y;
y = new double[m];
for ( i = 0; i < m; i++ )
{
y[i] = 0.0;
for ( j = 0; j < n; j++ )
{
y[i] = y[i] + a[i+j*m] * x[j];
}
}
return y;
}
//****************************************************************************80
void r8mat_nint ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NINT rounds the entries of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input/output, double A[M*N], the matrix.
//
{
int i;
int j;
int s;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
if ( a[i+j*m] < 0.0 )
{
s = -1;
}
else
{
s = 1;
}
a[i+j*m] = s * ( int ) ( fabs ( a[i+j*m] ) + 0.5 );
}
}
return;
}
//****************************************************************************80
int r8mat_nonzeros ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NONZEROS returns the number of nonzeros in an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 31 August 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], the matrix.
//
// Output, int R8MAT_NONZEROS, the number of nonzeros.
//
{
int i;
int j;
int value;
value = 0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
if ( a[i+j*m] != 0.0 )
{
value = value + 1;
}
}
}
return value;
}
//****************************************************************************80
double r8mat_norm_eis ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NORM_EIS returns the EISPACK norm of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The EISPACK norm is defined as:
//
// R8MAT_NORM_EIS =
// sum ( 1 <= I <= M ) sum ( 1 <= J <= N ) abs ( A(I,J) )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix whose EISPACK norm is desired.
//
// Output, double R8MAT_NORM_EIS, the EISPACK norm of A.
//
{
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + fabs ( a[i+j*m] );
}
}
return value;
}
//****************************************************************************80
double r8mat_norm_fro ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NORM_FRO returns the Frobenius norm of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The Frobenius norm is defined as
//
// R8MAT_NORM_FRO = sqrt (
// sum ( 1 <= I <= M ) sum ( 1 <= j <= N ) A(I,J)^2 )
// The matrix Frobenius norm is not derived from a vector norm, but
// is compatible with the vector L2 norm, so that:
//
// r8vec_norm_l2 ( A * x ) <= r8mat_norm_fro ( A ) * r8vec_norm_l2 ( x ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix whose Frobenius
// norm is desired.
//
// Output, double R8MAT_NORM_FRO, the Frobenius norm of A.
//
{
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + pow ( a[i+j*m], 2 );
}
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
double r8mat_norm_fro_affine ( int m, int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NORM_FRO_AFFINE returns the Frobenius norm of an R8MAT difference.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The Frobenius norm is defined as
//
// R8MAT_NORM_FRO = sqrt (
// sum ( 1 <= I <= M ) sum ( 1 <= j <= N ) A(I,J)^2 )
// The matrix Frobenius norm is not derived from a vector norm, but
// is compatible with the vector L2 norm, so that:
//
// r8vec_norm_l2 ( A * x ) <= r8mat_norm_fro ( A ) * r8vec_norm_l2 ( x ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows.
//
// Input, int N, the number of columns.
//
// Input, double A1[M*N], A2[M,N], the matrice for whose difference the
// Frobenius norm is desired.
//
// Output, double R8MAT_NORM_FRO_AFFINE, the Frobenius norm of A1 - A2.
//
{
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + pow ( a1[i+j*m] - a2[i+j*m], 2 );
}
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
double r8mat_norm_l1 ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NORM_L1 returns the matrix L1 norm of an R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// The matrix L1 norm is defined as:
//
// R8MAT_NORM_L1 = max ( 1 <= J <= N )
// sum ( 1 <= I <= M ) abs ( A(I,J) ).
//
// The matrix L1 norm is derived from the vector L1 norm, and
// satisifies:
//
// r8vec_norm_l1 ( A * x ) <= r8mat_norm_l1 ( A ) * r8vec_norm_l1 ( x ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A(M,N), the matrix whose L1 norm is desired.
//
// Output, double R8MAT_NORM_L1, the L1 norm of A.
//
{
double col_sum;
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
col_sum = 0.0;
for ( i = 0; i < m; i++ )
{
col_sum = col_sum + fabs ( a[i+j*m] );
}
value = r8_max ( value, col_sum );
}
return value;
}
//****************************************************************************80
double r8mat_norm_l2 ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NORM_L2 returns the matrix L2 norm of an R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// The matrix L2 norm is defined as:
//
// R8MAT_NORM_L2 = sqrt ( max ( 1 <= I <= M ) LAMBDA(I) )
//
// where LAMBDA contains the eigenvalues of A * A'.
//
// The matrix L2 norm is derived from the vector L2 norm, and
// satisifies:
//
// r8vec_norm_l2 ( A * x ) <= r8mat_norm_l2 ( A ) * r8vec_norm_l2 ( x ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A(M,N), the matrix whose L2 norm is desired.
//
// Output, double R8MAT_NORM_L2, the L2 norm of A.
//
{
double *at;
double *b;
double *diag;
double value;
at = r8mat_transpose_new ( m, n, a );
//
// Compute B = A * A'.
//
b = r8mat_mm_new ( m, n, m, a, at );
//
// Diagonalize B.
//
r8mat_symm_jacobi ( m, b );
//
// Find the maximum eigenvalue, and take its square root.
//
diag = r8mat_diag_get_vector_new ( m, b );
value = sqrt ( r8vec_max ( m, diag ) );
delete [] at;
delete [] b;
delete [] diag;
return value;
}
//****************************************************************************80
double r8mat_norm_li ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NORM_LI returns the matrix L-oo norm of an R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// The matrix L-oo norm is defined as:
//
// R8MAT_NORM_LI = max ( 1 <= I <= M ) sum ( 1 <= J <= N ) abs ( A(I,J) ).
//
// The matrix L-oo norm is derived from the vector L-oo norm,
// and satisifies:
//
// r8vec_norm_li ( A * x ) <= r8mat_norm_li ( A ) * r8vec_norm_li ( x ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix whose L-oo
// norm is desired.
//
// Output, double R8MAT_NORM_LI, the L-oo norm of A.
//
{
int i;
int j;
double row_sum;
double value;
value = 0.0;
for ( i = 0; i < m; i++ )
{
row_sum = 0.0;
for ( j = 0; j < n; j++ )
{
row_sum = row_sum + fabs ( a[i+j*m] );
}
value = r8_max ( value, row_sum );
}
return value;
}
//****************************************************************************80
double *r8mat_normal_01_new ( int m, int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NORMAL_01_NEW returns a unit pseudonormal R8MAT.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Springer Verlag, pages 201-202, 1983.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, pages 362-376, 1986.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, pages 136-143, 1969.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the array.
//
// Input/output, int &SEED, the "seed" value, which should NOT be 0.
// On output, SEED has been updated.
//
// Output, double R8MAT_NORMAL_01_NEW[M*N], the array of pseudonormal values.
//
{
double *r;
r = r8vec_normal_01_new ( m * n, seed );
return r;
}
//****************************************************************************80
double *r8mat_nullspace ( int m, int n, double a[], int nullspace_size )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NULLSPACE computes the nullspace of a matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Let A be an MxN matrix.
//
// If X is an N-vector, and A*X = 0, then X is a null vector of A.
//
// The set of all null vectors of A is called the nullspace of A.
//
// The 0 vector is always in the null space.
//
// If the 0 vector is the only vector in the nullspace of A, then A
// is said to have maximum column rank. (Because A*X=0 can be regarded
// as a linear combination of the columns of A). In particular, if A
// is square, and has maximum column rank, it is nonsingular.
//
// The dimension of the nullspace is the number of linearly independent
// vectors that span the nullspace. If A has maximum column rank,
// its nullspace has dimension 0.
//
// This routine uses the reduced row echelon form of A to determine
// a set of NULLSPACE_SIZE independent null vectors.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of
// the matrix A.
//
// Input, double A[M*N], the matrix to be analyzed.
//
// Input, int NULLSPACE_SIZE, the size of the nullspace.
//
// Output, double R8MAT_NULLSPACE[N*NULLSPACE_SIZE], vectors that
// span the nullspace.
//
{
int *col;
int i;
int i2;
int j;
int j2;
double *nullspace;
int *row;
double *rref;
//
// Make a copy of A.
//
rref = r8mat_copy_new ( m, n, a );
//
// Get the reduced row echelon form of A.
//
r8mat_rref ( m, n, rref );
//
// Note in ROW the columns of the leading nonzeros.
// COL(J) = +J if there is a leading 1 in that column, and -J otherwise.
//
row = new int[m];
for ( i = 0; i < m; i++ )
{
row[i] = 0;
}
col = new int[n];
for ( j = 0; j < n; j++ )
{
col[j] = - ( j + 1 );
}
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
if ( rref[i+j*m] == 1.0 )
{
row[i] = ( j + 1 );
col[j] = ( j + 1 );
break;
}
}
}
nullspace = r8mat_zeros_new ( n, nullspace_size );
j2 = 0;
//
// If column J does not contain a leading 1, then it contains
// information about a null vector.
//
for ( j = 0; j < n; j++ )
{
if ( col[j] < 0 )
{
for ( i = 0; i < m; i++ )
{
if ( rref[i+j*m] != 0.0 )
{
i2 = row[i] - 1;
nullspace[i2+j2*n] = - rref[i+j*m];
}
}
nullspace[j+j2*n] = 1.0;
j2 = j2 + 1;
}
}
delete [] col;
delete [] row;
delete [] rref;
return nullspace;
}
//****************************************************************************80
int r8mat_nullspace_size ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_NULLSPACE_SIZE computes the size of the nullspace of a matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Let A be an MxN matrix.
//
// If X is an N-vector, and A*X = 0, then X is a null vector of A.
//
// The set of all null vectors of A is called the nullspace of A.
//
// The 0 vector is always in the null space.
//
// If the 0 vector is the only vector in the nullspace of A, then A
// is said to have maximum column rank. (Because A*X=0 can be regarded
// as a linear combination of the columns of A). In particular, if A
// is square, and has maximum column rank, it is nonsingular.
//
// The dimension of the nullspace is the number of linearly independent
// vectors that span the nullspace. If A has maximum column rank,
// its nullspace has dimension 0.
//
// This routine ESTIMATES the dimension of the nullspace. Cases of
// singularity that depend on exact arithmetic will probably be missed.
//
// The nullspace will be estimated by counting the leading 1's in the
// reduced row echelon form of A, and subtracting this from N.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 August 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of
// the matrix A.
//
// Input, double A[M*N], the matrix to be analyzed.
//
// Output, int R8MAT_NULLSPACE_SIZE, the estimated size
// of the nullspace.
//
{
int i;
int j;
int leading;
int nullspace_size;
double *rref;
//
// Make a copy of A.
//
rref = r8mat_copy_new ( m, n, a );
//
// Get the reduced row echelon form of A.
//
r8mat_rref ( m, n, rref );
//
// Count the leading 1's in A.
//
leading = 0;
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
if ( rref[i+j*m] == 1.0 )
{
leading = leading + 1;
break;
}
}
}
nullspace_size = n - leading;
delete [] rref;
return nullspace_size;
}
//****************************************************************************80
double *r8mat_orth_uniform_new ( int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_ORTH_UNIFORM_NEW returns a random orthogonal matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The inverse of A is equal to A'.
//
// A * A' = A' * A = I.
//
// Columns and rows of A have unit Euclidean norm.
//
// Distinct pairs of columns of A are orthogonal.
//
// Distinct pairs of rows of A are orthogonal.
//
// The L2 vector norm of A*x = the L2 vector norm of x for any vector x.
//
// The L2 matrix norm of A*B = the L2 matrix norm of B for any matrix B.
//
// The determinant of A is +1 or -1.
//
// All the eigenvalues of A have modulus 1.
//
// All singular values of A are 1.
//
// All entries of A are between -1 and 1.
//
// Discussion:
//
// Thanks to Eugene Petrov, B I Stepanov Institute of Physics,
// National Academy of Sciences of Belarus, for convincingly
// pointing out the severe deficiencies of an earlier version of
// this routine.
//
// Essentially, the computation involves saving the Q factor of the
// QR factorization of a matrix whose entries are normally distributed.
// However, it is only necessary to generate this matrix a column at
// a time, since it can be shown that when it comes time to annihilate
// the subdiagonal elements of column K, these (transformed) elements of
// column K are still normally distributed random values. Hence, there
// is no need to generate them at the beginning of the process and
// transform them K-1 times.
//
// For computational efficiency, the individual Householder transformations
// could be saved, as recommended in the reference, instead of being
// accumulated into an explicit matrix format.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 November 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Pete Stewart,
// Efficient Generation of Random Orthogonal Matrices With an Application
// to Condition Estimators,
// SIAM Journal on Numerical Analysis,
// Volume 17, Number 3, June 1980, pages 403-409.
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8MAT_ORTH_UNIFORM_NEW[N*N], the orthogonal matrix.
//
{
double *a_col;
double *q;
double *q2;
int i;
int j;
double *v;
double *x;
//
// Start with Q = the identity matrix.
//
q = r8mat_identity_new ( n );
//
// Now behave as though we were computing the QR factorization of
// some other random matrix. Generate the N elements of the first column,
// compute the Householder matrix H1 that annihilates the subdiagonal elements,
// and set Q := Q * H1' = Q * H.
//
// On the second step, generate the lower N-1 elements of the second column,
// compute the Householder matrix H2 that annihilates them,
// and set Q := Q * H2' = Q * H2 = H1 * H2.
//
// On the N-1 step, generate the lower 2 elements of column N-1,
// compute the Householder matrix HN-1 that annihilates them, and
// and set Q := Q * H(N-1)' = Q * H(N-1) = H1 * H2 * ... * H(N-1).
// This is our random orthogonal matrix.
//
a_col = new double[n];
for ( j = 1; j < n; j++ )
{
//
// Set the vector that represents the J-th column to be annihilated.
//
for ( i = 1; i < j; i++ )
{
a_col[i-1] = 0.0;
}
for ( i = j; i <= n; i++ )
{
a_col[i-1] = r8_normal_01 ( seed );
}
//
// Compute the vector V that defines a Householder transformation matrix
// H(V) that annihilates the subdiagonal elements of A.
//
v = r8vec_house_column ( n, a_col, j );
//
// Postmultiply the matrix Q by H'(V) = H(V).
//
q2 = r8mat_house_axh_new ( n, q, v );
delete [] v;
r8mat_copy ( n, n, q2, q );
delete [] q2;
}
//
// Free memory.
//
delete [] a_col;
return q;
}
//****************************************************************************80
void r8mat_plot ( int m, int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_PLOT "plots" an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the matrix.
//
// Input, string TITLE, a title.
//
{
int i;
int j;
int jhi;
int jlo;
cout << "\n";
cout << title << "\n";
for ( jlo = 1; jlo <= n; jlo = jlo + 70 )
{
jhi = i4_min ( jlo + 70-1, n );
cout << "\n";
cout << " ";
for ( j = jlo; j <= jhi; j++ )
{
cout << ( j % 10 );
}
cout << "\n";
cout << "\n";
for ( i = 1; i <= m; i++ )
{
cout << setw(6) << i << " ";
for ( j = jlo; j <= jhi; j++ )
{
cout << r8mat_plot_symbol ( a[i-1+(j-1)*m] );
}
cout << "\n";
}
}
return;
}
//****************************************************************************80
char r8mat_plot_symbol ( double r )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_PLOT_SYMBOL returns a symbol for entries of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double R, a value whose symbol is desired.
//
// Output, char R8MAT_PLOT_SYMBOL, is
// '-' if R is negative,
// '0' if R is zero,
// '+' if R is positive.
//
{
char c;
if ( r < 0.0 )
{
c = '-';
}
else if ( r == 0.0 )
{
c = '0';
}
else if ( 0.0 < r )
{
c = '+';
}
return c;
}
//****************************************************************************80
double *r8mat_poly_char ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_POLY_CHAR computes the characteristic polynomial of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix A.
//
// Input, double A[N*N], the N by N matrix.
//
// Output, double R8MAT_POLY_CHAR[N+1], the coefficients of the characteristic
// polynomial of A. P(N) contains the coefficient of X^N
// (which will be 1), P(I) contains the coefficient of X^I,
// and P(0) contains the constant term.
//
{
int i;
int order;
double *p;
double trace;
double *work1;
double *work2;
p = new double[n+1];
//
// Initialize WORK1 to the identity matrix.
//
work1 = r8mat_identity_new ( n );
p[n] = 1.0;
for ( order = n-1; 0 <= order; order-- )
{
//
// Work2 = A * WORK1.
//
work2 = r8mat_mm_new ( n, n, n, a, work1 );
//
// Take the trace.
//
trace = r8mat_trace ( n, work2 );
//
// P(ORDER) = -Trace ( WORK2 ) / ( N - ORDER )
//
p[order] = -trace / ( double ) ( n - order );
//
// WORK1 := WORK2 + P(IORDER) * Identity.
//
delete [] work1;
r8mat_copy ( n, n, work2, work1 );
delete [] work2;
for ( i = 0; i < n; i++ )
{
work1[i+i*n] = work1[i+i*n] + p[order];
}
}
delete [] work1;
return p;
}
//****************************************************************************80
double *r8mat_power ( int n, double a[], int npow )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_POWER computes a nonnegative power of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The algorithm is:
//
// B = I
// do NPOW times:
// B = A * B
// end
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input, double A[N*N], the matrix to be raised to a power.
//
// Input, int NPOW, the power to which A is to be raised.
// NPOW must be nonnegative.
//
// Output, double B[N*N], the value of A^NPOW.
//
{
double *b;
double *c;
int ipow;
if ( npow < 0 )
{
cerr << "\n";
cerr << "R8MAT_POWER - Fatal error!\n";
cerr << " Input value of NPOW < 0.\n";
cerr << " NPOW = " << npow << "\n";
exit ( 1 );
}
b = r8mat_identity_new ( n );
for ( ipow = 1; ipow <= npow; ipow++ )
{
c = r8mat_mm_new ( n, n, n, a, b );
r8mat_copy ( n, n, c, b );
delete [] c;
}
return b;
}
//****************************************************************************80
void r8mat_power_method ( int n, double a[], double *r, double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_POWER_METHOD applies the power method to a matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// If the power method has not converged, then calling the routine
// again immediately with the output from the previous call will
// continue the iteration.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input, double A[N*N], the matrix.
//
// Output, double *R, the estimated eigenvalue.
//
// Input/output, double V[N], on input, an estimate
// for the eigenvector. On output, an improved estimate for the
// eigenvector.
//
{
double *av;
double eps;
int i;
int it;
double it_eps = 0.0001;
int it_max = 100;
int it_min = 10;
int j;
double r2;
double r_old;
eps = sqrt ( r8_epsilon ( ) );
*r = r8vec_norm ( n, v );
if ( *r == 0.0 )
{
for ( i = 0; i < n; i++ )
{
v[i] = 1.0;
}
*r = sqrt ( ( double ) n );
}
for ( i = 0; i < n; i++ )
{
v[i] = v[i] / *r;
}
for ( it = 1; it <= it_max; it++ )
{
av = r8mat_mv_new ( n, n, a, v );
r_old = *r;
*r = r8vec_norm ( n, av );
if ( it_min < it )
{
if ( fabs ( *r - r_old ) <= it_eps * ( 1.0 + fabs ( *r ) ) )
{
break;
}
}
r8vec_copy ( n, av, v );
delete [] av;
if ( *r != 0.0 )
{
for ( i = 0; i < n; i++ )
{
v[i] = v[i] / *r;
}
}
//
// Perturb V a bit, to avoid cases where the initial guess is exactly
// the eigenvector of a smaller eigenvalue.
//
if ( it < it_max / 2 )
{
j = ( ( it - 1 ) % n );
v[j] = v[j] + eps * ( 1.0 + fabs ( v[j] ) );
r2 = r8vec_norm ( n, v );
for ( i = 0; i < n; i++ )
{
v[i] = v[i] / r2;
}
}
}
return;
}
//****************************************************************************80
void r8mat_print ( int m, int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_PRINT prints an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Entry A(I,J) is stored as A[I+J*M]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[M*N], the M by N matrix.
//
// Input, string TITLE, a title.
//
{
r8mat_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
//****************************************************************************80
void r8mat_print_some ( int m, int n, double a[], int ilo, int jlo, int ihi,
int jhi, string title )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_PRINT_SOME prints some of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 June 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows of the matrix.
// M must be positive.
//
// Input, int N, the number of columns of the matrix.
// N must be positive.
//
// Input, double A[M*N], the matrix.
//
// Input, int ILO, JLO, IHI, JHI, designate the first row and
// column, and the last row and column to be printed.
//
// Input, string TITLE, a title.
//
{
# define INCX 5
int i;
int i2hi;
int i2lo;
int j;
int j2hi;
int j2lo;
cout << "\n";
cout << title << "\n";
if ( m <= 0 || n <= 0 )
{
cout << "\n";
cout << " (None)\n";
return;
}
//
// Print the columns of the matrix, in strips of 5.
//
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
if ( n < j2hi )
{
j2hi = n;
}
if ( jhi < j2hi )
{
j2hi = jhi;
}
cout << "\n";
//
// For each column J in the current range...
//
// Write the header.
//
cout << " Col: ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(7) << j - 1 << " ";
}
cout << "\n";
cout << " Row\n";
cout << "\n";
//
// Determine the range of the rows in this strip.
//
if ( 1 < ilo )
{
i2lo = ilo;
}
else
{
i2lo = 1;
}
if ( ihi < m )
{
i2hi = ihi;
}
else
{
i2hi = m;
}
for ( i = i2lo; i <= i2hi; i++ )
{
//
// Print out (up to) 5 entries in row I, that lie in the current strip.
//
cout << setw(5) << i - 1 << ": ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(12) << a[i-1+(j-1)*m] << " ";
}
cout << "\n";
}
}
return;
# undef INCX
}
//****************************************************************************80
void r8mat_ref ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_REF computes the row echelon form of a matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// A matrix is in row echelon form if:
//
// * The first nonzero entry in each row is 1.
//
// * The leading 1 in a given row occurs in a column to
// the right of the leading 1 in the previous row.
//
// * Rows which are entirely zero must occur last.
//
// Example:
//
// Input matrix:
//
// 1.0 3.0 0.0 2.0 6.0 3.0 1.0
// -2.0 -6.0 0.0 -2.0 -8.0 3.0 1.0
// 3.0 9.0 0.0 0.0 6.0 6.0 2.0
// -1.0 -3.0 0.0 1.0 0.0 9.0 3.0
//
// Output matrix:
//
// 1.0 3.0 0.0 2.0 6.0 3.0 1.0
// 0.0 0.0 0.0 1.0 2.0 4.5 1.5
// 0.0 0.0 0.0 0.0 0.0 1.0 0.3
// 0.0 0.0 0.0 0.0 0.0 0.0 0.0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 October 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of
// the matrix A.
//
// Input/output, double A[M*N]. On input, the matrix to be
// analyzed. On output, the REF form of the matrix.
//
{
int i;
int j;
int lead;
int r;
double temp;
lead = 0;
for ( r = 0; r < m; r++ )
{
if ( n - 1 < lead )
{
break;
}
i = r;
while ( a[i+lead*m] == 0.0 )
{
i = i + 1;
if ( m - 1 < i )
{
i = r;
lead = lead + 1;
if ( n - 1 < lead )
{
lead = -1;
break;
}
}
}
if ( lead < 0 )
{
break;
}
for ( j = 0; j < n; j++ )
{
temp = a[i+j*m];
a[i+j*m] = a[r+j*m];
a[r+j*m] = temp;
}
temp = a[r+lead*m];
for ( j = 0; j < n; j++ )
{
a[r+j*m] = a[r+j*m] / temp;
}
for ( i = r + 1; i < m; i++ )
{
temp = a[i+lead*m];
for ( j = 0; j < n; j++ )
{
a[i+j*m] = a[i+j*m] - temp * a[r+j*m];
}
}
lead = lead + 1;
}
return;
}
//****************************************************************************80
double r8mat_rms ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_RMS returns the RMS norm of an R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// The matrix RMS norm is defined as:
//
// R8MAT_RMS =
// sqrt ( sum ( 0 <= J < N ) sum ( 0 <= I < M ) A[I,J]^2 / M / N ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the dimensions of the array.
//
// Input, double A[M*N], the array.
//
// Output, double R8MAT_RMS, the RMS norm of A.
//
{
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + a[i+j*m] * a[i+j*m];
}
value = sqrt ( value / ( double ) ( m ) / ( double ) ( n ) );
}
return value;
}
//****************************************************************************80
void r8mat_row_copy ( int m, int n, int i, double v[], double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_ROW_COPY copies a vector into a row of an R8MAT.
//
// Discussion:
//
// An R8MAT is an MxN array of R8's, stored by (I,J) -> [I+J*M].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the order of the matrix.
//
// Input, int I, the index of the row.
// 0 <= I <= M-1.
//
// Input, double V[N], the row to be copied.
//
// Input/output, double A[M*N], the matrix into which
// the row is to be copied.
//
{
int j;
for ( j = 0; j < n; j++ )
{
a[i+j*m] = v[j];
}
return;
}
//****************************************************************************80
void r8mat_rref ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_RREF computes the reduced row echelon form of a matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// A matrix is in row echelon form if:
//
// * The first nonzero entry in each row is 1.
//
// * The leading 1 in a given row occurs in a column to
// the right of the leading 1 in the previous row.
//
// * Rows which are entirely zero must occur last.
//
// The matrix is in reduced row echelon form if, in addition to
// the first three conditions, it also satisfies:
//
// * Each column containing a leading 1 has no other nonzero entries.
//
// Example:
//
// Input matrix:
//
// 1.0 3.0 0.0 2.0 6.0 3.0 1.0
// -2.0 -6.0 0.0 -2.0 -8.0 3.0 1.0
// 3.0 9.0 0.0 0.0 6.0 6.0 2.0
// -1.0 -3.0 0.0 1.0 0.0 9.0 3.0
//
// Output matrix:
//
// 1.0 3.0 0.0 0.0 2.0 0.0 0.0
// 0.0 0.0 0.0 1.0 2.0 0.0 0.0
// 0.0 0.0 0.0 0.0 0.0 1.0 0.3
// 0.0 0.0 0.0 0.0 0.0 0.0 0.0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 October 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of
// the matrix A.
//
// Input/output, double A[M*N]. On input, the matrix to be
// analyzed. On output, the RREF form of the matrix.
//
{
int i;
int j;
int lead;
int r;
double temp;
lead = 0;
for ( r = 0; r < m; r++ )
{
if ( n - 1 < lead )
{
break;
}
i = r;
while ( a[i+lead*m] == 0.0 )
{
i = i + 1;
if ( m - 1 < i )
{
i = r;
lead = lead + 1;
if ( n - 1 < lead )
{
lead = -1;
break;
}
}
}
if ( lead < 0 )
{
break;
}
for ( j = 0; j < n; j++ )
{
temp = a[i+j*m];
a[i+j*m] = a[r+j*m];
a[r+j*m] = temp;
}
temp = a[r+lead*m];
for ( j = 0; j < n; j++ )
{
a[r+j*m] = a[r+j*m] / temp;
}
for ( i = 0; i < m; i++ )
{
if ( i != r )
{
temp = a[i+lead*m];
for ( j = 0; j < n; j++ )
{
a[i+j*m] = a[i+j*m] - temp * a[r+j*m];
}
}
}
lead = lead + 1;
}
return;
}
//****************************************************************************80
void r8mat_scale ( int m, int n, double s, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SCALE multiplies an R8MAT by a scalar.
//
// Discussion:
//
// An R8MAT is an array of R8 values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double S, the scale factor.
//
// Input/output, double A[M*N], the matrix to be scaled.
//
{
int i;
int j;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
a[i+j*m] = a[i+j*m] * s;
}
}
return;
}
//****************************************************************************80
bool r8mat_significant ( int m, int n, double r[], double s[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SIGNIFICANT determines if an R8MAT is significant compared to another.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the dimension of the matrices.
//
// Input, double R[M*N], the vector to be compared against.
//
// Input, double S[M*N], the vector to be compared.
//
// Output, bool R8MAT_SIGNIFICANT, is TRUE if S is significant
// compared to R.
//
{
int i;
int j;
double t;
double tol;
bool value;
value = false;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
t = r[i+j*m] + s[i+j*m];
tol = r8_epsilon ( ) * fabs ( r[i+j*m] );
if ( tol < fabs ( r[i+j*m] - t ) )
{
value = true;
break;
}
}
}
return value;
}
//****************************************************************************80
int r8mat_solve ( int n, int rhs_num, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SOLVE uses Gauss-Jordan elimination to solve an N by N linear system.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Entry A(I,J) is stored as A[I+J*N]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
//
// Input, int RHS_NUM, the number of right hand sides. RHS_NUM
// must be at least 0.
//
// Input/output, double A[N*(N+RHS_NUM)], contains in rows and columns 1
// to N the coefficient matrix, and in columns N+1 through
// N+RHS_NUM, the right hand sides. On output, the coefficient matrix
// area has been destroyed, while the right hand sides have
// been overwritten with the corresponding solutions.
//
// Output, int R8MAT_SOLVE, singularity flag.
// 0, the matrix was not singular, the solutions were computed;
// J, factorization failed on step J, and the solutions could not
// be computed.
//
{
double apivot;
double factor;
int i;
int ipivot;
int j;
int k;
double temp;
for ( j = 0; j < n; j++ )
{
//
// Choose a pivot row.
//
ipivot = j;
apivot = a[j+j*n];
for ( i = j; i < n; i++ )
{
if ( fabs ( apivot ) < fabs ( a[i+j*n] ) )
{
apivot = a[i+j*n];
ipivot = i;
}
}
if ( apivot == 0.0 )
{
return j;
}
//
// Interchange.
//
for ( i = 0; i < n + rhs_num; i++ )
{
temp = a[ipivot+i*n];
a[ipivot+i*n] = a[j+i*n];
a[j+i*n] = temp;
}
//
// A(J,J) becomes 1.
//
a[j+j*n] = 1.0;
for ( k = j; k < n + rhs_num; k++ )
{
a[j+k*n] = a[j+k*n] / apivot;
}
//
// A(I,J) becomes 0.
//
for ( i = 0; i < n; i++ )
{
if ( i != j )
{
factor = a[i+j*n];
a[i+j*n] = 0.0;
for ( k = j; k < n + rhs_num; k++ )
{
a[i+k*n] = a[i+k*n] - factor * a[j+k*n];
}
}
}
}
return 0;
}
//****************************************************************************80
double *r8mat_solve_2d ( double a[], double b[], double *det )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SOLVE_2D solves a 2 by 2 linear system using Cramer's rule.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// If the determinant DET is returned as zero, then the matrix A is
// singular, and does not have an inverse. In that case, X is
// returned as the NULL vector.
//
// If DET is nonzero, then its value is roughly an estimate
// of how nonsingular the matrix A is.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 November 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[2*2], the matrix.
//
// Input, double B[2], the right hand side.
//
// Output, double *DET, the determinant of the system.
//
// Output, double R8MAT_SOLVE_2D[2], the solution of the system,
// if DET is nonzero. Otherwise, the NULL vector.
//
{
double *x;
//
// Compute the determinant.
//
*det = a[0+0*2] * a[1+1*2] - a[0+1*2] * a[1+0*2];
//
// If the determinant is zero, bail out.
//
if ( *det == 0.0 )
{
return NULL;
}
//
// Compute the solution.
//
x = new double[2];
x[0] = ( a[1+1*2] * b[0] - a[0+1*2] * b[1] ) / ( *det );
x[1] = ( -a[1+0*2] * b[0] + a[0+0*2] * b[1] ) / ( *det );
return x;
}
//****************************************************************************80
double *r8mat_solve_3d ( double a[], double b[], double *det )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SOLVE_3D solves a 3 by 3 linear system using Cramer's rule.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// If the determinant DET is returned as zero, then the matrix A is
// singular, and does not have an inverse. In that case, X is
// returned as the NULL vector.
//
// If DET is nonzero, then its value is roughly an estimate
// of how nonsingular the matrix A is.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 December 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A[3*3], the matrix.
//
// Input, double B[3], the right hand side.
//
// Output, double *DET, the determinant of the system.
//
// Output, double R8MAT_SOLVE_3D[3], the solution of the system,
// if DET is nonzero. Otherwise, the NULL vector.
//
{
double *x;
//
// Compute the determinant.
//
*det = a[0+0*3] * ( a[1+1*3] * a[2+2*3] - a[1+2*3] * a[2+1*3] )
+ a[0+1*3] * ( a[1+2*3] * a[2+0*3] - a[1+0*3] * a[2+2*3] )
+ a[0+2*3] * ( a[1+0*3] * a[2+1*3] - a[1+1*3] * a[2+0*3] );
//
// If the determinant is zero, bail out.
//
if ( *det == 0.0 )
{
return NULL;
}
//
// Compute the solution.
//
x = new double[3];
x[0] = ( ( a[1+1*3] * a[2+2*3] - a[1+2*3] * a[2+1*3] ) * b[0]
- ( a[0+1*3] * a[2+2*3] - a[0+2*3] * a[2+1*3] ) * b[1]
+ ( a[0+1*3] * a[1+2*3] - a[0+2*3] * a[1+1*3] ) * b[2] ) / ( *det );
x[1] = ( - ( a[1+0*3] * a[2+2*3] - a[1+2*3] * a[2+0*3] ) * b[0]
+ ( a[0+0*3] * a[2+2*3] - a[0+2*3] * a[2+0*3] ) * b[1]
- ( a[0+0*3] * a[1+2*3] - a[0+2*3] * a[1+0*3] ) * b[2] ) / ( *det );
x[2] = ( ( a[1+0*3] * a[2+1*3] - a[1+1*3] * a[2+0*3] ) * b[0]
- ( a[0+0*3] * a[2+1*3] - a[0+1*3] * a[2+0*3] ) * b[1]
+ ( a[0+0*3] * a[1+1*3] - a[0+1*3] * a[1+0*3] ) * b[2] ) / ( *det );
return x;
}
//****************************************************************************80
double *r8mat_solve2 ( int n, double a[], double b[], int &ierror )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SOLVE2 computes the solution of an N by N linear system.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The linear system may be represented as
//
// A*X = B
//
// If the linear system is singular, but consistent, then the routine will
// still produce a solution.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 February 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of equations.
//
// Input/output, double A[N*N].
// On input, A is the coefficient matrix to be inverted.
// On output, A has been overwritten.
//
// Input/output, double B[N].
// On input, B is the right hand side of the system.
// On output, B has been overwritten.
//
// Output, double R8MAT_SOLVE2[N], the solution of the linear system.
//
// Output, int &IERROR.
// 0, no error detected.
// 1, consistent singularity.
// 2, inconsistent singularity.
//
{
double amax;
int i;
int imax;
int j;
int k;
int *piv;
double *x;
ierror = 0;
piv = i4vec_zeros_new ( n );
x = r8vec_zeros_new ( n );
//
// Process the matrix.
//
for ( k = 1; k <= n; k++ )
{
//
// In column K:
// Seek the row IMAX with the properties that:
// IMAX has not already been used as a pivot;
// A(IMAX,K) is larger in magnitude than any other candidate.
//
amax = 0.0;
imax = 0;
for ( i = 1; i <= n; i++ )
{
if ( piv[i-1] == 0 )
{
if ( amax < fabs ( a[i-1+(k-1)*n] ) )
{
imax = i;
amax = fabs ( a[i-1+(k-1)*n] );
}
}
}
//
// If you found a pivot row IMAX, then,
// eliminate the K-th entry in all rows that have not been used for pivoting.
//
if ( imax != 0 )
{
piv[imax-1] = k;
for ( j = k+1; j <= n; j++ )
{
a[imax-1+(j-1)*n] = a[imax-1+(j-1)*n] / a[imax-1+(k-1)*n];
}
b[imax-1] = b[imax-1] / a[imax-1+(k-1)*n];
a[imax-1+(k-1)*n] = 1.0;
for ( i = 1; i <= n; i++ )
{
if ( piv[i-1] == 0 )
{
for ( j = k+1; j <= n; j++ )
{
a[i-1+(j-1)*n] = a[i-1+(j-1)*n] - a[i-1+(k-1)*n] * a[imax-1+(j-1)*n];
}
b[i-1] = b[i-1] - a[i-1+(k-1)*n] * b[imax-1];
a[i-1+(k-1)*n] = 0.0;
}
}
}
}
//
// Now, every row with nonzero PIV begins with a 1, and
// all other rows are all zero. Begin solution.
//
for ( j = n; 1 <= j; j-- )
{
imax = 0;
for ( k = 1; k <= n; k++ )
{
if ( piv[k-1] == j )
{
imax = k;
}
}
if ( imax == 0 )
{
x[j-1] = 0.0;
if ( b[j-1] == 0.0 )
{
ierror = 1;
cout << "\n";
cout << "R8MAT_SOLVE2 - Warning:\n";
cout << " Consistent singularity, equation = " << j << "\n";
}
else
{
ierror = 2;
cout << "\n";
cout << "R8MAT_SOLVE2 - Warning:\n";
cout << " Inconsistent singularity, equation = " << j << "\n";
}
}
else
{
x[j-1] = b[imax-1];
for ( i = 1; i <= n; i++ )
{
if ( i != imax )
{
b[i-1] = b[i-1] - a[i-1+(j-1)*n] * x[j-1];
}
}
}
}
delete [] piv;
return x;
}
//****************************************************************************80
double r8mat_sum ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SUM returns the sum of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 January 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], the array.
//
// Output, double R8MAT_SUM, the sum of the entries.
//
{
int i;
int j;
double value;
value = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
value = value + a[i+j*m];
}
}
return value;
}
//****************************************************************************80
double *r8mat_symm_eigen ( int n, double x[], double q[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SYMM_EIGEN returns a symmetric matrix with given eigensystem.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The user must supply the desired eigenvalue vector, and the desired
// eigenvector matrix. The eigenvector matrix must be orthogonal. A
// suitable random orthogonal matrix can be generated by
// R8MAT_ORTH_UNIFORM_NEW.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input, double X[N], the desired eigenvalues for the matrix.
//
// Input, double Q[N*N], the eigenvector matrix of A.
//
// Output, double R8MAT_SYMM_EIGEN[N*N], a symmetric N by N matrix with
// eigenvalues X and eigenvectors the columns of Q.
//
{
double *a;
int i;
int j;
int k;
//
// Set A = Q * Lambda * Q'.
//
a = new double[n*n];
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < n; j++ )
{
a[i+j*n] = 0.0;
for ( k = 0; k < n; k++ )
{
a[i+j*n] = a[i+j*n] + q[i+k*n] * x[k] * q[j+k*n];
}
}
}
return a;
}
//****************************************************************************80
void r8mat_symm_jacobi ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_SYMM_JACOBI applies Jacobi eigenvalue iteration to a symmetric matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// This code was modified so that it treats as zero the off-diagonal
// elements that are sufficiently close to, but not exactly, zero.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of A.
//
// Input/output, double A[N*N], a symmetric N by N matrix.
// On output, the matrix has been overwritten by an approximately
// diagonal matrix, with the eigenvalues on the diagonal.
//
{
double c;
double eps = 0.00001;
int i;
int it;
int it_max = 100;
int j;
int k;
double norm_fro;
double s;
double sum2;
double t;
double t1;
double t2;
double u;
norm_fro = r8mat_norm_fro ( n, n, a );
it = 0;
for ( ; ; )
{
it = it + 1;
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < i; j++ )
{
if ( eps * norm_fro < fabs ( a[i+j*n] ) + fabs ( a[j+i*n] ) )
{
u = ( a[j+j*n] - a[i+i*n] ) / ( a[i+j*n] + a[j+i*n] );
t = r8_sign ( u ) / ( fabs ( u ) + sqrt ( u * u + 1.0 ) );
c = 1.0 / sqrt ( t * t + 1.0 );
s = t * c;
//
// A -> A * Q.
//
for ( k = 0; k < n; k++ )
{
t1 = a[i+k*n];
t2 = a[j+k*n];
a[i+k*n] = t1 * c - t2 * s;
a[j+k*n] = t1 * s + t2 * c;
}
//
// A -> QT * A
//
for ( k = 0; k < n; k++ )
{
t1 = a[k+i*n];
t2 = a[k+j*n];
a[k+i*n] = c * t1 - s * t2;
a[k+j*n] = s * t1 + c * t2;
}
}
}
}
//
// Test the size of the off-diagonal elements.
//
sum2 = 0.0;
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < i; j++ )
{
sum2 = sum2 + fabs ( a[i+j*n] );
}
}
if ( sum2 <= eps * ( norm_fro + 1.0 ) )
{
break;
}
if ( it_max <= it )
{
break;
}
}
return;
}
//****************************************************************************80
double **r8mat_to_r8cmat_new ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TO_R8CMAT_NEW copies data from an R8MAT to an R8CMAT.
//
// Discussion:
//
// An R8MAT is a column-major array stored as a vector, so
// that element (I,J) of the M by N array is stored in location
// I+J*M.
//
// An R8CMAT is a column-major array, storing element (I,J)
// as A[J][I], and can be created by a command like:
// double **a;
// a = r8cmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 January 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], the data, stored as an R8MAT.
//
// Output, double R8MAT_TO_R8CMAT_NEW[M][N], the data, stored as an R8CMAT.
//
{
double **b;
int i;
int j;
b = r8cmat_new ( m, n );
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
b[j][i] = a[i+j*m];
}
}
return b;
}
//****************************************************************************80
int r8mat_to_r8plu ( int n, double a[], int pivot[], double lu[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TO_R8PLU factors a general matrix.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// This routine is a simplified version of the LINPACK routine DGEFA.
// Fortran conventions are used to index doubly-dimensioned arrays.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2003
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
// LINPACK User's Guide,
// SIAM, 1979
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, double A[N*N], the matrix to be factored.
//
// Output, int PIVOT[N], a vector of pivot indices.
//
// Output, double LU[N*N], an upper triangular matrix U and the multipliers
// L which were used to obtain it. The factorization can be written
// A = L * U, where L is a product of permutation and unit lower
// triangular matrices and U is upper triangular.
//
// Output, int R8MAT_TO_R8PLU, singularity flag.
// 0, no singularity detected.
// nonzero, the factorization failed on the R8MAT_TO_R8PLU-th step.
//
{
int i;
int info;
int j;
int k;
int l;
double temp;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
lu[i+j*n] = a[i+j*n];
}
}
info = 0;
for ( k = 1; k <= n-1; k++ )
{
//
// Find L, the index of the pivot row.
//
l = k;
for ( i = k+1; i <= n; i++ )
{
if ( fabs ( lu[l-1+(k-1)*n] ) < fabs ( lu[i-1+(k-1)*n] ) )
{
l = i;
}
}
pivot[k-1] = l;
//
// If the pivot index is zero, the algorithm has failed.
//
if ( lu[l-1+(k-1)*n] == 0.0 )
{
info = k;
return info;
}
//
// Interchange rows L and K if necessary.
//
if ( l != k )
{
temp = lu[l-1+(k-1)*n];
lu[l-1+(k-1)*n] = lu[k-1+(k-1)*n];
lu[k-1+(k-1)*n] = temp;
}
//
// Normalize the values that lie below the pivot entry A(K,K).
//
for ( i = k+1; i <= n; i++ )
{
lu[i-1+(k-1)*n] = -lu[i-1+(k-1)*n] / lu[k-1+(k-1)*n];
}
//
// Row elimination with column indexing.
//
for ( j = k+1; j <= n; j++ )
{
if ( l != k )
{
temp = lu[l-1+(j-1)*n];
lu[l-1+(j-1)*n] = lu[k-1+(j-1)*n];
lu[k-1+(j-1)*n] = temp;
}
for ( i = k+1; i <= n; i++ )
{
lu[i-1+(j-1)*n] = lu[i-1+(j-1)*n] + lu[i-1+(k-1)*n] * lu[k-1+(j-1)*n];
}
}
}
pivot[n-1] = n;
if ( lu[n-1+(n-1)*n] == 0.0 )
{
info = n;
}
return info;
}
//****************************************************************************80
double **r8mat_to_r8rmat ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TO_R8RMAT copies data from an R8MAT to an R8RMAT.
//
// Discussion:
//
// An R8MAT is a column-major array stored as a vector, so
// that element (I,J) of the M by N array is stored in location
// I+J*M.
//
// An R8RMAT is a row-major array that was created by a
// command like:
//
// double **a;
// a = r8rmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 January 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], the data, stored as an R8MAT.
//
// Output, double R8RMAT_TO_R8MAT[M][N], the data, stored as an R8RMAT.
//
{
double **b;
int i;
int j;
b = r8rmat_new ( m, n );
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
b[i][j] = a[i+j*m];
}
}
return b;
}
//****************************************************************************80
double r8mat_trace ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TRACE computes the trace of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The trace of a square matrix is the sum of the diagonal elements.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix A.
//
// Input, double A[N*N], the matrix whose trace is desired.
//
// Output, double R8MAT_TRACE, the trace of the matrix.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + a[i+i*n];
}
return value;
}
//****************************************************************************80
void r8mat_transpose_in_place ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TRANSPOSE_IN_PLACE transposes a square R8MAT in place.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 June 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of the matrix A.
//
// Input/output, double A[N*N], the matrix to be transposed.
//
{
int i;
int j;
double t;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < j; i++ )
{
t = a[i+j*n];
a[i+j*n] = a[j+i*n];
a[j+i*n] = t;
}
}
return;
}
//****************************************************************************80
double *r8mat_transpose_new ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TRANSPOSE_NEW returns the transpose of an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of the matrix A.
//
// Input, double A[M*N], the matrix whose transpose is desired.
//
// Output, double R8MAT_TRANSPOSE_NEW[N*M], the transposed matrix.
//
{
double *b;
int i;
int j;
b = new double[n*m];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
b[j+i*n] = a[i+j*m];
}
}
return b;
}
//****************************************************************************80
void r8mat_transpose_print ( int m, int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TRANSPOSE_PRINT prints an R8MAT, transposed.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], an M by N matrix to be printed.
//
// Input, string TITLE, a title.
//
{
r8mat_transpose_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
//****************************************************************************80
void r8mat_transpose_print_some ( int m, int n, double a[], int ilo, int jlo,
int ihi, int jhi, string title )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 April 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M*N], an M by N matrix to be printed.
//
// Input, int ILO, JLO, the first row and column to print.
//
// Input, int IHI, JHI, the last row and column to print.
//
// Input, string TITLE, a title.
//
{
# define INCX 5
int i;
int i2;
int i2hi;
int i2lo;
int i2lo_hi;
int i2lo_lo;
int inc;
int j;
int j2hi;
int j2lo;
cout << "\n";
cout << title << "\n";
if ( m <= 0 || n <= 0 )
{
cout << "\n";
cout << " (None)\n";
return;
}
if ( ilo < 1 )
{
i2lo_lo = 1;
}
else
{
i2lo_lo = ilo;
}
if ( ihi < m )
{
i2lo_hi = m;
}
else
{
i2lo_hi = ihi;
}
for ( i2lo = i2lo_lo; i2lo <= i2lo_hi; i2lo = i2lo + INCX )
{
i2hi = i2lo + INCX - 1;
if ( m < i2hi )
{
i2hi = m;
}
if ( ihi < i2hi )
{
i2hi = ihi;
}
inc = i2hi + 1 - i2lo;
cout << "\n";
cout << " Row: ";
for ( i = i2lo; i <= i2hi; i++ )
{
cout << setw(7) << i - 1 << " ";
}
cout << "\n";
cout << " Col\n";
cout << "\n";
if ( jlo < 1 )
{
j2lo = 1;
}
else
{
j2lo = jlo;
}
if ( n < jhi )
{
j2hi = n;
}
else
{
j2hi = jhi;
}
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(5) << j - 1 << ":";
for ( i2 = 1; i2 <= inc; i2++ )
{
i = i2lo - 1 + i2;
cout << setw(14) << a[(i-1)+(j-1)*m];
}
cout << "\n";
}
}
return;
# undef INCX
}
//****************************************************************************80
double *r8mat_u_inverse ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_U_INVERSE inverts an upper triangular R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// An upper triangular matrix is a matrix whose only nonzero entries
// occur on or above the diagonal.
//
// The inverse of an upper triangular matrix is an upper triangular matrix.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 September 2005
//
// Author:
//
// FORTRAN77 original version by Albert Nijenhuis, Herbert Wilf.
// C++ version by John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, number of rows and columns in the matrix.
//
// Input, double A[N*N], the upper triangular matrix.
//
// Output, double R8MAT_U_INVERSE[N*N], the inverse matrix.
//
{
double *b;
int i;
int j;
int k;
b = new double[n*n];
for ( j = n-1; 0 <= j; j-- )
{
for ( i = n-1; 0 <= i; i-- )
{
if ( j < i )
{
b[i+j*n] = 0.0;
}
else if ( i == j )
{
b[i+j*n] = 1.0 / a[i+j*n];
}
else
{
b[i+j*n] = 0.0;
for ( k = i+1; k <= j; k++ )
{
b[i+j*n] = b[i+j*n] - a[i+k*n] * b[k+j*n];
}
b[i+j*n] = b[i+j*n] / a[i+i*n];
}
}
}
return b;
}
//****************************************************************************80
double *r8mat_u_solve ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_U_SOLVE solves an upper triangular linear system.
//
// Discussion:
//
// An R8MAT is an MxN array of R8's, stored by (I,J) -> [I+J*M].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 October 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of
// the matrix A.
//
// Input, double A[N*N], the N by N upper triangular matrix.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double R8MAT_U_SOLVE[N], the solution of the linear system.
//
{
int i;
int j;
double *x;
//
// Solve U * x = b.
//
x = new double[n];
for ( i = n - 1; 0 <= i; i-- )
{
x[i] = b[i];
for ( j = i + 1; j < n; j++ )
{
x[i] = x[i] - a[i+j*n] * x[j];
}
x[i] = x[i] / a[i+i*n];
}
return x;
}
//****************************************************************************80
double *r8mat_u1_inverse ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_U1_INVERSE inverts a unit upper triangular R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// A unit upper triangular matrix is a matrix with only 1's on the main
// diagonal, and only 0's below the main diagonal.
//
// The inverse of a unit upper triangular matrix is also
// a unit upper triangular matrix.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 September 2005
//
// Author:
//
// C++ translation by John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, number of rows and columns in the matrix.
//
// Input, double A[N*N], the unit upper triangular matrix.
//
// Output, double R8MAT_U1_INVERSE[N*N), the inverse matrix.
//
{
double *b;
int i;
int j;
int k;
b = new double[n*n];
for ( j = n-1; 0 <= j; j-- )
{
for ( i = n-1; 0 <= i; i-- )
{
if ( j < i )
{
b[i+j*n] = 0.0;
}
else if ( i == j )
{
b[i+j*n] = 1.0;
}
else
{
b[i+j*n] = 0.0;
for ( k = i+1; k <= j; k++ )
{
b[i+j*n] = b[i+j*n] - a[i+k*n] * b[k+j*n];
}
b[i+j*n] = b[i+j*n] / a[i+i*n];
}
}
}
return b;
}
//****************************************************************************80
void r8mat_uniform_01 ( int m, int n, int &seed, double r[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_01 returns a unit pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has
// been updated.
//
// Output, double R[M*N], a matrix of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int j;
int k;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8MAT_UNIFORM_01 - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i+j*m] = ( double ) ( seed ) * 4.656612875E-10;
}
}
return;
}
//****************************************************************************80
double *r8mat_uniform_01_new ( int m, int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_01_NEW returns a unit pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8's, stored as a vector
// in column-major order.
//
// This routine implements the recursion
//
// seed = 16807 * seed mod ( 2^31 - 1 )
// unif = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Springer Verlag, pages 201-202, 1983.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, pages 362-376, 1986.
//
// Philip Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, pages 136-143, 1969.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0, otherwise the output value of SEED
// will still be 0, and R8_UNIFORM will be 0. On output, SEED has
// been updated.
//
// Output, double R8MAT_UNIFORM_01_NEW[M*N], a matrix of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int j;
int k;
double *r;
r = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i+j*m] = ( double ) ( seed ) * 4.656612875E-10;
}
}
return r;
}
//****************************************************************************80
void r8mat_uniform_ab ( int m, int n, double a, double b, int &seed, double r[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_AB returns a scaled pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A, B, the limits of the pseudorandom values.
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has
// been updated.
//
// Output, double R[M*N], a matrix of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int j;
int k;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8MAT_UNIFORM_AB - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i+j*m] = a + ( b - a ) * ( double ) ( seed ) * 4.656612875E-10;
}
}
return;
}
//****************************************************************************80
double *r8mat_uniform_ab_new ( int m, int n, double a, double b, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_AB_NEW returns a new scaled pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A, B, the limits of the pseudorandom values.
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has
// been updated.
//
// Output, double R8MAT_UNIFORM_AB_NEW[M*N], a matrix of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int j;
int k;
double *r;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8MAT_UNIFORM_AB_NEW - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
r = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i+j*m] = a + ( b - a ) * ( double ) ( seed ) * 4.656612875E-10;
}
}
return r;
}
//****************************************************************************80
void r8mat_uniform_abvec ( int m, int n, double a[], double b[], int &seed,
double r[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_ABVEC returns a scaled pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M], B[M], the limits of the pseudorandom values.
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has
// been updated.
//
// Output, double R[M*N], a matrix of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int j;
int k;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8MAT_UNIFORM_ABVEC - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i+j*m] = a[i] + ( b[i] - a[i] ) * ( double ) ( seed ) * 4.656612875E-10;
}
}
return;
}
//****************************************************************************80
double *r8mat_uniform_abvec_new ( int m, int n, double a[], double b[],
int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_ABVEC_NEW returns a new scaled pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double A[M], B[M], the limits of the pseudorandom values.
//
// Input/output, int &SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has
// been updated.
//
// Output, double R8MAT_UNIFORM_ABVEC_NEW[M*N], a matrix of
// pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int j;
int k;
double *r;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8MAT_UNIFORM_ABVEC_NEW - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
r = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i+j*m] = a[i] + ( b[i] - a[i] ) * ( double ) ( seed ) * 4.656612875E-10;
}
}
return r;
}
//****************************************************************************80
double *r8mat_ut_solve ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UT_SOLVE solves a transposed upper triangular linear system.
//
// Discussion:
//
// An R8MAT is an MxN array of R8's, stored by (I,J) -> [I+J*M].
//
// Given the upper triangular matrix A, the linear system to be solved is:
//
// A' * x = b
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 October 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of rows and columns of
// the matrix A.
//
// Input, double A[N*N], the N by N upper triangular matrix.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double R8MAT_UT_SOLVE[N], the solution of the linear system.
//
{
int i;
int j;
double *x;
//
// Solve U' * x = b.
//
x = new double[n];
for ( i = 0; i < n; i++ )
{
x[i] = b[i];
for ( j = 0; j < i; j++ )
{
x[i] = x[i] - a[j+i*n] * x[j];
}
x[i] = x[i] / a[i+i*n];
}
return x;
}
//****************************************************************************80
double *r8mat_vand2 ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_VAND2 returns the N by N row Vandermonde matrix A.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// The row Vandermonde matrix returned by this routine reads "across"
// rather than down. In particular, each row begins with a 1, followed by
// some value X, followed by successive powers of X.
//
// The formula for the matrix entries is:
//
// A(I,J) = X(I)^(J-1)
//
// Properties:
//
// A is nonsingular if, and only if, the X values are distinct.
//
// The determinant of A is
//
// det(A) = product ( 2 <= I <= N ) (
// product ( 1 <= J <= I-1 ) ( ( X(I) - X(J) ) ) ).
//
// The matrix A is generally ill-conditioned.
//
// Example:
//
// N = 5, X = (2, 3, 4, 5, 6)
//
// 1 2 4 8 16
// 1 3 9 27 81
// 1 4 16 64 256
// 1 5 25 125 625
// 1 6 36 216 1296
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix desired.
//
// Input, double X[N], the values that define A.
//
// Output, double R8MAT_VAND2[N*N], the N by N row Vandermonde matrix.
//
{
double *a;
int i;
int j;
a = new double[n*n];
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < n; j++ )
{
if ( j == 0 && x[i] == 0.0 )
{
a[i+j*n] = 1.0;
}
else
{
a[i+j*n] = pow ( x[i], j );
}
}
}
return a;
}
//****************************************************************************80
double r8mat_vtmv ( int m, int n, double x[], double a[], double y[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_VTMV multiplies computes the scalar x' * A * y.
//
// Discussion:
//
// An R8MAT is an MxN array of R8's, stored by (I,J) -> [I+J*M].
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 June 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns of
// the matrix.
//
// Input, double X[N], the first vector factor.
//
// Input, double A[M*N], the M by N matrix.
//
// Input, double Y[M], the second vector factor.
//
// Output, double R8MAT_VTMV, the value of X' * A * Y.
//
{
int i;
int j;
double vtmv;
vtmv = 0.0;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
vtmv = vtmv + x[i] * a[i+j*m] * y[j];
}
}
return vtmv;
}
//****************************************************************************80
void r8mat_zeros ( int m, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_ZEROS zeroes an R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Output, double A[M*N], a matrix of zeroes.
//
{
int i;
int j;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
a[i+j*m] = 0.0;
}
}
return;
}
//****************************************************************************80
double *r8mat_zeros_new ( int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_ZEROS_NEW returns a new zeroed R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Output, double R8MAT_ZEROS_NEW[M*N], the new zeroed matrix.
//
{
double *a;
int i;
int j;
a = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
a[i+j*m] = 0.0;
}
}
return a;
}
//****************************************************************************80
double r8plu_det ( int n, int pivot[], double lu[] )
//****************************************************************************80
//
// Purpose:
//
// R8PLU_DET computes the determinant of a real PLU matrix.
//
// Discussion:
//
// The matrix should have been factored by R8MAT_TO_R8PLU.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2003
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
// LINPACK User's Guide,
// SIAM, 1979
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, int PIVOT[N], the pivot vector computed by R8MAT_TO_R8PLU.
//
// Input, double LU[N*N], the LU factors computed by R8MAT_TO_R8PLU.
//
// Output, double R8PLU_DET, the determinant of the matrix.
//
{
double det;
int i;
det = 1.0;
for ( i = 0; i < n; i++ )
{
det = det * lu[i+i*n];
if ( pivot[i] != i+1 )
{
det = -det;
}
}
return det;
}
//****************************************************************************80
void r8plu_inverse ( int n, int pivot[], double lu[], double a_inverse[] )
//****************************************************************************80
//
// Purpose:
//
// R8PLU_INVERSE computes the inverse of a real PLU matrix.
//
// Discussion:
//
// The matrix should have been factored by R8MAT_TO_R8PLU.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix A.
//
// Input, int PIVOT[N], the pivot vector from R8MAT_TO_R8PLU.
//
// Input, double LU[N*N], the LU factors computed by R8MAT_TO_R8PLU.
//
// Output, double A_INVERSE[N*N], the inverse of the original matrix
// A that was factored by R8MAT_TO_R8PLU.
//
{
int i;
int j;
int k;
double temp;
double *work;
//
work = new double[n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
a_inverse[i+j*n] = lu[i+j*n];
}
}
//
// Compute Inverse(U).
//
for ( k = 1; k <= n; k++ )
{
a_inverse[k-1+(k-1)*n] = 1.0 / a_inverse[k-1+(k-1)*n];
for ( i = 1; i <= k-1; i++ )
{
a_inverse[i-1+(k-1)*n] = -a_inverse[i-1+(k-1)*n] * a_inverse[k-1+(k-1)*n];
}
for ( j = k+1; j <= n; j++ )
{
temp = a_inverse[k-1+(j-1)*n];
a_inverse[k-1+(j-1)*n] = 0.0;
for ( i = 1; i <= k; i++ )
{
a_inverse[i-1+(j-1)*n] = a_inverse[i-1+(j-1)*n]
+ temp * a_inverse[i-1+(k-1)*n];
}
}
}
//
// Form Inverse(U) * Inverse(L).
//
for ( k = n-1; 1 <= k; k-- )
{
for ( i = k+1; i <= n; i++ )
{
work[i-1] = a_inverse[i-1+(k-1)*n];
a_inverse[i-1+(k-1)*n] = 0.0;
}
for ( j = k+1; j <= n; j++ )
{
for ( i = 1; i <= n; i++ )
{
a_inverse[i-1+(k-1)*n] = a_inverse[i-1+(k-1)*n]
+ a_inverse[i-1+(j-1)*n] * work[j-1];
}
}
if ( pivot[k-1] != k )
{
for ( i = 1; i <= n; i++ )
{
temp = a_inverse[i-1+(k-1)*n];
a_inverse[i-1+(k-1)*n] = a_inverse[i-1+(pivot[k-1]-1)*n];
a_inverse[i-1+(pivot[k-1]-1)*n] = temp;
}
}
}
delete [] work;
return;
}
//****************************************************************************80
void r8plu_mul ( int n, int pivot[], double lu[], double x[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8PLU_MUL computes A * x using the PLU factors of A.
//
// Discussion:
//
// It is assumed that R8MAT_TO_R8PLU has computed the PLU factors of
// the matrix A.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, int PIVOT[N], the pivot vector computed by R8MAT_TO_R8PLU.
//
// Input, double LU[N*N], the matrix factors computed by R8MAT_TO_R8PLU.
//
// Input, double X[N], the vector to be multiplied.
//
// Output, double B[N], the result of the multiplication.
//
{
int i;
int j;
int k;
double temp;
//
for ( i = 0; i < n; i++ )
{
b[i] = x[i];
}
//
// Y = U * X.
//
for ( j = 1; j <= n; j++ )
{
for ( i = 0; i < j-1; i++ )
{
b[i] = b[i] + lu[i+(j-1)*n] * b[j-1];
}
b[j-1] = lu[j-1+(j-1)*n] * b[j-1];
}
//
// B = PL * Y = PL * U * X = A * x.
//
for ( j = n-1; 1 <= j; j-- )
{
for ( i = j; i < n; i++ )
{
b[i] = b[i] - lu[i+(j-1)*n] * b[j-1];
}
k = pivot[j-1];
if ( k != j )
{
temp = b[k-1];
b[k-1] = b[j-1];
b[j-1] = temp;
}
}
return;
}
//****************************************************************************80
void r8plu_sol ( int n, int pivot[], double lu[], double b[], double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8PLU_SOL solves a linear system A*x=b from the PLU factors.
//
// Discussion:
//
// The PLU factors should have been computed by R8MAT_TO_R8PLU.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
//
// Input, int PIVOT[N], the pivot vector from R8MAT_TO_R8PLU.
//
// Input, double LU[N*N], the LU factors from R8MAT_TO_R8PLU.
//
// Input, double B[N], the right hand side vector.
//
// Output, double X[N], the solution vector.
//
{
int i;
int j;
int k;
double temp;
//
// Solve PL * Y = B.
//
for ( i = 0; i < n; i++ )
{
x[i] = b[i];
}
for ( k = 1; k <= n-1; k++ )
{
j = pivot[k-1];
if ( j != k )
{
temp = x[j-1];
x[j-1] = x[k-1];
x[k-1] = temp;
}
for ( i = k+1; i <= n; i++ )
{
x[i-1] = x[i-1] + lu[i-1+(k-1)*n] * x[k-1];
}
}
//
// Solve U * X = Y.
//
for ( k = n; 1 <= k; k-- )
{
x[k-1] = x[k-1] / lu[k-1+(k-1)*n];
for ( i = 1; i <= k-1; i++ )
{
x[i-1] = x[i-1] - lu[i-1+(k-1)*n] * x[k-1];
}
}
return;
}
//****************************************************************************80
void r8plu_to_r8mat ( int n, int pivot[], double lu[], double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8PLU_TO_R8MAT recovers the matrix A that was factored by R8MAT_TO_R8PLU.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, int PIVOT[N], the pivot vector computed by R8MAT_TO_R8PLU.
//
// Input, double LU[N*N], the matrix factors computed by R8MAT_TO_R8PLU.
//
// Output, double A[N*N], the matrix whose factors are represented by
// LU and PIVOT.
//
{
int i;
int j;
int k;
double temp;
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < n; i++ )
{
if ( i == j )
{
a[i+j*n] = 1.0;
}
else
{
a[i+j*n] = 0.0;
}
}
}
for ( j = 1; j <= n; j++ )
{
for ( i = 1; i <= n; i++ )
{
for ( k = 1; k <= i-1; k++ )
{
a[k-1+(j-1)*n] = a[k-1+(j-1)*n] + lu[k-1+(i-1)*n] * a[i-1+(j-1)*n];
}
a[i-1+(j-1)*n] = lu[i-1+(i-1)*n] * a[i-1+(j-1)*n];
}
//
// B = PL * Y = PL * U * X = A * x.
//
for ( i = n-1; 1 <= i; i-- )
{
for ( k = i+1; k <= n; k++ )
{
a[k-1+(j-1)*n] = a[k-1+(j-1)*n] - lu[k-1+(i-1)*n] * a[i-1+(j-1)*n];
}
k = pivot[i-1];
if ( k != i )
{
temp = a[k-1+(j-1)*n];
a[k-1+(j-1)*n] = a[i-1+(j-1)*n];
a[i-1+(j-1)*n] = temp;
}
}
}
return;
}
//****************************************************************************80
int r8poly_degree ( int na, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_DEGREE returns the degree of a polynomial.
//
// Discussion:
//
// The degree of a polynomial is the index of the highest power
// of X with a nonzero coefficient.
//
// The degree of a constant polynomial is 0. The degree of the
// zero polynomial is debatable, but this routine returns the
// degree as 0.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NA, the dimension of A.
//
// Input, double A[NA+1], the coefficients of the polynomials.
//
// Output, int R8POLY_DEGREE, the degree of A.
//
{
int degree;
degree = na;
while ( 0 < degree )
{
if ( a[degree] != 0.0 )
{
return degree;
}
degree = degree - 1;
}
return degree;
}
//****************************************************************************80
double *r8poly_deriv ( int n, double c[], int p )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_DERIV returns the derivative of a polynomial.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the degree of the polynomial.
//
// Input, double C[N+1], the polynomial coefficients.
// C[I] is the coefficient of X^I.
//
// Input, int P, the order of the derivative.
// 0 means no derivative is taken.
// 1 means first derivative,
// 2 means second derivative and so on.
// Values of P less than 0 are meaningless. Values of P greater
// than N are meaningful, but the code will behave as though the
// value of P was N+1.
//
// Output, double R8POLY_DERIV CP[N-P+1], the polynomial coefficients of
// the derivative.
//
{
double *cp;
double *cp_temp;
int d;
int i;
if ( n < p )
{
return NULL;
}
cp_temp = r8vec_copy_new ( n+1, c );
for ( d = 1; d <= p; d++ )
{
for ( i = 0; i <= n-d; i++ )
{
cp_temp[i] = ( double ) ( i + 1 ) * cp_temp[i+1];
}
cp_temp[n-d+1] = 0.0;
}
cp = r8vec_copy_new ( n - p + 1, cp_temp );
delete [] cp_temp;
return cp;
}
//****************************************************************************80
double r8poly_lagrange_0 ( int npol, double xpol[], double xval )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_LAGRANGE_0 evaluates the Lagrange factor at a point.
//
// Discussion:
//
// W(X) = Product ( 1 <= I <= NPOL ) ( X - XPOL(I) )
//
// Discussion:
//
// For a set of points XPOL(I), 1 <= I <= NPOL, the IPOL-th Lagrange basis
// polynomial L(IPOL)(X), has the property:
//
// L(IPOL)( XPOL(J) ) = delta ( IPOL, J )
//
// and may be expressed as:
//
// L(IPOL)(X) = W(X) / ( ( X - XPOL(IPOL) ) * W'(XPOL(IPOL)) )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPOL, the number of abscissas.
// NPOL must be at least 1.
//
// Input, double XPOL[NPOL], the abscissas, which should be distinct.
//
// Input, double XVAL, the point at which the Lagrange factor is to be
// evaluated.
//
// Output, double R8POLY_LAGRANGE_0, the value of the Lagrange factor at XVAL.
//
{
int i;
double wval;
wval = 1.0;
for ( i = 0; i < npol; i++ )
{
wval = wval * ( xval - xpol[i] );
}
return wval;
}
//****************************************************************************80
double r8poly_lagrange_1 ( int npol, double xpol[], double xval )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_LAGRANGE_1 evaluates the first derivative of the Lagrange factor.
//
// Discussion:
//
// W(XPOL(1:NPOL))(X) = Product ( 1 <= I <= NPOL ) ( X - XPOL(I) )
//
// W'(XPOL(1:NPOL))(X)
// = Sum ( 1 <= J <= NPOL ) Product ( I /= J ) ( X - XPOL(I) )
//
// We also have the recursion:
//
// W'(XPOL(1:NPOL))(X) = d/dX ( ( X - XPOL(NPOL) ) * W(XPOL(1:NPOL-1))(X) )
// = W(XPOL(1:NPOL-1))(X)
// + ( X - XPOL(NPOL) ) * W'(XPOL(1:NPOL-1))(X)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPOL, the number of abscissas.
//
// Input, double XPOL[NPOL], the abscissas, which should be distinct.
//
// Input, double XVAL, the point at which the Lagrange factor is to be
// evaluated.
//
// Output, double R8POLY_LAGRANGE_1, the derivative of W with respect to XVAL.
//
{
double dwdx;
int i;
double w;
dwdx = 0.0;
w = 1.0;
for ( i = 0; i < npol; i++ )
{
dwdx = w + ( xval - xpol[i] ) * dwdx;
w = w * ( xval - xpol[i] );
}
return dwdx;
}
//****************************************************************************80
double r8poly_lagrange_2 ( int npol, double xpol[], double xval )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_LAGRANGE_2 evaluates the second derivative of the Lagrange factor.
//
// Discussion:
//
// W(X) = Product ( 1 <= I <= NPOL ) ( X - XPOL(I) )
//
// W'(X) = Sum ( 1 <= J <= NPOL )
// Product ( I /= J ) ( X - XPOL(I) )
//
// W"(X) = Sum ( 1 <= K <= NPOL )
// Sum ( J =/ K )
// Product ( I /= K, J ) ( X - XPOL(I) )
//
// For a set of points XPOL(I), 1 <= I <= NPOL, the IPOL-th Lagrange basis
// polynomial L(IPOL)(X), has the property:
//
// L(IPOL)( XPOL(J) ) = delta ( IPOL, J )
//
// and may be expressed as:
//
// L(IPOL)(X) = W(X) / ( ( X - XPOL(IPOL) ) * W'(XPOL(IPOL)) )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPOL, the number of abscissas.
// NPOL must be at least 1.
//
// Input, double XPOL[NPOL], the abscissas, which should be distinct.
//
// Input, double XVAL, the point at which the Lagrange factor is to be
// evaluated.
//
// Output, double R8POLY_LAGRANGE_2, the second derivative of W with respect to XVAL.
//
{
double dw2dx2;
int i;
int j;
int k;
double term;
dw2dx2 = 0.0;
for ( k = 0; k < npol; k++ )
{
for ( j = 0; j < npol; j++ )
{
if ( j != k )
{
term = 1.0;
for ( i = 0; i < npol; i++ )
{
if ( i != j && i != k )
{
term = term * ( xval - xpol[i] );
}
}
dw2dx2 = dw2dx2 + term;
}
}
}
return dw2dx2;
}
//****************************************************************************80
double *r8poly_lagrange_coef ( int npol, int ipol, double xpol[] )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_LAGRANGE_COEF returns the coefficients of a Lagrange polynomial.
//
// Discussion:
//
// Given NPOL distinct abscissas, XPOL(*), the IPOL-th Lagrange
// polynomial P(IPOL)(X) is defined as the polynomial of degree
// NPOL - 1 which is 1 at XPOL(IPOL) and 0 at the NPOL - 1 other
// abscissas.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPOL, the number of abscissas.
// NPOL must be at least 1.
//
// Input, int IPOL, the index of the polynomial to evaluate.
// IPOL must be between 1 and NPOL.
//
// Input, double XPOL[NPOL], the abscissas of the Lagrange polynomials.
// The entries in XPOL must be distinct.
//
// Output, double R8POLY_LAGRANGE_COEF[NPOL], the polynomial coefficients
// of the IPOL-th Lagrange polynomial.
//
{
int i;
int index;
int j;
double *pcof;
//
// Make sure IPOL is legal.
//
if ( ipol < 1 || npol < ipol )
{
cerr << "\n";
cerr << "R8POLY_LAGRANGE_COEF - Fatal error!\n";
cerr << " 1 <= IPOL <= NPOL is required.\n";
cerr << " but IPOL = " << ipol << "\n";
cerr << " and NPOL = " << npol << "\n";
exit ( 1 );
}
//
// Check that the abscissas are distinct.
//
if ( !r8vec_distinct ( npol, xpol ) )
{
cerr << "\n";
cerr << "R8POLY_LAGRANGE_COEF - Fatal error!\n";
cerr << " Two entries of XPOL are equal:\n";
exit ( 1 );
}
pcof = new double[npol];
pcof[0] = 1.0;
for ( i = 1; i < npol; i++ )
{
pcof[i] = 0.0;
}
index = 0;
for ( i = 1; i <= npol; i++ )
{
if ( i != ipol )
{
index = index + 1;
for ( j = index; 0 <= j; j-- )
{
pcof[j] = - xpol[i-1] * pcof[j] / ( xpol[ipol-1] - xpol[i-1] );
if ( 0 < j )
{
pcof[j] = pcof[j] + pcof[j-1] / ( xpol[ipol-1] - xpol[i-1] );
}
}
}
}
return pcof;
}
//****************************************************************************80
void r8poly_lagrange_factor ( int npol, double xpol[], double xval,
double *wval, double *dwdx )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_LAGRANGE_FACTOR evaluates the polynomial Lagrange factor at a point.
//
// Discussion:
//
// Suppose F(X) is at least N times continuously differentiable in the
// interval [A,B]. Pick NPOL distinct points XPOL(I) in [A,B] and compute
// the interpolating polynomial P(X) of order NPOL ( and degree NPOL-1)
// which passes through all the points ( XPOL(I), F(XPOL(I)) ).
// Then in the interval [A,B], the maximum error
//
// abs ( F(X) - P(X) )
//
// is bounded by:
//
// C * FNMAX * W(X)
//
// where
//
// C is a constant,
// FNMAX is the maximum value of the NPOL-th derivative of F in [A,B],
// W(X) is the Lagrange factor.
//
// Thus, the value of W(X) is useful as part of an estimated bound
// for the interpolation error.
//
// The formula is:
//
// W(X) = Product ( 1 <= I <= NPOL ) ( X - XPOL(I) )
//
// Note that the Chebyshev abscissas have the property that they minimize
// the value of W(X) over the interval [A,B]. Hence, if the abscissas may
// be chosen arbitrarily, the Chebyshev abscissas have this advantage over
// other choices.
//
// For a set of points XPOL[I], 0 <= I <= NPOL-1, the IPOL-th Lagrange basis
// polynomial L(IPOL)(X), has the property:
//
// L(IPOL)( XPOL(J) ) = delta ( IPOL, J )
//
// and may be expressed as:
//
// L(IPOL)(X) = W(X) / ( ( X - XPOL[IPOL] ) * W'(XPOL[IPOL]) )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 May 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPOL, the number of abscissas.
// NPOL must be at least 1.
//
// Input, double XPOL[NPOL], the abscissas, which should be distinct.
//
// Input, double XVAL, the point at which the Lagrange factor is to be evaluated.
//
// Output, double *WVAL, the value of the Lagrange factor at XVAL.
//
// Output, double *DWDX, the derivative of W with respect to XVAL.
//
{
int i;
int j;
double term;
*wval = 1.0;
for ( i = 0; i < npol; i++ )
{
*wval = *wval * ( xval - xpol[i] );
}
*dwdx = 0.0;
for ( i = 0; i < npol; i++ )
{
term = 1.0;
for ( j = 0; j < npol; j++ )
{
if ( i != j )
{
term = term * ( xval - xpol[j] );
}
}
*dwdx = *dwdx + term;
}
return;
}
//****************************************************************************80
int r8poly_lagrange_val ( int npol, int ipol, double xpol[], double xval,
double *pval, double *dpdx )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_LAGRANGE_VAL evaluates the IPOL-th Lagrange polynomial.
//
// Discussion:
//
// Given NPOL distinct abscissas, XPOL[*], the IPOL-th Lagrange
// polynomial P(IPOL)(X) is defined as the polynomial of degree
// NPOL - 1 which is 1 at XPOL[IPOL] and 0 at the NPOL - 1 other
// abscissas.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 May 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NPOL, the number of abscissas.
// NPOL must be at least 1.
//
// Input, int IPOL, the index of the polynomial to evaluate.
// IPOL must be between 0 and NPOL-1.
//
// Input, double XPOL[NPOL], the abscissas of the Lagrange polynomials.
// The entries in XPOL must be distinct.
//
// Input, double XVAL, the point at which the IPOL-th Lagrange polynomial
// is to be evaluated.
//
// Output, double *PVAL, the value of the IPOL-th Lagrange polynomial at XVAL.
//
// Output, double *DPDX, the derivative of the IPOL-th Lagrange polynomial at XVAL.
//
// Output, int R8POLY_LAGRANGE_VAL, 0 if no error.
//
{
int i;
int j;
double p2;
//
// Make sure IPOL is legal.
//
if ( ipol < 0 || npol-1 < ipol )
{
cerr << "\n";
cerr << "R8POLY_LAGRANGE_VAL - Fatal error!\n";
cerr << " 0 <= IPOL <= NPOL-1 is required.\n";
exit ( 1 );
}
//
// Check that the abscissas are distinct.
//
for ( i = 1; i < npol; i++ )
{
for ( j = 0; j < i; j++ )
{
if ( xpol[i] == xpol[j] )
{
cerr << "\n";
cerr << "R8POLY_LAGRANGE_VAL - Fatal error!\n";
cerr << " Two entries of XPOL are equal:\n";
cerr << " XPOL(" << i << ") = " << xpol[i] << ".\n";
cerr << " XPOL(" << j << ") = " << xpol[j] << ".\n";
exit ( 1 );
}
}
}
//
// Evaluate the polynomial.
//
*pval = 1.0;
for ( i = 0; i < npol; i++ )
{
if ( i != ipol )
{
*pval = *pval * ( xval - xpol[i] ) / ( xpol[ipol] - xpol[i] );
}
}
//
// Evaluate the derivative, which can be found by summing up the result
// of differentiating one factor at a time, successively.
//
*dpdx = 0.0;
for ( i = 0; i < npol; i++ )
{
if ( i != ipol )
{
p2 = 1.0;
for ( j = 0; j < npol; j++ )
{
if ( j == i )
{
p2 = p2 / ( xpol[ipol] - xpol[j] );
}
else if ( j != ipol )
{
p2 = p2 * ( xval - xpol[j] ) / ( xpol[ipol] - xpol[j] );
}
}
*dpdx = *dpdx + p2;
}
}
return 0;
}
//****************************************************************************80
int r8poly_order ( int na, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_ORDER returns the order of a polynomial.
//
// Discussion:
//
// The order of a polynomial is one more than the degree.
//
// The order of a constant polynomial is 1. The order of the
// zero polynomial is debatable, but this routine returns the
// order as 1.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NA, the dimension of A.
//
// Input, double A[NA+1], the coefficients of the polynomials.
//
// Output, int R8POLY_ORDER, the order of A.
//
{
int order;
order = na + 1;
while ( 1 < order )
{
if ( a[order-1] != 0.0 )
{
return order;
}
order = order - 1;
}
return order;
}
//****************************************************************************80
void r8poly_print ( int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_PRINT prints out a polynomial.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 July 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of A.
//
// Input, double A[N+1], the polynomial coefficients.
// A(0) is the constant term and
// A(N) is the coefficient of X^N.
//
// Input, string TITLE, a title.
//
{
int i;
double mag;
int n2;
char plus_minus;
if ( 0 < title.length ( ) )
{
cout << "\n";
cout << title << "\n";
}
cout << "\n";
if ( n < 0 )
{
cout << " p(x) = 0\n";
return;
}
if ( a[n] < 0.0 )
{
plus_minus = '-';
}
else
{
plus_minus = ' ';
}
mag = fabs ( a[n] );
if ( 2 <= n )
{
cout << " p(x) = " << plus_minus
<< setw(14) << mag << " * x ^ " << n << "\n";
}
else if ( n == 1 )
{
cout << " p(x) = " << plus_minus
<< setw(14) << mag << " * x\n";
}
else if ( n == 0 )
{
cout << " p(x) = " << plus_minus
<< setw(14) << mag << "\n";
}
for ( i = n - 1; 0 <= i; i-- )
{
if ( a[i] < 0.0 )
{
plus_minus = '-';
}
else
{
plus_minus = '+';
}
mag = fabs ( a[i] );
if ( mag != 0.0 )
{
if ( 2 <= i )
{
cout << " " << plus_minus
<< setw(14) << mag << " * x ^ " << i << "\n";
}
else if ( i == 1 )
{
cout << " " << plus_minus
<< setw(14) << mag << " * x\n";
}
else if ( i == 0 )
{
cout << " " << plus_minus
<< setw(14) << mag << "\n";
}
}
}
return;
}
//****************************************************************************80
void r8poly_shift ( double scale, double shift, int n, double poly_cof[] )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_SHIFT adjusts the coefficients of a polynomial for a new argument.
//
// Discussion:
//
// Assuming P(X) is a polynomial in the argument X, of the form:
//
// P(X) =
// C(N) * X^N
// + ...
// + C(1) * X
// + C(0),
//
// and that Z is related to X by the formula:
//
// Z = SCALE * X + SHIFT
//
// then this routine computes coefficients C for the polynomial Q(Z):
//
// Q(Z) =
// C(N) * Z^N
// + ...
// + C(1) * Z
// + C(0)
//
// so that:
//
// Q(Z(X)) = P(X)
//
// Example:
//
// P(X) = 2 * X^2 - X + 6
//
// Z = 2.0 * X + 3.0
//
// Q(Z) = 0.5 * Z^2 - 3.5 * Z + 12
//
// Q(Z(X)) = 0.5 * ( 4.0 * X^2 + 12.0 * X + 9 )
// - 3.5 * ( 2.0 * X + 3 )
// + 12
//
// = 2.0 * X^2 - 1.0 * X + 6
//
// = P(X)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 September 2005
//
// Reference:
//
// Press, Flannery, Teukolsky, Vetterling,
// Numerical Recipes: The Art of Scientific Computing,
// Cambridge University Press.
//
// Parameters:
//
// Input, double SHIFT, SCALE, the shift and scale applied to X,
// so that Z = SCALE * X + SHIFT.
//
// Input, int N, the number of coefficients.
//
// Input/output, double POLY_COF[N+1].
// On input, the coefficient array in terms of the X variable.
// On output, the coefficient array in terms of the Z variable.
//
{
int i;
int j;
for ( i = 1; i <= n; i++ )
{
for ( j = i; j <= n; j++ )
{
poly_cof[j] = poly_cof[j] / scale;
}
}
for ( i = 0; i <= n - 1; i++ )
{
for ( j = n - 1; i <= j; j-- )
{
poly_cof[j] = poly_cof[j] - shift * poly_cof[j+1];
}
}
return;
}
//****************************************************************************80
double r8poly_value_horner ( int m, double c[], double x )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_VALUE_HORNER evaluates a polynomial using Horner's method.
//
// Discussion:
//
// The polynomial
//
// p(x) = c0 + c1 * x + c2 * x^2 + ... + cm * x^m
//
// is to be evaluated at the value X.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 January 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the degree of the polynomial.
//
// Input, double C[M+1], the coefficients of the polynomial.
// A[0] is the constant term.
//
// Input, double X, the point at which the polynomial is to be evaluated.
//
// Output, double R8POLY_VALUE_HORNER, the value of the polynomial at X.
//
{
int i;
double value;
value = c[m];
for ( i = m - 1; 0 <= i; i-- )
{
value = value * x + c[i];
}
return value;
}
//****************************************************************************80
double *r8poly_values_horner ( int m, double c[], int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_VALUES_HORNER evaluates a polynomial using Horner's method.
//
// Discussion:
//
// The polynomial
//
// p(x) = c0 + c1 * x + c2 * x^2 + ... + cm * x^m
//
// is to be evaluated at the vector of values X.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 December 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the degree.
//
// Input, double C[M+1], the polynomial coefficients.
// C[I] is the coefficient of X^I.
//
// Input, int N, the number of evaluation points.
//
// Input, double X[N], the evaluation points.
//
// Output, double R8POLY_VALUES_HORNER[N], the polynomial values.
//
{
int i;
int j;
double *p;
p = new double[n];
for ( j = 0; j < n; j++ )
{
p[j] = c[m];
}
for ( i = m - 1; 0 <= i; i-- )
{
for ( j = 0; j < n; j++ )
{
p[j] = p[j] * x[j] + c[i];
}
}
return p;
}
//****************************************************************************80
double *r8poly_value_2d ( int m, double c[], int n, double x[], double y[] )
//****************************************************************************80
//
// Purpose:
//
// R8POLY_VALUE_2D evaluates a polynomial in 2 variables, X and Y.
//
// Discussion:
//
// We assume the polynomial is of total degree M, and has the form:
//
// p(x,y) = c00
// + c10 * x + c01 * y
// + c20 * x^2 + c11 * xy + c02 * y^2
// + ...
// + cm0 * x^(m) + ... + c0m * y^m.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the degree of the polynomial.
//
// Input, double C[T(M+1)], the polynomial coefficients.
// C[0] is the constant term. T(M+1) is the M+1-th triangular number.
// The coefficients are stored consistent with the following ordering
// of monomials: 1, X, Y, X^2, XY, Y^2, X^3, X^2Y, XY^2, Y^3, X^4, ...
//
// Input, int N, the number of evaluation points.
//
// Input, double X[N], Y[N], the evaluation points.
//
// Output, double R8POLY_VALUE_2D[N], the value of the polynomial at the
// evaluation points.
//
{
int ex;
int ey;
int i;
int j;
double *p;
int s;
p = ( double * ) malloc ( n * sizeof ( double ) );
for ( i = 0; i < n; i++ )
{
p[i] = 0.0;
}
j = 0;
for ( s = 0; s <= m; s++ )
{
for ( ex = s; 0 <= ex; ex-- )
{
ey = s - ex;
for ( i = 0; i < n; i++ )
{
p[i] = p[i] + c[j] * pow ( x[i], ex ) * pow ( y[i], ey );
}
j = j + 1;
}
}
return p;
}
//****************************************************************************80
int r8poly2_ex ( double x1, double y1, double x2, double y2, double x3,
double y3, double *x, double *y )
//****************************************************************************80
//
// Purpose:
//
// R8POLY2_EX finds the extremal point of a parabola determined by three points.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X1, Y1, X2, Y2, X3, Y3, the coordinates of three points
// on the parabola. X1, X2 and X3 must be distinct.
//
// Output, double *X, *Y, the X coordinate of the extremal point of the
// parabola, and the value of the parabola at that point.
//
// Output, int R8POLY2_EX, error flag.
// 0, no error.
// 1, two of the X values are equal.
// 2, the data lies on a straight line; there is no finite extremal
// point.
// 3, the data lies on a horizontal line; every point is "extremal".
//
{
double bot;
*x = 0.0;
*y = 0.0;
if ( x1 == x2 || x2 == x3 || x3 == x1 )
{
return 1;
}
if ( y1 == y2 && y2 == y3 && y3 == y1 )
{
*x = x1;
*y = y1;
return 3;
}
bot = ( x2 - x3 ) * y1 + ( x3 - x1 ) * y2 + ( x1 - x2 ) * y3;
if ( bot == 0.0 )
{
return 2;
}
*x = 0.5 * (
x1 * x1 * ( y3 - y2 )
+ x2 * x2 * ( y1 - y3 )
+ x3 * x3 * ( y2 - y1 ) ) /
( ( x2 - x3 ) * y1 + ( x3 - x1 ) * y2 + ( x1 - x2 ) * y3 );
*y = - (
( *x - x2 ) * ( *x - x3 ) * ( x2 - x3 ) * y1
+ ( *x - x1 ) * ( *x - x3 ) * ( x3 - x1 ) * y2
+ ( *x - x1 ) * ( *x - x2 ) * ( x1 - x2 ) * y3 ) /
( ( x1 - x2 ) * ( x2 - x3 ) * ( x3 - x1 ) );
return 0;
}
//****************************************************************************80
int r8poly2_ex2 ( double x1, double y1, double x2, double y2, double x3,
double y3, double *x, double *y, double *a, double *b, double *c )
//****************************************************************************80
//
// Purpose:
//
// R8POLY2_EX2 finds the extremal point of a parabola determined by three points.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X1, Y1, X2, Y2, X3, Y3, the coordinates of three points
// on the parabola. X1, X2 and X3 must be distinct.
//
// Output, double *X, *Y, the X coordinate of the extremal point of the
// parabola, and the value of the parabola at that point.
//
// Output, double *A, *B, *C, the coefficients that define the parabola:
// P(X) = A * X^2 + B * X + C.
//
// Output, int R8POLY2_EX2, error flag.
// 0, no error.
// 1, two of the X values are equal.
// 2, the data lies on a straight line; there is no finite extremal
// point.
// 3, the data lies on a horizontal line; any point is an "extremal point".
//
{
double v[3*3];
double *w;
*a = 0.0;
*b = 0.0;
*c = 0.0;
*x = 0.0;
*y = 0.0;
if ( x1 == x2 || x2 == x3 || x3 == x1 )
{
return 1;
}
if ( y1 == y2 && y2 == y3 && y3 == y1 )
{
*x = x1;
*y = y1;
return 3;
}
//
// Set up the Vandermonde matrix.
//
v[0+0*3] = 1.0;
v[0+1*3] = x1;
v[0+2*3] = x1 * x1;
v[1+0*3] = 1.0;
v[1+1*3] = x2;
v[1+2*3] = x2 * x2;
v[2+0*3] = 1.0;
v[2+1*3] = x3;
v[2+2*3] = x3 * x3;
//
// Get the inverse.
//
w = r8mat_inverse_3d ( v );
//
// Compute the parabolic coefficients.
//
*c = w[0+0*3] * y1 + w[0+1*3] * y2 + w[0+2*3] * y3;
*b = w[1+0*3] * y1 + w[1+1*3] * y2 + w[1+2*3] * y3;
*a = w[2+0*3] * y1 + w[2+1*3] * y2 + w[2+2*3] * y3;
//
// Determine the extremal point.
//
if ( *a == 0.0 )
{
return 2;
}
*x = - *b / ( 2.0 * *a );
*y = *a * *x * *x + *b * *x + *c;
return 0;
}
//****************************************************************************80
void r8poly2_rroot ( double a, double b, double c, double *r1, double *r2 )
//****************************************************************************80
//
// Purpose:
//
// R8POLY2_RROOT returns the real parts of the roots of a quadratic polynomial.
//
// Example:
//
// A B C roots R1 R2
// -- -- -- ------------------ -- --
// 1 -4 3 1 3 1 3
// 1 0 4 2*i - 2*i 0 0
// 2 -6 5 3 + i 3 - i 3 3
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A, B, C, the coefficients of the quadratic
// polynomial A * X^2 + B * X + C = 0 whose roots are desired.
// A must not be zero.
//
// Output, double *R1, *R2, the real parts of the roots
// of the polynomial.
//
{
double disc;
double q;
if ( a == 0.0 )
{
cerr << "\n";
cerr << "R8POLY2_RROOT - Fatal error!\n";
cerr << " The coefficient A is zero.\n";
exit ( 1 );
}
disc = b * b - 4.0 * a * c;
disc = r8_max ( disc, 0.0 );
q = ( b + r8_sign ( b ) * sqrt ( disc ) );
*r1 = -0.5 * q / a;
*r2 = -2.0 * c / q;
return;
}
//****************************************************************************80
void r8poly2_val ( double x1, double y1, double x2, double y2,
double x3, double y3, double x, double *y, double *yp, double *ypp )
//****************************************************************************80
//
// Purpose:
//
// R8POLY2_VAL evaluates a parabola defined by three data values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X1, Y1, X2, Y2, X3, Y3, three pairs of data values.
// If the X values are distinct, then all the Y values represent
// actual values of the parabola.
//
// Three special cases are allowed:
//
// X1 = X2 =/= X3: Y2 is the derivative at X1;
// X1 =/= X2 = X3: Y3 is the derivative at X3;
// X1 = X2 = X3: Y2 is the derivative at X1, and
// Y3 is the second derivative at X1.
//
// Input, double X, an abscissa at which the parabola is to be
// evaluated.
//
// Output, double *Y, *YP, *YPP, the values of the parabola and
// its first and second derivatives at X.
//
{
int distinct;
double dif1;
double dif2;
double temp;
//
// If any X's are equal, put them and the Y data first.
//
if ( x1 == x2 && x2 == x3 )
{
distinct = 1;
}
else if ( x1 == x2 )
{
distinct = 2;
}
else if ( x1 == x3 )
{
cerr << "\n";
cerr << "R8POLY2_VAL - Fatal error!\n";
cerr << " X1 = X3 =/= X2.\n";
return;
}
else if ( x2 == x3 )
{
distinct = 2;
temp = x1;
x1 = x3;
x3 = temp;
temp = y1;
y1 = y2;
y2 = y3;
y3 = y1;
}
else
{
distinct = 3;
}
//
// Set up the coefficients.
//
if ( distinct == 1 )
{
dif1 = y2;
dif2 = 0.5 * y3;
}
else if ( distinct == 2 )
{
dif1 = y2;
dif2 = ( ( y3 - y1 ) / ( x3 - x1 )
- y2 ) / ( x3 - x2 );
}
else if ( distinct == 3 )
{
dif1 = ( y2 - y1 ) / ( x2 - x1 );
dif2 = ( ( y3 - y1 ) / ( x3 - x1 )
- ( y2 - y1 ) / ( x2 - x1 ) ) / ( x3 - x2 );
}
//
// Evaluate.
//
*y = y1 + ( x - x1 ) * dif1 + ( x - x1 ) * ( x - x2 ) * dif2;
*yp = dif1 + ( 2.0 * x - x1 - x2 ) * dif2;
*ypp = 2.0 * dif2;
return;
}
//****************************************************************************80
void r8poly2_val2 ( int ndata, double tdata[],
double ydata[], int left, double tval, double *yval )
//****************************************************************************80
//
// Purpose:
//
// R8POLY2_VAL2 evaluates a parabolic function through 3 points in a table.
//
// Discussion:
//
// This routine is a utility routine used by OVERHAUSER_SPLINE_VAL.
// It constructs the parabolic interpolant through the data in
// 3 consecutive entries of a table and evaluates this interpolant
// at a given abscissa value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 March 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NDATA, the number of data points.
// NDATA must be at least 3.
//
// Input, double TDATA[NDATA], the abscissas of the data points. The
// values in TDATA must be in strictly ascending order.
//
// Input, double YDATA[NDATA], the data points corresponding to
// the abscissas.
//
// Input, int LEFT, the location of the first of the three
// consecutive data points through which the parabolic interpolant
// must pass. 0 <= LEFT <= NDATA - 3.
//
// Input, double TVAL, the value of T at which the parabolic interpolant
// is to be evaluated. Normally, TDATA[0] <= TVAL <= T[NDATA-1], and
// the data will be interpolated. For TVAL outside this range,
// extrapolation will be used.
//
// Output, double *YVAL, the value of the parabolic interpolant
// at TVAL.
//
{
double dif1;
double dif2;
double t1;
double t2;
double t3;
double y1;
double y2;
double y3;
//
// Check.
//
if ( left < 0 || ndata-3 < left )
{
cerr << "\n";
cerr << "RPOLY2_VAL2 - Fatal error!\n";
cerr << " LEFT < 0 or NDATA-3 < LEFT.\n";
exit ( 1 );
}
//
// Copy out the three abscissas.
//
t1 = tdata[left];
t2 = tdata[left+1];
t3 = tdata[left+2];
if ( t2 <= t1 || t3 <= t2 )
{
cerr << "\n";
cerr << "RPOLY2_VAL2 - Fatal error!\n";
cerr << " T2 <= T1 or T3 <= T2.\n";
cerr << " T1 = " << t1 << "\n";
cerr << " T2 = " << t2 << "\n";
cerr << " T3 = " << t3 << "\n";
exit ( 1 );
}
//
// Construct and evaluate a parabolic interpolant for the data.
//
y1 = ydata[left];
y2 = ydata[left+1];
y3 = ydata[left+2];
dif1 = ( y2 - y1 ) / ( t2 - t1 );
dif2 =
( ( y3 - y1 ) / ( t3 - t1 )
- ( y2 - y1 ) / ( t2 - t1 ) ) / ( t3 - t2 );
*yval = y1 + ( tval - t1 ) * ( dif1 + ( tval - t2 ) * dif2 );
return;
}
//****************************************************************************80
void r8pp_delete ( int m, int n, double **a )
//****************************************************************************80
//
// Purpose:
//
// R8PP_DELETE frees the memory set aside by R8PP_NEW.
//
// Discussion:
//
// An R8PP is a pointer to pointers to R8's, and is a sort of
// variably-dimensioned matrix.
//
// This function releases the memory associated with an array that was
// created by a command like:
//
// double **a;
// a = r8pp_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the array.
//
// Input, double **A, the pointer to the pointers.
//
{
int i;
for ( i = 0; i < m; i++ )
{
delete [] a[i];
}
delete [] a;
return;
}
//****************************************************************************80
double **r8pp_new ( int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8PP_NEW allocates a new R8PP.
//
// Discussion:
//
// An R8PP is a pointer to pointers to R8's, and is a sort of
// variably-dimensioned matrix.
//
// A declaration of the form
// double **a;
// is necesary. Then an assignment of the form:
// a = r8pp_new ( m, n );
// allows the user to assign entries to the matrix using typical
// 2D array notation:
// a[2][3] = 17;
// y = a[1][0];
// and so on.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the matrix.
//
// Output, double **R8PP_NEW, a pointer to the pointers to the M by N array.
//
{
double **a;
int i;
a = new double *[m];
if ( a == NULL )
{
cerr << "\n";
cerr << "R8PP_NEW - Fatal error!\n";
cerr << " Unable to allocate row pointer array.\n";
exit ( 1 );
}
for ( i = 0; i < m; i++ )
{
a[i] = new double[n];
if ( a[i] == NULL )
{
cerr << "\n";
cerr << "R8PP_NEW - Fatal error!\n";
cerr << " Unable to allocate row array.\n";
exit ( 1 );
}
}
return a;
}
//****************************************************************************80
int r8r8_compare ( double x1, double y1, double x2, double y2 )
//****************************************************************************80
//
// Purpose:
//
// R8R8_COMPARE compares two R8R8's.
//
// Discussion:
//
// An R8R8 is simply a pair of R8 values, stored separately.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X1, Y1, the first vector.
//
// Input, double X2, Y2, the second vector.
//
// Output, int R8R8_COMPARE:
// -1, (X1,Y1) < (X2,Y2);
// 0, (X1,Y1) = (X2,Y2);
// +1, (X1,Y1) > (X2,Y2).
//
{
int value;
if ( x1 < x2 )
{
value = -1;
}
else if ( x2 < x1 )
{
value = +1;
}
else if ( y1 < y2 )
{
value = -1;
}
else if ( y2 < y1 )
{
value = +1;
}
else
{
value = 0;
}
return value;
}
//****************************************************************************80
void r8r8_print ( double a1, double a2, string title )
//****************************************************************************80
//
// Purpose:
//
// R8R8_PRINT prints an R8R8.
//
// Discussion:
//
// An R8R8 is a pair of R8 values, regarded as a single item.
//
// A format is used which suggests a coordinate pair:
//
// Example:
//
// Center : ( 1.23, 7.45 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double A1, A2, the coordinates of the vector.
//
// Input, string TITLE, a title.
//
{
cout << " " << title << " : ";
cout << " ( " << setw(12) << a1
<< ", " << setw(12) << a2 << " )\n";
return;
}
//****************************************************************************80
int r8r8r8_compare ( double x1, double y1, double z1, double x2, double y2,
double z2 )
//****************************************************************************80
//
// Purpose:
//
// R8R8R8_COMPARE compares two R8R8R8's.
//
// Discussion:
//
// An R8R8R8 is simply 3 R8 values, stored as scalars.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X1, Y1, Z1, the first vector.
//
// Input, double X2, Y2, Z2, the second vector.
//
// Output, int R8R8R8_COMPARE:
// -1, (X1,Y1,Z1) < (X2,Y2,Z2);
// 0, (X1,Y1,Z1) = (X2,Y2,Z2);
// +1, (X1,Y1,Z1) > (X2,Y2,Z2).
//
{
int value;
if ( x1 < x2 )
{
value = -1;
}
else if ( x2 < x1 )
{
value = +1;
}
else if ( y1 < y2 )
{
value = -1;
}
else if ( y2 < y1 )
{
value = +1;
}
else if ( z1 < z2 )
{
value = -1;
}
else if ( z2 < z1 )
{
value = +1;
}
else
{
value = 0;
}
return value;
}
//****************************************************************************80
void r8r8r8vec_index_insert_unique ( int maxn, int &n, double x[], double y[],
double z[], int indx[], double xval, double yval, double zval, int &ival,
int &ierror )
//****************************************************************************80
//
// Purpose:
//
// R8R8R8VEC_INDEX_INSERT_UNIQUE inserts a unique R8R8R8 value in an indexed sorted list.
//
// Discussion:
//
// If the input value does not occur in the current list, it is added,
// and N, X, Y, Z and INDX are updated.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int MAXN, the maximum size of the list.
//
// Input/output, int &N, the size of the list.
//
// Input/output, double X[N], Y[N], Z[N], the R8R8R8 vector.
//
// Input/output, int INDX[N], the sort index of the list.
//
// Input, double XVAL, YVAL, ZVAL, the value to be inserted
// if it is not already in the list.
//
// Output, int &IVAL, the index in X, Y, Z corresponding to the
// value XVAL, YVAL, ZVAL.
//
// Output, int &IERROR, 0 for no error, 1 if an error occurred.
//
{
int equal;
int i;
int less;
int more;
ierror = 0;
if ( n <= 0 )
{
if ( maxn <= 0 )
{
ierror = 1;
cerr << "\n";
cerr << "R8R8R8VEC_INDEX_INSERT_UNIQUE - Fatal error!\n";
cerr << " Not enough space to store new data.\n";
return;
}
n = 1;
x[0] = xval;
y[0] = yval;
z[0] = zval;
indx[0] = 1;
ival = 1;
return;
}
//
// Does ( XVAL, YVAL, ZVAL ) already occur in ( X, Y, Z)?
//
r8r8r8vec_index_search ( n, x, y, z, indx, xval, yval, zval,
less, equal, more );
if ( equal == 0 )
{
if ( maxn <= n )
{
ierror = 1;
cerr << "\n";
cerr << "R8R8R8VEC_INDEX_INSERT_UNIQUE - Fatal error!\n";
cerr << " Not enough space to store new data.\n";
return;
}
x[n] = xval;
y[n] = yval;
z[n] = zval;
ival = n + 1;
for ( i = n - 1; more - 1 <= i; i-- )
{
indx[i+1] = indx[i];
}
indx[more-1] = n + 1;
n = n + 1;
}
else
{
ival = indx[equal-1];
}
return;
}
//****************************************************************************80
void r8r8r8vec_index_search ( int n, double x[], double y[], double z[],
int indx[], double xval, double yval, double zval, int &less, int &equal,
int &more )
//****************************************************************************80
//
// Purpose:
//
// R8R8R8VEC_INDEX_SEARCH searches for an R8R8R8 value in an indexed sorted list.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the list.
//
// Input, double X[N], Y[N], Z[N], the list.
//
// Input, int INDX[N], the sort index of the list.
//
// Input, double XVAL, YVAL, ZVAL, the value to be sought.
//
// Output, int &LESS, &EQUAL, &MORE, the indexes in INDX of the
// entries of X that are just less than, equal to, and just greater
// than XVAL. If XVAL does not occur in X, then EQUAL is zero.
// If XVAL is the minimum entry of X, then LESS is 0. If XVAL
// is the greatest entry of X, then MORE is N+1.
//
{
int compare;
int hi;
int lo;
int mid;
double xhi;
double xlo;
double xmid;
double yhi;
double ylo;
double ymid;
double zhi;
double zlo;
double zmid;
if ( n <= 0 )
{
less = 0;
equal = 0;
more = 0;
return;
}
lo = 1;
hi = n;
xlo = x[indx[lo-1]-1];
ylo = y[indx[lo-1]-1];
zlo = z[indx[lo-1]-1];
xhi = x[indx[hi-1]-1];
yhi = y[indx[hi-1]-1];
zhi = z[indx[hi-1]-1];
compare = r8r8r8_compare ( xval, yval, zval, xlo, ylo, zlo );
if ( compare == -1 )
{
less = 0;
equal = 0;
more = 1;
return;
}
else if ( compare == 0 )
{
less = 0;
equal = 1;
more = 2;
return;
}
compare = r8r8r8_compare ( xval, yval, zval, xhi, yhi, zhi );
if ( compare == 1 )
{
less = n;
equal = 0;
more = n + 1;
return;
}
else if ( compare == 0 )
{
less = n - 1;
equal = n;
more = n + 1;
return;
}
for ( ; ; )
{
if ( lo + 1 == hi )
{
less = lo;
equal = 0;
more = hi;
return;
}
mid = ( lo + hi ) / 2;
xmid = x[indx[mid-1]-1];
ymid = y[indx[mid-1]-1];
zmid = z[indx[mid-1]-1];
compare = r8r8r8_compare ( xval, yval, zval, xmid, ymid, zmid );
if ( compare == 0 )
{
equal = mid;
less = mid - 1;
more = mid + 1;
return;
}
else if ( compare == -1 )
{
hi = mid;
}
else if ( compare == +1 )
{
lo = mid;
}
}
return;
}
//****************************************************************************80
void r8r8vec_index_insert_unique ( int maxn, int &n, double x[], double y[],
int indx[], double xval, double yval, int &ival, int &ierror )
//****************************************************************************80
//
// Purpose:
//
// R8R8VEC_INDEX_INSERT_UNIQUE inserts a unique R8R8 value in an indexed sorted list.
//
// Discussion:
//
// If the input value does not occur in the current list, it is added,
// and N, X, Y and INDX are updated.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int MAXN, the maximum size of the list.
//
// Input/output, int &N, the size of the list.
//
// Input/output, double X[N], Y[N], the list of R8R8 vectors.
//
// Input/output, int INDX[N], the sort index of the list.
//
// Input, double XVAL, YVAL, the value to be inserted if it is
// not already in the list.
//
// Output, int &IVAL, the index in X, Y corresponding to the
// value XVAL, YVAL.
//
// Output, int &IERROR, 0 for no error, 1 if an error occurred.
//
{
int equal;
int i;
int less;
int more;
ierror = 0;
if ( n <= 0 )
{
if ( maxn <= 0 )
{
cerr << "\n";
cerr << "R8R8VEC_INDEX_INSERT_UNIQUE - Fatal error!\n";
cerr << " Not enough space to store new data.\n";
exit ( 1 );
}
n = 1;
x[0] = xval;
y[0] = yval;
indx[0] = 1;
ival = 1;
return;
}
//
// Does ( XVAL, YVAL ) already occur in ( X, Y )?
//
r8r8vec_index_search ( n, x, y, indx, xval, yval, less, equal, more );
if ( equal == 0 )
{
if ( maxn <= n )
{
cerr << "\n";
cerr << "R8R8VEC_INDEX_INSERT_UNIQUE - Fatal error!\n";
cerr << " Not enough space to store new data.\n";
exit ( 1 );
}
x[n] = xval;
y[n] = yval;
ival = n + 1;
for ( i = n - 1; more - 1 <= i; i-- )
{
indx[i+1] = indx[i];
}
indx[more-1] = n + 1;
n = n + 1;
}
else
{
ival = indx[equal-1];
}
return;
}
//****************************************************************************80
void r8r8vec_index_search ( int n, double x[], double y[], int indx[],
double xval, double yval, int &less, int &equal, int &more )
//****************************************************************************80
//
// Purpose:
//
// R8R8VEC_INDEX_SEARCH searches for an R8R8 value in an indexed sorted list.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the current list.
//
// Input, double X[N], Y[N], the list.
//
// Input, int INDX[N], the sort index of the list.
//
// Input, double XVAL, YVAL, the value to be sought.
//
// Output, int &LESS, &EQUAL, &MORE, the indexes in INDX of the
// entries of X that are just less than, equal to, and just greater
// than XVAL. If XVAL does not occur in X, then EQUAL is zero.
// If XVAL is the minimum entry of X, then LESS is 0. If XVAL
// is the greatest entry of X, then MORE is N+1.
//
{
int compare;
int hi;
int lo;
int mid;
double xhi;
double xlo;
double xmid;
double yhi;
double ylo;
double ymid;
if ( n <= 0 )
{
less = 0;
equal = 0;
more = 0;
return;
}
lo = 1;
hi = n;
xlo = x[indx[lo-1]-1];
ylo = y[indx[lo-1]-1];
xhi = x[indx[hi-1]-1];
yhi = y[indx[hi-1]-1];
compare = r8r8_compare ( xval, yval, xlo, ylo );
if ( compare == -1 )
{
less = 0;
equal = 0;
more = 1;
return;
}
else if ( compare == 0 )
{
less = 0;
equal = 1;
more = 2;
return;
}
compare = r8r8_compare ( xval, yval, xhi, yhi );
if ( compare == 1 )
{
less = n;
equal = 0;
more = n + 1;
return;
}
else if ( compare == 0 )
{
less = n - 1;
equal = n;
more = n + 1;
return;
}
for ( ; ; )
{
if ( lo + 1 == hi )
{
less = lo;
equal = 0;
more = hi;
return;
}
mid = ( lo + hi ) / 2;
xmid = x[indx[mid-1]-1];
ymid = y[indx[mid-1]-1];
compare = r8r8_compare ( xval, yval, xmid, ymid );
if ( compare == 0 )
{
equal = mid;
less = mid - 1;
more = mid + 1;
return;
}
else if ( compare == -1 )
{
hi = mid;
}
else if ( compare == +1 )
{
lo = mid;
}
}
return;
}
//****************************************************************************80
double **r8rmat_copy_new ( int m, int n, double **a )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_COPY_NEW makes a new copy of an R8RMAT .
//
// Discussion:
//
// An R8RMAT is a matrix stored in row major form, using M pointers
// to the beginnings of rows.
//
// A declaration of the form
// double **a;
// is necesary. Then an assignment of the form:
// a = r8rmat_new ( m, n );
// allows the user to assign entries to the matrix using typical
// 2D array notation:
// a[2][3] = 17.0;
// y = a[1][0];
// and so on.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 May 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double **A, the array to copy.
//
// Output, double **R8RMAT_COPY_NEW, the copied array.
//
{
double **b;
int i;
int j;
b = r8rmat_new ( m, n );
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
b[i][j] = a[i][j];
}
}
return b;
}
//****************************************************************************80
void r8rmat_delete ( int m, int n, double **a )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_DELETE frees memory associated with an R8RMAT.
//
// Discussion:
//
// This function releases the memory associated with an R8RMAT.
//
// An R8RMAT is a row-major array that was created by a
// command like:
//
// double **a;
// a = r8rmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 September 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the array.
//
// Input, double **A, the pointer to the array.
//
{
int i;
for ( i = 0; i < m; i++ )
{
delete [] a[i];
}
delete [] a;
return;
}
//****************************************************************************80
double *r8rmat_fs_new ( int n, double **a, double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_FS_NEW factors and solves an R8RMAT system with one right hand side.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 May 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
// N must be positive.
//
// Input, double **A, the coefficient matrix of the linear system.
//
// Input, double B[N], the right hand side of the linear system.
//
// Output, double R8RMAT_FS_NEW[N], the solution of the linear system.
//
{
double **a2;
int i;
int j;
int k;
int p;
double t;
double *x;
a2 = r8rmat_copy_new ( n, n, a );
x = r8vec_copy_new ( n, b );
for ( k = 0; k < n; k++ )
{
//
// Find the maximum element in column I.
//
p = k;
for ( i = k + 1; i < n; i++ )
{
if ( fabs ( a2[p][k] ) < fabs ( a2[i][k] ) )
{
p = i;
}
}
if ( a2[p][k] == 0.0 )
{
cerr << "\n";
cerr << "R8RMAT_FS_NEW - Fatal error!\n";
cerr << " Zero pivot on step " << k << "\n";
exit ( 1 );
}
//
// Switch rows K and P.
//
if ( k != p )
{
for ( j = 0; j < n; j++ )
{
t = a2[k][j];
a2[k][j] = a2[p][j];
a2[p][j] = t;
}
t = x[k];
x[k] = x[p];
x[p] = t;
}
//
// Scale the pivot row.
//
t = a2[k][k];
a2[k][k] = 1.0;
for ( j = k + 1; j < n; j++ )
{
a2[k][j] = a2[k][j] / t;
}
x[k] = x[k] / t;
//
// Use the pivot row to eliminate lower entries in that column.
//
for ( i = k + 1; i < n; i++ )
{
if ( a2[i][k] != 0.0 )
{
t = - a2[i][k];
a2[i][k] = 0.0;
for ( j = k + 1; j < n; j++ )
{
a2[i][j] = a2[i][j] + t * a2[k][j];
}
x[i] = x[i] + t * x[k];
}
}
}
//
// Back solve.
//
for ( j = n - 1; 1 <= j; j-- )
{
for ( i = 0; i < j; i++ )
{
x[i] = x[i] - a2[i][j] * x[j];
}
}
r8rmat_delete ( n, n, a2 );
return x;
}
//****************************************************************************80
double **r8rmat_new ( int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_NEW allocates a new R8RMAT.
//
// Discussion:
//
// An R8RMAT is a row-major array that was created by a
// command like:
//
// double **a;
// a = r8rmat_new ( m, n );
//
// The user assigns entries to the matrix using typical
// 2D array notation:
// a[2][3] = 17.0;
// y = a[1][0];
// and so on.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 September 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the matrix.
//
// Output, double **R8RMAT_NEW, a new matrix.
//
{
double **a;
int i;
a = new double *[m];
if ( a == NULL )
{
cerr << "\n";
cerr << "R8RMAT_NEW - Fatal error!\n";
cerr << " Unable to allocate row pointer array.\n";
exit ( 1 );
}
for ( i = 0; i < m; i++ )
{
a[i] = new double[n];
if ( a[i] == NULL )
{
cerr << "\n";
cerr << "R8RMAT_NEW - Fatal error!\n";
cerr << " Unable to allocate row array.\n";
exit ( 1 );
}
}
return a;
}
//****************************************************************************80
void r8rmat_print ( int m, int n, double **a, string title )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_PRINT prints an R8RMAT.
//
// Discussion:
//
// An R8RMAT is a row-major array that was created by a
// command like:
//
// double **a;
// a = r8rmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double **A = A[M][N], the M by N matrix.
//
// Input, string TITLE, a title.
//
{
r8rmat_print_some ( m, n, a, 1, 1, m, n, title );
return;
}
//****************************************************************************80
void r8rmat_print_some ( int m, int n, double **a, int ilo, int jlo, int ihi,
int jhi, string title )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_PRINT_SOME prints some of an R8RMAT.
//
// Discussion:
//
// An R8RMAT is a row-major array that was created by a
// command like:
//
// double **a;
// a = r8rmat_new ( m, n );
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 June 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows of the matrix.
// M must be positive.
//
// Input, int N, the number of columns of the matrix.
// N must be positive.
//
// Input, double **A = A[M][N], the matrix.
//
// Input, int ILO, JLO, IHI, JHI, designate the first row and
// column, and the last row and column to be printed.
//
// Input, string TITLE, a title.
//
{
# define INCX 5
int i;
int i2hi;
int i2lo;
int j;
int j2hi;
int j2lo;
cout << "\n";
cout << title << "\n";
if ( m <= 0 || n <= 0 )
{
cout << "\n";
cout << " (None)\n";
return;
}
//
// Print the columns of the matrix, in strips of 5.
//
for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
{
j2hi = j2lo + INCX - 1;
if ( n < j2hi )
{
j2hi = n;
}
if ( jhi < j2hi )
{
j2hi = jhi;
}
cout << "\n";
//
// For each column J in the current range...
//
// Write the header.
//
cout << " Col: ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(7) << j - 1 << " ";
}
cout << "\n";
cout << " Row\n";
cout << "\n";
//
// Determine the range of the rows in this strip.
//
if ( 1 < ilo )
{
i2lo = ilo;
}
else
{
i2lo = 1;
}
if ( ihi < m )
{
i2hi = ihi;
}
else
{
i2hi = m;
}
for ( i = i2lo; i <= i2hi; i++ )
{
//
// Print out (up to) 5 entries in row I, that lie in the current strip.
//
cout << setw(5) << i - 1 << ": ";
for ( j = j2lo; j <= j2hi; j++ )
{
cout << setw(12) << a[i-1][j-1] << " ";
}
cout << "\n";
}
}
return;
# undef INCX
}
//****************************************************************************80
double *r8rmat_to_r8mat ( int m, int n, double **a )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_TO_R8MAT copies data from an R8RMAT to an R8MAT.
//
// Discussion:
//
// An R8RMAT is a row-major array that was created by a
// command like:
//
// double **a;
// a = r8rmat_new ( m, n );
//
// An R8MAT is a column-major array stored as a vector, so
// that element (I,J) of the M by N array is stored in location
// I+J*M.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 January 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input, double **A = double A[M][N], the data, stored as an R8RMAT.
//
// Output, double R8RMAT_TO_R8MAT[M*N], the data, stored as an R8MAT.
//
{
double *b;
int i;
int j;
b = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
b[i+j*m] = a[i][j];
}
}
return b;
}
//****************************************************************************80
double **r8rmat_zeros ( int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8RMAT_ZEROS allocates and zeroes a new R8RMAT.
//
// Discussion:
//
// An R8RMAT is a row-major array that was created by a
// command like:
//
// double **a;
// a = r8rmat_new ( m, n );
//
// The user assigns entries to the matrix using typical
// 2D array notation:
// a[2][3] = 17.0;
// y = a[1][0];
// and so on.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 May 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns in the matrix.
//
// Output, double **R8RMAT_ZEROS, a new matrix.
//
{
double **a;
int i;
int j;
a = new double *[m];
if ( a == NULL )
{
cerr << "\n";
cerr << "R8RMAT_ZEROS - Fatal error!\n";
cerr << " Unable to allocate row pointer array.\n";
exit ( 1 );
}
for ( i = 0; i < m; i++ )
{
a[i] = new double[n];
if ( a[i] == NULL )
{
cerr << "\n";
cerr << "R8RMAT_ZEROS - Fatal error!\n";
cerr << " Unable to allocate row array.\n";
exit ( 1 );
}
}
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
a[i][j] = 0.0;
}
}
return a;
}
//****************************************************************************80
void r8slmat_print ( int m, int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8SLMAT_PRINT prints a strict lower triangular R8MAT.
//
// Example:
//
// M = 5, N = 5
// A = (/ 21, 31, 41, 51, 32, 42, 52, 43, 53, 54 /)
//
// 21
// 31 32
// 41 42 43
// 51 52 53 54
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the number of rows in A.
//
// Input, int N, the number of columns in A.
//
// Input, double A[*], the M by N matrix. Only the strict
// lower triangular elements are stored, in column major order.
//
// Input, string TITLE, a title.
//
{
int i;
int indx;
int j;
int jhi;
int jlo;
int jmax;
int nn;
cout << "\n";
cout << title << "\n";
jmax = i4_min ( n, m - 1 );
nn = 5;
for ( jlo = 1; jlo <= jmax; jlo = jlo + nn )
{
jhi = i4_min ( jlo + nn - 1, i4_min ( m - 1, jmax ) );
cout << "\n";
cout << " Col ";
for ( j = jlo; j <= jhi; j++ )
{
cout << setw(7) << j << " ";
}
cout << "\n";
cout << " Row\n";
for ( i = jlo + 1; i <= m; i++ )
{
cout << setw(5) << i << ":";
jhi = i4_min ( jlo + nn - 1, i4_min ( i - 1, jmax ) );
for ( j = jlo; j <= jhi; j++ )
{
indx = ( j - 1 ) * m + i - ( j * ( j + 1 ) ) / 2;
cout << " " << setw(12) << a[indx-1];
}
cout << "\n";
}
}
return;
}
//****************************************************************************80
void r8vec_01_to_ab ( int n, double a[], double amax, double amin )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_01_TO_AB shifts and rescales data to lie within given bounds.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// On input, A contains the original data, which is presumed to lie
// between 0 and 1. However, it is not necessary that this be so.
//
// On output, A has been shifted and rescaled so that all entries which
// on input lay in [0,1] now lie between AMIN and AMAX. Other entries will
// be mapped in a corresponding way.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of data values.
//
// Input/output, double A[N], the vector to be rescaled.
//
// Input, double AMAX, AMIN, the maximum and minimum values
// allowed for A.
//
{
double amax2;
double amax3;
double amin2;
double amin3;
int i;
if ( amax == amin )
{
for ( i = 0; i < n; i++ )
{
a[i] = amin;
}
return;
}
amax2 = r8_max ( amax, amin );
amin2 = r8_min ( amax, amin );
amin3 = r8vec_min ( n, a );
amax3 = r8vec_max ( n, a );
if ( amax3 != amin3 )
{
for ( i = 0; i < n; i++ )
{
a[i] = ( ( amax3 - a[i] ) * amin2
+ ( a[i] - amin3 ) * amax2 )
/ ( amax3 - amin3 );
}
}
else
{
for ( i = 0; i < n; i++ )
{
a[i] = 0.5 * ( amax2 + amin2 );
}
}
return;
}
//****************************************************************************80
void r8vec_ab_to_01 ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_AB_TO_01 shifts and rescales data to lie within [0,1].
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// On input, A contains the original data. On output, A has been shifted
// and scaled so that all entries lie between 0 and 1.
//
// The formula is:
//
// A(I) := ( A(I) - AMIN ) / ( AMAX - AMIN )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of data values.
//
// Input/output, double A[N], the data to be rescaled.
//
{
double amax;
double amin;
int i;
amax = r8vec_max ( n, a );
amin = r8vec_min ( n, a );
if ( amin == amax )
{
for ( i = 0; i < n; i++ )
{
a[i] = 0.5;
}
}
else
{
for ( i = 0; i < n; i++ )
{
a[i] = ( a[i] - amin ) / ( amax - amin );
}
}
return;
}
//****************************************************************************80
double *r8vec_ab_to_cd ( int n, double a[], double bmin, double bmax )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_AB_TO_CD shifts and rescales data to lie within a given pair of bounds.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The mininum entry of A is mapped to BMIN, the maximum entry
// to BMAX, and values in between are mapped linearly.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of data values.
//
// Input, double A[N], the data to be remapped.
//
// Input, double BMIN, BMAX, the values to which min(A) and max(A)
// are to be assigned.
//
// Output, double R8VEC_AB_TO_CD[N], the remapped data.
//
{
double amax;
double amin;
double *b;
int i;
b = new double[n];
if ( bmax == bmin )
{
for ( i = 0; i < n; i++ )
{
b[i] = bmin;
}
return b;
}
amax = r8vec_max ( n, a );
amin = r8vec_min ( n, a );
if ( amin == amax )
{
for ( i = 0; i < n; i++ )
{
b[i] = 0.5 * ( bmax + bmin );
}
}
else
{
for ( i = 0; i < n; i++ )
{
b[i] = ( ( amax - a[i] ) * bmin
+ ( a[i] - amin ) * bmax )
/ ( amax - amin );
}
}
return b;
}
//****************************************************************************80
void r8vec_add ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ADD adds one R8VEC to another.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 September 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double A1[N], the vector to be added.
//
// Input/output, double A2[N], the vector to be increased.
// On output, A2 = A2 + A1.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a2[i] = a2[i] + a1[i];
}
return;
}
//****************************************************************************80
bool r8vec_all_nonpositive ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ALL_NONPOSITIVE: ( all ( A <= 0 ) ) for R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double A[N], the vector to check.
//
// Output, bool R8VEC_ALL_NONPOSITIVE is TRUE if all entries
// of A are less than or equal to zero.
//
{
int i;
bool value;
for ( i = 0; i < n; i++ )
{
if ( 0.0 < a[i] )
{
value = false;
return value;
}
}
value = true;
return value;
}
//****************************************************************************80
double r8vec_amax ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_AMAX returns the maximum absolute value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, double AMAX, the value of the entry
// of largest magnitude.
//
{
double amax;
int i;
amax = 0.0;
for ( i = 0; i < n; i++ )
{
if ( amax < fabs ( a[i] ) )
{
amax = fabs ( a[i] );
}
}
return amax;
}
//****************************************************************************80
int r8vec_amax_index ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_AMAX_INDEX returns the index of the maximum absolute value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, int R8VEC_AMAX_INDEX, the index of the entry of largest magnitude.
//
{
double amax;
int amax_index;
int i;
if ( n <= 0 )
{
amax_index = -1;
}
else
{
amax_index = 1;
amax = fabs ( a[0] );
for ( i = 2; i <= n; i++ )
{
if ( amax < fabs ( a[i-1] ) )
{
amax_index = i;
amax = fabs ( a[i-1] );
}
}
}
return amax_index;
}
//****************************************************************************80
double r8vec_amin ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_AMIN returns the minimum absolute value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, double R8VEC_AMIN, the value of the entry
// of smallest magnitude.
//
{
int i;
const double r8_huge = 1.79769313486231571E+308;
double value;
value = r8_huge;
for ( i = 0; i < n; i++ )
{
if ( fabs ( a[i] ) < value )
{
value = fabs ( a[i] );
}
}
return value;
}
//****************************************************************************80
int r8vec_amin_index ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_AMIN_INDEX returns the index of the minimum absolute value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, int R8VEC_AMIN_INDEX, the index of the entry of smallest magnitude.
//
{
double amin;
int amin_index;
int i;
if ( n <= 0 )
{
amin_index = -1;
}
else
{
amin_index = 1;
amin = fabs ( a[0] );
for ( i = 2; i <= n; i++ )
{
if ( fabs ( a[i-1] ) < amin )
{
amin_index = i;
amin = fabs ( a[i-1] );
}
}
}
return amin_index;
}
//****************************************************************************80
bool r8vec_any_negative ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ANY_NEGATIVE: ( any ( A < 0 ) ) for R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double A[N], the vector to check.
//
// Output, bool R8VEC_ANY_NEGATIVE is TRUE if any entry
// of A is less than zero.
//
{
int i;
bool value;
for ( i = 0; i < n; i++ )
{
if ( a[i] < 0.0 )
{
value = true;
return value;
}
}
value = false;
return value;
}
//****************************************************************************80
bool r8vec_any_nonzero ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ANY_NONZERO: ( any A nonzero ) for R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 December 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double A[N], the vector to check.
//
// Output, bool R8VEC_ANY_NONZERO is TRUE if any entry is nonzero.
//
{
int i;
bool value;
for ( i = 0; i < n; i++ )
{
if ( a[i] != 0.0 )
{
value = true;
return value;
}
}
value = false;
return value;
}
//****************************************************************************80
double *r8vec_any_normal ( int dim_num, double v1[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ANY_NORMAL returns some normal vector to V1.
//
// Discussion:
//
// If DIM_NUM < 2, then no normal vector can be returned.
//
// If V1 is the zero vector, then any unit vector will do.
//
// No doubt, there are better, more robust algorithms. But I will take
// just about ANY reasonable unit vector that is normal to V1.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the spatial dimension.
//
// Input, double V1[DIM_NUM], the vector.
//
// Output, double R8VEC_ANY_NORMAL[DIM_NUM], a vector that is
// normal to V2, and has unit Euclidean length.
//
{
int i;
int j;
int k;
double *v2;
double vj;
double vk;
if ( dim_num < 2 )
{
cerr << "\n";
cerr << "R8VEC_ANY_NORMAL - Fatal error!\n";
cerr << " Called with DIM_NUM < 2.\n";
exit ( 1 );
}
v2 = new double[dim_num];
if ( r8vec_norm ( dim_num, v1 ) == 0.0 )
{
r8vec_zeros ( dim_num, v2 );
v2[0] = 1.0;
return v2;
}
//
// Seek the largest entry in V1, VJ = V1(J), and the
// second largest, VK = V1(K).
//
// Since V1 does not have zero norm, we are guaranteed that
// VJ, at least, is not zero.
//
j = -1;
vj = 0.0;
k = -1;
vk = 0.0;
for ( i = 0; i < dim_num; i++ )
{
if ( fabs ( vk ) < fabs ( v1[i] ) || k == -1 )
{
if ( fabs ( vj ) < fabs ( v1[i] ) || j == -1 )
{
k = j;
vk = vj;
j = i;
vj = v1[i];
}
else
{
k = i;
vk = v1[i];
}
}
}
//
// Setting V2 to zero, except that V2(J) = -VK, and V2(K) = VJ,
// will just about do the trick.
//
r8vec_zeros ( dim_num, v2 );
v2[j] = -vk / sqrt ( vk * vk + vj * vj );
v2[k] = vj / sqrt ( vk * vk + vj * vj );
return v2;
}
//****************************************************************************80
bool r8vec_ascends ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ASCENDS determines if an R8VEC is (weakly) ascending.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// For example, if:
//
// X = ( -8.1, 1.3, 2.2, 3.4, 7.5, 7.5, 9.8 )
//
// then
//
// R8VEC_ASCENDS = TRUE
//
// The sequence is not required to be strictly ascending.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 July 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the array.
//
// Input, double X[N], the array to be examined.
//
// Output, bool R8VEC_ASCENDS, is TRUE if the
// entries of X ascend.
//
{
int i;
bool value;
for ( i = 0; i < n - 1; i++ )
{
if ( x[i+1] < x[i] )
{
value = false;
return value;
}
}
value = true;
return value;
}
//****************************************************************************80
bool r8vec_ascends_strictly ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ASCENDS_STRICTLY determines if an R8VEC is strictly ascending.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Notice the effect of entry number 6 in the following results:
//
// X = ( -8.1, 1.3, 2.2, 3.4, 7.5, 7.4, 9.8 )
// Y = ( -8.1, 1.3, 2.2, 3.4, 7.5, 7.5, 9.8 )
// Z = ( -8.1, 1.3, 2.2, 3.4, 7.5, 7.6, 9.8 )
//
// R8VEC_ASCENDS_STRICTLY ( X ) = FALSE
// R8VEC_ASCENDS_STRICTLY ( Y ) = FALSE
// R8VEC_ASCENDS_STRICTLY ( Z ) = TRUE
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 July 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the array.
//
// Input, double X[N], the array to be examined.
//
// Output, bool R8VEC_ASCENDS_STRICTLY, is TRUE if the
// entries of X strictly ascend.
//
{
int i;
bool value;
for ( i = 0; i < n - 1; i++ )
{
if ( x[i+1] <= x[i] )
{
value = false;
return value;
}
}
value = true;
return value;
}
//****************************************************************************80
double r8vec_asum ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ASUM sums the absolute values of the entries of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 January 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], the vector.
//
// Output, double R8VEC_ASUM, the sum of absolute values of the entries.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + fabs ( a[i] );
}
return value;
}
//****************************************************************************80
void r8vec_bin ( int n, double x[], int bin_num, double bin_min, double bin_max,
int bin[], double bin_limit[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_BIN computes bins based on a given R8VEC.
//
// Discussion:
//
// The user specifies minimum and maximum bin values, BIN_MIN and
// BIN_MAX, and the number of bins, BIN_NUM. This determines a
// "bin width":
//
// H = ( BIN_MAX - BIN_MIN ) / BIN_NUM
//
// so that bin I will count all entries X(J) such that
//
// BIN_LIMIT(I-1) <= X(J) < BIN_LIMIT(I).
//
// The array X does NOT have to be sorted.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 February 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of X.
//
// Input, double X[N], an (unsorted) array to be binned.
//
// Input, int BIN_NUM, the number of bins. Two extra bins,
// #0 and #BIN_NUM+1, count extreme values.
//
// Input, double BIN_MIN, BIN_MAX, define the range and size
// of the bins. BIN_MIN and BIN_MAX must be distinct.
// Normally, BIN_MIN < BIN_MAX, and the documentation will assume
// this, but proper results will be computed if BIN_MIN > BIN_MAX.
//
// Output, int BIN[BIN_NUM+2].
// BIN(0) counts entries of X less than BIN_MIN.
// BIN(BIN_NUM+1) counts entries greater than or equal to BIN_MAX.
// For 1 <= I <= BIN_NUM, BIN(I) counts the entries X(J) such that
// BIN_LIMIT(I-1) <= X(J) < BIN_LIMIT(I).
// where H is the bin spacing.
//
// Output, double BIN_LIMIT[BIN_NUM+1], the "limits" of the bins.
// BIN(I) counts the number of entries X(J) such that
// BIN_LIMIT(I-1) <= X(J) < BIN_LIMIT(I).
//
{
int i;
int j;
double t;
if ( bin_max == bin_min )
{
cerr << "\n";
cerr << "R8VEC_BIN - Fatal error!\n";
cerr << " BIN_MIN = BIN_MAX = " << bin_max << ".\n";
exit ( 1 );
}
for ( i = 0; i <= bin_num + 1; i++ )
{
bin[i] = 0;
}
for ( i = 0; i < n; i++ )
{
t = ( x[i] - bin_min ) / ( bin_max - bin_min );
if ( t < 0.0 )
{
j = 0;
}
else if ( 1.0 <= t )
{
j = bin_num + 1;
}
else
{
j = 1 + ( int ) ( ( double ) ( bin_num ) * t );
}
bin[j] = bin[j] + 1;
}
//
// Compute the bin limits.
//
for ( i = 0; i <= bin_num; i++ )
{
bin_limit[i] = ( ( double ) ( bin_num - i ) * bin_min
+ ( double ) ( i ) * bin_max )
/ ( double ) ( bin_num );
}
return;
}
//****************************************************************************80
void r8vec_bracket ( int n, double x[], double xval, int &left,
int &right )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_BRACKET searches a sorted array for successive brackets of a value.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// If the values in the vector are thought of as defining intervals
// on the real line, then this routine searches for the interval
// nearest to or containing the given value.
//
// It is always true that RIGHT = LEFT+1.
//
// If XVAL < X[0], then LEFT = 1, RIGHT = 2, and
// XVAL < X[0] < X[1];
// If X(1) <= XVAL < X[N-1], then
// X[LEFT-1] <= XVAL < X[RIGHT-1];
// If X[N-1] <= XVAL, then LEFT = N-1, RIGHT = N, and
// X[LEFT-1] <= X[RIGHT-1] <= XVAL.
//
// For consistency, this routine computes indices RIGHT and LEFT
// that are 1-based, although it would be more natural in C and
// C++ to use 0-based values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 February 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, length of input array.
//
// Input, double X[N], an array that has been sorted into ascending order.
//
// Input, double XVAL, a value to be bracketed.
//
// Output, int &LEFT, &RIGHT, the results of the search.
//
{
int i;
for ( i = 2; i <= n - 1; i++ )
{
if ( xval < x[i-1] )
{
left = i - 1;
right = i;
return;
}
}
left = n - 1;
right = n;
return;
}
//****************************************************************************80
void r8vec_bracket2 ( int n, double x[], double xval, int start, int &left,
int &right )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_BRACKET2 searches a sorted array for successive brackets of a value.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// If the values in the vector are thought of as defining intervals
// on the real line, then this routine searches for the interval
// containing the given value.
//
// R8VEC_BRACKET2 is a variation on R8VEC_BRACKET. It seeks to reduce
// the search time by allowing the user to suggest an interval that
// probably contains the value. The routine will look in that interval
// and the intervals to the immediate left and right. If this does
// not locate the point, a binary search will be carried out on
// appropriate subportion of the sorted array.
//
// In the most common case, 1 <= LEFT < LEFT + 1 = RIGHT <= N,
// and X(LEFT) <= XVAL <= X(RIGHT).
//
// Special cases:
// Value is less than all data values:
// LEFT = -1, RIGHT = 1, and XVAL < X(RIGHT).
// Value is greater than all data values:
// LEFT = N, RIGHT = -1, and X(LEFT) < XVAL.
// Value is equal to a data value:
// LEFT = RIGHT, and X(LEFT) = X(RIGHT) = XVAL.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, length of the input array.
//
// Input, double X[N], an array that has been sorted into
// ascending order.
//
// Input, double XVAL, a value to be bracketed by entries of X.
//
// Input, int START, between 1 and N, specifies that XVAL
// is likely to be in the interval:
// [ X(START), X(START+1) ]
// or, if not in that interval, then either
// [ X(START+1), X(START+2) ]
// or
// [ X(START-1), X(START) ].
//
// Output, int &LEFT, &RIGHT, the results of the search.
//
{
int high;
int low;
//
// Check.
//
if ( n < 1 )
{
cerr << "\n";
cerr << "R8VEC_BRACKET2 - Fatal error!\n";
cerr << " N < 1.\n";
exit ( 1 );
}
if ( start < 1 || n < start )
{
start = ( n + 1 ) / 2;
}
//
// XVAL = X(START)?
//
if ( x[start-1] == xval )
{
left = start;
right = start;
return;
}
//
// X(START) < XVAL?
//
else if ( x[start-1] < xval )
{
//
// X(START) = X(N) < XVAL < oo?
//
if ( n < start + 1 )
{
left = start;
right = -1;
return;
}
//
// XVAL = X(START+1)?
//
else if ( xval == x[start] )
{
left = start + 1;
right = start + 1;
return;
}
//
// X(START) < XVAL < X(START+1)?
//
else if ( xval < x[start] )
{
left = start;
right = start + 1;
return;
}
//
// X(START+1) = X(N) < XVAL < oo?
//
else if ( n < start + 2 )
{
left = start + 1;
right = -1;
return;
}
//
// XVAL = X(START+2)?
//
else if ( xval == x[start+1] )
{
left = start + 2;
right = start + 2;
return;
}
//
// X(START+1) < XVAL < X(START+2)?
//
else if ( xval < x[start+1] )
{
left = start + 1;
right = start + 2;
return;
}
//
// Binary search for XVAL in [ X(START+2), X(N) ],
// where XVAL is guaranteed to be greater than X(START+2).
//
else
{
low = start + 2;
high = n;
r8vec_bracket ( high + 1 - low, x+low-1, xval, left, right );
left = left + low - 1;
right = right + low - 1;
}
}
//
// -oo < XVAL < X(START) = X(1).
//
else if ( start == 1 )
{
left = -1;
right = start;
return;
}
//
// XVAL = X(START-1)?
//
else if ( xval == x[start-2] )
{
left = start - 1;
right = start - 1;
return;
}
//
// X(START-1) < XVAL < X(START)?
//
else if ( x[start-2] <= xval )
{
left = start - 1;
right = start;
return;
}
//
// Binary search for XVAL in [ X(1), X(START-1) ],
// where XVAL is guaranteed to be less than X(START-1).
//
else
{
low = 1;
high = start - 1;
r8vec_bracket ( high + 1 - low, x, xval, left, right );
}
return;
}
//****************************************************************************80
void r8vec_bracket3 ( int n, double t[], double tval, int &left )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_BRACKET3 finds the interval containing or nearest a given value.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The routine always returns the index LEFT of the sorted array
// T with the property that either
// * T is contained in the interval [ T[LEFT], T[LEFT+1] ], or
// * T < T[LEFT] = T[0], or
// * T > T[LEFT+1] = T[N-1].
//
// The routine is useful for interpolation problems, where
// the abscissa must be located within an interval of data
// abscissas for interpolation, or the "nearest" interval
// to the (extreme) abscissa must be found so that extrapolation
// can be carried out.
//
// This version of the function has been revised so that the value of
// LEFT that is returned uses the 0-based indexing natural to C++.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 April 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, length of the input array.
//
// Input, double T[N], an array that has been sorted into ascending order.
//
// Input, double TVAL, a value to be bracketed by entries of T.
//
// Input/output, int &LEFT.
// On input, if 0 <= LEFT <= N-2, LEFT is taken as a suggestion for the
// interval [ T[LEFT-1] T[LEFT] ] in which TVAL lies. This interval
// is searched first, followed by the appropriate interval to the left
// or right. After that, a binary search is used.
// On output, LEFT is set so that the interval [ T[LEFT], T[LEFT+1] ]
// is the closest to TVAL; it either contains TVAL, or else TVAL
// lies outside the interval [ T[0], T[N-1] ].
//
{
int high;
int low;
int mid;
//
// Check the input data.
//
if ( n < 2 )
{
cerr << "\n";
cerr << "R8VEC_BRACKET3 - Fatal error!\n";
cerr << " N must be at least 2.\n";
exit ( 1 );
}
//
// If LEFT is not between 0 and N-2, set it to the middle value.
//
if ( left < 0 || n - 2 < left )
{
left = ( n - 1 ) / 2;
}
//
// CASE 1: TVAL < T[LEFT]:
// Search for TVAL in (T[I],T[I+1]), for I = 0 to LEFT-1.
//
if ( tval < t[left] )
{
if ( left == 0 )
{
return;
}
else if ( left == 1 )
{
left = 0;
return;
}
else if ( t[left-1] <= tval )
{
left = left - 1;
return;
}
else if ( tval <= t[1] )
{
left = 0;
return;
}
//
// ...Binary search for TVAL in (T[I],T[I+1]), for I = 1 to LEFT-2.
//
low = 1;
high = left - 2;
for ( ; ; )
{
if ( low == high )
{
left = low;
return;
}
mid = ( low + high + 1 ) / 2;
if ( t[mid] <= tval )
{
low = mid;
}
else
{
high = mid - 1;
}
}
}
//
// CASE 2: T[LEFT+1] < TVAL:
// Search for TVAL in (T[I],T[I+1]) for intervals I = LEFT+1 to N-2.
//
else if ( t[left+1] < tval )
{
if ( left == n - 2 )
{
return;
}
else if ( left == n - 3 )
{
left = left + 1;
return;
}
else if ( tval <= t[left+2] )
{
left = left + 1;
return;
}
else if ( t[n-2] <= tval )
{
left = n - 2;
return;
}
//
// ...Binary search for TVAL in (T[I],T[I+1]) for intervals I = LEFT+2 to N-3.
//
low = left + 2;
high = n - 3;
for ( ; ; )
{
if ( low == high )
{
left = low;
return;
}
mid = ( low + high + 1 ) / 2;
if ( t[mid] <= tval )
{
low = mid;
}
else
{
high = mid - 1;
}
}
}
//
// CASE 3: T[LEFT] <= TVAL <= T[LEFT+1]:
// T is just where the user said it might be.
//
else
{
}
return;
}
//****************************************************************************80
void r8vec_bracket4 ( int nt, double t[], int ns, double s[], int left[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_BRACKET4 finds the interval containing or nearest a given value.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The routine always returns the index LEFT of the sorted array
// T with the property that either
// * T is contained in the interval [ T[LEFT], T[LEFT+1] ], or
// * T < T[LEFT] = T[0], or
// * T > T[LEFT+1] = T[NT-1].
//
// The routine is useful for interpolation problems, where
// the abscissa must be located within an interval of data
// abscissas for interpolation, or the "nearest" interval
// to the (extreme) abscissa must be found so that extrapolation
// can be carried out.
//
// This version of the function has been revised so that the value of
// LEFT that is returned uses the 0-based indexing natural to C++.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 April 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NT, length of the input array.
//
// Input, double T[NT], an array that has been sorted
// into ascending order.
//
// Input, int NS, the number of points to be bracketed.
//
// Input, double S[NS], values to be bracketed by entries of T.
//
// Output, int LEFT[NS].
// LEFT[I] is set so that the interval [ T[LEFT[I]], T[LEFT[I]+1] ]
// is the closest to S[I]; it either contains S[I], or else S[I]
// lies outside the interval [ T[0], T[NT-1] ].
//
{
int high;
int i;
int low;
int mid;
//
// Check the input data.
//
if ( nt < 2 )
{
cerr << "\n";
cerr << "R8VEC_BRACKET4 - Fatal error!\n";
cerr << " NT must be at least 2.\n";
exit ( 1 );
}
for ( i = 0; i < ns; i++ )
{
left[i] = ( nt - 1 ) / 2;
//
// CASE 1: S[I] < T[LEFT]:
// Search for S[I] in (T[I],T[I+1]), for I = 0 to LEFT-1.
//
if ( s[i] < t[left[i]] )
{
if ( left[i] == 0 )
{
continue;
}
else if ( left[i] == 1 )
{
left[i] = 0;
continue;
}
else if ( t[left[i]-1] <= s[i] )
{
left[i] = left[i] - 1;
continue;
}
else if ( s[i] <= t[1] )
{
left[i] = 0;
continue;
}
//
// ...Binary search for S[I] in (T[I],T[I+1]), for I = 1 to *LEFT-2.
//
low = 1;
high = left[i] - 2;
for ( ; ; )
{
if ( low == high )
{
left[i] = low;
break;
}
mid = ( low + high + 1 ) / 2;
if ( t[mid] <= s[i] )
{
low = mid;
}
else
{
high = mid - 1;
}
}
}
//
// CASE 2: T[LEFT+1] < S[I]:
// Search for S[I] in (T[I],T[I+1]) for intervals I = LEFT+1 to NT-2.
//
else if ( t[left[i]+1] < s[i] )
{
if ( left[i] == nt - 2 )
{
continue;
}
else if ( left[i] == nt - 3 )
{
left[i] = left[i] + 1;
continue;
}
else if ( s[i] <= t[left[i]+2] )
{
left[i] = left[i] + 1;
continue;
}
else if ( t[nt-2] <= s[i] )
{
left[i] = nt - 2;
continue;
}
//
// ...Binary search for S[I] in (T[I],T[I+1]) for intervals I = LEFT+2 to NT-3.
//
low = left[i] + 2;
high = nt - 3;
for ( ; ; )
{
if ( low == high )
{
left[i] = low;
break;
}
mid = ( low + high + 1 ) / 2;
if ( t[mid] <= s[i] )
{
low = mid;
}
else
{
high = mid - 1;
}
}
}
//
// CASE 3: T[LEFT] <= S[I] <= T[LEFT+1]:
//
else
{
}
}
return;
}
//****************************************************************************80
int r8vec_bracket5 ( int nd, double xd[], double xi )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_BRACKET5 brackets data between successive entries of a sorted R8VEC.
//
// Discussion:
//
// We assume XD is sorted.
//
// If XI is contained in the interval [XD(1),XD(N)], then the returned
// value B indicates that XI is contained in [ XD(B), XD(B+1) ].
//
// If XI is not contained in the interval [XD(1),XD(N)], then B = -1.
//
// This code implements a version of binary search which is perhaps more
// understandable than the usual ones.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 October 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int ND, the number of data values.
//
// Input, double XD[N], the sorted data.
//
// Input, double XD, the query value.
//
// Output, int R8VEC_BRACKET5, the bracket information.
//
{
int b;
int l;
int m;
int r;
if ( xi < xd[0] || xd[nd-1] < xi )
{
b = -1;
}
else
{
l = 0;
r = nd - 1;
while ( l + 1 < r )
{
m = ( l + r ) / 2;
if ( xi < xd[m] )
{
r = m;
}
else
{
l = m;
}
}
b = l;
}
return b;
}
//****************************************************************************80
int *r8vec_bracket6 ( int nd, double xd[], int ni, double xi[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_BRACKET6 brackets data between successive entries of a sorted R8VEC.
//
// Discussion:
//
// We assume XD is sorted.
//
// If XI(I) is contained in the interval [XD(1),XD(N)], then the value of
// B(I) indicates that XI(I) is contained in [ XD(B(I)), XD(B(I)+1) ].
//
// If XI(I) is not contained in the interval [XD(1),XD(N)], then B(I) = -1.
//
// This code implements a version of binary search which is perhaps more
// understandable than the usual ones.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 October 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int ND, the number of data values.
//
// Input, double XD[N], the sorted data.
//
// Input, int NI, the number of inquiry values.
//
// Input, double XD[NI], the query values.
//
// Output, int R8VEC_BRACKET6[NI], the bracket information.
//
{
int *b;
int i;
int l;
int m;
int r;
b = new int[ni];
for ( i = 0; i < ni; i++ )
{
if ( xi[i] < xd[0] || xd[nd-1] < xi[i] )
{
b[i] = -1;
}
else
{
l = 0;
r = nd - 1;
while ( l + 1 < r )
{
m = ( l + r ) / 2;
if ( xi[i] < xd[m] )
{
r = m;
}
else
{
l = m;
}
}
b[i] = l;
}
}
return b;
}
//****************************************************************************80
double *r8vec_chebyspace_new ( int n, double a, double b )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CHEBYSPACE_NEW creates a vector of Chebyshev spaced values in [A,B].
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 June 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A, B, the first and last entries.
//
// Output, double R8VEC_CHEBYSPACE_NEW[N], a vector of Chebyshev spaced data.
//
{
double c;
int i;
const double r8_pi = 3.141592653589793;
double theta;
double *x;
x = new double[n];
if ( n == 1 )
{
x[0] = ( a + b ) / 2.0;
}
else
{
for ( i = 0; i < n; i++ )
{
theta = ( double ) ( n - i - 1 ) * r8_pi / ( double ) ( n - 1 );
c = cos ( theta );
if ( ( n % 2 ) == 1 )
{
if ( 2 * i + 1 == n )
{
c = 0.0;
}
}
x[i] = ( ( 1.0 - c ) * a
+ ( 1.0 + c ) * b )
/ 2.0;
}
}
return x;
}
//****************************************************************************80
double *r8vec_cheby1space_new ( int n, double a, double b )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CHEBY1SPACE_NEW creates Type 1 Chebyshev spaced values in [A,B].
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A, B, the interval.
//
// Output, double R8VEC_CHEBY1SPACE_NEW[N], a vector of Chebyshev spaced data.
//
{
double c;
int i;
const double r8_pi = 3.141592653589793;
double theta;
double *x;
x = new double[n];
if ( n == 1 )
{
x[0] = ( a + b ) / 2.0;
}
else
{
for ( i = 0; i < n; i++ )
{
theta = ( double ) ( 2 * ( n - i ) - 1 ) * r8_pi / ( double ) ( 2 * n );
c = cos ( theta );
if ( ( n % 2 ) == 1 )
{
if ( 2 * i + 1 == n )
{
c = 0.0;
}
}
x[i] = ( ( 1.0 - c ) * a
+ ( 1.0 + c ) * b )
/ 2.0;
}
}
return x;
}
//****************************************************************************80
double *r8vec_cheby2space_new ( int n, double a, double b )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CHEBY2SPACE_NEW creates Type 2 Chebyshev spaced values in [A,B].
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A, B, the interval.
//
// Output, double R8VEC_CHEBY2SPACE_NEW[N], a vector of Chebyshev spaced data.
//
{
double c;
int i;
const double r8_pi = 3.141592653589793;
double theta;
double *x;
x = new double[n];
if ( n == 1 )
{
x[0] = ( a + b ) / 2.0;
}
else
{
for ( i = 0; i < n; i++ )
{
theta = ( double ) ( n - i - 1 ) * r8_pi / ( double ) ( n - 1 );
c = cos ( theta );
if ( ( n % 2 ) == 1 )
{
if ( 2 * i + 1 == n )
{
c = 0.0;
}
}
x[i] = ( ( 1.0 - c ) * a
+ ( 1.0 + c ) * b )
/ 2.0;
}
}
return x;
}
//****************************************************************************80
double r8vec_circular_variance ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CIRCULAR_VARIANCE returns the circular variance of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 December 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double X[N], the vector whose variance is desired.
//
// Output, double R8VEC_CIRCULAR VARIANCE, the circular variance
// of the vector entries.
//
{
int i;
double mean;
double sum_c;
double sum_s;
double value;
mean = r8vec_mean ( n, x );
sum_c = 0.0;
for ( i = 0; i < n; i++ )
{
sum_c = sum_c + cos ( x[i] - mean );
}
sum_s = 0.0;
for ( i = 0; i < n; i++ )
{
sum_s = sum_s + sin ( x[i] - mean );
}
value = sqrt ( sum_c * sum_c + sum_s * sum_s ) / ( double ) n;
value = 1.0 - value;
return value;
}
//****************************************************************************80
int r8vec_compare ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_COMPARE compares two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The lexicographic ordering is used.
//
// Example:
//
// Input:
//
// A1 = ( 2.0, 6.0, 2.0 )
// A2 = ( 2.0, 8.0, 12.0 )
//
// Output:
//
// ISGN = -1
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double A[N], B[N], the vectors to be compared.
//
// Output, int R8VEC_COMPARE, the results of the comparison:
// -1, A is lexicographically less than B,
// 0, A is equal to B,
// +1, A is lexicographically greater than B.
//
{
int isgn;
int k;
isgn = 0;
for ( k = 0; k < n; k++ )
{
if ( a[k] < b[k] )
{
isgn = -1;
return isgn;
}
else if ( b[k] < a[k] )
{
isgn = +1;
return isgn;
}
}
return isgn;
}
//****************************************************************************80
void r8vec_concatenate ( int n1, double a[], int n2, double b[], double c[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CONCATENATE concatenates two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 November 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, the number of entries in the first vector.
//
// Input, double A[N1], the first vector.
//
// Input, int N2, the number of entries in the second vector.
//
// Input, double B[N2], the second vector.
//
// Output, double C[N1+N2], the concatenated vector.
//
{
int i;
for ( i = 0; i < n1; i++ )
{
c[i] = a[i];
}
for ( i = 0; i < n2; i++ )
{
c[n1+i] = b[i];
}
return;
}
//****************************************************************************80
double *r8vec_concatenate_new ( int n1, double a[], int n2, double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CONCATENATE_NEW concatenates two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 November 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, the number of entries in the first vector.
//
// Input, double A[N1], the first vector.
//
// Input, int N2, the number of entries in the second vector.
//
// Input, double B[N2], the second vector.
//
// Output, double R8VEC_CONCATENATE_NEW[N1+N2], the concatenated vector.
//
{
int i;
double *c;
c = new double[n1+n2];
for ( i = 0; i < n1; i++ )
{
c[i] = a[i];
}
for ( i = 0; i < n2; i++ )
{
c[n1+i] = b[i];
}
return c;
}
//****************************************************************************80
double *r8vec_convolution ( int m, double x[], int n, double y[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CONVOLUTION returns the convolution of two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The I-th entry of the convolution can be formed by summing the products
// that lie along the I-th diagonal of the following table:
//
// Y3 | 3 4 5 6 7
// Y2 | 2 3 4 5 6
// Y1 | 1 2 3 4 5
// +------------------
// X1 X2 X3 X4 X5
//
// which will result in:
//
// Z = ( X1 * Y1,
// X1 * Y2 + X2 * Y1,
// X1 * Y3 + X2 * Y2 + X3 * Y1,
// X2 * Y3 + X3 * Y2 + X4 * Y1,
// X3 * Y3 + X4 * Y2 + X5 * Y1,
// X4 * Y3 + X5 * Y2,
// X5 * Y3 )
//
// Example:
//
// Input:
//
// X = (/ 1, 2, 3, 4 /)
// Y = (/ -1, 5, 3 /)
//
// Output:
//
// Z = (/ -1, 3, 10, 17, 29, 12 /)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 May 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the dimension of X.
//
// Input, double X[M], the first vector to be convolved.
//
// Input, int N, the dimension of Y.
//
// Input, double Y[N], the second vector to be convolved.
//
// Output, double R8VEC_CONVOLUTION[M+N-1], the convolution of X and Y.
//
{
int i;
int j;
double *z;
z = new double[m+n-1];
for ( i = 0; i < m + n - 1; i++ )
{
z[i] = 0.0;
}
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
z[j+i] = z[j+i] + x[i] * y[j];
}
}
return z;
}
//****************************************************************************80
double *r8vec_convolution_circ ( int n, double x[], double y[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CONVOLUTION_CIRC returns the discrete circular convolution of two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// z(1+m) = xCCy(m) = sum ( 0 <= k <= n-1 ) x(1+k) * y(1+m-k)
//
// Here, if the index of Y becomes nonpositive, it is "wrapped around"
// by having N added to it.
//
// The circular convolution is equivalent to multiplication of Y by a
// circulant matrix formed from the vector X.
//
// Example:
//
// Input:
//
// X = (/ 1, 2, 3, 4 /)
// Y = (/ 1, 2, 4, 8 /)
//
// Output:
//
// Circulant form:
//
// Z = ( 1 4 3 2 ) ( 1 )
// ( 2 1 4 3 ) ( 2 )
// ( 3 2 1 4 ) * ( 4 )
// ( 4 3 2 1 ) ( 8 )
//
// The formula:
//
// Z = (/ 1*1 + 2*8 + 3*4 + 4*2,
// 1*2 + 2*1 + 3*8 + 4*4,
// 1*4 + 2*2 + 3*1 + 4*8,
// 1*8 + 2*4 + 3*2 + 4*1 /)
//
// Result:
//
// Z = (/ 37, 44, 43, 26 /)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vectors.
//
// Input, double X[N], Y[N], the vectors to be convolved.
//
// Output, double R8VEC_CONVOLVE_CIRC[N], the circular convolution of X and Y.
//
{
int i;
int m;
double *z;
z = new double[n];
for ( m = 1; m <= n; m++ )
{
z[m-1] = 0.0;
for ( i = 1; i <= m; i++ )
{
z[m-1] = z[m-1] + x[i-1] * y[m-i];
}
for ( i = m+1; i <= n; i++ )
{
z[m-1] = z[m-1] + x[i-1] * y[n+m-i];
}
}
return z;
}
//****************************************************************************80
void r8vec_copy ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_COPY copies an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 July 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double A1[N], the vector to be copied.
//
// Output, double A2[N], the copy of A1.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a2[i] = a1[i];
}
return;
}
//****************************************************************************80
double *r8vec_copy_new ( int n, double a1[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_COPY_NEW copies an R8VEC to a new R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double A1[N], the vector to be copied.
//
// Output, double R8VEC_COPY_NEW[N], the copy of A1.
//
{
double *a2;
int i;
a2 = new double[n];
for ( i = 0; i < n; i++ )
{
a2[i] = a1[i];
}
return a2;
}
//****************************************************************************80
double r8vec_correlation ( int n, double x[], double y[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CORRELATION returns the correlation of two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// If X and Y are two nonzero vectors of length N, then
//
// correlation = (x/||x||)' (y/||y||)
//
// It is the cosine of the angle between the two vectors.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 21 August 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vectors.
//
// Input, double X[N], Y[N], the vectors to be convolved.
//
// Output, double R8VEC_CORRELATION, the correlation of X and Y.
//
{
double correlation;
double x_norm;
double xy_dot;
double y_norm;
x_norm = r8vec_norm ( n, x );
y_norm = r8vec_norm ( n, y );
xy_dot = r8vec_dot_product ( n, x, y );
if ( x_norm == 0.0 || y_norm == 0.0 )
{
correlation = 0.0;
}
else
{
correlation = xy_dot / x_norm / y_norm;
}
return correlation;
}
//****************************************************************************80
double r8vec_covar ( int n, double x[], double y[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_COVAR computes the covariance of two vectors.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 20 April 2013
//
// Author:
//
// John Burkardt.
//
// Parameters:
//
// Input, int N, the dimension of the two vectors.
//
// Input, double X[N], Y[N], the two vectors.
//
// Output, double R8VEC_COVAR, the covariance of the two vectors.
//
{
int i;
double value;
double x_average;
double y_average;
x_average = 0.0;
for ( i = 0; i < n; i++ )
{
x_average = x_average + x[i];
}
x_average = x_average / ( double ) ( n );
y_average = 0.0;
for ( i = 0; i < n; i++ )
{
y_average = y_average + x[i];
}
y_average = y_average / ( double ) ( n );
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + ( x[i] - x_average ) * ( y[i] - y_average );
}
value = value / ( double ) ( n - 1 );
return value;
}
//****************************************************************************80
double r8vec_cross_product_2d ( double v1[2], double v2[2] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CROSS_PRODUCT_2D finds the cross product of a pair of R8VEC's in 2D.
//
// Discussion:
//
// Strictly speaking, the vectors lie in the (X,Y) plane, and
// the cross product here is a vector in the Z direction.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double V1[2], V2[2], the vectors.
//
// Output, double R8VEC_CROSS_PRODUCT_2D, the Z component of the cross product
// of V1 and V2.
//
{
double value;
value = v1[0] * v2[1] - v1[1] * v2[0];
return value;
}
//****************************************************************************80
double r8vec_cross_product_affine_2d ( double v0[2], double v1[2],
double v2[2] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CROSS_PRODUCT_AFFINE_2D finds the affine cross product in 2D.
//
// Discussion:
//
// Strictly speaking, the vectors lie in the (X,Y) plane, and
// the cross product here is a vector in the Z direction.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double V0[2], the base vector.
//
// Input, double V1[2], V2[2], the vectors.
//
// Output, double R8VEC_CROSS_PRODUCT_AFFINE_2D, the Z component of the
// cross product of V1 and V2.
//
{
double value;
value =
( v1[0] - v0[0] ) * ( v2[1] - v0[1] )
- ( v2[0] - v0[0] ) * ( v1[1] - v0[1] );
return value;
}
//****************************************************************************80
double *r8vec_cross_product_3d ( double v1[3], double v2[3] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CROSS_PRODUCT_3D computes the cross product of two R8VEC's in 3D.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double V1[3], V2[3], the coordinates of the vectors.
//
// Output, double R8VEC_CROSS_PRODUCT_3D[3], the cross product vector.
//
{
double *v3;
v3 = new double[3];
v3[0] = v1[1] * v2[2] - v1[2] * v2[1];
v3[1] = v1[2] * v2[0] - v1[0] * v2[2];
v3[2] = v1[0] * v2[1] - v1[1] * v2[0];
return v3;
}
//****************************************************************************80
double *r8vec_cross_product_affine_3d ( double v0[3], double v1[3],
double v2[3] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CROSS_PRODUCT_AFFINE_3D computes the affine cross product in 3D.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double V0[3], the base vector.
//
// Input, double V1[3], V2[3], the coordinates of the vectors.
//
// Output, double R8VEC_CROSS_PRODUCT_AFFINE_3D[3], the cross product vector.
//
{
double *v3;
v3 = ( double * ) malloc ( 3 * sizeof ( double ) );
v3[0] =
( v1[1] - v0[1] ) * ( v2[2] - v0[2] )
- ( v2[1] - v0[1] ) * ( v1[2] - v0[2] );
v3[1] =
( v1[2] - v0[2] ) * ( v2[0] - v0[0] )
- ( v2[2] - v0[2] ) * ( v1[0] - v0[0] );
v3[2] =
( v1[0] - v0[0] ) * ( v2[1] - v0[1] )
- ( v2[0] - v0[0] ) * ( v1[1] - v0[1] );
return v3;
}
//****************************************************************************80
double *r8vec_cum_new ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CUM_NEW computes the cumulutive sums of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Input:
//
// A = { 1.0, 2.0, 3.0, 4.0 }
//
// Output:
//
// A_CUM = { 1.0, 3.0, 6.0, 10.0 }
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 May 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], the vector to be summed.
//
// Output, double R8VEC_CUM_NEW[N], the cumulative sums.
//
{
double *a_cum;
int i;
a_cum = new double[n];
a_cum[0] = a[0];
for ( i = 1; i < n; i++ )
{
a_cum[i] = a_cum[i-1] + a[i];
}
return a_cum;
}
//****************************************************************************80
double *r8vec_cum0_new ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_CUM0_NEW computes the cumulutive sums of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Input:
//
// A = { 1.0, 2.0, 3.0, 4.0 }
//
// Output:
//
// A_CUM = { 0.0, 1.0, 3.0, 6.0, 10.0 }
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 May 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], the vector to be summed.
//
// Output, double R8VEC_CUM0_NEW[N+1], the cumulative sums.
//
{
double *a_cum;
int i;
a_cum = new double[n+1];
a_cum[0] = 0.0;
for ( i = 1; i <= n; i++ )
{
a_cum[i] = a_cum[i-1] + a[i-1];
}
return a_cum;
}
//****************************************************************************80
double *r8vec_dif ( int n, double h )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIF computes coefficients for estimating the N-th derivative.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The routine computes the N+1 coefficients for a centered finite difference
// estimate of the N-th derivative of a function.
//
// The estimate has the form
//
// FDIF(N,X) = Sum (I = 0 to N) COF(I) * F ( X(I) )
//
// To understand the computation of the coefficients, it is enough
// to realize that the first difference approximation is
//
// FDIF(1,X) = F(X+DX) - F(X-DX) ) / (2*DX)
//
// and that the second difference approximation can be regarded as
// the first difference approximation repeated:
//
// FDIF(2,X) = FDIF(1,X+DX) - FDIF(1,X-DX) / (2*DX)
// = F(X+2*DX) - 2 F(X) + F(X-2*DX) / (4*DX)
//
// and so on for higher order differences.
//
// Thus, the next thing to consider is the integer coefficients of
// the sampled values of F, which are clearly the Pascal coefficients,
// but with an alternating negative sign. In particular, if we
// consider row I of Pascal's triangle to have entries j = 0 through I,
// then P(I,J) = P(I-1,J-1) - P(I-1,J), where P(*,-1) is taken to be 0,
// and P(0,0) = 1.
//
// 1
// -1 1
// 1 -2 1
// -1 3 -3 1
// 1 -4 6 -4 1
// -1 5 -10 10 -5 1
// 1 -6 15 -20 15 -6 1
//
// Next, note that the denominator of the approximation for the
// N-th derivative will be (2*DX)^N.
//
// And finally, consider the location of the N+1 sampling
// points for F:
//
// X-N*DX, X-(N-2)*DX, X-(N-4)*DX, ..., X+(N-4)*DX, X+(N-2*DX), X+N*DX.
//
// Thus, a formula for evaluating FDIF(N,X) is
//
// fdif = 0.0
// do i = 0, n
// xi = x + (2*i-n) * h
// fdif = fdif + cof(i) * f(xi)
// end do
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the derivative to be approximated.
// N must be 0 or greater.
//
// Input, double H, the half spacing between points.
// H must be positive.
//
// Output, double R8VEC_DIF[N+1], the coefficients needed to approximate
// the N-th derivative of a function F.
//
{
double *cof;
int i;
int j;
if ( n < 0 )
{
cerr << "\n";
cerr << "R8VEC_DIF - Fatal error!\n";
cerr << " Derivative order N = " << n << "\n";
cerr << " but N must be at least 0.\n";
exit ( 1 );
}
if ( h <= 0.0 )
{
cerr << "\n";
cerr << "R8VEC_DIF - Fatal error!\n";
cerr << " The half sampling spacing is H = " << h << "\n";
cerr << " but H must be positive.\n";
exit ( 1 );
}
cof = new double[n+1];
for ( i = 0; i <= n; i++ )
{
cof[i] = 1.0;
for ( j = i - 1; 1 <= j; j-- )
{
cof[j] = -cof[j] + cof[j-1];
}
if ( 0 < i )
{
cof[0] = - cof[0];
}
}
for ( i = 0; i <= n; i++ )
{
cof[i] = cof[i] / pow ( 2.0 * h, n );
}
return cof;
}
//****************************************************************************80
double r8vec_diff_norm ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIFF_NORM returns the L2 norm of the difference of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L2 norm is defined as:
//
// R8VEC_NORM_L2 = sqrt ( sum ( 1 <= I <= N ) A(I)^2 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 June 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], B[N], the vectors.
//
// Output, double R8VEC_DIFF_NORM, the L2 norm of A - B.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + ( a[i] - b[i] ) * ( a[i] - b[i] );
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
double r8vec_diff_norm_l1 ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIFF_NORM_L1 returns the L1 norm of the difference of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L1 norm is defined as:
//
// R8VEC_NORM_L1 = sum ( 1 <= I <= N ) abs ( A(I) ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 April 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], B[N], the vectors.
//
// Output, double R8VEC_DIFF_NORM_L1, the L1 norm of A - B.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + fabs ( a[i] - b[i] );
}
return value;
}
//****************************************************************************80
double r8vec_diff_norm_l2 ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIFF_NORM_L2 returns the L2 norm of the difference of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L2 norm is defined as:
//
// R8VEC_NORM_L2 = sqrt ( sum ( 1 <= I <= N ) A(I)^2 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 June 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], B[N], the vectors.
//
// Output, double R8VEC_DIFF_NORM_L2, the L2 norm of A - B.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + ( a[i] - b[i] ) * ( a[i] - b[i] );
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
double r8vec_diff_norm_li ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIFF_NORM_LI returns the L-oo norm of the difference of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L-oo norm is defined as:
//
// R8VEC_NORM_LI = max ( 1 <= I <= N ) abs ( A(I) ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 April 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], B[N], the vectors.
//
// Output, double R8VEC_DIFF_NORM_LI, the L-oo norm of A - B.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = r8_max ( value, fabs ( a[i] - b[i] ) );
}
return value;
}
//****************************************************************************80
double r8vec_diff_norm_squared ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIFF_NORM_SQUARED: square of the L2 norm of the difference of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The square of the L2 norm of the difference of A and B is:
//
// R8VEC_DIFF_NORM_SQUARED = sum ( 1 <= I <= N ) ( A[I] - B[I] )^2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 June 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], B[N], the vectors.
//
// Output, double R8VEC_DIFF_NORM_SQUARED, the square of the L2 norm of A - B.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + ( a[i] - b[i] ) * ( a[i] - b[i] );
}
return value;
}
//****************************************************************************80
void r8vec_direct_product ( int factor_index, int factor_order,
double factor_value[], int factor_num, int point_num, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIRECT_PRODUCT creates a direct product of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// To explain what is going on here, suppose we had to construct
// a multidimensional quadrature rule as the product of K rules
// for 1D quadrature.
//
// The product rule will be represented as a list of points and weights.
//
// The J-th item in the product rule will be associated with
// item J1 of 1D rule 1,
// item J2 of 1D rule 2,
// ...,
// item JK of 1D rule K.
//
// In particular,
// X(J) = ( X(1,J1), X(2,J2), ..., X(K,JK))
// and
// W(J) = W(1,J1) * W(2,J2) * ... * W(K,JK)
//
// So we can construct the quadrature rule if we can properly
// distribute the information in the 1D quadrature rules.
//
// This routine carries out that task.
//
// Another way to do this would be to compute, one by one, the
// set of all possible indices (J1,J2,...,JK), and then index
// the appropriate information. An advantage of the method shown
// here is that you can process the K-th set of information and
// then discard it.
//
// Example:
//
// Rule 1:
// Order = 4
// X(1:4) = ( 1, 2, 3, 4 )
//
// Rule 2:
// Order = 3
// X(1:3) = ( 10, 20, 30 )
//
// Rule 3:
// Order = 2
// X(1:2) = ( 100, 200 )
//
// Product Rule:
// Order = 24
// X(1:24) =
// ( 1, 10, 100 )
// ( 2, 10, 100 )
// ( 3, 10, 100 )
// ( 4, 10, 100 )
// ( 1, 20, 100 )
// ( 2, 20, 100 )
// ( 3, 20, 100 )
// ( 4, 20, 100 )
// ( 1, 30, 100 )
// ( 2, 30, 100 )
// ( 3, 30, 100 )
// ( 4, 30, 100 )
// ( 1, 10, 200 )
// ( 2, 10, 200 )
// ( 3, 10, 200 )
// ( 4, 10, 200 )
// ( 1, 20, 200 )
// ( 2, 20, 200 )
// ( 3, 20, 200 )
// ( 4, 20, 200 )
// ( 1, 30, 200 )
// ( 2, 30, 200 )
// ( 3, 30, 200 )
// ( 4, 30, 200 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 April 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int FACTOR_INDEX, the index of the factor being processed.
// The first factor processed must be factor 0.
//
// Input, int FACTOR_ORDER, the order of the factor.
//
// Input, double FACTOR_VALUE[FACTOR_ORDER], the factor values
// for factor FACTOR_INDEX.
//
// Input, int FACTOR_NUM, the number of factors.
//
// Input, int POINT_NUM, the number of elements in the direct product.
//
// Input/output, double X[FACTOR_NUM*POINT_NUM], the elements of the
// direct product, which are built up gradually.
//
// Local Parameters:
//
// Local, int START, the first location of a block of values to set.
//
// Local, int CONTIG, the number of consecutive values to set.
//
// Local, int SKIP, the distance from the current value of START
// to the next location of a block of values to set.
//
// Local, int REP, the number of blocks of values to set.
//
{
static int contig = 0;
int i;
int j;
int k;
static int rep = 0;
static int skip = 0;
int start;
if ( factor_index == 0 )
{
contig = 1;
skip = 1;
rep = point_num;
for ( j = 0; j < point_num; j++ )
{
for ( i = 0; i < factor_num; i++ )
{
x[i+j*factor_num] = 0.0;
}
}
}
rep = rep / factor_order;
skip = skip * factor_order;
for ( i = 0; i < factor_order; i++ )
{
start = 0 + i * contig;
for ( k = 1; k <= rep; k++ )
{
for ( j = start; j < start + contig; j++ )
{
x[factor_index+j*factor_num] = factor_value[i];
}
start = start + skip;
}
}
contig = contig * factor_order;
return;
}
//****************************************************************************80
void r8vec_direct_product2 ( int factor_index, int factor_order,
double factor_value[], int factor_num, int point_num, double w[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIRECT_PRODUCT2 creates a direct product of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// To explain what is going on here, suppose we had to construct
// a multidimensional quadrature rule as the product of K rules
// for 1D quadrature.
//
// The product rule will be represented as a list of points and weights.
//
// The J-th item in the product rule will be associated with
// item J1 of 1D rule 1,
// item J2 of 1D rule 2,
// ...,
// item JK of 1D rule K.
//
// In particular,
// X(J) = ( X(1,J1), X(2,J2), ..., X(K,JK))
// and
// W(J) = W(1,J1) * W(2,J2) * ... * W(K,JK)
//
// So we can construct the quadrature rule if we can properly
// distribute the information in the 1D quadrature rules.
//
// This routine carries out that task for the weights W.
//
// Another way to do this would be to compute, one by one, the
// set of all possible indices (J1,J2,...,JK), and then index
// the appropriate information. An advantage of the method shown
// here is that you can process the K-th set of information and
// then discard it.
//
// Example:
//
// Rule 1:
// Order = 4
// W(1:4) = ( 2, 3, 5, 7 )
//
// Rule 2:
// Order = 3
// W(1:3) = ( 11, 13, 17 )
//
// Rule 3:
// Order = 2
// W(1:2) = ( 19, 23 )
//
// Product Rule:
// Order = 24
// W(1:24) =
// ( 2 * 11 * 19 )
// ( 3 * 11 * 19 )
// ( 4 * 11 * 19 )
// ( 7 * 11 * 19 )
// ( 2 * 13 * 19 )
// ( 3 * 13 * 19 )
// ( 5 * 13 * 19 )
// ( 7 * 13 * 19 )
// ( 2 * 17 * 19 )
// ( 3 * 17 * 19 )
// ( 5 * 17 * 19 )
// ( 7 * 17 * 19 )
// ( 2 * 11 * 23 )
// ( 3 * 11 * 23 )
// ( 5 * 11 * 23 )
// ( 7 * 11 * 23 )
// ( 2 * 13 * 23 )
// ( 3 * 13 * 23 )
// ( 5 * 13 * 23 )
// ( 7 * 13 * 23 )
// ( 2 * 17 * 23 )
// ( 3 * 17 * 23 )
// ( 5 * 17 * 23 )
// ( 7 * 17 * 23 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 April 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int FACTOR_INDEX, the index of the factor being processed.
// The first factor processed must be factor 0.
//
// Input, int FACTOR_ORDER, the order of the factor.
//
// Input, double FACTOR_VALUE[FACTOR_ORDER], the factor values for
// factor FACTOR_INDEX.
//
// Input, int FACTOR_NUM, the number of factors.
//
// Input, int POINT_NUM, the number of elements in the direct product.
//
// Input/output, double W[POINT_NUM], the elements of the
// direct product, which are built up gradually.
//
// Local Parameters:
//
// Local, integer START, the first location of a block of values to set.
//
// Local, integer CONTIG, the number of consecutive values to set.
//
// Local, integer SKIP, the distance from the current value of START
// to the next location of a block of values to set.
//
// Local, integer REP, the number of blocks of values to set.
//
{
static int contig = 0;
int i;
int j;
int k;
static int rep = 0;
static int skip = 0;
int start;
if ( factor_index == 0 )
{
contig = 1;
skip = 1;
rep = point_num;
for ( i = 0; i < point_num; i++ )
{
w[i] = 1.0;
}
}
rep = rep / factor_order;
skip = skip * factor_order;
for ( j = 0; j < factor_order; j++ )
{
start = 0 + j * contig;
for ( k = 1; k <= rep; k++ )
{
for ( i = start; i < start + contig; i++ )
{
w[i] = w[i] * factor_value[j];
}
start = start + skip;
}
}
contig = contig * factor_order;
return;
}
//****************************************************************************80
double r8vec_distance ( int dim_num, double v1[], double v2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DISTANCE returns the Euclidean distance between two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the spatial dimension.
//
// Input, double V1[DIM_NUM], V2[DIM_NUM], the vectors.
//
// Output, double R8VEC_DISTANCE, the Euclidean distance
// between the vectors.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < dim_num; i++ )
{
value = pow ( v1[i] - v2[i], 2 );
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
bool r8vec_distinct ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DISTINCT is true if the entries in an R8VEC are distinct.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 January 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double X[N], the vector to be checked.
//
// Output, bool R8VEC_DISTINCT is true if all N elements of X
// are distinct.
//
{
int i;
int j;
for ( i = 1; i <= n-1; i++ )
{
for ( j = 1; j <= i - 1; j++ )
{
if ( x[i] == x[j] )
{
return false;
}
}
}
return true;
}
//****************************************************************************80
void r8vec_divide ( int n, double a[], double s )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DIVIDE divides an R8VEC by a nonzero scalar.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 August 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input/output, double A[N]. On input, the vector to be scaled.
// On output, each entry has been divided by S.
//
// Input, double S, the divisor.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = a[i] / s;
}
return;
}
//****************************************************************************80
double r8vec_dot_product ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DOT_PRODUCT computes the dot product of a pair of R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 July 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double A1[N], A2[N], the two vectors to be considered.
//
// Output, double R8VEC_DOT_PRODUCT, the dot product of the vectors.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + a1[i] * a2[i];
}
return value;
}
//****************************************************************************80
double r8vec_dot_product_affine ( int n, double v0[], double v1[], double v2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_DOT_PRODUCT_AFFINE computes the affine dot product.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double V0[N], the base vector.
//
// Input, double V1[N], V2[N], the two vectors to be considered.
//
// Output, double R8VEC_DOT_PRODUCT_AFFINE, the dot product of the vectors.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + ( v1[i] - v0[i] ) * ( v2[i] - v0[i] );
}
return value;
}
//****************************************************************************80
double r8vec_entropy ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ENTROPY computes the entropy of an R8VEC.
//
// Discussion:
//
// Typically, the entries represent probabilities, and must sum to 1.
// For this function, the only requirement is that the entries be nonnegative.
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 August 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double X[N], the vector.
// Each entry must be nonnegative.
//
// Output, double R8VEC_ENTROPY, the entropy of the
// normalized vector.
//
{
int i;
double value;
double x_sum;
double xi;
for ( i = 0; i < n; i++ )
{
if ( x[i] < 0.0 )
{
cerr << "\n";
cerr << "R8VEC_ENTROPY - Fatal error!\n";
cerr << " Some entries are negative.\n";
exit ( 1 );
}
}
x_sum = 0.0;
for ( i = 0; i < n; i++ )
{
x_sum = x_sum + x[i];
}
if ( x_sum == 0.0 )
{
cerr << "\n";
cerr << "R8VEC_ENTROPY - Fatal error!\n";
cerr << " Entries sum to 0.\n";
exit ( 1 );
}
value = 0.0;
for ( i = 0; i < n; i++ )
{
if ( 0.0 < x[i] )
{
xi = x[i] / x_sum;
value = value - r8_log_2 ( xi ) * xi;
}
}
return value;
}
//****************************************************************************80
bool r8vec_eq ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EQ is true if every pair of entries in two R8VEC's is equal.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double A1[N], A2[N], two vectors to compare.
//
// Output, bool R8VEC_EQ, is TRUE if every pair of elements A1(I)
// and A2(I) are equal, and FALSE otherwise.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( a1[i] != a2[i] )
{
return false;
}
}
return true;
}
//****************************************************************************80
void r8vec_even ( int n, double alo, double ahi, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EVEN returns an R8VEC of values evenly spaced between ALO and AHI.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 February 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of values.
//
// Input, double ALO, AHI, the low and high values.
//
// Output, double A[N], N evenly spaced values.
// Normally, A[0] = ALO and A[N-1] = AHI.
// However, if N = 1, then A[0] = 0.5*(ALO+AHI).
//
{
int i;
if ( n == 1 )
{
a[0] = 0.5 * ( alo + ahi );
}
else
{
for ( i = 0; i < n; i++ )
{
a[i] = ( ( double ) ( n - i - 1 ) * alo
+ ( double ) ( i ) * ahi )
/ ( double ) ( n - 1 );
}
}
return;
}
//****************************************************************************80
double *r8vec_even_new ( int n, double alo, double ahi )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EVEN_NEW returns an R8VEC of values evenly spaced between ALO and AHI.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 May 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of values.
//
// Input, double ALO, AHI, the low and high values.
//
// Output, double R8VEC_EVEN_NEW[N], N evenly spaced values.
// Normally, A[0] = ALO and A[N-1] = AHI.
// However, if N = 1, then A[0] = 0.5*(ALO+AHI).
//
{
double *a;
int i;
a = new double[n];
if ( n == 1 )
{
a[0] = 0.5 * ( alo + ahi );
}
else
{
for ( i = 0; i < n; i++ )
{
a[i] = ( ( double ) ( n - i - 1 ) * alo
+ ( double ) ( i ) * ahi )
/ ( double ) ( n - 1 );
}
}
return a;
}
//****************************************************************************80
double r8vec_even_select ( int n, double xlo, double xhi, int ival )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EVEN_SELECT returns the I-th of N evenly spaced values in [ XLO, XHI ].
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// XVAL = ( (N-IVAL) * XLO + (IVAL-1) * XHI ) / ( N - 1 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 January 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of values.
//
// Input, double XLO, XHI, the low and high values.
//
// Input, int IVAL, the index of the desired point.
// IVAL is normally between 1 and N, but may be any integer value.
//
// Output, double R8VEC_EVEN_SELECT, the IVAL-th of N evenly spaced values
// between XLO and XHI.
// Unless N = 1, X(1) = XLO and X(N) = XHI.
// If N = 1, then X(1) = 0.5*(XLO+XHI).
//
{
double xval;
if ( n == 1 )
{
xval = 0.5 * ( xlo + xhi );
}
else
{
xval = ( ( double ) ( n - ival ) * xlo
+ ( double ) ( ival - 1 ) * xhi )
/ ( double ) ( n - 1 );
}
return xval;
}
//****************************************************************************80
void r8vec_even2 ( int maxval, int nfill[], int nold, double xold[],
int &nval, double xval[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EVEN2 linearly interpolates new numbers into an R8VECa.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The number of values created between two old values can vary from
// one pair of values to the next.
//
// The interpolated values are evenly spaced.
//
// This routine is a generalization of R8VEC_EVEN.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 November 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int MAXVAL, the size of the XVAL array, as declared by the
// user. MAXVAL must be large enough to hold the NVAL values computed by
// this routine. In other words, MAXVAL must be at least equal to
// NOLD + SUM (1 <= I <= NOLD-1) NFILL(I).
//
// Input, int NFILL[NOLD-1], the number of values
// to be interpolated between XOLD(I) and XOLD(I+1).
// NFILL(I) does not count the endpoints. Thus, if
// NFILL(I) is 1, there will be one new point generated
// between XOLD(I) and XOLD(I+1).
// NFILL(I) must be nonnegative.
//
// Input, int NOLD, the number of values XOLD,
// between which extra values are to be interpolated.
//
// Input, double XOLD[NOLD], the original vector of numbers
// between which new values are to be interpolated.
//
// Output, int &NVAL, the number of values computed
// in the XVAL array.
// NVAL = NOLD + SUM ( 1 <= I <= NOLD-1 ) NFILL(I)
//
// Output, double XVAL[MAXVAL]. On output, XVAL contains the
// NOLD values of XOLD, as well as the interpolated
// values, making a total of NVAL values.
//
{
int i;
int j;
int nadd;
nval = 1;
for ( i = 1; i <= nold - 1; i++ )
{
if ( nfill[i-1] < 0 )
{
cerr << "\n";
cerr << "R8VEC_EVEN2 - Fatal error!\n";
cerr << " NFILL[I-1] is negative for I = " << i << "\n";
cerr << " NFILL[I-1] = " << nfill[i-1] << "\n";
exit ( 1 );
}
if ( maxval < nval + nfill[i-1] + 1 )
{
cerr << "\n";
cerr << "R8VEC_EVEN2 - Fatal error!\n";
cerr << " MAXVAL = " << maxval << " is not large enough.\n";
cerr << " for the storage for interval I = " << i << "\n";
exit ( 1 );
}
nadd = nfill[i-1] + 2;
for ( j = 1; j <= nadd; j++ )
{
xval[nval+j-2] = ( ( double ) ( nadd - j ) * xold[i-1]
+ ( double ) ( j - 1 ) * xold[i] )
/ ( double ) ( nadd - 1 );
}
nval = nval + nfill[i-1] + 1;
}
return;
}
//****************************************************************************80
double r8vec_even2_select ( int n, double xlo, double xhi, int ival )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EVEN2_SELECT returns the I-th of N evenly spaced midpoint values.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// This function returns the I-th of N evenly spaced midpoints of N
// equal subintervals of [XLO,XHI].
//
// XVAL = ( ( 2 * N - 2 * IVAL + 1 ) * XLO
// + ( 2 * IVAL - 1 ) * XHI )
// / ( 2 * N )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 July 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of values.
//
// Input, double XLO, XHI, the low and high values.
//
// Input, int IVAL, the index of the desired point.
// IVAL is normally between 1 and N, but may be any integer value.
//
// Output, double R8VEC_EVEN2_SELECT, the IVAL-th of N evenly spaced midpoints
// between XLO and XHI.
//
{
double xval;
xval = ( ( double ) ( 2 * n - 2 * ival + 1 ) * xlo
+ ( double ) ( 2 * ival - 1 ) * xhi )
/ ( double ) ( 2 * n );
return xval;
}
//****************************************************************************80
void r8vec_even3 ( int nold, int nval, double xold[], double xval[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EVEN3 evenly interpolates new data into an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// This routine accepts a short vector of numbers, and returns a longer
// vector of numbers, created by interpolating new values between
// the given values.
//
// Between any two original values, new values are evenly interpolated.
//
// Over the whole vector, the new numbers are interpolated in
// such a way as to try to minimize the largest distance interval size.
//
// The algorithm employed is not "perfect".
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NOLD, the number of values XOLD, between which extra
// values are to be interpolated.
//
// Input, int NVAL, the number of values to be computed
// in the XVAL array. NVAL should be at least NOLD.
//
// Input, double XOLD[NOLD], the original vector of numbers
// between which new values are to be interpolated.
//
// Output, double XVAL[NVAL]. On output, XVAL contains the
// NOLD values of XOLD, as well as interpolated
// values, making a total of NVAL values.
//
{
double density;
int i;
int ival;
int j;
int nmaybe;
int npts;
int ntemp;
int ntot;
double xlen;
double xleni;
double xlentot;
xlen = 0.0;
for ( i = 1; i <= nold - 1; i++ )
{
xlen = xlen + fabs ( xold[i] - xold[i-1] );
}
ntemp = nval - nold;
density = ( double ) ( ntemp ) / xlen;
ival = 1;
ntot = 0;
xlentot = 0.0;
for ( i = 1; i <= nold - 1; i++ )
{
xleni = fabs ( xold[i] - xold[i-1] );
npts = ( int ) ( density * xleni );
ntot = ntot + npts;
//
// Determine if we have enough left-over density that it should
// be changed into a point. A better algorithm would agonize
// more over where that point should go.
//
xlentot = xlentot + xleni;
nmaybe = r8_nint ( xlentot * density );
if ( ntot < nmaybe )
{
npts = npts + nmaybe - ntot;
ntot = nmaybe;
}
for ( j = 1; j <= npts + 2; j++ )
{
xval[ival+j-2] = ( ( double ) ( npts+2 - j ) * xold[i-1]
+ ( double ) ( j - 1 ) * xold[i] )
/ ( double ) ( npts+2 - 1 );
}
ival = ival + npts + 1;
}
return;
}
//****************************************************************************80
double *r8vec_expand_linear ( int n, double x[], int fat )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EXPAND_LINEAR linearly interpolates new data into an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of input data values.
//
// Input, double X[N], the original data.
//
// Input, int FAT, the number of data values to interpolate
// between each pair of original data values.
//
// Output, double R8VEC_EXPAND_LINEAR[(N-1)*(FAT+1)+1], the "fattened" data.
//
{
int i;
int j;
int k;
double *xfat;
xfat = new double[(n-1)*(fat+1)+1];
k = 0;
for ( i = 0; i < n-1; i++ )
{
xfat[k] = x[i];
k = k + 1;
for ( j = 1; j <= fat; j++ )
{
xfat[k] = ( ( double ) ( fat - j + 1 ) * x[i]
+ ( double ) ( j ) * x[i+1] )
/ ( double ) ( fat + 1 );
k = k + 1;
}
}
xfat[k] = x[n-1];
k = k + 1;
return xfat;
}
//****************************************************************************80
double *r8vec_expand_linear2 ( int n, double x[], int before, int fat,
int after )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_EXPAND_LINEAR2 linearly interpolates new data into an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// This routine starts with a vector of data.
//
// The intent is to "fatten" the data, that is, to insert more points
// between successive values of the original data.
//
// There will also be extra points placed BEFORE the first original
// value and AFTER that last original value.
//
// The "fattened" data is equally spaced between the original points.
//
// The BEFORE data uses the spacing of the first original interval,
// and the AFTER data uses the spacing of the last original interval.
//
// Example:
//
// N = 3
// BEFORE = 3
// FAT = 2
// AFTER = 1
//
// X = (/ 0.0, 6.0, 7.0 /)
// XFAT = (/ -6.0, -4.0, -2.0, 0.0, 2.0, 4.0, 6.0, 6.33, 6.66, 7.0, 7.66 /)
// 3 "BEFORE's" Old 2 "FATS" Old 2 "FATS" Old 1 "AFTER"
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 July 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of input data values.
// N must be at least 2.
//
// Input, double X[N], the original data.
//
// Input, int BEFORE, the number of "before" values.
//
// Input, int FAT, the number of data values to interpolate
// between each pair of original data values.
//
// Input, int AFTER, the number of "after" values.
//
// Output, double R8VEC_EXPAND_LINEAR2[BEFORE+(N-1)*(FAT+1)+1+AFTER], the
// "fattened" data.
//
{
int i;
int j;
int k;
double *xfat;
xfat = new double[before+(n-1)*(fat+1)+1+after];
k = 0;
//
// Points BEFORE.
//
for ( j = 1 - before + fat; j <= fat; j++ )
{
xfat[k] = ( ( double ) ( fat - j + 1 ) * ( x[0] - ( x[1] - x[0] ) )
+ ( double ) ( j ) * x[0] )
/ ( double ) ( fat + 1 );
k = k + 1;
}
//
// Original points and FAT points.
//
for ( i = 0; i < n - 1; i++ )
{
xfat[k] = x[0];
k = k + 1;
for ( j = 1; j <= fat; j++ )
{
xfat[k] = ( ( double ) ( fat - j + 1 ) * x[i]
+ ( double ) ( j ) * x[i+1] )
/ ( double ) ( fat + 1 );
k = k + 1;
}
}
xfat[k] = x[n-1];
k = k + 1;
//
// Points AFTER.
//
for ( j = 1; j <= after; j++ )
{
xfat[k] = ( ( double ) ( fat - j + 1 ) * x[n-1]
+ ( double ) ( j ) * ( x[n-1] + ( x[n-1] - x[n-2] ) ) )
/ ( double ) ( fat + 1 );
k = k + 1;
}
return xfat;
}
//****************************************************************************80
int *r8vec_first_index ( int n, double a[], double tol )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_FIRST_INDEX indexes the first occurrence of values in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// For element A(I) of the vector, FIRST_INDEX(I) is the index in A of
// the first occurrence of the value A(I).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 August 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], the unsorted array to examine.
//
// Input, double TOL, a tolerance for equality.
//
// Output, int R8VEC_FIRST_INDEX[N], the first occurrence index.
//
{
int *first_index;
int i;
int j;
first_index = new int[n];
for ( i = 0; i < n; i++ )
{
first_index[i] = -1;
}
for ( i = 0; i < n; i++ )
{
if ( first_index[i] == -1 )
{
first_index[i] = i;
for ( j = i + 1; j < n; j++ )
{
if ( fabs ( a[i] - a[j] ) <= tol )
{
first_index[j] = i;
}
}
}
}
return first_index;
}
//****************************************************************************80
double r8vec_frac ( int n, double a[], int k )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_FRAC searches for the K-th smallest entry in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Hoare's algorithm is used.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 August 2004
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input/output, double A[N].
// On input, A is the array to search.
// On output, the elements of A have been somewhat rearranged.
//
// Input, int K, the fractile to be sought. If K = 1, the minimum
// entry is sought. If K = N, the maximum is sought. Other values
// of K search for the entry which is K-th in size. K must be at
// least 1, and no greater than N.
//
// Output, double R8VEC_FRAC, the value of the K-th fractile of A.
//
{
double frac;
int i;
int iryt;
int j;
int left;
double temp;
double x;
if ( n <= 0 )
{
cerr << "\n";
cerr << "R8VEC_FRAC - Fatal error!\n";
cerr << " Illegal nonpositive value of N = " << n << "\n";
exit ( 1 );
}
if ( k <= 0 )
{
cerr << "\n";
cerr << "R8VEC_FRAC - Fatal error!\n";
cerr << " Illegal nonpositive value of K = " << k << "\n";
exit ( 1 );
}
if ( n < k )
{
cerr << "\n";
cerr << "R8VEC_FRAC - Fatal error!\n";
cerr << " Illegal N < K, K = " << k << "\n";
exit ( 1 );
}
left = 1;
iryt = n;
for ( ; ; )
{
if ( iryt <= left )
{
frac = a[k-1];
break;
}
x = a[k-1];
i = left;
j = iryt;
for ( ; ; )
{
if ( j < i )
{
if ( j < k )
{
left = i;
}
if ( k < i )
{
iryt = j;
}
break;
}
//
// Find I so that X <= A(I).
//
while ( a[i-1] < x )
{
i = i + 1;
}
//
// Find J so that A(J) <= X.
//
while ( x < a[j-1] )
{
j = j - 1;
}
if ( i <= j )
{
temp = a[i-1];
a[i-1] = a[j-1];
a[j-1] = temp;
i = i + 1;
j = j - 1;
}
}
}
return frac;
}
//****************************************************************************80
double *r8vec_fraction ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_FRACTION returns the fraction parts of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// If we regard a real number as
//
// R8 = SIGN * ( WHOLE + FRACTION )
//
// where
//
// SIGN is +1 or -1,
// WHOLE is a nonnegative integer
// FRACTION is a nonnegative real number strictly less than 1,
//
// then this routine returns the value of FRACTION.
//
// Example:
//
// R8 R8_FRACTION
//
// 0.00 0.00
// 1.01 0.01
// 2.02 0.02
// 19.73 0.73
// -4.34 0.34
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 April 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of arguments.
//
// Input, double X[N], the arguments.
//
// Output, double R8_FRACTION[N], the fraction parts.
//
{
double *fraction;
int i;
fraction = new double[n];
for ( i = 0; i < n; i++ )
{
fraction[i] = fabs ( x[i] ) - ( double ) ( ( int ) ( fabs ( x[i] ) ) );
}
return fraction;
}
//****************************************************************************80
bool r8vec_gt ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_GT == ( A1 > A2 ) for two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The comparison is lexicographic.
//
// A1 > A2 <=> A1(1) > A2(1) or
// ( A1(1) == A2(1) and A1(2) > A2(2) ) or
// ...
// ( A1(1:N-1) == A2(1:N-1) and A1(N) > A2(N)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vectors.
//
// Input, double A1[N], A2[N], the vectors to be compared.
//
// Output, bool R8VEC_GT, is TRUE if and only if A1 > A2.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( a2[i] < a1[i] )
{
return true;
}
else if ( a1[i] < a2[i] )
{
return false;
}
}
return false;
}
//****************************************************************************80
void r8vec_heap_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_HEAP_A reorders an R8VEC into a ascending heap.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An ascending heap is an array A with the property that, for every index J,
// A[J] <= A[2*J+1] and A[J] <= A[2*J+2], (as long as the indices
// 2*J+1 and 2*J+2 are legal).
//
// Diagram:
//
// A(0)
//
// A(1) A(2)
//
// A(3) A(4) A(5) A(6)
//
// A(7) A(8) A(9) A(10)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 September 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the size of the input array.
//
// Input/output, double A[N].
// On input, an unsorted array.
// On output, the array has been reordered into a heap.
//
{
int i;
int ifree;
double key;
int m;
//
// Only nodes (N/2)-1 down to 0 can be "parent" nodes.
//
for ( i = (n/2)-1; 0 <= i; i-- )
{
//
// Copy the value out of the parent node.
// Position IFREE is now "open".
//
key = a[i];
ifree = i;
for ( ; ; )
{
//
// Positions 2*IFREE + 1 and 2*IFREE + 2 are the descendants of position
// IFREE. (One or both may not exist because they equal or exceed N.)
//
m = 2 * ifree + 1;
//
// Does the first position exist?
//
if ( n <= m )
{
break;
}
else
{
//
// Does the second position exist?
//
if ( m + 1 < n )
{
//
// If both positions exist, take the larger of the two values,
// and update M if necessary.
//
if ( a[m+1] < a[m] )
{
m = m + 1;
}
}
//
// If the large descendant is larger than KEY, move it up,
// and update IFREE, the location of the free position, and
// consider the descendants of THIS position.
//
if ( a[m] <= key )
{
break;
}
a[ifree] = a[m];
ifree = m;
}
}
//
// When you have stopped shifting items up, return the item you
// pulled out back to the heap.
//
a[ifree] = key;
}
return;
}
//****************************************************************************80
void r8vec_heap_d ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_HEAP_D reorders an R8VEC into a descending heap.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// A heap is an array A with the property that, for every index J,
// A[J] >= A[2*J+1] and A[J] >= A[2*J+2], (as long as the indices
// 2*J+1 and 2*J+2 are legal).
//
// Diagram:
//
// A(0)
//
// A(1) A(2)
//
// A(3) A(4) A(5) A(6)
//
// A(7) A(8) A(9) A(10)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 April 1999
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the size of the input array.
//
// Input/output, double A[N].
// On input, an unsorted array.
// On output, the array has been reordered into a heap.
//
{
int i;
int ifree;
double key;
int m;
//
// Only nodes (N/2)-1 down to 0 can be "parent" nodes.
//
for ( i = (n/2)-1; 0 <= i; i-- )
{
//
// Copy the value out of the parent node.
// Position IFREE is now "open".
//
key = a[i];
ifree = i;
for ( ; ; )
{
//
// Positions 2*IFREE + 1 and 2*IFREE + 2 are the descendants of position
// IFREE. (One or both may not exist because they equal or exceed N.)
//
m = 2 * ifree + 1;
//
// Does the first position exist?
//
if ( n <= m )
{
break;
}
else
{
//
// Does the second position exist?
//
if ( m + 1 < n )
{
//
// If both positions exist, take the larger of the two values,
// and update M if necessary.
//
if ( a[m] < a[m+1] )
{
m = m + 1;
}
}
//
// If the large descendant is larger than KEY, move it up,
// and update IFREE, the location of the free position, and
// consider the descendants of THIS position.
//
if ( key < a[m] )
{
a[ifree] = a[m];
ifree = m;
}
else
{
break;
}
}
}
//
// When you have stopped shifting items up, return the item you
// pulled out back to the heap.
//
a[ifree] = key;
}
return;
}
//****************************************************************************80
int *r8vec_histogram ( int n, double a[], double a_lo, double a_hi,
int histo_num )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_HISTOGRAM histograms an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Values between A_LO and A_HI will be histogrammed into the bins
// 1 through HISTO_NUM. Values below A_LO are counted in bin 0,
// and values greater than A_HI are counted in bin HISTO_NUM+1.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], the array to examine.
//
// Input, double A_LO, A_HI, the lowest and highest
// values to be histogrammed. These values will also define the bins.
//
// Input, int HISTO_NUM, the number of bins to use.
//
// Output, int HISTO_GRAM[HISTO_NUM+2], contains the number of
// entries of A in each bin.
//
{
double delta;
int *histo_gram;
int i;
int j;
histo_gram = new int[histo_num+2];
i4vec_zeros ( histo_num+2, histo_gram );
delta = ( a_hi - a_lo ) / ( double ) ( 2 * histo_num );
for ( i = 0; i < n; i++ )
{
if ( a[i] < a_lo )
{
histo_gram[0] = histo_gram[0] + 1;
}
else if ( a[i] <= a_hi )
{
j = r8_nint (
( ( a_hi - delta - a[i] ) * ( double ) ( 1 )
+ ( - delta + a[i] - a_lo ) * ( double ) ( histo_num ) )
/ ( a_hi - 2.0 * delta - a_lo ) );
histo_gram[j] = histo_gram[j] + 1;
}
else if ( a_hi < a[i] )
{
histo_gram[histo_num+1] = histo_gram[histo_num+1] + 1;
}
}
return histo_gram;
}
//****************************************************************************80
double *r8vec_house_column ( int n, double a_vec[], int k )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_HOUSE_COLUMN defines a Householder premultiplier that "packs" a column.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The routine returns a vector V that defines a Householder
// premultiplier matrix H(V) that zeros out the subdiagonal entries of
// column K of the matrix A.
//
// H(V) = I - 2 * v * v'
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix A.
//
// Input, double A_VEC[N], a row or column of the matrix A.
//
// Input, int K, the index of the row or column.
//
// Output, double R8VEC_HOUSE_COLUMN[N], a vector of unit L2 norm which
// defines an orthogonal Householder premultiplier matrix H with the property
// that the K-th column of H*A is zero below the diagonal.
//
{
int i;
double s;
double *v;
v = r8vec_zeros_new ( n );
if ( k < 1 || n <= k )
{
return v;
}
s = r8vec_norm_l2 ( n+1-k, a_vec+k-1 );
if ( s == 0.0 )
{
return v;
}
v[k-1] = a_vec[k-1] + fabs ( s ) * r8_sign ( a_vec[k-1] );
r8vec_copy ( n-k, a_vec+k, v+k );
//
// Normalize.
//
s = r8vec_norm_l2 ( n-k+1, v+k-1 );
for ( i = k - 1; i < n; i++ )
{
v[i] = v[i] / s;
}
return v;
}
//****************************************************************************80
double r8vec_i4vec_dot_product ( int n, double r8vec[], int i4vec[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_I4VEC_DOT_PRODUCT computes the dot product of an R8VEC and an I4VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double R8VEC[N], the first vector.
//
// Input, int I4VEC[N], the second vector.
//
// Output, double R8VEC_I4VEC_DOT_PRODUCT, the dot product of the vectors.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + r8vec[i] * ( double ) ( i4vec[i] );
}
return value;
}
//****************************************************************************80
bool r8vec_in_01 ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_IN_01 is TRUE if the entries of an R8VEC are in the range [0,1].
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double X[N], the vector
//
// Output, bool R8VEC_IN_01, is TRUE if every entry is
// between 0 and 1.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( x[i] < 0.0 || 1.0 < x[i] )
{
return false;
}
}
return true;
}
//****************************************************************************80
bool r8vec_in_ab ( int n, double x[], double a, double b )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_IN_AB is TRUE if the entries of an R8VEC are in the range [A,B].
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double X[N], the vector
//
// Input, double A, B, the limits of the range.
//
// Output, bool R8VEC_IN_AB, is TRUE if every entry is
// between A and B.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( x[i] < a || b < x[i] )
{
return false;
}
}
return true;
}
//****************************************************************************80
void r8vec_index_delete_all ( int n, double x[], int indx[], double xval,
int &n2, double x2[], int indx2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_DELETE_ALL deletes all occurrences of a value from an indexed sorted list.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Note that the value of N is adjusted because of the deletions.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the current list.
//
// Input, double X[N], the list.
//
// Input, int INDX[N], the sort index of the list.
//
// Input, double XVAL, the value to be sought.
//
// Output, int &N2, the size of the current list.
//
// Output, double X2[N2], the list.
//
// Output, int INDX2[N2], the sort index of the list.
//
{
int equal;
int equal1;
int equal2;
int get;
int i;
int less;
int more;
int put;
if ( n < 1 )
{
n2 = 0;
return;
}
i4vec_copy ( n, indx, indx2 );
r8vec_copy ( n, x, x2 );
n2 = n;
r8vec_index_search ( n2, x2, indx2, xval, less, equal, more );
if ( equal == 0 )
{
return;
}
equal1 = equal;
for ( ; ; )
{
if ( equal1 <= 1 )
{
break;
}
if ( x2[indx2[equal1-2]-1] != xval )
{
break;
}
equal1 = equal1 - 1;
}
equal2 = equal;
for ( ; ; )
{
if ( n2 <= equal2 )
{
break;
}
if ( x2[indx2[equal2]-1] != xval )
{
break;
}
equal2 = equal2 + 1;
}
//
// Discard certain X values.
//
put = 0;
for ( get = 1; get <= n2; get++ )
{
if ( x2[get-1] != xval )
{
put = put + 1;
x2[put-1] = x2[get-1];
}
}
//
// Adjust the INDX values.
//
for ( equal = equal1; equal <= equal2; equal++ )
{
for ( i = 1; i <= n2; i++ )
{
if ( indx2[equal-1] < indx2[i-1] )
{
indx2[i-1] = indx2[i-1] - 1;
}
}
}
//
// Discard certain INDX values.
//
for ( i = 0; i <= n2 - equal2 - 1; i++ )
{
indx2[equal1+i-1] = indx2[equal2+i];
}
for ( i = n2 + equal1 - equal2; i <= n2; i++ )
{
indx2[i-1] = 0;
}
//
// Adjust N.
//
n2 = put;
return;
}
//****************************************************************************80
void r8vec_index_delete_dupes ( int n, double x[], int indx[],
int &n2, double x2[], int indx2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_DELETE_DUPES deletes duplicates from an indexed sorted list.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The output quantities N2, X2, and INDX2 are computed from the
// input quantities by sorting, and eliminating duplicates.
//
// The output arrays should be dimensioned of size N, unless the user
// knows in advance what the value of N2 will be.
//
// The output arrays may be identified with the input arrays.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the input list.
//
// Input, double X[N], the list.
//
// Input, int INDX[N], the sort index of the list.
//
// Output, int &N2, the number of unique entries in X.
//
// Output, double X2[N2], a copy of the list which has
// been sorted, and made unique.
//
// Output, int INDX2[N2], the sort index of the new list.
//
{
int i;
int n3;
double *x3;
i = 0;
n3 = 0;
x3 = new double[n];
for ( ; ; )
{
i = i + 1;
if ( n < i )
{
break;
}
if ( 1 < i )
{
if ( x[indx[i-1]-1] == x3[n3-1] )
{
continue;
}
}
n3 = n3 + 1;
x3[n3-1] = x[indx[i-1]-1];
}
//
// Set the output data.
//
n2 = n3;
r8vec_copy ( n3, x3, x2 );
for ( i = 0; i < n3; i++ )
{
indx2[i] = i + 1;
}
delete [] x3;
return;
}
//****************************************************************************80
void r8vec_index_delete_one ( int n, double x[], int indx[], double xval,
int &n2, double x2[], int indx2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_DELETE_ONE deletes one copy of a value from an indexed sorted list.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// If the value occurs in the list more than once, only one copy is deleted.
//
// Note that the value of N is adjusted because of the deletions.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 October 2000
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the current list.
//
// Input, double X[N], the list.
//
// Input, int INDX[N], the sort index of the list.
//
// Input, double XVAL, the value to be sought.
//
// Output, int &N2, the size of the current list.
//
// Output, double X2[N2], the list.
//
// Output, int INDX2[N2], the sort index of the list.
//
{
int equal;
int i;
int j;
int less;
int more;
if ( n < 1 )
{
n2 = 0;
return;
}
n2 = n;
i4vec_copy ( n2, indx, indx2 );
r8vec_copy ( n2, x, x2 );
r8vec_index_search ( n2, x2, indx2, xval, less, equal, more );
if ( equal != 0 )
{
j = indx2[equal-1];
for ( i = j; i <= n2 - 1; i++ )
{
x2[i-1] = x[i];
}
for ( i = equal; i <= n2 - 1; i++ )
{
indx2[i-1] = indx2[i];
}
for ( i = 1; i <= n2 - 1; i++ )
{
if ( j < indx2[i-1] )
{
indx2[i-1] = indx2[i-1] - 1;
}
}
n2 = n2 - 1;
}
return;
}
//****************************************************************************80
void r8vec_index_insert ( int &n, double x[], int indx[], double xval )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_INSERT inserts a value in an indexed sorted list.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input/output, int &N, the size of the current list.
//
// Input, double X[N], the list.
//
// Input, int INDX[N], the sort index of the list.
//
// Input, double XVAL, the value to be sought.
//
{
int equal;
int i;
int less;
int more;
if ( n <= 0 )
{
n = 1;
x[0] = xval;
indx[0] = 1;
return;
}
r8vec_index_search ( n, x, indx, xval, less, equal, more );
x[n] = xval;
for ( i = n; more <= i; i-- )
{
indx[i] = indx[i-1];
}
indx[more-1] = n + 1;
n = n + 1;
return;
}
//****************************************************************************80
void r8vec_index_insert_unique ( int &n, double x[], int indx[], double xval )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_INSERT_UNIQUE inserts a unique value in an indexed sorted list.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input/output, int &N, the size of the current list.
// If the input value XVAL does not already occur in X, then N is increased.
//
// Input/output, double X[N], the list.
// If the input value XVAL does not already occur in X, then it is added
// to X.
//
// Input/output, int INDX[N], the sort index of the list.
// If the input value XVAL does not already occur in X, then INDX is updated.
//
// Input, double XVAL, the value which will be inserted into the X
// vector if it is not there already.
//
{
int equal;
int i;
int less;
int more;
if ( n <= 0 )
{
n = 1;
x[0] = xval;
indx[0] = 1;
return;
}
//
// Does XVAL already occur in X?
//
r8vec_index_search ( n, x, indx, xval, less, equal, more );
if ( equal == 0 )
{
x[n] = xval;
for ( i = n; more <= i; i-- )
{
indx[i] = indx[i-1];
}
indx[more-1] = n + 1;
n = n + 1;
}
return;
}
//****************************************************************************80
void r8vec_index_order ( int n, double x[], int indx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_ORDER sorts an R8VEC using an index vector.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The index vector itself is not modified. Therefore, the pair
// (X,INDX) no longer represents an index sorted vector.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the current list.
//
// Input/output, double X[N], the list. On output, the list
// has been sorted.
//
// Input, int INDX[N], the sort index of the list.
//
{
int i;
double *y;
y = new double[n];
for ( i = 0; i < n; i++ )
{
y[i] = x[indx[i]-1];
}
for ( i = 0; i < n; i++ )
{
x[i] = y[i];
}
delete [] y;
return;
}
//****************************************************************************80
void r8vec_index_search ( int n, double x[], int indx[], double xval, int &less,
int &equal, int &more )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_SEARCH searches for a value in an indexed sorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the current list.
//
// Input, double X[N], the list.
//
// Input, int INDX[N], the sort index of the list.
//
// Input, double XVAL, the value to be sought.
//
// Output, int &LESS, &EQUAL, &MORE, the indexes in INDX of the
// entries of X that are just less than, equal to, and just greater
// than XVAL. If XVAL does not occur in X, then EQUAL is zero.
// If XVAL is the minimum entry of X, then LESS is 0. If XVAL
// is the greatest entry of X, then MORE is N+1.
//
{
int hi;
int lo;
int mid;
double xhi;
double xlo;
double xmid;
if ( n <= 0 )
{
less = 0;
equal = 0;
more = 0;
return;
}
lo = 1;
hi = n;
xlo = x[indx[lo-1]-1];
xhi = x[indx[hi-1]-1];
if ( xval < xlo )
{
less = 0;
equal = 0;
more = 1;
return;
}
else if ( xval == xlo )
{
less = 0;
equal = 1;
more = 2;
return;
}
if ( xhi < xval )
{
less = n;
equal = 0;
more = n + 1;
return;
}
else if ( xval == xhi )
{
less = n - 1;
equal = n;
more = n + 1;
return;
}
for ( ; ; )
{
if ( lo + 1 == hi )
{
less = lo;
equal = 0;
more = hi;
return;
}
mid = ( lo + hi ) / 2;
xmid = x[indx[mid-1]-1];
if ( xval == xmid )
{
equal = mid;
less = mid - 1;
more = mid + 1;
return;
}
else if ( xval < xmid )
{
hi = mid;
}
else if ( xmid < xval )
{
lo = mid;
}
}
return;
}
//****************************************************************************80
void r8vec_index_sort_unique ( int n, double x[], int &n2, double x2[],
int indx2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_SORT_UNIQUE creates a sort index for an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the current list.
//
// Input, double X[N], the list.
//
// Output, int &N2, the number of unique elements in X.
//
// Output, double X2[N2], a list of the unique elements of X.
//
// Output, int INDX2[N2], the sort index of the list.
//
{
int i;
n2 = 0;
for ( i = 0; i < n; i++ )
{
r8vec_index_insert_unique ( n2, x2, indx2, x[i] );
}
for ( i = n2; i < n; i++ )
{
x2[i] = -1;
}
for ( i = n2; i < n; i++ )
{
indx2[i] = -1;
}
return;
}
//****************************************************************************80
void r8vec_index_sorted_range ( int n, double r[], int indx[], double r_lo,
double r_hi, int &i_lo, int &i_hi )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEX_SORTED_RANGE: search index sorted vector for elements in a range.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items in the vector.
//
// Input, double R[N], the index sorted vector.
//
// Input, int INDX[N], the vector used to sort R.
// The vector R[INDX[*]] is sorted.
//
// Input, double R_LO, R_HI, the limits of the range.
//
// Output, int &I_LO, &I_HI, the range of indices
// so that I_LO <= I <= I_HI => R_LO <= R[INDX[I]] <= R_HI. If no
// values in R lie in the range, then I_HI < I_LO will be returned.
//
{
int i1;
int i2;
int j1;
int j2;
//
// Cases we can handle immediately.
//
if ( r[indx[n-1]] < r_lo )
{
i_lo = n;
i_hi = n - 1;
return;
}
if ( r_hi < r[indx[0]] )
{
i_lo = 0;
i_hi = -1;
return;
}
//
// Are there are least two intervals?
//
if ( n == 1 )
{
if ( r_lo <= r[indx[0]] && r[indx[0]] <= r_hi )
{
i_lo = 0;
i_hi = 0;
}
else
{
i_lo = -1;
i_hi = -2;
}
return;
}
//
// Bracket R_LO.
//
if ( r_lo <= r[indx[0]] )
{
i_lo = 0;
}
else
{
//
// R_LO is in one of the intervals spanned by R(INDX(J1)) to R(INDX(J2)).
// Examine the intermediate interval [R(INDX(I1)), R(INDX(I1+1))].
// Does R_LO lie here, or below or above?
//
j1 = 0;
j2 = n - 1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
for ( ; ; )
{
if ( r_lo < r[indx[i1]] )
{
j2 = i1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else if ( r[indx[i2]] < r_lo )
{
j1 = i2;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else
{
i_lo = i1;
break;
}
}
}
//
// Bracket R_HI.
//
if ( r[indx[n-1]] <= r_hi )
{
i_hi = n - 1;
}
else
{
j1 = i_lo;
j2 = n - 1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
for ( ; ; )
{
if ( r_hi < r[indx[i1]] )
{
j2 = i1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else if ( r[indx[i2]] < r_hi )
{
j1 = i2;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else
{
i_hi = i2;
break;
}
}
}
//
// We expect to have computed the largest I_LO and smallest I_HI such that
// R(INDX(I_LO)) <= R_LO <= R_HI <= R(INDX(I_HI))
// but what we want is actually
// R_LO <= R(INDX(I_LO)) <= R(INDX(I_HI)) <= R_HI
// which we can usually get simply by incrementing I_LO and decrementing I_HI.
//
if ( r[indx[i_lo]] < r_lo )
{
i_lo = i_lo + 1;
if ( n - 1 < i_lo )
{
i_hi = i_lo - 1;
}
}
if ( r_hi < r[indx[i_hi]] )
{
i_hi = i_hi - 1;
if ( i_hi < 0 )
{
i_lo = i_hi + 1;
}
}
return;
}
//****************************************************************************80
void r8vec_indexed_heap_d ( int n, double a[], int indx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEXED_HEAP_D creates a descending heap from an indexed R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An indexed R8VEC is an R8VEC of data values, and an R8VEC of N indices,
// each referencing an entry of the data vector.
//
// The function adjusts the index vector INDX so that, for 1 <= J <= N/2,
// we have:
// A[INDX[2*J+1]] <= A[INDX[J]]
// and
// A[INDX[2*J+2]] <= A[INDX[J]]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2010
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms for Computers and Calculators,
// Academic Press, 1978,
// ISBN: 0-12-519260-6,
// LC: QA164.N54.
//
// Parameters:
//
// Input, int N, the size of the index array.
//
// Input, double A[*], the data vector.
//
// Input/output, int INDX[N], the index array.
// Each entry of INDX must be a valid index for the array A.
// On output, the indices have been reordered into a descending heap.
//
{
int i;
int ifree;
int key;
int m;
//
// Only nodes N/2 - 1 down to 0 can be "parent" nodes.
//
for ( i = ( n / 2 ) - 1; 0 <= i; i-- )
{
//
// Copy the value out of the parent node.
// Position IFREE is now "open".
//
key = indx[i];
ifree = i;
for ( ; ; )
{
//
// Positions 2*IFREE+1 and 2*IFREE+2 are the descendants of position
// IFREE. (One or both may not exist because they exceed N-1.)
//
m = 2 * ifree + 1;
//
// Does the first position exist?
//
if ( n - 1 < m )
{
break;
}
//
// Does the second position exist?
//
if ( m + 1 <= n - 1 )
{
//
// If both positions exist, take the larger of the two values,
// and update M if necessary.
//
if ( a[indx[m]] < a[indx[m+1]] )
{
m = m + 1;
}
}
//
// If the large descendant is larger than KEY, move it up,
// and update IFREE, the location of the free position, and
// consider the descendants of THIS position.
//
if ( a[indx[m]] <= a[key] )
{
break;
}
indx[ifree] = indx[m];
ifree = m;
}
//
// Once there is no more shifting to do, KEY moves into the free spot IFREE.
//
indx[ifree] = key;
}
return;
}
//****************************************************************************80
int r8vec_indexed_heap_d_extract ( int &n, double a[], int indx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEXED_HEAP_D_EXTRACT: extract from heap descending indexed R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An indexed R8VEC is an R8VEC of data values, and an R8VEC of N indices,
// each referencing an entry of the data vector.
//
// The routine finds the maximum value in the heap, returns that value to the
// user, deletes that value from the heap, and restores the heap to its
// proper form.
//
// Note that the argument N must be a variable, which will be decremented
// before return, and that INDX will hold one less value on output than it
// held on input.
//
// This is one of three functions needed to model a priority queue.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2010
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Thomas Cormen, Charles Leiserson, Ronald Rivest,
// Introduction to Algorithms,
// MIT Press, 2001,
// ISBN: 0262032937,
// LC: QA76.C662.
//
// Parameters:
//
// Input/output, int &N, the number of items in the index vector.
//
// Input, double A[*], the data vector.
//
// Input/output, int INDX[N], the index vector.
//
// Output, int R8VEC_INDEXED_HEAP_D_EXTRACT, the index in A of the item of
// maximum value, which has now been removed from the heap.
//
{
int indx_extract;
if ( n < 1 )
{
cerr << "\n";
cerr << "R8VEC_INDEXED_HEAP_D_EXTRACT - Fatal error!\n";
cerr << " The heap is empty.\n";
exit ( 1 );
}
//
// Get the index of the maximum value.
//
indx_extract = indx[0];
if ( n == 1 )
{
n = 0;
return indx_extract;
}
//
// Shift the last index down.
//
indx[0] = indx[n-1];
//
// Restore the heap structure.
//
n = n - 1;
r8vec_indexed_heap_d ( n, a, indx );
return indx_extract;
}
//****************************************************************************80
void r8vec_indexed_heap_d_insert ( int &n, double a[], int indx[],
int indx_insert )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEXED_HEAP_D_INSERT: insert value into heap descending indexed R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An indexed R8VEC is an R8VEC of data values, and an R8VEC of N indices,
// each referencing an entry of the data vector.
//
// Note that the argument N must be a variable, and will be incremented before
// return, and that INDX must be able to hold one more entry on output than
// it held on input.
//
// This is one of three functions needed to model a priority queue.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2010
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Thomas Cormen, Charles Leiserson, Ronald Rivest,
// Introduction to Algorithms,
// MIT Press, 2001,
// ISBN: 0262032937,
// LC: QA76.C662.
//
// Parameters:
//
// Input/output, int &N, the number of items in the index vector.
//
// Input, double A[*], the data vector.
//
// Input/output, int INDX[N], the index vector.
//
// Input, int INDX_INSERT, the index in A of the value
// to be inserted into the heap.
//
{
int i;
int parent;
n = n + 1;
i = n - 1;
while ( 0 < i )
{
parent = ( i - 1 ) / 2;
if ( a[indx_insert] <= a[indx[parent]] )
{
break;
}
indx[i] = indx[parent];
i = parent;
}
indx[i] = indx_insert;
return;
}
//****************************************************************************80
int r8vec_indexed_heap_d_max ( int n, double a[], int indx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDEXED_HEAP_D_MAX: maximum value in heap descending indexed R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An indexed R8VEC is an R8VEC of data values, and an R8VEC of N indices,
// each referencing an entry of the data vector.
//
// This is one of three functions needed to model a priority queue.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2010
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Thomas Cormen, Charles Leiserson, Ronald Rivest,
// Introduction to Algorithms,
// MIT Press, 2001,
// ISBN: 0262032937,
// LC: QA76.C662.
//
// Parameters:
//
// Input, int N, the number of items in the index vector.
//
// Input, double A[*], the data vector.
//
// Input, int INDX[N], the index vector.
//
// Output, int R8VEC_INDEXED_HEAP_D_MAX, the index in A of the maximum value
// in the heap.
//
{
int indx_max;
indx_max = indx[0];
return indx_max;
}
//****************************************************************************80
void r8vec_indicator0 ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDICATOR0 sets an R8VEC to the indicator vector (0,1,2,...)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Output, double A[N], the array.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = ( double ) ( i );
}
return;
}
//****************************************************************************80
double *r8vec_indicator0_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDICATOR0_NEW sets an R8VEC to the indicator vector {0,1,2,...}.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Output, double R8VEC_INDICATOR0_NEW[N], the indicator array.
//
{
double *a;
int i;
a = new double[n];
for ( i = 0; i < n; i++ )
{
a[i] = ( double ) ( i );
}
return a;
}
//****************************************************************************80
void r8vec_indicator1 ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDICATOR1 sets an R8VEC to the indicator vector (1,2,3,...)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Output, double A[N], the array.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = ( double ) ( i + 1 );
}
return;
}
//****************************************************************************80
double *r8vec_indicator1_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INDICATOR1_NEW sets an R8VEC to the indicator vector {1,2,3,...}.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 September 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Output, double R8VEC_INDICATOR1_NEW[N], the indicator array.
//
{
double *a;
int i;
a = new double[n];
for ( i = 0; i < n; i++ )
{
a[i] = ( double ) ( i + 1 );
}
return a;
}
//****************************************************************************80
void r8vec_insert ( int n, double a[], int pos, double value )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INSERT inserts a value into an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the array on input.
//
// Input/output, double A[N+1], the array. On input, A is
// assumed to contain only N entries, while on output, A actually
// contains N+1 entries.
//
// Input, int POS, the position to be assigned the new entry.
// 1 <= POS <= N+1.
//
// Input, double VALUE, the value to be inserted.
//
{
int i;
if ( pos < 1 || n + 1 < pos )
{
cerr << "\n";
cerr << "R8VEC_INSERT - Fatal error!\n";
cerr << " Illegal insertion position = " << pos << "\n";;
exit ( 1 );
}
else
{
for ( i = n + 1; pos + 1 <= i; i-- )
{
a[i-1] = a[i-2];
}
a[pos-1] = value;
}
return;
}
//****************************************************************************80
bool r8vec_insignificant ( int n, double r[], double s[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_INSIGNIFICANT determines if an R8VEC is insignificant.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 November 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vectors.
//
// Input, double R[N], the vector to be compared against.
//
// Input, double S[N], the vector to be compared.
//
// Output, bool R8VEC_INSIGNIFICANT, is TRUE if S is insignificant
// compared to R.
//
{
int i;
double t;
double tol;
bool value;
value = true;
for ( i = 0; i < n; i++ )
{
t = r[i] + s[i];
tol = r8_epsilon ( ) * fabs ( r[i] );
if ( tol < fabs ( r[i] - t ) )
{
value = false;
break;
}
}
return value;
}
//****************************************************************************80
bool r8vec_is_int ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_IS_INT is TRUE if an R8VEC is integral.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector
//
// Output, bool R8VEC_IS_INT, is TRUE if every entry of A is an integer.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( a[i] != ( double ) ( int ) a[i] )
{
return false;
}
}
return true;
}
//****************************************************************************80
bool r8vec_is_nonnegative ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_IS_NONNEGATIVE is true if all entries in an R8VEC are nonnegative.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 August 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double X[N], the vector to be checked.
//
// Output, bool R8VEC_IS_NONNEGATIVE is true if all elements of X
// are nonnegative.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( x[i] < 0.0 )
{
return false;
}
}
return true;
}
//****************************************************************************80
bool r8vec_is_zero ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_IS_ZERO is true if the entries in an R8VEC are all zero.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double X[N], the vector to be checked.
//
// Output, bool R8VEC_IS_ZERO is true if all N elements of X
// are zero.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( x[i] != 0.0 )
{
return false;
}
}
return true;
}
//****************************************************************************80
double *r8vec_legendre_new ( int n, double a_first, double a_last )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_LEGENDRE_NEW creates a vector of Chebyshev spaced values.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 June 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A_FIRST, A_LAST, the first and last entries.
//
// Output, double R8VEC_LEGENDRE_NEW[N], a vector of Legendre spaced data.
//
{
double *a;
int i;
a = legendre_zeros ( n );
for ( i = 0; i < n; i++ )
{
a[i] = ( ( 1.0 - a[i] ) * a_first
+ ( 1.0 + a[i] ) * a_last )
/ 2.0;
}
return a;
}
//****************************************************************************80
void r8vec_linspace ( int n, double a_first, double a_last, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_LINSPACE creates a vector of linearly spaced values.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// 4 points evenly spaced between 0 and 12 will yield 0, 4, 8, 12.
//
// In other words, the interval is divided into N-1 even subintervals,
// and the endpoints of intervals are used as the points.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 April 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A_FIRST, A_LAST, the first and last entries.
//
// Output, double A[N], a vector of linearly spaced data.
//
{
int i;
if ( n == 1 )
{
a[0] = ( a_first + a_last ) / 2.0;
}
else
{
for ( i = 0; i < n; i++ )
{
a[i] = ( ( double ) ( n - 1 - i ) * a_first
+ ( double ) ( i ) * a_last )
/ ( double ) ( n - 1 );
}
}
return;
}
//****************************************************************************80
double *r8vec_linspace_new ( int n, double a_first, double a_last )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_LINSPACE_NEW creates a vector of linearly spaced values.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// 4 points evenly spaced between 0 and 12 will yield 0, 4, 8, 12.
//
// In other words, the interval is divided into N-1 even subintervals,
// and the endpoints of intervals are used as the points.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A_FIRST, A_LAST, the first and last entries.
//
// Output, double R8VEC_LINSPACE_NEW[N], a vector of linearly spaced data.
//
{
double *a;
int i;
a = new double[n];
if ( n == 1 )
{
a[0] = ( a_first + a_last ) / 2.0;
}
else
{
for ( i = 0; i < n; i++ )
{
a[i] = ( ( double ) ( n - 1 - i ) * a_first
+ ( double ) ( i ) * a_last )
/ ( double ) ( n - 1 );
}
}
return a;
}
//****************************************************************************80
double *r8vec_linspace2_new ( int n, double a_first, double a_last )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_LINSPACE2_NEW creates a vector of linearly spaced values.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// 4 points evenly spaced between 0 and 12 will yield 2, 4, 6, 8, 10.
//
// In other words, the interval is divided into N+1 even subintervals,
// and the endpoints of internal intervals are used as the points.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A_FIRST, A_LAST, the first and last entries.
//
// Output, double R8VEC_LINSPACE2_NEW[N], a vector of linearly spaced data.
//
{
double *a;
int i;
a = new double[n];
if ( n == 1 )
{
a[0] = ( a_first + a_last ) / 2.0;
}
else
{
for ( i = 0; i < n; i++ )
{
a[i] = ( ( double ) ( n - i ) * a_first
+ ( double ) ( i + 1 ) * a_last )
/ ( double ) ( n + 1 );
}
}
return a;
}
//****************************************************************************80
bool r8vec_lt ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_LT == ( A1 < A2 ) for two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The comparison is lexicographic.
//
// A1 < A2 <=> A1(1) < A2(1) or
// ( A1(1) == A2(1) and A1(2) < A2(2) ) or
// ...
// ( A1(1:N-1) == A2(1:N-1) and A1(N) < A2(N)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vectors.
//
// Input, double A1[N], A2[N], the vectors to be compared.
//
// Output, bool R8VEC_LT, is TRUE if and only if A1 < A2.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( a1[i] < a2[i] )
{
return true;
}
else if ( a2[i] < a1[i] )
{
return false;
}
}
return false;
}
//****************************************************************************80
void r8vec_mask_print ( int n, double a[], int mask_num, int mask[],
string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MASK_PRINT prints a masked R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A[N], the vector to be printed.
//
// Input, int MASK_NUM, the number of masked elements.
//
// Input, int MASK[MASK_NUM], the indices of the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << " Masked vector printout:\n";
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = 0; i < mask_num; i++ )
{
cout << " " << setw(6) << i
<< ": " << setw(6) << mask[i]
<< " " << setw(12) << a[mask[i]-1] << "\n";
}
return;
}
//****************************************************************************80
double r8vec_max ( int n, double r8vec[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MAX returns the value of the maximum element in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double R8VEC[N], a pointer to the first entry of the array.
//
// Output, double R8VEC_MAX, the value of the maximum element. This
// is set to 0.0 if N <= 0.
//
{
int i;
double value;
value = r8vec[0];
for ( i = 1; i < n; i++ )
{
if ( value < r8vec[i] )
{
value = r8vec[i];
}
}
return value;
}
//****************************************************************************80
int r8vec_max_abs_index ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MAX_ABS_INDEX returns the index of the maximum absolute value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 April 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, int R8VEC_MAX_ABS_INDEX, the index of the entry of
// largest absolute value.
//
{
int i;
int max_index;
if ( n <= 0 )
{
max_index = -1;
}
else
{
max_index = 0;
for ( i = 1; i < n; i++ )
{
if ( fabs ( a[max_index] ) < fabs ( a[i] ) )
{
max_index = i;
}
}
}
return max_index;
}
//****************************************************************************80
int r8vec_max_index ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MAX_INDEX returns the index of the maximum value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, int R8VEC_MAX_INDEX, the index of the largest entry.
//
{
int i;
int max_index;
if ( n <= 0 )
{
max_index = -1;
}
else
{
max_index = 0;
for ( i = 1; i < n; i++ )
{
if ( a[max_index] < a[i] )
{
max_index = i;
}
}
}
return max_index;
}
//****************************************************************************80
double r8vec_mean ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MEAN returns the mean of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 December 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double X[N], the vector whose mean is desired.
//
// Output, double R8VEC_MEAN, the mean, or average, of the vector entries.
//
{
int i;
double mean;
mean = 0.0;
for ( i = 0; i < n; i++ )
{
mean = mean + x[i];
}
mean = mean / ( double ) n;
return mean;
}
//****************************************************************************80
double r8vec_mean_geometric ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MEAN_GEOMETRIC returns the geometric mean of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 April 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double X[N], the vector whose mean is desired.
//
// Output, double R8VEC_MEAN_GEOMETRIC, the geometric mean of the
// vector entries.
//
{
int i;
double mean;
mean = 0.0;
for ( i = 0; i < n; i++ )
{
mean = mean + log ( x[i] );
}
mean = mean / ( double ) n;
mean = exp ( mean );
return mean;
}
//****************************************************************************80
double r8vec_median ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MEDIAN returns the median of an unsorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Hoare's algorithm is used. The values of the vector are
// rearranged by this routine.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input/output, double A[N], the array to search. On output,
// the order of the elements of A has been somewhat changed.
//
// Output, double R8VEC_MEDIAN, the value of the median of A.
//
{
int k;
double median;
k = ( n + 1 ) / 2;
median = r8vec_frac ( n, a, k );
return median;
}
//****************************************************************************80
void r8vec_mesh_2d ( int nx, int ny, double xvec[], double yvec[],
double xmat[], double ymat[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MESH_2D creates a 2D mesh from X and Y vectors.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// NX = 2
// XVEC = ( 1, 2, 3 )
// NY = 3
// YVEC = ( 4, 5 )
//
// XMAT = (
// 1, 2, 3
// 1, 2, 3 )
//
// YMAT = (
// 4, 4, 4
// 5, 5, 5 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 July 2013
//
// Parameters:
//
// Input, int NX, NY, the number of X and Y values.
//
// Input, double XVEC[NX], YVEC[NY], the X and Y coordinate
// values.
//
// Output, double XMAT[NX*NY], YMAT[NX*NY], the coordinate
// values of points on an NX by NY mesh.
//
{
int i;
int j;
for ( j = 0; j < ny; j++ )
{
for ( i = 0; i < nx; i++ )
{
xmat[i+j*nx] = xvec[i];
}
}
for ( j = 0; j < ny; j++ )
{
for ( i = 0; i < nx; i++ )
{
ymat[i+j*nx] = yvec[j];
}
}
return;
}
//****************************************************************************80
double *r8vec_midspace_new ( int n, double a, double b )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MIDSPACE_NEW creates a vector of linearly spaced values.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// This function divides the interval [a,b] into n subintervals, and then
// returns the midpoints of those subintervals.
//
// Example:
//
// N = 5, A = 10, B = 20
// X = [ 11, 13, 15, 17, 19 ]
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 June 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A, B, the endpoints of the interval.
//
// Output, double R8VEC_MIDSPACE_NEW[N], a vector of linearly spaced data.
//
{
double *x;
int i;
x = new double[n];
for ( i = 0; i < n; i++ )
{
x[i] = ( ( double ) ( 2 * n - 2 * i - 1 ) * a
+ ( double ) ( 2 * i + 1 ) * b )
/ ( double ) ( 2 * n );
}
return x;
}
//****************************************************************************80
double r8vec_min ( int n, double r8vec[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MIN returns the value of the minimum element in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 July 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double R8VEC[N], the array to be checked.
//
// Output, double R8VEC_MIN, the value of the minimum element.
//
{
int i;
double value;
value = r8vec[0];
for ( i = 1; i < n; i++ )
{
if ( r8vec[i] < value )
{
value = r8vec[i];
}
}
return value;
}
//****************************************************************************80
int r8vec_min_index ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MIN_INDEX returns the index of the minimum value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, int R8VEC_MIN_INDEX, the index of the smallest entry.
//
{
int i;
int min_index;
if ( n <= 0 )
{
min_index = -1;
}
else
{
min_index = 0;
for ( i = 1; i < n; i++ )
{
if ( a[i] < a[min_index] )
{
min_index = i;
}
}
}
return min_index;
}
//****************************************************************************80
double r8vec_min_pos ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MIN_POS returns the minimum positive value of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 November 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double A[N], the array.
//
// Output, double R8VEC_MIN_POS, the smallest positive entry.
//
{
int i;
const double r8_huge = 1.79769313486231571E+308;
double value;
value = r8_huge;
for ( i = 0; i < n; i++ )
{
if ( 0.0 < a[i] )
{
if ( a[i] < value )
{
value = a[i];
}
}
}
return value;
}
//****************************************************************************80
bool r8vec_mirror_next ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MIRROR_NEXT steps through all sign variations of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// In normal use, the user would set every element of A to be positive.
// The routine will take the input value of A, and output a copy in
// which the signs of one or more entries have been changed. Repeatedly
// calling the routine with the output from the previous call will generate
// every distinct "variation" of A; that is, all possible sign variations.
//
// When the output variable DONE is TRUE (or equal to 1), then the
// output value of A_NEW is the last in the series.
//
// Note that A may have some zero values. The routine will essentially
// ignore such entries; more exactly, it will not stupidly assume that -0
// is a proper "variation" of 0.
//
// Also, it is possible to call this routine with the signs of A set
// in any way you like. The routine will operate properly, but it
// will nonethess terminate when it reaches the value of A in which
// every nonzero entry has negative sign.
//
//
// More efficient algorithms using the Gray code seem to require internal
// memory in the routine, which is not one of MATLAB's strong points,
// or the passing back and forth of a "memory array", or the use of
// global variables, or unnatural demands on the user. This form of
// the routine is about as clean as I can make it.
//
// Example:
//
// Input Output
// --------- --------------
// A A DONE
// --------- -------- ----
// 1 2 3 -1 2 3 false
// -1 2 3 1 -2 3 false
// 1 -2 3 -1 -2 3 false
// -1 -2 3 1 2 -3 false
// 1 2 -3 -1 2 -3 false
// -1 2 -3 1 -2 -3 false
// 1 -2 -3 -1 -2 -3 false
// -1 -2 -3 1 2 3 true
//
// 1 0 3 -1 0 3 false
// -1 0 3 1 0 -3 false
// 1 0 -3 -1 0 -3 false
// -1 0 -3 1 0 3 true
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 March 2008
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input/output, double A[N], a vector of real numbers. On
// output, some signs have been changed.
//
// Output, bool R8VEC_MIRROR_NEXT, is TRUE if the input vector A was
// the last element
// in the series (every entry was nonpositive); the output vector is reset
// so that all entries are nonnegative, but presumably the ride is over.
//
{
bool done;
int i;
int positive;
//
// Seek the first strictly positive entry of A.
//
positive = -1;
for ( i = 0; i < n; i++ )
{
if ( 0.0 < a[i] )
{
positive = i;
break;
}
}
//
// If there is no strictly positive entry of A, there is no successor.
//
if ( positive == -1 )
{
for ( i = 0; i < n; i++ )
{
a[i] = - a[i];
}
done = true;
return done;
}
//
// Otherwise, negate A up to the positive entry.
//
for ( i = 0; i <= positive; i++ )
{
a[i] = - a[i];
}
done = false;
return done;
}
//****************************************************************************80
bool r8vec_negative_strict ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NEGATIVE_STRICT: all entries of R8VEC are strictly negative.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 June 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vector.
//
// Input, double A[N], the vector.
//
// Output, bool R8VEC_NEGATIVE_STRICT, is TRUE if every entry of
// A is strictly negative.
//
{
int i;
bool value;
for ( i = 0; i < n; i++ )
{
if ( 0 <= a[i] )
{
value = false;
return value;
}
}
value = true;
return value;
}
//****************************************************************************80
void r8vec_nint ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NINT rounds the entries of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input/output, double A[N], the vector to be rounded.
//
{
int i;
int s;
for ( i = 0; i < n; i++ )
{
if ( a[i] < 0.0 )
{
s = -1;
}
else
{
s = 1;
}
a[i] = ( double ) ( s * ( int ) ( fabs ( a[i] ) + 0.5 ) );
}
return;
}
//****************************************************************************80
double *r8vec_nint_new ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NINT_NEW rounds the entries of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector to be rounded.
//
// Output, double R8VEC_NINT_NEW[N], the rounded values.
//
{
double *b;
int i;
int s;
b = new double[n];
for ( i = 0; i < n; i++ )
{
if ( a[i] < 0.0 )
{
s = -1;
}
else
{
s = 1;
}
b[i] = ( double ) ( s * ( int ) ( fabs ( a[i] ) + 0.5 ) );
}
return b;
}
//****************************************************************************80
double r8vec_norm ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORM returns the L2 norm of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L2 norm is defined as:
//
// R8VEC_NORM = sqrt ( sum ( 1 <= I <= N ) A(I)^2 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector whose L2 norm is desired.
//
// Output, double R8VEC_NORM, the L2 norm of A.
//
{
int i;
double v;
v = 0.0;
for ( i = 0; i < n; i++ )
{
v = v + a[i] * a[i];
}
v = sqrt ( v );
return v;
}
//****************************************************************************80
double r8vec_norm_affine ( int n, double v0[], double v1[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORM_AFFINE returns the affine L2 norm of an R8VEC.
//
// Discussion:
//
// The affine vector L2 norm is defined as:
//
// R8VEC_NORM_AFFINE(V0,V1)
// = sqrt ( sum ( 1 <= I <= N ) ( V1(I) - V0(I) )^2 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vectors.
//
// Input, double V0[N], the base vector.
//
// Input, double V1[N], the vector.
//
// Output, double R8VEC_NORM_AFFINE, the affine L2 norm.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + ( v1[i] - v0[i] ) * ( v1[i] - v0[i] );
}
value = sqrt ( value );
return value;
}
//****************************************************************************80
double r8vec_norm_l0 ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORM_L0 returns the l0 "norm" of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The l0 "norm" simply counts the number of nonzero entries in the vector.
// It is not a true norm, but has some similarities to one. It is useful
// in the study of compressive sensing.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 January 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A(N), the vector.
//
// Output, double R8VEC_NORM_L0, the value of the norm.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
if ( a[i] != 0.0 )
{
value = value + 1.0;
}
}
return value;
}
//****************************************************************************80
double r8vec_norm_l1 ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORM_L1 returns the L1 norm of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L1 norm is defined as:
//
// R8VEC_NORM_L1 = sum ( 1 <= I <= N ) abs ( A(I) ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector whose L1 norm is desired.
//
// Output, double R8VEC_NORM_L1, the L1 norm of A.
//
{
int i;
double v;
v = 0.0;
for ( i = 0; i < n; i++ )
{
v = v + fabs ( a[i] );
}
return v;
}
//****************************************************************************80
double r8vec_norm_l2 ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORM_L2 returns the L2 norm of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L2 norm is defined as:
//
// R8VEC_NORM_L2 = sqrt ( sum ( 1 <= I <= N ) A(I)^2 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector whose L2 norm is desired.
//
// Output, double R8VEC_NORM_L2, the L2 norm of A.
//
{
int i;
double v;
v = 0.0;
for ( i = 0; i < n; i++ )
{
v = v + a[i] * a[i];
}
v = sqrt ( v );
return v;
}
//****************************************************************************80
double r8vec_norm_li ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORM_LI returns the L-oo norm of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector L-oo norm is defined as:
//
// R8VEC_NORM_LI = max ( 1 <= I <= N ) abs ( A(I) ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector whose L-oo norm is desired.
//
// Output, double R8VEC_NORM_LI, the L-oo norm of A.
//
{
int i;
double v1;
double v2;
v1 = 0.0;
for ( i = 0; i < n; i++ )
{
v2 = fabs ( a[i] );
if ( v1 < v2 )
{
v1 = v2;
}
}
return v1;
}
//****************************************************************************80
double r8vec_norm_lp ( int n, double a[], double p )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORM_LP returns the LP norm of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector LP norm is defined as:
//
// R8VEC_NORM_LP = ( sum ( 1 <= I <= N ) ( abs ( A(I) ) )^P )^(1/P).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector whose LP norm is desired.
//
// Input, double P, the index of the norm.
//
// Output, double R8VEC_NORML_LP, the LP norm of A.
//
{
int i;
double v;
v = 0.0;
if ( p == 1.0 )
{
for ( i = 0; i < n; i++ )
{
v = v + fabs ( a[i] );
}
}
else if ( p == 2.0 )
{
for ( i = 0; i < n; i++ )
{
v = v + a[i] * a[i];
}
v = sqrt ( v );
}
else
{
for ( i = 0; i < n; i++ )
{
v = v + pow ( fabs ( a[i] ), p );
}
v = pow ( ( double ) v, 1.0 / p );
}
return v;
}
//****************************************************************************80
void r8vec_normal_01 ( int n, int &seed, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORMAL_01 returns a unit pseudonormal R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The standard normal probability distribution function (PDF) has
// mean 0 and standard deviation 1.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 August 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of values desired.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double X[N], a sample of the standard normal PDF.
//
// Local parameters:
//
// Local, double R[N+1], is used to store some uniform random values.
// Its dimension is N+1, but really it is only needed to be the
// smallest even number greater than or equal to N.
//
// Local, int X_LO, X_HI, records the range of entries of
// X that we need to compute.
//
{
int i;
int m;
double *r;
const double r8_pi = 3.141592653589793;
int x_hi;
int x_lo;
//
// Record the range of X we need to fill in.
//
x_lo = 1;
x_hi = n;
//
// If we need just one new value, do that here to avoid null arrays.
//
if ( x_hi - x_lo + 1 == 1 )
{
r = r8vec_uniform_01_new ( 2, seed );
x[x_hi-1] = sqrt ( -2.0 * log ( r[0] ) ) * cos ( 2.0 * r8_pi * r[1] );
delete [] r;
}
//
// If we require an even number of values, that's easy.
//
else if ( ( x_hi - x_lo + 1 ) % 2 == 0 )
{
m = ( x_hi - x_lo + 1 ) / 2;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-2; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( -2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( -2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
delete [] r;
}
//
// If we require an odd number of values, we generate an even number,
// and handle the last pair specially, storing one in X(N), and
// saving the other for later.
//
else
{
x_hi = x_hi - 1;
m = ( x_hi - x_lo + 1 ) / 2 + 1;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-4; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( -2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( -2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
i = 2*m - 2;
x[x_lo+i-1] = sqrt ( -2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
delete [] r;
}
return;
}
//****************************************************************************80
double *r8vec_normal_01_new ( int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORMAL_01_NEW returns a unit pseudonormal R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The standard normal probability distribution function (PDF) has
// mean 0 and standard deviation 1.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 August 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of values desired.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8VEC_NORMAL_01_NEW[N], a sample of the standard normal PDF.
//
// Local parameters:
//
// Local, double R[N+1], is used to store some uniform random values.
// Its dimension is N+1, but really it is only needed to be the
// smallest even number greater than or equal to N.
//
// Local, int X_LO, X_HI, records the range of entries of
// X that we need to compute.
//
{
int i;
int m;
double *r;
const double r8_pi = 3.141592653589793;
double *x;
int x_hi;
int x_lo;
x = new double[n];
//
// Record the range of X we need to fill in.
//
x_lo = 1;
x_hi = n;
//
// If we need just one new value, do that here to avoid null arrays.
//
if ( x_hi - x_lo + 1 == 1 )
{
r = r8vec_uniform_01_new ( 2, seed );
x[x_hi-1] = sqrt ( -2.0 * log ( r[0] ) ) * cos ( 2.0 * r8_pi * r[1] );
delete [] r;
}
//
// If we require an even number of values, that's easy.
//
else if ( ( x_hi - x_lo + 1 ) % 2 == 0 )
{
m = ( x_hi - x_lo + 1 ) / 2;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-2; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( -2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( -2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
delete [] r;
}
//
// If we require an odd number of values, we generate an even number,
// and handle the last pair specially, storing one in X(N), and
// saving the other for later.
//
else
{
x_hi = x_hi - 1;
m = ( x_hi - x_lo + 1 ) / 2 + 1;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2*m-4; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( -2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( -2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
i = 2*m - 2;
x[x_lo+i-1] = sqrt ( -2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
delete [] r;
}
return x;
}
//****************************************************************************80
double *r8vec_normal_ab_new ( int n, double b, double c, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORMAL_AB_NEW returns a scaled pseudonormal R8VEC.
//
// Discussion:
//
// The scaled normal probability distribution function (PDF) has
// mean A and standard deviation B.
//
// This routine can generate a vector of values on one call.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 August 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of values desired.
//
// Input, double B, C, the mean and standard deviation.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8VEC_NORMAL_AB_NEW[N], a sample of the standard normal PDF.
//
// Local parameters:
//
// Local, double R(N+1), is used to store some uniform random values.
// Its dimension is N+1, but really it is only needed to be the
// smallest even number greater than or equal to N.
//
// Local, int X_LO, X_HI, records the range of entries of
// X that we need to compute.
//
{
int i;
int m;
double *r;
const double r8_pi = 3.141592653589793;
double *x;
int x_hi;
int x_lo;
x = new double[n];
//
// Record the range of X we need to fill in.
//
x_lo = 1;
x_hi = n;
//
// If we need just one new value, do that here to avoid null arrays.
//
if ( x_hi - x_lo + 1 == 1 )
{
r = r8vec_uniform_01_new ( 2, seed );
x[x_hi-1] = sqrt ( - 2.0 * log ( r[0] ) ) * cos ( 2.0 * r8_pi * r[1] );
delete [] r;
}
//
// If we require an even number of values, that's easy.
//
else if ( ( x_hi - x_lo + 1 ) % 2 == 0 )
{
m = ( x_hi - x_lo + 1 ) / 2;
r = r8vec_uniform_01_new ( 2 * m, seed );
for ( i = 0; i <= 2 * m - 2; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
delete [] r;
}
//
// If we require an odd number of values, we generate an even number,
// and handle the last pair specially, storing one in X(N), and
// saving the other for later.
//
else
{
x_hi = x_hi - 1;
m = ( x_hi - x_lo + 1 ) / 2 + 1;
r = r8vec_uniform_01_new ( 2*m, seed );
for ( i = 0; i <= 2 * m - 4; i = i + 2 )
{
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
x[x_lo+i ] = sqrt ( - 2.0 * log ( r[i] ) ) * sin ( 2.0 * r8_pi * r[i+1] );
}
i = 2*m - 2;
x[x_lo+i-1] = sqrt ( - 2.0 * log ( r[i] ) ) * cos ( 2.0 * r8_pi * r[i+1] );
delete [] r;
}
for ( i = 0; i < n; i++ )
{
x[i] = b + c * x[i];
}
return x;
}
//****************************************************************************80
void r8vec_normalize ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORMALIZE normalizes an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input/output, double A[N], the vector to be normalized.
// On output, A should have unit Euclidean norm.
//
{
int i;
double norm;
norm = 0.0;
for ( i = 0; i < n; i++ )
{
norm = norm + a[i] * a[i];
}
norm = sqrt ( norm );
if ( norm == 0.0 )
{
cerr << "\n";
cerr << "R8VEC_NORMALIZE - Fatal error!\n";
cerr << " The vector norm is 0.\n";
exit ( 1 );
}
for ( i = 0; i < n; i++ )
{
a[i] = a[i] / norm;
}
return;
}
//****************************************************************************80
void r8vec_normalize_l1 ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORMALIZE_L1 normalizes an R8VEC to have unit sum.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input/output, double A[N], the vector to be normalized.
// On output, the entries of A should have unit sum. However, if
// the input vector has zero sum, the routine halts.
//
{
double a_sum;
int i;
a_sum = 0.0;
for ( i = 0; i < n; i++ )
{
a_sum = a_sum + a[i];
}
if ( a_sum == 0.0 )
{
cerr << "\n";
cerr << "R8VEC_NORMALIZE_L1 - Fatal error!\n";
cerr << " The vector entries sum to 0.\n";
exit ( 1 );
}
for ( i = 0; i < n; i++ )
{
a[i] = a[i] / a_sum;
}
return;
}
//****************************************************************************80
double r8vec_normsq ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORMSQ returns the squared L2 norm of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The squared vector L2 norm is defined as:
//
// R8VEC_NORMSQ = sum ( 1 <= I <= N ) A(I)^2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the vector dimension.
//
// Input, double A[N], the vector.
//
// Output, double R8VEC_NORMSQ, the squared L2 norm.
//
{
int i;
double v;
v = 0.0;
for ( i = 0; i < n; i++ )
{
v = v + a[i] * a[i];
}
return v;
}
//****************************************************************************80
double r8vec_normsq_affine ( int n, double v0[], double v1[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_NORMSQ_AFFINE returns the squared affine L2 norm of an R8VEC.
//
// Discussion:
//
// The squared affine vector L2 norm is defined as:
//
// R8VEC_NORMSQ_AFFINE(V0,V1)
// = sum ( 1 <= I <= N ) ( V1(I) - V0(I) )^2
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vectors.
//
// Input, double V0[N], the base vector.
//
// Input, double V1[N], the vector whose squared affine L2 norm is desired.
//
// Output, double R8VEC_NORMSQ_AFFINE, the squared affine L2 norm.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + ( v1[i] - v0[i] ) * ( v1[i] - v0[i] );
}
return value;
}
//****************************************************************************80
double *r8vec_ones_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ONES_NEW creates a vector of 1's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, double R8VEC_ONES_NEW[N], a vector of 1's.
//
{
double *a;
int i;
a = new double[n];
for ( i = 0; i < n; i++ )
{
a[i] = 1.0;
}
return a;
}
//****************************************************************************80
int r8vec_order_type ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ORDER_TYPE determines if an R8VEC is (non)strictly ascending/descending.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 September 2000
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the array.
//
// Input, double X[N], the array to be checked.
//
// Output, int R8VEC_ORDER_TYPE, order indicator:
// -1, no discernable order;
// 0, all entries are equal;
// 1, ascending order;
// 2, strictly ascending order;
// 3, descending order;
// 4, strictly descending order.
//
{
int i;
int order;
//
// Search for the first value not equal to X(0).
//
i = 0;
for ( ; ; )
{
i = i + 1;
if ( n-1 < i )
{
order = 0;
return order;
}
if ( x[0] < x[i] )
{
if ( i == 1 )
{
order = 2;
break;
}
else
{
order = 1;
break;
}
}
else if ( x[i] < x[0] )
{
if ( i == 1 )
{
order = 4;
break;
}
else
{
order = 3;
break;
}
}
}
//
// Now we have a "direction". Examine subsequent entries.
//
for ( ; ; )
{
i = i + 1;
if ( n - 1 < i )
{
break;
}
if ( order == 1 )
{
if ( x[i] < x[i-1] )
{
order = -1;
break;
}
}
else if ( order == 2 )
{
if ( x[i] < x[i-1] )
{
order = -1;
break;
}
else if ( x[i] == x[i-1] )
{
order = 1;
}
}
else if ( order == 3 )
{
if ( x[i-1] < x[i] )
{
order = -1;
break;
}
}
else if ( order == 4 )
{
if ( x[i-1] < x[i] )
{
order = -1;
break;
}
else if ( x[i] == x[i-1] )
{
order = 3;
}
}
}
return order;
}
//****************************************************************************80
void r8vec_part_quick_a ( int n, double a[], int &l, int &r )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PART_QUICK_A reorders an R8VEC as part of a quick sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The routine reorders the entries of A. Using A[0] as a
// key, all entries of A that are less than or equal to A[0] will
// precede A[0] which precedes all entries that are greater than A[0].
//
// Example:
//
// Input:
//
// N = 8
//
// A = ( 6, 7, 3, 1, 6, 8, 2, 9 )
//
// Output:
//
// L = 3, R = 6
//
// A = ( 3, 1, 2, 6, 6, 8, 9, 7 )
// ------- -------
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 April 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of A.
//
// Input/output, double A[N]. On input, the array to be checked.
// On output, A has been reordered as described above.
//
// Output, int &L, &R, the indices of A that define the three segments.
// Let KEY = the input value of A[0]. Then
// I <= L A(I) < KEY;
// L < I < R A(I) = KEY;
// R <= I A(I) > KEY.
//
{
int i;
double key;
int m;
double temp;
if ( n < 1 )
{
cerr << "\n";
cerr << "R8VEC_PART_QUICK_A - Fatal error!\n";
cerr << " N < 1.\n";
exit ( 1 );
}
else if ( n == 1 )
{
l = 0;
r = 2;
return;
}
key = a[0];
m = 1;
//
// The elements of unknown size have indices between L+1 and R-1.
//
l = 1;
r = n + 1;
for ( i = 2; i <= n; i++ )
{
if ( key < a[l] )
{
r = r - 1;
temp = a[r-1];
a[r-1] = a[l];
a[l] = temp;
}
else if ( a[l] == key )
{
m = m + 1;
temp = a[m-1];
a[m-1] = a[l];
a[l] = temp;
l = l + 1;
}
else if ( a[l] < key )
{
l = l + 1;
}
}
//
// Now shift small elements to the left, and KEY elements to center.
//
for ( i = 1; i <= l - m; i++ )
{
a[i-1] = a[i+m-1];
}
l = l - m;
for ( i = l + 1; i <= l + m; i++ )
{
a[i-1] = key;
}
return;
}
//****************************************************************************80
void r8vec_permute ( int n, int p[], double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PERMUTE applies a 0-based permutation to an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// This routine permutes an array of real "objects", but the same
// logic can be used to permute an array of objects of any arithmetic
// type, or an array of objects of any complexity. The only temporary
// storage required is enough to store a single object. The number
// of data movements made is N + the number of cycles of order 2 or more,
// which is never more than N + N/2.
//
// Example:
//
// Input:
//
// N = 5
// P = ( 1, 3, 4, 0, 2 )
// A = ( 1.0, 2.0, 3.0, 4.0, 5.0 )
//
// Output:
//
// A = ( 2.0, 4.0, 5.0, 1.0, 3.0 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 May 2015
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of objects.
//
// Input, int P[N], a 0-based permutation.
//
// Input/output, double A[N], the array to be permuted.
//
{
double a_temp;
int i;
int iget;
int iput;
int istart;
if ( !perm0_check ( n, p ) )
{
cerr << "\n";
cerr << "R8VEC_PERMUTE - Fatal error!\n";
cerr << " PERM0_CHECK rejects permutation.\n";
exit ( 1 );
}
//
// In order for the sign negation trick to work, we need to assume that the
// entries of P are strictly positive. Presumably, the lowest number is 0.
// So temporarily add 1 to each entry to force positivity.
//
for ( i = 0; i < n; i++ )
{
p[i] = p[i] + 1;
}
//
// Search for the next element of the permutation that has not been used.
//
for ( istart = 1; istart <= n; istart++ )
{
if ( p[istart-1] < 0 )
{
continue;
}
else if ( p[istart-1] == istart )
{
p[istart-1] = - p[istart-1];
continue;
}
else
{
a_temp = a[istart-1];
iget = istart;
//
// Copy the new value into the vacated entry.
//
for ( ; ; )
{
iput = iget;
iget = p[iget-1];
p[iput-1] = - p[iput-1];
if ( iget < 1 || n < iget )
{
cerr << "\n";
cerr << "R8VEC_PERMUTE - Fatal error!\n";
cerr << " A permutation index is out of range.\n";
cerr << " P(" << iput << ") = " << iget << "\n";
exit ( 1 );
}
if ( iget == istart )
{
a[iput-1] = a_temp;
break;
}
a[iput-1] = a[iget-1];
}
}
}
//
// Restore the signs of the entries.
//
for ( i = 0; i < n; i++ )
{
p[i] = - p[i];
}
//
// Restore the entries.
//
for ( i = 0; i < n; i++ )
{
p[i] = p[i] - 1;
}
return;
}
//****************************************************************************80
void r8vec_permute_cyclic ( int n, int k, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PERMUTE_CYCLIC performs a cyclic permutation of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// For 0 <= K < N, this function cyclically permutes the input vector
// to have the form
//
// ( A[K], A[K+1], ..., A[N-1], A[0], ..., A[K-1] )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of objects.
//
// Input, int K, the increment used.
//
// Input/output, double A[N], the array to be permuted.
//
{
double *b;
int i;
int ipk;
b = new double[n];
for ( i = 0; i < n; i++ )
{
ipk = i4_wrap ( i + k, 0, n - 1 );
b[i] = a[ipk];
}
for ( i = 0; i < n; i++ )
{
a[i] = b[i];
}
delete [] b;
return;
}
//****************************************************************************80
void r8vec_permute_uniform ( int n, double a[], int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PERMUTE_UNIFORM randomly permutes an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 October 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of objects.
//
// Input/output, double A[N], the array to be permuted.
//
// Input/output, int &SEED, a seed for the random number generator.
//
{
int *p;
p = perm0_uniform_new ( n, seed );
r8vec_permute ( n, p, a );
delete [] p;
return;
}
//****************************************************************************80
void r8vec_polarize ( int n, double a[], double p[], double a_normal[],
double a_parallel[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_POLARIZE decomposes an R8VEC into normal and parallel components.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The (nonzero) vector P defines a direction.
//
// The vector A can be written as the sum
//
// A = A_normal + A_parallel
//
// where A_parallel is a linear multiple of P, and A_normal
// is perpendicular to P.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the vector to be polarized.
//
// Input, double P[N], the polarizing direction.
//
// Output, double A_NORMAL[N], A_PARALLEL[N], the normal
// and parallel components of A.
//
{
double a_dot_p;
int i;
double p_norm;
p_norm = r8vec_norm ( n, p );
if ( p_norm == 0.0 )
{
for ( i = 0; i < n; i++ )
{
a_normal[i] = a[i];
}
for ( i = 0; i < n; i++ )
{
a_parallel[i] = 0.0;
}
return;
}
a_dot_p = r8vec_dot_product ( n, a, p ) / p_norm;
for ( i = 0; i < n; i++ )
{
a_parallel[i] = a_dot_p * p[i] / p_norm;
}
for ( i = 0; i < n; i++ )
{
a_normal[i] = a[i] - a_parallel[i];
}
return;
}
//****************************************************************************80
bool r8vec_positive_strict ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_POSITIVE_STRICT: all entries of R8VEC are strictly positive.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 June 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the dimension of the vector.
//
// Input, double A[N], the vector.
//
// Output, bool R8VEC_POSITIVE_STRICT, is TRUE if every entry of
// A is strictly positive.
//
{
int i;
bool value;
for ( i = 0; i < n; i++ )
{
if ( a[i] <= 0.0 )
{
value = false;
return value;
}
}
value = true;
return value;
}
//****************************************************************************80
void r8vec_print ( int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PRINT prints an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A[N], the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i] << "\n";
}
return;
}
//****************************************************************************80
void r8vec_print_16 ( int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PRINT_16 prints an R8VEC to 16 decimal places.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 May 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A[N], the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< ": " << setprecision(16) << setw(24) << a[i] << "\n";
}
return;
}
//****************************************************************************80
void r8vec_print_part ( int n, double a[], int i_lo, int i_hi, string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PRINT_PART prints "part" of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vector.
//
// Input, double A[N], the vector to be printed.
//
// Input, integer I_LO, I_HI, the first and last indices to print.
// The routine expects 1 <= I_LO <= I_HI <= N.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = i4_max ( 1, i_lo ); i <= i4_min ( n, i_hi ); i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i-1] << "\n";
}
return;
}
//****************************************************************************80
void r8vec_print_some ( int n, double a[], int max_print, string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PRINT_SOME prints "some" of an R8VEC.
//
// Discussion:
//
// The user specifies MAX_PRINT, the maximum number of lines to print.
//
// If N, the size of the vector, is no more than MAX_PRINT, then
// the entire vector is printed, one entry per line.
//
// Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
// followed by a line of periods suggesting an omission,
// and the last entry.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 February 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vector.
//
// Input, double A[N], the vector to be printed.
//
// Input, int MAX_PRINT, the maximum number of lines
// to print.
//
// Input, string TITLE, a title.
//
{
int i;
if ( max_print <= 0 )
{
return;
}
if ( n <= 0 )
{
return;
}
cout << "\n";
cout << title << "\n";
cout << "\n";
if ( n <= max_print )
{
for ( i = 0; i < n; i++ )
{
cout << " " << setw(8) << i
<< " " << setw(14) << a[i] << "\n";
}
}
else if ( 3 <= max_print )
{
for ( i = 0; i < max_print - 2; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i] << "\n";
}
cout << " ........ ..............\n";
i = n - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i] << "\n";
}
else
{
for ( i = 0; i < max_print - 1; i++ )
{
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i] << "\n";
}
i = max_print - 1;
cout << " " << setw(8) << i
<< ": " << setw(14) << a[i]
<< " " << "...more entries...\n";
}
return;
}
//****************************************************************************80
double r8vec_product ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_PRODUCT returns the product of the entries of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], the vector.
//
// Output, double R8VEC_PRODUCT, the product of the vector.
//
{
int i;
double product;
product = 1.0;
for ( i = 0; i < n; i++ )
{
product = product * a[i];
}
return product;
}
//****************************************************************************80
void r8vec_range ( int n, double x[], double xmin, double xmax, double y[],
double *ymin, double *ymax )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_RANGE finds the range of Y's within a restricted X range.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The routine is given a set of pairs of points (X,Y), and a range
// XMIN to XMAX of valid X values. Over this range, it seeks
// YMIN and YMAX, the minimum and maximum values of Y for
// valid X's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double X[N], the X array.
//
// Input, double XMIN, XMAX, the range of X values to check.
//
// Input, double Y[N], the Y array.
//
// Output, double *YMIN, *YMAX, the range of Y values whose
// X value is within the X range.
//
{
int i;
const double r8_huge = 1.79769313486231571E+308;
*ymin = r8_huge;
*ymax = - r8_huge;
for ( i = 0; i < n; i++ )
{
if ( xmin <= x[i] && x[i] <= xmax )
{
*ymin = r8_min ( *ymin, y[i] );
*ymax = r8_max ( *ymax, y[i] );
}
}
return;
}
//****************************************************************************80
void r8vec_range_2 ( int n, double a[], double *amin, double *amax )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_RANGE_2 updates a range to include a new R8VEC
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Given a range AMIN to AMAX, and an array A, the routine will
// decrease AMIN if necessary, or increase AMAX if necessary, so that
// every entry of A is between AMIN and AMAX.
//
// However, AMIN will not be increased, nor AMAX decreased.
//
// This routine may be used to compute the maximum and minimum of a
// collection of arrays one at a time.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Input/output, double *AMIN, *AMAX. On input, the
// current legal range of values for A. On output, AMIN and AMAX
// are either unchanged, or else "widened" so that all entries
// of A are within the range.
//
{
*amax = r8_max ( *amax, r8vec_max ( n, a ) );
*amin = r8_min ( *amin, r8vec_min ( n, a ) );
return;
}
//****************************************************************************80
void r8vec_reverse ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_REVERSE reverses the elements of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Example:
//
// Input:
//
// N = 5, A = ( 11.0, 12.0, 13.0, 14.0, 15.0 ).
//
// Output:
//
// A = ( 15.0, 14.0, 13.0, 12.0, 11.0 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input/output, double A[N], the array to be reversed.
//
{
int i;
int i_hi;
double temp;
i_hi = n / 2;
for ( i = 1; i <= i_hi; i++ )
{
temp = a[i-1];
a[i-1] = a[n-i];
a[n-i] = temp;
}
return;
}
//****************************************************************************80
double r8vec_rms ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_RMS returns the RMS norm of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The vector RMS norm is defined as:
//
// R8VEC_NORM = sqrt ( sum ( 1 <= I <= N ) A(I)^2 / N ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], the vector.
//
// Output, double R8VEC_RMS, the RMS norm of A.
//
{
int i;
double v;
v = 0.0;
if ( 0 < n )
{
for ( i = 0; i < n; i++ )
{
v = v + a[i] * a[i];
}
v = sqrt ( v / ( double ) ( n ) );
}
return v;
}
//****************************************************************************80
void r8vec_rotate ( int n, double a[], int m )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ROTATE "rotates" the entries of an R8VEC in place.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// This routine rotates an array of real "objects", but the same
// logic can be used to permute an array of objects of any arithmetic
// type, or an array of objects of any complexity. The only temporary
// storage required is enough to store a single object. The number
// of data movements made is N + the number of cycles of order 2 or more,
// which is never more than N + N/2.
//
// Example:
//
// Input:
//
// N = 5, M = 2
// A = ( 1.0, 2.0, 3.0, 4.0, 5.0 )
//
// Output:
//
// A = ( 4.0, 5.0, 1.0, 2.0, 3.0 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of objects.
//
// Input, int M, the number of positions to the right that
// each element should be moved. Elements that shift pass position
// N "wrap around" to the beginning of the array.
//
// Input/output, double A[N], the array to be rotated.
//
{
int iget;
int iput;
int istart;
int mcopy;
int nset;
double temp;
//
// Force M to be positive, between 0 and N-1.
//
mcopy = i4_modp ( m, n );
if ( mcopy == 0 )
{
return;
}
istart = 0;
nset = 0;
for ( ; ; )
{
istart = istart + 1;
if ( n < istart )
{
break;
}
temp = a[istart-1];
iget = istart;
//
// Copy the new value into the vacated entry.
//
for ( ; ; )
{
iput = iget;
iget = iget - mcopy;
if ( iget < 1 )
{
iget = iget + n;
}
if ( iget == istart )
{
break;
}
a[iput-1] = a[iget-1];
nset = nset + 1;
}
a[iput-1] = temp;
nset = nset + 1;
if ( n <= nset )
{
break;
}
}
return;
}
//****************************************************************************80
double *r8vec_running_average ( int n, double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_RUNNING_AVERAGE computes the running average of an R8VEC.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2016
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items.
//
// Input, double V(N), the data.
//
// Output, double R8VEC_RUNNING_AVERAGE[N+1], the running average. A[i] is
// the average value of the first I-1 values in V.
//
{
double *a;
int i;
a = new double[n+1];
//
// Sum.
//
a[0] = 0.0;
for ( i = 1; i < n + 1; i++ )
{
a[i] = a[i-1] + v[i-1];
}
//
// Average.
//
for ( i = 1; i < n + 1; i++ )
{
a[i] = a[i] / ( double ) ( i );
}
return a;
}
//****************************************************************************80
double *r8vec_running_sign3 ( int n, double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_RUNNING_SIGN3 computes the running threeway sign of an R8VEC.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2016
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items.
//
// Input, double V(N), the data.
//
// Output, double R8VEC_RUNNING_SIGN3[N+1], the running threeway sign.
// S[i] is:
// -1.0, if the sum of the first I-1 values in V is negative
// 0.0, if zero
// +1.0, if positive.
//
{
int i;
double *s;
s = new double[n+1];
//
// Sum.
//
s[0] = 0.0;
for ( i = 1; i < n + 1; i++ )
{
s[i] = s[i-1] + v[i-1];
}
for ( i = 0; i < n + 1; i++ )
{
if ( s[i] < 0.0 )
{
s[i] = -1.0;
}
else if ( s[i] == 0.0 )
{
s[i] = 0.0;
}
else if ( 0.0 < s[i] )
{
s[i] = +1.0;
}
}
return s;
}
//****************************************************************************80
double *r8vec_running_sum ( int n, double v[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_RUNNING_SUM computes the running sum of an R8VEC.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2016
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items.
//
// Input, double V(N), the data.
//
// Output, double R8VEC_RUNNING_SUM[N+1], the running sum. S[i] is the sum
// of the first I-1 values in V.
//
{
int i;
double *s;
s = new double[n+1];
//
// Sum.
//
s[0] = 0.0;
for ( i = 1; i < n + 1; i++ )
{
s[i] = s[i-1] + v[i-1];
}
return s;
}
//****************************************************************************80
double r8vec_scalar_triple_product ( double v1[3], double v2[3], double v3[3] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SCALAR_TRIPLE_PRODUCT computes the scalar triple product.
//
// Discussion:
//
// STRIPLE = V1 dot ( V2 x V3 ).
//
// STRIPLE is the volume of the parallelogram whose sides are
// formed by V1, V2 and V3.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 27 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double V1[3], V2[3], V3[3], the three vectors.
//
// Output, double R8VEC_SCALAR_TRIPLE_PRODUCT, the scalar
// triple product.
//
{
double value;
value =
v1[0] * ( v2[1] * v3[2] - v2[2] * v3[1] )
+ v1[1] * ( v2[2] * v3[0] - v2[0] * v3[2] )
+ v1[2] * ( v2[0] * v3[1] - v2[1] * v3[0] );
return value;
}
//****************************************************************************80
void r8vec_scale ( double s, int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SCALE multiplies an R8VEC by a scale factor.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 September 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double S, the scale factor.
//
// Input, int N, the number of entries in the vectors.
//
// Input/output, double A[N], the vector to be scaled.
// On output, A[] = S * A[].
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = s * a[i];
}
return;
}
//****************************************************************************80
int r8vec_search_binary_a ( int n, double a[], double aval )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SEARCH_BINARY_A searches an ascending sorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Binary search is used.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 September 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Donald Kreher, Douglas Simpson,
// Algorithm 1.9,
// Combinatorial Algorithms,
// CRC Press, 1998, page 26.
//
// Parameters:
//
// Input, int N, the number of elements in the array.
//
// Input, double A[N], the array to be searched. The array must
// be sorted in ascending order.
//
// Input, double AVAL, the value to be searched for.
//
// Output, int R8VEC_SEARCH_BINARY_A, the result of the search.
// -1, AVAL does not occur in the array.
// I, A(I) = AVAL.
//
{
int high;
int indx;
int low;
int mid;
indx = -1;
low = 1;
high = n;
while ( low <= high )
{
mid = ( low + high ) / 2;
if ( a[mid-1] == aval )
{
indx = mid;
break;
}
else if ( a[mid-1] < aval )
{
low = mid + 1;
}
else if ( aval < a[mid-1] )
{
high = mid - 1;
}
}
return indx;
}
//****************************************************************************80
void r8vec_shift ( int shift, int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SHIFT performs a shift on an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8 values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int SHIFT, the amount by which each entry is to
// be shifted.
//
// Input, int N, the length of the vector.
//
// Input/output, double X[N], the vector to be shifted.
//
{
int i;
int ihi;
int ilo;
double *y;
y = new double[n];
for ( i = 0; i < n; i++ )
{
y[i] = x[i];
}
for ( i = 0; i < n; i++ )
{
x[i] = 0.0;
}
ilo = i4_max ( 0, shift );
ihi = i4_min ( n, n + shift );
for ( i = ilo; i < ihi; i++ )
{
x[i] = y[i-shift];
}
delete [] y;
return;
}
//****************************************************************************80
void r8vec_shift_circular ( int shift, int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SHIFT_CIRCULAR performs a circular shift on an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8 values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int SHIFT, the amount by which each entry is to
// be shifted.
//
// Input, int N, the length of the vector.
//
// Input/output, double X[N], the vector to be shifted.
//
{
int i;
int j;
double *y;
y = new double[n];
for ( i = 0; i < n; i++ )
{
y[i] = x[i];
}
for ( i = 0; i < n; i++ )
{
j = i4_wrap ( i - shift, 0, n - 1 );
x[i] = y[j];
}
delete [] y;
return;
}
//****************************************************************************80
void r8vec_sort_bubble_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_BUBBLE_A ascending sorts an R8VEC using bubble sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, length of input array.
//
// Input/output, double A[N].
// On input, an unsorted array of doubles.
// On output, A has been sorted.
//
{
int i;
int j;
double temp;
for ( i = 0; i < n-1; i++ )
{
for ( j = i+1; j < n; j++ )
{
if ( a[j] < a[i] )
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return;
}
//****************************************************************************80
void r8vec_sort_bubble_d ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_BUBBLE_D descending sorts an R8VEC using bubble sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, length of input array.
//
// Input/output, double A[N].
// On input, an unsorted array of doubles.
// On output, A has been sorted.
//
{
int i;
int j;
double temp;
for ( i = 0; i < n-1; i++ )
{
for ( j = i+1; j < n; j++ )
{
if ( a[i] < a[j] )
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return;
}
//****************************************************************************80
void r8vec_sort_heap_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_HEAP_A ascending sorts an R8VEC using heap sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 April 1999
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input/output, double A[N].
// On input, the array to be sorted;
// On output, the array has been sorted.
//
{
int n1;
double temp;
if ( n <= 1 )
{
return;
}
//
// 1: Put A into descending heap form.
//
r8vec_heap_d ( n, a );
//
// 2: Sort A.
//
// The largest object in the heap is in A[0].
// Move it to position A[N-1].
//
temp = a[0];
a[0] = a[n-1];
a[n-1] = temp;
//
// Consider the diminished heap of size N1.
//
for ( n1 = n-1; 2 <= n1; n1-- )
{
//
// Restore the heap structure of the initial N1 entries of A.
//
r8vec_heap_d ( n1, a );
//
// Take the largest object from A[0] and move it to A[N1-1].
//
temp = a[0];
a[0] = a[n1-1];
a[n1-1] = temp;
}
return;
}
//****************************************************************************80
void r8vec_sort_heap_d ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_HEAP_D descending sorts an R8VEC using heap sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 September 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input/output, double A[N].
// On input, the array to be sorted;
// On output, the array has been sorted.
//
{
int n1;
double temp;
if ( n <= 1 )
{
return;
}
//
// 1: Put A into ascending heap form.
//
r8vec_heap_a ( n, a );
//
// 2: Sort A.
//
// The smallest object in the heap is in A[0].
// Move it to position A[N-1].
//
temp = a[0];
a[0] = a[n-1];
a[n-1] = temp;
//
// Consider the diminished heap of size N1.
//
for ( n1 = n-1; 2 <= n1; n1-- )
{
//
// Restore the heap structure of the initial N1 entries of A.
//
r8vec_heap_a ( n1, a );
//
// Take the largest object from A[0] and move it to A[N1-1].
//
temp = a[0];
a[0] = a[n1-1];
a[n1-1] = temp;
}
return;
}
//****************************************************************************80
void r8vec_sort_heap_index_a ( int n, double a[], int indx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_HEAP_INDEX_A does an indexed heap ascending sort of an R8VEC
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The sorting is not actually carried out. Rather an index array is
// created which defines the sorting. This array may be used to sort
// or index the array, or to sort or index related arrays keyed on the
// original array.
//
// Once the index array is computed, the sorting can be carried out
// "implicitly:
//
// a(indx(*))
//
// or explicitly, by the call
//
// r8vec_permute ( n, indx, 0, a )
//
// after which a(*) is sorted.
//
// Note that the index vector is 0-based.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], an array to be index-sorted.
//
// Output, int INDX[N], contains the sort index. The
// I-th element of the sorted array is A(INDX(I)).
//
{
double aval;
int i;
int indxt;
int ir;
int j;
int l;
if ( n < 1 )
{
return;
}
for ( i = 0; i < n; i++ )
{
indx[i] = i;
}
if ( n == 1 )
{
return;
}
l = n / 2 + 1;
ir = n;
for ( ; ; )
{
if ( 1 < l )
{
l = l - 1;
indxt = indx[l-1];
aval = a[indxt];
}
else
{
indxt = indx[ir-1];
aval = a[indxt];
indx[ir-1] = indx[0];
ir = ir - 1;
if ( ir == 1 )
{
indx[0] = indxt;
break;
}
}
i = l;
j = l + l;
while ( j <= ir )
{
if ( j < ir )
{
if ( a[indx[j-1]] < a[indx[j]] )
{
j = j + 1;
}
}
if ( aval < a[indx[j-1]] )
{
indx[i-1] = indx[j-1];
i = j;
j = j + j;
}
else
{
j = ir + 1;
}
}
indx[i-1] = indxt;
}
return;
}
//****************************************************************************80
int *r8vec_sort_heap_index_a_new ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_HEAP_INDEX_A_NEW: indexed heap ascending sort of an R8VEC
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The sorting is not actually carried out. Rather an index array is
// created which defines the sorting. This array may be used to sort
// or index the array, or to sort or index related arrays keyed on the
// original array.
//
// Once the index array is computed, the sorting can be carried out
// "implicitly:
//
// a(indx(*))
//
// or explicitly, by the call
//
// r8vec_permute ( n, indx, 0, a )
//
// after which a(*) is sorted.
//
// Note that the index vector is 0-based.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], an array to be index-sorted.
//
// Output, int R8VEC_SORT_HEAP_INDEX_A[N], contains the sort index. The
// I-th element of the sorted array is A(INDX(I)).
//
{
double aval;
int i;
int *indx;
int indxt;
int ir;
int j;
int l;
if ( n < 1 )
{
return NULL;
}
indx = new int[n];
for ( i = 0; i < n; i++ )
{
indx[i] = i;
}
if ( n == 1 )
{
return indx;
}
l = n / 2 + 1;
ir = n;
for ( ; ; )
{
if ( 1 < l )
{
l = l - 1;
indxt = indx[l-1];
aval = a[indxt];
}
else
{
indxt = indx[ir-1];
aval = a[indxt];
indx[ir-1] = indx[0];
ir = ir - 1;
if ( ir == 1 )
{
indx[0] = indxt;
break;
}
}
i = l;
j = l + l;
while ( j <= ir )
{
if ( j < ir )
{
if ( a[indx[j-1]] < a[indx[j]] )
{
j = j + 1;
}
}
if ( aval < a[indx[j-1]] )
{
indx[i-1] = indx[j-1];
i = j;
j = j + j;
}
else
{
j = ir + 1;
}
}
indx[i-1] = indxt;
}
return indx;
}
//****************************************************************************80
void r8vec_sort_heap_index_d ( int n, double a[], int indx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_HEAP_INDEX_D_NEW: indexed heap descending sort of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The sorting is not actually carried out. Rather an index array is
// created which defines the sorting. This array may be used to sort
// or index the array, or to sort or index related arrays keyed on the
// original array.
//
// Once the index array is computed, the sorting can be carried out
// "implicitly:
//
// a(indx(*))
//
// or explicitly, by the call
//
// r8vec_permute ( n, indx, 0, a )
//
// after which a(*) is sorted.
//
// Note that the index vector is 0-based.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 October 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], an array to be index-sorted.
//
// Output, int INDX[N], contains the sort index. The
// I-th element of the sorted array is A(INDX(I)).
//
{
double aval;
int i;
int indxt;
int ir;
int j;
int l;
if ( n < 1 )
{
return;
}
for ( i = 0; i < n; i++ )
{
indx[i] = i;
}
if ( n == 1 )
{
return;
}
l = n / 2 + 1;
ir = n;
for ( ; ; )
{
if ( 1 < l )
{
l = l - 1;
indxt = indx[l-1];
aval = a[indxt];
}
else
{
indxt = indx[ir-1];
aval = a[indxt];
indx[ir-1] = indx[0];
ir = ir - 1;
if ( ir == 1 )
{
indx[0] = indxt;
break;
}
}
i = l;
j = l + l;
while ( j <= ir )
{
if ( j < ir )
{
if ( a[indx[j]] < a[indx[j-1]] )
{
j = j + 1;
}
}
if ( a[indx[j-1]] < aval )
{
indx[i-1] = indx[j-1];
i = j;
j = j + j;
}
else
{
j = ir + 1;
}
}
indx[i-1] = indxt;
}
return;
}
//****************************************************************************80
int *r8vec_sort_heap_index_d_new ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_HEAP_INDEX_D_NEW: indexed heap descending sort of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The sorting is not actually carried out. Rather an index array is
// created which defines the sorting. This array may be used to sort
// or index the array, or to sort or index related arrays keyed on the
// original array.
//
// Once the index array is computed, the sorting can be carried out
// "implicitly:
//
// a(indx(*))
//
// or explicitly, by the call
//
// r8vec_permute ( n, indx, 0, a )
//
// after which a(*) is sorted.
//
// Note that the index vector is 0-based.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 October 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], an array to be index-sorted.
//
// Output, int R8VEC_SORT_HEAP_INDEX_D[N], contains the sort index. The
// I-th element of the sorted array is A(INDX(I)).
//
{
double aval;
int i;
int *indx;
int indxt;
int ir;
int j;
int l;
if ( n < 1 )
{
return NULL;
}
indx = new int[n];
for ( i = 0; i < n; i++ )
{
indx[i] = i;
}
if ( n == 1 )
{
return indx;
}
l = n / 2 + 1;
ir = n;
for ( ; ; )
{
if ( 1 < l )
{
l = l - 1;
indxt = indx[l-1];
aval = a[indxt];
}
else
{
indxt = indx[ir-1];
aval = a[indxt];
indx[ir-1] = indx[0];
ir = ir - 1;
if ( ir == 1 )
{
indx[0] = indxt;
break;
}
}
i = l;
j = l + l;
while ( j <= ir )
{
if ( j < ir )
{
if ( a[indx[j]] < a[indx[j-1]] )
{
j = j + 1;
}
}
if ( a[indx[j-1]] < aval )
{
indx[i-1] = indx[j-1];
i = j;
j = j + j;
}
else
{
j = ir + 1;
}
}
indx[i-1] = indxt;
}
return indx;
}
//****************************************************************************80
int *r8vec_sort_heap_mask_a ( int n, double a[], int mask_num, int mask[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_HEAP_MASK_A: indexed heap ascending sort of a masked R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An array A is given. An array MASK of indices into A is given.
// The routine produces a vector INDX, which is a permutation of the
// entries of MASK, so that:
//
// A(MASK(INDX(I)) <= A(MASK(INDX(J))
//
// whenever
//
// I <= J
//
// In other words, only the elements of A that are indexed by MASK
// are to be considered, and the only thing that happens is that
// a rearrangment of the indices in MASK is returned that orders the
// masked elements.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 September 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], an array to be index-sorted.
//
// Input, int MASK_NUM, the number of mask elements.
//
// Input, int MASK[MASK_NUM], the mask array. This is
// simply a list of indices of A. The entries of MASK should
// be unique, and each one should be between 1 and N.
//
// Output, int INDX[MASK_NUM], the sort index. There are MASK_NUM
// elements of A selected by MASK. If we want to list those elements
// in order, then the I-th element is A(MASK(INDX(I))).
//
{
double aval;
int i;
int *indx;
int indxt;
int ir;
int j;
int l;
if ( n < 1 )
{
return NULL;
}
if ( mask_num < 1 )
{
return NULL;
}
if ( mask_num == 1 )
{
indx = new int[1];
indx[0] = 0;
return indx;
}
indx = i4vec_indicator1_new ( mask_num );
l = mask_num / 2 + 1;
ir = mask_num;
for ( ; ; )
{
if ( 1 < l )
{
l = l - 1;
indxt = indx[l-1];
aval = a[mask[indxt-1]-1];
}
else
{
indxt = indx[ir-1];
aval = a[mask[indxt-1]-1];
indx[ir-1] = indx[0];
ir = ir - 1;
if ( ir == 1 )
{
indx[0] = indxt;
break;
}
}
i = l;
j = l + l;
while ( j <= ir )
{
if ( j < ir )
{
if ( a[mask[indx[j-1]-1]-1] < a[mask[indx[j]-1]-1] )
{
j = j + 1;
}
}
if ( aval < a[mask[indx[j-1]-1]-1] )
{
indx[i-1] = indx[j-1];
i = j;
j = j + j;
}
else
{
j = ir + 1;
}
}
indx[i-1] = indxt;
}
for ( i = 0; i < mask_num; i++ )
{
indx[i] = indx[i] - 1;
}
return indx;
}
//****************************************************************************80
void r8vec_sort_insert_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_INSERT_A ascending sorts an R8VEC using an insertion sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 April 1999
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Donald Kreher, Douglas Simpson,
// Algorithm 1.1,
// Combinatorial Algorithms,
// CRC Press, 1998, page 11.
//
// Parameters:
//
// Input, int N, the number of items in the vector.
// N must be positive.
//
// Input/output, double A[N].
//
// On input, A contains data to be sorted.
// On output, the entries of A have been sorted in ascending order.
//
{
int i;
int j;
double x;
for ( i = 1; i < n; i++ )
{
x = a[i];
j = i;
while ( 1 <= j && x < a[j-1] )
{
a[j] = a[j-1];
j = j - 1;
}
a[j] = x;
}
return;
}
//****************************************************************************80
int *r8vec_sort_insert_index_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_INSERT_INDEX_A ascending index sorts an R8VEC using insertion.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 October 2014
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Donald Kreher, Douglas Simpson,
// Combinatorial Algorithms,
// CRC Press, 1998, page 11.
//
// Parameters:
//
// Input, int N, the number of items in the vector.
// N must be positive.
//
// Input, double A[N], the array to be sorted.
//
// Output, int R8VEC_SORT_INSERT_INDEX_A[N], the sorted indices. The array
// is sorted when listed from A(INDX(1)) through A(INDX(N)).
//
{
int i;
int *indx;
int j;
int k;
double x;
if ( n < 1 )
{
return NULL;
}
indx = i4vec_indicator0_new ( n );
for ( i = 1; i < n; i++ )
{
x = a[i];
j = i - 1;
while ( 0 <= j )
{
if ( a[indx[j]] <= x )
{
break;
}
indx[j+1] = indx[j];
j = j - 1;
}
indx[j+1] = i;
}
return indx;
}
//****************************************************************************80
void r8vec_sort_quick_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_QUICK_A ascending sorts an R8VEC using quick sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Example:
//
// Input:
//
// N = 7
//
// A = ( 6, 7, 3, 2, 9, 1, 8 )
//
// Output:
//
// A = ( 1, 2, 3, 6, 7, 8, 9 )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 April 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of A.
//
// Input/output, double A[N]. On input, the array to be sorted.
// On output, A has been reordered into ascending order.
//
{
# define LEVEL_MAX 30
int base;
int l_segment;
int level;
int n_segment;
int rsave[LEVEL_MAX];
int r_segment;
if ( n < 1 )
{
cerr << "\n";
cerr << "R8VEC_SORT_QUICK_A - Fatal error!\n";
cerr << " N < 1.\n";
exit ( 1 );
}
else if ( n == 1 )
{
return;
}
level = 1;
rsave[0] = n + 1;
base = 1;
n_segment = n;
while ( 0 < n_segment )
{
//
// Partition the segment.
//
r8vec_part_quick_a ( n_segment, a+base-1, l_segment, r_segment );
//
// If the left segment has more than one element, we need to partition it.
//
if ( 1 < l_segment )
{
if ( LEVEL_MAX < level )
{
cerr << "\n";
cerr << "R8VEC_SORT_QUICK_A - Fatal error!\n";
cerr << " Exceeding recursion maximum of " << LEVEL_MAX << "\n";
exit ( 1 );
}
level = level + 1;
n_segment = l_segment;
rsave[level-1] = r_segment + base - 1;
}
//
// The left segment and the middle segment are sorted.
// Must the right segment be partitioned?
//
else if ( r_segment < n_segment )
{
n_segment = n_segment + 1 - r_segment;
base = base + r_segment - 1;
}
//
// Otherwise, we back up a level if there is an earlier one.
//
else
{
for ( ; ; )
{
if ( 1 < level )
{
base = rsave[level-1];
n_segment = rsave[level-2] - rsave[level-1];
level = level - 1;
if ( 0 < n_segment )
{
break;
}
}
else
{
n_segment = 0;
break;
}
}
}
}
return;
# undef LEVEL_MAX
}
//****************************************************************************80
void r8vec_sort_shell_a ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORT_SHELL_A ascending sorts an R8VEC using Shell's sort.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input/output, double A[N].
// On input, an array to be sorted.
// On output, the sorted array.
//
{
double asave;
int i;
int ifree;
int inc;
int ipow;
int j;
int k;
int maxpow;
int test;
if ( n <= 1 )
{
return;
}
//
// Determine the smallest MAXPOW so that
// N <= ( 3^MAXPOW - 1 ) / 2
//
maxpow = 1;
test = 3;
while ( test < 2 * n + 1 )
{
maxpow = maxpow + 1;
test = test * 3;
}
if ( 1 < maxpow )
{
maxpow = maxpow - 1;
test = test / 3;
}
//
// Now sort groups of size ( 3^IPOW - 1 ) / 2.
//
for ( ipow = maxpow; 1 <= ipow; ipow-- )
{
inc = ( test - 1 ) / 2;
test = test / 3;
//
// Sort the values with indices equal to K mod INC.
//
for ( k = 1; k <= inc; k++ )
{
//
// Insertion sort of the items with index
// INC+K, 2*INC+K, 3*INC+K, ...
//
for ( i = inc+k; i <= n; i = i + inc )
{
asave = a[i-1];
ifree = i;
j = i - inc;
for ( ; ; )
{
if ( j < 1 )
{
break;
}
if ( a[j-1] <= asave )
{
break;
}
ifree = j;
a[j+inc-1] = a[j-1];
j = j - inc;
}
a[ifree-1] = asave;
}
}
}
return;
}
//****************************************************************************80
double *r8vec_sorted_merge_a ( int na, double a[], int nb, double b[], int &nc )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_MERGE_A merges two ascending sorted R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The elements of A and B should be sorted in ascending order.
//
// The elements in the output array C will also be in ascending order,
// and unique.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int NA, the dimension of A.
//
// Input, double A[NA], the first sorted array.
//
// Input, int NB, the dimension of B.
//
// Input, double B[NB], the second sorted array.
//
// Output, int &NC, the number of entries in the merged vector.
//
// Output, double R8VEC_SORTED_MERGE_A[NC], the merged unique sorted array.
//
{
double *c;
double *d;
int j;
int ja;
int jb;
int na2;
int nb2;
int nd;
int order;
na2 = na;
nb2 = nb;
ja = 0;
jb = 0;
nc = 0;
nd = 0;
d = new double[na+nb];
order = r8vec_order_type ( na2, a );
if ( order < 0 || 2 < order )
{
cerr << "\n";
cerr << "R8VEC_SORTED_MERGE_A - Fatal error!\n";
cerr << " The input array A is not ascending sorted.\n";
return NULL;
}
order = r8vec_order_type ( nb2, b );
if ( order < 0 || 2 < order )
{
cerr << "\n";
cerr << "R8VEC_SORTED_MERGE_A - Fatal error!\n";
cerr << " The input array B is not ascending sorted.\n";
return NULL;
}
for ( ; ; )
{
//
// If we've used up all the entries of A, stick the rest of B on the end.
//
if ( na2 <= ja )
{
for ( j = 1; j <= nb2 - jb; j++ )
{
jb = jb + 1;
if ( nd == 0 )
{
nd = nd + 1;
d[nd-1] = b[jb-1];
}
else if ( d[nd-1] < b[jb-1] )
{
nd = nd + 1;
d[nd-1] = b[jb-1];
}
}
break;
}
//
// If we've used up all the entries of B, stick the rest of A on the end.
//
else if ( nb2 <= jb )
{
for ( j = 1; j <= na2 - ja; j++ )
{
ja = ja + 1;
if ( nd == 0 )
{
nd = nd + 1;
d[nd-1] = a[ja-1];
}
else if ( d[nd-1] < a[ja-1] )
{
nd = nd + 1;
d[nd-1] = a[ja-1];
}
}
break;
}
//
// Otherwise, if the next entry of A is smaller, that's our candidate.
//
else if ( a[ja] <= b[jb] )
{
ja = ja + 1;
if ( nd == 0 )
{
nd = nd + 1;
d[nd-1] = a[ja-1];
}
else if ( d[nd-1] < a[ja-1] )
{
nd = nd + 1;
d[nd-1] = a[ja-1];
}
}
//
// ...or if the next entry of B is the smaller, consider that.
//
else
{
jb = jb + 1;
if ( nd == 0 )
{
nd = nd + 1;
d[nd-1] = b[jb-1];
}
else if ( d[nd-1] < b[jb-1] )
{
nd = nd + 1;
d[nd-1] = b[jb-1];
}
}
}
nc = nd;
c = r8vec_copy_new ( nd, d );
delete [] d;
return c;
}
//****************************************************************************80
int r8vec_sorted_nearest ( int n, double a[], double value )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_NEAREST returns the nearest element in a sorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], a sorted vector.
//
// Input, double VALUE, the value whose nearest vector entry is sought.
//
// Output, int R8VEC_SORTED_NEAREST, the index of the nearest
// entry in the vector.
//
{
int hi;
int lo;
int mid;
if ( n < 1 )
{
return (-1);
}
if ( n == 1 )
{
return 1;
}
if ( a[0] < a[n-1] )
{
if ( value < a[0] )
{
return 1;
}
else if ( a[n-1] < value )
{
return n;
}
//
// Seek an interval containing the value.
//
lo = 1;
hi = n;
while ( lo < hi - 1 )
{
mid = ( lo + hi ) / 2;
if ( value == a[mid-1] )
{
return mid;
}
else if ( value < a[mid-1] )
{
hi = mid;
}
else
{
lo = mid;
}
}
//
// Take the nearest.
//
if ( fabs ( value - a[lo-1] ) < fabs ( value - a[hi-1] ) )
{
return lo;
}
else
{
return hi;
}
}
//
// A descending sorted vector A.
//
else
{
if ( value < a[n-1] )
{
return n;
}
else if ( a[0] < value )
{
return 1;
}
//
// Seek an interval containing the value.
//
lo = n;
hi = 1;
while ( lo < hi - 1 )
{
mid = ( lo + hi ) / 2;
if ( value == a[mid-1] )
{
return mid;
}
else if ( value < a[mid-1] )
{
hi = mid;
}
else
{
lo = mid;
}
}
//
// Take the nearest.
//
if ( fabs ( value - a[lo-1] ) < fabs ( value - a[hi-1] ) )
{
return lo;
}
else
{
return hi;
}
}
}
//****************************************************************************80
void r8vec_sorted_range ( int n, double r[], double r_lo, double r_hi,
int &i_lo, int &i_hi )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_RANGE searches a sorted vector for elements in a range.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 25 September 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items in the vector.
//
// Input, double R[N], the sorted vector.
//
// Input, double R_LO, R_HI, the limits of the range.
//
// Output, int &I_LO, &I_HI, the range of indices
// so that I_LO <= I <= I_HI => R_LO <= R(I) <= R_HI. If no
// values in R lie in the range, then I_HI < I_LO will be returned.
//
{
int i1;
int i2;
int j1;
int j2;
//
// Cases we can handle immediately.
//
if ( r[n-1] < r_lo )
{
i_lo = - 1;
i_hi = - 2;
return;
}
if ( r_hi < r[0] )
{
i_lo = - 1;
i_hi = - 2;
return;
}
//
// Are there are least two intervals?
//
if ( n == 1 )
{
if ( r_lo <= r[0] && r[0] <= r_hi )
{
i_lo = 1;
i_hi = 1;
}
else
{
i_lo = - 1;
i_hi = - 2;
}
return;
}
//
// Bracket R_LO.
//
if ( r_lo <= r[0] )
{
i_lo = 0;
}
else
{
//
// R_LO is in one of the intervals spanned by R(J1) to R(J2).
// Examine the intermediate interval [R(I1), R(I1+1)].
// Does R_LO lie here, or below or above?
//
j1 = 0;
j2 = n - 1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
for ( ; ; )
{
if ( r_lo < r[i1] )
{
j2 = i1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else if ( r[i2] < r_lo )
{
j1 = i2;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else
{
i_lo = i1;
break;
}
}
}
//
// Bracket R_HI
//
if ( r[n-1] <= r_hi )
{
i_hi = n - 1;
}
else
{
j1 = i_lo;
j2 = n - 1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
for ( ; ; )
{
if ( r_hi < r[i1] )
{
j2 = i1;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else if ( r[i2] < r_hi )
{
j1 = i2;
i1 = ( j1 + j2 - 1 ) / 2;
i2 = i1 + 1;
}
else
{
i_hi = i2;
break;
}
}
}
//
// We expect to have computed the largest I_LO and smallest I_HI such that
// R(I_LO) <= R_LO <= R_HI <= R(I_HI)
// but what we want is actually
// R_LO <= R(I_LO) <= R(I_HI) <= R_HI
// which we can usually get simply by incrementing I_LO and decrementing I_HI.
//
if ( r[i_lo] < r_lo )
{
i_lo = i_lo + 1;
if ( n - 1 < i_lo )
{
i_hi = i_lo - 1;
}
}
if ( r_hi < r[i_hi] )
{
i_hi = i_hi - 1;
if ( i_hi < 0 )
{
i_lo = i_hi + 1;
}
}
return;
}
//****************************************************************************80
void r8vec_sorted_split ( int n, double a[], double split, int &i_lt,
int &i_gt )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_SPLIT "splits" a sorted R8VEC, given a splitting value.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Given a splitting value SPLIT, the routine seeks indices
// I_LT and I_GT so that
//
// A(I_LT) < SPLIT < A(I_GT),
//
// and if there are intermediate index values between I_LT and
// I_GT, then those entries of A are exactly equal to SPLIT.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters
//
// Input, int N, the number of entries in A.
//
// Input, double A[N], a sorted array.
//
// Input, double SPLIT, a value to which the entries in A are
// to be compared.
//
// Output, int &I_LT:
// 0 if no entries are less than SPLIT;
// N if all entries are less than SPLIT;
// otherwise, the index of the last entry in A less than SPLIT.
//
// Output, int &I_GT:
// 1 if all entries are greater than SPLIT;
// N+1 if no entries are greater than SPLIT;
// otherwise the index of the first entry in A greater than SPLIT.
//
{
int hi;
int i;
int lo;
int mid;
if ( n < 1 )
{
i_lt = -1;
i_gt = -1;
return;
}
if ( split < a[0] )
{
i_lt = 0;
i_gt = 1;
return;
}
if ( a[n-1] < split )
{
i_lt = n;
i_gt = n + 1;
return;
}
lo = 1;
hi = n;
for ( ; ; )
{
if ( lo + 1 == hi )
{
i_lt = lo;
break;
}
mid = ( lo + hi ) / 2;
if ( split <= a[mid-1] )
{
hi = mid;
}
else
{
lo = mid;
}
}
for ( i = i_lt + 1; i <= n; i++ )
{
if ( split < a[i-1] )
{
i_gt = i;
return;
}
}
i_gt = n + 1;
return;
}
//****************************************************************************80
void r8vec_sorted_undex ( int x_num, double x_val[], int x_unique_num,
double tol, int undx[], int xdnu[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_UNDEX returns unique sorted indexes for a sorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The goal of this routine is to determine a vector UNDX,
// which points, to the unique elements of X, in sorted order,
// and a vector XDNU, which identifies, for each entry of X, the index of
// the unique sorted element of X.
//
// This is all done with index vectors, so that the elements of
// X are never moved.
//
// Assuming X is already sorted, we examine the entries of X in order,
// noting the unique entries, creating the entries of XDNU and
// UNDX as we go.
//
// Once this process has been completed, the vector X could be
// replaced by a compressed vector XU, containing the unique entries
// of X in sorted order, using the formula
//
// XU(I) = X(UNDX(I)).
//
// We could then, if we wished, reconstruct the entire vector X, or
// any element of it, by index, as follows:
//
// X(I) = XU(XDNU(I)).
//
// We could then replace X by the combination of XU and XDNU.
//
// Later, when we need the I-th entry of X, we can locate it as
// the XDNU(I)-th entry of XU.
//
// Here is an example of a vector X, the sort and inverse sort
// index vectors, and the unique sort and inverse unique sort vectors
// and the compressed unique sorted vector.
//
// I X XU Undx Xdnu
// ----+------+------+-----+-----+
// 0 | 11.0 | 11.0 0 0
// 1 | 11.0 | 22.0 4 0
// 2 | 11.0 | 33.0 7 0
// 3 | 11.0 | 55.0 8 0
// 4 | 22.0 | 1
// 5 | 22.0 | 1
// 6 | 22.0 | 1
// 7 | 33.0 | 2
// 8 | 55.0 | 3
//
// INDX(2) = 3 means that sorted item(2) is X(3).
// XDNI(2) = 5 means that X(2) is sorted item(5).
//
// UNDX(3) = 4 means that unique sorted item(3) is at X(4).
// XDNU(8) = 2 means that X(8) is at unique sorted item(2).
//
// XU(XDNU(I))) = X(I).
// XU(I) = X(UNDX(I)).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 November 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int X_NUM, the number of data values.
//
// Input, double X_VAL[X_NUM], the data values.
//
// Input, int X_UNIQUE_NUM, the number of unique values in X_VAL.
// This value is only required for languages in which the size of
// UNDX must be known in advance.
//
// Input, double TOL, a tolerance for equality.
//
// Output, int UNDX[X_UNIQUE_NUM], the UNDX vector.
//
// Output, int XDNU[X_NUM], the XDNU vector.
//
{
int i;
int j;
//
// Walk through the sorted array X.
//
i = 0;
j = 0;
undx[j] = i;
xdnu[i] = j;
for ( i = 1; i < x_num; i++ )
{
if ( tol < fabs ( x_val[i] - x_val[undx[j]] ) )
{
j = j + 1;
undx[j] = i;
}
xdnu[i] = j;
}
return;
}
//****************************************************************************80
double *r8vec_sorted_unique ( int n, double a[], double tol, int &unique_num )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_UNIQUE finds the unique elements in a sorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// If the data is not sorted, the results of the routine will
// be garbage.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], the sorted array of N elements;
//
// Input, double TOL, a tolerance for checking equality.
//
// Output, int &UNIQUE_NUM, the number of unique elements of A.
//
// Output, double R8VEC_SORTED_UNIQUE[UNIQUE_NUM], the unique elements of A.
//
{
double *a_unique;
int i;
int iuniq;
unique_num = 0;
if ( n <= 0 )
{
return NULL;
}
//
// Determine the number of unique elements.
//
iuniq = 0;
unique_num = 1;
for ( i = 1; i < n; i++ )
{
if ( tol < fabs ( a[i] - a[iuniq] ) )
{
iuniq = i;
unique_num = unique_num + 1;
}
}
//
// Set aside space for the unique elements.
//
a_unique = new double[unique_num];
//
// Repeat the search, but now store the unique elements.
//
unique_num = 0;
a_unique[unique_num] = a[0];
unique_num = 1;
for ( i = 1; i < n; i++ )
{
if ( tol < fabs ( a[i] - a_unique[unique_num-1] ) )
{
a_unique[unique_num] = a[i];
unique_num = unique_num + 1;
}
}
return a_unique;
}
//****************************************************************************80
int r8vec_sorted_unique_count ( int n, double a[], double tol )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_UNIQUE_COUNT counts unique elements in a sorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Because the array is sorted, this algorithm is O(N).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], the sorted array to examine.
//
// Input, double TOL, a tolerance for checking equality.
//
// Output, int R8VEC_SORTED_UNIQUE_COUNT, the number of unique elements of A.
//
{
int i;
int unique_num;
unique_num = 0;
if ( n < 1 )
{
return unique_num;
}
unique_num = 1;
for ( i = 1; i < n; i++ )
{
if ( tol < fabs ( a[i-1] - a[i] ) )
{
unique_num = unique_num + 1;
}
}
return unique_num;
}
//****************************************************************************80
void r8vec_sorted_unique_hist ( int n, double a[], double tol, int maxuniq,
int &unique_num, double auniq[], int acount[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SORTED_UNIQUE_HIST histograms unique elements of a sorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], the array to examine, which must have been
// sorted.
//
// Input, double TOL, a tolerance for checking equality.
//
// Input, int MAXUNIQ, the maximum number of unique elements
// that can be handled. If there are more than MAXUNIQ unique
// elements in A, the excess will be ignored.
//
// Output, int &UNIQUE_NUM, the number of unique elements of A.
//
// Output, double AUNIQ[UNIQUE_NUM], the unique elements of A.
//
// Output, int ACOUNT[UNIQUE_NUM], the number of times each element
// of AUNIQ occurs in A.
//
{
int i;
int index;
//
// Start taking statistics.
//
index = -1;
for ( i = 0; i < n; i++ )
{
if ( i == 0 )
{
index = 0;
auniq[index] = a[0];
acount[index] = 1;
}
else if ( fabs ( a[i] - auniq[index] ) <= tol )
{
acount[index] = acount[index] + 1;
}
else if ( index + 1 < maxuniq )
{
index = index + 1;
auniq[index] = a[i];
acount[index] = 1;
}
}
unique_num = index + 1;
return;
}
//****************************************************************************80
int r8vec_split ( int n, double a[], double split )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SPLIT "splits" an unsorted R8VEC based on a splitting value.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// If the vector is already sorted, it is simpler to do a binary search
// on the data than to call this routine.
//
// The vector is not assumed to be sorted before input, and is not
// sorted during processing. If sorting is not needed, then it is
// more efficient to use this routine.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input/output, double A[N], the array to split. On output,
// all the entries of A that are less than or equal to SPLIT
// are in A(1:ISPLIT).
//
// Input, double SPLIT, the value used to split the vector.
// It is not necessary that any value of A actually equal SPLIT.
//
// Output, int R8VEC_SPLIT, indicates the position of the last
// entry of the split vector that is less than or equal to SPLIT.
//
{
int i;
int i1;
int i2;
int i3;
int isplit;
int j1;
int j2;
int j3;
double temp;
//
// Partition the vector into A1, A2, A3, where
// A1 = A(I1:J1) holds values <= SPLIT,
// A2 = A(I2:J2) holds untested values,
// A3 = A(I3:J3) holds values > SPLIT.
//
i1 = 1;
j1 = 0;
i2 = 1;
j2 = n;
i3 = n+1;
j3 = n;
//
// Pick the next item from A2, and move it into A1 or A3.
// Adjust indices appropriately.
//
for ( i = 1; i <= n; i++ )
{
if ( a[i2-1] <= split )
{
i2 = i2 + 1;
j1 = j1 + 1;
}
else
{
temp = a[i2-1];
a[i2-1] = a[i3-2];
a[i3-2] = temp;
i3 = i3 - 1;
j2 = j2 - 1;
}
}
isplit = j1;
return isplit;
}
//****************************************************************************80
double r8vec_std ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_STD returns the standard deviation of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The standard deviation of a vector X of length N is defined as
//
// mean ( X(1:n) ) = sum ( X(1:n) ) / n
//
// std ( X(1:n) ) = sqrt ( sum ( ( X(1:n) - mean )^2 ) / ( n - 1 ) )
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 April 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
// N should be at least 2.
//
// Input, double A[N], the vector.
//
// Output, double R8VEC_STD, the standard deviation of the vector.
//
{
int i;
double mean;
double std;
if ( n < 2 )
{
std = 0.0;
}
else
{
mean = 0.0;
for ( i = 0; i < n; i++ )
{
mean = mean + a[i];
}
mean = mean / ( ( double ) n );
std = 0.0;
for ( i = 0; i < n; i++ )
{
std = std + ( a[i] - mean ) * ( a[i] - mean );
}
std = sqrt ( std / ( ( double ) ( n - 1 ) ) );
}
return std;
}
//****************************************************************************80
void r8vec_step ( double x0, int n, double x[], double fx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_STEP evaluates a unit step function.
//
// Discussion:
//
// F(X) = 0 if X < X0
// 1 if X0 <= X
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 May 2013
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X0, the location of the jump.
//
// Input, int N, the number of argument values.
//
// Output, double X[N], the arguments.
//
// Output, double FX[N], the function values.
//
{
int i;
for ( i = 0; i < n; i++ )
{
if ( x[i] < x0 )
{
fx[i] = 0.0;
}
else
{
fx[i] = 1.0;
}
}
return;
}
//****************************************************************************80
void r8vec_stutter ( int n, double a[], int m, double am[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_STUTTER makes a "stuttering" copy of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Applying a stuttering factor M of 3, the vector A = ( 1, 5, 8 ) becomes
// AM = ( 1, 1, 1, 5, 5, 5, 8, 8, 8 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the input vector.
//
// Input, double A[N], the vector.
//
// Input, int M, the "stuttering factor".
//
// Output, double AM[M*N], the stuttering vector.
//
{
int i;
int j;
int k;
k = 0;
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < m; j++ )
{
am[k] = a[i];
k = k + 1;
}
}
return;
}
//****************************************************************************80
double *r8vec_stutter_new ( int n, double a[], int m )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_STUTTER_NEW makes a "stuttering" copy of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Applying a stuttering factor M of 3, the vector A = ( 1, 5, 8 ) becomes
// AM = ( 1, 1, 1, 5, 5, 5, 8, 8, 8 ).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the size of the input vector.
//
// Input, double A[N], the vector.
//
// Input, int M, the "stuttering factor".
//
// Output, double R8VEC_STUTTER_NEW[M*N], the stuttering vector.
//
{
double *am;
int i;
int j;
int k;
am = new double[m*n];
k = 0;
for ( i = 0; i < n; i++ )
{
for ( j = 0; j < m; j++ )
{
am[k] = a[i];
k = k + 1;
}
}
return am;
}
//****************************************************************************80
double r8vec_sum ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SUM returns the sum of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], the vector.
//
// Output, double R8VEC_SUM, the sum of the vector.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + a[i];
}
return value;
}
//****************************************************************************80
void r8vec_swap ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SWAP swaps the entries of two R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 28 August 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the arrays.
//
// Input/output, double A1[N], A2[N], the vectors to swap.
//
{
int i;
double temp;
for ( i = 0; i < n; i++ )
{
temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
}
return;
}
//****************************************************************************80
void r8vec_transpose_print ( int n, double a[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_TRANSPOSE_PRINT prints an R8VEC "transposed".
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Example:
//
// A = (/ 1.0, 2.1, 3.2, 4.3, 5.4, 6.5, 7.6, 8.7, 9.8, 10.9, 11.0 /)
// TITLE = 'My vector: '
//
// My vector: 1.0 2.1 3.2 4.3 5.4
// 6.5 7.6 8.7 9.8 10.9
// 11.0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 May 2014
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A[N], the vector to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
int ihi;
int ilo;
int title_length;
title_length = s_len_trim ( title );
for ( ilo = 0; ilo < n; ilo = ilo + 5 )
{
if ( ilo == 0 )
{
cout << title;
}
else
{
for ( i = 0; i < title_length; i++ )
{
cout << " ";
}
}
cout << " ";
ihi = i4_min ( ilo + 5, n );
for ( i = ilo; i < ihi; i++ )
{
cout << " " << setw(12) << a[i];
}
cout << "\n";
}
return;
}
//****************************************************************************80
void r8vec_undex ( int x_num, double x_val[], int x_unique_num, double tol,
int undx[], int xdnu[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNDEX returns unique sorted indexes for an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// The goal of this routine is to determine a vector UNDX,
// which points, to the unique elements of X, in sorted order,
// and a vector XDNU, which identifies, for each entry of X, the index of
// the unique sorted element of X.
//
// This is all done with index vectors, so that the elements of
// X are never moved.
//
// The first step of the algorithm requires the indexed sorting
// of X, which creates arrays INDX and XDNI. (If all the entries
// of X are unique, then these arrays are the same as UNDX and XDNU.)
//
// We then use INDX to examine the entries of X in sorted order,
// noting the unique entries, creating the entries of XDNU and
// UNDX as we go.
//
// Once this process has been completed, the vector X could be
// replaced by a compressed vector XU, containing the unique entries
// of X in sorted order, using the formula
//
// XU(*) = X(UNDX(*)).
//
// We could then, if we wished, reconstruct the entire vector X, or
// any element of it, by index, as follows:
//
// X(I) = XU(XDNU(I)).
//
// We could then replace X by the combination of XU and XDNU.
//
// Later, when we need the I-th entry of X, we can locate it as
// the XDNU(I)-th entry of XU.
//
// Here is an example of a vector X, the sort and inverse sort
// index vectors, and the unique sort and inverse unique sort vectors
// and the compressed unique sorted vector.
//
// I X Indx Xdni XU Undx Xdnu
// ----+-----+-----+-----+--------+-----+-----+
// 0 | 11. 0 0 | 11. 0 0
// 1 | 22. 2 4 | 22. 1 1
// 2 | 11. 5 1 | 33. 3 0
// 3 | 33. 8 7 | 55. 4 2
// 4 | 55. 1 8 | 3
// 5 | 11. 6 2 | 0
// 6 | 22. 7 5 | 1
// 7 | 22. 3 6 | 1
// 8 | 11. 4 3 | 0
//
// INDX(2) = 3 means that sorted item(2) is X(3).
// XDNI(2) = 5 means that X(2) is sorted item(5).
//
// UNDX(3) = 4 means that unique sorted item(3) is at X(4).
// XDNU(8) = 2 means that X(8) is at unique sorted item(2).
//
// XU(XDNU(I))) = X(I).
// XU(I) = X(UNDX(I)).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int X_NUM, the number of data values.
//
// Input, double X_VAL[X_NUM], the data values.
//
// Input, int X_UNIQUE_NUM, the number of unique values in X_VAL.
// This value is only required for languages in which the size of
// UNDX must be known in advance.
//
// Input, double TOL, a tolerance for equality.
//
// Output, int UNDX[X_UNIQUE_NUM], the UNDX vector.
//
// Output, int XDNU[X_NUM], the XDNU vector.
//
{
int i;
int *indx;
int j;
//
// Implicitly sort the array.
//
indx = r8vec_sort_heap_index_a_new ( x_num, x_val );
//
// Walk through the implicitly sorted array X.
//
i = 0;
j = 0;
undx[j] = indx[i];
xdnu[indx[i]] = j;
for ( i = 1; i < x_num; i++ )
{
if ( tol < fabs ( x_val[indx[i]] - x_val[undx[j]] ) )
{
j = j + 1;
undx[j] = indx[i];
}
xdnu[indx[i]] = j;
}
delete [] indx;
return;
}
//****************************************************************************80
void r8vec_uniform_01 ( int n, int &seed, double r[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.
//
// Discussion:
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 August 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R[N], the vector of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int k;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8VEC_UNIFORM_01 - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( i = 0; i < n; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i] = ( double ) ( seed ) * 4.656612875E-10;
}
return;
}
//****************************************************************************80
double *r8vec_uniform_01_new ( int n, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_01_NEW returns a new unit pseudorandom R8VEC.
//
// Discussion:
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 August 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8VEC_UNIFORM_01_NEW[N], the vector of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int k;
double *r;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8VEC_UNIFORM_01_NEW - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
r = new double[n];
for ( i = 0; i < n; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i] = ( double ) ( seed ) * 4.656612875E-10;
}
return r;
}
//****************************************************************************80
void r8vec_uniform_ab ( int n, double a, double b, int &seed, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_AB returns a scaled pseudorandom R8VEC.
//
// Discussion:
//
// Each dimension ranges from A to B.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A, B, the lower and upper limits of the pseudorandom values.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double X[N], the vector of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int k;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8VEC_UNIFORM_AB - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( i = 0; i < n; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
x[i] = a + ( b - a ) * ( double ) ( seed ) * 4.656612875E-10;
}
return;
}
//****************************************************************************80
double *r8vec_uniform_ab_new ( int n, double a, double b, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_AB_NEW returns a scaled pseudorandom R8VEC.
//
// Discussion:
//
// Each dimension ranges from A to B.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A, B, the lower and upper limits of the pseudorandom values.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8VEC_UNIFORM_AB_NEW[N], the vector of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int k;
double *r;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8VEC_UNIFORM_AB_NEW - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
r = new double[n];
for ( i = 0; i < n; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i] = a + ( b - a ) * ( double ) ( seed ) * 4.656612875E-10;
}
return r;
}
//****************************************************************************80
void r8vec_uniform_abvec ( int n, double a[], double b[], int &seed, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_ABVEC returns a scaled pseudorandom R8VEC.
//
// Discussion:
//
// Dimension I ranges from A[I] to B[I].
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], B[N], the lower and upper limits of the
// pseudorandom values.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double X[N], the vector of pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int k;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8VEC_UNIFORM_ABVEC - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( i = 0; i < n; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
x[i] = a[i] + ( b[i] - a[i] ) * ( double ) ( seed ) * 4.656612875E-10;
}
return;
}
//****************************************************************************80
double *r8vec_uniform_abvec_new ( int n, double a[], double b[], int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_ABVEC_NEW returns a scaled pseudorandom R8VEC.
//
// Discussion:
//
// Dimension I ranges from A[I] to B[I].
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 April 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], B[N], the lower and upper limits of the
// pseudorandom values.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8VEC_UNIFORM_ABVEC_NEW[N], the vector of
// pseudorandom values.
//
{
int i;
const int i4_huge = 2147483647;
int k;
double *r;
if ( seed == 0 )
{
cerr << "\n";
cerr << "R8VEC_UNIFORM_ABVEC_NEW - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
r = new double[n];
for ( i = 0; i < n; i++ )
{
k = seed / 127773;
seed = 16807 * ( seed - k * 127773 ) - k * 2836;
if ( seed < 0 )
{
seed = seed + i4_huge;
}
r[i] = a[i] + ( b[i] - a[i] ) * ( double ) ( seed ) * 4.656612875E-10;
}
return r;
}
//****************************************************************************80
double *r8vec_uniform_unit_new ( int m, int &seed )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_UNIT_NEW generates a random unit vector.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 04 October 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, the dimension of the space.
//
// Input/output, int &SEED, a seed for the random number generator.
//
// Output, double R8VEC_UNIFORM_UNIT_NEW[M], a random direction vector,
// with unit norm.
//
{
double *a;
int i;
double norm;
//
// Take M random samples from the normal distribution.
//
a = r8vec_normal_01_new ( m, seed );
//
// Compute the norm.
//
norm = 0.0;
for ( i = 0; i < m; i++ )
{
norm = norm + a[i] * a[i];
}
norm = sqrt ( norm );
//
// Normalize.
//
for ( i = 0; i < m; i++ )
{
a[i] = a[i] / norm;
}
return a;
}
//****************************************************************************80
int r8vec_unique_count ( int n, double a[], double tol )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIQUE_COUNT counts the unique elements in an unsorted R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Because the array is unsorted, this algorithm is O(N^2).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 April 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], the array to examine, which does NOT have to
// be sorted.
//
// Input, double TOL, a tolerance for checking equality.
//
// Output, int R8VEC_UNIQUE_COUNT, the number of unique elements of A.
//
{
int i;
int j;
int unique_num;
unique_num = 0;
for ( i = 0; i < n; i++ )
{
unique_num = unique_num + 1;
for ( j = 0; j < i; j++ )
{
if ( fabs ( a[i] - a[j] ) <= tol )
{
unique_num = unique_num - 1;
break;
}
}
}
return unique_num;
}
//****************************************************************************80
int *r8vec_unique_index ( int n, double a[], double tol )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIQUE_INDEX indexes the unique occurrence of values in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// For element A(I) of the vector, UNIQUE_INDEX(I) is the uniqueness index
// of A(I). That is, if A_UNIQUE contains the unique elements of A,
// gathered in order, then
//
// A_UNIQUE ( UNIQUE_INDEX(I) ) = A(I)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 24 August 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of elements of A.
//
// Input, double A[N], the unsorted array to examine.
//
// Input, double TOL, a tolerance for equality.
//
// Output, int R8VEC_UNIQUE_INDEX[N], the unique index.
//
{
int i;
int j;
int *unique_index;
int unique_num;
unique_index = new int[n];
for ( i = 0; i < n; i++ )
{
unique_index[i] = -1;
}
unique_num = 0;
for ( i = 0; i < n; i++ )
{
if ( unique_index[i] == -1 )
{
unique_index[i] = unique_num;
for ( j = i + 1; j < n; j++ )
{
if ( fabs ( a[i] - a[j] ) <= tol )
{
unique_index[j] = unique_num;
}
}
unique_num = unique_num + 1;
}
}
return unique_index;
}
//****************************************************************************80
double r8vec_variance ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_VARIANCE returns the variance of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 May 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double X[N], the vector whose variance is desired.
//
// Output, double R8VEC_VARIANCE, the variance of the vector entries.
//
{
int i;
double mean;
double variance;
mean = r8vec_mean ( n, x );
variance = 0.0;
for ( i = 0; i < n; i++ )
{
variance = variance + ( x[i] - mean ) * ( x[i] - mean );
}
if ( 1 < n )
{
variance = variance / ( double ) ( n - 1 );
}
else
{
variance = 0.0;
}
return variance;
}
//****************************************************************************80
double *r8vec_vector_triple_product ( double v1[3], double v2[3], double v3[3] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_VECTOR_TRIPLE_PRODUCT computes the vector triple product.
//
// Discussion:
//
// VTRIPLE = V1 x (V2 x V3)
//
// VTRIPLE is a vector perpendicular to V1, lying in the plane
// spanned by V2 and V3. The norm of VTRIPLE is the product
// of the norms of V1, V2 and V3.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double V1[3], V2[3], V3[3], the coordinates
// of the three vectors.
//
// Output, double R8VEC_VECTOR_TRIPLE_PRODUCT[3], the vector triple product.
//
{
double *v123;
double *v23;
v23 = r8vec_cross_product_3d ( v2, v3 );
v123 = r8vec_cross_product_3d ( v1, v23 );
delete [] v23;
return v123;
}
//****************************************************************************80
void r8vec_write ( int n, double r[], string output_file )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_WRITE writes an R8VEC to a file.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 August 2010
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the matrix.
//
// Input, double R[N], the vector to be written.
//
// Input, string OUTPUT_FILE, the name of the file to which
// the information is to be written.
//
{
int i;
ofstream output;
output.open ( output_file.c_str ( ) );
if ( !output )
{
cerr << "\n";
cerr << "R8VEC_WRITE - Fatal error!\n";
cerr << " Could not open the output file.\n";
return;
}
for ( i = 0; i < n; i++ )
{
output << " " << setw(16) << r[i] << "\n";
}
output.close ( );
return;
}
//****************************************************************************80
void r8vec_zeros ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ZEROS zeroes an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 July 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, double A[N], a vector of zeroes.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = 0.0;
}
return;
}
//****************************************************************************80
double *r8vec_zeros_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ZEROS_NEW creates and zeroes an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, double R8VEC_ZEROS_NEW[N], a vector of zeroes.
//
{
double *a;
int i;
a = new double[n];
for ( i = 0; i < n; i++ )
{
a[i] = 0.0;
}
return a;
}
//****************************************************************************80
int r8vec2_compare ( int n, double a1[], double a2[], int i, int j )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_COMPARE compares two elements of an R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of data items.
//
// Input, double A1[N], A2[N], contain the two components of each item.
//
// Input, int I, J, the items to be compared. These values will be
// 1-based indices for the arrays A1 and A2.
//
// Output, int R8VEC2_COMPARE, the results of the comparison:
// -1, item I < item J,
// 0, item I = item J,
// +1, item J < item I.
//
{
int isgn;
isgn = 0;
if ( a1[i-1] < a1[j-1] )
{
isgn = -1;
}
else if ( a1[i-1] == a1[j-1] )
{
if ( a2[i-1] < a2[j-1] )
{
isgn = -1;
}
else if ( a2[i-1] < a2[j-1] )
{
isgn = 0;
}
else if ( a2[j-1] < a2[i-1] )
{
isgn = +1;
}
}
else if ( a1[j-1] < a1[i-1] )
{
isgn = +1;
}
return isgn;
}
//****************************************************************************80
void r8vec2_print ( int n, double a1[], double a2[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_PRINT prints an R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 November 2002
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A1[N], double A2[N], the vectors to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = 0; i <= n - 1; i++ )
{
cout << setw(6) << i
<< ": " << setw(14) << a1[i]
<< " " << setw(14) << a2[i] << "\n";
}
return;
}
//****************************************************************************80
void r8vec2_print_some ( int n, double x1[], double x2[], int max_print,
string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_PRINT_SOME prints "some" of an R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// The user specifies MAX_PRINT, the maximum number of lines to print.
//
// If N, the size of the vectors, is no more than MAX_PRINT, then
// the entire vectors are printed, one entry of each per line.
//
// Otherwise, if possible, the first MAX_PRINT-2 entries are printed,
// followed by a line of periods suggesting an omission,
// and the last entry.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 November 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries of the vectors.
//
// Input, double X1[N], X2[N], the vector to be printed.
//
// Input, int MAX_PRINT, the maximum number of lines to print.
//
// Input, string TITLE, a title.
//
{
int i;
if ( max_print <= 0 )
{
return;
}
if ( n <= 0 )
{
return;
}
cout << "\n";
cout << title << "\n";
cout << "\n";
if ( n <= max_print )
{
for ( i = 0; i < n; i++ )
{
cout << setw(6) << i << ": "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
}
else if ( 3 <= max_print )
{
for ( i = 0; i < max_print-2; i++ )
{
cout << setw(6) << i << ": "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
cout << "...... .............. ..............\n";
i = n - 1;
cout << setw(6) << i << ": "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
else
{
for ( i = 0; i < max_print - 1; i++ )
{
cout << setw(6) << i << ": "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "\n";
}
i = max_print - 1;
cout << setw(6) << i << ": "
<< setw(14) << x1[i] << " "
<< setw(14) << x2[i] << "...more entries...\n";
}
return;
}
//****************************************************************************80
void r8vec2_sort_a ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_SORT_A ascending sorts an R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// Each item to be sorted is a pair of reals (X,Y), with the X
// and Y values stored in separate vectors A1 and A2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items of data.
//
// Input/output, double A1[N], A2[N], the data to be sorted.
//
{
int i;
int indx;
int isgn;
int j;
double temp;
//
// Initialize.
//
i = 0;
indx = 0;
isgn = 0;
j = 0;
//
// Call the external heap sorter.
//
for ( ; ; )
{
sort_heap_external ( n, indx, i, j, isgn );
//
// Interchange the I and J objects.
//
if ( 0 < indx )
{
temp = a1[i-1];
a1[i-1] = a1[j-1];
a1[j-1] = temp;
temp = a2[i-1];
a2[i-1] = a2[j-1];
a2[j-1] = temp;
}
//
// Compare the I and J objects.
//
else if ( indx < 0 )
{
isgn = r8vec2_compare ( n, a1, a2, i, j );
}
else if ( indx == 0 )
{
break;
}
}
return;
}
//****************************************************************************80
void r8vec2_sort_d ( int n, double a1[], double a2[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_SORT_D descending sorts an R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// Each item to be sorted is a pair of reals (X,Y), with the X
// and Y values stored in separate vectors A1 and A2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items of data.
//
// Input/output, double A1[N], A2[N], the data to be sorted.
//
{
int i;
int indx;
int isgn;
int j;
double temp;
//
// Initialize.
//
i = 0;
indx = 0;
isgn = 0;
j = 0;
//
// Call the external heap sorter.
//
for ( ; ; )
{
sort_heap_external ( n, indx, i, j, isgn );
//
// Interchange the I and J objects.
//
if ( 0 < indx )
{
temp = a1[i-1];
a1[i-1] = a1[j-1];
a1[j-1] = temp;
temp = a2[i-1];
a2[i-1] = a2[j-1];
a2[j-1] = temp;
}
//
// Compare the I and J objects.
//
else if ( indx < 0 )
{
isgn = - r8vec2_compare ( n, a1, a2, i, j );
}
else if ( indx == 0 )
{
break;
}
}
return;
}
//****************************************************************************80
int *r8vec2_sort_heap_index_a ( int n, double x[], double y[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_SORT_HEAP_INDEX_A does an indexed heap ascending sort of an R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// The sorting is not actually carried out. Rather an index array is
// created which defines the sorting. This array may be used to sort
// or index the array, or to sort or index related arrays keyed on the
// original array.
//
// ( X(I), Y(I) ) < ( X(J), Y(J) ) if:
//
// * X(I) < X(J), or
//
// * X(I) = X(J), and Y(I) < Y(J).
//
// Once the index array is computed, the sorting can be carried out
// implicitly:
//
// ( x(indx(*)), y(indx(*) )
//
// or explicitly, by the calls
//
// r8vec_permute ( n, indx, 0, x )
// r8vec_permute ( n, indx, 0, y )
//
// after which ( x(*), y(*) ), is sorted.
//
// Note that the index vector is 0-based.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double X[N], Y[N], pairs of X, Y coordinates of points.
//
// Output, int INDX[N], the sort index. The
// I-th element of the sorted array has coordinates
// ( X(INDX(I)), Y(INDX(I) ).
//
{
int i;
int *indx;
int indxt;
int ir;
int j;
int l;
double xval;
double yval;
if ( n < 1 )
{
return NULL;
}
indx = new int[n];
for ( i = 0; i < n; i++ )
{
indx[i] = i;
}
if ( n == 1 )
{
indx[0] = indx[0];
return indx;
}
l = n / 2 + 1;
ir = n;
for ( ; ; )
{
if ( 1 < l )
{
l = l - 1;
indxt = indx[l-1];
xval = x[indxt];
yval = y[indxt];
}
else
{
indxt = indx[ir-1];
xval = x[indxt];
yval = y[indxt];
indx[ir-1] = indx[0];
ir = ir - 1;
if ( ir == 1 )
{
indx[0] = indxt;
break;
}
}
i = l;
j = l + l;
while ( j <= ir )
{
if ( j < ir )
{
if ( x[indx[j-1]] < x[indx[j]] ||
( x[indx[j-1]] == x[indx[j]] && y[indx[j-1]] < y[indx[j]] ) )
{
j = j + 1;
}
}
if ( xval < x[indx[j-1]] ||
( xval == x[indx[j-1]] && yval < y[indx[j-1]] ) )
{
indx[i-1] = indx[j-1];
i = j;
j = j + j;
}
else
{
j = ir + 1;
}
}
indx[i-1] = indxt;
}
return indx;
}
//****************************************************************************80
void r8vec2_sorted_unique ( int n, double a1[], double a2[], int &unique_num )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_SORTED_UNIQUE keeps the unique elements in an R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// Item I is stored as the pair A1(I), A2(I).
//
// The items must have been sorted, or at least it must be the
// case that equal items are stored in adjacent vector locations.
//
// If the items were not sorted, then this routine will only
// replace a string of equal values by a single representative.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items.
//
// Input/output, double A1[N], A2[N].
// On input, the array of N items.
// On output, an array of UNIQUE_NUM unique items.
//
// Output, int &UNIQUE_NUM, the number of unique items.
//
{
int itest;
unique_num = 0;
if ( n <= 0 )
{
return;
}
unique_num = 1;
for ( itest = 1; itest < n; itest++ )
{
if ( a1[itest] != a1[unique_num-1] ||
a2[itest] != a2[unique_num-1] )
{
a1[unique_num] = a1[itest];
a2[unique_num] = a2[itest];
unique_num = unique_num + 1;
}
}
return;
}
//****************************************************************************80
void r8vec2_sorted_unique_index ( int n, double a1[], double a2[],
int &unique_num, int indx[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_SORTED_UNIQUE_INDEX indexes unique elements in a sorted R8VEC2.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// Item I is stored as the pair A1(I), A2(I).
//
// The items must have been sorted, or at least it should be the
// case that equal items are stored in adjacent vector locations.
//
// If the items are not sorted, then this routine will only
// replace a string of equal values by a single representative.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 16 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of items.
//
// Input/output, double A1[N], A2[N].
// On input, the array of N items.
// On output, an array of unique items.
//
// Output, int &UNIQUE_NUM, the number of unique items.
//
// Output, int INDX[N], contains in entries 1 through UNIQUE_NUM an index
// array of the unique items. To build new arrays with no repeated elements:
// B1(*) = A1(INDX(*))
//
{
int itest;
if ( n <= 0 )
{
unique_num = 0;
return;
}
i4vec_zeros ( n, indx );
unique_num = 1;
indx[0] = 1;
for ( itest = 2; itest <= n; itest++ )
{
if ( a1[itest-2] != a1[itest-1] || a2[itest-2] != a2[itest-1] )
{
unique_num = unique_num + 1;
indx[unique_num-1] = itest;
}
}
return;
}
//****************************************************************************80
int r8vec2_sum_max_index ( int n, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC2_SUM_MAX_INDEX returns the index of the maximum sum of two R8VEC's.
//
// Discussion:
//
// An R8VEC2 is a dataset consisting of N pairs of real values, stored
// as two separate vectors A1 and A2.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], B[N], two arrays whose sum
// is to be examined.
//
// Output, int R8VEC2_SUM_MAX_INDEX, the index of the largest entry in A+B.
//
{
int i;
double sum_max;
int sum_max_index;
if ( n <= 0 )
{
sum_max_index = -1;
}
else
{
sum_max_index = 1;
sum_max = a[0] + b[0];
for ( i = 2; i <= n; i++ )
{
if ( sum_max < a[i-1] + b[i-1] )
{
sum_max = a[i-1] + b[i-1];
sum_max_index = i;
}
}
}
return sum_max_index;
}
//****************************************************************************80
void r8vec3_print ( int n, double a1[], double a2[], double a3[], string title )
//****************************************************************************80
//
// Purpose:
//
// R8VEC3_PRINT prints a triple of real vectors.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 September 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of components of the vector.
//
// Input, double A1[N], double A2[N], double A3[N], the vectors
// to be printed.
//
// Input, string TITLE, a title.
//
{
int i;
cout << "\n";
cout << title << "\n";
cout << "\n";
for ( i = 0; i <= n - 1; i++ )
{
cout << setw(4) << i << ": "
<< setw(10) << a1[i] << " "
<< setw(10) << a2[i] << " "
<< setw(10) << a3[i] << "\n";
}
return;
}
//****************************************************************************80
double *roots_to_r8poly ( int n, double x[] )
//****************************************************************************80
//
// Purpose:
//
// ROOTS_TO_R8POLY converts polynomial roots to polynomial coefficients.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 December 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of roots specified.
//
// Input, double X[N], the roots.
//
// Output, double ROOTS_TO_R8POLY[N+1], the coefficients of the polynomial.
//
{
double *c;
int i;
int j;
c = r8vec_zeros_new ( n + 1 );
//
// Initialize C to (0, 0, ..., 0, 1).
// Essentially, we are setting up a divided difference table.
//
c[n] = 1.0;
//
// Convert to standard polynomial form by shifting the abscissas
// of the divided difference table to 0.
//
for ( j = 1; j <= n; j++ )
{
for ( i = 1; i <= n+1-j; i++ )
{
c[n-i] = c[n-i] - x[n+1-i-j] * c[n-i+1];
}
}
return c;
}
//****************************************************************************80
int s_len_trim ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_LEN_TRIM returns the length of a string to the last nonblank.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, a string.
//
// Output, int S_LEN_TRIM, the length of the string to the last nonblank.
// If S_LEN_TRIM is 0, then the string is entirely blank.
//
{
int n;
n = s.length ( );
while ( 0 < n )
{
if ( s[n-1] != ' ' )
{
return n;
}
n = n - 1;
}
return n;
}
//****************************************************************************80
void sort_heap_external ( int n, int &indx, int &i, int &j, int isgn )
//****************************************************************************80
//
// Purpose:
//
// SORT_HEAP_EXTERNAL externally sorts a list of items into ascending order.
//
// Discussion:
//
// The actual list is not passed to the routine. Hence it may
// consist of integers, reals, numbers, names, etc. The user,
// after each return from the routine, will be asked to compare or
// interchange two items.
//
// The current version of this code mimics the FORTRAN version,
// so the values of I and J, in particular, are FORTRAN indices.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 January 2013
//
// Author:
//
// Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.
// C++ version by John Burkardt
//
// Reference:
//
// Albert Nijenhuis, Herbert Wilf,
// Combinatorial Algorithms,
// Academic Press, 1978, second edition,
// ISBN 0-12-519260-6.
//
// Parameters:
//
// Input, int N, the length of the input list.
//
// Input/output, int &INDX.
// The user must set INDX to 0 before the first call.
// On return,
// if INDX is greater than 0, the user must interchange
// items I and J and recall the routine.
// If INDX is less than 0, the user is to compare items I
// and J and return in ISGN a negative value if I is to
// precede J, and a positive value otherwise.
// If INDX is 0, the sorting is done.
//
// Output, int &I, &J. On return with INDX positive,
// elements I and J of the user's list should be
// interchanged. On return with INDX negative, elements I
// and J are to be compared by the user.
//
// Input, int ISGN. On return with INDX negative, the
// user should compare elements I and J of the list. If
// item I is to precede item J, set ISGN negative,
// otherwise set ISGN positive.
//
{
static int i_save = 0;
static int j_save = 0;
static int k = 0;
static int k1 = 0;
static int n1 = 0;
//
// INDX = 0: This is the first call.
//
if ( indx == 0 )
{
i_save = 0;
j_save = 0;
k = n / 2;
k1 = k;
n1 = n;
}
//
// INDX < 0: The user is returning the results of a comparison.
//
else if ( indx < 0 )
{
if ( indx == -2 )
{
if ( isgn < 0 )
{
i_save = i_save + 1;
}
j_save = k1;
k1 = i_save;
indx = -1;
i = i_save;
j = j_save;
return;
}
if ( 0 < isgn )
{
indx = 2;
i = i_save;
j = j_save;
return;
}
if ( k <= 1 )
{
if ( n1 == 1 )
{
i_save = 0;
j_save = 0;
indx = 0;
}
else
{
i_save = n1;
j_save = 1;
n1 = n1 - 1;
indx = 1;
}
i = i_save;
j = j_save;
return;
}
k = k - 1;
k1 = k;
}
//
// 0 < INDX: the user was asked to make an interchange.
//
else if ( indx == 1 )
{
k1 = k;
}
for ( ; ; )
{
i_save = 2 * k1;
if ( i_save == n1 )
{
j_save = k1;
k1 = i_save;
indx = -1;
i = i_save;
j = j_save;
return;
}
else if ( i_save <= n1 )
{
j_save = i_save + 1;
indx = -2;
i = i_save;
j = j_save;
return;
}
if ( k <= 1 )
{
break;
}
k = k - 1;
k1 = k;
}
if ( n1 == 1 )
{
i_save = 0;
j_save = 0;
indx = 0;
i = i_save;
j = j_save;
}
else
{
i_save = n1;
j_save = 1;
n1 = n1 - 1;
indx = 1;
i = i_save;
j = j_save;
}
return;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct std::tm *tm_ptr;
size_t len;
std::time_t now;
now = std::time ( NULL );
tm_ptr = std::localtime ( &now );
len = std::strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm_ptr );
std::cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
| 20.018767 | 92 | 0.468755 | [
"mesh",
"object",
"vector",
"model",
"transform",
"3d"
] |
4fae26879d17e55681283e8650717a4bb4c4abfb | 11,135 | cpp | C++ | dali-toolkit/internal/visuals/color/color-visual.cpp | Coquinho/dali-toolkit | 8fea8f2ae64923690519e0de039ce4af51271d9f | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | dali-toolkit/internal/visuals/color/color-visual.cpp | Coquinho/dali-toolkit | 8fea8f2ae64923690519e0de039ce4af51271d9f | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-10-19T15:47:43.000Z | 2020-10-19T15:47:43.000Z | dali-toolkit/internal/visuals/color/color-visual.cpp | expertisesolutions/dali-toolkit | eac3e6ee30183868f1af12addd94e7f2fc467ed7 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include "color-visual.h"
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
//INTERNAL INCLUDES
#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/visuals/color-visual-properties-devel.h>
#include <dali-toolkit/devel-api/visuals/color-visual-actions-devel.h>
#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
namespace Dali
{
namespace Toolkit
{
namespace Internal
{
namespace
{
const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
attribute mediump vec2 aPosition;\n
uniform highp mat4 uMvpMatrix;\n
uniform highp vec3 uSize;\n
\n
//Visual size and offset
uniform mediump vec2 offset;\n
uniform highp vec2 size;\n
uniform mediump vec4 offsetSizeMode;\n
uniform mediump vec2 origin;\n
uniform mediump vec2 anchorPoint;\n
uniform mediump vec2 extraSize;\n
vec4 ComputeVertexPosition()\n
{\n
vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
return vec4( (aPosition + anchorPoint)*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
}\n
void main()\n
{\n
gl_Position = uMvpMatrix * ComputeVertexPosition();\n
}\n
);
const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
uniform lowp vec4 uColor;\n
uniform lowp vec3 mixColor;\n
\n
void main()\n
{\n
gl_FragColor = vec4(mixColor, 1.0)*uColor;\n
}\n
);
const char* VERTEX_SHADER_ROUNDED_CORNER = DALI_COMPOSE_SHADER(
attribute mediump vec2 aPosition;\n
uniform highp mat4 uMvpMatrix;\n
uniform highp vec3 uSize;\n
varying mediump vec2 vPosition;\n
varying mediump vec2 vRectSize;\n
varying mediump float vCornerRadius;\n
\n
//Visual size and offset
uniform mediump vec2 offset;\n
uniform highp vec2 size;\n
uniform mediump vec2 extraSize;\n
uniform mediump vec4 offsetSizeMode;\n
uniform mediump vec2 origin;\n
uniform mediump vec2 anchorPoint;\n
uniform mediump float cornerRadius;\n
uniform mediump float cornerRadiusPolicy;\n
\n
vec4 ComputeVertexPosition()\n
{\n
vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
mediump float minSize = min( visualSize.x, visualSize.y );\n
vCornerRadius = mix( cornerRadius * minSize, cornerRadius, cornerRadiusPolicy);\n
vCornerRadius = min( vCornerRadius, minSize * 0.5 );\n
vRectSize = visualSize / 2.0 - vCornerRadius;\n
vPosition = aPosition* visualSize;\n
return vec4( vPosition + anchorPoint*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
}\n
\n
void main()\n
{\n
gl_Position = uMvpMatrix * ComputeVertexPosition();\n
}\n
);
//float distance = length( max( abs( position - center ), size ) - size ) - radius;
const char* FRAGMENT_SHADER_ROUNDED_CORNER = DALI_COMPOSE_SHADER(
varying mediump vec2 vPosition;\n
varying mediump vec2 vRectSize;\n
varying mediump float vCornerRadius;\n
uniform lowp vec4 uColor;\n
uniform lowp vec3 mixColor;\n
\n
void main()\n
{\n
mediump float dist = length( max( abs( vPosition ), vRectSize ) - vRectSize ) - vCornerRadius;\n
gl_FragColor = uColor * vec4( mixColor, 1.0 );\n
gl_FragColor.a *= 1.0 - smoothstep( -1.0, 1.0, dist );\n
}\n
);
const char* VERTEX_SHADER_BLUR_EDGE = DALI_COMPOSE_SHADER(
attribute mediump vec2 aPosition;\n
uniform highp mat4 uMvpMatrix;\n
uniform highp vec3 uSize;\n
varying mediump vec2 vPosition;\n
varying mediump vec2 vRectSize;\n
\n
//Visual size and offset
uniform mediump vec2 offset;\n
uniform highp vec2 size;\n
uniform mediump vec2 extraSize;\n
uniform mediump vec4 offsetSizeMode;\n
uniform mediump vec2 origin;\n
uniform mediump vec2 anchorPoint;\n
uniform mediump float blurRadius;\n
\n
vec4 ComputeVertexPosition()\n
{\n
vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize + blurRadius * 2.0;\n
vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
vRectSize = visualSize / 2.0;\n
vPosition = aPosition* visualSize;\n
return vec4( vPosition + anchorPoint*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
}\n
\n
void main()\n
{\n
gl_Position = uMvpMatrix * ComputeVertexPosition();\n
}\n
);
const char* FRAGMENT_SHADER_BLUR_EDGE = DALI_COMPOSE_SHADER(
varying mediump vec2 vPosition;\n
varying mediump vec2 vRectSize;\n
uniform lowp vec4 uColor;\n
uniform lowp vec3 mixColor;\n
uniform mediump float blurRadius;\n
\n
void main()\n
{\n
mediump vec2 blur = 1.0 - smoothstep( vRectSize - blurRadius * 2.0, vRectSize, abs( vPosition ) );\n
gl_FragColor = uColor * vec4( mixColor, 1.0 );\n
gl_FragColor.a *= blur.x * blur.y;\n
}\n
);
}
ColorVisualPtr ColorVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
{
ColorVisualPtr colorVisualPtr( new ColorVisual( factoryCache ) );
colorVisualPtr->SetProperties( properties );
return colorVisualPtr;
}
ColorVisual::ColorVisual( VisualFactoryCache& factoryCache )
: Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::COLOR ),
mBlurRadius( 0.0f ),
mRenderIfTransparent( false )
{
}
ColorVisual::~ColorVisual()
{
}
void ColorVisual::DoSetProperties( const Property::Map& propertyMap )
{
// By virtue of DoSetProperties being called last, this will override
// anything set by Toolkit::Visual::Property::MIX_COLOR
Property::Value* colorValue = propertyMap.Find( Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR );
if( colorValue )
{
Vector4 color;
if( colorValue->Get( color ) )
{
Property::Type type = colorValue->GetType();
if( type == Property::VECTOR4 )
{
SetMixColor( color );
}
else if( type == Property::VECTOR3 )
{
Vector3 color3(color);
SetMixColor( color3 );
}
}
else
{
DALI_LOG_ERROR("ColorVisual: mixColor property has incorrect type\n");
}
}
Property::Value* renderIfTransparentValue = propertyMap.Find( Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, RENDER_IF_TRANSPARENT_NAME );
if( renderIfTransparentValue )
{
if( ! renderIfTransparentValue->Get( mRenderIfTransparent ) )
{
DALI_LOG_ERROR( "ColorVisual: renderIfTransparent property has incorrect type: %d\n", renderIfTransparentValue->GetType() );
}
}
Property::Value* blurRadiusValue = propertyMap.Find( Toolkit::DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME );
if( blurRadiusValue )
{
if( !blurRadiusValue->Get( mBlurRadius ) )
{
DALI_LOG_ERROR( "ColorVisual:DoSetProperties:: BLUR_RADIUS property has incorrect type: %d\n", blurRadiusValue->GetType() );
}
}
}
void ColorVisual::DoSetOnScene( Actor& actor )
{
InitializeRenderer();
// Only add the renderer if it's not fully transparent
// We cannot avoid creating a renderer as it's used in the base class
if( mRenderIfTransparent || mImpl->mMixColor.a > 0.0f )
{
actor.AddRenderer( mImpl->mRenderer );
}
// Color Visual generated and ready to display
ResourceReady( Toolkit::Visual::ResourceStatus::READY );
}
void ColorVisual::DoCreatePropertyMap( Property::Map& map ) const
{
map.Clear();
map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR );
map.Insert( Toolkit::ColorVisual::Property::MIX_COLOR, mImpl->mMixColor );
map.Insert( Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, mRenderIfTransparent );
map.Insert( Toolkit::DevelColorVisual::Property::BLUR_RADIUS, mBlurRadius );
}
void ColorVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
{
// Do nothing
}
void ColorVisual::OnSetTransform()
{
if( mImpl->mRenderer )
{
mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
}
}
void ColorVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes )
{
// Check if action is valid for this visual type and perform action if possible
switch( actionId )
{
case DevelColorVisual::Action::UPDATE_PROPERTY:
{
const Property::Map* map = attributes.GetMap();
if( map )
{
DoSetProperties( *map );
}
break;
}
}
}
void ColorVisual::InitializeRenderer()
{
Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
Shader shader;
if( !EqualsZero( mBlurRadius ) )
{
shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER_BLUR_EDGE );
if( !shader )
{
shader = Shader::New( VERTEX_SHADER_BLUR_EDGE, FRAGMENT_SHADER_BLUR_EDGE );
mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER_BLUR_EDGE, shader );
}
}
else if( !IsRoundedCornerRequired() )
{
shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER );
if( !shader )
{
shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER, shader );
}
}
else
{
shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER );
if( !shader )
{
shader = Shader::New( VERTEX_SHADER_ROUNDED_CORNER, FRAGMENT_SHADER_ROUNDED_CORNER );
mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER, shader );
}
}
mImpl->mRenderer = Renderer::New( geometry, shader );
// ColorVisual has it's own index key for mix color - use this instead
// of using the new base index to avoid changing existing applications
// String keys will get to this property.
mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty( Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR, Vector3(mImpl->mMixColor) );
mImpl->mRenderer.RegisterProperty( BLUR_RADIUS_NAME, mBlurRadius );
if( mImpl->mMixColor.a < 1.f || !EqualsZero( mBlurRadius ) )
{
mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
}
// Register transform properties
mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
}
} // namespace Internal
} // namespace Toolkit
} // namespace Dali
| 31.103352 | 153 | 0.715132 | [
"geometry",
"transform"
] |
4faf1391cd8db44b24e53b3c4a3404050ea271c3 | 2,200 | hpp | C++ | src/image_management/lib/mesh/format/mesh_io_obj.hpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | src/image_management/lib/mesh/format/mesh_io_obj.hpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | src/image_management/lib/mesh/format/mesh_io_obj.hpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | /*
** TP CPE Lyon
** Copyright (C) 2015 Damien Rohmer
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef MESH_IO_OBJ_HPP
#define MESH_IO_OBJ_HPP
#include <vector>
#include "../../3d/vec3.hpp"
#include "../../3d/vec2.hpp"
namespace cpe
{
class mesh;
/** Load a mesh structure from a OFF file */
mesh load_mesh_file_obj(std::string const& filename);
/** An obj structure following the definition of an obj file */
struct obj_structure
{
std::vector<vec3> data_vertex; //the coordinates of vertices
std::vector<vec2> data_texture; //the coordinates of textures (optional)
std::vector<vec3> data_normal; //the coordinates of normals (optional)
std::vector<std::vector<int>> data_face_vertex; //the indices of the polygon of vertices
std::vector<std::vector<int>> data_face_texture; //the indices of the polygon of texture (optional)
std::vector<std::vector<int>> data_face_normal; //the indices of the polygon of normal (optional)
};
/** Split a given string of face f from obj style into a set of values.
*
* ex. 1/2 4/5 7/8 -> 1 2 4 5 7 8
* 1/2/3 4/4/1 4/7/8 -> 1 2 3 4 4 1 4 7 8
* 1//3 4//1 7//9 -> 1 3 4 1 7 9
* 4 7 8 4 -> 4 7 8 4
*
*/
std::vector<int> split_face_data(std::string const& face_data_str);
/** Read an obj file and return an obj structure. */
obj_structure load_file_obj_structure(std::string const& filename);
void read_vertex_obj(std::stringstream& tokens,obj_structure& obj);
void read_texture_obj(std::stringstream& tokens,obj_structure& obj);
}
#endif
| 31.428571 | 103 | 0.695455 | [
"mesh",
"vector",
"3d"
] |
4fb18e438c0f81f6498bfeca652086dc38a1f83d | 3,714 | cpp | C++ | Code/Editor/Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Editor/Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Editor/Controls/ReflectedPropertyControl/PropertyAnimationCtrl.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 "EditorDefs.h"
#include "PropertyAnimationCtrl.h"
// Qt
#include <QHBoxLayout>
#include <QLabel>
#include <QToolButton>
// Editor
#include "Util/UIEnumerations.h"
#include "IResourceSelectorHost.h"
AnimationPropertyCtrl::AnimationPropertyCtrl(QWidget *pParent)
: QWidget(pParent)
{
m_animationLabel = new QLabel;
m_pApplyButton = new QToolButton;
m_pApplyButton->setIcon(QIcon(":/reflectedPropertyCtrl/img/apply.png"));
m_pApplyButton->setFocusPolicy(Qt::StrongFocus);
QHBoxLayout *pLayout = new QHBoxLayout(this);
pLayout->setContentsMargins(0, 0, 0, 0);
pLayout->addWidget(m_animationLabel, 1);
pLayout->addWidget(m_pApplyButton);
connect(m_pApplyButton, &QAbstractButton::clicked, this, &AnimationPropertyCtrl::OnApplyClicked);
};
AnimationPropertyCtrl::~AnimationPropertyCtrl()
{
}
void AnimationPropertyCtrl::SetValue(const CReflectedVarAnimation &animation)
{
m_animation = animation;
m_animationLabel->setText(animation.m_animation.c_str());
}
CReflectedVarAnimation AnimationPropertyCtrl::value() const
{
return m_animation;
}
void AnimationPropertyCtrl::OnApplyClicked()
{
QStringList cSelectedAnimations;
int nTotalAnimations(0);
int nCurrentAnimation(0);
QString combinedString = GetIEditor()->GetResourceSelectorHost()->GetGlobalSelection("animation");
SplitString(combinedString, cSelectedAnimations, ',');
nTotalAnimations = cSelectedAnimations.size();
for (nCurrentAnimation = 0; nCurrentAnimation < nTotalAnimations; ++nCurrentAnimation)
{
QString& rstrCurrentAnimAction = cSelectedAnimations[nCurrentAnimation];
if (!rstrCurrentAnimAction.isEmpty())
{
m_animation.m_animation = rstrCurrentAnimAction.toUtf8().data();
m_animationLabel->setText(m_animation.m_animation.c_str());
emit ValueChanged(m_animation);
}
}
}
QWidget* AnimationPropertyCtrl::GetFirstInTabOrder()
{
return m_pApplyButton;
}
QWidget* AnimationPropertyCtrl::GetLastInTabOrder()
{
return m_pApplyButton;
}
void AnimationPropertyCtrl::UpdateTabOrder()
{
setTabOrder(m_pApplyButton, m_pApplyButton);
}
QWidget* AnimationPropertyWidgetHandler::CreateGUI(QWidget *pParent)
{
AnimationPropertyCtrl* newCtrl = aznew AnimationPropertyCtrl(pParent);
connect(newCtrl, &AnimationPropertyCtrl::ValueChanged, newCtrl, [newCtrl]()
{
EBUS_EVENT(AzToolsFramework::PropertyEditorGUIMessages::Bus, RequestWrite, newCtrl);
});
return newCtrl;
}
void AnimationPropertyWidgetHandler::ConsumeAttribute(AnimationPropertyCtrl* GUI, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue, const char* debugName)
{
Q_UNUSED(GUI);
Q_UNUSED(attrib);
Q_UNUSED(attrValue);
Q_UNUSED(debugName);
}
void AnimationPropertyWidgetHandler::WriteGUIValuesIntoProperty(size_t index, AnimationPropertyCtrl* GUI, property_t& instance, AzToolsFramework::InstanceDataNode* node)
{
Q_UNUSED(index);
Q_UNUSED(node);
CReflectedVarAnimation val = GUI->value();
instance = static_cast<property_t>(val);
}
bool AnimationPropertyWidgetHandler::ReadValuesIntoGUI(size_t index, AnimationPropertyCtrl* GUI, const property_t& instance, AzToolsFramework::InstanceDataNode* node)
{
Q_UNUSED(index);
Q_UNUSED(node);
CReflectedVarAnimation val = instance;
GUI->SetValue(val);
return false;
}
#include <Controls/ReflectedPropertyControl/moc_PropertyAnimationCtrl.cpp>
| 28.136364 | 174 | 0.751481 | [
"3d"
] |
4fb55832ddc3f1abcffb5fed0968a76b2e3b4a49 | 15,713 | hpp | C++ | driver/support_library/src/cascading/CascadingCompilerUtils.hpp | ARM-software/npu-driver-stack | 1e6b00b21ed4cf39b2df625fa242c6f67c05b19f | [
"Apache-2.0"
] | 4 | 2019-05-31T18:48:24.000Z | 2019-06-04T07:59:39.000Z | driver/support_library/src/cascading/CascadingCompilerUtils.hpp | ARM-software/npu-driver-stack | 1e6b00b21ed4cf39b2df625fa242c6f67c05b19f | [
"Apache-2.0"
] | null | null | null | driver/support_library/src/cascading/CascadingCompilerUtils.hpp | ARM-software/npu-driver-stack | 1e6b00b21ed4cf39b2df625fa242c6f67c05b19f | [
"Apache-2.0"
] | null | null | null | //
// Copyright © 2022 Arm Limited.
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "Plan.hpp"
#include "Utils.hpp"
#define ETHOSN_ASSERT_MSG(cond, msg) assert(cond)
#include "ethosn_utils/NumericCast.hpp"
using namespace ethosn::command_stream::cascading;
namespace ethosn
{
namespace support_library
{
namespace cascading_compiler
{
namespace CommonUtils
{
inline void SetTileInfoForBuffer(const HardwareCapabilities& hwCap, Tile& tile, const Buffer* const buffer)
{
assert(buffer->m_Format == CascadingBufferFormat::NHWCB || buffer->m_Format == CascadingBufferFormat::WEIGHT);
tile.baseAddr = ethosn::utils::NumericCast<uint16_t>(buffer->m_Offset.value());
tile.numSlots = ethosn::utils::NumericCast<uint16_t>(buffer->m_NumStripes);
switch (buffer->m_Format)
{
case CascadingBufferFormat::NHWCB:
tile.slotSize = ethosn::utils::NumericCast<uint16_t>(
utils::DivRoundUp(utils::TotalSizeBytesNHWCB(buffer->m_StripeShape), hwCap.GetNumberOfSrams()));
break;
case CascadingBufferFormat::WEIGHT:
tile.slotSize = ethosn::utils::NumericCast<uint16_t>(
utils::DivRoundUp(buffer->m_SizeInBytes, (hwCap.GetNumberOfSrams() * buffer->m_NumStripes)));
break;
default:
assert(false);
}
}
uint32_t CalculateBufferSize(const TensorShape& shape, CascadingBufferFormat dataFormat)
{
assert(dataFormat == CascadingBufferFormat::NHWC || dataFormat == CascadingBufferFormat::NCHW ||
dataFormat == CascadingBufferFormat::NHWCB || dataFormat == CascadingBufferFormat::FCAF_WIDE ||
dataFormat == CascadingBufferFormat::FCAF_DEEP);
switch (dataFormat)
{
case CascadingBufferFormat::FCAF_DEEP:
return ethosn::support_library::utils::TotalSizeBytesFCAFDeep(shape);
case CascadingBufferFormat::FCAF_WIDE:
return ethosn::support_library::utils::TotalSizeBytesFCAFWide(shape);
case CascadingBufferFormat::NHWCB:
return ethosn::support_library::utils::TotalSizeBytesNHWCB(shape);
default:
return ethosn::support_library::utils::TotalSizeBytes(shape);
}
}
} // namespace CommonUtils
namespace StreamersUtils
{
inline void SetBufferDataType(FmSData& streamerData, const CascadingBufferFormat bufferFormat)
{
switch (bufferFormat)
{
case CascadingBufferFormat::NHWC:
streamerData.dataType = FmsDataType::NHWC;
break;
case CascadingBufferFormat::NHWCB:
streamerData.dataType = FmsDataType::NHWCB;
break;
case CascadingBufferFormat::FCAF_DEEP:
streamerData.dataType = FmsDataType::FCAF_DEEP;
break;
case CascadingBufferFormat::FCAF_WIDE:
streamerData.dataType = FmsDataType::FCAF_WIDE;
break;
default:
assert(false);
}
}
inline void SetStripeHeightInfo(FmSData& streamerData, const TensorShape& tensorShape, const TensorShape& stripeShape)
{
uint16_t tensorHeight = ethosn::utils::NumericCast<uint16_t>(utils::GetHeight(tensorShape));
uint16_t stripeHeight = ethosn::utils::NumericCast<uint16_t>(utils::GetHeight(stripeShape));
assert(stripeHeight != 0);
streamerData.numStripes.height =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesH(tensorShape, stripeShape));
streamerData.dfltStripeSize.height = stripeHeight;
streamerData.edgeStripeSize.height = stripeHeight;
uint16_t remainingHeight = tensorHeight % stripeHeight;
if (remainingHeight != 0)
{
streamerData.edgeStripeSize.height = remainingHeight;
}
}
inline void SetStripeWidthInfo(FmSData& streamerData, const TensorShape& tensorShape, const TensorShape& stripeShape)
{
uint16_t tensorWidth = ethosn::utils::NumericCast<uint16_t>(utils::GetWidth(tensorShape));
uint16_t stripeWidth = ethosn::utils::NumericCast<uint16_t>(utils::GetWidth(stripeShape));
assert(stripeWidth != 0);
streamerData.numStripes.width =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesW(tensorShape, stripeShape));
streamerData.dfltStripeSize.width = stripeWidth;
streamerData.edgeStripeSize.width = stripeWidth;
uint16_t remainingWidth = tensorWidth % stripeWidth;
if (remainingWidth != 0)
{
streamerData.edgeStripeSize.width = remainingWidth;
}
}
inline void SetStripeChannelsInfo(FmSData& streamerData, const TensorShape& tensorShape, const TensorShape& stripeShape)
{
uint16_t tensorChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(tensorShape));
uint16_t stripeChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(stripeShape));
assert(stripeChannels != 0);
streamerData.numStripes.channels =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesC(tensorShape, stripeShape));
streamerData.dfltStripeSize.channels = stripeChannels;
streamerData.edgeStripeSize.channels = stripeChannels;
uint16_t remainingChannels = tensorChannels % stripeChannels;
if (remainingChannels != 0)
{
streamerData.edgeStripeSize.channels = remainingChannels;
}
}
inline void SetSuperTensorSizeInCells(FmSData& streamerData,
const TensorShape& tensorShape,
const CascadingBufferFormat bufferFormat)
{
uint16_t cellWidth = 0;
uint16_t cellDepth = 0;
switch (bufferFormat)
{
case CascadingBufferFormat::NHWC:
cellWidth = 1;
cellDepth = 1;
break;
case CascadingBufferFormat::NHWCB:
cellWidth = 8;
cellDepth = 16;
break;
case CascadingBufferFormat::FCAF_DEEP:
cellWidth = 8;
cellDepth = 32;
break;
case CascadingBufferFormat::FCAF_WIDE:
cellWidth = 16;
cellDepth = 16;
break;
default:
assert(false);
}
streamerData.supertensorSizeInCells.width =
ethosn::utils::NumericCast<uint16_t>(utils::DivRoundUp(tensorShape[2], cellWidth));
streamerData.supertensorSizeInCells.channels =
ethosn::utils::NumericCast<uint16_t>(utils::DivRoundUp(tensorShape[3], cellDepth));
}
inline void SetStripeIdStrides(FmSData& streamerData, TraversalOrder traversalOrder)
{
if (traversalOrder == TraversalOrder::Xyz)
{
streamerData.stripeIdStrides.height =
ethosn::utils::NumericCast<uint16_t>(streamerData.numStripes.width * streamerData.numStripes.channels);
streamerData.stripeIdStrides.width = streamerData.numStripes.channels;
streamerData.stripeIdStrides.channels = 1U;
}
else
{
assert(false);
}
}
} // namespace StreamersUtils
namespace MceSUtils
{
inline void
SetMcesOfmHeightStripeInfo(MceS& mceSchedulerData, const TensorShape& ofmShape, const TensorShape& ofmStripeShape)
{
uint16_t ofmHeight = ethosn::utils::NumericCast<uint16_t>(utils::GetHeight(ofmShape));
uint16_t ofmStripeHeight = ethosn::utils::NumericCast<uint16_t>(utils::GetHeight(ofmStripeShape));
assert(ofmStripeHeight != 0);
mceSchedulerData.numStripes.ofmHeight =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesH(ofmShape, ofmStripeShape));
mceSchedulerData.dfltStripeSize.ofmHeight = ofmStripeHeight;
mceSchedulerData.edgeStripeSize.ofmHeight = ofmStripeHeight;
uint16_t remainingHeight = ofmHeight % ofmStripeHeight;
if (remainingHeight != 0)
{
mceSchedulerData.edgeStripeSize.ofmHeight = remainingHeight;
}
}
inline void
SetMcesOfmWidthStripeInfo(MceS& mceSchedulerData, const TensorShape& ofmShape, const TensorShape& ofmStripeShape)
{
uint16_t ofmWidth = ethosn::utils::NumericCast<uint16_t>(utils::GetWidth(ofmShape));
uint16_t ofmStripeWidth = ethosn::utils::NumericCast<uint16_t>(utils::GetWidth(ofmStripeShape));
assert(ofmStripeWidth != 0);
mceSchedulerData.numStripes.ofmWidth =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesW(ofmShape, ofmStripeShape));
mceSchedulerData.dfltStripeSize.ofmWidth = ofmStripeWidth;
mceSchedulerData.edgeStripeSize.ofmWidth = ofmStripeWidth;
uint16_t remainingWidth = ofmWidth % ofmStripeWidth;
if (remainingWidth != 0)
{
mceSchedulerData.edgeStripeSize.ofmWidth = remainingWidth;
}
}
inline void
SetMcesOfmChannelsStripeInfo(MceS& mceSchedulerData, const TensorShape& ofmShape, const TensorShape& ofmStripeShape)
{
uint16_t ofmChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(ofmShape));
uint16_t ofmStripeChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(ofmStripeShape));
assert(ofmStripeChannels != 0);
mceSchedulerData.numStripes.ofmChannels =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesC(ofmShape, ofmStripeShape));
mceSchedulerData.dfltStripeSize.ofmChannels = ofmStripeChannels;
mceSchedulerData.edgeStripeSize.ofmChannels = ofmStripeChannels;
uint16_t remainingChannels = ofmChannels % ofmStripeChannels;
if (remainingChannels != 0)
{
mceSchedulerData.edgeStripeSize.ofmChannels = remainingChannels;
}
}
inline void
SetMcesIfmChannelsStripeInfo(MceS& mceSchedulerData, const TensorShape& ifmShape, const TensorShape& ifmStripeShape)
{
uint16_t ifmChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(ifmShape));
uint16_t ifmStripeChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(ifmStripeShape));
assert(ifmStripeChannels != 0);
mceSchedulerData.numStripes.ifmChannels =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesC(ifmShape, ifmStripeShape));
mceSchedulerData.dfltStripeSize.ifmChannels = ifmStripeChannels;
mceSchedulerData.edgeStripeSize.ifmChannels = ifmStripeChannels;
uint16_t remainingChannels = ifmChannels % ifmStripeChannels;
if (remainingChannels != 0)
{
mceSchedulerData.edgeStripeSize.ifmChannels = remainingChannels;
}
}
inline void SetStripeIdStrides(MceS& mceSchedulerData, TraversalOrder traversalOrder)
{
if (traversalOrder == TraversalOrder::Xyz)
{
mceSchedulerData.stripeIdStrides.ofmHeight = ethosn::utils::NumericCast<uint16_t>(
mceSchedulerData.numStripes.ifmChannels * mceSchedulerData.numStripes.ofmWidth);
mceSchedulerData.stripeIdStrides.ofmWidth = mceSchedulerData.numStripes.ifmChannels;
mceSchedulerData.stripeIdStrides.ofmChannels = ethosn::utils::NumericCast<uint16_t>(
mceSchedulerData.numStripes.ifmChannels * mceSchedulerData.numStripes.ofmWidth *
mceSchedulerData.numStripes.ofmHeight);
mceSchedulerData.stripeIdStrides.ifmChannels = 1U;
}
else
{
assert(false);
}
}
inline void setMcesOpMode(MceS& mceSchedulerData, command_stream::MceOperation operationMode)
{
if (operationMode == command_stream::MceOperation::CONVOLUTION)
{
mceSchedulerData.mceOpMode = MceOperation::CONVOLUTION;
}
else if (operationMode == command_stream::MceOperation::DEPTHWISE_CONVOLUTION)
{
mceSchedulerData.mceOpMode = MceOperation::DEPTHWISE_CONVOLUTION;
}
else if (operationMode == command_stream::MceOperation::FULLY_CONNECTED)
{
mceSchedulerData.mceOpMode = MceOperation::FULLY_CONNECTED;
}
else
{
assert(false);
}
}
inline void setMcesAlgorithm(MceS& mceSchedulerData, CompilerMceAlgorithm algorithm)
{
if (algorithm == CompilerMceAlgorithm::Direct)
{
mceSchedulerData.algorithm = MceAlgorithm::DIRECT;
}
else if (algorithm == CompilerMceAlgorithm::Winograd)
{
mceSchedulerData.algorithm = MceAlgorithm::WINOGRAD;
}
else
{
assert(false);
}
}
} // namespace MceSUtils
namespace PleSUtils
{
inline void
SetPlesHeightStripeInfo(PleS& pleSchedulerData, const TensorShape& ofmShape, const TensorShape& ofmStripeShape)
{
uint16_t ofmHeight = ethosn::utils::NumericCast<uint16_t>(utils::GetHeight(ofmShape));
uint16_t ofmStripeHeight = ethosn::utils::NumericCast<uint16_t>(utils::GetHeight(ofmStripeShape));
pleSchedulerData.dfltStripeSize.height = ofmStripeHeight;
pleSchedulerData.numStripes.height =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesH(ofmShape, ofmStripeShape));
pleSchedulerData.edgeStripeSize.height = ofmStripeHeight;
uint16_t remainingHeight = ofmHeight % ofmStripeHeight;
if (remainingHeight != 0)
{
pleSchedulerData.edgeStripeSize.height = remainingHeight;
}
}
inline void
SetPlesWidthStripeInfo(PleS& pleSchedulerData, const TensorShape& ofmShape, const TensorShape& ofmStripeShape)
{
uint16_t ofmWidth = ethosn::utils::NumericCast<uint16_t>(utils::GetWidth(ofmShape));
uint16_t ofmStripeWidth = ethosn::utils::NumericCast<uint16_t>(utils::GetWidth(ofmStripeShape));
pleSchedulerData.dfltStripeSize.width = ofmStripeWidth;
pleSchedulerData.numStripes.width =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesW(ofmShape, ofmStripeShape));
pleSchedulerData.edgeStripeSize.width = ofmStripeWidth;
uint16_t remainingWidth = ofmWidth % ofmStripeWidth;
if (remainingWidth != 0)
{
pleSchedulerData.edgeStripeSize.width = remainingWidth;
}
}
inline void
SetPlesChannelsStripeInfo(PleS& pleSchedulerData, const TensorShape& ofmShape, const TensorShape& ofmStripeShape)
{
uint16_t ofmChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(ofmShape));
uint16_t ofmStripeChannels = ethosn::utils::NumericCast<uint16_t>(utils::GetChannels(ofmStripeShape));
pleSchedulerData.dfltStripeSize.channels = ofmStripeChannels;
pleSchedulerData.numStripes.channels =
ethosn::utils::NumericCast<uint16_t>(utils::GetNumStripesC(ofmShape, ofmStripeShape));
pleSchedulerData.edgeStripeSize.channels = ofmStripeChannels;
uint16_t remainingChannels = ofmChannels % ofmStripeChannels;
if (remainingChannels != 0)
{
pleSchedulerData.edgeStripeSize.channels = remainingChannels;
}
}
inline void SetStripeIdStrides(PleS& pleSchedulerData, Buffer* outputBuffer)
{
if (outputBuffer->m_Order == TraversalOrder::Xyz)
{
pleSchedulerData.stripeIdStrides.height =
ethosn::utils::NumericCast<uint16_t>(pleSchedulerData.numStripes.width);
pleSchedulerData.stripeIdStrides.width = 1;
pleSchedulerData.stripeIdStrides.channels = ethosn::utils::NumericCast<uint16_t>(
pleSchedulerData.numStripes.width * pleSchedulerData.numStripes.height);
}
else
{
assert(false);
}
}
inline void SetFusedPleSInputMode(PleS& pleSchedulerData, MceOp* pleOpProducer)
{
// Calculate input mode of Ple OP dependent on input buffer producer.
switch (pleOpProducer->m_Op)
{
case command_stream::MceOperation::CONVOLUTION:
pleSchedulerData.inputMode = PleInputMode::MCE_ALL_OGS;
break;
case command_stream::MceOperation::DEPTHWISE_CONVOLUTION:
pleSchedulerData.inputMode = PleInputMode::MCE_ONE_OG;
break;
case command_stream::MceOperation::FULLY_CONNECTED:
pleSchedulerData.inputMode = PleInputMode::MCE_ALL_OGS;
break;
default:
assert(false);
}
}
} // namespace PleSUtils
} // namespace cascading_compiler
} // namespace support_library
} // namespace ethosn
| 34.30786 | 120 | 0.715331 | [
"shape"
] |
4fb57988e3865b69786a460f596b47b4bef67208 | 33,588 | cpp | C++ | src/client/mapview.cpp | nekiro/otclient | 4aba78bf7304346038739b62f2016e714392c57a | [
"MIT"
] | 1 | 2022-02-09T03:27:34.000Z | 2022-02-09T03:27:34.000Z | src/client/mapview.cpp | nekiro/otclient | 4aba78bf7304346038739b62f2016e714392c57a | [
"MIT"
] | null | null | null | src/client/mapview.cpp | nekiro/otclient | 4aba78bf7304346038739b62f2016e714392c57a | [
"MIT"
] | 1 | 2022-01-04T16:48:27.000Z | 2022-01-04T16:48:27.000Z | /*
* Copyright (c) 2010-2020 OTClient <https://github.com/edubart/otclient>
*
* 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 "mapview.h"
#include "animatedtext.h"
#include "creature.h"
#include "game.h"
#include "lightview.h"
#include "map.h"
#include "missile.h"
#include "shadermanager.h"
#include "statictext.h"
#include "tile.h"
#include <framework/core/application.h>
#include <framework/core/eventdispatcher.h>
#include <framework/core/resourcemanager.h>
#include <framework/graphics/drawpool.h>
#include <framework/graphics/graphics.h>
#include "framework/graphics/texturemanager.h"
#include <framework/platform/platformwindow.h>
MapView::MapView()
{
m_pools.map = g_drawPool.createPoolF(MAP);
m_pools.creatureInformation = g_drawPool.createPool(CREATURE_INFORMATION);
m_pools.text = g_drawPool.createPool(TEXT);
m_pools.map->onBeforeDraw([&]() {
const Position cameraPosition = getCameraPosition();
float fadeOpacity = 1.0f;
if(!m_shaderSwitchDone && m_fadeOutTime > 0) {
fadeOpacity = 1.0f - (m_fadeTimer.timeElapsed() / m_fadeOutTime);
if(fadeOpacity < 0.0f) {
m_shader = m_nextShader;
m_nextShader = nullptr;
m_shaderSwitchDone = true;
m_fadeTimer.restart();
}
}
if(m_shaderSwitchDone && m_shader && m_fadeInTime > 0)
fadeOpacity = std::min<float>(m_fadeTimer.timeElapsed() / m_fadeInTime, 1.0f);
if(m_shader && g_painter->hasShaders() && g_graphics.shouldUseShaders()) {
auto framebufferRect = Rect(0, 0, m_drawDimension * m_tileSize);
const Point center = m_rectCache.srcRect.center();
const Point globalCoord = Point(cameraPosition.x - m_drawDimension.width() / 2, -(cameraPosition.y - m_drawDimension.height() / 2)) * m_tileSize;
m_shader->bind();
m_shader->setUniformValue(ShaderManager::MAP_CENTER_COORD, center.x / static_cast<float>(m_rectDimension.width()), 1.0f - center.y / static_cast<float>(m_rectDimension.height()));
m_shader->setUniformValue(ShaderManager::MAP_GLOBAL_COORD, globalCoord.x / static_cast<float>(m_rectDimension.height()), globalCoord.y / static_cast<float>(m_rectDimension.height()));
m_shader->setUniformValue(ShaderManager::MAP_ZOOM, m_scaleFactor);
Point last = transformPositionTo2D(cameraPosition, m_shader->getPosition());
//Reverse vertical axis.
last.y = -last.y;
m_shader->setUniformValue(ShaderManager::MAP_WALKOFFSET, last.x / static_cast<float>(m_rectDimension.width()), last.y / static_cast<float>(m_rectDimension.height()));
g_painter->setShaderProgram(m_shader);
}
g_painter->setOpacity(fadeOpacity);
});
m_pools.map->onAfterDraw([&]() {
g_painter->resetShaderProgram();
g_painter->resetOpacity();
});
m_shader = g_shaders.getDefaultMapShader();
setVisibleDimension(Size(15, 11));
}
MapView::~MapView()
{
#ifndef NDEBUG
assert(!g_app.isTerminated());
#endif
}
void MapView::draw(const Rect& rect)
{
// update visible tiles cache when needed
if(m_mustUpdateVisibleTilesCache)
updateVisibleTilesCache();
if(m_rectCache.rect != rect) {
m_rectCache.rect = rect;
m_rectCache.srcRect = calcFramebufferSource(rect.size());
m_rectCache.drawOffset = m_rectCache.srcRect.topLeft();
m_rectCache.horizontalStretchFactor = rect.width() / static_cast<float>(m_rectCache.srcRect.width());
m_rectCache.verticalStretchFactor = rect.height() / static_cast<float>(m_rectCache.srcRect.height());
}
drawFloor();
// this could happen if the player position is not known yet
if(!getCameraPosition().isValid()) {
return;
}
drawCreatureInformation();
if(m_drawLights) m_lightView->draw(rect, m_rectCache.srcRect);
drawText();
}
void MapView::drawFloor()
{
g_drawPool.use(m_pools.map, m_rectCache.rect, m_rectCache.srcRect);
{
const Position cameraPosition = getCameraPosition();
const auto& lightView = m_drawLights ? m_lightView.get() : nullptr;
g_drawPool.addFilledRect(m_rectDimension, Color::black);
for(int_fast8_t z = m_floorMax; z >= m_floorMin; --z) {
if(canFloorFade()) {
float fading = getFadeLevel(z);
if(fading == 0) break;
if(fading < 0.99)
g_drawPool.setOpacity(fading);
}
if(isDrawingLights()) {
const int8 nextFloor = z - 1;
if(nextFloor >= m_floorMin && (m_floorViewMode != FloorViewMode::FADE || getFadeLevel(nextFloor) > 0.4)) {
Position _camera = cameraPosition;
const bool alwaysTransparent = m_floorViewMode == FloorViewMode::ALWAYS_WITH_TRANSPARENCY && nextFloor < cameraPosition.z&& _camera.coveredUp(cameraPosition.z - nextFloor);
lightView->setFloor(nextFloor);
for(const auto& tile : m_cachedVisibleTiles[nextFloor].shades) {
const auto& ground = tile->getGround();
if(ground && !ground->isTranslucent()) {
if(alwaysTransparent && tile->getPosition().isInRange(_camera, TRANSPARENT_FLOOR_VIEW_RANGE, TRANSPARENT_FLOOR_VIEW_RANGE, true))
continue;
auto pos2D = transformPositionTo2D(tile->getPosition(), cameraPosition);
if(ground->isTopGround()) {
const auto currentPos = tile->getPosition();
for(const auto& pos : currentPos.translatedToDirections({ Otc::South, Otc::East })) {
const auto& nextDownTile = g_map.getTile(pos);
if(nextDownTile && nextDownTile->hasGround() && !nextDownTile->isTopGround()) {
lightView->setShade(pos2D);
break;
}
}
pos2D -= m_tileSize;
lightView->setShade(pos2D);
continue;
}
lightView->setShade(pos2D, std::vector<Otc::Direction>() /*tile->hasTallItems() || tile->hasWideItems() ? tile->getBorderDirections() : std::vector<Otc::Direction>()*/);
}
}
}
}
if(lightView) lightView->setFloor(z);
Position _camera = cameraPosition;
const bool alwaysTransparent = m_floorViewMode == FloorViewMode::ALWAYS_WITH_TRANSPARENCY && z < m_cachedFirstVisibleFloor&& _camera.coveredUp(cameraPosition.z - z);
const auto& map = m_cachedVisibleTiles[z];
g_drawPool.startPosition();
{
for(const auto& tile : map.grounds) {
if(!tile->canRender(m_drawViewportEdge, cameraPosition, m_viewport, lightView))
continue;
if(alwaysTransparent)
g_drawPool.setOpacity(tile->getPosition().isInRange(_camera, TRANSPARENT_FLOOR_VIEW_RANGE, TRANSPARENT_FLOOR_VIEW_RANGE, true) ? .16 : .7);
tile->drawGround(transformPositionTo2D(tile->getPosition(), cameraPosition), m_scaleFactor, lightView);
if(alwaysTransparent)
g_drawPool.resetOpacity();
}
}
for(const auto& tile : map.surfaces) {
if(!tile->canRender(m_drawViewportEdge, cameraPosition, m_viewport, lightView))
continue;
if(alwaysTransparent)
g_drawPool.setOpacity(tile->getPosition().isInRange(_camera, TRANSPARENT_FLOOR_VIEW_RANGE, TRANSPARENT_FLOOR_VIEW_RANGE, true) ? .16 : .7);
tile->drawSurface(transformPositionTo2D(tile->getPosition(), cameraPosition), m_scaleFactor, lightView);
if(alwaysTransparent)
g_drawPool.resetOpacity();
}
for(const auto& tile : map.effects) {
for(const auto& effect : tile->getEffects()) {
effect->drawEffect(transformPositionTo2D(effect->getPosition(), cameraPosition), m_scaleFactor, lightView);
}
}
g_drawPool.startPosition();
{
for(const MissilePtr& missile : g_map.getFloorMissiles(z))
missile->draw(transformPositionTo2D(missile->getPosition(), cameraPosition), m_scaleFactor, lightView);
}
if(m_shadowFloorIntensity > 0 && z == cameraPosition.z + 1) {
g_drawPool.addFilledRect(m_rectDimension, Color::black);
g_drawPool.setOpacity(m_shadowFloorIntensity, g_drawPool.size());
}
if(canFloorFade())
g_drawPool.resetOpacity();
}
if(m_rectCache.rect.contains(g_window.getMousePosition())) {
if(m_crosshairTexture) {
const Point& point = transformPositionTo2D(m_mousePosition, cameraPosition);
const auto crosshairRect = Rect(point, m_tileSize, m_tileSize);
g_drawPool.addTexturedRect(crosshairRect, m_crosshairTexture);
}
} else if(m_lastHighlightTile) {
m_mousePosition = {}; // Invalidate mousePosition
m_lastHighlightTile->unselect();
m_lastHighlightTile = nullptr;
}
}
}
void MapView::drawCreatureInformation()
{
if(!m_drawNames && !m_drawHealthBars && !m_drawManaBar) return;
g_drawPool.use(m_pools.creatureInformation);
g_drawPool.forceGrouping(true);
const Position cameraPosition = getCameraPosition();
uint32_t flags = 0;
if(m_drawNames) { flags = Otc::DrawNames; }
if(m_drawHealthBars) { flags |= Otc::DrawBars; }
if(m_drawManaBar) { flags |= Otc::DrawManaBar; }
for(const auto& creature : m_visibleCreatures) {
if(creature->isDead() || !creature->canBeSeen())
continue;
const auto& tile = creature->getTile();
if(!tile) continue;
bool useGray = false;
if(m_floorViewMode == FloorViewMode::ALWAYS_WITH_TRANSPARENCY) {
useGray = tile->isCovered() && !tile->getPosition().isInRange(cameraPosition, TRANSPARENT_FLOOR_VIEW_RANGE, TRANSPARENT_FLOOR_VIEW_RANGE, true);
} else if(canFloorFade()) {
useGray = g_map.isCovered(tile->getPosition(), m_cachedFirstVisibleFloor);
} else {
useGray = tile->isCovered();
}
creature->drawInformation(m_rectCache.rect,
transformPositionTo2D(creature->getPosition(), cameraPosition),
m_scaleFactor, m_rectCache.drawOffset, useGray,
m_rectCache.horizontalStretchFactor, m_rectCache.verticalStretchFactor, flags);
}
}
void MapView::drawText()
{
if(!m_drawTexts || (g_map.getStaticTexts().empty() && g_map.getAnimatedTexts().empty())) return;
g_drawPool.use(m_pools.text);
g_drawPool.forceGrouping(true);
const Position cameraPosition = getCameraPosition();
for(const StaticTextPtr& staticText : g_map.getStaticTexts()) {
if(staticText->getMessageMode() == Otc::MessageNone) continue;
const Position pos = staticText->getPosition();
if(pos.z != cameraPosition.z)
continue;
Point p = transformPositionTo2D(pos, cameraPosition) - m_rectCache.drawOffset;
p.x *= m_rectCache.horizontalStretchFactor;
p.y *= m_rectCache.verticalStretchFactor;
p += m_rectCache.rect.topLeft();
staticText->drawText(p, m_rectCache.rect);
}
for(const AnimatedTextPtr& animatedText : g_map.getAnimatedTexts()) {
const Position pos = animatedText->getPosition();
if(pos.z != cameraPosition.z)
continue;
Point p = transformPositionTo2D(pos, cameraPosition) - m_rectCache.drawOffset;
p.x *= m_rectCache.horizontalStretchFactor;
p.y *= m_rectCache.verticalStretchFactor;
p += m_rectCache.rect.topLeft();
animatedText->drawText(p, m_rectCache.rect);
}
}
void MapView::updateVisibleTilesCache()
{
// there is no tile to render on invalid positions
const Position cameraPosition = getCameraPosition();
if(!cameraPosition.isValid())
return;
// clear current visible tiles cache
do {
m_cachedVisibleTiles[m_floorMin].clear();
} while(++m_floorMin <= m_floorMax);
if(m_mustUpdateVisibleCreaturesCache) {
m_visibleCreatures.clear();
}
if(m_floorViewMode == FloorViewMode::LOCKED) {
m_lockedFirstVisibleFloor = cameraPosition.z;
} else {
m_lockedFirstVisibleFloor = -1;
}
uint8 prevFirstVisibleFloor = m_cachedFirstVisibleFloor;
if(m_lastCameraPosition != cameraPosition) {
if(m_mousePosition.isValid()) {
const Otc::Direction direction = m_lastCameraPosition.getDirectionFromPosition(cameraPosition);
m_mousePosition = m_mousePosition.translatedToDirection(direction);
if(cameraPosition.z != m_lastCameraPosition.z) {
m_mousePosition.z += cameraPosition.z - m_lastCameraPosition.z;
m_mousePosition = m_mousePosition.translatedToDirection(direction); // Two steps
}
onMouseMove(m_mousePosition, true);
}
if(m_lastCameraPosition.z != cameraPosition.z) {
onFloorChange(cameraPosition.z, m_lastCameraPosition.z);
}
const uint8 cachedFirstVisibleFloor = calcFirstVisibleFloor(m_floorViewMode != FloorViewMode::ALWAYS);
uint8 cachedLastVisibleFloor = calcLastVisibleFloor();
assert(cachedFirstVisibleFloor <= MAX_Z && cachedLastVisibleFloor <= MAX_Z);
if(cachedLastVisibleFloor < cachedFirstVisibleFloor)
cachedLastVisibleFloor = cachedFirstVisibleFloor;
m_cachedFirstVisibleFloor = cachedFirstVisibleFloor;
m_cachedLastVisibleFloor = cachedLastVisibleFloor;
m_floorMin = m_floorMax = cameraPosition.z;
}
const bool _canFloorFade = canFloorFade();
uint8 cachedFirstVisibleFloor = m_cachedFirstVisibleFloor;
if(m_floorViewMode == FloorViewMode::ALWAYS_WITH_TRANSPARENCY || _canFloorFade) {
cachedFirstVisibleFloor = calcFirstVisibleFloor(false);
}
// Fading System by Kondra https://github.com/OTCv8/otclientv8
if(!m_lastCameraPosition.isValid() || m_lastCameraPosition.z != cameraPosition.z || m_lastCameraPosition.distance(cameraPosition) >= 3) {
for(int iz = m_cachedLastVisibleFloor; iz >= cachedFirstVisibleFloor; --iz) {
m_fadingFloorTimers[iz].restart(m_floorFading * 1000);
}
} else if(prevFirstVisibleFloor < m_cachedFirstVisibleFloor) { // showing new floor
for(int iz = prevFirstVisibleFloor; iz < m_cachedFirstVisibleFloor; ++iz) {
int shift = std::max<int>(0, m_floorFading - m_fadingFloorTimers[iz].elapsed_millis());
m_fadingFloorTimers[iz].restart(shift * 1000);
}
} else if(prevFirstVisibleFloor > m_cachedFirstVisibleFloor) { // hiding floor
for(int iz = m_cachedFirstVisibleFloor; iz < prevFirstVisibleFloor; ++iz) {
int shift = std::max<int>(0, m_floorFading - m_fadingFloorTimers[iz].elapsed_millis());
m_fadingFloorTimers[iz].restart(shift * 1000);
}
}
m_lastCameraPosition = cameraPosition;
// cache visible tiles in draw order
// draw from last floor (the lower) to first floor (the higher)
const uint32 numDiagonals = m_drawDimension.width() + m_drawDimension.height() - 1;
for(int_fast32_t iz = m_cachedLastVisibleFloor; iz >= cachedFirstVisibleFloor; --iz) {
auto& floor = m_cachedVisibleTiles[iz];
// loop through / diagonals beginning at top left and going to top right
for(uint_fast32_t diagonal = 0; diagonal < numDiagonals; ++diagonal) {
// loop current diagonal tiles
const uint32 advance = std::max<uint32>(diagonal - m_drawDimension.height(), 0);
for(int iy = diagonal - advance, ix = advance; iy >= 0 && ix < m_drawDimension.width(); --iy, ++ix) {
// position on current floor
//TODO: check position limits
Position tilePos = cameraPosition.translated(ix - m_virtualCenterOffset.x, iy - m_virtualCenterOffset.y);
// adjust tilePos to the wanted floor
tilePos.coveredUp(cameraPosition.z - iz);
if(const TilePtr& tile = g_map.getTile(tilePos)) {
// skip tiles that have nothing
if(!tile->isDrawable())
continue;
if(m_mustUpdateVisibleCreaturesCache) {
const auto& tileCreatures = tile->getCreatures();
if(isInRange(tilePos) && !tileCreatures.empty()) {
m_visibleCreatures.insert(m_visibleCreatures.end(), tileCreatures.rbegin(), tileCreatures.rend());
}
}
if(!_canFloorFade) {
// skip tiles that are completely behind another tile
if(tile->isCompletelyCovered(cachedFirstVisibleFloor)) {
if(m_floorViewMode != FloorViewMode::ALWAYS_WITH_TRANSPARENCY || (tilePos.z < cameraPosition.z && tile->isCovered())) {
continue;
}
}
}
if(isDrawingLights() && (tile->isFullyOpaque() || (tile->getGround() && tile->getGround()->isTopGround())))
floor.shades.push_back(tile);
if(tile->hasGround())
floor.grounds.push_back(tile);
if(tile->hasSurface())
floor.surfaces.push_back(tile);
if(g_app.isDrawingEffectsOnTop() && tile->hasEffect())
floor.effects.push_back(tile);
tile->onAddVisibleTileList(this);
if(iz < m_floorMin)
m_floorMin = iz;
else if(iz > m_floorMax)
m_floorMax = iz;
}
}
}
}
m_mustUpdateVisibleCreaturesCache = false;
m_mustUpdateVisibleTilesCache = false;
}
void MapView::updateGeometry(const Size& visibleDimension)
{
const uint8 tileSize = SPRITE_SIZE * m_scaleFactor;
const Size drawDimension = visibleDimension + Size(3),
bufferSize = drawDimension * tileSize;
if(bufferSize.width() > g_graphics.getMaxTextureSize() || bufferSize.height() > g_graphics.getMaxTextureSize()) {
g_logger.traceError("reached max zoom out");
return;
}
m_visibleDimension = visibleDimension;
m_drawDimension = drawDimension;
m_tileSize = tileSize;
m_virtualCenterOffset = (drawDimension / 2 - Size(1)).toPoint();
m_rectDimension = Rect(0, 0, bufferSize);
m_pools.map->resize(bufferSize);
if(m_drawLights) m_lightView->resize();
m_awareRange.left = std::min<uint16>(g_map.getAwareRange().left, (m_drawDimension.width() / 2) - 1);
m_awareRange.top = std::min<uint16>(g_map.getAwareRange().top, (m_drawDimension.height() / 2) - 1);
m_awareRange.bottom = m_awareRange.top + 1;
m_awareRange.right = m_awareRange.left + 1;
m_rectCache.rect = Rect();
updateViewportDirectionCache();
requestVisibleTilesCacheUpdate();
}
void MapView::onCameraMove(const Point& /*offset*/)
{
m_rectCache.rect = Rect();
if(isFollowingCreature()) {
if(m_followingCreature->isWalking()) {
m_viewport = m_viewPortDirection[m_followingCreature->getDirection()];
} else {
m_viewport = m_viewPortDirection[Otc::InvalidDirection];
}
}
}
void MapView::onGlobalLightChange(const Light&)
{
updateLight();
}
void MapView::updateLight()
{
if(!m_drawLights) return;
const auto cameraPosition = getCameraPosition();
Light ambientLight = cameraPosition.z > SEA_FLOOR ? Light() : g_map.getLight();
ambientLight.intensity = std::max<uint8>(m_minimumAmbientLight * 255, ambientLight.intensity);
m_lightView->setGlobalLight(ambientLight);
}
void MapView::onFloorChange(const uint8 /*floor*/, const uint8 /*previousFloor*/)
{
m_mustUpdateVisibleCreaturesCache = true;
updateLight();
}
void MapView::onTileUpdate(const Position&, const ThingPtr& thing, const Otc::Operation)
{
if(thing && thing->isCreature())
m_mustUpdateVisibleCreaturesCache = true;
requestVisibleTilesCacheUpdate();
}
// isVirtualMove is when the mouse is stopped, but the camera moves,
// so the onMouseMove event is triggered by sending the new tile position that the mouse is in.
void MapView::onMouseMove(const Position& mousePos, const bool /*isVirtualMove*/)
{
{ // Highlight Target System
if(m_lastHighlightTile) {
m_lastHighlightTile->unselect();
m_lastHighlightTile = nullptr;
}
if(m_drawHighlightTarget) {
if(m_lastHighlightTile = m_shiftPressed ? getTopTile(mousePos) : g_map.getTile(mousePos))
m_lastHighlightTile->select(m_shiftPressed);
}
}
}
void MapView::onKeyRelease(const InputEvent& inputEvent)
{
const bool shiftPressed = inputEvent.keyboardModifiers == Fw::KeyboardShiftModifier;
if(shiftPressed != m_shiftPressed) {
m_shiftPressed = shiftPressed;
onMouseMove(m_mousePosition);
}
}
void MapView::onMapCenterChange(const Position& /*newPos*/, const Position& /*oldPos*/)
{
requestVisibleTilesCacheUpdate();
}
void MapView::lockFirstVisibleFloor(uint8 firstVisibleFloor)
{
m_lockedFirstVisibleFloor = firstVisibleFloor;
requestVisibleTilesCacheUpdate();
}
void MapView::unlockFirstVisibleFloor()
{
m_lockedFirstVisibleFloor = -1;
requestVisibleTilesCacheUpdate();
}
void MapView::setVisibleDimension(const Size& visibleDimension)
{
if(visibleDimension == m_visibleDimension)
return;
if(visibleDimension.width() % 2 != 1 || visibleDimension.height() % 2 != 1) {
g_logger.traceError("visible dimension must be odd");
return;
}
if(visibleDimension < Size(3)) {
g_logger.traceError("reach max zoom in");
return;
}
updateGeometry(visibleDimension);
}
void MapView::setFloorViewMode(FloorViewMode floorViewMode)
{
m_floorViewMode = floorViewMode;
resetLastCamera();
requestVisibleTilesCacheUpdate();
}
void MapView::setAntiAliasingMode(const AntialiasingMode mode)
{
m_pools.map->setSmooth(mode != ANTIALIASING_DISABLED);
m_scaleFactor = mode == ANTIALIASING_SMOOTH_RETRO ? 2.f : 1.f;
updateGeometry(m_visibleDimension);
}
void MapView::followCreature(const CreaturePtr& creature)
{
m_follow = true;
m_followingCreature = creature;
m_lastCameraPosition = Position();
requestVisibleTilesCacheUpdate();
}
void MapView::setCameraPosition(const Position& pos)
{
m_follow = false;
m_customCameraPosition = pos;
requestVisibleTilesCacheUpdate();
}
Position MapView::getPosition(const Point& point, const Size& mapSize)
{
const Position cameraPosition = getCameraPosition();
// if we have no camera, its impossible to get the tile
if(!cameraPosition.isValid())
return {};
const Rect srcRect = calcFramebufferSource(mapSize);
const float sh = srcRect.width() / static_cast<float>(mapSize.width());
const float sv = srcRect.height() / static_cast<float>(mapSize.height());
const auto framebufferPos = Point(point.x * sh, point.y * sv);
const Point centerOffset = (framebufferPos + srcRect.topLeft()) / m_tileSize;
const Point tilePos2D = m_virtualCenterOffset - m_drawDimension.toPoint() + centerOffset + Point(2);
if(tilePos2D.x + cameraPosition.x < 0 && tilePos2D.y + cameraPosition.y < 0)
return {};
Position position = Position(tilePos2D.x, tilePos2D.y, 0) + cameraPosition;
if(!position.isValid())
return {};
return position;
}
void MapView::move(int32 x, int32 y)
{
m_moveOffset.x += x;
m_moveOffset.y += y;
int32_t tmp = m_moveOffset.x / SPRITE_SIZE;
bool requestTilesUpdate = false;
if(tmp != 0) {
m_customCameraPosition.x += tmp;
m_moveOffset.x %= SPRITE_SIZE;
requestTilesUpdate = true;
}
tmp = m_moveOffset.y / SPRITE_SIZE;
if(tmp != 0) {
m_customCameraPosition.y += tmp;
m_moveOffset.y %= SPRITE_SIZE;
requestTilesUpdate = true;
}
m_rectCache.rect = Rect();
if(requestTilesUpdate)
requestVisibleTilesCacheUpdate();
onCameraMove(m_moveOffset);
}
Rect MapView::calcFramebufferSource(const Size& destSize)
{
Point drawOffset = ((m_drawDimension - m_visibleDimension - Size(1)).toPoint() / 2) * m_tileSize;
if(isFollowingCreature())
drawOffset += m_followingCreature->getWalkOffset() * m_scaleFactor;
else if(!m_moveOffset.isNull())
drawOffset += m_moveOffset * m_scaleFactor;
Size srcSize = destSize;
const Size srcVisible = m_visibleDimension * m_tileSize;
srcSize.scale(srcVisible, Fw::KeepAspectRatio);
drawOffset.x += (srcVisible.width() - srcSize.width()) / 2;
drawOffset.y += (srcVisible.height() - srcSize.height()) / 2;
return Rect(drawOffset, srcSize);
}
uint8 MapView::calcFirstVisibleFloor(bool checkLimitsFloorsView)
{
uint8 z = SEA_FLOOR;
// return forced first visible floor
if(m_lockedFirstVisibleFloor != -1) {
z = m_lockedFirstVisibleFloor;
} else {
const Position cameraPosition = getCameraPosition();
// this could happens if the player is not known yet
if(cameraPosition.isValid()) {
// if nothing is limiting the view, the first visible floor is 0
uint8 firstFloor = 0;
// limits to underground floors while under sea level
if(cameraPosition.z > SEA_FLOOR)
firstFloor = std::max<uint8>(cameraPosition.z - AWARE_UNDEGROUND_FLOOR_RANGE, UNDERGROUND_FLOOR);
// loop in 3x3 tiles around the camera
for(int_fast32_t ix = -1; checkLimitsFloorsView && ix <= 1 && firstFloor < cameraPosition.z; ++ix) {
for(int_fast32_t iy = -1; iy <= 1 && firstFloor < cameraPosition.z; ++iy) {
const Position pos = cameraPosition.translated(ix, iy);
// process tiles that we can look through, e.g. windows, doors
if((ix == 0 && iy == 0) || ((std::abs(ix) != std::abs(iy)) && g_map.isLookPossible(pos))) {
Position upperPos = pos;
Position coveredPos = pos;
const auto isLookPossible = g_map.isLookPossible(pos);
while(coveredPos.coveredUp() && upperPos.up() && upperPos.z >= firstFloor) {
// check tiles physically above
TilePtr tile = g_map.getTile(upperPos);
if(tile && tile->limitsFloorsView(!isLookPossible)) {
firstFloor = upperPos.z + 1;
break;
}
// check tiles geometrically above
tile = g_map.getTile(coveredPos);
if(tile && tile->limitsFloorsView(isLookPossible)) {
firstFloor = coveredPos.z + 1;
break;
}
}
}
}
}
z = firstFloor;
}
}
// just ensure the that the floor is in the valid range
z = std::clamp<int>(z, 0, static_cast<int>(MAX_Z));
return z;
}
uint8 MapView::calcLastVisibleFloor()
{
uint8 z = SEA_FLOOR;
const Position cameraPosition = getCameraPosition();
// this could happens if the player is not known yet
if(cameraPosition.isValid()) {
// view only underground floors when below sea level
if(cameraPosition.z > SEA_FLOOR)
z = cameraPosition.z + AWARE_UNDEGROUND_FLOOR_RANGE;
else
z = SEA_FLOOR;
}
if(m_lockedFirstVisibleFloor != -1)
z = std::max<int>(m_lockedFirstVisibleFloor, z);
// just ensure the that the floor is in the valid range
z = std::clamp<int>(z, 0, static_cast<int>(MAX_Z));
return z;
}
TilePtr MapView::getTopTile(Position tilePos)
{
// we must check every floor, from top to bottom to check for a clickable tile
TilePtr tile;
if(m_floorViewMode == FloorViewMode::ALWAYS_WITH_TRANSPARENCY && tilePos.isInRange(m_lastCameraPosition, TRANSPARENT_FLOOR_VIEW_RANGE, TRANSPARENT_FLOOR_VIEW_RANGE))
tile = g_map.getTile(tilePos);
else {
tilePos.coveredUp(tilePos.z - m_cachedFirstVisibleFloor);
for(uint8 i = m_cachedFirstVisibleFloor; i <= m_floorMax; ++i) {
tile = g_map.getTile(tilePos);
if(tile && tile->isClickable())
break;
tilePos.coveredDown();
tile = nullptr;
}
}
return tile;
}
Position MapView::getCameraPosition()
{
if(isFollowingCreature())
return m_followingCreature->getPosition();
return m_customCameraPosition;
}
void MapView::setShader(const PainterShaderProgramPtr& shader, float fadein, float fadeout)
{
if((m_shader == shader))
return;
if(fadeout > 0.0f && m_shader) {
m_nextShader = shader;
m_shaderSwitchDone = false;
} else {
m_shader = shader;
m_nextShader = nullptr;
m_shaderSwitchDone = true;
}
m_fadeTimer.restart();
m_fadeInTime = fadein;
m_fadeOutTime = fadeout;
if(shader) shader->setPosition(getCameraPosition());
}
void MapView::setDrawLights(bool enable)
{
const auto& pool = g_drawPool.get(LIGHT);
if(pool) pool->setEnable(enable);
if(enable == m_drawLights) return;
m_lightView = enable ? LightViewPtr(new LightView(this)) : nullptr;
m_drawLights = enable;
updateLight();
}
void MapView::updateViewportDirectionCache()
{
for(uint8 dir = Otc::North; dir <= Otc::InvalidDirection; ++dir) {
AwareRange& vp = m_viewPortDirection[dir];
vp.top = m_awareRange.top;
vp.right = m_awareRange.right;
vp.bottom = vp.top;
vp.left = vp.right;
switch(dir) {
case Otc::North:
case Otc::South:
vp.top += 1;
vp.bottom += 1;
break;
case Otc::West:
case Otc::East:
vp.right += 1;
vp.left += 1;
break;
case Otc::NorthEast:
case Otc::SouthEast:
case Otc::NorthWest:
case Otc::SouthWest:
vp.left += 1;
vp.bottom += 1;
vp.top += 1;
vp.right += 1;
break;
case Otc::InvalidDirection:
vp.left -= 1;
vp.right -= 1;
break;
default:
break;
}
}
}
std::vector<CreaturePtr> MapView::getSightSpectators(const Position& centerPos, bool multiFloor)
{
return g_map.getSpectatorsInRangeEx(centerPos, multiFloor, m_awareRange.left - 1, m_awareRange.right - 2, m_awareRange.top - 1, m_awareRange.bottom - 2);
}
std::vector<CreaturePtr> MapView::getSpectators(const Position& centerPos, bool multiFloor)
{
return g_map.getSpectatorsInRangeEx(centerPos, multiFloor, m_awareRange.left, m_awareRange.right, m_awareRange.top, m_awareRange.bottom);
}
bool MapView::isInRange(const Position& pos, const bool ignoreZ)
{
return getCameraPosition().isInRange(pos, m_awareRange.left - 1, m_awareRange.right - 2, m_awareRange.top - 1, m_awareRange.bottom - 2, ignoreZ);
}
void MapView::setCrosshairTexture(const std::string& texturePath)
{
m_crosshairTexture = texturePath.empty() ? nullptr : g_textures.getTexture(texturePath);
}
| 36.668122 | 197 | 0.626414 | [
"render",
"vector"
] |
4fb77c377e2013a589825c9d8745ae8397d776fc | 2,185 | hpp | C++ | src/mbgl/renderer/buckets/line_bucket.hpp | tz576/Mapbox | 681e0141de63d0d5a545e87c40216163b2d63fc6 | [
"BSL-1.0",
"Apache-2.0"
] | 4 | 2018-02-21T14:04:04.000Z | 2021-12-15T04:16:53.000Z | src/mbgl/renderer/buckets/line_bucket.hpp | leejing397/GeoMap | d94d3f275234ad4434858e08a6b42e72c44dc6db | [
"BSL-1.0",
"Apache-2.0"
] | 76 | 2018-08-30T20:47:55.000Z | 2022-03-19T19:40:41.000Z | src/mbgl/renderer/buckets/line_bucket.hpp | leejing397/GeoMap | d94d3f275234ad4434858e08a6b42e72c44dc6db | [
"BSL-1.0",
"Apache-2.0"
] | 3 | 2019-04-10T03:37:12.000Z | 2019-05-28T08:59:00.000Z | #pragma once
#include <mbgl/renderer/bucket.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
#include <mbgl/gl/vertex_buffer.hpp>
#include <mbgl/gl/index_buffer.hpp>
#include <mbgl/programs/segment.hpp>
#include <mbgl/programs/line_program.hpp>
#include <mbgl/style/layers/line_layer_properties.hpp>
#include <vector>
namespace mbgl {
class BucketParameters;
class RenderLineLayer;
class LineBucket : public Bucket {
public:
LineBucket(const BucketParameters&,
const std::vector<const RenderLayer*>&,
const style::LineLayoutProperties::Unevaluated&);
void addFeature(const GeometryTileFeature&,
const GeometryCollection&) override;
bool hasData() const override;
void upload(gl::Context&) override;
float getQueryRadius(const RenderLayer&) const override;
style::LineLayoutProperties::PossiblyEvaluated layout;
gl::VertexVector<LineLayoutVertex> vertices;
gl::IndexVector<gl::Triangles> triangles;
SegmentVector<LineAttributes> segments;
optional<gl::VertexBuffer<LineLayoutVertex>> vertexBuffer;
optional<gl::IndexBuffer<gl::Triangles>> indexBuffer;
std::map<std::string, LineProgram::PaintPropertyBinders> paintPropertyBinders;
private:
void addGeometry(const GeometryCoordinates&, const GeometryTileFeature&);
struct TriangleElement {
TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) : a(a_), b(b_), c(c_) {}
uint16_t a, b, c;
};
void addCurrentVertex(const GeometryCoordinate& currentVertex, double& distance,
const Point<double>& normal, double endLeft, double endRight, bool round,
std::size_t startVertex, std::vector<LineBucket::TriangleElement>& triangleStore);
void addPieSliceVertex(const GeometryCoordinate& currentVertex, double distance,
const Point<double>& extrude, bool lineTurnsLeft, std::size_t startVertex,
std::vector<TriangleElement>& triangleStore);
std::ptrdiff_t e1;
std::ptrdiff_t e2;
std::ptrdiff_t e3;
const uint32_t overscaling;
const float zoom;
float getLineWidth(const RenderLineLayer& layer) const;
};
} // namespace mbgl
| 32.132353 | 94 | 0.724027 | [
"vector"
] |
4fb841dec7eae1a79101ee2b384fcadb4009ae33 | 416,923 | cpp | C++ | source/matplot/util/world_map_110m.cpp | dendisuhubdy/matplotplusplus | 3781773832306e5571376f29f0c1d1389eb82af0 | [
"MIT"
] | 1 | 2021-05-18T00:02:58.000Z | 2021-05-18T00:02:58.000Z | source/matplot/util/world_map_110m.cpp | dendisuhubdy/matplotplusplus | 3781773832306e5571376f29f0c1d1389eb82af0 | [
"MIT"
] | null | null | null | source/matplot/util/world_map_110m.cpp | dendisuhubdy/matplotplusplus | 3781773832306e5571376f29f0c1d1389eb82af0 | [
"MIT"
] | 1 | 2020-09-07T07:44:27.000Z | 2020-09-07T07:44:27.000Z | //
// Created by Alan Freitas on 20/07/20.
//
#include <limits>
#include <matplot/util/geodata.h>
// http://www.gnuplotting.org/plotting-the-world-revisited/
namespace matplot {
// (-?\d+\.\d+) +(-?\d+\.\d+) *\n
// $1,\n
// $2,\n
// \n\n
// \nstd::numeric_limits<double>::quiet_NaN(),\n
std::pair<std::vector<double>, std::vector<double>> prepare_world_map_110m() {
static constexpr double x[] = {
-163.71289567772871,
-163.105800951163786,
-161.245113491846439,
-160.24620805564453,
-159.482404548154477,
-159.208183560197654,
-161.127601284814716,
-162.439846768218416,
-163.027407803377002,
-163.06660437727038,
-163.71289567772871,
std::numeric_limits<double>::quiet_NaN(),
-6.197884894220991,
-6.032985398777611,
-6.788856573910849,
-8.561616583683559,
-9.977085740590269,
-9.166282517930782,
-9.688524542672454,
-8.327987433292009,
-7.572167934591064,
-6.733847011736145,
-5.661948614921968,
-6.197884894220991,
std::numeric_limits<double>::quiet_NaN(),
141.000210402591847,
142.735246616791471,
144.583970982033236,
145.273127883077677,
145.829786411725706,
145.981921828393013,
147.648073358347574,
147.891107619416232,
146.970905389594861,
147.191873814074938,
148.084635858349316,
148.734105259393573,
149.306835158484432,
149.266630894161324,
150.038728469034254,
149.738798456012205,
150.801627638959133,
150.690574985963906,
150.028393182575826,
149.782310012001972,
148.923137648717272,
147.913018426707993,
147.135443150012179,
146.567880894150562,
146.048481073184917,
144.744167922138047,
143.897087844009661,
143.286375767184325,
143.413913202080664,
142.628431431244167,
142.068258905200253,
141.033851760013818,
140.143415155192542,
139.127766554928087,
138.881476678625006,
137.614473911692869,
138.039099155835174,
138.668621454014783,
138.407913853102286,
137.927839797110778,
135.989250116113453,
135.164597609599753,
133.662880487197867,
133.367704705946721,
132.983955519747269,
132.756940952689035,
132.753788690319254,
131.989804315316178,
133.066844517143409,
133.780030959203543,
133.69621178602614,
132.232373488494261,
131.836221958544741,
130.942839797082854,
130.519558140180095,
131.867537876513609,
132.380116408416711,
133.985548130428356,
134.143367954647715,
134.422627394753022,
135.457602980694674,
136.293314243718839,
137.440737746327557,
138.329727411044701,
139.184920689042883,
139.926684198160444,
141.000210402591847,
std::numeric_limits<double>::quiet_NaN(),
114.204016554828371,
114.599961379048722,
115.450710483869813,
116.220741001451017,
116.72510298061971,
117.129626092600475,
117.643393182446275,
117.689075148592309,
118.34769127815224,
119.181903924639968,
119.11069380094176,
118.439727004064082,
118.618320754064797,
117.882034946770176,
117.313232456533498,
118.048329705885394,
117.875627069165972,
118.996747267738158,
117.811858351717802,
117.478338657706033,
117.521643507966644,
116.560048455879468,
116.5337968282752,
116.148083937648664,
116.00085778204911,
114.864803094544556,
114.468651564595064,
113.75567182826407,
113.256994256647516,
112.068126255340673,
111.703290643360049,
111.048240187628238,
110.223846063276,
110.070935500124335,
109.571947869913998,
109.091873813922504,
108.952657505328204,
109.069136183714079,
109.663260125773746,
110.396135288537096,
111.168852980597478,
111.370081007942048,
111.796928338672899,
112.995614862115218,
113.712935418758676,
114.204016554828371,
std::numeric_limits<double>::quiet_NaN(),
-93.612755906940464,
-94.156908738973911,
-95.608680589565637,
-96.820932176484547,
-96.28858740922982,
-94.85081987178917,
-93.977746548217965,
-93.612755906940464,
std::numeric_limits<double>::quiet_NaN(),
-93.840003017943985,
-94.295608283245286,
-96.169654100310069,
-96.436304490936138,
-94.422577277386409,
-93.720656297565895,
-93.840003017943985,
std::numeric_limits<double>::quiet_NaN(),
-96.754398769908761,
-95.559277920294605,
-95.830294969449341,
-97.309842902397989,
-98.124289313534035,
-98.552867804746683,
-98.631984422585532,
-97.337231411512661,
-96.754398769908761,
std::numeric_limits<double>::quiet_NaN(),
-88.150350307960281,
-89.764722052758401,
-92.422440965529461,
-92.768285488642817,
-92.889905972041745,
-93.893824022175991,
-95.962457445035795,
-97.121378953829506,
-96.74512285031237,
-94.684085862999439,
-93.573921068073133,
-91.6050231595366,
-90.741845872749295,
-90.969661424508018,
-89.822237921899259,
-89.187082892599847,
-87.838276333349654,
-86.379192267588635,
-84.789625210290581,
-82.753444586910064,
-81.12853084992436,
-80.057510952459154,
-79.833932868148366,
-80.457770758775865,
-81.948842536125568,
-83.228893602211429,
-86.097452358733321,
-88.150350307960281,
std::numeric_limits<double>::quiet_NaN(),
-111.264443325630879,
-109.854451870547109,
-110.186938035913016,
-112.051191169058498,
-113.534278937619121,
-112.724586758253906,
-111.264443325630879,
std::numeric_limits<double>::quiet_NaN(),
-110.963660651476019,
-109.6631457182026,
-110.881314256618921,
-112.542091437615156,
-112.525890876091637,
-111.500010342233395,
-110.963660651476019,
std::numeric_limits<double>::quiet_NaN(),
-66.282434455008215,
-65.7713028632093,
-65.591003790942949,
-65.847163865813769,
-66.599934455009489,
-67.184162360285271,
-67.242427537694354,
-67.10067908391774,
-66.282434455008215,
std::numeric_limits<double>::quiet_NaN(),
-77.569600796199211,
-76.896618618462128,
-76.365359056285541,
-76.199658576141644,
-76.9025614081757,
-77.206341315403478,
-77.766022915340614,
-78.33771928578561,
-78.217726610003879,
-77.797364671525628,
-77.569600796199211,
std::numeric_limits<double>::quiet_NaN(),
-82.268151211257063,
-81.404457160146833,
-80.618768683581195,
-79.67952368846025,
-79.281485968732085,
-78.347434455056487,
-77.993295864560281,
-77.146422492161051,
-76.523824835908556,
-76.19462012399319,
-75.59822241891267,
-75.671060350228061,
-74.933896043584497,
-74.17802486845126,
-74.296648118777256,
-74.961594611292938,
-75.634680141894592,
-76.323656175425995,
-77.755480923153073,
-77.085108405246743,
-77.492654588516615,
-78.137292243141587,
-78.482826707661189,
-78.719866502584011,
-79.284999966127941,
-80.217475348618649,
-80.517534552721415,
-81.820943366203181,
-82.16999182811864,
-81.795001797192668,
-82.775897996740852,
-83.494458787759356,
-83.908800421875625,
-84.052150845053262,
-84.54703019889638,
-84.974911058273108,
-84.447062140627764,
-84.230357021811784,
-83.778239915690193,
-83.26754757356575,
-82.510436164057509,
-82.268151211257063,
std::numeric_limits<double>::quiet_NaN(),
-55.600218268442056,
-56.134035814017089,
-56.795881720595276,
-56.143105027884332,
-55.471492275602998,
-55.822401089080962,
-54.935142584845636,
-54.473775397343786,
-53.476549445191367,
-53.786013759971254,
-53.086133999226263,
-52.958648240762216,
-52.648098720904208,
-53.069158291218386,
-53.521456264853001,
-54.178935512902513,
-53.961868659060499,
-54.240482143762137,
-55.400773078011568,
-55.997480841685828,
-55.291219041552793,
-56.250798712780586,
-57.325229254777078,
-59.266015184146823,
-59.419494188053676,
-58.796586473207441,
-59.23162451845657,
-58.391804979065199,
-57.35868974468606,
-56.738650071832026,
-55.870976935435323,
-55.406974249886588,
-55.600218268442056,
std::numeric_limits<double>::quiet_NaN(),
-83.882626308919768,
-82.787576870438826,
-81.642013719392594,
-81.553440314444316,
-80.817361212878865,
-80.103451300766636,
-80.991019863595724,
-82.547178107417039,
-83.108797573565113,
-84.100416632813875,
-85.523404710619047,
-85.866768764982396,
-87.221983201836778,
-86.35275977247133,
-86.224886440765104,
-85.883847825854858,
-85.161307949549894,
-84.975763719405919,
-84.464012010419495,
-83.882626308919768,
std::numeric_limits<double>::quiet_NaN(),
-78.770638597310779,
-77.824623989559598,
-75.605844692675731,
-74.228616095665004,
-74.099140794557712,
-72.242225714797684,
-71.200015428335178,
-68.786054246684898,
-67.914970465756937,
-66.969033372654195,
-68.805122850200604,
-66.449866095633894,
-64.862314419195243,
-63.424934454996794,
-61.851981370680605,
-62.16317684594226,
-63.918444383384184,
-65.148860236253682,
-66.721219041598516,
-68.015016038674005,
-68.141287400979195,
-67.089646165623421,
-65.732080451099762,
-65.320167609301251,
-64.669406297449683,
-65.01380388045888,
-66.275044725190483,
-68.783186204692697,
-67.369680752213085,
-66.328297288667258,
-66.165568203380147,
-68.877366502544646,
-71.023437059193853,
-72.235378587519023,
-71.886278449171272,
-73.378306240518384,
-74.834418911422631,
-74.818502570276735,
-77.709979824520076,
-78.555948859354203,
-77.897281053361979,
-76.018274298797166,
-73.959795294882682,
-74.29388342964964,
-73.94491248238262,
-72.651167161739423,
-72.926059943316048,
-73.311617804645721,
-74.843307257776843,
-76.869100918266724,
-76.228649054657382,
-77.287369961237147,
-78.168633999326602,
-78.957242194316734,
-79.492455003563663,
-81.30547095409176,
-84.944706183598512,
-87.060003424817893,
-88.681713223001481,
-89.513419562523026,
-88.467721116880824,
-89.88815121128755,
-90.205160285182046,
-89.436576707705001,
-88.408241543312869,
-85.826151089200977,
-86.562178514334121,
-85.774371304044536,
-84.850112474288224,
-82.315590176101011,
-80.600087653307682,
-80.748941616524434,
-78.770638597310779,
std::numeric_limits<double>::quiet_NaN(),
-94.503657599652371,
-92.420012173211731,
-90.509792853542635,
-92.003965216829869,
-93.196295539100262,
-94.269046597047264,
-95.409855516322665,
-96.033745083382442,
-96.018267991911017,
-95.495793423224043,
-94.503657599652371,
std::numeric_limits<double>::quiet_NaN(),
-100.438359951564109,
-101.54,
-100.356426968165351,
-99.163864101949656,
-97.38,
-97.12,
-98.053595954158752,
-96.54,
-96.72,
-98.359649624407368,
-99.322846645895595,
-100.014819912499945,
-102.48,
-102.48,
-100.438359951564109,
std::numeric_limits<double>::quiet_NaN(),
-107.819433966893129,
-106.92891984742343,
-105.880999315192668,
-105.704989386806545,
-106.313479377043365,
-109.699991014426701,
-112.223066982861269,
-113.743801032346525,
-113.871338467242865,
-111.794204271271013,
-116.312197231901067,
-117.710406460422277,
-116.346019456836089,
-115.404862433720353,
-112.590563931104924,
-110.814212409287933,
-109.067109748148127,
-110.497255011825715,
-109.581109381939228,
-108.54859,
-108.21141,
-107.819433966893129,
std::numeric_limits<double>::quiet_NaN(),
-122.854924486159021,
-121.157534552883988,
-119.103938971821094,
-117.570130784965997,
-116.198586595507379,
-116.335813361458449,
-117.106050584768823,
-118.04041215703819,
-119.899316779441449,
-121.499994269682233,
-122.854924486159021,
std::numeric_limits<double>::quiet_NaN(),
-121.537873094552182,
-120.109769049950103,
-117.555635545708128,
-116.58442867721466,
-115.510799119918701,
-116.767931688283085,
-119.22,
-120.46,
-120.46,
-123.092196825027145,
-123.62,
-125.928948737473391,
-125.5,
-124.80729,
-123.94,
-124.917744310386013,
-121.537873094552182,
std::numeric_limits<double>::quiet_NaN(),
-166.467792121424623,
-165.674429694663644,
-165.579164191733582,
-166.192770148767266,
-166.848337368821973,
-167.455277066090076,
-166.467792121424623,
std::numeric_limits<double>::quiet_NaN(),
-153.22872941792113,
-152.564790615835136,
-152.141147223906387,
-153.006314053336922,
-154.0050902984581,
-154.516402757770038,
-154.670992804971178,
-153.762779507441508,
-153.22872941792113,
std::numeric_limits<double>::quiet_NaN(),
-132.710007697461464,
-131.749988776559178,
-132.049479539906741,
-131.179041714382407,
-131.577828742378813,
-132.180427619334324,
-132.549991624869676,
-133.054611986199802,
-133.239665290237014,
-133.180004849156035,
-132.710007697461464,
std::numeric_limits<double>::quiet_NaN(),
-125.415000780114568,
-124.920767381675091,
-123.922507900876823,
-123.510000780106935,
-124.012889980955308,
-125.655011969894161,
-125.954993659348489,
-126.850003628427601,
-127.029992642100169,
-128.059335496922017,
-128.444583299657921,
-128.358412848811241,
-127.308580288585674,
-126.695000169768122,
-125.755005866378951,
-125.415000780114568,
std::numeric_limits<double>::quiet_NaN(),
-171.731656867539442,
-171.114433560245288,
-170.491112433940714,
-169.682505459653612,
-168.68943946030069,
-168.771940884454665,
-169.529439867205099,
-170.290556200215946,
-170.671385667990933,
-171.553063117538727,
-171.791110602891223,
-171.731656867539442,
std::numeric_limits<double>::quiet_NaN(),
-105.492289191493199,
-103.529282396237946,
-100.8251580472688,
-100.060191820052196,
-99.670939093813644,
-101.303940192453013,
-102.949808722733025,
-105.176132778731514,
-104.210429450277132,
-105.419580451258525,
-105.492289191493199,
std::numeric_limits<double>::quiet_NaN(),
32.946960890440806,
33.667227003724946,
34.576473829900465,
33.900804477684204,
34.004880812320039,
32.979827101378447,
32.490296258277539,
32.25666710788596,
32.80247358575275,
32.946960890440806,
std::numeric_limits<double>::quiet_NaN(),
26.290002882601698,
26.164997592887659,
24.724982130642303,
24.735007358506916,
23.514978468528081,
23.699980096133004,
24.246665073348705,
25.025015496528908,
25.769207797964185,
25.745023227651586,
26.290002882601698,
std::numeric_limits<double>::quiet_NaN(),
49.543518914595751,
49.808980747279094,
50.056510857957164,
50.217431268114069,
50.476536899625529,
50.377111443895956,
50.200274692593183,
49.860605503138679,
49.672606642460863,
49.863344354050156,
49.774564243372708,
49.498612094934117,
49.435618523970305,
49.041792433473944,
48.548540887248009,
47.930749139198667,
47.547723423051309,
47.095761346226595,
46.282477654817086,
45.409507684110451,
44.833573846217554,
44.039720493349762,
43.763768344911171,
43.697777540874455,
43.345654331237625,
43.254187046081,
43.43329756040464,
43.893682895692926,
43.896370070172104,
44.374325392439658,
44.464397413924388,
44.232421909366167,
44.042976108584156,
43.963084344260913,
44.31246870298628,
44.446517368351401,
44.944936557806528,
45.502731967964991,
45.872993605336262,
46.31224327981721,
46.882182651564285,
47.705129835812357,
48.005214878131255,
47.868995802609874,
48.293827752481377,
48.845060255738787,
48.863508742066983,
49.194651320193316,
49.543518914595751,
std::numeric_limits<double>::quiet_NaN(),
167.2168013857696,
167.84487674384502,
167.515181105822876,
167.180007765977791,
167.2168013857696,
std::numeric_limits<double>::quiet_NaN(),
166.79315799384085,
166.649859247095492,
166.6291369977464,
167.107712437201485,
167.270028111030229,
167.001207310247935,
166.79315799384085,
std::numeric_limits<double>::quiet_NaN(),
134.210133905168846,
134.112775506730941,
134.290335728085836,
134.499625278867882,
134.727001580952162,
134.724624465066711,
134.210133905168846,
std::numeric_limits<double>::quiet_NaN(),
-48.660616014182523,
-48.1513964503784,
-46.662856818210983,
-45.15475765642109,
-43.920827806155742,
-43.48994971370611,
-43.372437506674387,
-43.333266770997142,
-44.880536668464266,
-46.506173875502029,
-48.386420864441831,
-50.482106899606457,
-52.851988084511788,
-54.16425940613162,
-53.987991095584036,
-51.853134324742157,
-50.991326463410587,
-50.364594692574755,
-49.914131232286493,
-49.306958991073117,
-48.660616014182523,
std::numeric_limits<double>::quiet_NaN(),
-66.29003089055513,
-64.037687750897675,
-61.883245612217181,
-61.138975796133479,
-60.610119188058441,
-59.572094692611586,
-59.865849371974733,
-60.159655727770193,
-62.255393439367111,
-64.48812537296979,
-65.741666429289907,
-65.741666429289907,
-66.29003089055513,
std::numeric_limits<double>::quiet_NaN(),
-73.915818651002297,
-73.23033077665059,
-72.07471655952358,
-71.780961880160419,
-71.722179938428411,
-71.741791144483187,
-71.173815477163203,
-70.253251512315771,
-69.724446580673032,
-69.489422166609586,
-69.058518235943808,
-68.725541144471123,
-68.451345994730431,
-68.333833787698723,
-68.510127936462439,
-68.784297247986984,
-69.959470994736478,
-71.07588863797011,
-72.388134121373781,
-71.898499925408288,
-73.073621995725489,
-74.190039638959121,
-74.953894822881452,
-75.012625088181167,
-73.915818651002297,
std::numeric_limits<double>::quiet_NaN(),
-102.330725063876386,
-101.703967454824408,
-100.430918545314086,
-98.981549648823915,
-97.884743211645059,
-96.787936774466189,
-96.200349901091442,
-96.983764614636229,
-98.198083258846822,
-99.432013109112177,
-100.783455166409254,
-101.801868455801369,
-102.330725063876386,
std::numeric_limits<double>::quiet_NaN(),
-122.621734585441928,
-122.406243862784819,
-121.211510586412857,
-119.918850470847786,
-118.724143032691956,
-119.29211870001194,
-120.23221635626571,
-121.622829149240019,
-122.621734585441928,
std::numeric_limits<double>::quiet_NaN(),
-127.283129645681925,
-126.558471035652985,
-125.559565599451076,
-124.03188106982256,
-124.619467943197321,
-125.91217973519467,
-127.283129645681925,
std::numeric_limits<double>::quiet_NaN(),
165.779989862326374,
166.599991489933842,
167.120011428086912,
166.740034621444806,
166.18973229396866,
165.474375441752215,
164.829815301775682,
164.167995233413649,
164.029605747736014,
164.459967075862721,
165.02003624904205,
165.46000939357512,
165.779989862326374,
std::numeric_limits<double>::quiet_NaN(),
152.640016717742526,
153.019993524384688,
153.14003787659874,
152.827292108368283,
152.63867313050298,
152.406025832324929,
151.953236932583536,
151.384279413050024,
150.662049595338829,
150.939965448204475,
151.479984165654571,
151.820015090135087,
152.239989455371131,
152.640016717742526,
std::numeric_limits<double>::quiet_NaN(),
151.301390415653884,
150.754447056276661,
150.241196730753813,
149.709963006793316,
148.890064732050462,
148.318936802360668,
148.401825799756864,
149.298411900020824,
149.845561965127217,
149.996250441690279,
150.139755894164864,
150.236907586873542,
150.80746707580812,
151.089672072554038,
151.647880894170896,
151.537861769821461,
152.136791620084296,
152.338743117480931,
152.318692661751697,
151.982795851854519,
151.459106887008659,
151.301390415653884,
std::numeric_limits<double>::quiet_NaN(),
162.119024693040899,
162.398645868172196,
161.700032180018354,
161.319796991214758,
161.917383254238018,
162.119024693040899,
std::numeric_limits<double>::quiet_NaN(),
161.679981724289121,
161.529396600590587,
160.788253208660535,
160.579997186524338,
160.920028111004854,
161.280006138349989,
161.679981724289121,
std::numeric_limits<double>::quiet_NaN(),
160.852228631837875,
160.4625883323572,
159.849447463214119,
159.640002883135139,
159.70294477766663,
160.362956170898428,
160.688517694337236,
160.852228631837875,
std::numeric_limits<double>::quiet_NaN(),
159.640002883135139,
159.875027297198585,
159.917401971677918,
159.133677199539363,
158.586113722974687,
158.211149530264834,
158.359977655265425,
158.8200012555277,
159.640002883135139,
std::numeric_limits<double>::quiet_NaN(),
157.140000441718882,
157.538425734689213,
157.339419793933246,
156.902030471014825,
156.491357863591304,
156.542827590153991,
157.140000441718882,
std::numeric_limits<double>::quiet_NaN(),
154.759990676084385,
155.062917922179338,
155.547746209941693,
156.019965448224809,
155.880025669578401,
155.599991082988765,
155.166994256815144,
154.729191522438384,
154.514114211239644,
154.652503696917279,
154.759990676084385,
std::numeric_limits<double>::quiet_NaN(),
176.8858236026052,
176.508017206119263,
176.012440220440226,
175.239567499082966,
175.067898391009351,
174.650972935278475,
175.227630243223558,
174.900156691789903,
173.824046665743936,
173.852261997775315,
174.57480187408035,
174.743473749080977,
174.696964960018278,
174.292028436579187,
174.31900353423552,
173.840996535535709,
173.054171177459608,
172.636005487353771,
173.007042271209457,
173.551298456107475,
174.329390497126212,
174.612008905330441,
175.336615838927116,
175.357596470437613,
175.808886753642525,
175.958490025127503,
176.763195428776555,
177.438813104560495,
178.010354445708657,
178.517093540762744,
178.274731073313831,
177.970460239979275,
177.206992629299179,
176.939980503647064,
177.032946405340113,
176.8858236026052,
std::numeric_limits<double>::quiet_NaN(),
169.667814569373149,
170.524919875366152,
171.125089960004004,
171.569713983443251,
171.948708937871857,
172.097227004278693,
172.798579543344033,
173.02037479074076,
173.247234328502088,
173.95840538970279,
174.247586704808157,
174.24851688058942,
173.876446568087943,
173.222739699595706,
172.711246372770745,
173.080112746470149,
172.308583612352493,
171.452925246463622,
171.185137974327176,
170.616697219116531,
169.831422154009289,
169.332331170934282,
168.411353794628553,
167.763744745146823,
166.676886021184174,
166.509144321964669,
167.046372512071002,
168.303763462596862,
168.949408807651565,
169.667814569373149,
std::numeric_limits<double>::quiet_NaN(),
147.689259474884182,
148.289067824495987,
148.35986453673587,
148.017301467073025,
147.914051955353841,
147.564564243763925,
146.870343052354883,
146.663327264593647,
146.048377720320332,
145.431929559510593,
145.29509036680173,
144.718071323830657,
144.743754510679707,
145.397978143494811,
146.364120721623692,
146.908583612250879,
147.689259474884182,
std::numeric_limits<double>::quiet_NaN(),
126.148713820501143,
125.088623488465657,
124.221647983904916,
124.028946567888511,
123.659666782730767,
122.811036411633637,
122.183064406422801,
121.299190708502593,
120.580268182458056,
119.893695103028222,
119.298899367348753,
119.00734093635802,
118.505717808100798,
118.024971958489488,
117.29550744025741,
116.625109084134948,
115.564346958479661,
115.026808709779573,
115.048616164206763,
115.545123325667078,
115.714673700016704,
115.679378696761347,
115.801645135563945,
115.689610630355162,
115.160909051576994,
114.997043084779477,
115.040037876446291,
114.641974318502008,
114.616497837382099,
114.173579136208474,
114.048883905088161,
113.477497593236919,
113.338953078262421,
113.778357782040217,
113.440962355606558,
113.936901076311671,
114.232852004047231,
114.216160516416977,
113.721255324357699,
113.625343866023968,
113.393523390762638,
113.502043898575593,
113.706992629045146,
113.843418410295669,
113.736551548316086,
114.149756300921894,
114.225307244932623,
114.647762078918703,
115.460167270979241,
115.947372674627019,
116.711615431791529,
117.166316359527713,
117.441545037914238,
118.229558953932994,
118.836085239742744,
118.987807244951682,
119.252493931150667,
119.805225050944514,
120.856220330896676,
121.39985639860717,
121.655086297696727,
122.241665480641785,
122.286623976735711,
122.312772251475394,
123.012574497571933,
123.433789097183038,
123.859344517106592,
123.503242222183289,
123.817073195491844,
124.258286574399847,
124.379726190285751,
124.926152785340037,
125.167275018413875,
125.670086704613809,
125.685796340030549,
126.125149367376082,
126.142822707219864,
126.582589146023736,
127.065867140817318,
127.804633416861961,
128.359689976108939,
128.985543247595842,
129.621473423379655,
129.409600050982931,
129.888640578328591,
130.339465773642928,
130.183506300986039,
130.617795037966971,
131.223494500859999,
131.735091180549546,
132.575298293183096,
132.557211541880974,
131.824698114143644,
132.357223748911395,
133.019560581596352,
133.550845981989085,
134.393068475482039,
134.678632440326965,
135.298491245667947,
135.882693312727611,
136.258380975489501,
136.492475213771684,
136.951620314684988,
136.685124953355796,
136.305406528875096,
135.961758254134168,
136.077616815332533,
135.783836297753226,
135.4286641786112,
135.500184360903177,
136.29517459528131,
137.06536014215942,
137.580470819244795,
138.303217401278971,
138.585164015863427,
139.108542922115475,
139.260574985918197,
140.215142043213689,
140.875411818606949,
141.071110467696258,
141.274095493738741,
141.398222284103838,
141.702183058844639,
141.563380161708665,
141.635520461188094,
141.519868605718898,
141.650920038011066,
141.842691278246207,
141.686990187750837,
141.928629185147599,
142.118488397387978,
142.143706496346397,
142.51526004452495,
142.797310011973991,
142.866763136974271,
143.115946893485727,
143.158631626558758,
143.522123651299808,
143.597157830987612,
143.561811151299992,
143.922099237238911,
144.563713820574833,
144.894856398701165,
145.374723748963504,
145.271991001567244,
145.485259637635806,
145.636981642844717,
145.888852573835322,
146.16030887266453,
146.063673944278719,
146.387478469019641,
147.471081577747896,
148.177601760042421,
148.848413527623222,
148.717465448195583,
149.289420200802056,
149.678337030230693,
150.077382440388533,
150.482939081015161,
150.727265252891129,
150.899554478152254,
151.609175246384268,
152.07353966695905,
152.855197381805908,
153.136162144176808,
153.161948683890444,
153.092908970348503,
153.569469028944184,
153.512108189100218,
153.339095493786999,
153.069241164358857,
153.089550002249553,
152.891577590139377,
152.450002476205327,
151.709117466436737,
151.343971795862387,
151.010555454715188,
150.714139439089024,
150.32821984273329,
150.075212030232308,
149.946124302367195,
149.997283970336127,
149.423882277625523,
148.304622430615836,
147.38173302631526,
146.922122837511324,
146.317921991154776,
145.489652134380606,
144.876976353128157,
145.032212355732952,
144.485682407814068,
143.60997358619602,
142.745426873952965,
142.178329705981923,
141.606581659104677,
140.638578729413268,
139.992158237874264,
139.8065881695141,
139.574147577065276,
139.082808058834132,
138.120747918856352,
138.449461704664941,
138.207564325106716,
137.719170363516184,
136.829405552314711,
137.352371047108477,
137.503886346588274,
137.890116001537706,
137.810327590079055,
136.996837192940404,
136.372017450099349,
135.989043410384284,
135.208212518454047,
135.239218377829161,
134.613416782774607,
134.085903761939164,
134.273902622617015,
132.990776808809755,
132.288080682504869,
131.326330601120844,
129.535793898639724,
128.240937534702255,
127.102867466338296,
126.148713820501143,
std::numeric_limits<double>::quiet_NaN(),
81.787959018891399,
81.637322218760588,
81.218019647144331,
80.348356968104412,
79.872468703128533,
79.695166863935128,
80.147800734379643,
80.838817986986555,
81.304319289071771,
81.787959018891399,
std::numeric_limits<double>::quiet_NaN(),
129.370997756060945,
130.471344028851775,
130.834836053592824,
129.990546502808172,
129.155248651242346,
128.590683628453633,
127.898891229362349,
128.135879347852836,
129.370997756060945,
std::numeric_limits<double>::quiet_NaN(),
126.874922723498855,
126.183802118027359,
125.989033644719257,
127.000651483264974,
127.249215122588907,
126.874922723498855,
std::numeric_limits<double>::quiet_NaN(),
127.932377557487484,
128.004156121940866,
128.594559360875508,
128.688248732620707,
128.635952183141342,
128.120169712436109,
127.968034295768859,
128.379998813999691,
128.100015903842291,
127.696474644075067,
127.399490187693686,
127.600511509309058,
127.932377557487484,
std::numeric_limits<double>::quiet_NaN(),
122.927566766451804,
124.077522414242878,
125.065989211121803,
125.240500522971502,
124.437035353697397,
123.685504998876695,
122.723083123872868,
121.056724888189109,
120.183083123862716,
120.040869582195484,
120.935905389490728,
121.475820754076196,
123.340564813328456,
123.25839928598441,
122.822663608899319,
122.388529901215293,
121.508273553555512,
122.454572381684301,
122.271896193532498,
123.170962762546552,
123.162332798353802,
122.628515252778755,
122.236394484548015,
122.719569126477012,
121.738233677254357,
121.489463332201268,
121.619171177253861,
120.898181593917656,
120.972388950688782,
120.305452915529855,
120.390047235191673,
120.430716587405371,
119.796543410319487,
119.366905552244887,
119.653606398600175,
119.498835483886012,
119.078344354327044,
118.767768996252869,
119.18097374885869,
119.323393996255106,
119.82599897672587,
120.035701938966298,
120.885779250167616,
121.666816847826965,
122.927566766451804,
std::numeric_limits<double>::quiet_NaN(),
120.295014276206885,
118.967808465654713,
119.900309686361567,
120.425755649905341,
120.775501743656747,
120.715608758630452,
120.295014276206885,
std::numeric_limits<double>::quiet_NaN(),
121.341668735846511,
122.007364536630433,
122.903537225436068,
122.756982863456315,
121.2544905945701,
119.924390903809581,
119.920928582846045,
120.715091994307571,
121.341668735846511,
std::numeric_limits<double>::quiet_NaN(),
118.260616489740443,
118.878459914222077,
119.126506789223072,
117.970401645989284,
117.277730747549015,
116.740140822416649,
117.083737420725299,
117.632024367342098,
117.900018345207755,
118.260616489740443,
std::numeric_limits<double>::quiet_NaN(),
108.486846144649263,
108.623478631628956,
110.539227329553285,
110.759575636845852,
112.614811232556406,
112.978768345188058,
114.478935174621142,
115.705526971501058,
114.564511346496488,
113.464733514460846,
112.559672479300971,
111.522061395312448,
110.586149530074323,
109.427667270955112,
108.693655226681329,
108.27776329959633,
106.454102004016121,
106.280624220812314,
105.365486281355516,
106.051645949327025,
107.265008579540194,
108.072091099074669,
108.486846144649263,
std::numeric_limits<double>::quiet_NaN(),
104.369991489684892,
104.539490187602212,
104.887892694114015,
105.622111444116968,
106.108593377712651,
105.85744591677414,
105.817655063909399,
104.710384149191441,
103.868213332130779,
102.584260695406897,
102.156173130300999,
101.399113397225065,
100.902502882900151,
100.141980828860653,
99.263739862060277,
98.970011020913262,
98.601351352943055,
97.699597609449853,
97.176942173249842,
96.424016554757259,
95.380876092513503,
95.293026157617291,
95.936862827541745,
97.484882033277103,
98.369169142655664,
99.142558628335806,
99.693997837322414,
100.641433546961622,
101.658012323007341,
102.498271112073226,
103.07684044801303,
103.838396030698362,
103.437645298274902,
104.010788608824043,
104.369991489684892,
std::numeric_limits<double>::quiet_NaN(),
120.833896112146562,
120.323436313967449,
121.180128208502111,
121.527393833503496,
121.262190382981586,
120.833896112146562,
std::numeric_limits<double>::quiet_NaN(),
122.5860889018671,
122.837081333508749,
122.947410516451896,
123.498849725438447,
123.337774285984722,
124.077935825701203,
123.98243777882584,
123.623079868668142,
123.309920688979389,
122.9958313335094,
122.38005496631942,
122.5860889018671,
std::numeric_limits<double>::quiet_NaN(),
126.376813592637447,
126.478512811387887,
126.537423944200611,
126.196772902532587,
125.831420526229067,
125.363852166852212,
125.683160841983693,
125.396511672060626,
124.219787632342388,
123.938719517106904,
124.243662144061275,
123.610160760595193,
123.29607140512519,
122.825505812675374,
122.085499302255727,
121.91992801319256,
122.312358840017055,
122.942397902519588,
123.487687616063468,
123.841154412939829,
124.601469761250215,
124.764612257995623,
125.471390822451554,
125.412117954612768,
126.2227144715431,
126.306636997585144,
126.376813592637447,
std::numeric_limits<double>::quiet_NaN(),
109.475209588663645,
108.655207961056163,
108.62621748254044,
109.119055617308035,
110.211598748822809,
110.786550734502214,
111.010051304164577,
110.570646600386766,
110.339187860151469,
109.475209588663645,
std::numeric_limits<double>::quiet_NaN(),
121.777817824389928,
121.175632358892742,
120.747079705896226,
120.220083449383679,
120.106188592612398,
120.694679803552248,
121.495044386888779,
121.951243931161457,
121.777817824389928,
std::numeric_limits<double>::quiet_NaN(),
141.884600864834965,
140.959489373945814,
140.976335890872974,
140.599769728762112,
140.774074334882584,
140.2532792502451,
138.975527785396196,
137.217598911691255,
135.792983026268928,
135.120982700745401,
135.07943484918269,
133.340316196832021,
132.15677086805124,
130.986144647343451,
132.000036248909964,
131.33279015515734,
130.686317987185987,
130.202419875204896,
130.447676222862128,
129.814691603718927,
129.408411493040262,
130.353935174684636,
130.878450962447175,
131.884229364143891,
132.617672967662429,
134.608300815977714,
135.677537876528845,
136.723830601142424,
137.390611607004473,
138.85760216690619,
139.426404657142825,
140.054790073812001,
139.883379347899847,
140.305782505453635,
141.36897342342661,
141.914263136970476,
141.884600864834965,
std::numeric_limits<double>::quiet_NaN(),
144.613426548439634,
145.320825230083074,
145.543137241802697,
144.059661899999867,
143.183849725517234,
141.6114909201724,
141.067286411706675,
139.955106235920994,
139.81754357315998,
140.312087030193254,
141.380548944259999,
141.671952345953855,
141.967644891527982,
143.142870314709739,
143.910161981379474,
144.613426548439634,
std::numeric_limits<double>::quiet_NaN(),
8.709990675500109,
9.210011834356266,
9.80997521326492,
9.669518670295616,
9.214817742559433,
8.806935662479674,
8.428302443077115,
8.388253208050912,
8.159998406617689,
8.709990675500109,
std::numeric_limits<double>::quiet_NaN(),
8.746009148807559,
9.390000848028876,
9.560016310269134,
9.229752231491773,
8.775723097375362,
8.544212680707773,
8.746009148807559,
std::numeric_limits<double>::quiet_NaN(),
12.370904168353292,
12.690006137755603,
12.089991082414684,
11.043543328504226,
10.903913608451603,
12.370904168353292,
std::numeric_limits<double>::quiet_NaN(),
-4.211494513353671,
-3.005004848635309,
-4.073828497728101,
-3.05500179687769,
-1.959280564776947,
-2.219988165689443,
-3.119003058271176,
-2.08500932454308,
-1.114991013992324,
-0.430484991854172,
0.184981316742039,
0.46997684083172,
1.68153079591471,
1.559987827164207,
1.050561557630942,
1.449865349950244,
0.550333693045587,
-0.787517462558725,
-2.489997524414491,
-2.956273972984065,
-3.617448085942442,
-4.542507900399272,
-5.245023159191136,
-5.776566941745344,
-4.30998979330198,
-3.414850633142152,
-4.984367234710916,
-5.267295701508927,
-4.222346564134966,
-4.770013393564227,
-4.579999152027,
-3.092079637047106,
-2.945008510744429,
-3.630005458989359,
-4.844169073903061,
-5.082526617849339,
-4.719112107756729,
-5.047980922862223,
-5.586397670911253,
-5.644998745130239,
-6.149980841486425,
-5.786824713555276,
-5.009998745127689,
-4.211494513353671,
std::numeric_limits<double>::quiet_NaN(),
-14.508695441129234,
-14.739637417041607,
-13.60973222497981,
-14.909833746794902,
-17.794438035543422,
-18.656245896874992,
-19.97275468594276,
-22.762971971110158,
-21.778484259517683,
-23.955043911219111,
-22.184402635170358,
-22.227423265053332,
-24.326184047939336,
-23.650514695723089,
-22.134922451250887,
-20.57628373867955,
-19.05684160000159,
-17.798623826559052,
-16.167818976292125,
-14.508695441129234,
std::numeric_limits<double>::quiet_NaN(),
142.914615513276544,
143.260847609632094,
143.235267775647628,
143.648007440362846,
144.65414757708561,
143.173927850517202,
142.558668247650132,
143.533492466404027,
143.505277134372648,
142.747700636973832,
142.092030064054541,
141.906925083585008,
142.018442824470867,
141.904444614835029,
142.135800002205713,
142.179983351815281,
141.594075962490024,
141.682546014573688,
142.606934035410745,
142.209748976815433,
142.654786411713019,
142.914615513276544,
std::numeric_limits<double>::quiet_NaN(),
118.504580926590364,
117.174274530100661,
117.664477166821371,
118.38691369026175,
118.98734215706105,
119.511496209797514,
119.689676548339889,
119.029458449378922,
118.504580926590364,
std::numeric_limits<double>::quiet_NaN(),
122.336956821787993,
122.174279412933174,
122.515653924653293,
122.252310825693925,
121.662786086108213,
121.505017938321117,
121.728828566577207,
122.258925409027256,
122.701275669445693,
123.950295037940293,
123.85510704965867,
124.18128869028493,
124.077419061378293,
123.298035109552245,
122.928651971529945,
122.671355015148706,
122.034649692880521,
121.126384718918573,
120.62863732308324,
120.679383579593861,
120.991819289230534,
120.693336216312673,
120.56414513558299,
120.070428501466438,
119.920928582846045,
119.88377322802819,
120.286435988446442,
120.390047235191673,
120.715867140791914,
121.321308221523509,
121.937601353036399,
122.246006300954292,
122.336956821787993,
std::numeric_limits<double>::quiet_NaN(),
122.038370396005547,
121.883547804859091,
122.483821242361486,
123.120216506035945,
123.100837843926456,
122.637713657726692,
122.002610304859573,
121.967366978036523,
122.038370396005547,
std::numeric_limits<double>::quiet_NaN(),
125.502551711123544,
125.783413120629916,
125.01188398651226,
125.032761265158172,
125.277449172060187,
124.801819289245771,
124.760168084818531,
124.459101190286049,
124.302521600441708,
124.891012811381529,
124.877990350444009,
124.266761509295691,
125.227116327007877,
125.502551711123544,
std::numeric_limits<double>::quiet_NaN(),
-77.353360765273862,
-76.836673957003569,
-76.086383836557857,
-75.674600185840063,
-75.664704149056178,
-75.480425991503353,
-74.906895107711989,
-74.276752692344886,
-74.197222663047697,
-73.414763963500292,
-72.627835252559635,
-72.238194953078917,
-71.754090135368642,
-71.399822353791706,
-71.13746110704588,
-71.331583624950298,
-71.360005662710819,
-71.947049933546509,
-71.620868292920193,
-71.633063930941091,
-72.074173956984509,
-71.695644090446535,
-71.264559292267734,
-71.03999935574339,
-71.350083787710787,
-71.400623338492238,
-70.155298834906517,
-70.29384334988103,
-69.943244594996827,
-69.584300096297468,
-68.882999233664449,
-68.23327145045873,
-68.194126552997631,
-67.296248541926332,
-66.227864142507997,
-65.655237596281751,
-64.89045223657817,
-64.329478725833738,
-64.318006557864948,
-63.079322475828732,
-61.880946010980196,
-62.730118984616411,
-62.388511928950976,
-61.58876746280194,
-60.830596686431718,
-60.671252407459733,
-60.15009558779618,
-59.758284878159195,
-59.101684129458661,
-58.482962205628063,
-58.454876064677421,
-58.078103196837375,
-57.542218593970645,
-57.147436489476888,
-55.9493184067898,
-55.841779751190415,
-55.033250291551774,
-53.958044603070903,
-53.618452928264844,
-52.882141282754091,
-51.823342861525902,
-51.657797410678889,
-51.299989793489956,
-51.069771287629656,
-50.508875291533656,
-49.974075893745059,
-49.947100796088712,
-50.699251268096916,
-50.388210822132137,
-48.62056677915632,
-48.584496629416591,
-47.824956427590635,
-46.566583624851226,
-44.905703090990414,
-44.417619187993665,
-44.581588507655781,
-43.418791266440195,
-41.472656826328247,
-39.978665330554037,
-38.500383470196567,
-37.2232521225352,
-36.452937384576387,
-35.597795783010469,
-35.23538896334756,
-34.896029832486832,
-34.729993455533034,
-35.128212042774223,
-35.636966518687714,
-37.046518724096998,
-37.683611619607362,
-38.423876512188443,
-38.673887091616521,
-38.953275722802545,
-38.882298143049653,
-39.161092495264313,
-39.267339240056401,
-39.583521491034233,
-39.760823330227637,
-40.774740770010339,
-40.944756232250612,
-41.754164191238225,
-41.98828426773656,
-43.074703742024752,
-44.647811855637812,
-45.352135789559917,
-46.472093268405537,
-47.648972337420659,
-48.495458136577703,
-48.64100480812774,
-48.474735887228654,
-48.661520351747626,
-48.8884574041574,
-49.587329474472675,
-50.696874152211485,
-51.576226162306156,
-52.256081305538046,
-52.712099982297694,
-53.373661668498244,
-53.806425950726535,
-54.93586605489773,
-55.674089728403288,
-56.215297003796067,
-57.139685024633103,
-57.81786068381551,
-58.427074144104388,
-58.495442064026548,
-57.225829637263658,
-57.36235877137878,
-56.737487352105447,
-56.78828528504836,
-57.749156867083457,
-59.231857062401893,
-61.237445237865643,
-62.335956997310127,
-62.125763108962936,
-62.330530971919494,
-62.145994432205214,
-62.745802781816984,
-63.77049475773255,
-64.732089809819726,
-65.118035244391578,
-64.978560553635816,
-64.303407965742494,
-63.755947842042389,
-63.458059048095876,
-64.378803880456331,
-65.181803961839748,
-65.328823411710133,
-65.565268927661606,
-66.509965786389344,
-67.29379391139247,
-67.580546434180079,
-66.597066413017288,
-65.64102657740149,
-65.985088263600787,
-67.166178961847692,
-67.816087612566434,
-68.728745083273211,
-69.138539191347775,
-68.81556148952356,
-68.149994879820383,
-68.571545376241332,
-69.461284349226673,
-69.942779507106195,
-70.8451016913546,
-71.006332160105245,
-71.429794684520999,
-72.557942877884884,
-73.702756720662904,
-74.946763475225168,
-75.260026007778507,
-74.976632453089877,
-75.479754197883551,
-75.608015102831985,
-75.182769741502156,
-74.126580980104706,
-75.644395311165454,
-74.692153693323121,
-74.351709357384252,
-73.24035600451522,
-72.717803921179794,
-73.388899909138217,
-73.701335618774877,
-74.331943122032612,
-74.017957119427194,
-73.677099372029986,
-73.217592536090649,
-73.505559455037115,
-73.58806087919109,
-73.166717088499297,
-72.553136969681745,
-71.861732143832626,
-71.438450486929895,
-71.668720669222466,
-71.370082567007728,
-71.48989437527645,
-70.905123867461612,
-70.724953986275992,
-70.403965827095021,
-70.091245897080739,
-70.164419725206045,
-70.372572394477714,
-71.375250210236928,
-71.462040778271131,
-73.444529588500416,
-75.237882656541444,
-76.009205084929945,
-76.423469204397747,
-76.25924150257417,
-77.106192389621839,
-78.092152879534638,
-79.036953091126946,
-79.445920376284846,
-79.760578172510051,
-80.537481655586078,
-81.249996304026425,
-80.926346808582437,
-81.410942552399462,
-81.099669562489368,
-80.302560594387216,
-79.770293341780928,
-79.986559210922422,
-80.368783942369248,
-80.967765469064361,
-80.764806281238037,
-80.933659023751716,
-80.583370327461267,
-80.399324713853758,
-80.020898200180369,
-80.090609707342111,
-79.542762010399798,
-78.855258755188714,
-78.99093522817104,
-78.617831387023713,
-78.662118089497852,
-78.427610439757331,
-77.931542527971487,
-77.51043128122501,
-77.12768978545526,
-77.496271938777028,
-77.307601284479404,
-77.533220587865728,
-77.318815070286746,
-77.47666073272228,
-77.881571417945253,
std::numeric_limits<double>::quiet_NaN(),
-74.662543097619874,
-73.838097296835315,
-72.434177822545848,
-71.107721320261902,
-70.591783820259835,
-70.267488369412177,
-69.345658331973596,
-68.63412553574679,
-68.250014614521305,
-67.749993455665134,
-66.449995286714625,
-65.050003221279326,
-65.50000159367697,
-66.449995286714625,
-66.959912482354682,
-67.291029222264854,
-68.148625454364648,
-68.639990810811923,
-69.232099372012215,
-69.958075731064582,
-71.00568620470159,
-72.263903978144128,
-73.285211147744576,
-74.662543097619874,
std::numeric_limits<double>::quiet_NaN(),
44.846958042181143,
46.799138624871233,
48.318477410684608,
48.522806023966673,
49.097189568890855,
50.039767693894618,
51.522932977103665,
51.13618655783128,
49.793684523320707,
48.894411248577548,
48.754936557821772,
47.586119012244183,
46.502825962109632,
47.072455275262939,
44.846958042181143,
std::numeric_limits<double>::quiet_NaN(),
53.50828982932515,
55.902458937407658,
55.631932814359686,
57.868643833248854,
61.170044386647476,
64.498368361270167,
66.210925327422842,
68.157059767534804,
68.852211134725081,
68.180572544227601,
64.637326287703019,
61.583507521414759,
58.477082147053352,
56.986785516188029,
55.419335971910925,
55.622837762276333,
57.535692579992315,
56.944979282463883,
53.677375115784173,
53.412016635965394,
51.601894565645665,
51.455753615124216,
52.478275180883543,
52.444168735570877,
54.427613559797578,
53.50828982932515,
std::numeric_limits<double>::quiet_NaN(),
27.407505730913446,
25.92465050629815,
23.024465773213617,
20.075188429451828,
19.897266473070914,
18.462263624757867,
17.368015170977458,
20.45599205901064,
21.907944777115404,
22.919252557067381,
25.447625359811866,
27.407505730913446,
std::numeric_limits<double>::quiet_NaN(),
24.724103631293332,
22.490338169044833,
20.726001417735688,
21.416088494561365,
20.81188764820476,
22.884267612405779,
23.281349318136538,
24.724103631293332,
std::numeric_limits<double>::quiet_NaN(),
15.142827996489387,
15.522546420970059,
16.990828891679058,
18.251837192465359,
21.543832635186874,
19.027397088301797,
18.471720411867295,
17.594409620848154,
17.118211297278549,
15.913168572664349,
13.762602166405742,
14.669575229560424,
13.170596958070035,
11.22229210780182,
10.444561801809131,
13.170751987366913,
13.718522169660758,
15.142827996489387,
std::numeric_limits<double>::quiet_NaN(),
-77.881571417945253,
-78.214936082660117,
-78.429160732726075,
-78.182095709938636,
-78.435465257465694,
-78.622120530903942,
-79.120307176413746,
-79.55787736684519,
-79.760578172510051,
-80.164481167303336,
-80.382659064439622,
-80.4806892564973,
-80.003689948227162,
-80.276670701808996,
-80.42115800649708,
-80.886400926420805,
-81.059542812814726,
-81.189715745757951,
-81.51951473664468,
-81.721311204744467,
-82.131441209628917,
-82.390934414382571,
-82.605494961258415,
-82.82008134635042,
-82.850958014644817,
-82.965783047197363,
-83.508437262694315,
-83.711473965169077,
-83.596313035806645,
-83.632641567707836,
-83.909885626953738,
-84.303401658856359,
-84.647644212568665,
-84.713350796227772,
-84.975660366541334,
-84.91137488477024,
-85.11092342806532,
-85.339488288092269,
-85.66078650586698,
-85.797444831062847,
-85.791708747078431,
-85.659313727546674,
-85.800519578784218,
-85.941725430021762,
-85.712540452807303,
-86.058488328785259,
-86.525849982432959,
-86.745991583996329,
-87.16751624220116,
-87.668493415054712,
-87.557466600275617,
-87.392386237319229,
-87.316654425795491,
-87.489408738947219,
-87.641259935236889,
-87.793111131526572,
-87.904112108089521,
-88.48330156121682,
-88.84322791212972,
-89.256742723329296,
-89.812393561547665,
-90.095554572290979,
-90.608624030300845,
-91.232410244496052,
-91.689746670279135,
-92.227750006869826,
-93.359463874061859,
-93.875168830118611,
-94.691656460330194,
-95.250227016973056,
-96.05338212765335,
-96.557434048228288,
-97.263592495496738,
-98.013029954809639,
-98.9476757474566,
-99.697397427147109,
-100.829498867581322,
-101.666088629954473,
-101.918528001700253,
-102.47813208698895,
-103.500989549558142,
-103.917527432046811,
-104.99200965047558,
-105.493038499761425,
-105.73139604370769,
-105.397772996831364,
-105.500660773524487,
-105.270752326257934,
-105.26581722697405,
-105.603160976975417,
-105.69341386597317,
-106.028716396898986,
-106.909980434988455,
-107.915448778091431,
-108.401904873470983,
-109.260198737406725,
-109.444089321717343,
-109.29164384645631,
-109.801457689231796,
-110.391731737085706,
-110.641018846461719,
-111.178918830187826,
-111.759606899851605,
-112.22823462609044,
-112.27182369672866,
-112.809594489374049,
-113.163810594518679,
-113.148669399857155,
-113.871881069781907,
-114.205736660603563,
-114.776451178835018,
-114.936699795372121,
-114.771231859173554,
-114.673899298951795,
-114.330974494262932,
-113.588875088335485,
-113.424053107540544,
-113.271969367305573,
-113.14003943566442,
-112.962298346796516,
-112.761587083774884,
-112.457910529411706,
-112.244951951936883,
-111.616489020619255,
-111.284674648873136,
-110.987819383572472,
-110.710006883571367,
-110.655048997828956,
-110.172856208113487,
-109.77184709352855,
-109.409104377055755,
-109.433392300232924,
-109.854219326601793,
-110.031391974714481,
-110.295070970483764,
-110.949501309028051,
-111.670568407012709,
-112.182035895621524,
-112.148988817170874,
-112.300710822379813,
-112.777296719191625,
-113.464670783321964,
-113.596729906043848,
-113.84893673384434,
-114.46574662968014,
-115.055142178185093,
-114.98225257043741,
-114.570365566855031,
-114.199328782999387,
-114.162018398884655,
-114.93184221073669,
-115.51865393762705,
-115.887365282029577,
-116.258350389452929,
-116.721526252085013,
-117.127754686331414,
-117.295937691273906,
-117.944,
-118.410602275897574,
-118.519894822799827,
-119.081,
-119.438840642016743,
-120.367789476383436,
-120.622864346176129,
-120.744329800278166,
-121.714580654774238,
-122.54747555223851,
-122.511999681470144,
-122.953187222162001,
-123.727196825029679,
-123.865172899248989,
-124.398060269042787,
-124.178848843260653,
-124.213704596841524,
-124.53284,
-124.14214,
-124.020535,
-123.89893,
-124.079635,
-124.39567,
-124.687210083007798,
-124.56610107421875,
-123.12,
-122.587369757967835,
-122.339994676586642,
-122.500010749178415,
-122.84,
-122.97421,
-124.910251227703711,
-125.624600389490411,
-127.435600959159089,
-127.992750413913939,
-127.850330166517537,
-129.129786953632021,
-129.305228441262926,
-130.514973721215682,
-130.536109382023056,
-131.085817430527868,
-131.967210659698054,
-132.250009935415335,
-133.539181891800695,
-134.078063727740357,
-135.038211839723374,
-136.628063117398995,
-137.80000708713024,
-139.867787848857262,
-140.825274624577247,
-142.574444343008736,
-143.958881802324157,
-145.92555762427213,
-147.114373949146682,
-148.224306200127671,
-148.018065558850822,
-148.570822516860829,
-149.727857835875881,
-150.608243374616393,
-151.716392788683322,
-151.859433153267219,
-151.409719001247197,
-150.346941494732533,
-150.621110806257064,
-151.895839199816862,
-152.578329841095609,
-154.019172126257644,
-153.287511359653138,
-154.232492438758499,
-155.307491421510178,
-156.308334723923053,
-156.55609737854644,
-158.117216559867785,
-158.433321296197164,
-159.603327399717472,
-160.289719611634268,
-161.223047655257801,
-162.237766079741021,
-163.069446581046435,
-164.785569221027231,
-164.942226325520096,
-163.848339606765705,
-162.870001390615954,
-161.804174974596066,
-160.56360470278122,
-160.070559862284455,
-158.68444291891953,
-158.461097378554058,
-157.722770352183915,
-157.550274421193649,
-157.041674974577006,
-158.194731208305598,
-158.517217984023034,
-159.058606126928851,
-159.711667040017375,
-159.981288825500229,
-160.355271165996527,
-161.355003425115115,
-161.968893602526379,
-162.054986538724705,
-161.874170702135416,
-162.51805904849212,
-163.818341437820237,
-164.662217577146578,
-165.346387702474829,
-165.35083187565192,
-166.121379157556021,
-165.734451870770641,
-164.919178636717902,
-164.562507901039396,
-163.753332485997134,
-163.067224494457889,
-162.260555386381753,
-161.534449836248626,
-160.772506680321101,
-160.95833513084267,
-161.518068407212155,
-160.777777676414871,
-161.391926235987654,
-162.45305009666896,
-162.757786017894148,
-163.54639421288428,
-164.960829841145141,
-166.42528825586453,
-166.845004238939168,
-168.110560065767118,
-166.70527116602193,
-164.474709642575505,
-163.652511766595637,
-163.788601651036288,
-161.67777442121016,
-162.489714525380066,
-163.719716966791196,
-164.430991380856568,
-165.390286831706732,
-166.764440680996103,
-166.204707404626703,
-164.430810513343516,
-163.168613654614546,
-162.930566169262022,
-161.908897264635556,
-160.934796515933726,
-159.039175788387098,
-158.119722866833939,
-156.580824551398081,
-155.067790290324325,
-154.344165208941234,
-153.900006273392563,
-152.210006069935304,
-152.270002407826155,
-150.739992438744508,
-149.720003018167517,
-147.613361579357019,
-145.689990607669642,
-144.920011766520702,
-143.589446987869565,
-142.072511156157759,
-140.985988329004982,
-139.120520799700643,
-137.546353319225602,
-136.50357459200788,
-135.625747036665814,
-134.414632331257337,
-132.929244961459716,
-131.43135189504747,
-129.794707607931571,
-129.107721117043411,
-128.361565111181051,
-128.138167894383258,
-127.447124803560186,
-125.75632361540238,
-124.424828660969979,
-124.289668952310578,
-123.061087612787432,
-122.683487922030722,
-121.472269863757646,
-119.942880011863508,
-117.602686937309869,
-116.226440192512698,
-115.246887580204088,
-113.897951829873193,
-115.304894375451724,
-113.497278612098143,
-110.798011847764428,
-109.946177537865182,
-108.880196092548417,
-107.792381354588358,
-108.812990892352843,
-108.167216356217438,
-106.950003831798512,
-106.150000983488013,
-105.342815111088953,
-104.337915208741194,
-103.221161668697661,
-101.454344448638494,
-99.901958584374484,
-98.443210415423323,
-98.558603888731085,
-97.669485032933267,
-96.11991553422915,
-96.125884162158854,
-95.489437222052146,
-94.684990200564556,
-94.232821418010658,
-95.304073859421194,
-96.471315273813872,
-96.391139289113042,
-95.208808356491119,
-93.88997412797022,
-92.878175421911479,
-91.519653693390424,
-92.406912197625758,
-90.547103237657367,
-90.551495734402181,
-89.215143195334335,
-88.019660610694132,
-88.317497728208338,
-87.350166592136759,
-86.306070115895622,
-85.576631435879676,
-85.52198360873102,
-84.100804206056083,
-82.622574022130877,
-81.280433722646322,
-81.220204840810155,
-81.964371304029285,
-81.259272223622816,
-81.386525438141561,
-83.344571295896785,
-84.73541663281641,
-85.769436204760652,
-86.067609219084787,
-87.031426357760495,
-87.323243170912704,
-88.482965664406919,
-89.914428677107963,
-90.703992886095506,
-90.770035366564514,
-91.933426886751462,
-93.156969774126139,
-94.241528896851833,
-94.629308844770051,
-94.684602627322363,
-93.215028245806053,
-92.764616461950098,
-92.297022264357082,
-90.897676154325438,
-89.039520840190406,
-88.039788581071818,
-87.324199184910086,
-86.071200731129039,
-85.011808030929487,
-83.360539313474959,
-82.272853766595645,
-82.436202969070237,
-82.125033332024699,
-81.400736457021807,
-79.912894456690353,
-79.143018968406011,
-78.601915045877817,
-79.124208747051782,
-79.829566209619713,
-78.228733690082052,
-77.095598721002006,
-76.541368984671664,
-76.623198615205837,
-77.302252773737195,
-78.516881476541528,
-77.336746792292018,
-77.772715013322411,
-78.106880662737808,
-77.41066992868555,
-75.696200934538069,
-74.668201666955838,
-73.839880133749389,
-72.908541632769101,
-71.677092251253754,
-71.373699917268169,
-69.59042375352405,
-69.620318569604905,
-69.28788408067129,
-68.374554816344713,
-67.649767015235042,
-66.201767544200607,
-65.245185106045739,
-64.583520066980583,
-63.804756232342065,
-62.502355109289987,
-61.396556972892306,
-61.798651292555384,
-60.468525763578711,
-59.569614223861585,
-57.975086229063535,
-57.333213263566165,
-56.93688086610365,
-56.15811703146511,
-55.756306932179655,
-55.683391486215825,
-56.409161139539037,
-57.126920945857009,
-58.774830695212557,
-60.033100145087388,
-61.723668789299879,
-63.862504645428231,
-65.363317430264956,
-66.399042324474834,
-67.236303880467759,
-68.511135626892141,
-69.953631557887491,
-71.104569057892093,
-70.255215216742869,
-68.649990200460394,
-66.552443813733262,
-65.056256069586652,
-64.170987107994563,
-65.115451422776985,
-64.798545701747074,
-64.472183193607748,
-63.173296067951512,
-61.520709601473534,
-60.518135138578913,
-60.448604498930194,
-59.802881639227103,
-61.039886237213807,
-63.25471228702736,
-64.246563890221424,
-65.364066738533197,
-66.123400234629983,
-66.161718309174404,
-64.42549353703204,
-66.026041836192093,
-67.13742102727727,
-66.96466,
-68.03252,
-69.06,
-70.11617,
-70.645475633411081,
-70.814896816680005,
-70.82499955919306,
-70.494993862577161,
-70.080006273057265,
-70.184986945258203,
-69.884979417587743,
-69.965026211207856,
-70.639997931588141,
-71.120382046173404,
-71.85382564969197,
-72.294987352167681,
-72.8764247300997,
-73.71,
-72.241243862584142,
-71.945008714470973,
-73.345000779906258,
-73.981990322552036,
-73.952325,
-74.256702236615638,
-73.96244,
-74.178386603477307,
-74.906042446579178,
-74.980404832647181,
-75.200029669887641,
-75.52804582386031,
-75.319996507453226,
-75.071834764789827,
-75.05673,
-75.377460700161791,
-75.94024288603643,
-76.031270921518569,
-75.72205,
-76.23287,
-76.35,
-76.542725,
-76.32933,
-76.989997931613544,
-76.30162,
-76.25874,
-75.9718,
-75.86805091012468,
-75.727491014290791,
-76.363188646129274,
-77.397635,
-78.05496,
-78.554346889953138,
-79.06067,
-79.20357,
-80.301325,
-80.86498,
-81.33629,
-81.490420905264372,
-81.31371,
-80.979986945301391,
-80.535585,
-80.529988572903761,
-80.05653928497766,
-80.088015,
-80.13156,
-80.38103,
-80.680005255847064,
-81.172119920562579,
-81.329991421214245,
-81.709994066072525,
-82.240013393874136,
-82.70515,
-82.85526,
-82.650014207677856,
-82.93,
-83.70959,
-84.1,
-85.10882,
-85.28784,
-85.7731,
-86.399992031586095,
-87.530362311538539,
-88.417827521503028,
-89.18049,
-89.593831178419791,
-89.41373,
-89.43,
-89.21767,
-89.40823,
-89.77928,
-90.15463,
-90.880225,
-91.626785,
-92.49906,
-93.22637,
-93.84842,
-94.690002814496864,
-95.600257331102057,
-96.594046800507073,
-97.140008307670726,
-97.369994269585703,
-97.379993659234174,
-97.329996710991807,
-97.140008307670726,
-97.528072475966553,
-97.702945522842242,
-97.776041836319109,
-97.872366706111151,
-97.699043952204207,
-97.388959520236824,
-97.18933346229332,
-96.525575527720335,
-96.292127244841808,
-95.900884975960039,
-94.839063483442771,
-94.425729539756219,
-93.548651292682393,
-92.786113857783505,
-92.037348192090406,
-91.40790340855925,
-90.771869879910852,
-90.533589850613055,
-90.451475999701259,
-90.278618333684932,
-89.601321173851503,
-88.543866339862888,
-87.658416510757803,
-87.051890224948082,
-86.811982388033044,
-86.84590796583268,
-87.383291185235862,
-87.621054450210764,
-87.436750454441793,
-87.58656043165594,
-87.837191128271527,
-88.09066402866317,
-88.300031094093697,
-88.296336229184817,
-88.106812913754382,
-88.123478563168504,
-88.285354987322805,
-88.197866787452654,
-88.302640753924436,
-88.239517991879907,
-88.355428229510565,
-88.55182451043585,
-88.732433641295941,
-88.930612759135272,
-88.604586147805847,
-88.51836402052686,
-88.189986131528144,
-88.121153123715374,
-87.901812506852508,
-87.615680101252423,
-87.522920905288501,
-87.367762417332159,
-86.903191291028207,
-86.440945604177401,
-86.119233974944336,
-86.001954311857929,
-85.68331743034625,
-85.44400387240259,
-85.182443610357268,
-84.983721889978867,
-84.526979743167146,
-84.368255581382655,
-84.063054572266864,
-83.773976610026111,
-83.410381232420491,
-83.147219000974133,
-83.233234422523935,
-83.284161546547594,
-83.182126430987282,
-83.412499966144452,
-83.519831916014681,
-83.552207200845544,
-83.498515387694269,
-83.473323126951982,
-83.626104499022915,
-83.719613003255063,
-83.650857510090717,
-83.855470343750397,
-83.808935716471552,
-83.655611741861577,
-83.59000851106704,
-83.402319708982958,
-83.015676642575173,
-82.546196255203483,
-82.187122565423408,
-82.207586432610967,
-81.808566860669288,
-81.714154018872037,
-81.439287075511544,
-80.947301601876759,
-80.521901211250082,
-79.914599778955989,
-79.573302781884308,
-79.021191779277927,
-79.058450486960368,
-78.500887620747193,
-78.055927700498017,
-77.729513515926413,
-77.353360765273862,
std::numeric_limits<double>::quiet_NaN(),
-71.712361416292964,
-71.587304450146632,
-71.380004442007788,
-70.806706102161741,
-70.214364997016133,
-69.950815192327582,
-69.769250047470081,
-69.222125820579876,
-69.254346076113848,
-68.809411994080833,
-68.317943284768972,
-68.689315965434517,
-69.164945848248919,
-69.623987596297638,
-69.952933926051543,
-70.133232998317894,
-70.517137213814223,
-70.669298468697633,
-70.999950120717187,
-71.400209927033899,
-71.657661912712015,
-71.708304816358051,
-72.372476162389347,
-72.844411180294884,
-73.454554816365032,
-73.922433234335656,
-74.458033616824778,
-74.369925299767132,
-73.449542202432724,
-72.694937099890637,
-72.334881557897006,
-72.791649542924887,
-72.784104783810278,
-73.415022345661754,
-73.189790615517623,
-72.579672817663621,
-71.712361416292964,
std::numeric_limits<double>::quiet_NaN(),
14.761249220446189,
15.520324334381513,
15.160242954171736,
15.309897902089006,
15.099988234119422,
14.335228712631988,
13.826732618879959,
12.431003859108756,
12.570943637755136,
13.741156447004613,
14.761249220446189,
std::numeric_limits<double>::quiet_NaN(),
37.539135369625853,
38.679995965333546,
39.955008579270924,
std::numeric_limits<double>::quiet_NaN(),
132.371176385630235,
132.924372593314729,
133.492968377822194,
133.904106073136347,
134.638428176003856,
134.766379022358535,
134.203415968970887,
133.792950067276536,
133.280268182508848,
133.014858026257798,
132.363114862192674,
132.371176385630235,
std::numeric_limits<double>::quiet_NaN(),
180.000000441810386,
178.599982538158855,
175.72403,
173.64391,
170.45345,
170.0082,
170.81688,
169.57763,
167.862952358686726,
165.94037,
164.05248,
162.27907,
160.94053,
159.70866,
159.83031,
158.99779,
157.00688,
152.968885532848049,
150.351164178670899,
149.500001662391469,
140.46817,
139.14791,
139.86983,
138.23409,
137.49755,
135.56193,
133.85766,
132.2535,
131.28855512911548,
129.71599,
128.46,
129.05157,
128.59126,
126.97644,
125.38,
123.25777,
123.20067671111434,
119.02,
118.77633,
115.56782,
113.96881,
113.52958,
113.01954,
112.11919,
110.64,
109.4,
110.15125,
112.779193963676846,
113.88539,
114.13417,
113.33151,
111.07726,
108.153739862095847,
107.239997186310958,
106.970142856882759,
104.705009800233086,
106.066632114691657,
104.35159467978896,
101.990808546967031,
101.035311313890276,
100.759669224045425,
98.922572056069342,
96.678212925200981,
95.860019972723734,
93.234237095109094,
92.90061404823274,
90.25994835811801,
88.315674269568589,
87.166803826855642,
86.009561802111421,
86.822328729198006,
84.655225864605995,
82.249998000013051,
80.511086053391494,
80.610718214850252,
81.500017938161079,
79.652017042971423,
77.576639845697485,
75.90313,
76.35911,
75.28898,
75.68351,
75.15801,
74.65926,
74.89082,
73.1011,
74.3998,
73.60187,
73.84236,
74.93584,
74.46926,
75.052,
74.18651,
73.92099,
72.82077,
72.42301,
71.28,
73.2387,
73.66787,
72.564697707005578,
72.79188,
72.47011,
71.84811,
72.79603,
72.58754,
69.94,
69.19636,
68.54006,
66.69466,
66.72492,
67.25976,
66.93008,
68.13522,
68.16444,
69.18068,
68.51216,
64.888115,
63.504010451109934,
60.550030552009559,
60.03,
61.07784,
59.94142,
58.802,
57.31702,
55.44268,
54.753014637135081,
53.48582,
54.47171,
53.71743,
48.13876,
47.89416,
46.34915,
45.562004835803783,
45.55517,
46.82134,
46.250024855337792,
43.452831251810977,
44.174789664369463,
43.698397658061971,
44.532248569523638,
43.94975,
43.01604,
42.09309,
39.7626,
40.4356,
39.59345,
37.17604,
36.539579035089687,
37.14197,
37.01273,
36.23129,
34.94391,
34.878574253078739,
34.81477,
33.18446577325426,
33.918684523257213,
38.382959832519845,
40.01583,
41.125944858572495,
41.059850701671195,
40.29235232927229,
36.513978305819677,
33.77548912937641,
32.132747023250062,
31.101078728975097,
30.005435011522792,
31.293418409965454,
28.165547316202943,
26.370049676221811,
24.546543409938465,
23.023742303161526,
21.378416375420585,
19.184028354578459,
16.435927361728943,
14.761145867581604,
12.358346795306373,
10.527709181366758,
8.553411085655739,
5.912900424837886,
4.992078077828978,
5.308234490590678,
5.665835402050419,
7.048748406613271,
8.382000359743586,
10.356556837616067,
11.027368605196868,
11.787942335668674,
12.625100538797028,
12.942910597392057,
14.100721062891465,
14.666681349352075,
15.879785597403783,
16.447709588291474,
16.829185011470088,
17.86922488777634,
18.787721795332089,
17.831346062906391,
17.119554884518124,
17.847779168375212,
19.77887576669022,
21.369631381930958,
21.21351687997722,
22.18317345550193,
23.903378533633802,
25.294043003040404,
25.398067661243942,
24.730511508897536,
22.442744174903993,
21.536029493910803,
21.059211053153689,
21.544866163832694,
21.322244093519316,
22.290763787533592,
22.869694858499457,
24.496623976344523,
26.255172967236973,
28.069997592895277,
29.117685581180694,
27.981114129353244,
26.949135776484525,
25.864189080516638,
24.604214308376186,
23.339795363058645,
23.426560092876684,
24.061198357853186,
24.428927850042161,
24.312862583114622,
24.120729607853431,
23.318452996522097,
22.524341261492879,
21.581866489353672,
21.090423618257972,
21.055800408622417,
21.268448927503467,
19.888481479581287,
19.660640089606403,
18.696254510175464,
18.620858595461641,
17.622831658608675,
16.363477003655731,
14.802900424873458,
14.119686313542587,
13.647467075259442,
12.518440382546601,
11.956252475643311,
10.939466993868393,
10.950112338920519,
9.939579705452957,
9.921906365609118,
9.649984978889279,
10.369992710011957,
10.667803989310016,
10.912181837618306,
10.369992710011957,
10.250000034230226,
10.546105991262664,
10.580005730846125,
9.775558709358535,
9.424469028367554,
8.543437534223415,
8.256581658571207,
8.089976840862221,
8.120310906617533,
8.526229282270208,
8.572117954145398,
8.80073449060464,
8.121706170289428,
7.936239454793877,
7.100424838905127,
6.905139601274129,
6.07418257002081,
4.705997348661185,
3.830288527043081,
3.314971144228537,
2.513573032246143,
1.6390010921385,
1.338761020522696,
-0.98946895995536,
-1.933494025063311,
-1.616510789384961,
-3.295813971357803,
-4.592349819344776,
-4.491554938159482,
-2.963276129559603,
-2.225724249673845,
-1.193797573237418,
-1.384225226232985,
-1.901351284177764,
-3.51753170410609,
-4.347842779955783,
-5.411886359061597,
-6.754491746436756,
-7.97818966310831,
-9.392883673530648,
-8.984433152695674,
-9.034817674180246,
-8.990789353867569,
-8.79085323733031,
-8.768684047877102,
-8.977353481471683,
-9.048305223008427,
-9.446988898140235,
-9.526570603869713,
-9.287463751655224,
-8.83999752443988,
-8.746101446965556,
-8.898856980820328,
-8.382816127953689,
-7.855613165711986,
-7.453725551778092,
-6.520190802425404,
-6.236693894872175,
-5.866432257500904,
-5.377159796561457,
-4.995219285492212,
-4.368900926114719,
-3.415780808923386,
-2.146452602538119,
-1.438382127274849,
-0.683389451490598,
-0.467123582349103,
0.111290724293838,
-0.278711310212941,
0.106691521819869,
0.721331007499401,
0.810524529635188,
2.091841668312185,
3.039484083680549,
2.985998976258458,
3.100410597352663,
4.556962517931424,
6.52924523278304,
7.435184767291872,
7.850766635783144,
8.428560825238577,
8.888946160526871,
9.702488234097842,
10.200028924203991,
10.511947869517741,
11.191906365614216,
12.106682570044939,
12.888081902730365,
13.627985060285397,
14.060671827865264,
14.703268263414714,
14.99849572109818,
15.413612501698793,
15.718813510814613,
16.109332309644287,
15.89198123542468,
15.687962680736348,
15.684086948314473,
16.100960727613,
16.635088331781816,
17.052840610429314,
17.17148969897147,
16.448743116937322,
16.869595981522338,
17.738380161213314,
18.293385044028042,
18.480247023195432,
18.376687452882521,
17.51916873543118,
16.785001661860548,
15.889345737377797,
16.169897088290384,
15.926191033601896,
15.142569614327925,
14.029820997787029,
13.526905958722494,
12.589237094786455,
12.261453484759102,
12.383874952858548,
12.328581170306251,
13.141606479554296,
13.937630242578308,
13.715059848697223,
13.679403110415819,
13.656975538801165,
13.95225467291692,
14.258747592840024,
14.901602410550908,
14.920309279040566,
15.376250441151768,
15.174453973052012,
16.015384555737654,
16.930005730871528,
17.509970330483242,
18.450016310304704,
18.882134637129354,
19.162479282312745,
19.371768833094848,
19.540027296637192,
19.403549838954348,
19.319058872157143,
19.406081984136648,
19.960001661873235,
19.980000441170205,
20.150015903410463,
20.2177120297128,
20.73003217945444,
21.120034213961219,
21.295010613701493,
21.67002648284361,
22.490028110451075,
23.154225294698506,
22.774971958108466,
23.409971958110987,
23.115002882588982,
24.040011020613516,
24.025024855248891,
23.53001631032501,
22.97309939951549,
23.350027296652428,
22.849747755634809,
22.626298862404749,
22.81398766448882,
23.342999301860743,
23.899967889102555,
24.407998894963953,
23.714811232200759,
24.925848422960826,
25.447677036244158,
26.056942172965339,
26.04335127127257,
26.35800906749779,
27.192376743282381,
27.619017368284091,
28.806438429486743,
28.988442824018733,
28.115524529744416,
27.99672041190539,
27.673897739378049,
28.039095086384719,
28.558081495891997,
28.8378577003202,
29.141611769331835,
29.626543409958771,
29.603289015427436,
30.377608676888883,
30.748748813609101,
31.675307244602408,
31.744140252415178,
33.298567335754711,
33.588162062318389,
32.630804477679135,
32.454174432105503,
33.546924269349461,
33.326420932760044,
33.882511020652885,
35.239999220528119,
36.33471276219916,
36.529997999830158,
35.510008579253167,
35.020787794745985,
34.962341749823878,
35.823684523264831,
36.75985477066439,
37.425137159989987,
38.22353803889942,
39.121209344241549,
39.147667677574987,
37.673700799313906,
38.232943149576556,
37.403174676265934,
36.67546715673177,
37.539135369625853,
38.679995965333546,
39.955008579270924,
40.32139448422032,
40.875469191253792,
41.453470086438386,
41.70317060727271,
41.554084100110657,
40.373432651538224,
39.512606642420195,
38.347664829264517,
36.913127068842101,
35.167703891751785,
33.513282911927462,
32.347979363745708,
31.145933872204441,
29.240003696415584,
28.81997765474722,
27.280019972449391,
26.170785353304328,
26.804700148228733,
26.318218214633045,
27.048767937943264,
27.641186557737317,
28.732902866335422,
29.699975620245539,
30.391096225717064,
30.621624790171097,
31.699595167779567,
32.509158156064075,
34.026894972476384,
34.714553256984345,
35.550936313628313,
36.160821567536999,
35.782084995269855,
36.149762811026534,
35.905023227692226,
35.998402540843642,
35.979592319489399,
35.482206658680127,
35.126052687324545,
35.098457472480675,
34.955417107896778,
34.752587111151172,
34.488107130681357,
34.556371697738911,
34.265433383935687,
33.773370395652449,
32.993934767394137,
32.192484978979479,
31.960406121556677,
31.68796797051391,
30.976951938610028,
30.095041945116918,
29.683439161912133,
28.913511997195513,
28.450491163860335,
27.457631870236554,
26.495313348097312,
25.164800245878439,
24.921145867622243,
23.927511427514105,
23.609132928163888,
23.236804233500919,
22.895791456806847,
21.543005812270192,
20.854520704845555,
20.133996209399982,
19.820320265388318,
20.053380975024652,
19.574030389085237,
19.08641157397912,
18.021101922282156,
16.611627231521311,
15.713955926179182,
15.24561242031791,
13.918664991927187,
13.083263787496776,
12.663341098692996,
11.488787469131012,
11.108500603895122,
10.856836378633687,
10.339658644256616,
10.149592726287125,
10.807847120821009,
10.939518670300687,
10.593286573945138,
10.600004510143094,
11.100025668999251,
11.02886722173335,
10.180650262094531,
10.210002475636317,
9.509993523810607,
8.420964389691676,
7.737078484741005,
7.330384962603971,
6.261819695672613,
5.320120070017794,
4.81575809084913,
3.161698846050825,
1.466918572606545,
0.503876580415209,
-0.127454392894606,
-1.208602871089056,
-2.169913702798624,
-2.604305792644113,
-3.640056525070122,
-4.591006232105173,
-5.193863491222174,
-5.929994269219918,
-6.244342006851383,
-6.912544114601445,
-7.654178432638275,
-8.657476365584985,
-9.300692918321941,
-9.434793260119349,
-9.814718390329206,
-9.564811163765697,
-10.399592251008627,
-10.900956997104387,
-11.688919236690865,
-12.618836635783126,
-13.139941779014379,
-13.773804897506494,
-14.439939947964888,
-14.800925665739769,
-14.82464514816175,
-15.089331834360719,
-15.426003790742271,
-15.982610642958051,
-16.326413946995871,
-16.261921759495621,
-16.589136928767758,
-16.973247849993257,
-17.020428432675743,
-17.063423224342571,
-16.536323614965468,
-16.277838100641517,
-16.37765112961327,
-16.256883307347167,
-16.14634741867485,
-16.270551723688357,
-16.549707810929064,
-16.463098110407884,
-16.700706346085923,
-17.185172898822231,
-17.625042690490659,
-17.126106736712615,
-16.713728807023472,
-16.841524624081273,
-16.677451951554573,
-16.613838263403281,
-16.30894731288123,
-16.314786749730203,
-16.085214199273565,
-15.664180467175527,
-15.130311245168173,
-14.839553798877944,
-14.693231980843505,
-14.579698859098258,
-14.330075852912371,
-14.074044969122282,
-13.685153977909792,
-13.246550258832515,
-13.124025437868482,
-12.949049038128194,
-12.428098924193819,
-11.70819454593574,
-11.438779466182055,
-10.765383876986645,
-9.913420376006684,
-9.004793667018674,
-7.974107224957251,
-7.71215938966975,
-7.518941209330436,
-6.528769090185847,
-5.834496222344526,
-4.649917364917911,
-4.008819545904942,
-3.311084357100071,
-2.856125047202397,
-1.964706590167594,
-1.063624640294194,
-0.507637905265938,
1.060121697604927,
1.865240512712319,
2.691701694356254,
3.574180128604553,
4.325607130560684,
5.033574252959369,
5.362804803090881,
5.898172641634687,
6.6980721370806,
7.082596469764439,
7.462108188515941,
8.500287713259695,
8.48881554529089,
8.744923943729418,
8.948115675501072,
9.404366896206,
9.795195753629457,
9.649158155972628,
9.305613234096256,
9.492888624721985,
9.291350538783689,
9.048419630579588,
8.830086704146424,
8.79799563969317,
9.405245395554971,
10.06613528813574,
11.093772820691925,
11.91496300624209,
12.182336866920252,
12.322431674863511,
12.227347039446471,
12.728298374083892,
12.933040398824289,
13.236432732809874,
12.929061313537829,
12.875369500386569,
13.120987583069846,
13.387327915102162,
13.686379428775238,
13.738727654686897,
13.633721144269799,
13.312913852601866,
12.738478631245385,
12.500095249082991,
12.175618930722294,
12.123580763404391,
11.778537224991537,
11.640096062881611,
11.734198846085121,
11.794918654028066,
12.608564080463621,
12.826845330464494,
13.352497999737439,
13.86864220546866,
14.257714064194175,
14.385716586981149,
14.408144158595833,
14.743214145576331,
14.989710727608553,
15.210472446359461,
15.601818068105816,
16.344976840895242,
17.062917514726223,
17.064416131262703,
17.566917758868868,
18.221761508871481,
18.247909783611192,
17.925190463948439,
18.250080193767445,
18.24449913907992,
18.377410922934615,
18.42464318204938,
18.85531456876987,
19.193278435958717,
19.616405063564571,
20.071261020597632,
20.689052768647002,
21.542799106541025,
22.574157342222236,
22.988188917744736,
23.594043409934642,
24.677853224392123,
25.172861769315972,
25.780628289500697,
25.909664340933489,
26.419452345492825,
27.464608188595975,
28.2197558936771,
28.925552605919538,
30.055716180142781,
30.622813348113819,
30.901762729625347,
31.325561150851001,
31.521001417778876,
32.203388706193039,
32.462132602678452,
32.580264926897684,
32.830120477028885,
32.915955031065693,
32.660363396950089,
32.574632195777866,
33.013210076639012,
34.215824008935471,
35.040734897610662,
35.458745558419622,
35.607470330555628,
35.371774122872381,
35.533934767404304,
35.562545536369086,
35.385848253705404,
35.373427768705739,
35.176127150215365,
34.701892531072843,
34.786383497870048,
35.198399692533144,
35.896496616364061,
36.281279331209362,
37.411132846838882,
38.538350864421517,
39.452558628097051,
40.089263950365222,
40.477250604012603,
40.775475294768995,
40.59962039567975,
40.560811395028573,
40.437253045418686,
40.478387485523029,
40.316588576017189,
39.949582553880276,
39.535757684086974,
39.186528354658492,
39.252002394372283,
39.19469323096061,
39.4699735857794,
39.440001255050134,
38.799781935386108,
38.740509067547322,
39.20222,
39.604900750493499,
39.800082635259912,
40.121199985521599,
40.26304,
40.63785,
40.884770949066308,
41.585141635918092,
41.810967645033571,
42.041599562352189,
43.135951368997212,
44.068142531110311,
45.56396854023086,
46.564734327995296,
47.740786574093761,
48.594532911987784,
49.452723423058927,
50.070928582566609,
50.552397902229984,
50.834189487517591,
51.045287713429872,
51.041515333872582,
51.13386111837815,
51.111226841034323,
50.732025180876548,
50.258772413947582,
49.728623895065255,
49.267773471886301,
48.948206414593358,
48.378783807169214,
48.021596307167783,
47.525657586462664,
46.645401238802911,
45.556940545439176,
44.614259067570835,
44.117803582542791,
43.666668328634728,
43.470659620951665,
43.145304803242027,
42.715873650896562,
43.28638146339884,
43.317852410664585,
43.081226027200103,
42.58957645037524,
42.276830682144805,
41.73495161313221,
41.179274936697709,
39.814293654140158,
39.266110060387973,
38.990622999839985,
38.410089959473083,
37.862733188637577,
37.481774529781887,
37.114716831212689,
36.969402703607955,
37.188717482254674,
36.86623,
36.690711704257865,
35.525976596831356,
35.493730503081224,
35.692426385243465,
34.79506513849509,
34.473896111801082,
34.104564650211074,
33.348745151510144,
32.734829135882677,
32.320435825334158,
32.423220249162682,
33.136768426248864,
33.588110385886097,
33.92137169773639,
34.154535760237309,
34.426560499821733,
34.641741163885087,
34.92260257339143,
34.956037225084259,
34.832220493312946,
34.787778761541944,
34.632336053207979,
35.130186801907882,
35.640181512196392,
36.249136590323815,
36.639603712721225,
36.93162723160259,
37.209491408036001,
37.154817742671185,
37.483634881344386,
38.023860304523623,
38.492772251140082,
39.066328973147591,
39.023695916506796,
39.139399448408284,
39.801684604660949,
40.247652215339826,
40.93934126156654,
41.22139122901558,
41.754381951673963,
42.270887892431226,
42.347989129410713,
42.649572788266084,
42.77933230975097,
42.823670688657415,
42.702437778500659,
42.805015496600049,
42.60487267433362,
42.892245314308724,
43.087943963398061,
43.25144819516953,
43.222871128112132,
43.482958611837127,
44.175112745954493,
44.494576450382851,
44.989533318874415,
45.144355910020863,
45.406458774605255,
45.625050083199881,
45.877592807810267,
46.717076450391744,
47.354453566279716,
47.938914015500785,
48.238947381387419,
48.679230584514158,
49.57457645040315,
51.172515089732485,
52.1681649107,
52.19172936382509,
52.385205926325881,
53.108572625547509,
53.570508253804576,
54.239252964093708,
54.791002231674042,
55.274900343655133,
55.269939406155117,
55.661491733630641,
56.283520949127933,
56.512189162019467,
56.609650913321929,
57.234263950433814,
57.694390903560645,
57.788700392493325,
57.665762160070955,
57.826372511634105,
58.034318475176605,
58.48798587426694,
58.861141391846559,
59.282407667889913,
59.442191196536385,
59.806148309168066,
59.808060337162857,
59.450097690677033,
59.180501743410332,
58.72921146020542,
58.136947869708251,
57.4034525897574,
56.845140415276006,
56.396847365144005,
56.261041701080956,
56.39142133975335,
56.485679152253738,
56.362017449779273,
56.070820753814559,
55.43902469261414,
54.693023716048629,
54.008000929587581,
53.404006788960146,
52.577080519425607,
51.794389275932872,
51.757440626844186,
51.579518670463273,
51.38960778179063,
51.606700473848811,
51.589078810437258,
51.286461622936059,
51.013351678273494,
50.743910760303692,
50.810108270069577,
50.660556675016892,
50.527386509000735,
50.239858839728754,
50.113303257045942,
50.212935418504685,
50.152422316290881,
49.470913527225662,
49.299554477745829,
48.807594842327177,
48.416094191283946,
48.093943312376418,
48.18318851094449,
47.974519077349896,
48.567971225789755,
48.941333449098551,
49.576850213423995,
50.115008579311585,
50.852948032439542,
51.520762566947418,
52.483597853409613,
53.493096958231348,
54.715089552637266,
55.723710158110066,
56.492138706290206,
56.970765822177555,
57.397251417882387,
58.525761346272304,
59.616134067630846,
61.49736290878419,
62.905700718034609,
64.530407749291129,
66.372827589793275,
67.145441928989072,
67.443666619745471,
68.176645135373406,
69.349596795534353,
69.644927606082405,
69.164130080038831,
70.470458611945105,
71.175273471973952,
72.630533481745402,
72.824475132136797,
72.820909458308648,
73.119909295549434,
73.534199253233396,
74.443859490867226,
74.616717156883539,
74.864815708316826,
75.396101108709587,
75.746467319648502,
76.130061476551077,
76.592978957021671,
77.539897902337941,
77.941165399084355,
78.277940708330505,
79.189719679688295,
78.885345493489183,
79.340511509115998,
79.857999302086824,
79.862546828128501,
80.286293572921863,
80.233273553390404,
80.025069207686442,
80.324895867843878,
80.791999139330144,
81.692719354177484,
82.191241896497189,
82.192792189465919,
83.189217156917849,
83.941005893900012,
85.060265740909699,
86.499351027373791,
87.033168572948867,
86.975704380240273,
88.208497348995223,
88.888765903685425,
89.031961297566227,
89.418862746135488,
89.702049595094934,
89.847467075564282,
90.272970819055558,
90.586956821660976,
90.496006300827275,
91.41708702999766,
91.834890985077436,
92.02521528520839,
92.082886183646139,
92.36855350135562,
93.078277622452191,
93.663254835996213,
93.540988397193644,
94.324816522196755,
94.533485955791349,
94.188804152404543,
94.80840457558412,
95.369352248112406,
96.505768670642993,
97.164539829499802,
97.597071567782763,
97.777732375075175,
98.103603957107694,
98.509574009192676,
98.428338657629851,
98.764545526120784,
98.457174106848726,
98.553550653073046,
98.259150018306258,
98.150009393305822,
98.339661899817003,
98.503786248775995,
98.988252801512303,
99.519641554769635,
99.690690545655755,
100.085756870527106,
100.306260207116523,
100.196706170657748,
100.557407668055021,
100.695435418706637,
101.273539666755823,
101.390638462329193,
102.573615350354771,
103.519707472754391,
104.228811476663481,
104.24793175661145,
103.854674106870306,
103.502447544368891,
103.429428745540491,
103.332122023534865,
103.438575474056123,
103.381214634212171,
102.96170535686673,
102.371147088635212,
102.141186964936381,
101.62307905477806,
101.017327915452725,
100.459274123132758,
100.279646844486223,
99.873831821698133,
99.222398716226763,
99.153772414143162,
99.47892052612363,
100.018732537844556,
100.097797479251113,
100.978467238369205,
100.831809523524868,
101.687157830819956,
102.584932489026698,
103.090689731867258,
103.497279901139706,
104.334334751403475,
105.076201613385621,
104.795185174582386,
105.15826378786511,
106.405112746203429,
107.220928582795239,
108.366129998815452,
109.200135939573983,
109.335269810017223,
108.877106561317476,
108.269495070429628,
107.361953566519745,
106.42681684776602,
105.662005649846307,
105.881682163519031,
106.715067987090094,
108.050180291782937,
108.522812941524407,
109.864488153118316,
109.627655063924664,
109.889861281373612,
110.444039341271676,
110.509358351688604,
110.785465529424073,
111.843592157032475,
113.241077915501592,
113.806779819800738,
114.152546828265642,
114.763827345846238,
115.890735304835118,
117.281606479970876,
118.656871372554519,
119.585496860839498,
120.395473260582321,
121.125661248866493,
121.684438511238511,
121.938428175953064,
122.0921138855891,
121.503519321784665,
121.264257440273283,
121.891919386890379,
121.90814578663003,
121.229014113450233,
120.620369093916551,
120.227524855633732,
119.151208123858595,
119.664561802246055,
120.637008905114527,
121.104163853033072,
122.5199947449658,
122.35793745329849,
121.711258579597995,
120.823457472823605,
119.702802362142052,
118.911636183753444,
118.878149855628322,
118.059698520989642,
117.532702264477109,
118.042748651197911,
119.023463983233057,
119.63960208544907,
120.76862877816194,
121.640358514493528,
122.168595005381064,
121.376757033372684,
121.58599490772248,
121.054554478032856,
122.131387974130902,
122.867570428560953,
124.265624627785314,
124.737482131042398,
125.321115757346817,
125.386589797060594,
125.132858514507518,
125.221948683778706,
124.985994093933982,
124.71216067921938,
124.981033156433966,
125.240087111513162,
125.275330438336198,
125.568439162295704,
125.689103631697208,
126.174758742376241,
126.860143263863392,
126.117397902532289,
126.559231398627787,
126.373919712429142,
126.485747511908755,
127.386519403188402,
128.185850457879098,
129.091376580929591,
129.4683044780665,
129.460449660358165,
129.212919549680066,
128.349716424676615,
127.783342726757724,
127.385434198110275,
127.502119582225305,
127.533435500194173,
127.96741417858135,
128.63336836152672,
129.010399611528214,
129.188114862179987,
129.705189243692473,
129.667362095254816,
129.965948521037262,
130.400030552289024,
130.78000735893113,
130.935863478723434,
132.278055454640253,
132.906234165580258,
133.5368933452703,
134.86942182834855,
135.515377231996979,
136.862375116116937,
138.219708286695266,
138.554726597243473,
140.061973097900591,
140.51308,
140.59742,
141.379205357020396,
141.34531,
139.901517775634318,
138.80463,
138.164724562736751,
137.19342,
136.70171,
135.12619,
138.958474562739923,
142.19782,
145.48722,
148.54481,
149.78371,
151.33815,
151.26573,
152.81185,
155.04375,
154.21806,
156.72068,
159.30232,
160.12148,
162.657906528980561,
163.258386672212112,
164.473557977555515,
163.669679396823142,
161.87204,
160.150669387043422,
158.36433,
156.81035648012903,
156.75816328351425,
155.91442,
155.433644647441213,
155.991853469058015,
156.42,
156.78979,
158.23118,
158.53094,
160.02173,
160.368743931315123,
162.11749,
161.70146,
162.126344510879164,
163.057933791351957,
163.19191,
162.05297,
162.01733,
163.21711,
163.539299758150719,
164.87674,
165.84,
166.29498,
168.900419549838801,
170.33085,
170.6985,
172.15,
173.68013,
174.56929,
177.3643,
179.228264601963474,
179.48636,
179.37034,
178.90825,
178.313,
177.41128,
178.7072,
180.0,
std::numeric_limits<double>::quiet_NaN(),
-177.550009732146037,
-179.999989387103767,
std::numeric_limits<double>::quiet_NaN(),
-179.999989387103767,
-179.793309496152403,
-179.917358771869033,
-179.999989387103767,
std::numeric_limits<double>::quiet_NaN(),
125.947072381698263,
126.644704217638548,
126.957243280139835,
127.33592817597463,
126.967991978056546,
125.925885044458596,
125.088520135601087,
124.435950148619327,
123.579981724136687,
123.459989048354998,
123.550009393407436,
123.980008986508096,
124.968682489116233,
125.086246372580263,
125.947072381698263,
std::numeric_limits<double>::quiet_NaN(),
-180.0,
-177.550009732146037,
-174.92825,
-175.01425,
-174.33983,
-174.57182,
-171.85731,
-169.89958,
-170.89107,
-172.53025,
-172.555,
-172.95533,
-173.89184,
-174.65392,
-175.98353,
-176.20716,
-177.22266,
-178.35993,
-178.90332,
-178.68611,
-179.88377,
-179.43268,
-180.0,
std::numeric_limits<double>::quiet_NaN(),
-180.0,
-179.87187,
-179.02433,
-177.577945,
-177.663575,
-178.69378,
-180.0,
std::numeric_limits<double>::quiet_NaN(),
180.0,
178.903425,
178.7253,
180.0,
std::numeric_limits<double>::quiet_NaN(),
180.0,
179.364142661964138,
178.725059362997115,
178.596838595117134,
179.0966093629971,
179.413509362997104,
180.0,
std::numeric_limits<double>::quiet_NaN(),
-61.2,
-60.0,
-59.15,
-58.55,
-57.75,
-58.05,
-59.4,
-59.85,
-60.7,
-61.2,
std::numeric_limits<double>::quiet_NaN(),
68.935,
69.58,
70.525,
70.56,
70.28,
68.745,
68.72,
68.8675,
68.935,
std::numeric_limits<double>::quiet_NaN(),
178.12557,
178.3736,
178.71806,
178.55271,
177.93266,
177.38146,
177.28504,
177.67087,
178.12557,
std::numeric_limits<double>::quiet_NaN(),
-61.68,
-61.105,
-60.895,
-60.935,
-61.77,
-61.95,
-61.66,
-61.68,
std::numeric_limits<double>::quiet_NaN(),
-155.40214,
-155.22452,
-155.06226,
-154.80741,
-154.83147,
-155.22217,
-155.54211,
-155.68817,
-155.93665,
-155.90806,
-156.07347,
-156.02368,
-155.85008,
-155.91907,
-155.86108,
-155.78505,
-155.40214,
std::numeric_limits<double>::quiet_NaN(),
-155.99566,
-156.07926,
-156.41445,
-156.58673,
-156.70167,
-156.71055,
-156.61258,
-156.25711,
-155.99566,
std::numeric_limits<double>::quiet_NaN(),
-156.75824,
-156.78933,
-157.32521,
-157.25027,
-156.75824,
std::numeric_limits<double>::quiet_NaN(),
-158.0252,
-157.94161,
-157.65283,
-157.70703,
-157.7786,
-158.12667,
-158.2538,
-158.29265,
-158.0252,
std::numeric_limits<double>::quiet_NaN(),
-159.36569,
-159.34512,
-159.46372,
-159.80051,
-159.74877,
-159.5962,
-159.36569,
std::numeric_limits<double>::quiet_NaN(),
-78.19087,
-77.89,
-77.54,
-77.53466,
-77.78,
-78.03405,
-78.40848,
-78.19087,
std::numeric_limits<double>::quiet_NaN(),
-78.98,
-78.51,
-77.85,
-77.82,
-78.91,
-78.98,
std::numeric_limits<double>::quiet_NaN(),
-77.79,
-77.0,
-77.17255,
-77.35641,
-77.34,
-77.78802,
-77.79,
std::numeric_limits<double>::quiet_NaN(),
-64.01486,
-63.6645,
-62.9393,
-62.01208,
-62.50391,
-62.87433,
-64.1428,
-64.39261,
-64.01486,
std::numeric_limits<double>::quiet_NaN(),
46.68201,
47.67591,
48.64541,
49.10116,
50.034083286342536,
51.191945428274238,
52.042022739475556,
53.042736850807643,
53.220865512917811,
53.040876499245172,
52.167389764215642,
51.316899041556013,
51.278503452363168,
50.305642938036272,
50.339129266161422,
50.891291945200066,
51.342427199108215,
52.501426222550293,
52.692112257707294,
52.446339145727251,
52.50246,
52.814688755103617,
52.916749708880076,
53.72171349469059,
54.008310988181364,
54.736845330632235,
53.858139275941113,
52.915251092343652,
52.693972609269821,
53.357808058491202,
53.101027866432986,
53.880928582581845,
53.735511102112497,
53.921597934795585,
53.825789829326396,
52.264024692601453,
50.842354363819766,
50.14777143738462,
49.199612257693332,
48.88327,
48.85653242370762,
49.223228387250771,
49.395259230350376,
49.56920210144483,
50.392821079312654,
50.084829542853129,
49.618914829309574,
49.110263706260724,
48.58437,
47.49252,
47.59094,
46.68201,
std::numeric_limits<double>::quiet_NaN(),
-64.51912,
-64.17322,
-62.85829,
-61.835585,
-61.8063,
-62.29318,
-63.58926,
-64.51912,
std::numeric_limits<double>::quiet_NaN(),
-80.315395,
-79.92939,
-79.52002,
-79.26582,
-79.65752,
-80.09956,
-80.36215,
-80.315395,
std::numeric_limits<double>::quiet_NaN(),
-83.99367,
-83.25048,
-81.87699,
-81.89825,
-83.06857,
-83.77462,
-83.99367,
std::numeric_limits<double>::quiet_NaN(),
-75.21597,
-75.86588,
-76.98687,
-77.2364,
-76.81166,
-75.89521,
-75.1145,
-75.10333,
-75.21597,
std::numeric_limits<double>::quiet_NaN(),
-96.557401203800524,
-95.647688645579422,
-96.269511155347473,
-97.61740120380054,
-98.431808111736416,
-99.797401203800518,
-98.9174115459831,
-98.218255255290174,
-97.157401203800546,
-96.557401203800524,
std::numeric_limits<double>::quiet_NaN(),
-106.52258806031243,
-105.402449713953743,
-104.774839443768968,
-104.464755011801614,
-102.785374315180249,
-100.980781623115746,
-101.089302130928687,
-102.731165737706107,
-102.093297695711342,
-102.430253872470516,
-104.24,
-105.96,
-107.122551439221041,
-109.0,
-111.534148875200216,
-113.3132,
-113.854957038206337,
-115.22,
-116.107946133267404,
-117.34,
-116.674733242644706,
-115.131132371870294,
-113.721399298947986,
-112.416104295687518,
-114.349991421346317,
-116.48683773483144,
-117.904813198704318,
-118.432377895972053,
-116.113113776496647,
-117.655681118625196,
-119.40198279506447,
-118.562680019995952,
-117.866417609511473,
-115.189087490685679,
-114.167160203897637,
-114.666328701620998,
-112.441012336052268,
-111.050399543077901,
-109.920339321719212,
-109.006544969502059,
-108.18835201702484,
-107.685979580499392,
-108.396401333431911,
-107.516455044365841,
-106.52258806031243,
std::numeric_limits<double>::quiet_NaN(),
-79.775833129882812,
-80.8760986328125,
-80.833885192871136,
-80.353057861328082,
-78.064437866210909,
-76.34,
-76.251403808593722,
-77.314437866210966,
-78.391670227050781,
-79.48625183105473,
-79.775833129882812,
std::numeric_limits<double>::quiet_NaN(),
139.86312,
140.81171,
142.06207,
143.48283,
143.60385,
142.08763,
140.038155,
139.86312,
std::numeric_limits<double>::quiet_NaN(),
148.22223,
150.73167,
149.575925,
147.977465,
146.11919,
146.358485,
148.22223,
std::numeric_limits<double>::quiet_NaN(),
138.831075,
141.471615,
145.086285,
144.3,
140.61381,
138.95544,
136.97439,
137.51176,
138.831075,
std::numeric_limits<double>::quiet_NaN(),
-98.577000698626961,
-98.5,
-97.735585,
-97.704415,
-98.16,
-99.808734300519902,
-100.883655768623171,
-100.86290768105799,
-102.502084113356219,
-102.565516933994488,
-101.489742804758421,
-99.983478156314902,
-98.577000698626961,
std::numeric_limits<double>::quiet_NaN(),
102.837815,
105.37243,
105.07547,
99.43814,
101.2649,
102.08635,
102.837815,
std::numeric_limits<double>::quiet_NaN(),
93.77766,
95.94089,
97.88385,
100.186655,
99.93976,
97.75794,
94.97259,
93.31288,
92.5454,
91.18107,
93.77766,
std::numeric_limits<double>::quiet_NaN(),
-96.016433478564679,
-95.323452521530669,
-94.298424648805195,
-94.735426398481408,
-92.409831916050209,
-91.132881435901922,
-87.81,
-87.02,
-85.814343024422314,
-87.187566697930365,
-89.035360887390851,
-90.804348517606286,
-92.876676805375055,
-93.951159023803825,
-93.935733608764664,
-93.145239223995873,
-94.973990648156786,
-96.076145596077893,
-96.709724494192415,
-96.016433478564679,
std::numeric_limits<double>::quiet_NaN(),
-91.58702,
-90.1,
-88.93227,
-86.97024,
-85.5,
-84.260005,
-83.18,
-82.42,
-81.1,
-79.30664,
-76.25,
-75.71878,
-72.83153,
-70.665765,
-68.5,
-65.82735,
-63.68,
-61.85,
-61.89388,
-64.334,
-66.75342,
-67.65755,
-65.48031,
-67.84,
-69.4697,
-71.18,
-73.2428,
-73.88,
-76.90773,
-75.52924,
-76.22046,
-75.39345,
-76.34354,
-77.88851,
-78.36269,
-79.75951,
-79.61965,
-77.91089,
-77.88911,
-80.56125,
-83.17439,
-86.11184,
-87.6,
-89.49068,
-89.6161,
-87.76739,
-88.26,
-87.65,
-84.97634,
-86.34,
-87.96192,
-87.15198,
-85.37868,
-85.09495,
-86.50734,
-86.93179,
-84.19844,
-83.408695652173904,
-81.84823,
-84.1,
-87.59895,
-89.36663,
-90.2,
-91.36786,
-91.58702,
std::numeric_limits<double>::quiet_NaN(),
-46.76379,
-43.40644,
-39.89753,
-38.62214,
-35.08787,
-27.10046,
-20.84539,
-22.69182,
-26.51753,
-31.9,
-31.39646,
-27.85666,
-24.84448,
-22.90328,
-22.07175,
-23.16961,
-20.62363,
-15.76818,
-12.77018,
-12.20855,
-16.28533,
-16.85,
-20.04624,
-17.73035,
-18.9,
-19.70499,
-19.67353,
-18.47285,
-20.03503,
-21.67944,
-19.83407,
-19.59896,
-20.66818,
-19.37281,
-21.59422,
-20.43454,
-20.76234,
-22.17221,
-23.56593,
-22.31311,
-22.29954,
-24.27834,
-24.79296,
-23.44296,
-22.13281,
-21.75356,
-23.53603,
-24.30702,
-25.54341,
-25.20135,
-26.36276,
-23.72742,
-22.34902,
-25.02927,
-27.74737,
-30.67371,
-31.77665,
-32.81105,
-34.20196,
-36.35284,
-37.04378,
-38.37505,
-39.81222,
-40.66899,
-40.68281,
-41.1887,
-42.81938,
-42.41666,
-42.86619,
-43.3784,
-44.7875,
-46.26364,
-48.26294,
-49.23308,
-49.90039,
-51.63325,
-52.14014,
-52.27659,
-53.66166,
-53.30161,
-53.96911,
-52.9804,
-51.47536,
-51.08041,
-50.87122,
-52.01358,
-52.55792,
-53.45629,
-54.68336,
-54.75001,
-54.35884,
-53.43131,
-51.39014,
-53.10937,
-54.00422,
-55.0,
-55.83468,
-54.71819,
-55.32634,
-56.12003,
-57.32363,
-58.59679,
-58.58516,
-61.26861,
-63.39165,
-66.06427,
-68.50438,
-69.66485,
-71.40257,
-68.77671,
-66.76397,
-71.04293,
-73.297,
-73.15938,
-69.37345,
-65.7107,
-65.3239,
-68.02298,
-67.15129,
-63.68925,
-62.23444,
-62.65116,
-60.28249,
-57.20744,
-54.13442,
-53.04328,
-50.39061,
-48.00386,
-46.59984,
-44.523,
-46.9007,
-46.76379,
std::numeric_limits<double>::quiet_NaN(),
-106.6,
-105.26,
-104.5,
-105.38,
-106.94,
-106.6,
std::numeric_limits<double>::quiet_NaN(),
-180.0,
-179.942499356179042,
-179.058677334691168,
-177.2567718171058,
-176.084672818077706,
-175.829882168662607,
-174.382502814815666,
-173.116559414745495,
-172.889105598012804,
-169.951222907571378,
-168.999988980158719,
-168.530198534193289,
-167.022099372403432,
-164.182143521155098,
-161.929774543281468,
-158.071379564424888,
-155.192252977499322,
-150.942098965438049,
-148.533072883071611,
-145.888919033777199,
-143.107719286044727,
-142.892280239819883,
-146.829068366463247,
-150.060731574483981,
-150.902928229760789,
-153.586201138300169,
-153.409906989536438,
-153.037759162386521,
-152.665637173452751,
-152.861516690055083,
-154.526298794553924,
-155.290179816692415,
-156.837449714159533,
-154.408786587522229,
-152.097661506132766,
-150.648292609642596,
-148.865998298112032,
-147.220749885019501,
-146.41774980363607,
-146.770286424731239,
-148.062946540296309,
-149.53190080462511,
-151.588416104112497,
-153.390321621697836,
-155.329376390585793,
-155.975667691044123,
-157.268301968393018,
-158.051768358370111,
-158.365134243788049,
-157.875474209606409,
-156.974573127246032,
-155.329376390585793,
-153.742832404576831,
-152.920246955354799,
-151.333780483994303,
-150.001949632751973,
-148.748486091080309,
-147.612483080008047,
-146.104409756434308,
-146.143528815679247,
-146.496091274990562,
-146.202310757411254,
-144.909624803630038,
-144.322037930255306,
-142.79435340062679,
-141.638765021715926,
-140.209007331280503,
-138.8575911121996,
-137.506200731334815,
-136.428902147346122,
-135.214583503135543,
-134.431194627806889,
-133.745655077022889,
-132.257167121287779,
-130.925310431829303,
-129.554283006693623,
-128.242037523289923,
-126.890621304209006,
-125.402081672041589,
-124.011494717283426,
-122.562151659009402,
-121.073612026841985,
-119.702558763490146,
-118.684145474098045,
-117.469800991671335,
-116.216311611783496,
-115.021552497195387,
-113.944331427855118,
-113.29798845096451,
-112.945451829869356,
-112.29908301476263,
-111.261058519315753,
-110.06632524294379,
-108.714909023862873,
-107.559346483168127,
-106.149148322355202,
-104.876073574628748,
-103.367948574622716,
-102.016506517325652,
-100.645530768622251,
-100.116699998763366,
-100.763042975653974,
-101.252703009835628,
-102.545337287184552,
-103.113312954504522,
-103.328752000729338,
-103.681288621824493,
-102.917485114334454,
-101.605239630930782,
-100.312527838933406,
-99.137379930400073,
-98.118889126359534,
-97.688036872126048,
-96.336594814828956,
-95.043960537480032,
-93.672907274128207,
-92.439003262078998,
-91.420564134470766,
-90.08873328322845,
-89.226951260113012,
-88.423951178729595,
-87.268336961602586,
-86.014821743498615,
-85.192236294276569,
-83.879990810872897,
-82.665646328446158,
-81.470913052074195,
-80.687446662097102,
-80.295790981756994,
-79.296885545555071,
-77.925858120419377,
-76.907367316378838,
-76.221879442027145,
-74.890048590784843,
-73.852024095337981,
-72.833533291297442,
-71.619214647086864,
-70.209042324490071,
-68.935915900331338,
-67.956621670184191,
-67.36906063502559,
-67.134036220962145,
-67.251548427993868,
-67.564940151627937,
-67.917476772723091,
-68.230842658141015,
-68.485452440043076,
-68.544208543558938,
-68.44628170436583,
-67.976232876238953,
-67.584499681250406,
-67.427842576757598,
-67.623670416927652,
-67.741182623959361,
-67.251548427993868,
-66.703183966728659,
-66.056815151621905,
-65.371327277270197,
-64.568275519454488,
-64.176542324465942,
-63.628152024984587,
-63.001394415932594,
-62.041685553624056,
-61.414927944572078,
-60.709854702381762,
-59.887269253159715,
-59.16258480491463,
-58.594557461162367,
-57.811142747617566,
-57.223581712458966,
-57.595729539608882,
-58.614142829000983,
-59.045072597882907,
-59.789342413966622,
-60.611927863188654,
-61.297415737540362,
-62.022100185785447,
-62.511760219967094,
-62.64885779483744,
-62.590127529537725,
-62.120078701410833,
-62.805566575762548,
-63.745690070232442,
-64.294106207929957,
-64.881693081304704,
-65.508424852140536,
-65.665081956633358,
-65.312545335538189,
-64.783714565679304,
-63.961103278241126,
-63.197299770751087,
-62.785955369707779,
-62.570516323482948,
-62.276735805903655,
-61.806661139560632,
-61.512906460197478,
-61.375808885327132,
-61.081976691315546,
-61.003661058177201,
-60.690269334543153,
-60.827366909413485,
-61.375808885327132,
-61.963369920485725,
-63.295200771728034,
-63.745690070232442,
-64.352836473229672,
-65.860987311451851,
-67.192818162694152,
-68.44628170436583,
-69.797723761662908,
-70.600723843046325,
-72.20677568224545,
-73.969536302369704,
-75.555976935514067,
-77.24037024606767,
-76.926978522433615,
-75.399293992805099,
-74.282876349571467,
-73.656118740519489,
-74.772536383753121,
-76.496100429983983,
-77.925858120419377,
-77.984665900367531,
-78.02378495961247,
-76.848637051079123,
-76.633223843070454,
-75.360097418911721,
-73.244851854124619,
-71.442946336539279,
-70.013162807887724,
-68.191646084247623,
-65.704278530526736,
-63.256030036050802,
-61.552025519442424,
-59.691415574773515,
-58.712121344626368,
-58.222487148660875,
-57.00811682801799,
-55.362894253141619,
-53.619770677288287,
-51.543644171746131,
-49.76134986021556,
-47.273930630062374,
-44.825707973802594,
-42.808363409992438,
-42.16202043310183,
-40.771433478343667,
-38.244817674297096,
-36.266669684380332,
-34.386396857224369,
-32.310296189898366,
-30.097097947702011,
-28.549802212018733,
-29.254901292425203,
-29.685805223090984,
-29.685805223090984,
-31.624808315546659,
-33.68132361503406,
-35.63991207532834,
-35.914107225069031,
-35.777009650198693,
-35.326546189910431,
-33.896762661258876,
-32.212369350705259,
-30.998050706494666,
-29.783732062284088,
-28.882779303491418,
-27.511751878355724,
-26.160335659274793,
-25.474821946706953,
-23.927552049239821,
-22.458597784911039,
-21.224693772861826,
-20.010375128651233,
-18.913542853256232,
-17.5229817367142,
-16.641588507544014,
-15.701490851290259,
-15.407710333710952,
-16.46532019699643,
-16.112783575901275,
-15.446855231172053,
-14.408804897509043,
-13.311972622114027,
-12.293507656289634,
-11.510067104528686,
-11.020432908563194,
-10.295774298534253,
-9.101015183946146,
-8.611380987980638,
-7.416621873392529,
-7.377451137715283,
-6.86823157391116,
-5.790984666354775,
-5.536374884452712,
-4.341667446296896,
-3.048981492515679,
-1.795492112627841,
-0.659489101555607,
-0.228636847322093,
0.868195428072909,
1.886686232113448,
3.022637566753389,
4.139055209987021,
5.15754601402756,
6.273911980828899,
7.135719842160483,
7.7428662451577,
8.487110223025269,
9.525134718472117,
10.249845004933347,
10.817820672253333,
11.953823683325595,
12.404287143613857,
13.422777947654367,
14.734997592841919,
15.126756626046614,
15.949342075268646,
17.026588982825047,
18.201711053142247,
19.259372592860018,
20.375738559661357,
21.452985467217758,
21.923034295344621,
22.56940311045139,
23.666183709414099,
24.841357456163593,
25.977308790803562,
27.09372643403719,
28.092580193806807,
29.150241733524577,
30.031583286262475,
30.97173261894855,
31.990171746556772,
32.75405276869526,
33.302443068176615,
33.8704187354966,
34.90849490737574,
35.30020226414814,
36.162010125479725,
37.200034620926573,
37.90510786311691,
38.649403517416744,
39.667894321457283,
40.020430942552451,
40.921357863128968,
41.959434035008115,
42.93870242693913,
44.113876173688624,
44.897290887233417,
45.719928012887756,
46.50334272643255,
47.443440382686298,
48.344418979695121,
48.990736118369561,
49.930885451055644,
50.753470900277676,
50.949324578663862,
51.791547072156817,
52.614132521378878,
53.613037957580786,
54.533550245995905,
55.414943475166126,
56.355041131419881,
57.158092889235576,
57.255968051996398,
58.137361281166591,
58.744507684163807,
59.939318475184223,
60.6052209816973,
61.427806430919333,
62.387489455011718,
63.190489536395148,
64.052349074158997,
64.992446730412752,
65.971715122343767,
66.911864455029814,
67.891132846960801,
68.890038283162738,
69.71262373238477,
69.673452996707539,
69.555940789675816,
68.596257765583431,
67.812739699174045,
67.949888950476662,
69.066306593710294,
68.929157342407677,
68.419989455035847,
67.949888950476662,
68.713769972615154,
69.869306675093725,
71.024895054004588,
71.573285353485971,
71.906288283174803,
72.454626906223865,
73.081410353492004,
73.336020135394051,
73.864876743469097,
74.491556837872622,
75.627559848944884,
76.626465285146793,
77.644904412755039,
78.134538608720533,
78.428370802732132,
79.11385867708384,
80.093127069014827,
80.935349562507781,
81.483791538421428,
82.051767205741413,
82.776425815770352,
83.775331251972261,
84.676206496116492,
85.6555265644798,
86.752358839874802,
87.477017449903741,
87.986288690140157,
88.358410679073941,
88.828407830768526,
89.670630324261481,
90.630365024786158,
91.590099725310836,
92.608538852919082,
93.548636509172837,
94.175419956440962,
95.01759077350161,
95.781471795640101,
96.682398716216625,
97.759645623772983,
98.680209588620443,
99.718182407634998,
100.384188267012661,
100.893356154384477,
101.578895705168506,
102.832410923272477,
103.478676385514618,
104.242557407653095,
104.908459914166187,
106.181560500108787,
107.160880568472066,
108.08139285688722,
109.15863976444362,
110.235834995567714,
111.058472121222053,
111.743959995573732,
112.860377638807364,
113.604673293107226,
114.388088006652026,
114.89730757045615,
115.602380812646459,
116.699161411609182,
117.384700962393168,
118.579460076981292,
119.832923618652984,
120.870999790532125,
121.654414504076925,
122.320368687022281,
123.221295607598847,
124.122274204607621,
125.160247023622219,
126.100396356308238,
127.001426629749332,
127.882768182487254,
128.803280470902394,
129.70425906791121,
130.781454299035317,
131.799945103075856,
132.935896437715826,
133.856460402563243,
134.757387323139767,
135.031582472880416,
135.070753208557676,
135.69748497939355,
135.87380496637337,
136.206704543197645,
136.618048944240968,
137.460271437733923,
138.596222772373892,
139.908442417561389,
140.809421014570205,
142.121692336190051,
143.061841668876127,
144.374061314063624,
145.490427280864992,
146.195552199487622,
145.999698521101379,
146.646067336208148,
147.723262567332256,
148.839628534133624,
150.132314487914812,
151.483704868779569,
152.5022473492524,
153.638198683892369,
154.284567498999138,
155.165857375304711,
155.929790073875495,
156.811131626613417,
158.025527785472434,
159.181012811518713,
159.670698683916498,
160.806650018556468,
161.570479364262667,
162.686897007496242,
163.842433709974841,
164.919680617531242,
166.114439732119365,
167.309095493842904,
168.425616489941092,
169.463589308955704,
170.501665480834845,
171.206790399457475,
171.08922651599346,
170.560421584350706,
170.109958124062416,
169.757369826534955,
169.28732099840812,
167.975101353220566,
167.387488641629659,
166.094802687848471,
165.644390903992473,
164.958851353208473,
164.234192743179563,
163.822796665703947,
163.568238560234192,
163.470260044608807,
163.489897088879758,
164.057872756199714,
164.273363478856822,
164.74346398341595,
166.604125604517151,
166.995781284857287,
165.193875767271948,
163.666217075859549,
161.766384719081145,
160.924162225588191,
160.747893915040606,
160.316964146158682,
159.788210890948221,
161.120015903974377,
161.629287144210821,
162.490991652677792,
163.705336135104517,
165.095948928078826,
166.604125604517151,
168.895665318067955,
169.40478152900755,
172.283933954149234,
172.477048781623978,
173.22408328683531,
175.985671828513034,
178.277211542063895,
180.0
};
static constexpr double y[] = {
-78.595667413241543,
-78.223338718578589,
-78.380176690584435,
-78.693645928866943,
-79.046337579258974,
-79.497007745276406,
-79.634208673011329,
-79.281465346186991,
-78.928773695794959,
-78.869965915846805,
-78.595667413241543,
std::numeric_limits<double>::quiet_NaN(),
53.867565009163364,
53.153190009160497,
52.260117906292336,
51.669301255899356,
51.820454820353078,
52.864628811242682,
53.881362616585299,
54.664518947968631,
55.131622219454869,
55.172860012423783,
54.554603176483809,
53.867565009163364,
std::numeric_limits<double>::quiet_NaN(),
-2.60015105551566,
-3.28915292726321,
-3.861417738463416,
-4.373737888205049,
-4.876497897972683,
-5.465609226100043,
-6.083659356310847,
-6.614014580922343,
-6.721656589386313,
-7.388024183790023,
-8.044108168167647,
-9.104663588093764,
-9.071435642130091,
-9.514406019736029,
-9.684318129111709,
-9.872937106977048,
-10.293686618697478,
-10.582712904505925,
-10.652476088099952,
-10.393267103723923,
-10.280922539921384,
-10.13044076908745,
-9.492443536011983,
-8.942554619994155,
-8.067414239131281,
-7.630128269077446,
-7.915330498896296,
-8.245491224809079,
-8.983068942910982,
-9.326820570516524,
-9.159595635620022,
-9.117892754760483,
-8.29716765710095,
-8.096042982620979,
-8.380935153846075,
-8.41168263105974,
-7.597882175327321,
-7.320224704623087,
-6.232849216337485,
-5.393365573756,
-4.54654387778907,
-4.462931410340822,
-3.538853448097541,
-4.024818617370315,
-4.112978610860253,
-3.746282647317123,
-3.31178720460705,
-2.820551039240499,
-2.460417982598436,
-2.479848321140182,
-2.214541517753702,
-2.212526136894319,
-1.617161960459647,
-1.432522067880783,
-0.937720228686089,
-0.695461114101789,
-0.369537855636949,
-0.780210463060456,
-1.151867364103623,
-2.769184665542376,
-3.367701104346857,
-2.307042331556154,
-1.703513278819365,
-1.702634779470401,
-2.051295668143673,
-2.408999932468021,
-2.60015105551566,
std::numeric_limits<double>::quiet_NaN(),
4.525873928236805,
4.900011298029966,
5.447729803891534,
6.143191229675566,
6.924771429873999,
6.92805288332454,
6.422166449403249,
5.987490139180154,
5.708695786965492,
5.407835598162207,
5.016128241389808,
4.966518866389606,
4.478202419447555,
4.137551377779516,
3.234428208830593,
2.287690131027333,
1.827640692548925,
0.902219143066063,
0.784241848143708,
0.102474676917026,
-0.803723239753268,
-1.487609144703917,
-2.483517347832901,
-4.012726332214022,
-3.657037448749058,
-4.106984144714396,
-3.495703627133828,
-3.43916961020652,
-3.118775729996905,
-3.478392022316051,
-2.994442233902654,
-3.049425957861211,
-2.934032484553455,
-1.592874037282463,
-1.314906507984475,
-0.459506524257094,
0.415375474444318,
1.341933905437614,
2.006492824711103,
1.663774725751395,
1.850636704918813,
2.697303371588859,
2.885896511238059,
3.102394924324855,
3.893509426281156,
4.525873928236805,
std::numeric_limits<double>::quiet_NaN(),
74.97999726022438,
74.592346503386878,
74.666863918751758,
74.927623196096576,
75.377828274223376,
75.647217515760886,
75.296489569795952,
74.97999726022438,
std::numeric_limits<double>::quiet_NaN(),
77.519997260234547,
77.491342678528682,
77.555111395976851,
77.83462921824362,
77.820004787905006,
77.634331366680314,
77.519997260234547,
std::numeric_limits<double>::quiet_NaN(),
78.765812689927017,
78.418314520980331,
78.056941229963243,
77.850597235821809,
78.08285696075761,
78.458105373845072,
78.871930243638374,
78.831984361476756,
78.765812689927017,
std::numeric_limits<double>::quiet_NaN(),
74.392307033985034,
74.515555325001159,
74.837757880340988,
75.386819973442144,
75.882655341282671,
76.319243679500559,
76.441380927222397,
76.751077785947601,
77.161388658345075,
77.097878323058367,
76.776295884906048,
76.778517971494594,
76.449597479956807,
76.074013170059473,
75.847773749485654,
75.610165513807615,
75.566188869927245,
75.482421373182106,
75.699204006646525,
75.784315090631239,
75.713983466281988,
75.336848863415909,
74.923127346487163,
74.657303778777774,
74.442459011524321,
74.564027818490942,
74.410032050261165,
74.392307033985034,
std::numeric_limits<double>::quiet_NaN(),
78.152981879377691,
77.996324774884883,
77.697014879050343,
77.4092288276169,
77.732206529441115,
78.051050116681964,
78.152981879377691,
std::numeric_limits<double>::quiet_NaN(),
78.804440823065207,
78.601972561345647,
78.406945705876112,
78.407901719873493,
78.550554511215225,
78.849993598130496,
78.804440823065207,
std::numeric_limits<double>::quiet_NaN(),
18.514761664295364,
18.426679185453878,
18.228034979723915,
17.975905666571862,
17.981822618069273,
17.946553453030077,
18.374485988839083,
18.520601101144351,
18.514761664295364,
std::numeric_limits<double>::quiet_NaN(),
18.490525417550487,
18.400866807524082,
18.160700588447597,
17.886867173732966,
17.868237819891746,
17.701116237859821,
17.861597398342241,
18.225967922432233,
18.454532782459196,
18.524218451404778,
18.490525417550487,
std::numeric_limits<double>::quiet_NaN(),
23.188610744717707,
23.117271429938782,
23.106005967699151,
22.76530324959883,
22.399201565027056,
22.512166246017088,
22.277193508385935,
21.657851467367834,
21.206819566324373,
21.220565497314013,
21.016624457274133,
20.735091254148003,
20.693905137611385,
20.284653632075887,
20.050378526280682,
19.923435370355691,
19.873774318923196,
19.95289093676206,
19.855480861891877,
20.413353786698792,
20.673105373613893,
20.739948838783434,
21.028613389565852,
21.598113511638434,
21.559175319906501,
21.827324327069036,
22.03707896574176,
22.192056586185071,
22.387109279870753,
22.636964830001958,
22.688150336187064,
22.168517971276131,
22.154565334557333,
21.910575059491254,
21.801227728761646,
21.89602814380109,
22.204949856041907,
22.565754706303764,
22.788118394455694,
22.983041897060644,
23.078746649665188,
23.188610744717707,
std::numeric_limits<double>::quiet_NaN(),
51.317074693397942,
50.687009792679277,
49.812308661490889,
50.150117499382858,
49.935815334668462,
49.58712860777905,
49.313010972686797,
49.556691189159125,
49.249138902374042,
48.516780503933624,
48.687803656603577,
48.157164211614472,
47.535548407575519,
46.655498765644921,
46.618291734394766,
46.807065741556983,
47.62520701760193,
47.752279364607645,
46.884993801453135,
46.919720363953275,
47.389562486350989,
47.632545070987376,
47.572807115257973,
47.603347886742469,
47.899453843774886,
48.251525376979423,
48.523188381537807,
49.125580552764177,
50.718274034215867,
51.287438259478549,
51.632094224649208,
51.588272610065701,
51.317074693397942,
std::numeric_limits<double>::quiet_NaN(),
65.109617824963536,
64.766693020274673,
64.45513580998697,
63.979609280037138,
64.057485663500998,
63.725981350348619,
63.41124603947496,
63.651722317145207,
64.101875718839707,
63.569711819098004,
63.052379055424055,
63.637252916103492,
63.54123810490519,
64.035833238370699,
64.822916978608234,
65.738778388117098,
65.657284654392797,
65.217518215588981,
65.37177236598022,
65.109617824963536,
std::numeric_limits<double>::quiet_NaN(),
72.352199001750321,
72.749616604290978,
72.243678493937395,
71.767144273557889,
71.330840155717581,
71.556924546994523,
70.920012518997183,
70.52502370877427,
70.12194753689765,
69.186087348091817,
68.720198472764437,
68.067163397892031,
67.847538560651586,
66.928473212340592,
66.862120673277829,
66.160251369889622,
64.998668524832894,
65.426032619886669,
66.388041083432185,
66.262725735124391,
65.689789130304391,
65.108455105236956,
64.648405666758563,
64.382737128346051,
63.392926744227495,
62.674185085695981,
62.945098781986118,
63.745670071051833,
62.883965562584841,
62.280074774822012,
61.930897121825822,
62.330149237712824,
62.910708116295879,
63.397836005295218,
63.679989325608872,
64.193963121183842,
64.679101467539951,
64.389093329517934,
64.229542344816778,
64.572906399180127,
65.309192206474748,
65.326968899183143,
65.454764716240945,
65.81177134872938,
66.310578111426665,
67.284575507263909,
67.726925767682346,
68.069437160912869,
68.554627183701271,
68.894735622830254,
69.147769273547411,
69.769540106883213,
69.826487535268868,
70.16688019477543,
69.871807766388841,
69.74318512641436,
69.966634019644417,
70.260001125765385,
70.410741278760796,
70.762089341913239,
71.218185533321318,
71.222552191849971,
72.235074367960792,
73.12946421985238,
73.537888902471209,
73.803815823045184,
73.157447007938444,
72.534125881633869,
73.340278225387081,
73.750950832810602,
72.716543687624167,
72.061906643350724,
72.352199001750321,
std::numeric_limits<double>::quiet_NaN(),
74.134906724739224,
74.100025132942207,
73.856732489712059,
72.966244208458519,
72.771992499473342,
72.024596259235992,
72.061880805134578,
72.940276801231832,
73.437429918095816,
73.862416897264168,
74.134906724739224,
std::numeric_limits<double>::quiet_NaN(),
72.705898342572041,
73.36,
73.843865058071387,
73.633386949346587,
73.76,
73.47,
72.990532131635675,
72.56,
71.66,
71.272859198686106,
71.356394151485929,
71.738257147906708,
72.482921284975077,
72.83,
72.705898342572041,
std::numeric_limits<double>::quiet_NaN(),
75.845525824680962,
76.012828274225896,
75.969394232884596,
75.479527492973759,
75.005267035615091,
74.850005194794178,
74.416956692188265,
74.394270738412146,
74.720297349741557,
75.162492580863116,
75.043430080862649,
75.222230536592534,
76.199018459773512,
76.478872178850153,
76.141347561335792,
75.549187323703208,
75.473222968234168,
76.429805406389036,
76.794175930479028,
76.67832,
76.20168,
75.845525824680962,
std::numeric_limits<double>::quiet_NaN(),
76.116542873835684,
76.864533393044425,
77.512219957174622,
77.498318996888102,
77.645286770326194,
76.876961575010611,
76.530031846819114,
76.481171780087138,
76.053239244278146,
75.900018622532755,
76.116542873835684,
std::numeric_limits<double>::quiet_NaN(),
74.448944403776935,
74.241360175260482,
74.18575633411443,
73.896058254686196,
73.475205390101181,
73.222921047652235,
72.52,
71.82,
71.383601793087607,
70.901641547317425,
71.34,
71.868688463011395,
72.292260811794975,
73.02256,
73.68,
74.292726548958612,
74.448944403776935,
std::numeric_limits<double>::quiet_NaN(),
60.384169826897754,
60.293606879306253,
59.909986884187532,
59.75444082298899,
59.941406155020985,
60.213069159579362,
60.384169826897754,
std::numeric_limits<double>::quiet_NaN(),
57.96902008730477,
57.901427313866996,
57.591058661521998,
57.115842190165928,
56.734676825581076,
56.992748928446687,
57.461195787172528,
57.81657461204373,
57.96902008730477,
std::numeric_limits<double>::quiet_NaN(),
54.040009263721338,
54.120004380909151,
52.984621487024413,
52.180432847698263,
52.182370713909222,
52.639707139692291,
53.10001496033216,
53.411468817755278,
53.851080227262237,
54.1699754909354,
54.040009263721338,
std::numeric_limits<double>::quiet_NaN(),
49.950000515332576,
49.475274970083291,
49.062483628935794,
48.510010891303381,
48.370846259141373,
48.825004584338501,
49.179995835967517,
49.530000311880386,
49.814995835970066,
49.994959011426516,
50.539137681676074,
50.770648098343671,
50.552573554071977,
50.400903225295323,
50.295018215529275,
49.950000515332576,
std::numeric_limits<double>::quiet_NaN(),
63.782515367275934,
63.592191067144952,
63.694975490973505,
63.431115627691192,
63.297506212000556,
63.188598130945437,
62.976931464277918,
63.194437567794424,
63.375821845138901,
63.317789211675105,
63.405845852300459,
63.782515367275934,
std::numeric_limits<double>::quiet_NaN(),
79.301593939929163,
79.165349026191635,
78.800461737778718,
78.324780178532038,
77.907544664207435,
78.018984890444855,
78.343228664860234,
78.380332343245797,
78.677420152491763,
78.918335679836488,
79.301593939929163,
std::numeric_limits<double>::quiet_NaN(),
35.386703396133697,
35.373215847305516,
35.671595567358793,
35.245781765273762,
34.978097846001859,
34.571869411755443,
34.701654771456475,
35.103232326796629,
35.145503648411378,
35.386703396133697,
std::numeric_limits<double>::quiet_NaN(),
35.299990342747932,
35.004995429009767,
34.919987697889638,
35.084990546197588,
35.279991563450977,
35.70500438083549,
35.368022365860185,
35.424995632461972,
35.35401805270908,
35.179997666966202,
35.299990342747932,
std::numeric_limits<double>::quiet_NaN(),
-12.469832858940554,
-12.895284925999555,
-13.555761407121985,
-14.758788750876796,
-15.226512139550543,
-15.706069431219127,
-16.000263360256767,
-15.414252618066918,
-15.710151869370186,
-16.451036879138776,
-16.875042006093601,
-17.106035658438273,
-17.953064060134366,
-19.118781019774445,
-20.496888116134127,
-22.391501153251085,
-23.781958916928517,
-24.941629733990453,
-25.178462823184105,
-25.601434421493089,
-25.34610116953894,
-24.988345228782308,
-24.460677178649991,
-23.574116306250602,
-22.776903985283873,
-22.057413018484123,
-21.336475111580189,
-21.163307386970128,
-20.830459486578174,
-20.072366224856388,
-19.435454196859048,
-18.961994724200906,
-18.331387220943171,
-17.409944756746782,
-16.85044402432267,
-16.216219170804507,
-16.179373874580399,
-15.974373467678539,
-15.793454278224687,
-15.780018405828798,
-15.210182386946315,
-14.594302666891764,
-14.091232598530375,
-13.663868503476586,
-13.784067884987486,
-13.089174899958664,
-12.487867933810421,
-12.040505059459676,
-12.469832858940554,
std::numeric_limits<double>::quiet_NaN(),
-15.89184620530842,
-16.46633310309717,
-16.597849623279991,
-16.159995212470946,
-15.89184620530842,
std::numeric_limits<double>::quiet_NaN(),
-15.668810723536687,
-15.392703545801211,
-14.626497084209605,
-14.933920179913954,
-15.740020847234888,
-15.614602146062516,
-15.668810723536687,
std::numeric_limits<double>::quiet_NaN(),
-6.89523772545472,
-6.142467136259,
-5.783057549669017,
-5.445042006047871,
-5.737582289252167,
-6.214400730009288,
-6.89523772545472,
std::numeric_limits<double>::quiet_NaN(),
-78.047018731598726,
-78.047070408031018,
-77.831476332509325,
-78.047070408031018,
-78.478103529777528,
-79.085559991368498,
-79.516644789547314,
-80.026122735512899,
-80.339643650227686,
-80.594356784994332,
-80.829484551922334,
-81.025441583173134,
-80.966685479657286,
-80.633527520671578,
-80.222028090331378,
-79.947729587726116,
-79.614623305172699,
-79.183486830561606,
-78.811209812330944,
-78.458569838371204,
-78.047018731598726,
std::numeric_limits<double>::quiet_NaN(),
-80.255772800617976,
-80.294891859862929,
-80.392870375488314,
-79.981370945148129,
-79.628679294756097,
-80.040178725096283,
-80.549656671061854,
-81.000326837079285,
-80.863177585776654,
-80.92193368929253,
-80.5888274067391,
-80.549656671061854,
-80.255772800617976,
std::numeric_limits<double>::quiet_NaN(),
-71.269344577925779,
-71.151780694461763,
-71.190951430139009,
-70.681473484173424,
-70.309144789510484,
-69.50578297310102,
-69.035475762812681,
-68.878741143671419,
-69.251018161902081,
-69.623346856565021,
-70.074017022582453,
-70.505153497193561,
-70.955823663210978,
-71.40649382922841,
-71.79840789172998,
-72.170684909960627,
-72.307885837695551,
-72.503842868946336,
-72.484205824675428,
-72.09234343860615,
-72.229492689908781,
-72.366693617643705,
-72.072758070767534,
-71.661258640427349,
-71.269344577925779,
std::numeric_limits<double>::quiet_NaN(),
-71.894164320766819,
-71.71779265735465,
-71.854993585089574,
-71.933335056444065,
-72.070535984178989,
-71.952972100714973,
-72.521206150196406,
-72.442864678841929,
-72.482035414519174,
-72.442864678841929,
-72.50162078235779,
-72.305663751107005,
-71.894164320766819,
std::numeric_limits<double>::quiet_NaN(),
-73.65777760202387,
-73.324619643038162,
-73.500991306450331,
-73.657725925591578,
-73.481354262179423,
-73.834097589003747,
-74.088810723770393,
-74.010469252415916,
-73.65777760202387,
std::numeric_limits<double>::quiet_NaN(),
-73.461768894340793,
-73.246226495251392,
-73.481354262179423,
-73.873268324680993,
-73.834097589003747,
-73.736119073378347,
-73.461768894340793,
std::numeric_limits<double>::quiet_NaN(),
-21.080004978115628,
-21.700018812753527,
-22.159990736583492,
-22.39997608814695,
-22.129708347260454,
-21.679606621998232,
-21.149819838141951,
-20.444746595951628,
-20.105645847252354,
-20.120011895429499,
-20.45999114347773,
-20.80002206795826,
-21.080004978115628,
std::numeric_limits<double>::quiet_NaN(),
-3.659983005389691,
-3.980015150573265,
-4.499983412294092,
-4.766427097190991,
-4.176127211120921,
-3.789742526874583,
-3.462062269711816,
-3.035421644710112,
-2.741486097833935,
-2.500002129734007,
-2.779985039891379,
-2.999971612157886,
-3.24000864015364,
-3.659983005389691,
std::numeric_limits<double>::quiet_NaN(),
-5.840728448106752,
-6.083711032743138,
-6.317753594593028,
-6.316513360218025,
-6.026040134305404,
-5.747142429226166,
-5.437755629094717,
-5.58374155031926,
-5.505503431829368,
-5.026101169457654,
-5.001348158389852,
-5.532220147324267,
-5.455842380396874,
-5.113692722192383,
-4.757073662946162,
-4.167807305521933,
-4.14879037843852,
-4.312966403829805,
-4.867661228050771,
-5.478063246282382,
-5.560280450058754,
-5.840728448106752,
std::numeric_limits<double>::quiet_NaN(),
-10.482719008021149,
-10.826367282762106,
-10.820011081590211,
-10.204751478723168,
-10.446648858281423,
-10.482719008021149,
std::numeric_limits<double>::quiet_NaN(),
-9.599982191611367,
-9.784312025596485,
-8.917543226764892,
-8.32000864017396,
-8.32000864017396,
-9.120011488484451,
-9.599982191611367,
std::numeric_limits<double>::quiet_NaN(),
-9.872937106977048,
-9.895209649294841,
-9.794027194867354,
-9.639979750205278,
-9.242949720906815,
-9.400304457235571,
-9.610162448772869,
-9.872937106977048,
std::numeric_limits<double>::quiet_NaN(),
-8.020026950719632,
-8.337320244991737,
-8.538289890174831,
-8.114181410355428,
-7.754823500197737,
-7.421872246941199,
-7.320017998893917,
-7.560003350457379,
-8.020026950719632,
std::numeric_limits<double>::quiet_NaN(),
-7.021638278840641,
-7.347819919466943,
-7.404767347852592,
-7.176874281445428,
-6.765943291860452,
-6.599338474151452,
-7.021638278840641,
std::numeric_limits<double>::quiet_NaN(),
-5.339983819198495,
-5.56679168052753,
-6.200654799019645,
-6.540013929880381,
-6.819996840037753,
-6.919990736522522,
-6.535931491729322,
-5.900776462429902,
-5.139117526879986,
-5.042379245629597,
-5.339983819198495,
std::numeric_limits<double>::quiet_NaN(),
-40.065977878582203,
-40.60475636165728,
-41.289624118821472,
-41.688307793953278,
-41.425894870775132,
-41.281820977545401,
-40.459235528323362,
-39.908881524414909,
-39.508854262043513,
-39.146602471677483,
-38.797683200842755,
-38.027807712558428,
-37.381128838857919,
-36.71109221776149,
-36.534823907213912,
-36.121980889634131,
-35.237125339500388,
-34.529106540669432,
-34.450661716450369,
-35.006183363588008,
-35.265495700828623,
-36.156345717108231,
-37.20909799575827,
-36.52619394302117,
-36.798942152657673,
-37.55538176854612,
-37.881253350578675,
-37.961248467766495,
-37.579824721020174,
-37.695373223624799,
-38.582812595373142,
-39.166342868812976,
-39.145775648760818,
-39.449736423501612,
-39.879942722331464,
-40.065977878582203,
std::numeric_limits<double>::quiet_NaN(),
-43.555325616226376,
-43.031688327812816,
-42.512753594737823,
-41.767424411792135,
-41.514416599291124,
-40.956104424809716,
-40.493962090823501,
-40.919052422856446,
-41.331998793300812,
-40.926700534835646,
-41.349155368821712,
-41.770008233406728,
-42.233184096038791,
-42.970038344088614,
-43.372287693048555,
-43.853343601253606,
-43.86569426857136,
-44.242467136411406,
-44.897104180684863,
-45.908928724959736,
-46.355774834987571,
-46.641235446967876,
-46.619944756863632,
-46.290197442409188,
-46.219917494492236,
-45.852704766626189,
-45.110941257508635,
-44.123973077166141,
-43.935819187191434,
-43.555325616226376,
std::numeric_limits<double>::quiet_NaN(),
-40.808258152022674,
-40.875437514002108,
-42.062393487314147,
-42.407023614268653,
-43.211522312188535,
-42.937688897473905,
-43.634597263362103,
-43.580853773778557,
-43.549744561538844,
-42.693776137056254,
-42.033609714527564,
-41.162551771815757,
-40.70397511165767,
-40.79254851660594,
-41.137643731451085,
-41.000546156580732,
-40.808258152022674,
std::numeric_limits<double>::quiet_NaN(),
-32.215966078420593,
-32.72875131605285,
-32.959486586236068,
-33.483847344701701,
-33.890179131812708,
-33.914467054989885,
-34.003402194964202,
-33.821036065406176,
-33.930176690406611,
-33.976065362281801,
-34.509366143533938,
-34.464149265278543,
-34.746819349915093,
-35.0647327613747,
-35.025458672832869,
-35.025096937806829,
-34.386427911111568,
-34.196517022438933,
-33.623425388322055,
-33.487257989232972,
-33.259571628554973,
-32.900368747694166,
-32.205062351207005,
-31.612437025683807,
-30.601594333622465,
-30.03072478609414,
-29.461043796508527,
-28.81023080822467,
-28.516398614213081,
-28.118076674107321,
-27.334713636994813,
-26.543134047147902,
-26.116545098578484,
-26.549025160429174,
-25.621278171493167,
-25.91123463308287,
-26.298446140245879,
-25.786281019801123,
-24.998938897402141,
-24.683971042583167,
-24.384712823180937,
-23.806350192970285,
-23.560215345964089,
-23.059987481378755,
-22.475475355725379,
-21.755829359628745,
-22.517488295178673,
-21.829519952076954,
-21.495173435148537,
-21.068687839443704,
-20.701681817306824,
-20.623547051681516,
-20.746898695562209,
-20.374208265873222,
-20.263310642174858,
-20.044202569257315,
-19.952941989829867,
-19.976506442954964,
-19.683707777589206,
-19.239755547769725,
-18.705317885007169,
-18.197648614171804,
-17.798603204013958,
-17.254915459871157,
-16.405199883695886,
-17.268558037996215,
-17.069035332917288,
-16.596506036040402,
-16.111316013252001,
-16.327943617419535,
-15.56705982835399,
-15.075100192935359,
-14.680395603090028,
-14.510070082256014,
-14.23065561285385,
-14.347340996968903,
-14.095986830301227,
-13.952791436420448,
-13.817967624570954,
-14.27690601975508,
-14.869169610252243,
-14.875990899314765,
-14.969783623924522,
-14.42066985439107,
-13.618703301653492,
-13.357375583553484,
-13.107520033422276,
-12.536392103732489,
-12.183648776908166,
-12.302452894747184,
-12.114040622611007,
-11.603012383676678,
-11.273781833545151,
-11.128519382372696,
-11.376411228076812,
-11.786515394745116,
-12.042365411022182,
-11.941182956594693,
-12.248606052299046,
-11.962266940969776,
-12.049341729381588,
-11.857208754120398,
-12.351958916882793,
-12.887223402562022,
-13.291229750219884,
-13.324509372615852,
-13.724278252825783,
-14.2239893530882,
-14.715432224183912,
-14.997740573794424,
-15.55026498785913,
-15.870762220933329,
-16.215082289294081,
-16.807604261952704,
-16.806622409739155,
-17.062679131745391,
-17.371600843986208,
-17.710804945550066,
-17.369068698803908,
-16.832047214426758,
-16.38887013109165,
-15.840531508042588,
-15.044921156476901,
-14.561333103089552,
-14.270394789286307,
-13.698078301653808,
-12.944687595270585,
-12.741547539931231,
-12.407614434461145,
-11.877465915578817,
-11.328042087451612,
-11.042736504768186,
-10.668185723516686,
-11.157354831591562,
-11.784706719614903,
-11.905629571177885,
-12.325655612846232,
-12.834358412327433,
-13.400422051652612,
-13.763655694232192,
-14.548310642151996,
-14.171176039285903,
-14.594457696188641,
-14.98497649501833,
-15.428205254785732,
-16.28567229580478,
-16.784918308176572,
-16.906926364817686,
-17.761654554925272,
-18.28007252367734,
-18.958274021075887,
-19.480722751546729,
-19.955939222902799,
-20.391209812097244,
-20.633468926681552,
-21.260510756111135,
-22.342511895438385,
-22.122783705333337,
-22.556142266532994,
-22.402353204032373,
-23.462236830338696,
-24.076256198830741,
-24.457834974873929,
-25.267501316023001,
-26.071173191026215,
-26.641319268502457,
-27.260299574494514,
-28.110066827102081,
-28.995077406532712,
-29.458201592732479,
-30.350240166954794,
-30.923641859665423,
-31.640445651985999,
-32.550002536755265,
-33.041342054986394,
-33.816023451473868,
-34.310360202777929,
-35.173459974916796,
-35.671879164371916,
-36.420205580390537,
-37.109052422841209,
-37.42526051203518,
-37.772681166333442,
-37.809061374666925,
-38.219217217767522,
-38.606532077795116,
-39.035756524411411,
-38.593767999019022,
-38.417448012039152,
-37.896187839511022,
-38.085323581699285,
-38.8094654274053,
-38.538267510737555,
-38.380034275059835,
-38.308514092767879,
-38.019332777662555,
-37.402936293285094,
-36.643602797188308,
-36.138362318670659,
-35.732754001611745,
-35.61229623793939,
-35.127261244447865,
-34.384722588845932,
-35.076825046530999,
-35.260534763328607,
-34.7073385556441,
-34.130267836240748,
-33.640478610978377,
-32.900007012668119,
-33.752771498348615,
-34.094766127256236,
-34.890118096660458,
-34.478670342752565,
-33.947953383115021,
-33.222778008763164,
-32.848072198214787,
-32.617233575166992,
-32.011224053680188,
-31.982646986622782,
-31.495803318001041,
-31.590422865527465,
-31.948488864877852,
-32.282266941051063,
-32.215966078420593,
std::numeric_limits<double>::quiet_NaN(),
7.523055324733164,
6.481775214051922,
6.197141424988288,
5.968369859232155,
6.76346344647493,
8.200843410673386,
9.824077663609557,
9.268426825391188,
8.56420624433369,
7.523055324733164,
std::numeric_limits<double>::quiet_NaN(),
-2.802154229344595,
-3.093764336767634,
-3.858472181822776,
-3.446300957862796,
-3.362636813982248,
-3.428679294451264,
-3.393435967628207,
-2.843650404474971,
-2.802154229344595,
std::numeric_limits<double>::quiet_NaN(),
-3.790931084817302,
-3.607376397316564,
-3.177221774919012,
-3.129317722184446,
-3.45906503663889,
-3.790931084817302,
std::numeric_limits<double>::quiet_NaN(),
2.174596258956569,
1.628531398928345,
1.540810655112878,
1.132385972494063,
0.258485826006194,
0.356412665199286,
-0.252077325037519,
-0.7800037573313,
-0.899996433113031,
-0.266598402511534,
1.011721503092545,
1.810690822757195,
2.174596258956569,
std::numeric_limits<double>::quiet_NaN(),
0.875192368977409,
0.917101955566125,
1.64325918213153,
1.419836127117605,
0.427881171058957,
0.235593166500891,
0.431136786293337,
0.381217352699394,
0.237246812334234,
-0.519657891444837,
-1.408905938323393,
-0.95596200928513,
-0.615672702643138,
-1.076213067228309,
-0.930950616055853,
-1.516858005381117,
-1.904482924002458,
-3.186058444840924,
-3.529500013852712,
-4.683693129091701,
-5.340603936385996,
-5.634591159694466,
-5.282933037948268,
-4.464171644715826,
-4.851331475446543,
-4.574552504091265,
-4.188477878438682,
-3.602105401222794,
-2.627642917494939,
-2.931603692235733,
-4.097579034037274,
-5.528241062037793,
-5.673400160345665,
-5.37987802492782,
-4.459417412944973,
-3.494411716326532,
-3.487021986508793,
-2.801999200047718,
-2.147103773612805,
-1.353147067880464,
0.154254462073482,
0.566477362465761,
1.30922272379685,
1.013943589681091,
0.875192368977409,
std::numeric_limits<double>::quiet_NaN(),
-10.258649997603591,
-9.557969252158074,
-9.361340427287502,
-9.665921319215798,
-9.969675388227429,
-10.239581394087885,
-10.258649997603591,
std::numeric_limits<double>::quiet_NaN(),
-8.536739597206072,
-8.460620212440148,
-8.094234307490765,
-8.649807631060696,
-8.933666273639957,
-8.810417982623839,
-8.444858900591122,
-8.236964613480914,
-8.536739597206072,
std::numeric_limits<double>::quiet_NaN(),
-8.362383314653293,
-8.280682875199844,
-8.705824883665088,
-8.906639499551304,
-9.040894870645594,
-9.032885023640354,
-8.457157891476591,
-8.449303073768228,
-8.095681247594939,
-8.362383314653293,
std::numeric_limits<double>::quiet_NaN(),
-6.42198495852574,
-6.777673841990705,
-6.877357679881726,
-6.465186455921747,
-6.946035658397626,
-7.594213148634594,
-7.776527601760328,
-8.370806573116873,
-8.751816908404855,
-8.348947442257405,
-8.376180922075221,
-8.302128594600973,
-8.122604668819001,
-7.740664157749762,
-7.641600437046243,
-7.766657403192576,
-7.354899590690934,
-6.924899997590252,
-6.851416110871206,
-5.895918877794472,
-5.954985039904081,
-6.345762220895224,
-6.42198495852574,
std::numeric_limits<double>::quiet_NaN(),
-1.084843031421059,
-1.782371514496766,
-2.340425306816705,
-2.428843682468099,
-3.061776625178965,
-4.305524997579774,
-5.85235564537242,
-5.873284600450632,
-5.037314955264996,
-4.220258884298183,
-3.614146009946801,
-2.799777113459164,
-2.050262139497832,
-0.650347588710986,
0.183141587724634,
1.042882391764536,
1.823506577965574,
2.45318390544206,
3.308790594898596,
3.868859768077925,
4.970782172053688,
5.479820868344788,
5.439513251157123,
5.246320909033955,
4.268370266126396,
3.590349636240873,
3.174328518075143,
2.099381211755741,
2.083697414555161,
1.398700466310231,
0.561361395668868,
0.104541734208695,
-0.711945896002902,
-1.059211521004286,
-1.084843031421059,
std::numeric_limits<double>::quiet_NaN(),
12.704496161342433,
13.466413479053825,
13.429697373910443,
13.069590155484519,
12.205560207564403,
12.704496161342433,
std::numeric_limits<double>::quiet_NaN(),
9.981044826696134,
10.26118276615037,
10.881868394408061,
10.94062449792392,
10.267383938025404,
11.232725531453738,
10.278778591345755,
9.950090643753299,
9.318268744336706,
9.022188625520414,
9.713360907424217,
9.981044826696134,
std::numeric_limits<double>::quiet_NaN(),
8.414706325713297,
7.750354112168978,
7.189406439640692,
6.274294338400054,
7.293715318221842,
6.786485297060949,
6.049656887227272,
5.581003322772276,
6.161355495626154,
6.885135606306136,
7.360610459823661,
7.83352732994274,
7.418875637232759,
7.457374579290204,
6.899424139834836,
7.192119452336015,
8.034962063016465,
8.316236883981134,
8.693035590037326,
8.240324204944372,
8.514157619659002,
8.960409450715488,
8.986996975129657,
9.760334784377534,
9.286074327018866,
8.782487494334561,
8.414706325713297,
std::numeric_limits<double>::quiet_NaN(),
18.197700913968575,
18.507681993071387,
19.367887885001906,
19.821038519769345,
20.101253973872033,
20.077534491450052,
19.695929877190721,
19.255879218009269,
18.678395087147592,
18.197700913968575,
std::numeric_limits<double>::quiet_NaN(),
24.3942735865194,
22.790857245367167,
21.970571397382113,
22.814860948166739,
23.556262722258236,
24.538450832613737,
25.295458889257386,
24.997595933527037,
24.3942735865194,
std::numeric_limits<double>::quiet_NaN(),
39.180864569651476,
38.174000962876619,
37.142074286440192,
36.343983466124499,
35.842877102190215,
35.138139756809792,
34.667600002576137,
34.606285915661829,
33.464805202766627,
33.849071153289003,
34.596544908174806,
34.375938218720805,
33.904933376596517,
33.885761420216241,
33.149992377244544,
31.450354519164822,
31.029579169228246,
31.418237616495432,
32.319474595665696,
32.610309556604363,
33.296055813117519,
33.604150702441672,
34.232742824840017,
34.749713853487918,
35.433393052709405,
35.731617743465804,
35.527134100886869,
37.304984239240326,
36.82739065199884,
37.827484646143461,
38.215988064113759,
39.43880748143637,
40.563312486323682,
41.195005194659529,
41.378559882160275,
39.991616115878685,
39.180864569651476,
std::numeric_limits<double>::quiet_NaN(),
43.960908718433608,
44.384732977875409,
43.262114162766764,
42.988358262700558,
41.995214748699198,
42.6787905950561,
41.584593817707969,
41.56955597591103,
42.563758856774385,
43.333272610032687,
43.388824774746439,
44.772125352551463,
45.551483466161343,
44.510358384776971,
44.174099839853739,
43.960908718433608,
std::numeric_limits<double>::quiet_NaN(),
40.899984442705225,
41.209991360024176,
40.500008856766129,
39.17737641047178,
39.240473334300148,
38.906617743478506,
39.171847032216547,
40.378310858718763,
40.950007229163759,
40.899984442705225,
std::numeric_limits<double>::quiet_NaN(),
42.628121853193917,
43.00998484961471,
42.152517808595654,
41.380006822264455,
41.583611965494427,
42.256542466799203,
42.628121853193917,
std::numeric_limits<double>::quiet_NaN(),
56.111407375708794,
55.609990953180741,
54.800014553437919,
55.36486379660424,
55.779954738988721,
56.111407375708794,
std::numeric_limits<double>::quiet_NaN(),
58.550845038478968,
58.635000108466286,
57.553024807355186,
57.690019029360947,
57.684799709699462,
56.870017401753486,
55.973793036515531,
55.909998480851215,
54.624986477265338,
54.464376125702202,
53.325014146530968,
52.92999949809191,
52.73952016866405,
52.099998480835978,
51.806760565795742,
51.289427802121793,
50.765738837275947,
50.774988918656192,
50.500018622431128,
50.69687999124703,
50.228355617872744,
50.341837063185707,
49.959999904981061,
50.159677639356858,
51.210001125689189,
51.426008612669207,
51.593466091511033,
51.991400458374599,
52.301355699261251,
52.840004991255597,
53.495003770555094,
53.404440822963593,
53.984999701546641,
54.615012925833014,
54.790971177786844,
55.061600653699386,
55.508472601943353,
55.783985500707487,
55.311146145236833,
56.275014960344862,
56.78500967063335,
57.818848375064576,
58.63001333275011,
58.550845038478968,
std::numeric_limits<double>::quiet_NaN(),
66.455892239031428,
65.808748277440301,
65.126671047619865,
64.364081936288684,
63.678749091233854,
63.49638296167582,
63.643634955491528,
63.960178941495386,
64.402115790455511,
64.891129869233495,
65.084968166760305,
65.378593655042735,
65.611189276788465,
66.262519029395222,
66.41046865504687,
65.732112128351432,
66.276626695410911,
65.993853257909777,
66.526818142352013,
66.455892239031428,
std::numeric_limits<double>::quiet_NaN(),
53.704577541714784,
52.740760403039062,
51.756660264688762,
50.747600409541505,
48.976390692737539,
49.306551418650315,
47.861575018904951,
46.836728013692522,
46.137907619809525,
46.740764878926512,
45.966755276058834,
46.805928860046563,
47.780132961612964,
48.85918854429957,
49.615163072297392,
50.952342434281903,
51.9354348822025,
53.301966457728795,
53.762145087287934,
54.225475979216874,
54.365880845753892,
53.704577541714784,
std::numeric_limits<double>::quiet_NaN(),
9.316382554558047,
8.367499904814679,
9.066888739452892,
9.684499619989211,
10.376292019080523,
11.3696680770272,
10.554291490109875,
10.003653265823829,
9.316382554558047,
std::numeric_limits<double>::quiet_NaN(),
18.224882717354106,
17.810282701076403,
17.093504746971973,
16.262444362854069,
15.931017564350142,
15.124813544164622,
14.328376369682275,
14.218202216035991,
14.336541245984378,
13.782130642141027,
13.237771104378425,
12.997527370653501,
12.536676947474575,
13.02752553959894,
13.552919826710422,
13.185836289925092,
13.784481919810304,
13.636687323455547,
13.857655747935596,
14.271015529838294,
14.52539276779504,
14.756670640517312,
14.396279201713796,
14.970869452367126,
15.406346747290739,
16.363704331929995,
16.034628811095345,
17.599081122299523,
18.505227362537525,
18.504064642810945,
18.218552354398355,
18.478975734933243,
18.224882717354106,
std::numeric_limits<double>::quiet_NaN(),
11.415840969279998,
11.891755072471994,
11.582213243043682,
11.583660183147856,
11.16593374271649,
10.74130849857417,
10.441016750526089,
10.905691229694625,
11.415840969279998,
std::numeric_limits<double>::quiet_NaN(),
12.162694606978292,
11.046147772663929,
11.311454576050409,
10.975816148314692,
10.358722032101284,
10.134678859899864,
10.837995103392258,
10.889929917845592,
11.495370998577187,
11.415582587118536,
11.794189968304947,
12.557760931849671,
12.53572093347718,
12.162694606978292,
std::numeric_limits<double>::quiet_NaN(),
8.67050466555807,
8.638749497914716,
9.336820583529487,
9.443248195834599,
9.774003200718738,
10.618990383339309,
11.083044745320322,
11.102035834187587,
11.310472723836867,
11.22701528568548,
11.731971543825523,
11.955549628136326,
12.437303168177309,
12.376040757695293,
12.112981879113505,
11.776284084515808,
11.539993597861212,
11.423282375530022,
10.969459947142795,
10.446494452349029,
9.865651353388373,
9.072263088411248,
9.137220363802129,
9.859992784052409,
10.211935126176215,
10.968969021036015,
11.375481675660041,
11.846822414594214,
12.162307033736099,
11.459610907431212,
11.443384507691563,
10.885744126829946,
10.554653225135922,
10.54586823164631,
10.648626817258688,
10.200798855017323,
10.077214667191299,
10.38959870039568,
10.64141795495398,
10.7017243514386,
10.715625311725104,
10.420268662960906,
9.94820445397464,
9.873066921422264,
9.381339829948942,
8.580174261911878,
8.602756862823426,
8.367034816924047,
7.999201971870492,
7.347691351750697,
6.832787380394464,
6.809093736188643,
6.321268215353356,
5.973149929219161,
5.772877915872002,
5.95312531170606,
6.025291449401664,
5.756548163267765,
5.646529038918374,
5.409850979021584,
4.565768133966131,
4.156232408053029,
4.120007229016437,
3.650397650564031,
1.901563828942457,
1.736483465986069,
1.046189683431223,
0.222984117021682,
-0.078444512536819,
-0.235489190271821,
-1.237805271005001,
-0.5816179337628,
-0.941027520352776,
-1.551739597178134,
-2.137750339367976,
-2.691308282078524,
-2.383110039889793,
-2.912018324397116,
-2.873054294449041,
-3.700652357603396,
-4.820945733258917,
-5.109403578312154,
-5.149504489770649,
-5.464937432480247,
-6.738193047719711,
-7.343220716992967,
-8.996401462442286,
-9.649281508017815,
-11.040721123908803,
-12.171194756725823,
-13.038118584854288,
-13.057652276260619,
-13.793369642800023,
-15.667053724838768,
-17.208406670808472,
-17.867746270420483,
-18.262295830968938,
-19.599113457927409,
-20.904511814052423,
-21.937316989837811,
-22.370675551037458,
-22.970070489190896,
-22.967693373305469,
-23.351959323827842,
-23.796841729428582,
-24.088968601174543,
-24.885199069927722,
-25.877024834905654,
-26.62364592865864,
-27.175911960561891,
-28.18613453543572,
-28.674115085567884,
-29.224469089476337,
-30.98446502047296,
-31.777698256153212,
-32.24536996839467,
-33.196578057591182,
-33.768377780900764,
-34.396814874002231,
-34.952646579733624,
-34.752658786764073,
-34.859835707337417,
-34.430456231424245,
-34.462547295877499,
-33.909454441057576,
-34.431489760070079,
-35.288026625307879,
-35.977390232081476,
-36.413125909166553,
-36.901571547189334,
-38.183870538079887,
-38.720168552404942,
-38.928424574541197,
-38.827707208004334,
-39.424104913084847,
-40.172586358400338,
-40.676896661136723,
-41.028761488612098,
-41.166789239263693,
-40.802677097335149,
-41.064314874028909,
-42.05800099056934,
-42.359016208669509,
-42.043686618824495,
-42.563138116222405,
-42.873558444999688,
-43.495380954767796,
-44.501366062193696,
-45.036785577169795,
-45.039627780945857,
-45.55189625425519,
-46.30177296324257,
-47.033872979521526,
-47.23613453551193,
-48.133289076531135,
-48.697337334996945,
-49.869668877970383,
-50.264166762086539,
-50.732510267947795,
-51.77110320414986,
-52.349982598683425,
-52.299443047901974,
-52.291949965219658,
-52.53792978292897,
-52.899199721081459,
-53.833251234757071,
-53.856453952856121,
-53.531409193740238,
-52.835069268607235,
-52.262752780974751,
-51.629354750373253,
-51.043395684615703,
-50.378371677451582,
-48.673772881871841,
-47.711919447623202,
-46.939253431995112,
-46.647643324572073,
-45.763976332381027,
-44.103044122087937,
-44.454960625995604,
-42.383355808278978,
-42.117532240569574,
-43.365776462579774,
-43.224958184584423,
-41.794812920906828,
-39.942212823243167,
-39.258688653318558,
-38.282882582351114,
-37.156284681955981,
-37.123780206044387,
-35.508840020491057,
-33.909092706031529,
-32.418899428030777,
-30.920644626592495,
-30.095682061485029,
-28.861442152625923,
-27.640379734001247,
-25.705924167587256,
-23.628996677344574,
-21.393319187101259,
-19.756468194256165,
-18.347975355708869,
-17.773746840081571,
-17.363487644116383,
-16.359362888252996,
-15.265682875227782,
-14.649286390850321,
-13.823186944232432,
-13.535039157772943,
-12.22271615972082,
-10.377712497604065,
-8.386567884965892,
-7.93083342858386,
-7.194340915560084,
-6.541667575713717,
-6.136834405139183,
-5.690556735866565,
-4.736764825055459,
-4.036394138203697,
-3.404856459164713,
-2.65751189535964,
-2.220794366061014,
-2.685158786635788,
-2.246942640800704,
-1.965047702648533,
-1.057454522306358,
-0.906662692878683,
-0.283703301600141,
0.360340074053468,
0.768428859862397,
0.982937730305963,
1.380923773601822,
1.691369940595251,
1.766404120283056,
2.267355454920477,
2.629555568854215,
2.696605739752926,
3.325016994638247,
3.849636135265357,
4.087606105969428,
4.667984117039452,
5.582811997902497,
5.84535411216136,
6.691116441266303,
7.223771267114785,
std::numeric_limits<double>::quiet_NaN(),
-52.837498060924958,
-53.047407728894548,
-53.715377292699308,
-54.07432179139866,
-53.615848484105157,
-52.931239109102421,
-52.518292738658062,
-52.636270033580402,
-53.100014336967668,
-53.849994398819632,
-54.450009454160579,
-54.700020033588665,
-55.199989516012536,
-55.25001230247107,
-54.896803887756114,
-55.301223646872309,
-55.611850681378769,
-55.580017999086969,
-55.499041029685614,
-55.198439223043778,
-55.053848565491123,
-54.495122979551383,
-53.957533054419024,
-52.837498060924958,
std::numeric_limits<double>::quiet_NaN(),
80.589809882317141,
80.771917629713684,
80.784009914869984,
80.514568996900167,
80.753985907708397,
80.918885403151776,
80.699725653801934,
80.54728017854093,
80.415427761548202,
80.339566758943747,
80.175468248200886,
80.010181179515328,
80.247246812654296,
80.559424140129508,
80.589809882317141,
std::numeric_limits<double>::quiet_NaN(),
73.749813951300197,
74.627486477345357,
75.081412258597183,
75.609390367323257,
76.251883450008123,
76.439055487769267,
76.80978221303117,
76.939696763812933,
76.544811306454605,
76.233641669409067,
75.737754625136247,
75.260884507946841,
74.309056301562848,
73.333043524866227,
72.371267605266027,
71.540594794390316,
70.720463975702117,
70.632743231886664,
70.762657782668455,
71.206661688920221,
71.474759019650449,
72.014881089965129,
72.229441636840974,
72.774731350384812,
73.6275475124976,
73.749813951300197,
std::numeric_limits<double>::quiet_NaN(),
80.056405748200419,
79.517833970854511,
79.40003754344518,
79.566823228667218,
79.84236196564747,
79.859880276194431,
80.318896186026976,
80.598155626132254,
80.357679348462042,
80.657144273593431,
80.407340399894522,
80.056405748200419,
std::numeric_limits<double>::quiet_NaN(),
77.853852851056175,
77.444937242330596,
77.677041937969548,
77.935036526186721,
78.25462942169581,
78.454953111475263,
78.079523830874805,
77.853852851056175,
std::numeric_limits<double>::quiet_NaN(),
79.674310207834296,
80.016098131012754,
80.050876369945186,
79.701750393381289,
78.956111151841853,
78.562595119939218,
77.826671047670672,
77.637948716940727,
76.809420478005123,
76.770456448057061,
77.380341701965747,
77.735668850404679,
78.024927680158427,
78.869294745591489,
79.652399400542535,
80.010465399892936,
79.660409247547776,
79.674310207834296,
std::numeric_limits<double>::quiet_NaN(),
7.223771267114785,
7.512254950384161,
8.052041123888927,
8.319182440621773,
8.387705389840789,
8.718124497915028,
8.996092027213024,
8.932374986197146,
8.584515082224399,
8.333315944853595,
8.298408514840432,
8.090307522001069,
7.547524115423372,
7.419754136581716,
7.271571966984765,
7.220541490096537,
7.817921047390597,
7.64790558515034,
7.706610012233909,
8.108962714058435,
8.175392767769637,
8.292362372262289,
8.291613063994063,
8.290863755725823,
8.073822740099956,
8.225053819202117,
8.446926581247283,
8.656836249216866,
8.830443223501419,
9.051385809765321,
9.290802720573581,
9.487354030795714,
9.615537421095709,
9.908051866083852,
10.086723130733006,
9.795991522658923,
9.55703969974131,
9.83454214114866,
9.933347479690724,
10.134885565629034,
10.439337266476613,
10.754330959511719,
10.824791774941687,
10.895278428587801,
11.088444932494824,
11.403438625529944,
11.806876532432597,
12.143961900272487,
12.458257961471658,
12.909909979702633,
13.064551703336065,
12.914018256069838,
12.984685777228975,
13.297534898323974,
13.341020616097595,
13.384480495655055,
13.149016831917137,
13.163951320849492,
13.259759426318624,
13.458532823129303,
13.520622056527998,
13.735337632700734,
13.909771429901951,
13.927832342987957,
14.126218166556455,
14.538828640190928,
15.615429592343673,
15.940190131081948,
16.200975246642884,
16.128318182840516,
15.752087917539525,
15.653515122942778,
15.917064927631332,
16.107311713113859,
16.566043402568823,
16.70616404872824,
17.171071071842078,
17.649026394109612,
17.91609019619402,
17.975750637274984,
18.292294623278849,
18.748571682199952,
19.316133938061597,
19.946767279535479,
20.434101874263987,
20.531718654863337,
20.81689504646604,
21.076284898355102,
21.422103583252305,
21.871145941652546,
22.269080308516124,
22.773752346278556,
23.767800197845034,
24.548915310152836,
25.172313951105863,
25.580609442643951,
25.824883938087634,
26.442934068298442,
26.676175645447817,
27.162114976504441,
27.859876003525457,
27.941240546169013,
28.467952582303937,
28.954408677683489,
29.266844387320145,
30.021113593052338,
30.786880804969456,
31.170965887978809,
31.567608344035076,
31.524045111613034,
31.799532172161012,
31.393484605427616,
30.913617255165278,
30.162681179315925,
29.750432440707495,
29.061611436472973,
28.826173610951205,
28.754782619739981,
28.411289374295894,
28.42519033458241,
27.780216783147537,
27.525813706974642,
27.171752631126875,
26.662817287700364,
25.732589830014348,
25.294632066340721,
24.826004340101861,
24.298594672130999,
24.265547593680353,
23.811182562754055,
23.364672349536121,
23.185587673428643,
22.818271592697997,
22.82307750090115,
23.430973212166592,
24.00096426034597,
24.484423122652586,
24.738412787367135,
25.470125230403927,
26.0120042994165,
26.321959540303165,
26.768185533143495,
26.639459540304426,
26.900063788352352,
27.142090358991343,
27.722726752222822,
27.798200181585113,
27.741485297144777,
28.115002549750443,
28.566111965442342,
29.279479275015515,
29.556361599235373,
30.180793768834224,
30.836464341753512,
31.635743720011916,
32.535327053348851,
33.046224615203748,
33.621236431201282,
33.740909223124468,
34.02778157757573,
34.078,
34.34847717828417,
34.447096665986706,
34.608559678682667,
35.156872463515583,
36.161513983701894,
37.551765041650171,
37.783378811182345,
38.113694566391999,
38.951653754220871,
39.766978664705903,
40.313198554031004,
41.142036851560363,
41.999633083660157,
42.76599,
43.70838,
44.615895,
45.52341,
46.86475,
47.72017,
48.184432983398438,
48.379714965820305,
48.04,
47.095988674500845,
47.360003567080028,
48.180005194687482,
49.0,
49.002537777777782,
49.984572048535846,
50.416561184279757,
50.830592759802244,
51.715835883178187,
52.329622707724909,
52.755384833377661,
53.56158885356318,
54.287565212615561,
54.802753404349396,
55.17890615500194,
55.497775580458928,
56.369996242897322,
57.178887437562025,
58.123067531966839,
58.187714748763966,
58.212209377670327,
58.499995429103762,
59.537761542389163,
59.727517401764928,
60.084446519604903,
59.999180406323305,
60.458609727614196,
60.88465607364455,
60.672989406977045,
59.978328965893525,
59.914172675203176,
59.70565827090546,
59.368211168039522,
59.155821031319938,
59.744984035879583,
60.725802720779328,
61.033587551509726,
61.284450792070629,
60.727197984451209,
60.061657212964178,
59.35027944603425,
58.864727688219801,
58.14637360293046,
57.727794501366297,
57.422774359763515,
56.979984849670601,
56.463608099994048,
55.994153550838533,
55.566686102920151,
55.643580634170462,
55.364734605523509,
55.024186916720069,
54.689737046927071,
54.404173082082167,
54.572224839895341,
55.039431464246164,
55.348043117893234,
55.894986477270422,
56.008054511125039,
56.418055324928773,
57.016675116597824,
57.216947129944984,
57.570000515363063,
58.328326321030161,
58.918884589261694,
58.61580231386985,
58.787781480537205,
58.424186102931586,
58.931390285876319,
58.572549140041559,
59.071123358793535,
58.670837714260699,
58.671664537177364,
59.266951198963596,
59.633621324290587,
59.989723619213891,
59.798055731843334,
60.267484442782703,
60.507495632562311,
61.073895168697391,
61.500019029376176,
62.074996853271713,
62.633076483807798,
63.14637848576298,
63.219448961023673,
63.059458726648039,
63.541961574957256,
63.455816962326722,
63.76610810002326,
64.222798570402702,
64.402787584075284,
64.788603827566405,
64.777235012462214,
64.559444688568092,
64.338605455168775,
64.559160468190512,
64.446945095468706,
64.686672064870706,
65.088895575614501,
65.669997056736619,
66.088317776139334,
66.576660061297517,
66.576660061297517,
66.077207343196577,
66.116119696712346,
66.735565090595045,
67.116394558370004,
67.616338202577722,
68.042772121850263,
68.35887685817967,
68.883030910916133,
68.915535386827727,
69.371114813912882,
69.858061835399198,
70.333329983187568,
70.447689927849481,
70.891642157668954,
70.824721177850975,
71.35776357694165,
71.147776394323628,
70.696408596470249,
70.889988511835625,
70.829992173944746,
70.600006212029783,
70.430016588005643,
70.530010484490433,
70.214034939241756,
70.120009670686713,
69.989991767040365,
70.152514146598307,
69.851964016388749,
69.711998399526223,
69.471005357533059,
68.990001125760315,
68.898017076280766,
69.315123399524637,
69.62742991808058,
69.505344346791006,
69.944516506623515,
70.193700263134915,
69.779255276154103,
70.012858588329507,
70.483837592237634,
70.377203274203353,
69.480565497507072,
70.158405259879558,
69.399691880970281,
69.563712877064674,
69.855529690216898,
69.797781277130738,
69.377858588326959,
69.011291815864567,
68.841483059353479,
68.905923570421422,
68.398900254989726,
67.902625637474713,
67.688168443463425,
67.806094061953488,
67.981044623477615,
67.381442979595008,
67.887329413516326,
68.311644599064877,
68.65394928656626,
68.699992987738327,
68.799986884223088,
68.561215928818498,
68.018019110782475,
68.097755845808834,
67.646878974062233,
67.805628974062856,
67.781651109479427,
68.403938707138181,
68.578656724716993,
68.239400946720835,
67.293386338969654,
68.090702012800975,
68.063830268009198,
69.06901439073458,
69.685720933705809,
70.089778957795957,
71.194827785925369,
71.920519924600157,
71.760167955198469,
71.318696194129004,
70.191271470817199,
69.699983629018348,
69.497670396595666,
68.474993801539497,
69.258718573678053,
68.615088609482754,
67.873376776797514,
67.198740953227102,
67.921461697045103,
68.78456146918397,
69.88209137641492,
69.805403550893786,
69.65825490994267,
69.162031968859949,
68.665679836696498,
68.132534084741266,
67.597166246197432,
67.110787665466333,
66.411553860124982,
66.257299709733743,
66.558314927833905,
66.056252549902226,
65.212970689547276,
64.775633043061148,
64.09898183863136,
64.032732652433182,
63.610174465582546,
62.96021413843151,
62.83507965763674,
62.024689846435564,
60.898660386795655,
60.110207221102385,
58.948805243558688,
58.782122911201242,
57.845720119856352,
57.087084255595499,
57.284669094463482,
56.85172394472216,
56.471617946999288,
55.999114488338549,
55.723834133519745,
55.302619533908683,
55.244896959038655,
55.148313707085151,
54.282268378305645,
53.277032579147971,
52.157850246786722,
51.208399156288138,
51.533934841510785,
52.562063300173762,
54.141450100310273,
54.667722886770719,
55.136453965874168,
55.837418931697272,
56.534223944720893,
57.202632758200139,
58.052089952213947,
58.804576321032059,
59.852626044343552,
60.757893785232589,
62.319658921957583,
62.550549221437677,
62.278395290772522,
62.18111440698307,
62.443785712322665,
62.105072536865578,
61.52536631941534,
61.137198798254943,
61.061415310298905,
60.22123403588148,
58.957357693102992,
58.801062323636216,
58.212054348373442,
58.767317613349618,
59.870712795645701,
60.335593980543401,
59.44257355410754,
58.167095852279509,
56.967427476623662,
56.33945547141284,
55.775484727595469,
55.204072577528081,
54.945483710339545,
54.626485093801804,
53.780335191454668,
53.647475084032266,
53.270366319382319,
52.146636460979394,
51.770690416056013,
51.419704087929603,
51.064299424842254,
50.242773342482195,
50.080457668653409,
50.290987453810502,
50.298170477899077,
50.22897573506026,
49.511551825552175,
49.068374742217074,
47.744889634789899,
46.821716010111729,
46.986072903016037,
48.29999787046922,
49.133073635446493,
49.232783311553675,
48.742503160184526,
48.070864569687046,
46.992971706727005,
46.238495795265649,
45.739017238948541,
45.883762925798081,
47.007932033875505,
46.282653306659057,
45.920401516293026,
45.265247707696645,
44.670141913423436,
44.265515448578071,
43.545249335293931,
43.618681545580685,
44.46511566830543,
45.292041937839983,
45.259304917983087,
45.137503567071128,
44.8097,
44.3252,
43.98,
43.68405,
43.090238348963993,
42.865290839197471,
42.334987291018265,
41.804993801432822,
41.780008246419683,
42.144998887697184,
41.922816067058278,
41.637174587564957,
41.474988104816909,
41.4944442815748,
41.319984646157437,
41.269987697915042,
41.220636705076302,
40.93110235165436,
41.119480088864961,
40.930008449866804,
40.630000922196345,
40.628011379553101,
40.75075,
40.4734988470004,
40.42763,
39.70925608983589,
38.939535630848425,
39.196393337555193,
39.248457343089242,
39.498493760733481,
38.959999498036012,
38.782032230179233,
38.40412,
38.015509345037444,
37.216901760398827,
37.256589260398982,
37.93705,
38.319215,
39.15,
38.717615,
38.08326,
38.239991766913334,
37.917945,
36.9664,
36.89726,
36.551257636047211,
35.550750230444251,
34.808547471652219,
34.51201,
33.92547,
33.861344305958326,
33.49395,
33.15839,
32.509355,
32.0333,
31.44049,
30.729985053016108,
30.03552,
29.180002142853652,
28.47213,
28.039994208278785,
26.88,
26.205765,
25.816775,
25.20616,
25.079994004816427,
25.201252753189308,
25.639985663347304,
25.869997463478445,
26.729996649679791,
27.49504,
27.88624,
28.54998891856728,
29.1,
29.93656,
30.09,
29.63615,
29.68612,
30.15261,
30.400005194616355,
30.274328111282514,
30.384915676387124,
30.31598,
30.159994004836747,
29.89419,
29.48864,
29.29108,
29.15961,
29.30714,
29.11743,
29.148535,
29.677,
29.5523,
29.78375,
29.71363,
29.480009670524126,
28.738633734648772,
28.307471421821518,
27.830007025660766,
27.380008653263118,
26.68999909108588,
26.210002549742825,
25.869997463478445,
24.992144069920244,
24.272343044526735,
22.932579860927632,
22.444211737553271,
21.898689480064121,
21.411018988525711,
20.635433254473128,
19.890930894444111,
19.320397243725679,
18.828024196848702,
18.562717393462222,
18.144370835843361,
18.423836981677823,
18.524838568592287,
18.704595038319567,
18.876083278880145,
19.284120388256781,
19.867418117751299,
20.707521877520293,
20.999855454995412,
21.261725775634488,
21.493675441976563,
21.458845526611839,
21.54354319913821,
21.331514797444655,
20.849864610268256,
20.255404771398688,
19.646553046135836,
19.472403469312226,
19.040130113190699,
18.259815985583415,
18.516647854074023,
18.499982204659901,
18.353272813383271,
18.348673610909287,
18.07667470954101,
17.644142971258034,
17.489475409408456,
17.131693630435663,
17.036066392479555,
16.530774237529627,
16.265467434143147,
16.233660590067501,
15.887273464415076,
15.70638011317736,
15.855389105690975,
15.71999685308627,
15.688655096901257,
15.86445831955821,
15.878798529519202,
15.797278957578769,
15.846940009011263,
15.756712958229656,
15.782835394753191,
15.893448798073948,
16.005405788634292,
15.953651841693983,
15.885749009662463,
15.909158433490672,
15.995923163308731,
15.857223619037342,
15.835157782448718,
15.648244126849006,
15.424071763566857,
15.270902818253745,
14.995829169164111,
14.899866034398102,
14.676623846897201,
14.31070302983845,
13.970077826386557,
13.567699286345883,
13.127054348193086,
12.869292303921227,
12.419087225794428,
12.320850328007566,
11.893124497927728,
11.62903209070012,
11.373311265503787,
11.103043524617275,
10.938764146361422,
10.785000922076946,
10.395438137244653,
9.992982082555557,
9.566160590040823,
9.207448635286781,
8.9955752628901,
8.950616766796173,
9.031955471223583,
8.786234035675719,
8.858503526235907,
9.111072089062432,
9.312765204297619,
9.611610012241528,
9.552931423374105,
9.454565334506526,
9.420458889193881,
9.247730414258299,
8.946844387238869,
8.67050466555807,
std::numeric_limits<double>::quiet_NaN(),
19.714455878167357,
19.8849105900821,
19.904986884027494,
19.880285549391985,
19.622885240146161,
19.647999986240009,
19.293267116772441,
19.313214219637103,
19.015196234609874,
18.979100246653999,
18.612197577381693,
18.205142320218613,
18.422648423735112,
18.38071299893025,
18.428306993071061,
18.245915025296895,
18.184290879788833,
18.426885891183034,
18.283328762276213,
17.598564357976599,
17.757572740138698,
18.044997056546094,
18.21496084235406,
18.145611070218365,
18.2179063989947,
18.030992743395004,
18.342549953682706,
18.664907538319412,
18.526052964751145,
18.445799465401862,
18.668421535715254,
19.101625067618031,
19.483591416903408,
19.639550889560283,
19.915683905511912,
19.871500555902358,
19.714455878167357,
std::numeric_limits<double>::quiet_NaN(),
38.143873602850462,
38.231180935207576,
37.444045518537763,
37.134219468731828,
36.619987290995397,
36.996630967754726,
37.104531358380157,
37.612949937483748,
38.126381130519661,
38.034965521795328,
38.143873602850462,
std::numeric_limits<double>::quiet_NaN(),
44.657222805350479,
44.279984849619794,
43.434997666999223,
std::numeric_limits<double>::quiet_NaN(),
33.463642483040061,
34.060298570282043,
33.944620876596673,
34.364931138642632,
34.149233710256354,
33.806334743783623,
33.201177883429636,
33.521985175097598,
33.289570420864891,
32.704567369104737,
32.989382025681394,
33.463642483040061,
std::numeric_limits<double>::quiet_NaN(),
68.963646145291463,
69.400001939564035,
69.87725,
69.81743,
70.09703,
69.65276,
69.01363,
68.6938,
69.568768316486583,
69.47199,
69.66823,
69.64204,
69.43728,
69.72198,
70.45324,
70.86672,
71.03141,
70.84221365018179,
71.606430569130154,
72.199986070434605,
72.84941,
72.41619,
71.48783,
71.62803,
71.34763,
71.65525,
71.38642,
71.8363,
70.786997382277903,
71.19304,
71.98,
72.39872,
73.03871,
73.56549,
73.56,
73.73503,
72.971205145958535,
73.12,
73.58772,
73.75285,
73.59488,
73.33505,
73.97693,
73.78774,
74.04,
74.18,
74.47673,
75.031854560029259,
75.32779,
75.84764,
76.22224,
76.71,
76.723353380023028,
76.47998322214444,
76.974190782367756,
77.127385565897029,
77.373882147929251,
77.69791921661546,
77.287530829569548,
76.861872056781394,
76.430270494279668,
76.446884467261484,
75.91546987578802,
76.140003974096217,
76.047193101699989,
75.773333848769212,
75.639982815240032,
75.143940741670335,
75.116448879691077,
74.459667263477499,
73.936882636196756,
73.805908718552999,
73.850014553514129,
73.648218085414371,
72.582856757285086,
71.749987698036975,
72.320107937297067,
72.267165432414046,
71.87401,
71.15287,
71.33556,
72.30056,
72.85497,
72.83227,
72.12119,
71.44717,
70.63175,
69.62763,
69.07146,
68.98918,
68.32899,
67.76047,
67.28429,
66.78946,
66.53267,
66.17267,
66.32,
67.7404,
68.4079,
69.020851955838552,
70.39114,
71.09019,
71.40898,
72.22006,
72.77629,
73.04,
72.84336,
71.9345,
71.02897,
70.70889,
69.92873,
69.45461,
69.35649,
69.14436,
68.61563,
68.09233,
69.234835,
69.547383124460467,
69.850000311961665,
69.52,
68.94069,
68.27844,
68.88082,
68.46628,
68.43866,
68.086846481688369,
68.20131,
68.80815,
68.85738,
67.52238,
66.88455,
66.66767,
67.010044460713331,
67.56652,
67.68997,
68.249994615340668,
68.570801907008629,
67.961614284935877,
67.352426662863124,
66.756339016376373,
66.06908,
66.41858,
66.47623,
65.49682,
64.76446,
64.52079,
65.14322,
64.76446,
64.33471,
63.84983,
64.10945,
64.41437,
65.436212877048163,
65.90015,
66.632522284605059,
66.759594631610767,
65.999537665461887,
66.26618,
66.791582343199437,
67.457123114686468,
67.932391262474837,
69.063433336047055,
69.301403306751141,
69.905965888133764,
69.558080145944885,
70.186258856884891,
70.453787746859902,
71.185474351680554,
70.986261705195389,
71.030496731237221,
70.202071845166202,
70.2551693793461,
69.817444159617779,
68.563205471461728,
67.810641587995164,
65.879725857193179,
64.486038316497499,
63.45400828719648,
62.614472968182724,
61.970998033284317,
59.663231919993834,
58.588155422593701,
58.078884182357285,
58.313288479233215,
59.469807033925356,
58.856149400459358,
57.441817125063068,
56.30708018658197,
55.361737372450577,
55.407781073622651,
56.200885118222175,
56.104301866268663,
57.041118069071885,
58.719826972073392,
58.953766181058697,
60.081914374422595,
60.636583360427409,
61.341165676510968,
62.74940013289681,
63.609554348395037,
64.413587958424287,
65.026005357515274,
65.723740546320172,
66.006927395279618,
65.534346421970454,
65.111426500093742,
64.902343655040838,
63.817810370531291,
63.18973501245587,
62.60739329695874,
61.705329494871791,
60.720169989659524,
60.391921291741539,
59.846373196036225,
60.057316392651657,
60.423960679762502,
60.503516547275837,
60.028067531974457,
59.475388088612874,
59.445803331125774,
59.611090399811332,
59.465853786855021,
59.187240302153384,
58.612753404364625,
58.257374579493408,
58.383413397853289,
57.793423570376973,
57.025692654032767,
57.006236477274868,
57.753374335350763,
57.411870632549935,
56.783872789122938,
56.031076361711065,
55.190481675835315,
54.866160386771512,
54.426083889373928,
54.43871877706929,
54.682605699270781,
54.851535956432912,
54.513158677785725,
54.050706285205749,
53.75702912049104,
54.075510972705857,
54.470370591848052,
54.196485500701129,
54.008693345752469,
54.363607082733054,
54.596641954153256,
54.983104153048032,
55.469999498102055,
56.190007229224733,
56.081383368547208,
56.458621324277885,
56.609981594460791,
56.890016181050441,
57.215732733786119,
57.73001658795485,
57.447940782289663,
57.172066148499503,
57.110002753316948,
56.809969387430328,
56.540011705137587,
55.517722683323598,
54.96274363872503,
54.395646470754016,
54.020785630908762,
53.527792466844296,
53.748295803433706,
53.693932196662658,
53.482162177130562,
53.510403347378073,
53.09179840759775,
51.620544542031958,
51.345780951536092,
51.148506171261857,
50.9466063502975,
50.127173163445264,
49.347375800160911,
49.776341864615745,
48.644421291694542,
48.901692409859628,
48.68416046812699,
47.954954332056374,
47.570326646507951,
47.064362697938222,
46.014917710954862,
44.022610378590116,
43.422802028978339,
43.455900783861303,
43.403449205085039,
43.574239813809683,
43.567909450853925,
43.748337714200993,
43.026624660812701,
42.592775173506269,
41.880570583659676,
41.543459377603639,
41.184334011391257,
40.760638943030187,
40.159306138665812,
39.755093085278773,
39.39206614842837,
38.737429104154913,
38.358485826158599,
38.266243394517616,
37.651345526676607,
36.868809312480778,
36.978880113262463,
36.838268540996268,
37.097787583966067,
36.942913316387319,
36.367677110330334,
36.029816596006057,
35.946850083961465,
36.324708156879637,
36.677839056946155,
36.65889964451118,
36.674144192037289,
37.443063666324221,
37.642353827457825,
38.292365831041153,
38.73851430923304,
39.30997813573272,
40.123933620762017,
40.678318386389236,
41.014731960609339,
41.226088568683096,
41.892120266276905,
42.473015041669861,
43.075200507167054,
43.399650987311595,
43.128892320318315,
43.693844916349221,
43.767147935555244,
44.231228135752417,
44.366336167979512,
44.03627879493132,
43.920006822274601,
42.93146251074721,
42.355425319989699,
41.704534817057407,
41.253089504555604,
41.1882872584616,
40.786347968095399,
40.604550279292596,
40.17294871679087,
40.048356838535156,
39.544072374014917,
38.964547024077703,
38.75094249119924,
38.214592800441878,
37.908849188787016,
37.985898749334197,
38.843572496082416,
38.902871202137348,
39.424699815420681,
39.795400702466438,
40.44223460546381,
40.277671006830346,
39.810774441073264,
40.168866278639811,
40.35562490494263,
40.877143459632222,
41.179605617836557,
41.541082261718216,
41.740294908203389,
41.961315009115715,
41.955139675456849,
42.761007798832466,
43.587727362637864,
44.091365871754462,
44.600482082693986,
44.885374253919096,
45.381778062514826,
45.736691799495418,
45.591015936864622,
45.500323798192376,
45.484149074885018,
45.136935126315933,
44.802123521496881,
45.233776760430899,
45.076060289076096,
44.738483995129442,
44.317915350922036,
44.243191229827985,
43.507215481127119,
43.209998480800401,
42.849994615239069,
42.47999136002926,
42.281502183596174,
41.955010484376118,
41.877547512370597,
41.719986070312672,
41.409565741535388,
40.727230129553504,
40.250773423822423,
39.915005805005976,
39.694993394523323,
39.624997666983987,
39.340234686839622,
38.769985256498799,
38.310323391262585,
37.64498932550471,
36.844986477194212,
36.410000108377375,
36.422505804992014,
37.305010077456473,
37.40999074965741,
37.920011298162066,
37.655014553369327,
38.219992987616379,
38.510001125638382,
38.9709032252496,
39.190011298167136,
39.659310818025787,
40.256561184239118,
40.476005153966554,
39.96099782974575,
39.962005520175438,
40.124992987624012,
40.687129218095009,
40.947061672523134,
40.852545477861298,
40.824123440100763,
40.617753607743168,
40.151993923496505,
40.69056570084242,
40.999823309893138,
41.054962063148558,
41.299934190428189,
41.622886054036243,
42.007358710287789,
42.577892361006221,
43.293171698574184,
43.707461656258133,
44.913873806328056,
44.820210272799045,
45.035390936862399,
45.293308010431126,
46.03241018328567,
46.583100084004002,
46.706245022155542,
46.333347886737386,
46.080598456397844,
45.851568508480241,
45.519185695978912,
45.327466132176077,
45.03477081967489,
44.564877020844889,
44.361478583344073,
44.939996242851606,
45.113215643893966,
45.469989732437057,
45.409993394546191,
45.651218980484657,
46.273196519549643,
46.645964463887069,
46.698700263040934,
47.022220567404204,
47.102189846375886,
47.263368638694232,
47.044725653667314,
46.636585191426093,
46.240872911151072,
45.404515692723251,
45.244680487644487,
44.657222805350479,
44.279984849619794,
43.434997666999223,
43.128633938156845,
43.013628038091284,
42.64512339941794,
41.962942816732919,
41.535656236327569,
41.013672593747351,
41.102762763018553,
40.948586127275732,
41.33535838476427,
42.040224921225416,
42.018960069337311,
41.736264146484615,
41.087621568357022,
41.219990749672668,
40.460011298172212,
40.420013739578309,
39.463612168936464,
38.985760199533516,
38.208133246405396,
37.653360907535998,
36.658822129862742,
36.676831366516467,
36.144357408180994,
36.26298065850699,
36.677864895162301,
36.64427521417258,
36.107563788389186,
36.219960028624016,
36.795532131490901,
36.565442816711325,
36.650605577128331,
36.274995429014851,
35.821534735653671,
35.410009467097325,
34.644914048800004,
34.610058295219133,
33.905450140919442,
33.090900376918782,
33.080539252244265,
32.827376410446377,
32.072926337201167,
31.605538845337321,
31.548823960896996,
31.219360866820153,
30.967464097613416,
31.024075629189156,
31.260340277627606,
30.933616034462233,
31.429606431599638,
31.555851955688681,
31.473402207966998,
31.186856390908559,
30.870054022743233,
31.025755113238645,
31.32126679129972,
31.585669257121097,
31.569158637003838,
31.899345201132761,
32.01667654065146,
32.187260443646935,
32.191497911094871,
32.638576565068021,
32.843215236943834,
32.706789455693283,
32.238187567670579,
31.75178314872332,
30.985757554644735,
30.525811469030913,
30.266395778925713,
30.763574734005829,
31.182179673786152,
31.376250515258281,
32.265085150678502,
32.711957098922483,
32.878820298792931,
32.792779039026968,
33.136995754523141,
33.293342800422195,
33.768740139291282,
33.785741685515319,
34.330773016897709,
34.83350718844919,
35.698984076473494,
35.947444362932814,
36.410000108377375,
36.899996039368915,
37.092103176413957,
36.724037787415085,
37.230001735984814,
37.349994411766545,
36.946427313783161,
36.885707505840216,
37.118380642234371,
37.110655015606739,
36.716518866516623,
36.865036932923459,
36.78390493422522,
36.605647081034405,
36.301272894835279,
35.888662421200806,
35.714848741187097,
35.16839630791668,
35.179093329401098,
35.399855048151977,
35.330711981745452,
35.755182196590894,
35.759988104794047,
35.145865383437425,
34.110476386037448,
33.697064927702456,
33.240245266242297,
32.564679266890636,
32.038096421836443,
31.177735500609046,
29.933573716749905,
29.098585923777815,
28.83214223888092,
28.148643907172456,
28.038185533148567,
27.640147813420413,
26.618892320252272,
26.254418443297681,
25.636264960222292,
25.103532619725371,
24.520260728447003,
24.359133612560939,
23.723358466074021,
23.017768459560788,
22.679339504481305,
22.158234361250052,
21.885744533774997,
21.422310288981478,
20.999752102130827,
20.567866319251493,
20.092520656814699,
19.593817246981985,
19.096715806550307,
18.108481553616656,
17.166962795474873,
16.673892116761962,
16.13503611903846,
15.621527411354108,
14.919477240452862,
14.729540513564073,
14.373515733289224,
13.594958604379855,
13.151393947802561,
12.384851589401052,
12.170911159712702,
11.95870189050612,
11.80651479740655,
11.52459402103824,
11.458474025920795,
11.040411688679526,
10.876571560098141,
10.656300767454042,
10.214467271358515,
10.015719712763968,
9.886166897008252,
9.49474376061346,
8.903048610871508,
8.163946438016978,
7.798645738145738,
7.26294200279203,
6.860098374860726,
6.785916856305747,
6.140710760925558,
5.593560695819207,
4.8324185245922,
4.355755113131963,
4.364565944837722,
4.338288479017308,
4.705087795425015,
4.993700669775137,
5.168263658057086,
5.179813340674315,
4.984295559098015,
4.994475816259509,
4.710462144383371,
5.000547797053812,
5.343472601742675,
5.928837388528876,
6.142157701029731,
6.258817246928629,
6.258300482605719,
6.270651149923467,
5.611802476418234,
4.887970689305959,
4.262453314628985,
4.240594183769517,
4.464689032403228,
4.412108262546241,
4.771982937026849,
4.495617377129918,
4.35221527751996,
3.904128933117136,
3.734526882335203,
3.073404445809117,
2.283866075037736,
1.160911363119183,
1.010119533691494,
0.268666083167687,
-0.459351494960217,
-0.779073581550037,
-1.111301364754496,
-2.144313246269043,
-2.969482517105682,
-3.978826592630547,
-5.037986748884791,
-5.789930515163839,
-6.10009246177966,
-6.294447523629394,
-6.927122084178805,
-7.596538588087733,
-8.562629489784307,
-8.959091078327553,
-9.166933689005468,
-9.766897067914122,
-10.373578383020714,
-10.73107594161589,
-11.297863050993165,
-12.03864470789717,
-12.483630466362492,
-13.137905775609902,
-13.54769988368445,
-14.449143568583892,
-14.878316338767904,
-15.793816013250735,
-16.673142185129251,
-17.301889336824473,
-18.069129327061916,
-19.045348809487699,
-19.673165785401665,
-20.872834161057504,
-21.699036960539978,
-22.111208184499958,
-22.656652927340691,
-23.853014011329847,
-25.39292001719538,
-26.117371921495156,
-27.090955905874047,
-27.821247247022804,
-28.576705010697701,
-29.875953871379984,
-29.878641045859162,
-30.725721123987547,
-31.661632989225669,
-32.42913136162457,
-32.611290785453427,
-33.281430759414441,
-33.86775156019803,
-34.136520684548067,
-33.99787281670897,
-34.444305515278465,
-34.462598972309792,
-34.819166355123713,
-34.795136814107991,
-34.417175388325234,
-34.258838799782936,
-33.864082533505311,
-33.916430759416983,
-33.794474379208154,
-33.987175795224552,
-33.796851495093584,
-33.944646091448341,
-33.667040297176399,
-33.614950453426189,
-33.226963799778801,
-32.771952813448856,
-32.172041110972501,
-31.140269463832958,
-30.423775730106129,
-29.909956963828037,
-29.401977634398914,
-29.257386976846256,
-28.752404880490069,
-28.301011244420557,
-27.470157566031816,
-26.742191664336197,
-26.215867201443466,
-26.148584486599447,
-25.727318210556092,
-25.357573337507738,
-24.816314385682659,
-24.478350518493805,
-24.122609958596549,
-23.706563002214683,
-23.535358982031699,
-23.070787855727758,
-22.09,
-22.14,
-21.840837090748877,
-21.254361260668411,
-20.497043145431011,
-19.784011732667736,
-19.552811374593894,
-18.842260430580637,
-18.659687595293448,
-17.586368096591237,
-17.101023044505958,
-16.72089120856694,
-16.10077402106446,
-15.406294447493972,
-14.691764418194241,
-14.201975192931862,
-12.639176527561027,
-11.761710707245015,
-10.765440769089993,
-10.317096042525698,
-10.098401381066489,
-9.11236337650525,
-8.485528252804826,
-8.007831312698748,
-7.703922214390246,
-7.099979750195118,
-6.839995619334701,
-6.475676771676994,
-5.908941338732021,
-4.67677,
-4.346556084819518,
-3.681170342629358,
-3.277680759294412,
-2.57309,
-2.49979,
-2.082559909680256,
-1.683256117360948,
-1.446474704599588,
-0.919168389493308,
0.292178859860499,
1.052804266764582,
2.045766913252919,
2.855278225105125,
4.21940684652985,
5.339105943214022,
6.804649563011552,
8.081729234240612,
9.198741156445607,
10.279734605343151,
10.640901190631055,
11.166502183471707,
11.748146267132881,
12.024641018110557,
12.021902167199087,
11.679571641481573,
11.578905951376996,
11.430336208537868,
11.41062164961852,
11.375481675660041,
11.193063869669729,
11.127228094929876,
10.816549383991131,
10.69802948652972,
10.4422053084688,
10.445538438351631,
10.864169216348103,
11.277709865763812,
11.462039699748928,
11.735640570518257,
11.974928290245771,
12.390148423710968,
12.699638576707001,
13.000421250861848,
13.343992010954366,
13.921036892141572,
14.491079616753225,
15.435647284400234,
15.922723496967292,
16.840626125551694,
17.998307399970386,
18.367871405505724,
18.614083767160352,
19.807964382399504,
20.837436428302052,
21.018846543862676,
22.0,
22.204846503177325,
23.102440293871012,
23.752374782805902,
23.926705227142534,
25.033743597915205,
25.59856700286538,
26.142280585224313,
27.699885769149816,
28.705224921172075,
29.760431830355984,
29.85107229259593,
28.417645575467802,
27.97136790619518,
27.648700262964724,
27.823314927678965,
28.343980821235732,
29.09941274669448,
29.501326198844524,
29.356554673778845,
28.957483425404845,
28.607427273059699,
28.058546047471566,
28.063351955674719,
27.376520494083422,
26.570135606384881,
25.826227525327223,
25.602959499610179,
25.084541530858107,
24.858482977797308,
24.285494696545015,
24.078685614512935,
23.688451036060854,
22.57965566659027,
21.986875311770195,
21.291904812092934,
20.338862209550058,
20.174634507726491,
19.486485297111756,
18.67159963630121,
17.833046169500975,
17.474721787989125,
17.075805568912003,
16.774635321514964,
16.347891343648683,
15.911742255105267,
15.718885809791999,
15.261962795467255,
15.213335272680595,
14.802249253798749,
14.062630316621309,
13.767583726450852,
13.220950425667425,
12.636800035040084,
12.585950425664876,
12.721652736863348,
12.69958690027471,
12.953938300015309,
13.026905422411433,
13.290946153206763,
13.347764390511685,
13.399699204965019,
13.592219753468383,
14.007233181204427,
13.948089504446372,
14.00320241948566,
14.708766587782748,
15.175249742081492,
15.597420355689948,
15.93843313238402,
16.382411200419654,
16.651051133688952,
16.707662665264706,
17.044980577049913,
16.950696926333379,
17.22835439703762,
17.632309068263197,
17.884128322821496,
17.876066799383963,
18.087113348863966,
18.574267076079465,
18.947991034414287,
18.94470958096376,
19.067570298737678,
19.73600495043307,
20.24300242764863,
20.481437486243337,
20.428985907467094,
21.114034532144302,
21.43388580981485,
21.714540513592027,
22.310524807214193,
22.533611965418217,
22.6602709009656,
22.992395331305474,
23.565667832935361,
23.74793060962881,
23.878594468678813,
24.241673081961505,
24.924732163995486,
25.714606431576769,
25.895990708921246,
26.309117946878633,
26.395934353128979,
26.055464178973981,
25.439145209244941,
24.797892360935091,
24.121757920828216,
24.15131684009917,
24.177439276622707,
24.019826158132506,
24.294072984305469,
24.245497137951105,
24.627385972588058,
25.215670477798739,
25.801112779233382,
26.114582017515868,
26.006991685484195,
25.482424221289396,
24.754742539971378,
24.999895534764022,
25.327808335872103,
25.608049628190926,
25.943972276304251,
26.277026882425375,
26.689663194275997,
27.109999294538085,
27.461218166609811,
27.689627997339883,
28.55200429942667,
29.306299343375002,
29.534476630159762,
29.975819200148504,
29.926778265903522,
30.317090359004037,
29.985715236932407,
30.147772528599717,
28.814520575469388,
27.865689602158298,
27.580849107365495,
26.812368882753049,
26.480657863871514,
26.964633490501043,
27.143304755150197,
26.966106268821363,
25.739902045183641,
25.609961656185732,
25.380156561783778,
25.078237006118499,
25.218409328710209,
25.237038682551429,
25.425140896093851,
24.663611151624647,
23.944843654876991,
23.691965033456711,
22.84317963306269,
22.450774644454338,
22.0892980005727,
20.877330634031384,
20.757441311114235,
21.356009426351008,
20.419503282141534,
19.208233547436166,
17.928570054592498,
15.990652167214961,
14.617221787977698,
13.992582912649681,
12.741935736537897,
11.781245022015824,
11.308250637248307,
10.299630031775521,
8.89927623131419,
7.965534776232332,
8.252959092639742,
8.933046779816934,
9.216543687370148,
9.546135972527722,
10.30885427493962,
10.35727509199711,
12.056215318240888,
13.006260687710835,
13.835770778859981,
15.136414903214147,
15.89918488205835,
15.951972357644493,
16.310219224507904,
16.556664130107848,
17.016636053937816,
17.671221421778981,
18.302009792549725,
19.4785788029711,
20.151638495356607,
20.743307806882413,
21.495561631755209,
21.703171698487807,
21.690588487224748,
22.055708319582976,
21.966178900637299,
21.857115790285306,
22.039146023033425,
21.836367702720111,
22.392793687422866,
22.805016587815128,
22.765019029221222,
22.182935695885565,
21.701569729086767,
21.19219513598577,
20.670883287025347,
19.855144965081976,
19.726961574781996,
19.366492621330025,
18.2135139022499,
17.277240301985728,
16.037936102762018,
15.803454291237641,
15.714389960182601,
16.427240505432849,
16.92873444260934,
16.100567938699768,
14.837285874892642,
13.640459703012851,
13.122377631070677,
12.032986761925685,
11.441291612183749,
10.67526601810515,
9.932959906448545,
8.973922837759801,
8.350007432483878,
7.794511623562386,
8.382305202666288,
7.907993068875328,
7.34345388430276,
6.848212795433597,
6.464489447450291,
6.040561835143905,
5.312492580583708,
4.767280381688295,
3.93913971599487,
3.270291652841152,
2.760813706875581,
1.967115383304687,
1.226333726400682,
1.293048000489492,
1.631141058759084,
2.515454006353764,
2.791018581550176,
3.382868760589005,
3.726697902842986,
4.181605536308339,
4.855001125503748,
5.524495144061106,
6.128205064310919,
6.221636053894628,
6.74062246340192,
6.856868597842478,
7.429572658717177,
8.295152899606052,
9.20786204674512,
9.239255479362427,
9.963061428258555,
10.846366685423547,
12.307001044153354,
13.406856390837433,
13.412721665902566,
12.627084865769206,
12.645740057826572,
12.186594956913282,
11.153660590047165,
10.632555446815928,
10.48654368737523,
9.918490505406808,
9.241038316276502,
8.599759629750494,
9.530839748569321,
10.364483954301832,
11.008320624226272,
11.666859239137764,
13.426028347217724,
15.27669057867044,
16.079742336486149,
16.697456569887052,
18.004120998603227,
19.05816518806057,
19.752050482659698,
20.696850694252021,
21.552379869060118,
21.715212307211814,
21.395050970947523,
21.008227037026703,
20.282457383703488,
20.341032619706329,
20.565411688717631,
21.397143866455338,
21.550493679281473,
22.051367499270455,
22.548339748621402,
22.22376007739615,
22.668074042241667,
22.78287323657807,
23.624501451099658,
24.547390855400241,
25.740780544532612,
27.053206895449321,
28.135673122667185,
28.225512600206617,
29.018022365834781,
29.832520453403149,
30.142914943964289,
30.676267401648701,
30.949351508095106,
31.692174384074647,
32.460318711877193,
33.376722723925141,
34.360331936168649,
34.909859117160437,
35.609790554337721,
36.111439520811075,
36.651329047180425,
36.93061432550185,
37.454484157860719,
37.48112335870718,
37.870427761378011,
37.156388658185051,
37.448463853498708,
37.897325344385933,
38.061475531561058,
38.737635809884083,
39.204273993479703,
39.252333075511146,
39.898055935214245,
40.593388169917539,
40.946389878903332,
40.422442531896024,
39.750261338859488,
39.360853583324072,
38.897471014962846,
39.170451768544666,
39.63778758397622,
39.928493353834156,
39.660344346671621,
39.55138458918421,
39.387957872061165,
38.848559271798592,
38.665857245430672,
38.54847422947968,
38.10834605564979,
37.94882090916478,
37.857224432927438,
37.669070542952724,
37.752088731429623,
37.940010077459021,
37.74968577732804,
36.893924058574626,
36.725484727519259,
35.684540513647903,
34.934560451795946,
34.39004588473648,
34.475673733044118,
34.890377102186392,
35.082484239231434,
35.632140611303953,
36.784189154602828,
37.432392483055949,
38.61224294692785,
39.050898342437421,
39.213472398427655,
39.323930772451533,
39.756850083976701,
40.025412502597561,
40.189846910150308,
40.485436102859815,
40.661807766271991,
40.882827867184332,
41.601104437825228,
41.94136790625106,
42.280003567059708,
42.22000722916885,
42.552751776696212,
43.284541734381435,
42.798499050460215,
42.811469834965479,
43.398204047207415,
43.988994859384256,
45.143498033217,
46.307948920265929,
46.999663804708796,
48.446707261745843,
50.04553,
51.23967,
52.238775539755792,
53.08957,
54.1896642116386,
54.25455,
53.755013739631657,
53.97732,
54.60355,
54.72959,
57.088040269592902,
59.03998,
59.33637,
59.16448,
59.65573,
59.50396,
58.78089,
58.88385,
59.14495,
59.75818,
61.43442,
61.77396,
60.54423,
61.64249095320487,
62.466264960369621,
62.55060089786997,
61.140893663163808,
60.343,
59.314777737049724,
58.05575,
57.832025865299009,
57.364715888083595,
56.76792,
55.381012681695452,
53.158951931361045,
51.7,
51.01105,
51.94269,
52.95868,
53.20257,
54.344331773488179,
54.85514,
55.28568,
56.115868129953121,
56.159233913794921,
57.61503,
57.83912,
58.24328,
59.21101,
59.868697414786325,
59.7316,
60.16,
59.78855,
60.573563951247479,
59.88177,
60.33618,
60.95,
61.65261,
61.76915,
62.5219,
62.304104315837733,
62.56894,
62.98262,
63.25197,
64.07593,
64.60821,
64.53493,
64.979708702198408,
std::numeric_limits<double>::quiet_NaN(),
68.199997667098287,
68.963646145291463,
std::numeric_limits<double>::quiet_NaN(),
-16.067132663642447,
-16.020882256741224,
-16.501783135649397,
-16.555216566639196,
std::numeric_limits<double>::quiet_NaN(),
-8.432094821815035,
-8.398246758663852,
-8.273344821814398,
-8.397316582882603,
-8.668256117388893,
-9.106007175333353,
-9.393173109579294,
-10.140000909061449,
-10.359987481327956,
-10.239994805546223,
-9.900015557497987,
-9.290026950724716,
-8.892790215697083,
-8.65688730228468,
-8.432094821815035,
std::numeric_limits<double>::quiet_NaN(),
68.963636363636354,
68.199997667098287,
67.20589,
66.58435,
66.33556,
67.06219,
66.91308,
65.97724,
65.54139,
65.43791,
64.46079,
64.25269,
64.2826,
64.63125,
64.92288,
65.35667,
65.52024,
65.39052,
65.74044,
66.11211,
65.87456,
65.40411,
64.979708702198394,
std::numeric_limits<double>::quiet_NaN(),
71.515714336428275,
71.55762,
71.55553,
71.26948,
71.13277,
70.89302,
70.832199208546726,
std::numeric_limits<double>::quiet_NaN(),
70.832199208546726,
70.78114,
71.0988,
71.515714336428289,
std::numeric_limits<double>::quiet_NaN(),
-16.555216566639196,
-16.801354076946883,
-17.012041674368039,
-16.63915,
-16.433984277547403,
-16.379054277547404,
-16.067132663642447,
std::numeric_limits<double>::quiet_NaN(),
-51.85,
-51.25,
-51.5,
-51.1,
-51.55,
-51.9,
-52.2,
-51.85,
-52.3,
-51.85,
std::numeric_limits<double>::quiet_NaN(),
-48.625,
-48.94,
-49.065,
-49.255,
-49.71,
-49.775,
-49.2425,
-48.83,
-48.625,
std::numeric_limits<double>::quiet_NaN(),
-17.50481,
-17.33992,
-17.62846,
-18.15059,
-18.28799,
-18.16432,
-17.72465,
-17.38114,
-17.50481,
std::numeric_limits<double>::quiet_NaN(),
10.76,
10.89,
10.855,
10.11,
10.0,
10.09,
10.365,
10.76,
std::numeric_limits<double>::quiet_NaN(),
20.07975,
19.99302,
19.8591,
19.50871,
19.45328,
19.23972,
19.08348,
18.91619,
19.05939,
19.33888,
19.70294,
19.81422,
19.97729,
20.17395,
20.26721,
20.2487,
20.07975,
std::numeric_limits<double>::quiet_NaN(),
20.76404,
20.64397,
20.57241,
20.783,
20.8643,
20.92676,
21.01249,
20.91745,
20.76404,
std::numeric_limits<double>::quiet_NaN(),
21.17684,
21.06873,
21.09777,
21.21958,
21.17684,
std::numeric_limits<double>::quiet_NaN(),
21.71696,
21.65272,
21.32217,
21.26442,
21.27729,
21.31244,
21.53919,
21.57912,
21.71696,
std::numeric_limits<double>::quiet_NaN(),
22.21494,
21.982,
21.88299,
22.06533,
22.1382,
22.23618,
22.21494,
std::numeric_limits<double>::quiet_NaN(),
25.2103,
25.17,
24.34,
23.75975,
23.71,
24.28615,
24.57564,
25.2103,
std::numeric_limits<double>::quiet_NaN(),
26.79,
26.87,
26.84,
26.58,
26.42,
26.79,
std::numeric_limits<double>::quiet_NaN(),
27.04,
26.59,
25.87918,
26.00735,
26.53,
26.92516,
27.04,
std::numeric_limits<double>::quiet_NaN(),
47.03601,
46.55001,
46.41587,
46.44314,
46.03339,
45.96818,
46.39265,
46.72747,
47.03601,
std::numeric_limits<double>::quiet_NaN(),
44.6092,
45.64149,
45.80629,
46.39933,
46.608989976582279,
47.048704738953774,
46.80463694923931,
46.853006089864451,
46.23464590105992,
45.259046535821639,
45.408391425145183,
45.245998236667944,
44.514854234386348,
44.609835516938801,
44.284015611338546,
44.031033637053667,
43.132974758469416,
42.792297878585188,
42.443895372073356,
42.027150783855546,
41.78333,
41.135370591794711,
41.868116563477358,
42.123191433270051,
41.551210842447418,
40.951014919593447,
40.631034450842193,
40.876523342444742,
40.033629055332014,
39.975286363274492,
39.290573635407156,
38.952093003895328,
37.906136176091707,
37.198918361961276,
36.965030829408249,
36.700421657857675,
36.872814235983384,
37.374566555321366,
37.582874253889884,
38.32026,
38.815486355131839,
39.049218858387903,
39.399481716462219,
40.176100979160694,
40.256561184239175,
40.52615713150584,
40.572924302729945,
41.282286688800497,
41.80888,
42.98658,
43.66016,
44.6092,
std::numeric_limits<double>::quiet_NaN(),
49.87304,
49.95718,
49.70641,
49.28855,
49.10506,
49.08717,
49.40069,
49.87304,
std::numeric_limits<double>::quiet_NaN(),
62.085565,
62.3856,
62.36371,
62.158675,
61.63308,
61.7181,
62.01649,
62.085565,
std::numeric_limits<double>::quiet_NaN(),
62.4528,
62.91409,
62.90458,
62.7108,
62.15922,
62.18231,
62.4528,
std::numeric_limits<double>::quiet_NaN(),
67.44425,
67.14886,
67.09873,
67.58809,
68.14856,
68.28721,
68.01036,
67.58202,
67.44425,
std::numeric_limits<double>::quiet_NaN(),
69.680030358321773,
69.10769485484937,
68.757044423532847,
69.060030358321768,
68.950701853546605,
69.4000303583218,
69.710035349643448,
70.143523101923819,
69.860030358321779,
69.680030358321773,
std::numeric_limits<double>::quiet_NaN(),
73.07600495064645,
72.672592881959986,
71.698414618609689,
70.992979641393362,
70.497764390740315,
70.024304918082152,
69.584486802846072,
69.504026597767592,
69.119605617948366,
68.75280630154063,
68.91,
69.18,
69.119243882922262,
68.78,
68.630059156817936,
68.53554,
69.007441921658852,
69.28,
69.168207302518852,
69.96,
70.066524563264636,
70.237315171989309,
70.192356675895326,
70.366351223422072,
70.600006212029854,
70.520450344516462,
70.540552476677988,
70.909212144648222,
71.309187730587354,
71.295183417436277,
71.558578192827923,
72.307834784627801,
72.705950019004348,
73.314595038538044,
73.121454372847154,
72.652774970176011,
72.95539215767721,
72.450410061321065,
72.96112824166164,
72.633344631634316,
71.65087230090117,
72.065472317178859,
73.089544175906951,
73.235995185022034,
73.07600495064645,
std::numeric_limits<double>::quiet_NaN(),
72.802902221679744,
73.333183288574219,
73.693183898925781,
73.759719848632869,
73.651931762695341,
73.102684989953104,
72.826385498046847,
72.855545043945369,
72.876655578613281,
72.742202758789062,
72.802902221679744,
std::numeric_limits<double>::quiet_NaN(),
73.36983,
73.76506,
73.85758,
73.47525,
73.21244,
73.20544,
73.31692,
73.36983,
std::numeric_limits<double>::quiet_NaN(),
75.345845,
75.08406,
74.68892,
74.778355,
75.17298,
75.49682,
75.345845,
std::numeric_limits<double>::quiet_NaN(),
76.13676,
76.09289,
75.562625,
74.82,
74.84768,
74.61148,
75.26167,
75.94917,
76.13676,
std::numeric_limits<double>::quiet_NaN(),
76.588607082821966,
76.72,
76.25656,
75.74344,
75.0,
74.897444159638098,
75.057356879365301,
75.640757961724404,
75.563811754041836,
76.336581122534483,
76.305368557430228,
76.646329657692007,
76.588607082821966,
std::numeric_limits<double>::quiet_NaN(),
79.28129,
78.71334,
78.30689,
77.921,
79.23399,
79.34641,
79.28129,
std::numeric_limits<double>::quiet_NaN(),
81.0246,
81.2504,
80.746975,
79.780135,
78.88094,
78.7562,
79.044745,
79.4265,
80.14379,
80.34146,
81.0246,
std::numeric_limits<double>::quiet_NaN(),
80.60231557893178,
80.907284044102198,
80.977279771641605,
81.206464748856064,
81.257391872879737,
80.723445136223916,
80.32,
79.66,
79.336914781400736,
79.039310207831704,
78.287211412255857,
78.215329494937862,
78.343332017724862,
78.751007392075394,
79.113724270332114,
79.38011627879672,
79.372468166817526,
79.705006008615669,
80.157769070140972,
80.60231557893178,
std::numeric_limits<double>::quiet_NaN(),
81.89429,
82.085,
82.11751,
82.27961,
82.65227345805701,
82.6,
82.32,
82.86,
83.02,
83.13056,
83.172058823529397,
83.06404,
83.23324,
83.169780758382814,
83.106321516765718,
83.02801,
82.9,
82.6286,
82.36165,
81.92775,
81.72527,
81.50141,
81.50657,
80.9,
80.61683,
79.8,
79.63415,
79.430162204802087,
79.32309,
79.19766,
79.01907,
78.52581,
78.18296,
77.89991,
77.50859,
77.20968,
76.98336,
77.022045,
76.777955,
76.17812,
76.45403,
76.29901,
76.42,
76.47239,
76.95213,
77.17833,
77.9,
77.970222222222304,
77.53873,
78.18,
78.37181,
78.75867,
78.9969,
79.34543,
79.73624,
80.25145,
80.20836,
80.1,
80.46442,
80.58,
80.51627,
80.85569,
81.26,
81.5531,
81.89429,
std::numeric_limits<double>::quiet_NaN(),
82.62796,
83.22516,
83.18018,
83.54905,
83.64513,
83.51966,
82.72669,
82.34165,
82.29765,
82.2,
82.02154,
82.13178,
81.78697,
82.09317,
81.73449,
81.15271,
81.52462,
81.91245,
81.71885,
81.29154,
80.58004,
80.35,
80.17708,
80.12912,
79.4,
78.75128,
77.63859,
76.98565,
76.94434,
76.62795,
76.09808,
75.24838,
75.15585,
74.29561,
74.22382,
73.81713,
73.46436,
73.30955,
73.30663,
72.62928,
72.18409,
72.59788,
72.3302,
72.08016,
71.46898,
70.66369,
70.471,
70.85649,
71.43094,
70.75226,
70.22646,
70.18401,
70.12946,
69.2588,
68.47046,
68.12503,
68.12078,
67.73547,
66.67974,
65.9789,
65.93768,
65.69213,
65.45848,
64.83997,
64.13902,
63.48246,
62.68233,
61.90093,
61.07404,
60.09772,
60.03676,
60.85328,
60.85843,
61.40681,
62.38336,
63.62691,
64.27842,
65.1767,
66.09957,
66.8365,
67.18899,
68.35759,
68.72958,
69.14781,
69.9291,
69.574925,
69.42616,
69.28362,
69.61003,
70.28932,
70.821315,
70.835755,
70.56978,
71.20485,
71.54719,
71.406536967272586,
71.65444,
72.58625,
72.95861,
73.64977,
74.71026,
75.09861,
75.51727,
76.10238,
76.1752,
76.13486,
76.06141,
76.37975,
77.00857,
77.32312,
77.37595,
77.63595,
78.04419,
78.43271,
78.91388,
79.39436,
79.75814,
80.11721,
80.51582,
81.21396,
81.3211,
81.77042,
82.03363,
82.19074,
82.19962,
81.88833,
82.43883,
82.06481,
81.98594,
81.6607,
82.19979,
82.62796,
std::numeric_limits<double>::quiet_NaN(),
73.6,
73.64,
73.42,
72.76,
73.46,
73.6,
std::numeric_limits<double>::quiet_NaN(),
-84.71338,
-84.721443373552503,
-84.139411716649136,
-84.452932631363922,
-84.099259128758348,
-84.117914320815714,
-84.534323012223638,
-84.117914320815714,
-84.06101856886238,
-83.884646905450211,
-84.117914320815714,
-84.237390232274535,
-84.570496514827937,
-84.825209649594598,
-85.138730564309384,
-85.373910007669707,
-85.099559828632152,
-85.295516859882923,
-85.609037774597738,
-85.315102227721567,
-85.040752048683999,
-84.570496514827937,
-84.531274102718413,
-84.296146335790382,
-83.904232273288827,
-83.688689874199397,
-83.238019708182009,
-82.826520277841809,
-82.454191583178854,
-82.042692152838669,
-81.768393650233406,
-81.415650323409054,
-81.102129408694282,
-81.16093718864245,
-81.004150893068882,
-81.337308852054591,
-81.04337330517842,
-80.671044610515466,
-80.33793832796205,
-79.926438897621864,
-79.652088718584309,
-79.358204848140431,
-79.299397068192278,
-79.162247816889646,
-79.064269301264247,
-78.691940606601307,
-78.378419691886506,
-78.025676365062182,
-76.889208266099303,
-76.98723845815698,
-77.300759372871781,
-77.202729180814103,
-77.065579929511472,
-77.496664727690273,
-77.39873788849718,
-77.183143812975473,
-76.908845310370211,
-76.575739027816795,
-76.477760512191409,
-76.105431817528455,
-75.733154799297807,
-75.380411472473469,
-75.204039809061314,
-75.537197768047022,
-75.341240736796237,
-75.086475925597298,
-75.066890557758683,
-74.968912042133283,
-74.733784275205267,
-74.518241876115866,
-74.302699477026451,
-74.361455580542312,
-74.439848728329082,
-74.302699477026451,
-74.479019464006328,
-74.459434096167712,
-74.322284844865067,
-74.420263360490466,
-74.518241876115866,
-74.479019464006328,
-74.498604831844943,
-74.518241876115866,
-74.479019464006328,
-74.185083917130157,
-74.028349297988896,
-74.243891697078297,
-74.067520033666142,
-73.714828383274096,
-74.028349297988896,
-74.381040948380928,
-74.714198907366637,
-74.420263360490466,
-74.792540378721128,
-74.910104262185129,
-75.184454441222684,
-75.125698337706837,
-74.949326674294667,
-74.988497409971899,
-75.125698337706837,
-75.302018324686699,
-74.870933526507898,
-74.537827243954482,
-74.185083917130157,
-74.106742445775666,
-73.734413751112726,
-73.362085056449772,
-72.617531019988462,
-72.754680271291093,
-72.813436374806955,
-72.754680271291093,
-72.911414890432354,
-73.205350437308525,
-73.558042087700557,
-73.61684986764871,
-73.479700616346079,
-73.283743585095294,
-73.166179701631279,
-73.40130746855931,
-73.32291432077254,
-72.558723240040308,
-73.00939340605774,
-73.185765069469909,
-73.087786553844509,
-73.479700616346079,
-73.518871352023325,
-73.636435235487326,
-73.851977634576741,
-73.479700616346079,
-73.126957289521755,
-73.518871352023325,
-73.420892836397925,
-73.636435235487326,
-73.969541518040742,
-73.871614678847649,
-73.656020603325956,
-73.40130746855931,
-73.264158217256679,
-73.146542657360371,
-73.00939340605774,
-72.793851006968339,
-72.480330092253539,
-72.049245294074737,
-71.637745863734537,
-71.245831801232981,
-70.853917738731411,
-70.462055352662134,
-70.109312025837809,
-69.717397963336239,
-69.325535577266962,
-68.953206882604007,
-68.541707452263822,
-68.149845066194544,
-67.718760268015743,
-67.326846205514173,
-66.876176039496741,
-66.582240492620571,
-66.209963474389909,
-65.89639088324283,
-65.602507012798938,
-65.171422214620137,
-64.897072035582582,
-64.642307224383643,
-64.583551120867781,
-64.270030206152981,
-64.074073174902196,
-63.956509291438188,
-63.701744480239256,
-63.388223565524456,
-63.270659682060447,
-63.525424493259386,
-63.858530775812795,
-64.15246632268898,
-64.368008721778381,
-64.211222426204841,
-64.309200941830227,
-64.544328708758258,
-64.799093519957182,
-65.093029066833367,
-65.484943129334937,
-65.857220147565585,
-66.190326430119001,
-66.425505873479324,
-66.503847344833801,
-66.83700530381951,
-67.150474542102003,
-67.581611016713111,
-67.953888034943759,
-68.365335788851667,
-68.678908379998745,
-68.913984470494484,
-69.227557061641562,
-69.61941944771084,
-69.991748142373794,
-70.383662204875364,
-70.71676848742878,
-71.089045505659428,
-72.010074558397491,
-72.382351576628153,
-72.774265639129709,
-73.166179701631279,
-73.69524301543548,
-74.106742445775666,
-74.439848728329082,
-74.576997979631713,
-74.929741306456052,
-75.262847589009468,
-75.635124607240115,
-75.791910902813669,
-76.00745330190307,
-76.22299570099247,
-76.634495131332656,
-76.673665867009902,
-76.634495131332656,
-76.712888279119426,
-76.712888279119426,
-77.104802341620996,
-77.28107065216858,
-77.555420831206135,
-77.908112481598167,
-78.221633396312967,
-78.123654880687567,
-78.378419691886506,
-78.789919122226692,
-79.181833184728262,
-79.514939467281678,
-79.88721648551234,
-80.25954518017528,
-80.416331475748834,
-80.690629978354096,
-81.004150893068882,
-81.317671807783668,
-81.474458103357222,
-81.748756605962484,
-82.042692152838669,
-82.375850111824363,
-82.846105645680424,
-83.218434340343379,
-82.86569101351904,
-82.571755466642855,
-82.258234551928069,
-82.003521417161423,
-81.729171238123868,
-81.709585870285252,
-81.846735121587869,
-82.081914564948192,
-81.650829766769377,
-81.356894219893206,
-81.337308852054591,
-81.121714776532912,
-80.906172377443497,
-80.769023126140866,
-80.592651462728696,
-80.33793832796205,
-79.985195001137726,
-79.632503350745694,
-79.260226332515032,
-79.299397068192278,
-79.456131687333524,
-79.456131687333524,
-79.083854669102877,
-78.339248956209275,
-78.123654880687567,
-77.888527113759551,
-77.653451023263813,
-77.359515476387642,
-77.065579929511472,
-76.673665867009902,
-76.497345880030025,
-76.360144952295101,
-76.281803480940624,
-76.242581068831086,
-76.105431817528455,
-75.90947478627767,
-75.674347019349653,
-75.439219252421623,
-75.125698337706837,
-74.792540378721128,
-74.498604831844943,
-74.106742445775666,
-73.871614678847649,
-73.460115248507464,
-73.146542657360371,
-72.950585626109586,
-72.715457859181569,
-72.401936944466769,
-72.010074558397491,
-71.539767348109152,
-71.265417169071597,
-71.324224949019751,
-71.657331231573167,
-71.696501967250398,
-71.324224949019751,
-70.932310886518181,
-71.030289402143566,
-71.40261809680652,
-71.461374200322382,
-71.285054213342505,
-71.167438653446197,
-71.226246433394351,
-71.637745863734537,
-71.304639581181135,
-71.128267917768966,
-70.991118666466335,
-70.853917738731411,
-70.61878997180338,
-70.462055352662134,
-70.246512953572733,
-69.893769626748394,
-70.148534437947333,
-70.01133351021241,
-70.481640720500749,
-70.834332370892781,
-70.63837533964201,
-70.246512953572733,
-69.972162774535178,
-70.03091887805104,
-70.40324757271398,
-70.03091887805104,
-69.913354994587024,
-69.874184258909779,
-69.893769626748394,
-70.01133351021241,
-70.070141290160564,
-70.40324757271398,
-70.69718311959015,
-70.520811456177995,
-70.481640720500749,
-70.481640720500749,
-70.462055352662134,
-70.32485442492721,
-70.207290541463195,
-69.93294036242564,
-69.756620375445763,
-69.658641859820378,
-69.384291680782823,
-68.835642999140006,
-68.502588393018883,
-68.659271335727837,
-69.012014662552161,
-69.247142429480192,
-69.168749281693422,
-69.521440932085454,
-69.776205743284393,
-69.541077976356362,
-69.109941501745269,
-68.933621514765392,
-68.600515232211976,
-68.463314304477052,
-68.267408949658559,
-68.051866550569159,
-67.816738783641128,
-67.601196384551727,
-67.718760268015743,
-67.366068617623711,
-67.091718438586156,
-67.111303806424772,
-66.876176039496741,
-66.523484389104709,
-66.249134210067155,
-66.05317717881637,
-65.89639088324283,
-65.818049411888353,
-65.8768055154042,
-65.9747840310296,
-66.249134210067155,
-66.680219008245956,
-67.013325290799372,
-67.287675469836927,
-67.405239353300942,
-67.679589532338497,
-67.953888034943759,
-68.012695814891913,
-67.816738783641128,
-67.405239353300942,
-67.620730075958051,
-67.738345635854358,
-67.855909519318374,
-67.934302667105143,
-67.934302667105143,
-68.972792250442637,
-69.227557061641562,
-69.678227227658994,
-69.93294036242564,
-70.305269057088594,
-70.69718311959015,
-70.677546075319242,
-71.069460137820812,
-71.441788832483766,
-71.853288262823952,
-72.166809177538738,
-72.264787693164138,
-72.088416029751968,
-71.696501967250398,
-71.324224949019751,
-71.01070403430495,
-70.71676848742878,
-70.364025160604442,
-69.874184258909779,
-69.776205743284393,
-69.737035007607147,
-69.61941944771084,
-69.462684828569593,
-69.070770766068023,
-68.698442071405083,
-68.326216729606713,
-68.071503594840067,
-67.875546563589282,
-67.542388604603573,
-67.366068617623711,
-67.209282322050157,
-67.307260837675557,
-67.209282322050157,
-67.091718438586156,
-67.150474542102003,
-66.876176039496741,
-66.209911797957616,
-66.484261976995171,
-66.954569187283511,
-67.150474542102003,
-67.228867689888787,
-67.111303806424772,
-67.189696954211541,
-67.209282322050157,
-67.111303806424772,
-67.170111586372926,
-67.385653985462326,
-67.248504734159695,
-67.248504734159695,
-67.111303806424772,
-67.248504734159695,
-66.915346775173987,
-66.582240492620571,
-66.307890313583016,
-65.563284600689414,
-65.700485528424338,
-65.9747840310296,
-66.327527357853924,
-66.934932143012603,
-66.954569187283511,
-66.954569187283511,
-66.83700530381951,
-66.699804376084586,
-66.425505873479324,
-66.131570326603139,
-66.092347914493615,
-65.8768055154042,
-66.072762546654985,
-66.386283461369786,
-66.699804376084586,
-66.66063364040734,
-66.915346775173987,
-67.170111586372926,
-67.268090101998311,
-67.189696954211541,
-66.876176039496741,
-66.562655124781955,
-66.484261976995171,
-66.621462904730095,
-66.719389743923202,
-66.562655124781955,
-66.562655124781955,
-66.66063364040734,
-66.75861215603274,
-66.582240492620571,
-66.425505873479324,
-66.386283461369786,
-66.386283461369786,
-66.2883049457444,
-66.209963474389909,
-65.720070896262953,
-65.308571465922768,
-65.58286996852803,
-66.033591810977754,
-66.44509124131794,
-66.778197523871356,
-66.954569187283511,
-66.895761407335371,
-66.876176039496741,
-66.817368259548587,
-66.817368259548587,
-66.797782891709971,
-66.83700530381951,
-66.915346775173987,
-67.228867689888787,
-67.601196384551727,
-67.895131931427912,
-68.130259698355928,
-68.385024509554867,
-68.561292820102452,
-68.718130792108283,
-68.874813734817238,
-68.894502455520438,
-68.561292820102452,
-68.835642999140006,
-69.149215590287085,
-69.384291680782823,
-69.482270196408209,
-69.599834079872224,
-69.991748142373794,
-70.22687590930181,
-70.579619236126149,
-70.736353855267396,
-70.71676848742878,
-70.775524590944642,
-70.755939223106012,
-70.834332370892781,
-70.971481622195427,
-71.206661065555735,
-71.40261809680652,
-71.696501967250398,
-72.088416029751968,
-72.441159356576293,
-72.891829522593724,
-73.24452117298577,
-73.656020603325956,
-73.812806898899495,
-74.165498549291527,
-74.381040948380928,
-74.772955010882498,
-75.145283705545452,
-75.458804620260253,
-75.870304050600438,
-76.242581068831086,
-76.69330291128081,
-77.065579929511472,
-77.457442315580735,
-77.829771010243689,
-78.182514337068014,
-78.319611911938352,
-78.750748386549461,
-78.907483005690708,
-79.123025404780108,
-79.162247816889646,
-79.730481866371079,
-80.200737400227126,
-80.573066094890081,
-80.945394789553035,
-81.278501072106451,
-81.690000502446622,
-82.062277520677284,
-82.395435479662993,
-82.708956394377807,
-83.022477309092579,
-83.33599822380738,
-83.825890801934349,
-84.04143320102375,
-84.117914320815714,
-84.413710219254398,
-84.158997084487751,
-84.472517999202552,
-84.71338
};
return std::make_pair(std::vector(std::begin(x), std::end(x)), std::vector(std::begin(y), std::end(y)));
}
std::pair<std::vector<double>, std::vector<double>>& world_map_110m() {
static std::pair<std::vector<double>, std::vector<double>> world_map_110m_ = prepare_world_map_110m();
return world_map_110m_;
}
}
| 39.560015 | 112 | 0.405087 | [
"vector"
] |
4fbc045992dc96147731ee174e7e0c98750bb25a | 10,566 | cxx | C++ | vtkAttributedPolyDataToImage.cxx | Connor-Bowley/MeshToLabelMap | 91ab7128b72b14d0a954717c9064f6c359086f3c | [
"Apache-2.0"
] | 4 | 2018-06-26T04:11:17.000Z | 2020-06-01T05:47:45.000Z | vtkAttributedPolyDataToImage.cxx | Connor-Bowley/MeshToLabelMap | 91ab7128b72b14d0a954717c9064f6c359086f3c | [
"Apache-2.0"
] | 9 | 2017-05-18T15:07:22.000Z | 2022-01-26T16:40:59.000Z | vtkAttributedPolyDataToImage.cxx | Connor-Bowley/MeshToLabelMap | 91ab7128b72b14d0a954717c9064f6c359086f3c | [
"Apache-2.0"
] | 6 | 2016-02-04T19:17:58.000Z | 2021-12-17T14:24:32.000Z |
/*
* This is a subclass of vtkPolyDataToImageStencil, with extended functionality to build a lookup from the
* stencil back to the triangles of the mesh.
*
* Author: Ipek Oguz
*
*/
#include "vtkAttributedPolyDataToImage.h"
#include "vtkGarbageCollector.h"
#include "vtkImageStencilData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkOBBTree.h"
#include "vtkObjectFactory.h"
#include "vtkPolyData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include <math.h>
vtkStandardNewMacro(vtkAttributedPolyDataToImage);
vtkAttributedPolyDataToImage::vtkAttributedPolyDataToImage()
{
this->BinaryVolume = NULL ;
this->AttributeVolume = NULL ;
this->Attributes = NULL ;
this->faceList = vtkSmartPointer<vtkIdTypeArray>::New () ;
this->pointList = vtkSmartPointer<vtkPoints>::New () ;
this->ScanConvertPerformed = false ;
this->mesh = NULL ;
this->stencil = NULL ;
}
//----------------------------------------------------------------------------
vtkAttributedPolyDataToImage::~vtkAttributedPolyDataToImage()
{
}
//----------------------------------------------------------------------------
//void vtkAttributedPolyDataToImage::PrintSelf(ostream& os, vtkIndent indent)
//{
// this->Superclass::PrintSelf(os,indent);
//}
//----------------------------------------------------------------------------
int vtkAttributedPolyDataToImage::RequestData(
vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// the following is largely copied from the vtkPolyDataToImageStencil code
this->SuperSuperclass::RequestData(request, inputVector, outputVector);
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// need to build the OBB tree
vtkPolyData *polydata = vtkPolyData::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkImageStencilData *data = vtkImageStencilData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
this->mesh = polydata ;
if (this->OBBTree == NULL)
{
this->OBBTree = vtkOBBTree::New();
}
this->OBBTree->SetDataSet(polydata);
this->OBBTree->SetTolerance(this->Tolerance);
this->OBBTree->BuildLocator();
// for keeping track of progress
unsigned long count = 0;
int extent[6];
data->GetExtent(extent);
unsigned long target = (unsigned long)
((extent[5] - extent[4] + 1)*(extent[3] - extent[2] + 1)/50.0);
target++;
// if we have no data then return
if (!polydata->GetNumberOfPoints())
{
return 1;
}
double *spacing = data->GetSpacing();
double *origin = data->GetOrigin();
if( this->GetDebug() )
{
std::cout << "Spacing: " << spacing[0] << " " << spacing[1] << " " << spacing[2] << std::endl ;
std::cout << "Origin: " << origin[0] << " " << origin[1] << " " << origin[2] << std::endl ;
std::cout << "Extent: " << extent[0] << " " << extent[1] << " " << extent[2] << " " << extent[3] << " " << extent[4] << " " << extent[5] << std::endl ;
}
vtkSmartPointer<vtkOBBTree> tree = this->OBBTree;
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
double p0[3],p1[3];
p1[0] = p0[0] = extent[0]*spacing[0] + origin[0];
p1[1] = p0[1] = extent[2]*spacing[1] + origin[1];
p0[2] = extent[4]*spacing[2] + origin[2];
p1[2] = extent[5]*spacing[2] + origin[2];
int zstate = tree->InsideOrOutside(p0);
if (zstate == 0)
{
zstate = -1;
}
int *zlist = 0;
int zlistlen = 0;
int zlistidx = 0;
if (extent[4] < extent[5])
{
tree->IntersectWithLine(p0, p1, points, 0);
vtkTurnPointsIntoList(points, zlist, zlistlen,
extent, origin, spacing, 2);
}
for (int idZ = extent[4]; idZ <= extent[5]; idZ++)
{
if (zlistidx < zlistlen && idZ >= zlist[zlistidx])
{
zstate = -zstate;
zlistidx++;
}
p1[0] = p0[0] = extent[0]*spacing[0] + origin[0];
p0[1] = extent[2]*spacing[1] + origin[1];
p1[1] = extent[3]*spacing[1] + origin[1];
p1[2] = p0[2] = idZ*spacing[2] + origin[2];
int ystate = zstate;
int *ylist = 0;
int ylistlen = 0;
int ylistidx = 0;
if (extent[2] != extent[3])
{
tree->IntersectWithLine(p0, p1, points, 0);
vtkTurnPointsIntoList(points, ylist, ylistlen,
extent, origin, spacing, 1);
}
for (int idY = extent[2]; idY <= extent[3]; idY++)
{
if (ylistidx < ylistlen && idY >= ylist[ylistidx])
{
ystate = -ystate;
ylistidx++;
}
if (count%target == 0)
{
this->UpdateProgress(count/(50.0*target));
}
count++;
p0[1] = p1[1] = idY*spacing[1] + origin[1];
p0[2] = p1[2] = idZ*spacing[2] + origin[2];
p0[0] = extent[0]*spacing[0] + origin[0];
p1[0] = extent[1]*spacing[0] + origin[0];
int xstate = ystate;
int *xlist = 0;
int xlistlen = 0;
int xlistidx = 0;
//tree->IntersectWithLine(p0, p1, points, 0);
vtkIdList *faces = vtkIdList::New () ;
tree->IntersectWithLine ( p0, p1, points, faces ) ;
int nFaces = faces->GetNumberOfIds () ;
int i ;
for ( i = 0 ; i < nFaces ; i++ )
{
this->faceList->InsertNextValue ( faces->GetId ( i ) ) ;
}
int nPoints = points->GetNumberOfPoints () ;
if ( this->GetDebug() && nPoints != nFaces )
{
std::cout << "Problem: nPoints != nFaces. nPoints=" << nPoints << "-- nFaces=" << nFaces << std::endl ;
}
double p[3] ;
for ( i = 0 ; i < nPoints ; i++ )
{
points->GetPoint ( i, p ) ;
this->pointList->InsertNextPoint ( p ) ;
}
faces->Delete () ;
vtkTurnPointsIntoList(points, xlist, xlistlen,
extent, origin, spacing, 0);
// now turn 'xlist' into sub-extents:
int r1 = extent[0];
int r2 = extent[1];
for (xlistidx = 0; xlistidx < xlistlen; xlistidx++)
{
xstate = -xstate;
if (xstate < 0)
{ // sub extent starts
r1 = xlist[xlistidx];
}
else
{ // sub extent ends
r2 = xlist[xlistidx] - 1;
data->InsertNextExtent(r1, r2, idY, idZ);
}
}
if (xstate < 0)
{ // if inside at end, cap off the sub extent
data->InsertNextExtent(r1, extent[1], idY, idZ);
}
if (xlist)
{
delete [] xlist;
}
} // for idY
if (ylist)
{
delete [] ylist;
}
} // for idZ
if (zlist)
{
delete [] zlist;
}
this->ScanConvertPerformed = true ;
return 1 ;
}
void vtkAttributedPolyDataToImage::ComputeAttributeVolume ()
{
double spacing[3], origin[3] ;
int *extent ;
vtkSmartPointer<vtkImageStencilData> stencil = this->GetOutput () ;
stencil->GetSpacing ( spacing ) ;
stencil->GetOrigin ( origin ) ;
extent= this->GetOutputWholeExtent () ;
// create empty image
this->AttributeVolume = vtkSmartPointer<vtkImageData>::New () ;
this->AttributeVolume->SetOrigin ( origin ) ;
this->AttributeVolume->SetSpacing ( spacing ) ;
this->AttributeVolume->SetDimensions ( extent[1] - extent[0] + 1, extent[3] - extent[2] + 1, extent[5] - extent[4] + 1 ) ;
this->AttributeVolume->AllocateScalars(VTK_FLOAT, 1);
for ( int i = 0 ; i <= extent[1] ; i++ )
{
for ( int j = 0 ; j <= extent[3] ; j++ )
{
for ( int k = 0 ; k <= extent[5] ; k++ )
{
this->AttributeVolume->SetScalarComponentFromDouble ( i, j, k, 0, 0.0 ) ;
}
}
}
int nPts = this->pointList->GetNumberOfPoints () ;
double p[3];
vtkIdType faceId ;
double closestPoint[3], dist2, pCoords[3], weights[3] ;
int subId, result ;
for ( int i = 0 ; i < nPts ; i++ )
{
this->pointList->GetPoint ( i, p ) ;
faceId = this->faceList->GetValue ( i ) ;
vtkSmartPointer<vtkIdList> facePoints = vtkSmartPointer<vtkIdList>::New () ;
this->mesh->GetCellPoints ( faceId, facePoints ) ;
result = this->mesh->GetCell ( faceId )->EvaluatePosition ( p, closestPoint, subId, pCoords, dist2, weights ) ;
if( this->GetDebug() )
{
if ( result == 0 )
{
std::cout << "outside" << std::endl ;
}
else if ( result == -1 )
{
std::cout << "numerical error" << std::endl ;
}
}
int gridCoords[3] ;
double attributeValue, vertAttributes[3] ;
attributeValue = 0 ;
for ( int j = 0 ; j < 3 ; j++ )
{
gridCoords[j] = ceil ( ( p[j] - origin[j] ) / spacing[j] ) ;
vertAttributes[j] = this->Attributes->GetValue ( facePoints->GetId ( j ) ) ;
attributeValue += vertAttributes[j] * pCoords[j] ;
}
//std::cout << attributeValue << std::endl ;
if ( !(i % 2) )
gridCoords[0]-- ;
this->AttributeVolume->SetScalarComponentFromDouble ( gridCoords[0], gridCoords[1], gridCoords[2], 0, attributeValue );
}
//std::cout << "Attribute volume computed. " << std::endl ;
}
vtkSmartPointer<vtkImageData> vtkAttributedPolyDataToImage::GetBinaryVolume()
{
if ( !this->ScanConvertPerformed )
return NULL ;
double spacing[3], origin[3] ;
int *extent, size[3] ;
vtkImageStencilData *temp = this->GetOutput () ;
temp->GetSpacing ( spacing ) ;
temp->GetOrigin ( origin ) ;
extent = this->GetOutputWholeExtent () ;
size[0] = extent[1] - extent[0] + 1 ;
size[1] = extent[3] - extent[2] + 1 ;
size[2] = extent[5] - extent[4] + 1 ;
// Create an empty image
vtkSmartPointer<vtkImageData> emptyImage = vtkSmartPointer<vtkImageData>::New () ;
emptyImage->SetOrigin ( origin ) ;
emptyImage->SetSpacing ( spacing ) ;
emptyImage->SetDimensions ( size ) ;
emptyImage->AllocateScalars(VTK_INT, 1);
// Use the stencil as a cookie cutter
this->stencil = vtkSmartPointer<vtkImageStencil>::New () ;
this->stencil->SetInputData ( emptyImage ) ;
//this->GetOutput() ;
this->stencil->SetStencilData ( this->GetOutput () ) ;
this->stencil->ReverseStencilOn () ;
this->stencil->SetBackgroundValue ( 128 ) ;
this->stencil->Update () ;
this->BinaryVolume = this->stencil->GetOutput () ;
//this->stencil->Delete() ;
return this->BinaryVolume ;
}
vtkSmartPointer<vtkImageData> vtkAttributedPolyDataToImage::GetAttributeVolume()
{
if ( ( !this->ScanConvertPerformed ) || ( !this->Attributes ) )
return NULL ;
this->ComputeAttributeVolume () ;
return this->AttributeVolume ;
}
| 28.790191 | 157 | 0.581961 | [
"mesh"
] |
4fbc673eff4cb51aaa99eed177387291ff76ab76 | 2,492 | cpp | C++ | examples/t04_blackboard.cpp | mjeronimo/BehaviorTree.CPP | 8756f5ba1a0bd5d9da2ff259d941c8528c5c01b1 | [
"MIT"
] | null | null | null | examples/t04_blackboard.cpp | mjeronimo/BehaviorTree.CPP | 8756f5ba1a0bd5d9da2ff259d941c8528c5c01b1 | [
"MIT"
] | null | null | null | examples/t04_blackboard.cpp | mjeronimo/BehaviorTree.CPP | 8756f5ba1a0bd5d9da2ff259d941c8528c5c01b1 | [
"MIT"
] | 1 | 2019-07-18T17:13:24.000Z | 2019-07-18T17:13:24.000Z | #include "behavior_tree_core/xml_parsing.h"
#include "behavior_tree_logger/bt_cout_logger.h"
#include "Blackboard/blackboard_local.h"
#include "movebase_node.h"
using namespace BT;
/** This tutorial will tech you:
*
* - How to use the Blackboard to shared data between TreeNodes
* - How to use a Blackboard as a NodeParameter
*
* The tree is a Sequence of 4 actions
* 1) Store a value of Pose2D in the key "GoalPose" of the blackboard using the action CalculateGoalPose.
* 2) Call MoveAction. The NodeParameter "goal" will be read from the Blackboard at run-time.
* 3) Use the built-in action SetBlackboard to write the key "OtherGoal".
* 4) Call MoveAction. The NodeParameter "goal" will be read from the Blackboard entry "OtherGoal".
*
*/
// clang-format off
const std::string xml_text = R"(
<root main_tree_to_execute = "MainTree" >
<BehaviorTree ID="MainTree">
<SequenceStar name="root">
<CalculateGoalPose/>
<MoveBase goal="${GoalPose}" />
<SetBlackboard key="OtherGoal" value="-1;3;0.5" />
<MoveBase goal="${OtherGoal}" />
</SequenceStar>
</BehaviorTree>
</root>
)";
// clang-format on
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// Write into the blackboard key: [GoalPose]
// Use this function to create a SimpleActionNode that can access the blackboard
NodeStatus CalculateGoalPose(TreeNode& self)
{
const Pose2D mygoal = {1, 2, M_PI};
// RECOMMENDED: check if the blackboard is nullptr first
if (self.blackboard())
{
// store it in the blackboard
self.blackboard()->set("GoalPose", mygoal);
return NodeStatus::SUCCESS;
}
else
{
return NodeStatus::FAILURE;
}
}
int main()
{
using namespace BT;
BehaviorTreeFactory factory;
factory.registerSimpleAction("CalculateGoalPose", CalculateGoalPose);
factory.registerNodeType<MoveBaseAction>("MoveBase");
// create a Blackboard from BlackboardLocal (simple, not persistent, local storage)
auto blackboard = Blackboard::create<BlackboardLocal>();
// Important: when the object tree goes out of scope, all the TreeNodes are destroyed
auto tree = buildTreeFromText(factory, xml_text, blackboard);
NodeStatus status = NodeStatus::RUNNING;
while (status == NodeStatus::RUNNING)
{
status = tree.root_node->executeTick();
SleepMS(1); // optional sleep to avoid "busy loops"
}
return 0;
}
| 29.317647 | 106 | 0.683387 | [
"object"
] |
4fbc8bc1de2edb7b455d67222afd020a88748185 | 3,136 | cpp | C++ | pdfium_lib/pdfium/core/fxcrt/xml/cfx_xmlnode.cpp | qingqibing/vs_pdfium | 6d009d478c3e761fac49b357d81532c3ed7aad9f | [
"BSD-3-Clause"
] | 6 | 2015-04-17T01:37:17.000Z | 2019-01-12T06:59:49.000Z | core/fxcrt/xml/cfx_xmlnode.cpp | agrogoth/pdfium | 1be462069ea1a40894a100844882acc76a427717 | [
"BSD-3-Clause"
] | null | null | null | core/fxcrt/xml/cfx_xmlnode.cpp | agrogoth/pdfium | 1be462069ea1a40894a100844882acc76a427717 | [
"BSD-3-Clause"
] | 3 | 2015-05-12T08:37:57.000Z | 2020-04-27T05:58:54.000Z | // Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxcrt/xml/cfx_xmlnode.h"
#include <utility>
#include <vector>
#include "core/fxcrt/xml/cfx_xmlchardata.h"
#include "core/fxcrt/xml/cfx_xmlelement.h"
#include "core/fxcrt/xml/cfx_xmlinstruction.h"
#include "core/fxcrt/xml/cfx_xmltext.h"
CFX_XMLNode::CFX_XMLNode() = default;
CFX_XMLNode::~CFX_XMLNode() = default;
void CFX_XMLNode::DeleteChildren() {
while (first_child_) {
first_child_->parent_ = nullptr;
first_child_->prev_sibling_ = nullptr;
CFX_XMLNode* child = first_child_;
first_child_ = child->next_sibling_;
child->next_sibling_ = nullptr;
}
last_child_ = nullptr;
}
void CFX_XMLNode::AppendChild(CFX_XMLNode* pNode) {
InsertChildNode(pNode, -1);
}
void CFX_XMLNode::InsertChildNode(CFX_XMLNode* pNode, int32_t index) {
ASSERT(!pNode->parent_);
pNode->parent_ = this;
// No existing children, add node as first child.
if (!first_child_) {
ASSERT(!last_child_);
first_child_ = pNode;
last_child_ = first_child_;
first_child_->prev_sibling_ = nullptr;
first_child_->next_sibling_ = nullptr;
return;
}
if (index == 0) {
first_child_->prev_sibling_ = pNode;
pNode->next_sibling_ = first_child_;
pNode->prev_sibling_ = nullptr;
first_child_ = pNode;
return;
}
CFX_XMLNode* pFind;
// Note, negative indexes, and indexes after the end of the list will result
// in appending to the list.
if (index < 0) {
// Optimize the negative index case.
pFind = last_child_;
} else {
pFind = first_child_;
int32_t iCount = 0;
while (++iCount != index && pFind->next_sibling_)
pFind = pFind->next_sibling_;
}
pNode->prev_sibling_ = pFind;
if (pFind->next_sibling_)
pFind->next_sibling_->prev_sibling_ = pNode;
pNode->next_sibling_ = pFind->next_sibling_;
pFind->next_sibling_ = pNode;
if (pFind == last_child_)
last_child_ = pFind->next_sibling_;
}
void CFX_XMLNode::RemoveChildNode(CFX_XMLNode* pNode) {
ASSERT(first_child_);
ASSERT(pNode);
if (pNode->GetParent() != this)
return;
if (first_child_ == pNode)
first_child_ = pNode->next_sibling_;
if (last_child_ == pNode)
last_child_ = pNode->prev_sibling_;
if (pNode->prev_sibling_)
pNode->prev_sibling_->next_sibling_ = pNode->next_sibling_;
if (pNode->next_sibling_)
pNode->next_sibling_->prev_sibling_ = pNode->prev_sibling_;
pNode->parent_ = nullptr;
pNode->prev_sibling_ = nullptr;
pNode->next_sibling_ = nullptr;
}
CFX_XMLNode* CFX_XMLNode::GetRoot() {
CFX_XMLNode* pParent = this;
while (pParent->parent_)
pParent = pParent->parent_;
return pParent;
}
WideString CFX_XMLNode::EncodeEntities(const WideString& value) {
WideString ret = value;
ret.Replace(L"&", L"&");
ret.Replace(L"<", L"<");
ret.Replace(L">", L">");
ret.Replace(L"\'", L"'");
ret.Replace(L"\"", L""");
return ret;
}
| 25.495935 | 80 | 0.695472 | [
"vector"
] |
4fbdb0964ab98ac6bce3c206181c9e7a31477a96 | 6,761 | cpp | C++ | libmalloc/libmalloc-283.100.6/tests/MallocBenchTest/BMALLOC/bmalloc/bmalloc/Allocator.cpp | L-Zheng/AppleOpenSource | 65fac74ce17dc97404f1aeb8c24625fe82b7d142 | [
"MIT"
] | null | null | null | libmalloc/libmalloc-283.100.6/tests/MallocBenchTest/BMALLOC/bmalloc/bmalloc/Allocator.cpp | L-Zheng/AppleOpenSource | 65fac74ce17dc97404f1aeb8c24625fe82b7d142 | [
"MIT"
] | null | null | null | libmalloc/libmalloc-283.100.6/tests/MallocBenchTest/BMALLOC/bmalloc/bmalloc/Allocator.cpp | L-Zheng/AppleOpenSource | 65fac74ce17dc97404f1aeb8c24625fe82b7d142 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2014-2018 Apple 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:
* 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 APPLE INC. ``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 APPLE INC. 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 "Allocator.h"
#include "BAssert.h"
#include "Chunk.h"
#include "Deallocator.h"
#include "DebugHeap.h"
#include "Heap.h"
#include "PerProcess.h"
#include "Sizes.h"
#include <algorithm>
#include <cstdlib>
namespace bmalloc {
Allocator::Allocator(Heap& heap, Deallocator& deallocator)
: m_heap(heap)
, m_debugHeap(heap.debugHeap())
, m_deallocator(deallocator)
{
for (size_t sizeClass = 0; sizeClass < sizeClassCount; ++sizeClass)
m_bumpAllocators[sizeClass].init(objectSize(sizeClass));
}
Allocator::~Allocator()
{
scavenge();
}
void* Allocator::tryAllocate(size_t size)
{
if (m_debugHeap)
return m_debugHeap->malloc(size);
if (size <= smallMax)
return allocate(size);
std::unique_lock<Mutex> lock(Heap::mutex());
return m_heap.tryAllocateLarge(lock, alignment, size);
}
void* Allocator::allocate(size_t alignment, size_t size)
{
bool crashOnFailure = true;
return allocateImpl(alignment, size, crashOnFailure);
}
void* Allocator::tryAllocate(size_t alignment, size_t size)
{
bool crashOnFailure = false;
return allocateImpl(alignment, size, crashOnFailure);
}
void* Allocator::allocateImpl(size_t alignment, size_t size, bool crashOnFailure)
{
BASSERT(isPowerOfTwo(alignment));
if (m_debugHeap)
return m_debugHeap->memalign(alignment, size, crashOnFailure);
if (!size)
size = alignment;
if (size <= smallMax && alignment <= smallMax)
return allocate(roundUpToMultipleOf(alignment, size));
std::unique_lock<Mutex> lock(Heap::mutex());
if (crashOnFailure)
return m_heap.allocateLarge(lock, alignment, size);
return m_heap.tryAllocateLarge(lock, alignment, size);
}
void* Allocator::reallocate(void* object, size_t newSize)
{
bool crashOnFailure = true;
return reallocateImpl(object, newSize, crashOnFailure);
}
void* Allocator::tryReallocate(void* object, size_t newSize)
{
bool crashOnFailure = false;
return reallocateImpl(object, newSize, crashOnFailure);
}
void* Allocator::reallocateImpl(void* object, size_t newSize, bool crashOnFailure)
{
if (m_debugHeap)
return m_debugHeap->realloc(object, newSize, crashOnFailure);
size_t oldSize = 0;
switch (objectType(m_heap.kind(), object)) {
case ObjectType::Small: {
BASSERT(objectType(m_heap.kind(), nullptr) == ObjectType::Small);
if (!object)
break;
size_t sizeClass = Object(object).page()->sizeClass();
oldSize = objectSize(sizeClass);
break;
}
case ObjectType::Large: {
std::unique_lock<Mutex> lock(Heap::mutex());
oldSize = m_heap.largeSize(lock, object);
if (newSize < oldSize && newSize > smallMax) {
m_heap.shrinkLarge(lock, Range(object, oldSize), newSize);
return object;
}
break;
}
}
void* result = nullptr;
if (crashOnFailure)
result = allocate(newSize);
else {
result = tryAllocate(newSize);
if (!result)
return nullptr;
}
size_t copySize = std::min(oldSize, newSize);
memcpy(result, object, copySize);
m_deallocator.deallocate(object);
return result;
}
void Allocator::scavenge()
{
for (size_t sizeClass = 0; sizeClass < sizeClassCount; ++sizeClass) {
BumpAllocator& allocator = m_bumpAllocators[sizeClass];
BumpRangeCache& bumpRangeCache = m_bumpRangeCaches[sizeClass];
while (allocator.canAllocate())
m_deallocator.deallocate(allocator.allocate());
while (bumpRangeCache.size()) {
allocator.refill(bumpRangeCache.pop());
while (allocator.canAllocate())
m_deallocator.deallocate(allocator.allocate());
}
allocator.clear();
}
}
BNO_INLINE void Allocator::refillAllocatorSlowCase(BumpAllocator& allocator, size_t sizeClass)
{
BumpRangeCache& bumpRangeCache = m_bumpRangeCaches[sizeClass];
std::unique_lock<Mutex> lock(Heap::mutex());
m_deallocator.processObjectLog(lock);
m_heap.allocateSmallBumpRanges(lock, sizeClass, allocator, bumpRangeCache, m_deallocator.lineCache(lock));
}
BINLINE void Allocator::refillAllocator(BumpAllocator& allocator, size_t sizeClass)
{
BumpRangeCache& bumpRangeCache = m_bumpRangeCaches[sizeClass];
if (!bumpRangeCache.size())
return refillAllocatorSlowCase(allocator, sizeClass);
return allocator.refill(bumpRangeCache.pop());
}
BNO_INLINE void* Allocator::allocateLarge(size_t size)
{
std::unique_lock<Mutex> lock(Heap::mutex());
return m_heap.allocateLarge(lock, alignment, size);
}
BNO_INLINE void* Allocator::allocateLogSizeClass(size_t size)
{
size_t sizeClass = bmalloc::sizeClass(size);
BumpAllocator& allocator = m_bumpAllocators[sizeClass];
if (!allocator.canAllocate())
refillAllocator(allocator, sizeClass);
return allocator.allocate();
}
void* Allocator::allocateSlowCase(size_t size)
{
if (m_debugHeap)
return m_debugHeap->malloc(size);
if (size <= maskSizeClassMax) {
size_t sizeClass = bmalloc::maskSizeClass(size);
BumpAllocator& allocator = m_bumpAllocators[sizeClass];
refillAllocator(allocator, sizeClass);
return allocator.allocate();
}
if (size <= smallMax)
return allocateLogSizeClass(size);
return allocateLarge(size);
}
} // namespace bmalloc
| 30.731818 | 110 | 0.698861 | [
"object"
] |
4fbe28271e0ee327ffdcea71a655ea6aa8f73f27 | 2,124 | cc | C++ | octo/memory/OctoHeap.cc | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null | octo/memory/OctoHeap.cc | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null | octo/memory/OctoHeap.cc | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null |
#include "OctoHeap.hh"
#include <iostream>
using namespace std;
namespace memory {
bool GC_verbose_stats = false;
bool GC_trace = false;
OctoHeap::OctoHeap()
: currentMark_(0)
{
}
OctoHeap::~OctoHeap()
{
garbageCollect();
}
void OctoHeap::addRoot(HeapObject* obj)
{
if (GC_trace) cerr << "GC: adding root " << obj << endl;
roots_.insert(obj);
}
void OctoHeap::removeRoot(HeapObject* obj)
{
if (GC_trace) cerr << "GC: removing root " << obj << endl;
roots_.erase(obj);
}
void OctoHeap::manageObject(HeapObject* obj)
{
if (GC_trace) cerr << "GC: managing obj " << obj << endl;
allocated_.insert(obj);
}
void OctoHeap::garbageCollect()
{
if (GC_verbose_stats) cerr << "GC start: object count = " << allocated_.size() << endl;
currentMark_ = (currentMark_ + 1) & 127;
markRoots_();
mark_();
queue_.clear();
sweep_();
if (GC_verbose_stats) cerr << "GC done: object count = " << allocated_.size() << endl;
}
void OctoHeap::markRoots_()
{
for(auto& rt : roots_) {
queue_.push_back(&* rt);
}
}
void OctoHeap::mark_()
{
int8_t mark = currentMark_;
while(! queue_.empty()) {
HeapObject* obj = queue_.back();
queue_.pop_back();
if (obj) {
if (GC_trace) cerr << "GC: marking obj " << obj << endl;
obj->setGCMark(mark);
obj->scanGC(queue_);
}
}
}
void OctoHeap::sweep_()
{
int8_t mark = currentMark_;
auto iter = allocated_.begin();
auto iend = allocated_.end();
while(iter != iend) {
HeapObject* obj = *iter;
if (obj->getGCMark() == mark) {
++iter;
} else {
iter = allocated_.erase(iter);
if (GC_trace) cerr << "deleting object " << obj << endl;
delete obj;
}
}
}
}
| 21.896907 | 95 | 0.490584 | [
"object"
] |
4fbf79b53c1b65fe58176a12c918b84604b82028 | 58,774 | cpp | C++ | src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp | hendrikweisser/OpenMS | 2a27f0ce46699d81b83f6620d0b9323bf538bcd2 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp | hendrikweisser/OpenMS | 2a27f0ce46699d81b83f6620d0b9323bf538bcd2 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 7 | 2018-06-19T14:51:57.000Z | 2022-01-12T14:34:32.000Z | src/openms/source/ANALYSIS/OPENSWATH/TransitionTSVFile.cpp | hendrikweisser/OpenMS | 2a27f0ce46699d81b83f6620d0b9323bf538bcd2 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2018.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/ANALYSIS/OPENSWATH/TransitionTSVFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/TextFile.h>
namespace OpenMS
{
template<class T> // primary template
bool extractName(T& value, const std::string& header_name,
const std::vector<std::string>& tmp_line,
const std::map<std::string, int>& header_dict)
{
auto tmp = header_dict.find( header_name );
if (tmp != header_dict.end())
{
value = tmp_line[ tmp->second ];
// perform cleanup
value = value.remove('"');
value = value.remove('\'');
value = value.remove(',');
return true;
}
return false;
}
template<> // specialization for int
bool extractName<int>(int& value, const std::string& header_name,
const std::vector<std::string>& tmp_line,
const std::map<std::string, int>& header_dict)
{
auto tmp = header_dict.find( header_name );
if (tmp != header_dict.end() && !String(tmp_line[ tmp->second ]).empty())
{
value = String(tmp_line[ tmp->second ]).toInt();
return true;
}
return false;
}
template<> // specialization for double
bool extractName<double>(double& value, const std::string& header_name,
const std::vector<std::string>& tmp_line,
const std::map<std::string, int>& header_dict)
{
auto tmp = header_dict.find(header_name);
if (tmp != header_dict.end() && !String(tmp_line[ tmp->second ]).empty())
{
value = String(tmp_line[ tmp->second ]).toDouble();
return true;
}
return false;
}
template<> // specialization for bool
bool extractName<bool>(bool& value, const std::string& header_name,
const std::vector<std::string>& tmp_line,
const std::map<std::string, int>& header_dict)
{
auto tmp = header_dict.find( header_name );
if (tmp != header_dict.end() && !String(tmp_line[ tmp->second ]).empty())
{
auto str_value = tmp_line[ tmp->second ];
if (str_value == "1" || str_value == "TRUE") value = true;
else if (str_value == "0" || str_value == "FALSE") value = false;
else return false;
// all went well, we set the value and can return
return true;
}
return false;
}
TransitionTSVFile::TransitionTSVFile() :
DefaultParamHandler("TransitionTSVFile")
{
defaults_.setValue("retentionTimeInterpretation", "iRT", "How to interpret the provided retention time (the retention time column can either be interpreted to be in iRT, minutes or seconds)", ListUtils::create<String>("advanced"));
defaults_.setValidStrings("retentionTimeInterpretation", ListUtils::create<String>("iRT,seconds,minutes"));
defaults_.setValue("override_group_label_check", "false", "Override an internal check that assures that all members of the same PeptideGroupLabel have the same PeptideSequence (this ensures that only different isotopic forms of the same peptide can be grouped together in the same label group). Only turn this off if you know what you are doing.", ListUtils::create<String>("advanced"));
defaults_.setValidStrings("override_group_label_check", ListUtils::create<String>("true,false"));
defaults_.setValue("force_invalid_mods", "false", "Force reading even if invalid modifications are encountered (OpenMS may not recognize the modification)", ListUtils::create<String>("advanced"));
defaults_.setValidStrings("force_invalid_mods", ListUtils::create<String>("true,false"));
// write defaults into Param object param_
defaultsToParam_();
updateMembers_();
}
TransitionTSVFile::~TransitionTSVFile()
{
}
void TransitionTSVFile::updateMembers_()
{
retentionTimeInterpretation_ = param_.getValue("retentionTimeInterpretation");
override_group_label_check_ = param_.getValue("override_group_label_check").toBool();
force_invalid_mods_ = param_.getValue("force_invalid_mods").toBool();
}
const std::vector<std::string> TransitionTSVFile::header_names_ =
{
"PrecursorMz",
"ProductMz",
"PrecursorCharge",
"ProductCharge",
"LibraryIntensity",
"NormalizedRetentionTime",
"PeptideSequence",
"ModifiedPeptideSequence",
"PeptideGroupLabel",
"LabelType",
"CompoundName",
"SumFormula",
"SMILES",
"Adducts",
"ProteinId",
"UniprotId",
"GeneName",
"FragmentType",
"FragmentSeriesNumber",
"Annotation",
"CollisionEnergy",
"PrecursorIonMobility",
"TransitionGroupId",
"TransitionId",
"Decoy",
"DetectingTransition",
"IdentifyingTransition",
"QuantifyingTransition",
"Peptidoforms"
};
void TransitionTSVFile::getTSVHeader_(const std::string& line, char& delimiter, std::map<std::string, int>& header_dict) const
{
std::string tmp;
std::vector<std::string> header;
int nr_delimiters = 3;
Size min_header_size = 8;
const char possibleDelimiters[3] = {',', ';', '\t'};
for (int i = 0; i < nr_delimiters; i++)
{
header.clear();
std::stringstream lineStream(line);
delimiter = possibleDelimiters[i];
while (std::getline(lineStream, tmp, delimiter))
{
String tmp2(tmp);
tmp2 = tmp2.remove('"');
tmp2 = tmp2.remove('\'');
tmp2 = tmp2.remove(',');
header.push_back(tmp2);
}
if (header.size() >= min_header_size)
{
break; // found the delimiter, got the correct header
}
}
for (Size i = 0; i < header.size(); i++)
{
header_dict[header[i]] = i;
}
char txt_delimiter = delimiter;
if (txt_delimiter == '\t')
{
txt_delimiter = 't';
}
// could not determine the delimiter correctly
if (header.size() < min_header_size)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Determined your csv/tsv file to have delimiter '" + (String)txt_delimiter +
"', but the parsed header has only " + (String)header.size() + " fields instead of the minimal " +
(String)min_header_size + ". Please check your input file.");
}
}
void TransitionTSVFile::readUnstructuredTSVInput_(const char* filename, FileTypes::Type filetype, std::vector<TSVTransition>& transition_list)
{
std::ifstream data(filename);
std::string line;
std::string tmp;
// read header
std::vector<std::string> tmp_line;
std::map<std::string, int> header_dict;
char delimiter = ',';
// SpectraST MRM Files do not have a header
if (filetype == FileTypes::MRM)
{
delimiter = '\t';
header_dict["SpectraSTBestSample"] = 0;
header_dict["SpectraSTmaxNumUsed/totNumUsed"] = 1;
header_dict["SpectraSTpI"] = 2;
header_dict["PrecursorMz"] = 3;
header_dict["SpectraSTRetentionTime"] = 4;
header_dict["ProductMz"] = 5;
header_dict["LibraryIntensity"] = 6;
header_dict["SpectraSTAnnotation"] = 7;
header_dict["FragmentCharge"] = 8;
header_dict["SpectraSTFullPeptideName"] = 9;
header_dict["SpectraSTUnknown"] = 10;
header_dict["SpectraSTNumberOfProteinsMappedTo"] = 11;
header_dict["ProteinName"] = 12;
}
// Read header for TSV input
else
{
TextFile::getLine(data, line);
getTSVHeader_(line, delimiter, header_dict);
}
bool spectrast_legacy = false; // we will check below if SpectraST was run in legacy (<5.0) mode or if the RT normalization was forgotten.
int cnt = 0;
while (TextFile::getLine(data, line)) // make sure line endings are handled correctly
{
line.push_back(delimiter); // avoid losing last column if it is empty
std::stringstream lineStream(line);
while (std::getline(lineStream, tmp, delimiter)) // default getline is fine here, we only want to split the line
{
tmp_line.push_back(tmp);
}
cnt++;
#ifdef TRANSITIONTSVREADER_TESTING
for (Size i = 0; i < tmp_line.size(); i++)
{
std::cout << "line " << i << " " << tmp_line[i] << std::endl;
}
for (const auto& iter : header_dict)
{
std::cout << "header " << iter.first << " " << iter.second << std::endl;
}
#endif
if (tmp_line.size() != header_dict.size())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error reading the file on line " + String(cnt) + ": length of the header and length of the line" +
" do not match: " + String(tmp_line.size()) + " != " + String(header_dict.size()));
}
TSVTransition mytransition;
bool skip_transition = false; // skip unannotated transitions in SpectraST MRM files
//// Required columns (they are guaranteed to be present, see getTSVHeader_)
// PrecursorMz
mytransition.precursor = String(tmp_line[header_dict["PrecursorMz"]]).toDouble();
// ProductMz
if (!extractName<double>(mytransition.product, "ProductMz", tmp_line, header_dict) &&
!extractName<double>(mytransition.product, "FragmentMz", tmp_line, header_dict)) // Spectronaut
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Expected a header named ProductMz or FragmentMz but found none");
}
// LibraryIntensity
if (!extractName<double>(mytransition.library_intensity, "LibraryIntensity", tmp_line, header_dict) &&
!extractName<double>(mytransition.library_intensity, "RelativeIntensity", tmp_line, header_dict) && // Spectronaut
!extractName<double>(mytransition.library_intensity, "RelativeFragmentIntensity", tmp_line, header_dict)) // Spectronaut
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Expected a header named LibraryIntensity or RelativeFragmentIntensity but found none");
}
//// Additional columns for both proteomics and metabolomics
// NormalizedRetentionTime
if (!extractName<double>(mytransition.rt_calibrated, "RetentionTimeCalculatorScore", tmp_line, header_dict) && // Skyline
!extractName<double>(mytransition.rt_calibrated, "iRT", tmp_line, header_dict) && // Spectronaut
!extractName<double>(mytransition.rt_calibrated, "NormalizedRetentionTime", tmp_line, header_dict) &&
!extractName<double>(mytransition.rt_calibrated, "RetentionTime", tmp_line, header_dict) &&
!extractName<double>(mytransition.rt_calibrated, "Tr_recalibrated", tmp_line, header_dict))
{
if (header_dict.find("SpectraSTRetentionTime") != header_dict.end())
{
spectrastRTExtract(tmp_line[header_dict["SpectraSTRetentionTime"]], mytransition.rt_calibrated, spectrast_legacy);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Expected a header named RetentionTime, NormalizedRetentionTime, iRT, RetentionTimeCalculatorScore, Tr_recalibrated or SpectraSTRetentionTime but found none");
}
}
// PrecursorCharge
!extractName(mytransition.precursor_charge, "PrecursorCharge", tmp_line, header_dict) &&
!extractName(mytransition.precursor_charge, "Charge", tmp_line, header_dict); // charge is assumed to be the charge of the precursor
!extractName(mytransition.fragment_type, "FragmentType", tmp_line, header_dict) &&
!extractName(mytransition.fragment_type, "FragmentIonType", tmp_line, header_dict); // Skyline
!extractName(mytransition.fragment_charge, "FragmentCharge", tmp_line, header_dict) &&
!extractName(mytransition.fragment_charge, "ProductCharge", tmp_line, header_dict);
!extractName<int>(mytransition.fragment_nr, "FragmentSeriesNumber", tmp_line, header_dict) &&
!extractName<int>(mytransition.fragment_nr, "FragmentNumber", tmp_line, header_dict) &&
!extractName<int>(mytransition.fragment_nr, "FragmentIonOrdinal", tmp_line, header_dict);
extractName<double>(mytransition.drift_time, "PrecursorIonMobility", tmp_line, header_dict);
extractName<double>(mytransition.fragment_mzdelta, "FragmentMzDelta", tmp_line, header_dict);
extractName<int>(mytransition.fragment_modification, "FragmentModification", tmp_line, header_dict);
//// Proteomics
extractName(mytransition.GeneName, "GeneName", tmp_line, header_dict);
!extractName(mytransition.ProteinName, "ProteinName", tmp_line, header_dict) &&
!extractName(mytransition.ProteinName, "ProteinId", tmp_line, header_dict); // Spectronaut
extractName(mytransition.peptide_group_label, "PeptideGroupLabel", tmp_line, header_dict);
extractName(mytransition.label_type, "LabelType", tmp_line, header_dict);
!extractName(mytransition.PeptideSequence, "PeptideSequence", tmp_line, header_dict) &&
!extractName(mytransition.PeptideSequence, "Sequence", tmp_line, header_dict) && // Skyline
!extractName(mytransition.PeptideSequence, "StrippedSequence", tmp_line, header_dict); // Spectronaut
!extractName(mytransition.FullPeptideName, "FullUniModPeptideName", tmp_line, header_dict) &&
!extractName(mytransition.FullPeptideName, "FullPeptideName", tmp_line, header_dict) &&
!extractName(mytransition.FullPeptideName, "ModifiedSequence", tmp_line, header_dict) && // Spectronaut
!extractName(mytransition.FullPeptideName, "ModifiedPeptideSequence", tmp_line, header_dict);
//// IPF
String peptidoforms;
!extractName<bool>(mytransition.detecting_transition, "detecting_transition", tmp_line, header_dict) &&
!extractName<bool>(mytransition.detecting_transition, "DetectingTransition", tmp_line, header_dict);
!extractName<bool>(mytransition.identifying_transition, "identifying_transition", tmp_line, header_dict) &&
!extractName<bool>(mytransition.identifying_transition, "IdentifyingTransition", tmp_line, header_dict);
!extractName<bool>(mytransition.quantifying_transition, "quantifying_transition", tmp_line, header_dict) &&
!extractName<bool>(mytransition.quantifying_transition, "QuantifyingTransition", tmp_line, header_dict) &&
!extractName<bool>(mytransition.quantifying_transition, "Quantitative", tmp_line, header_dict); // Skyline
extractName(peptidoforms, "Peptidoforms", tmp_line, header_dict);
peptidoforms.split('|', mytransition.peptidoforms);
//// Targeted Metabolomics
extractName(mytransition.CompoundName, "CompoundName", tmp_line, header_dict);
extractName(mytransition.SumFormula, "SumFormula", tmp_line, header_dict);
extractName(mytransition.SMILES, "SMILES", tmp_line, header_dict);
extractName(mytransition.Adducts, "Adducts", tmp_line, header_dict);
//// Meta
extractName(mytransition.Annotation, "Annotation", tmp_line, header_dict);
// UniprotId
!extractName(mytransition.uniprot_id, "UniprotId", tmp_line, header_dict) &&
!extractName(mytransition.uniprot_id, "UniprotID", tmp_line, header_dict);
if (mytransition.uniprot_id == "NA") mytransition.uniprot_id = "";
!extractName<double>(mytransition.CE, "CE", tmp_line, header_dict) &&
!extractName<double>(mytransition.CE, "CollisionEnergy", tmp_line, header_dict);
// Decoy
!extractName<bool>(mytransition.decoy, "decoy", tmp_line, header_dict) &&
!extractName<bool>(mytransition.decoy, "Decoy", tmp_line, header_dict) &&
!extractName<bool>(mytransition.decoy, "IsDecoy", tmp_line, header_dict);
if (header_dict.find("SpectraSTAnnotation") != header_dict.end())
{
skip_transition = spectrastAnnotationExtract(tmp_line[header_dict["SpectraSTAnnotation"]], mytransition);
}
//// Generate Group IDs
// SpectraST
if (filetype == FileTypes::MRM)
{
std::vector<String> substrings;
String(tmp_line[header_dict["SpectraSTFullPeptideName"]]).split("/", substrings);
AASequence peptide = AASequence::fromString(substrings[0]);
mytransition.FullPeptideName = peptide.toString();
mytransition.PeptideSequence = peptide.toUnmodifiedString();
mytransition.precursor_charge = substrings[1];
mytransition.transition_name = String(cnt);
mytransition.group_id = mytransition.FullPeptideName + String("_") + String(mytransition.precursor_charge);
}
// Generate transition_group_id and transition_name if not defined
else
{
// Use TransitionId if available, else generate from attributes
if (!extractName(mytransition.transition_name, "transition_name", tmp_line, header_dict) &&
!extractName(mytransition.transition_name, "TransitionName", tmp_line, header_dict) &&
!extractName(mytransition.transition_name, "TransitionId", tmp_line, header_dict))
{
mytransition.transition_name = String(cnt);
}
// Use TransitionGroupId if available, else generate from attributes
if (!extractName(mytransition.group_id, "transition_group_id", tmp_line, header_dict) &&
!extractName(mytransition.group_id, "TransitionGroupId", tmp_line, header_dict) &&
!extractName(mytransition.group_id, "TransitionGroupName", tmp_line, header_dict))
{
mytransition.group_id = AASequence::fromString(mytransition.FullPeptideName).toString() + String("_") + String(mytransition.precursor_charge);
}
}
cleanupTransitions_(mytransition);
if (!skip_transition)
{
transition_list.push_back(mytransition);
}
#ifdef TRANSITIONTSVREADER_TESTING
std::cout << mytransition.precursor << std::endl;
std::cout << mytransition.product << std::endl;
std::cout << mytransition.rt_calibrated << std::endl;
std::cout << mytransition.transition_name << std::endl;
std::cout << mytransition.CE << std::endl;
std::cout << mytransition.library_intensity << std::endl;
std::cout << mytransition.group_id << std::endl;
std::cout << mytransition.decoy << std::endl;
std::cout << mytransition.PeptideSequence << std::endl;
std::cout << mytransition.ProteinName << std::endl;
std::cout << mytransition.Annotation << std::endl;
std::cout << mytransition.FullPeptideName << std::endl;
std::cout << mytransition.precursor_charge << std::endl;
std::cout << mytransition.peptide_group_label << std::endl;
std::cout << mytransition.fragment_charge << std::endl;
std::cout << mytransition.fragment_nr << std::endl;
std::cout << mytransition.fragment_mzdelta << std::endl;
std::cout << mytransition.fragment_modification << std::endl;
std::cout << mytransition.fragment_type << std::endl;
std::cout << mytransition.uniprot_id << std::endl;
#endif
tmp_line.clear();
}
if (spectrast_legacy && retentionTimeInterpretation_ == "iRT")
{
std::cout << "Warning: SpectraST was not run in RT normalization mode but the converted list was interpreted to have iRT units. Check whether you need to adapt the parameter -algorithm:retentionTimeInterpretation. You can ignore this warning if you used a legacy SpectraST 4.0 file." << std::endl;
}
}
void TransitionTSVFile::spectrastRTExtract(const String str_inp, double & value, bool & spectrast_legacy)
{
// If SpectraST was run in RT normalization mode, the retention time is annotated as following: "3887.50(57.30)"
// 3887.50 refers to the non-normalized RT of the individual or consensus run, and 57.30 refers to the normalized
// iRT.
size_t start_position = str_inp.find("(");
if (start_position != std::string::npos)
{
++start_position;
size_t end_position = str_inp.find(")");
if (end_position != std::string::npos)
{
value = String(str_inp.substr(start_position, end_position - start_position)).toDouble();
}
}
else
{
// SpectraST was run without RT Normalization mode
spectrast_legacy = true;
value = str_inp.toDouble();
}
}
bool TransitionTSVFile::spectrastAnnotationExtract(const String str_inp, TSVTransition & mytransition)
{
// Parses SpectraST fragment ion annotations
// Example: y13^2/0.000,b16-18^2/-0.013,y7-45/0.000
// Important: m2:8 are not yet supported! See SpectraSTPeakList::annotateInternalFragments for further information
mytransition.Annotation = str_inp;
std::vector<String> all_fragment_annotations;
str_inp.split(",", all_fragment_annotations);
if (all_fragment_annotations[0].find("[") == std::string::npos && // non-unique peak annotation
all_fragment_annotations[0].find("]") == std::string::npos && // non-unique peak annotation
all_fragment_annotations[0].find("I") == std::string::npos && // immonium ion
all_fragment_annotations[0].find("p") == std::string::npos && // precursor ion
all_fragment_annotations[0].find("i") == std::string::npos && // isotope ion
all_fragment_annotations[0].find("m") == std::string::npos &&
all_fragment_annotations[0].find("?") == std::string::npos
)
{
std::vector<String> best_fragment_annotation_with_deviation;
all_fragment_annotations[0].split("/", best_fragment_annotation_with_deviation);
String best_fragment_annotation = best_fragment_annotation_with_deviation[0];
if (best_fragment_annotation.find("^") != std::string::npos)
{
std::vector<String> best_fragment_annotation_charge;
best_fragment_annotation.split("^", best_fragment_annotation_charge);
mytransition.fragment_charge = String(best_fragment_annotation_charge[1]);
best_fragment_annotation = best_fragment_annotation_charge[0];
}
else
{
mytransition.fragment_charge = 1; // assume 1 (most frequent charge state)
}
if (best_fragment_annotation.find("-") != std::string::npos)
{
std::vector<String> best_fragment_annotation_modification;
best_fragment_annotation.split("-", best_fragment_annotation_modification);
mytransition.fragment_type = best_fragment_annotation_modification[0].substr(0, 1);
mytransition.fragment_nr = String(best_fragment_annotation_modification[0].substr(1)).toInt();
mytransition.fragment_modification = -1 * String(best_fragment_annotation_modification[1]).toInt();
}
else if (best_fragment_annotation.find("+") != std::string::npos)
{
std::vector<String> best_fragment_annotation_modification;
best_fragment_annotation.split("+", best_fragment_annotation_modification);
mytransition.fragment_type = best_fragment_annotation_modification[0].substr(0, 1);
mytransition.fragment_nr = String(best_fragment_annotation_modification[0].substr(1)).toInt();
mytransition.fragment_modification = String(best_fragment_annotation_modification[1]).toInt();
}
else
{
mytransition.fragment_type = best_fragment_annotation.substr(0, 1);
mytransition.fragment_nr = String(best_fragment_annotation.substr(1)).toInt();
mytransition.fragment_modification = 0;
}
mytransition.fragment_mzdelta = String(best_fragment_annotation_with_deviation[1]).toDouble();
}
else
{
// The fragment ion could not be annotated and will likely not be used for detection transitions;
// we thus skip it and reduce the size of the output TraML.
return true;
}
return false;
}
void TransitionTSVFile::cleanupTransitions_(TSVTransition& mytransition)
{
// deal with FullPeptideNames like PEPTIDE/2
std::vector<String> substrings;
mytransition.FullPeptideName.split("/", substrings);
if (substrings.size() == 2)
{
mytransition.FullPeptideName = substrings[0];
mytransition.precursor_charge = substrings[1];
}
}
void TransitionTSVFile::TSVToTargetedExperiment_(std::vector<TSVTransition>& transition_list, OpenMS::TargetedExperiment& exp)
{
// For the CV terms, see
// http://psidev.cvs.sourceforge.net/viewvc/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo
typedef std::vector<OpenMS::TargetedExperiment::Compound> CompoundVectorType;
CompoundVectorType compounds;
PeptideVectorType peptides;
ProteinVectorType proteins;
std::map<String, int> peptide_map;
std::map<String, int> compound_map;
std::map<String, int> protein_map;
resolveMixedSequenceGroups_(transition_list);
Size progress = 0;
startProgress(0, transition_list.size(), "conversion to internal data representation");
for (auto tr_it = transition_list.begin(); tr_it != transition_list.end(); ++tr_it)
{
ReactionMonitoringTransition rm_trans;
createTransition_(tr_it, rm_trans);
exp.addTransition(rm_trans);
// check whether we need a new peptide
if (peptide_map.find(tr_it->group_id) == peptide_map.end() &&
compound_map.find(tr_it->group_id) == compound_map.end() )
{
// should we make a peptide or a compound ?
if (tr_it->isPeptide())
{
OpenMS::TargetedExperiment::Peptide peptide;
createPeptide_(tr_it, peptide);
peptides.push_back(peptide);
peptide_map[peptide.id] = 0;
}
else
{
OpenMS::TargetedExperiment::Compound compound;
createCompound_(tr_it, compound);
compounds.push_back(compound);
compound_map[compound.id] = 0;
}
}
// check whether we need a new protein
if (tr_it->isPeptide() && protein_map.find(tr_it->ProteinName) == protein_map.end())
{
OpenMS::TargetedExperiment::Protein protein;
createProtein_(tr_it, protein);
proteins.push_back(protein);
protein_map[tr_it->ProteinName] = 0;
}
setProgress(progress++);
}
endProgress();
exp.setCompounds(compounds);
exp.setPeptides(peptides);
exp.setProteins(proteins);
OPENMS_POSTCONDITION(exp.getTransitions().size() == transition_list.size(), "Input and output list need to have equal size.")
}
void TransitionTSVFile::TSVToTargetedExperiment_(std::vector<TSVTransition>& transition_list, OpenSwath::LightTargetedExperiment& exp)
{
std::map<String, int> compound_map;
std::map<String, int> protein_map;
resolveMixedSequenceGroups_(transition_list);
Size progress = 0;
startProgress(0, transition_list.size(), "conversion to internal data representation");
for (auto tr_it = transition_list.cbegin(); tr_it != transition_list.cend(); ++tr_it)
{
OpenSwath::LightTransition transition;
transition.transition_name = tr_it->transition_name;
transition.peptide_ref = tr_it->group_id;
transition.library_intensity = tr_it->library_intensity;
transition.precursor_mz = tr_it->precursor;
transition.product_mz = tr_it->product;
transition.fragment_charge = 0; // use zero for charge that is not set
if (!tr_it->fragment_charge.empty() && tr_it->fragment_charge != "NA")
{
transition.fragment_charge = tr_it->fragment_charge.toInt();
}
transition.decoy = tr_it->decoy;
transition.detecting_transition = tr_it->detecting_transition;
transition.identifying_transition = tr_it->identifying_transition;
transition.quantifying_transition = tr_it->quantifying_transition;
exp.transitions.push_back(transition);
// check whether we need a new compound
if (compound_map.find(tr_it->group_id) == compound_map.end())
{
OpenSwath::LightCompound compound;
if (tr_it->isPeptide())
{
OpenMS::TargetedExperiment::Peptide tramlpeptide;
createPeptide_(tr_it, tramlpeptide);
OpenSwathDataAccessHelper::convertTargetedCompound(tramlpeptide, compound);
}
else
{
OpenMS::TargetedExperiment::Compound tramlcompound;
createCompound_(tr_it, tramlcompound);
OpenSwathDataAccessHelper::convertTargetedCompound(tramlcompound, compound);
}
exp.compounds.push_back(compound);
compound_map[compound.id] = 0;
}
// check whether we need a new protein
if (tr_it->isPeptide() && protein_map.find(tr_it->ProteinName) == protein_map.end())
{
OpenSwath::LightProtein protein;
protein.id = tr_it->ProteinName;
protein.sequence = "";
exp.proteins.push_back(protein);
protein_map[tr_it->ProteinName] = 0;
}
setProgress(progress++);
}
endProgress();
OPENMS_POSTCONDITION(exp.transitions.size() == transition_list.size(), "Input and output list need to have equal size.")
}
void TransitionTSVFile::resolveMixedSequenceGroups_(std::vector<TransitionTSVFile::TSVTransition>& transition_list) const
{
// Create temporary map by group label
std::map<String, std::vector<TSVTransition*> > label_transition_map;
for (auto & tr_it : transition_list)
{
if (!tr_it.peptide_group_label.empty())
{
label_transition_map[tr_it.peptide_group_label].push_back(&tr_it);
}
}
// Iterate through all the group labels and perform sanity check whether
// the peptide sequence is the same for all of them
for (auto & pep_it : label_transition_map)
{
String curr_sequence;
if (!pep_it.second.empty())
{
curr_sequence = (*pep_it.second.begin())->PeptideSequence;
}
for (auto & tr_it : pep_it.second)
{
// Sanity check: different peptide sequence in the same peptide label
// group means that something is probably wrong ...
if (!curr_sequence.empty() && tr_it->PeptideSequence != curr_sequence)
{
if (override_group_label_check_)
{
// We wont fix it but give out a warning
LOG_WARN << "Warning: Found multiple peptide sequences for peptide label group " << pep_it.first <<
". Since 'override_group_label_check' is on, nothing will be changed." << std::endl;
}
else
{
// Lets fix it and inform the user
LOG_WARN << "Warning: Found multiple peptide sequences for peptide label group " << pep_it.first <<
". This is most likely an error and to fix this, a new peptide label group will be inferred - " <<
"to override this decision, please use the override_group_label_check parameter." << std::endl;
tr_it->peptide_group_label = tr_it->group_id;
}
}
}
}
}
void TransitionTSVFile::createTransition_(std::vector<TSVTransition>::iterator& tr_it, OpenMS::ReactionMonitoringTransition& rm_trans)
{
// the following attributes will be stored as meta values (userParam):
// - annotation (as by SpectraST)
// the following attributes will be stored as CV values (CV):
// - collision energy
// - library intensity (product ion intensity)
// - decoy / target transition (binary MS:1002007 or MS:1002008)
// the following attributes will be stored as attributes:
// - id (native id)
// the following attributes will be stored in sub-tags:
// - Precursor:
// * target precursor mass isolation window [Q1] (CV Param)
// - Product:
// * charge state (CV Param)
// * target product mass isolation window [Q3] (CV Param)
// - Interpretation (only best)
// * Fragment number (number in series) (CV Param)
// * Fragment type (which series) (CV Param)
rm_trans.setNativeID(tr_it->transition_name);
rm_trans.setPrecursorMZ(tr_it->precursor);
rm_trans.setProductMZ(tr_it->product);
if (tr_it->isPeptide())
{
rm_trans.setPeptideRef(tr_it->group_id);
}
else
{
rm_trans.setCompoundRef(tr_it->group_id);
}
rm_trans.setLibraryIntensity(tr_it->library_intensity);
if (!tr_it->fragment_charge.empty() && tr_it->fragment_charge != "NA")
{
OpenMS::ReactionMonitoringTransition::Product p = rm_trans.getProduct();
p.setChargeState(tr_it->fragment_charge.toInt());
rm_trans.setProduct(p);
}
// add interpretation
OpenMS::ReactionMonitoringTransition::Product p = rm_trans.getProduct();
TargetedExperiment::Interpretation interpretation;
// check if we have any information about the interpretation
bool interpretation_set = false;
if (tr_it->fragment_nr != -1 ||
tr_it->fragment_mzdelta != -1 ||
tr_it->fragment_modification < 0 ||
tr_it->fragment_type != "" )
{
interpretation_set = true;
}
if (tr_it->fragment_nr != -1)
{
interpretation.rank = 1; // we only store the best interpretation
}
if (tr_it->fragment_nr != -1)
{
interpretation.ordinal = tr_it->fragment_nr;
}
if (tr_it->fragment_mzdelta != -1)
{
CVTerm frag_mzdelta;
frag_mzdelta.setCVIdentifierRef("MS");
frag_mzdelta.setAccession("MS:1000904");
frag_mzdelta.setName("product ion m/z delta");
frag_mzdelta.setValue(tr_it->fragment_mzdelta);
interpretation.addCVTerm(frag_mzdelta);
}
if (tr_it->fragment_modification < 0)
{
CVTerm frag_loss;
frag_loss.setCVIdentifierRef("MS");
frag_loss.setAccession("MS:1001524");
frag_loss.setName("fragment neutral loss");
frag_loss.setValue(tr_it->fragment_modification);
interpretation.addCVTerm(frag_loss);
}
// figure out which fragment it is
if (tr_it->fragment_type == "v")
{
CVTerm ion;
ion.setCVIdentifierRef("MS");
ion.setAccession("MS:1001237");
ion.setName("frag: v ion");
interpretation.addCVTerm(ion);
}
else if (tr_it->fragment_type == "w")
{
CVTerm ion;
ion.setCVIdentifierRef("MS");
ion.setAccession("MS:1001238");
ion.setName("frag: w ion");
interpretation.addCVTerm(ion);
}
else if (tr_it->fragment_type == "x")
{
interpretation.iontype = TargetedExperiment::IonType::XIon;
}
else if (tr_it->fragment_type == "y")
{
interpretation.iontype = TargetedExperiment::IonType::YIon;
}
else if (tr_it->fragment_type == "z")
{
interpretation.iontype = TargetedExperiment::IonType::ZIon;
}
else if (tr_it->fragment_type == "a")
{
interpretation.iontype = TargetedExperiment::IonType::AIon;
}
else if (tr_it->fragment_type == "b")
{
interpretation.iontype = TargetedExperiment::IonType::BIon;
}
else if (tr_it->fragment_type == "c")
{
interpretation.iontype = TargetedExperiment::IonType::CIon;
}
else if (tr_it->fragment_type == "d")
{
CVTerm ion;
ion.setCVIdentifierRef("MS");
ion.setAccession("MS:1001236");
ion.setName("frag: d ion");
interpretation.addCVTerm(ion);
}
else if (tr_it->fragment_type == "unknown")
{
// unknown means that we should write CV Term "1001240"
interpretation.iontype = TargetedExperiment::IonType::NonIdentified;
}
else if (tr_it->fragment_type == "")
{
// empty means that we have no information whatsoever
interpretation.iontype = TargetedExperiment::IonType::Unannotated;
}
else
{
interpretation.iontype = TargetedExperiment::IonType::NonIdentified;
}
// dont add empty interpretations
if (interpretation_set)
{
p.addInterpretation(interpretation);
}
rm_trans.setProduct(p);
// add collision energy
if (tr_it->CE > 0.0)
{
CVTerm CE;
CE.setCVIdentifierRef("MS");
CE.setAccession("MS:1000045"); // collision energy
CE.setName("collision energy");
CE.setValue(tr_it->CE);
rm_trans.addCVTerm(CE);
}
if (!tr_it->decoy)
{
rm_trans.setDecoyTransitionType(ReactionMonitoringTransition::TARGET);
}
else
{
rm_trans.setDecoyTransitionType(ReactionMonitoringTransition::DECOY);
}
if (!tr_it->Annotation.empty())
{
rm_trans.setMetaValue("annotation", tr_it->Annotation);
}
rm_trans.setDetectingTransition(tr_it->detecting_transition);
rm_trans.setIdentifyingTransition(tr_it->identifying_transition);
rm_trans.setQuantifyingTransition(tr_it->quantifying_transition);
if (!tr_it->peptidoforms.empty())
{
rm_trans.setMetaValue("Peptidoforms", ListUtils::concatenate(tr_it->peptidoforms, "|"));
}
}
void TransitionTSVFile::createProtein_(std::vector<TSVTransition>::iterator& tr_it, OpenMS::TargetedExperiment::Protein& protein)
{
// the following attributes will be stored as CV values (CV):
// - uniprot accession number (if available)
// the following attributes will be stored as attributes:
// - id
protein.id = tr_it->ProteinName;
if (!tr_it->uniprot_id.empty())
{
// accession numbers
CVTerm acc;
OpenMS::DataValue dtype(tr_it->uniprot_id);
acc.setCVIdentifierRef("MS");
acc.setAccession("MS:1000885"); // Accession number for a specific protein in a database.
acc.setName("protein accession");
acc.setValue(dtype);
protein.addCVTerm(acc);
}
}
void TransitionTSVFile::interpretRetentionTime_(std::vector<TargetedExperiment::RetentionTime>& retention_times, const OpenMS::DataValue rt_value)
{
TargetedExperiment::RetentionTime retention_time;
retention_time.setRT(rt_value);
if (retentionTimeInterpretation_ == "iRT")
{
retention_time.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::IRT;
// no unit, since it is iRT (normalized RT)
}
else if (retentionTimeInterpretation_ == "seconds" || retentionTimeInterpretation_ == "minutes")
{
retention_time.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::LOCAL;
if (retentionTimeInterpretation_ == "seconds")
{
retention_time.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND;
}
else if (retentionTimeInterpretation_ == "minutes")
{
retention_time.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::MINUTE;
}
}
retention_times.push_back(retention_time);
}
void TransitionTSVFile::createPeptide_(std::vector<TSVTransition>::const_iterator tr_it, OpenMS::TargetedExperiment::Peptide& peptide)
{
// the following attributes will be stored as meta values (userParam):
// - full_peptide_name (full unimod peptide name)
// the following attributes will be stored as CV values (CV):
// - retention time
// - charge state
// - group label
// the following attributes will be stored as attributes:
// - id
// - sequence
peptide.id = tr_it->group_id;
peptide.sequence = tr_it->PeptideSequence;
// per peptide user params
peptide.setMetaValue("full_peptide_name", tr_it->FullPeptideName);
if (!tr_it->label_type.empty())
{
peptide.setMetaValue("LabelType", tr_it->label_type);
}
if (!tr_it->GeneName.empty())
{
peptide.setMetaValue("GeneName", tr_it->GeneName);
}
// per peptide CV terms
peptide.setPeptideGroupLabel(tr_it->peptide_group_label);
if (!tr_it->precursor_charge.empty() && tr_it->precursor_charge != "NA")
{
peptide.setChargeState(tr_it->precursor_charge.toInt());
}
// add retention time for the peptide
std::vector<TargetedExperiment::RetentionTime> retention_times;
OpenMS::DataValue rt_value(tr_it->rt_calibrated);
interpretRetentionTime_(retention_times, rt_value);
peptide.rts = retention_times;
// add ion mobility drift time
if (tr_it->drift_time >= 0.0)
{
peptide.setDriftTime(tr_it->drift_time);
}
// Try to parse full UniMod string including modifications. If we fail, we
// can force reading and only parse the "naked" sequence.
// Note: If the user did not provide a modified sequence string, we will
// fall back to the "naked" sequence by default.
std::vector<TargetedExperiment::Peptide::Modification> mods;
AASequence aa_sequence;
String sequence = tr_it->FullPeptideName;
if (sequence.empty()) sequence = tr_it->PeptideSequence;
try
{
aa_sequence = AASequence::fromString(sequence);
} catch (Exception::InvalidValue & e)
{
if (force_invalid_mods_)
{
LOG_DEBUG << "Invalid sequence when parsing '" << tr_it->FullPeptideName << "'" << std::endl;
aa_sequence = AASequence::fromString(tr_it->PeptideSequence);
}
else
{
LOG_DEBUG << "Invalid sequence when parsing '" << tr_it->FullPeptideName << "'" << std::endl;
std::cerr << "Error while reading file (use 'force_invalid_mods' parameter to override): " << e.what() << std::endl;
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Invalid input, cannot parse: " + tr_it->FullPeptideName);
}
}
std::vector<String> tmp_proteins;
tmp_proteins.push_back(tr_it->ProteinName);
peptide.protein_refs = tmp_proteins;
// check if the naked peptide sequence is equal to the unmodified AASequence
if (peptide.sequence != aa_sequence.toUnmodifiedString())
{
if (force_invalid_mods_)
{
// something is wrong, return and do not try and add any modifications
return;
}
LOG_WARN << "Warning: The peptide sequence " << peptide.sequence << " and the full peptide name " << aa_sequence <<
" are not equal. Please check your input." << std::endl;
LOG_WARN << "(use force_invalid_mods to override)" << std::endl;
}
// Unfortunately, we cannot store an AASequence here but have to work with
// the TraML modification object.
// In TraML, the modification the AA starts with residue 1 but the
// OpenMS objects start with zero -> we start counting with zero here
// and the TraML handler will add 1 when storing the file.
if (std::string::npos == tr_it->FullPeptideName.find("["))
{
if (aa_sequence.hasNTerminalModification())
{
const ResidueModification& rmod = *(aa_sequence.getNTerminalModification());
addModification_(mods, -1, rmod);
}
if (aa_sequence.hasCTerminalModification())
{
const ResidueModification& rmod = *(aa_sequence.getCTerminalModification());
addModification_(mods, aa_sequence.size(), rmod);
}
for (Size i = 0; i != aa_sequence.size(); i++)
{
if (aa_sequence[i].isModified())
{
const ResidueModification& rmod = *(aa_sequence.getResidue(i).getModification());
addModification_(mods, i, rmod);
}
}
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Error, could not parse modifications on " + tr_it->FullPeptideName +
". Please use unimod / freetext identifiers like PEPT(Phosphorylation)IDE(UniMod:27)A.");
}
peptide.mods = mods;
OPENMS_POSTCONDITION(aa_sequence.toUnmodifiedString() == peptide.sequence,
(String("Internal error: the sequences of the naked and modified peptide sequence are unequal(")
+ aa_sequence.toUnmodifiedString() + " != " + peptide.sequence).c_str())
}
void TransitionTSVFile::createCompound_(std::vector<TSVTransition>::const_iterator tr_it, OpenMS::TargetedExperiment::Compound& compound)
{
// the following attributes will be stored as meta values (userParam):
// - CompoundName (name of the compound)
// - Adducts (adduct associated to the compound)
// the following attributes will be stored as CV values (CV):
// - label type
// the following attributes will be stored as attributes:
// - retention time
// - charge state
// - SMILES
// - id
compound.id = tr_it->group_id;
compound.molecular_formula = tr_it->SumFormula;
compound.smiles_string = tr_it->SMILES;
compound.setMetaValue("CompoundName", tr_it->CompoundName);
if (!tr_it->Adducts.empty()) compound.setMetaValue("Adducts", tr_it->Adducts);
// does this apply to compounds as well?
if (!tr_it->label_type.empty())
{
compound.setMetaValue("LabelType", tr_it->label_type);
}
// add ion mobility drift time
if (tr_it->drift_time >= 0.0)
{
compound.setDriftTime(tr_it->drift_time);
}
if (!tr_it->precursor_charge.empty() && tr_it->precursor_charge != "NA")
{
compound.setChargeState(tr_it->precursor_charge.toInt());
}
// add retention time for the compound
std::vector<TargetedExperiment::RetentionTime> retention_times;
OpenMS::DataValue rt_value(tr_it->rt_calibrated);
interpretRetentionTime_(retention_times, rt_value);
compound.rts = retention_times;
}
void TransitionTSVFile::addModification_(std::vector<TargetedExperiment::Peptide::Modification>& mods,
int location, const ResidueModification& rmod)
{
TargetedExperiment::Peptide::Modification mod;
mod.location = location;
mod.mono_mass_delta = rmod.getDiffMonoMass();
mod.avg_mass_delta = rmod.getDiffAverageMass();
mod.unimod_id = rmod.getUniModRecordId();
mods.push_back(mod);
}
TransitionTSVFile::TSVTransition TransitionTSVFile::convertTransition_(const ReactionMonitoringTransition* it, OpenMS::TargetedExperiment& targeted_exp)
{
TSVTransition mytransition;
mytransition.precursor = it->getPrecursorMZ();
mytransition.product = it->getProductMZ();
mytransition.rt_calibrated = -1;
mytransition.fragment_type = "";
mytransition.fragment_nr = -1;
mytransition.fragment_charge = "NA";
if (!it->getPeptideRef().empty())
{
const OpenMS::TargetedExperiment::Peptide& pep = targeted_exp.getPeptideByRef(it->getPeptideRef());
mytransition.group_id = it->getPeptideRef();
#ifdef TRANSITIONTSVREADER_TESTING
LOG_DEBUG << "Peptide rts empty " <<
pep.rts.empty() << " or no cv term " << pep.getRetentionTime() << std::endl;
#endif
if (pep.hasRetentionTime())
{
mytransition.rt_calibrated = pep.getRetentionTime();
}
mytransition.PeptideSequence = pep.sequence;
mytransition.ProteinName = "NA";
mytransition.GeneName = "NA";
mytransition.uniprot_id = "NA";
if (!pep.protein_refs.empty())
{
const OpenMS::TargetedExperiment::Protein& prot = targeted_exp.getProteinByRef(pep.protein_refs[0]);
mytransition.ProteinName = prot.id;
if (prot.hasCVTerm("MS:1000885"))
{
mytransition.uniprot_id = prot.getCVTerms()["MS:1000885"][0].getValue().toString();
}
}
mytransition.FullPeptideName = TargetedExperimentHelper::getAASequence(pep).toUniModString();
mytransition.drift_time = -1;
if (pep.getDriftTime() >= 0.0)
{
mytransition.drift_time = pep.getDriftTime();
}
mytransition.precursor_charge = "NA";
if (pep.hasCharge())
{
mytransition.precursor_charge = String(pep.getChargeState());
}
mytransition.peptide_group_label = "NA";
if (pep.getPeptideGroupLabel() != "")
{
mytransition.peptide_group_label = pep.getPeptideGroupLabel();
}
if (pep.metaValueExists("LabelType"))
{
mytransition.label_type = pep.getMetaValue("LabelType").toString();
}
if (pep.metaValueExists("GeneName"))
{
mytransition.GeneName = pep.getMetaValue("GeneName").toString();
}
}
else if (!it->getCompoundRef().empty())
{
const OpenMS::TargetedExperiment::Compound& compound = targeted_exp.getCompoundByRef(it->getCompoundRef());
mytransition.group_id = it->getCompoundRef();
if (compound.hasRetentionTime())
{
mytransition.rt_calibrated = compound.getRetentionTime();
}
mytransition.drift_time = -1;
if (compound.getDriftTime() >= 0.0)
{
mytransition.drift_time = compound.getDriftTime();
}
mytransition.precursor_charge = "NA";
if (compound.hasCharge())
{
mytransition.precursor_charge = String(compound.getChargeState());
}
// get metabolomics specific terms
mytransition.SumFormula = compound.molecular_formula;
mytransition.SMILES = compound.smiles_string;
if (compound.metaValueExists("CompoundName"))
{
mytransition.CompoundName = compound.getMetaValue("CompoundName");
}
if (compound.metaValueExists("Adducts"))
{
mytransition.Adducts = compound.getMetaValue("Adducts");
}
}
else
{
// Error?
}
if (it->isProductChargeStateSet())
{
mytransition.fragment_charge = String(it->getProductChargeState());
}
const auto & product = it->getProduct();
for (const auto& int_it : product.getInterpretationList())
{
// only report first / best interpretation
if (int_it.rank == 1 || product.getInterpretationList().size() == 1)
{
if (int_it.ordinal != 0) mytransition.fragment_nr = int_it.ordinal;
switch (int_it.iontype)
{
case Residue::AIon:
mytransition.fragment_type = "a";
break;
case Residue::BIon:
mytransition.fragment_type = "b";
break;
case Residue::CIon:
mytransition.fragment_type = "c";
break;
case Residue::XIon:
mytransition.fragment_type = "x";
break;
case Residue::YIon:
mytransition.fragment_type = "y";
break;
case Residue::ZIon:
mytransition.fragment_type = "z";
break;
case Residue::Precursor:
mytransition.fragment_type = "prec";
break;
case Residue::BIonMinusH20:
mytransition.fragment_type = "b-H20";
break;
case Residue::YIonMinusH20:
mytransition.fragment_type = "y-H20";
break;
case Residue::BIonMinusNH3:
mytransition.fragment_type = "b-NH3";
break;
case Residue::YIonMinusNH3:
mytransition.fragment_type = "y-NH3";
break;
case Residue::NonIdentified:
mytransition.fragment_type = "unknown";
break;
case Residue::Unannotated:
// means no annotation and no input cvParam - to write out a cvParam, use Residue::NonIdentified
mytransition.fragment_type = "";
break;
// invalid values
case Residue::Full: break;
case Residue::Internal: break;
case Residue::NTerminal: break;
case Residue::CTerminal: break;
case Residue::SizeOfResidueType: break;
}
}
}
mytransition.transition_name = it->getNativeID();
mytransition.CE = -1;
if (it->hasCVTerm("MS:1000045"))
{
mytransition.CE = it->getCVTerms()["MS:1000045"][0].getValue().toString().toDouble();
}
mytransition.library_intensity = -1;
if (it->getLibraryIntensity() > -100)
{
mytransition.library_intensity = it->getLibraryIntensity();
}
mytransition.decoy = false;
if (it->getDecoyTransitionType() == ReactionMonitoringTransition::TARGET)
{
mytransition.decoy = false;
}
else if (it->getDecoyTransitionType() == ReactionMonitoringTransition::DECOY)
{
mytransition.decoy = true;
}
mytransition.Annotation = "NA";
if (it->metaValueExists("annotation"))
{
mytransition.Annotation = it->getMetaValue("annotation").toString();
}
if (it->metaValueExists("Peptidoforms"))
{
String(it->getMetaValue("Peptidoforms")).split('|', mytransition.peptidoforms);
}
mytransition.detecting_transition = it->isDetectingTransition();
mytransition.identifying_transition = it->isIdentifyingTransition();
mytransition.quantifying_transition = it->isQuantifyingTransition();
return mytransition;
}
void TransitionTSVFile::writeTSVOutput_(const char* filename, OpenMS::TargetedExperiment& targeted_exp)
{
std::vector<TSVTransition> mytransitions;
Size progress = 0;
startProgress(0, targeted_exp.getTransitions().size(), "writing OpenSWATH Transition List TSV file");
for (const auto& tr : targeted_exp.getTransitions())
{
mytransitions.push_back(convertTransition_(&tr, targeted_exp));
setProgress(progress++);
}
endProgress();
// start writing
std::ofstream os(filename);
os.precision(writtenDigits(double()));
for (Size i = 0; i < header_names_.size(); i++)
{
os << header_names_[i];
if (i != header_names_.size() - 1)
{
os << "\t";
}
}
os << std::endl;
for (const auto& it : mytransitions)
{
String line;
line +=
(String)it.precursor + "\t"
+ (String)it.product + "\t"
+ (String)it.precursor_charge + "\t"
+ (String)it.fragment_charge + "\t"
+ (String)it.library_intensity + "\t"
+ (String)it.rt_calibrated + "\t"
+ (String)it.PeptideSequence + "\t"
+ (String)it.FullPeptideName + "\t"
+ (String)it.peptide_group_label + "\t"
+ (String)it.label_type + "\t"
+ (String)it.CompoundName + "\t"
+ (String)it.SumFormula + "\t"
+ (String)it.SMILES + "\t"
+ (String)it.Adducts + "\t"
+ (String)it.ProteinName + "\t"
+ (String)it.uniprot_id + "\t"
+ (String)it.GeneName + "\t"
+ (String)it.fragment_type + "\t"
+ (String)it.fragment_nr + "\t"
+ (String)it.Annotation + "\t"
+ (String)it.CE + "\t"
+ (String)it.drift_time + "\t"
+ (String)it.group_id + "\t"
+ (String)it.transition_name + "\t"
+ (String)it.decoy + "\t"
+ (String)it.detecting_transition + "\t"
+ (String)it.identifying_transition + "\t"
+ (String)it.quantifying_transition + "\t"
+ ListUtils::concatenate(it.peptidoforms, "|");
os << line << std::endl;
}
os.close();
}
// public methods
void TransitionTSVFile::convertTargetedExperimentToTSV(const char* filename, OpenMS::TargetedExperiment& targeted_exp)
{
if (targeted_exp.containsInvalidReferences())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Your input file contains invalid references, cannot process file.");
}
writeTSVOutput_(filename, targeted_exp);
}
void TransitionTSVFile::convertTSVToTargetedExperiment(const char* filename, FileTypes::Type filetype, OpenMS::TargetedExperiment& targeted_exp)
{
std::vector<TSVTransition> transition_list;
readUnstructuredTSVInput_(filename, filetype, transition_list);
TSVToTargetedExperiment_(transition_list, targeted_exp);
}
void TransitionTSVFile::convertTSVToTargetedExperiment(const char* filename, FileTypes::Type filetype, OpenSwath::LightTargetedExperiment& targeted_exp)
{
std::vector<TSVTransition> transition_list;
readUnstructuredTSVInput_(filename, filetype, transition_list);
TSVToTargetedExperiment_(transition_list, targeted_exp);
}
void TransitionTSVFile::validateTargetedExperiment(const OpenMS::TargetedExperiment& targeted_exp)
{
if (targeted_exp.containsInvalidReferences())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Invalid input, contains duplicate or invalid references");
}
}
}
| 39.340027 | 391 | 0.657025 | [
"object",
"vector"
] |
4fc0b13c0a574d28c3a1196ae5b772ea7586af64 | 13,106 | cxx | C++ | cmake-2.8.10.1/Source/cmTryRunCommand.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | cmake-2.8.10.1/Source/cmTryRunCommand.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | cmake-2.8.10.1/Source/cmTryRunCommand.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | /*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "cmTryRunCommand.h"
#include "cmCacheManager.h"
#include "cmTryCompileCommand.h"
// cmTryRunCommand
bool cmTryRunCommand
::InitialPass(std::vector<std::string> const& argv, cmExecutionStatus &)
{
if(argv.size() < 4)
{
return false;
}
if(this->Makefile->GetCMakeInstance()->GetWorkingMode() ==
cmake::FIND_PACKAGE_MODE)
{
this->Makefile->IssueMessage(cmake::FATAL_ERROR,
"The TRY_RUN() command is not supported in --find-package mode.");
return false;
}
// build an arg list for TryCompile and extract the runArgs,
std::vector<std::string> tryCompile;
this->CompileResultVariable = "";
this->RunResultVariable = "";
this->OutputVariable = "";
this->RunOutputVariable = "";
this->CompileOutputVariable = "";
std::string runArgs;
unsigned int i;
for (i = 1; i < argv.size(); ++i)
{
if (argv[i] == "ARGS")
{
++i;
while (i < argv.size() && argv[i] != "COMPILE_DEFINITIONS" &&
argv[i] != "CMAKE_FLAGS")
{
runArgs += " ";
runArgs += argv[i];
++i;
}
if (i < argv.size())
{
tryCompile.push_back(argv[i]);
}
}
else
{
if (argv[i] == "OUTPUT_VARIABLE")
{
if ( argv.size() <= (i+1) )
{
cmSystemTools::Error(
"OUTPUT_VARIABLE specified but there is no variable");
return false;
}
i++;
this->OutputVariable = argv[i];
}
else if (argv[i] == "RUN_OUTPUT_VARIABLE")
{
if (argv.size() <= (i + 1))
{
cmSystemTools::Error(
"RUN_OUTPUT_VARIABLE specified but there is no variable");
return false;
}
i++;
this->RunOutputVariable = argv[i];
}
else if (argv[i] == "COMPILE_OUTPUT_VARIABLE")
{
if (argv.size() <= (i + 1))
{
cmSystemTools::Error(
"COMPILE_OUTPUT_VARIABLE specified but there is no variable");
return false;
}
i++;
this->CompileOutputVariable = argv[i];
}
else
{
tryCompile.push_back(argv[i]);
}
}
}
// although they could be used together, don't allow it, because
// using OUTPUT_VARIABLE makes crosscompiling harder
if (this->OutputVariable.size()
&& ((this->RunOutputVariable.size())
|| (this->CompileOutputVariable.size())))
{
cmSystemTools::Error(
"You cannot use OUTPUT_VARIABLE together with COMPILE_OUTPUT_VARIABLE "
"or RUN_OUTPUT_VARIABLE. Please use only COMPILE_OUTPUT_VARIABLE and/or "
"RUN_OUTPUT_VARIABLE.");
return false;
}
bool captureRunOutput = false;
if (this->OutputVariable.size())
{
captureRunOutput = true;
tryCompile.push_back("OUTPUT_VARIABLE");
tryCompile.push_back(this->OutputVariable);
}
if (this->CompileOutputVariable.size())
{
tryCompile.push_back("OUTPUT_VARIABLE");
tryCompile.push_back(this->CompileOutputVariable);
}
if (this->RunOutputVariable.size())
{
captureRunOutput = true;
}
this->RunResultVariable = argv[0];
this->CompileResultVariable = argv[1];
// do the try compile
int res = this->TryCompileCode(tryCompile);
// now try running the command if it compiled
if (!res)
{
if (this->OutputFile.size() == 0)
{
cmSystemTools::Error(this->FindErrorMessage.c_str());
}
else
{
// "run" it and capture the output
std::string runOutputContents;
if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING"))
{
this->DoNotRunExecutable(runArgs,
argv[3],
captureRunOutput ? &runOutputContents : 0);
}
else
{
this->RunExecutable(runArgs, &runOutputContents);
}
// now put the output into the variables
if(this->RunOutputVariable.size())
{
this->Makefile->AddDefinition(this->RunOutputVariable.c_str(),
runOutputContents.c_str());
}
if(this->OutputVariable.size())
{
// if the TryCompileCore saved output in this outputVariable then
// prepend that output to this output
const char* compileOutput
= this->Makefile->GetDefinition(this->OutputVariable.c_str());
if (compileOutput)
{
runOutputContents = std::string(compileOutput) + runOutputContents;
}
this->Makefile->AddDefinition(this->OutputVariable.c_str(),
runOutputContents.c_str());
}
}
}
// if we created a directory etc, then cleanup after ourselves
if(!this->Makefile->GetCMakeInstance()->GetDebugTryCompile())
{
this->CleanupFiles(this->BinaryDirectory.c_str());
}
return true;
}
void cmTryRunCommand::RunExecutable(const std::string& runArgs,
std::string* out)
{
int retVal = -1;
std::string finalCommand = cmSystemTools::ConvertToRunCommandPath(
this->OutputFile.c_str());
if (runArgs.size())
{
finalCommand += runArgs;
}
int timeout = 0;
bool worked = cmSystemTools::RunSingleCommand(finalCommand.c_str(),
out, &retVal,
0, cmSystemTools::OUTPUT_NONE, timeout);
// set the run var
char retChar[1000];
if (worked)
{
sprintf(retChar, "%i", retVal);
}
else
{
strcpy(retChar, "FAILED_TO_RUN");
}
this->Makefile->AddCacheDefinition(this->RunResultVariable.c_str(), retChar,
"Result of TRY_RUN",
cmCacheManager::INTERNAL);
}
/* This is only used when cross compiling. Instead of running the
executable, two cache variables are created which will hold the results
the executable would have produced.
*/
void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
const std::string& srcFile,
std::string* out
)
{
// copy the executable out of the CMakeFiles/ directory, so it is not
// removed at the end of TRY_RUN and the user can run it manually
// on the target platform.
std::string copyDest = this->Makefile->GetHomeOutputDirectory();
copyDest += cmake::GetCMakeFilesDirectory();
copyDest += "/";
copyDest += cmSystemTools::GetFilenameWithoutExtension(
this->OutputFile.c_str());
copyDest += "-";
copyDest += this->RunResultVariable;
copyDest += cmSystemTools::GetFilenameExtension(this->OutputFile.c_str());
cmSystemTools::CopyFileAlways(this->OutputFile.c_str(), copyDest.c_str());
std::string resultFileName = this->Makefile->GetHomeOutputDirectory();
resultFileName += "/TryRunResults.cmake";
std::string detailsString = "For details see ";
detailsString += resultFileName;
std::string internalRunOutputName=this->RunResultVariable+"__TRYRUN_OUTPUT";
bool error = false;
if (this->Makefile->GetDefinition(this->RunResultVariable.c_str()) == 0)
{
// if the variables doesn't exist, create it with a helpful error text
// and mark it as advanced
std::string comment;
comment += "Run result of TRY_RUN(), indicates whether the executable "
"would have been able to run on its target platform.\n";
comment += detailsString;
this->Makefile->AddCacheDefinition(this->RunResultVariable.c_str(),
"PLEASE_FILL_OUT-FAILED_TO_RUN",
comment.c_str(),
cmCacheManager::STRING);
cmCacheManager::CacheIterator it = this->Makefile->GetCacheManager()->
GetCacheIterator(this->RunResultVariable.c_str());
if ( !it.IsAtEnd() )
{
it.SetProperty("ADVANCED", "1");
}
error = true;
}
// is the output from the executable used ?
if (out!=0)
{
if (this->Makefile->GetDefinition(internalRunOutputName.c_str()) == 0)
{
// if the variables doesn't exist, create it with a helpful error text
// and mark it as advanced
std::string comment;
comment+="Output of TRY_RUN(), contains the text, which the executable "
"would have printed on stdout and stderr on its target platform.\n";
comment += detailsString;
this->Makefile->AddCacheDefinition(internalRunOutputName.c_str(),
"PLEASE_FILL_OUT-NOTFOUND",
comment.c_str(),
cmCacheManager::STRING);
cmCacheManager::CacheIterator it = this->Makefile->GetCacheManager()->
GetCacheIterator(internalRunOutputName.c_str());
if ( !it.IsAtEnd() )
{
it.SetProperty("ADVANCED", "1");
}
error = true;
}
}
if (error)
{
static bool firstTryRun = true;
std::ofstream file(resultFileName.c_str(),
firstTryRun ? std::ios::out : std::ios::app);
if ( file )
{
if (firstTryRun)
{
file << "# This file was generated by CMake because it detected "
"TRY_RUN() commands\n"
"# in crosscompiling mode. It will be overwritten by the next "
"CMake run.\n"
"# Copy it to a safe location, set the variables to "
"appropriate values\n"
"# and use it then to preset the CMake cache (using -C).\n\n";
}
std::string comment ="\n";
comment += this->RunResultVariable;
comment += "\n indicates whether the executable would have been able "
"to run on its\n"
" target platform. If so, set ";
comment += this->RunResultVariable;
comment += " to\n"
" the exit code (in many cases 0 for success), otherwise "
"enter \"FAILED_TO_RUN\".\n";
if (out!=0)
{
comment += internalRunOutputName;
comment += "\n contains the text the executable "
"would have printed on stdout and stderr.\n"
" If the executable would not have been able to run, set ";
comment += internalRunOutputName;
comment += " empty.\n"
" Otherwise check if the output is evaluated by the "
"calling CMake code. If so,\n"
" check what the source file would have printed when "
"called with the given arguments.\n";
}
comment += "The ";
comment += this->CompileResultVariable;
comment += " variable holds the build result for this TRY_RUN().\n\n"
"Source file : ";
comment += srcFile + "\n";
comment += "Executable : ";
comment += copyDest + "\n";
comment += "Run arguments : ";
comment += runArgs;
comment += "\n";
comment += " Called from: " + this->Makefile->GetListFileStack();
cmsys::SystemTools::ReplaceString(comment, "\n", "\n# ");
file << comment << "\n\n";
file << "SET( " << this->RunResultVariable << " \n \""
<< this->Makefile->GetDefinition(this->RunResultVariable.c_str())
<< "\"\n CACHE STRING \"Result from TRY_RUN\" FORCE)\n\n";
if (out!=0)
{
file << "SET( " << internalRunOutputName << " \n \""
<< this->Makefile->GetDefinition(internalRunOutputName.c_str())
<< "\"\n CACHE STRING \"Output from TRY_RUN\" FORCE)\n\n";
}
file.close();
}
firstTryRun = false;
std::string errorMessage = "TRY_RUN() invoked in cross-compiling mode, "
"please set the following cache variables "
"appropriately:\n";
errorMessage += " " + this->RunResultVariable + " (advanced)\n";
if (out!=0)
{
errorMessage += " " + internalRunOutputName + " (advanced)\n";
}
errorMessage += detailsString;
cmSystemTools::Error(errorMessage.c_str());
return;
}
if (out!=0)
{
(*out) = this->Makefile->GetDefinition(internalRunOutputName.c_str());
}
}
| 33.778351 | 79 | 0.560659 | [
"vector"
] |
4fc24d5ac55e6c111116726eeb8566e6192dee3e | 12,929 | cpp | C++ | src/plua.cpp | yszf/pLua | 5b4c06f53c50e6787bcf59560b8dabb67b383897 | [
"MIT"
] | null | null | null | src/plua.cpp | yszf/pLua | 5b4c06f53c50e6787bcf59560b8dabb67b383897 | [
"MIT"
] | null | null | null | src/plua.cpp | yszf/pLua | 5b4c06f53c50e6787bcf59560b8dabb67b383897 | [
"MIT"
] | null | null | null | #include <string>
#include <list>
#include <vector>
#include <map>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <typeinfo>
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <unordered_map>
#include <fcntl.h>
#include <sstream>
#include <algorithm>
#include <vector>
#include <unordered_set>
#include <set>
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int open_debug = 0;
int gsamplecount;
std::string gfilename;
lua_State *gL;
int grunning = 0;
#define LLOG(...) if (open_debug) {llog("[DEBUG] ", __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__);}
#define LERR(...) if (open_debug) {llog("[ERROR] ", __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__);}
void llog(const char *header, const char *file, const char *func, int pos, const char *fmt, ...) {
FILE *pLog = NULL;
time_t clock1;
struct tm *tptr;
va_list ap;
pLog = fopen("plua.log", "a+");
if (pLog == NULL) {
return;
}
clock1 = time(0);
tptr = localtime(&clock1);
struct timeval tv;
gettimeofday(&tv, NULL);
fprintf(pLog, "===========================[%d.%d.%d, %d.%d.%d %llu]%s:%d,%s:===========================\n%s",
tptr->tm_year + 1990, tptr->tm_mon + 1,
tptr->tm_mday, tptr->tm_hour, tptr->tm_min,
tptr->tm_sec, (long long) ((tv.tv_sec) * 1000 + (tv.tv_usec) / 1000), file, pos, func, header);
va_start(ap, fmt);
vfprintf(pLog, fmt, ap);
fprintf(pLog, "\n\n");
va_end(ap);
va_start(ap, fmt);
vprintf(fmt, ap);
printf("\n\n");
va_end(ap);
fclose(pLog);
}
static const int MAX_FUNC_NAME_SIZE = 127;
/////////////////////////////copy from lua start///////////////////////////////////////////////
/*
** search for 'objidx' in table at index -1.
** return 1 + string at top if find a good name.
*/
static int findfield(lua_State *L, int objidx, int level) {
if (level == 0 || !lua_istable(L, -1))
return 0; /* not found */
lua_pushnil(L); /* start 'next' loop */
while (lua_next(L, -2)) { /* for each pair in table */
if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
if (lua_rawequal(L, objidx, -1)) { /* found object? */
lua_pop(L, 1); /* remove value (but keep name) */
return 1;
} else if (findfield(L, objidx, level - 1)) { /* try recursively */
lua_remove(L, -2); /* remove table (but keep name) */
lua_pushliteral(L, ".");
lua_insert(L, -2); /* place '.' between the two names */
lua_concat(L, 3);
return 1;
}
}
lua_pop(L, 1); /* remove value */
}
return 0; /* not found */
}
/*
** Search for a name for a function in all loaded modules
*/
static int pushglobalfuncname(lua_State *L, lua_Debug *ar) {
int top = lua_gettop(L);
lua_getinfo(L, "f", ar); /* push function */
lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
if (findfield(L, top + 1, 2)) {
const char *name = lua_tostring(L, -1);
if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */
lua_pushstring(L, name + 3); /* push name without prefix */
lua_remove(L, -2); /* remove original name */
}
lua_copy(L, -1, top + 1); /* move name to proper place */
lua_pop(L, 2); /* remove pushed values */
return 1;
} else {
lua_settop(L, top); /* remove function and global table */
return 0;
}
}
static void pushfuncname(lua_State *L, lua_Debug *ar) {
if (pushglobalfuncname(L, ar)) { /* try first a global name */
lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
lua_remove(L, -2); /* remove name */
} else if (*ar->namewhat != '\0') /* is there a name from code? */
lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
else if (*ar->what == 'm') /* main? */
lua_pushliteral(L, "main chunk");
else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
else /* nothing left... */
lua_pushliteral(L, "?");
}
static int lastlevel(lua_State *L) {
lua_Debug ar;
int li = 1, le = 1;
/* find the bottom index of the call stack. */
while (lua_getstack(L, le, &ar)) {
li = le;
le *= 2;
}
/* do a binary search */
while (li < le) {
int m = (li + le) / 2;
if (lua_getstack(L, m, &ar)) li = m + 1;
else le = m;
}
return le - 1;
}
/////////////////////////////copy from lua end///////////////////////////////////////////////
std::unordered_map<std::string, int> gString2Id;
std::unordered_map<int, std::string> gId2String;
static const char *IGNORE_NAME[] = {"?", "function 'xpcall'", "function 'pcall'", "function", "function 'tcall'",
"function 'txpcall'", "local 'func'"};
static const int VALID_MIN_ID = sizeof(IGNORE_NAME) / sizeof(const char *);
static const int MAX_STACK_SIZE = 64;
static const int MAX_CALL_STACK_SIZE = 4;
static const int MAX_BUCKET_SIZE = 1 << 10;
static const int MAX_CALL_STACK_SAVE_SIZE = 1 << 18;
struct CallStack {
int count;
int depth;
int stack[MAX_STACK_SIZE];
};
struct Bucket {
CallStack cs[MAX_CALL_STACK_SIZE];
};
struct ProfileData {
Bucket bucket[MAX_BUCKET_SIZE];
int total;
};
int gfd;
ProfileData gProfileData;
CallStack gCallStackSaved[MAX_CALL_STACK_SAVE_SIZE];
int gCallStackSavedSize = 0;
static void flush_file(int fd, const char *buf, size_t len) {
while (len > 0) {
ssize_t r = write(fd, buf, len);
buf += r;
len -= r;
}
}
static void flush_callstack() {
LLOG("flush_callstack");
flush_file(gfd, (const char *) gCallStackSaved, sizeof(CallStack) * gCallStackSavedSize);
gCallStackSavedSize = 0;
}
static void save_callstack(CallStack *pcs) {
LLOG("save_callstack");
if (gCallStackSavedSize >= MAX_CALL_STACK_SAVE_SIZE) {
flush_callstack();
}
gCallStackSaved[gCallStackSavedSize] = *pcs;
gCallStackSavedSize++;
}
static void flush() {
if (gProfileData.total <= 0) {
return;
}
LLOG("flush...");
int total = 0;
for (int b = 0; b < MAX_BUCKET_SIZE; b++) {
Bucket *bucket = &gProfileData.bucket[b];
for (int a = 0; a < MAX_CALL_STACK_SIZE; a++) {
if (bucket->cs[a].count > 0) {
save_callstack(&bucket->cs[a]);
bucket->cs[a].depth = 0;
bucket->cs[a].count = 0;
total++;
}
}
}
flush_callstack();
int total_len = 0;
for (auto iter = gString2Id.begin(); iter != gString2Id.end(); iter++) {
const std::string &str = iter->first;
int id = iter->second;
if (id < VALID_MIN_ID) {
continue;
}
int len = str.length();
len = len > MAX_FUNC_NAME_SIZE ? MAX_FUNC_NAME_SIZE : len;
flush_file(gfd, str.c_str(), len);
flush_file(gfd, (const char *) &len, sizeof(len));
flush_file(gfd, (const char *) &id, sizeof(id));
total_len++;
}
flush_file(gfd, (const char *) &total_len, sizeof(total_len));
LLOG("flush ok %d %d", total, gProfileData.total);
gProfileData.total = 0;
if (gfd != 0) {
close(gfd);
gfd = 0;
}
printf("pLua flush ok\n");
}
extern "C" int lrealstop(lua_State *L) {
lua_sethook(L, 0, 0, 0);
grunning = 0;
struct itimerval timer;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
timer.it_value = timer.it_interval;
int ret = setitimer(ITIMER_PROF, &timer, NULL);
if (ret != 0) {
LERR("setitimer fail %d", ret);
return ret;
}
flush();
return 0;
}
static void SignalHandlerHook(lua_State *L, lua_Debug *par) {
LLOG("Hook...");
lua_sethook(gL, 0, 0, 0);
if (gsamplecount != 0 && gsamplecount <= gProfileData.total) {
LLOG("lrealstop...");
lrealstop(L);
return;
}
gProfileData.total++;
lua_Debug ar;
int last = lastlevel(L);
int i = 0;
CallStack cs;
cs.depth = 0;
while (lua_getstack(L, last, &ar) && i < MAX_STACK_SIZE) {
lua_getinfo(L, "Slnt", &ar);
pushfuncname(L, &ar);
const char *funcname = lua_tostring(L, -1);
lua_pop(L, 1);
i++;
last--;
int id = 0;
auto iter = gString2Id.find(funcname);
if (iter == gString2Id.end()) {
id = gString2Id.size();
gString2Id[funcname] = id;
gId2String[id] = funcname;
} else {
id = iter->second;
}
if (id < VALID_MIN_ID) {
continue;
}
LLOG("%s %d %d", funcname, id, last);
cs.stack[cs.depth] = id;
cs.depth++;
}
int hash = 0;
for (int i = 0; i < cs.depth; i++) {
int id = cs.stack[i];
hash = (hash << 8) | (hash >> (8 * (sizeof(hash) - 1)));
hash += (id * 31) + (id * 7) + (id * 3);
}
LLOG("hash %d", hash);
bool done = false;
Bucket *bucket = &gProfileData.bucket[(uint32_t) hash % MAX_BUCKET_SIZE];
for (int a = 0; a < MAX_CALL_STACK_SIZE; a++) {
CallStack *pcs = &bucket->cs[a];
if (pcs->depth == 0 && pcs->count == 0) {
pcs->depth = cs.depth;
pcs->count = 1;
memcpy(pcs->stack, cs.stack, sizeof(int) * cs.depth);
done = true;
LLOG("hash %d add first %d %d", hash, pcs->count, pcs->depth);
break;
} else if (pcs->depth == cs.depth) {
if (memcmp(pcs->stack, cs.stack, sizeof(int) * cs.depth) != 0) {
break;
} else {
pcs->count++;
done = true;
LLOG("hash %d add %d %d", hash, pcs->count, pcs->depth);
break;
}
}
}
if (!done) {
CallStack *pcs = &bucket->cs[0];
for (int a = 1; a < MAX_CALL_STACK_SIZE; a++) {
if (bucket->cs[a].count < pcs->count) {
pcs = &bucket->cs[a];
}
}
if (pcs->count > 0) {
save_callstack(pcs);
}
// Use the newly evicted entry
pcs->depth = cs.depth;
pcs->count = 1;
memcpy(pcs->stack, cs.stack, sizeof(int) * cs.depth);
LLOG("hash %d add new %d %d", hash, pcs->count, pcs->depth);
}
}
static void SignalHandler(int sig, siginfo_t *sinfo, void *ucontext) {
lua_sethook(gL, SignalHandlerHook, LUA_MASKCOUNT, 1);
}
extern "C" int lrealstart(lua_State *L, int second, const char *file) {
if (grunning) {
LERR("start again, failed");
return -1;
}
grunning = 1;
for (int i = 0; i < VALID_MIN_ID; i++) {
gString2Id[IGNORE_NAME[i]] = i;
gId2String[i] = IGNORE_NAME[i];
}
const int iter = 10;
gsamplecount = second * 1000 / iter;
gfilename = file;
gL = L;
LLOG("lstart %u %s", gsamplecount, file);
struct sigaction sa;
sa.sa_sigaction = SignalHandler;
sa.sa_flags = SA_RESTART | SA_SIGINFO;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGPROF, &sa, NULL) == -1) {
LERR("sigaction(SIGALRM) failed");
return -1;
}
struct itimerval timer;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = iter * 1000;
timer.it_value = timer.it_interval;
int ret = setitimer(ITIMER_PROF, &timer, NULL);
if (ret != 0) {
LERR("setitimer fail %d", ret);
return -1;
}
memset(&gProfileData, 0, sizeof(gProfileData));
memset(&gCallStackSaved, 0, sizeof(gCallStackSaved));
memset(&gCallStackSavedSize, 0, sizeof(gCallStackSavedSize));
int fd = open(file, O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fd < 0) {
LERR("open file fail %s", file);
return -1;
}
gfd = fd;
return 0;
}
static int lstart(lua_State *L) {
int second = (int) lua_tointeger(L, 1);
const char *file = lua_tostring(L, 2);
int ret = lrealstart(L, second, file);
lua_pushinteger(L, ret);
return 1;
}
static int lstop(lua_State *L) {
LLOG("lstop %s", gfilename.c_str());
int ret = lrealstop(L);
lua_pushinteger(L, ret);
return 1;
}
extern "C" int luaopen_libplua(lua_State *L) {
luaL_checkversion(L);
luaL_Reg l[] = {
{"start", lstart},
{"stop", lstop},
{NULL, NULL},
};
luaL_newlib(L, l);
return 1;
}
| 26.066532 | 113 | 0.543894 | [
"object",
"vector"
] |
4fc2b55a832c5dcecff3f73e894afda0a08ae046 | 2,233 | cpp | C++ | SketchUpNET/Vector.cpp | moethu/SketchUpSharp | eed3cd9a734ec6a3ed66a28a9f85d1d1d6b325e0 | [
"MIT"
] | 1 | 2015-11-05T20:54:25.000Z | 2015-11-05T20:54:25.000Z | SketchUpNET/Vector.cpp | moethu/SketchUpSharp | eed3cd9a734ec6a3ed66a28a9f85d1d1d6b325e0 | [
"MIT"
] | 1 | 2015-11-05T09:55:22.000Z | 2015-11-05T09:55:22.000Z | SketchUpNET/Vector.cpp | moethu/SketchUpSharp | eed3cd9a734ec6a3ed66a28a9f85d1d1d6b325e0 | [
"MIT"
] | null | null | null | /*
SketchUpNET - a C++ Wrapper for the Trimble(R) SketchUp(R) C API
Copyright(C) 2015, Autor: Maximilian Thumfart
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <SketchUpAPI/slapi.h>
#include <SketchUpAPI/geometry.h>
#include <SketchUpAPI/initialize.h>
#include <SketchUpAPI/unicodestring.h>
#include <SketchUpAPI/model/model.h>
#include <SketchUpAPI/model/entities.h>
#include <SketchUpAPI/model/face.h>
#include <SketchUpAPI/model/edge.h>
#include <SketchUpAPI/model/vertex.h>
#include <msclr/marshal.h>
#include <vector>
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
namespace SketchUpNET
{
public ref class Vector
{
public:
double X;
double Y;
double Z;
/// <summary>
/// Creates a new vector
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
Vector(double x, double y, double z)
{
this->X = x;
this->Y = y;
this->Z = z;
};
Vector(){};
internal:
static Vector^ FromSU(SUVector3D vec)
{
Vector^ v = gcnew Vector(vec.x, vec.y, vec.z);
return v;
};
SUVector3D ToSU()
{
SUVector3D point = { this->X, this->Y, this->Z };
return point;
}
};
} | 27.567901 | 126 | 0.728168 | [
"geometry",
"vector",
"model"
] |
4fc98cf8fd1ae2969ba7353a84f8d629cc0256e9 | 184 | cpp | C++ | Greedy/Highest Product.cpp | torquecoder/InterviewBit-Solutions | 7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2 | [
"MIT"
] | null | null | null | Greedy/Highest Product.cpp | torquecoder/InterviewBit-Solutions | 7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2 | [
"MIT"
] | null | null | null | Greedy/Highest Product.cpp | torquecoder/InterviewBit-Solutions | 7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2 | [
"MIT"
] | null | null | null | int Solution::maxp3(vector<int> &A) {
sort(A.begin(), A.end());
int n = A.size();
int ans = max(A[n - 1] * A[n - 2] * A[n - 3], A[0] * A[1] * A[n - 1]);
return ans;
}
| 23 | 74 | 0.451087 | [
"vector"
] |
4fc9cbb9f87e3de7d4fa4377cccc02248f819ded | 32,135 | cpp | C++ | UIAddressBook/AddressBookPanel.cpp | qunarcorp/startalk_pc_v2 | 59d873ddcd41052d9a1379a9c35cb69075fcef3c | [
"MIT"
] | 30 | 2019-08-22T08:33:23.000Z | 2022-03-15T02:04:20.000Z | UIAddressBook/AddressBookPanel.cpp | lirui1111/startalk_pc | 7d625f812e784bca68b3d6f6ffe21d383b400491 | [
"MIT"
] | 4 | 2019-12-11T08:18:55.000Z | 2021-03-19T07:23:50.000Z | UIAddressBook/AddressBookPanel.cpp | lirui1111/startalk_pc | 7d625f812e784bca68b3d6f6ffe21d383b400491 | [
"MIT"
] | 19 | 2019-08-22T17:09:24.000Z | 2021-08-10T08:24:39.000Z | #include <memory>
#include "AddressBookPanel.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <thread>
#include <QDebug>
#include <QHeaderView>
#include <QApplication>
#include <QFileInfo>
#include "ListItemView.h"
#include "MessageManager.h"
#include "../Platform/Platform.h"
#include "../QtUtil/Utils/Log.h"
#include "../QtUtil/Utils/utils.h"
#include "../Platform/dbPlatForm.h"
AddressBookPanel::AddressBookPanel(QWidget *parent)
: QWidget(parent), _mainSplitter(nullptr), _pEmptyLabel(nullptr), _pUserCard(nullptr), _pstStrcuture(nullptr) {
initUi();
_pMsgManager = new AddressBookMsgManager;
_pMsgListener = new AddressBookListener(this);
//
connect(this, &AddressBookPanel::updateUiSignal, this, &AddressBookPanel::updateUi);
initStaff();
updateStaffUi();
getStructure();
}
AddressBookPanel::~AddressBookPanel() {
}
//
void AddressBookPanel::initUi() {
setObjectName("AddressBookPanel");
_mainSplitter = new QSplitter(this);
// left frame
QFrame *leftFrame = new QFrame(_mainSplitter);
leftFrame->setObjectName("AddressBookLeftFrm");
leftFrame->setMinimumWidth(260);
_leftLay = new QVBoxLayout(leftFrame);
_leftLay->setContentsMargins(0, 10, 0, 0);
_leftLay->setSpacing(0);
_mapNavItems[EM_ITEM_TYPE_START] = new NavigationItem(EM_ITEM_TYPE_START, this);
_mapNavItems[EM_ITEM_TYPE_FRIENDLIST] = new NavigationItem(EM_ITEM_TYPE_FRIENDLIST, this);
_mapNavItems[EM_ITEM_TYPE_GROUPLIST] = new NavigationItem(EM_ITEM_TYPE_GROUPLIST, this);
_mapNavItems[EM_ITEM_TYPE_STAFF] = new NavigationItem(EM_ITEM_TYPE_STAFF, this);
// _mapNavItems[EM_ITEM_TYPE_SUBSCRIPTION] = new NavigationItem(EM_ITEM_TYPE_SUBSCRIPTION, this);
_mapNavItems[EM_ITEM_TYPE_BLACKLIST] = new NavigationItem(EM_ITEM_TYPE_BLACKLIST, this);
_pStaffView = new QTreeView(this);
_pStaffView->setObjectName("StaffView");
_pStaffDelegate = new StaffDelegate(this);
_pStaffView->setEditTriggers(QAbstractItemView::NoEditTriggers);
_pStaffView->header()->setVisible(false);
_pStaffView->setItemDelegate(_pStaffDelegate);
_pStaffView->setFrameShape(QFrame::NoFrame);
_mapItemWidgets[EM_ITEM_TYPE_START] = new ListItemView(this, leftFrame);
_mapItemWidgets[EM_ITEM_TYPE_FRIENDLIST] = new ListItemView(this, leftFrame);
_mapItemWidgets[EM_ITEM_TYPE_GROUPLIST] = new ListItemView(this, leftFrame);
_mapItemWidgets[EM_ITEM_TYPE_BLACKLIST] = new ListItemView(this, leftFrame);
_mapItemWidgets[EM_ITEM_TYPE_STAFF] = _pStaffView;
dealNavItem(_leftLay);
_leftLay->addItem(new QSpacerItem(10, 10, QSizePolicy::Fixed, QSizePolicy::Expanding));
// right frame
QFrame *rightFrm = new QFrame(_mainSplitter);
rightFrm->setObjectName("AddressBookRightFrm");
_rightLay = new QStackedLayout(rightFrm);
_pEmptyLabel = new QLabel(this);
_pEmptyLabel->setObjectName("EmptyLabel");
_pEmptyLabel->setPixmap(QPixmap(QString(":/addressbook/image1/Artboard_%1.png").arg(AppSetting::instance().getThemeMode())));
_pEmptyLabel->setAlignment(Qt::AlignCenter);
_rightLay->addWidget(_pEmptyLabel);
// main layout
_mainSplitter->addWidget(leftFrame);
_mainSplitter->addWidget(rightFrm);
_mainSplitter->setHandleWidth(1);
_mainSplitter->setStretchFactor(1, 1);
_mainSplitter->setCollapsible(0, false);
_mainSplitter->setCollapsible(1, false);
auto *layout = new QHBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(_mainSplitter);
connect(_pStaffDelegate, &StaffDelegate::itemClicked, this, &AddressBookPanel::onStaffItemClicked);
}
/**
*
* @param sto
* @param index
* @return
*/
QString getStrName(QStringList sto, int index) {
QString ret = "";
if (index <= 0 || index >= sto.size())
return ret;
for (int i = 1; i <= index; i++) {
ret += "/" + sto[i];
}
return ret;
}
/**
* 初始化组织架构
*/
void AddressBookPanel::initStaff() {
if (nullptr == _pMsgManager) return;
//
_pStaffStructure = new StaffStructure(this);
_rightLay->addWidget(_pStaffStructure);
_pStaffModel = new QStandardItemModel;
connect(_pStaffStructure, &StaffStructure::creatGroupSignal, this, &AddressBookPanel::creatGroup);
// connect(this, &AddressBookPanel::updateStaffUiSinal, this, &AddressBookPanel::updateStaffUi);
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/22
*/
void AddressBookPanel::updateStaffUi() {
_pStaffView->setModel(_pStaffModel);
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/16
*/
void AddressBookPanel::onNavItemClicked(QUInt8 type)
{
static QUInt8 old_type = EM_ITEM_TYPE_EMPTY;
if(type == old_type)
{
auto item = _mapNavItems[type];
_mapNavItems[type]->setSelectState(!item->getItemWgt()->isVisible());
}
else
{
old_type = type;
for(const auto item : _mapNavItems) {
bool isSelectItem = item->getItemType() == type;
auto *lstView = qobject_cast<ListItemView *>(item->getItemWgt());
if (isSelectItem) {
if (lstView)
{
#ifdef _STARTALK
switch (type)
{
case EM_ITEM_TYPE_START:
_pEmptyLabel->setPixmap(QPixmap(":/addressbook/image1/star_default.png"));
break;
case EM_ITEM_TYPE_FRIENDLIST:
_pEmptyLabel->setPixmap(QPixmap(":/addressbook/image1/friend_default.png"));
break;
case EM_ITEM_TYPE_GROUPLIST:
_pEmptyLabel->setPixmap(QPixmap(":/addressbook/image1/group_default.png"));
break;
case EM_ITEM_TYPE_BLACKLIST:
_pEmptyLabel->setPixmap(QPixmap(":/addressbook/image1/balck_list_default.png"));
break;
default:
break;
}
#endif
lstView->resetHeight(this->height(), getFixedHeight());
}
else if (item->getItemWgt() == _pStaffView)
{
emit sgOpeartor(tr("组织架构"));
#ifdef _STARTALK
_pEmptyLabel->setPixmap(QPixmap(":/addressbook/image1/staff_default.png"));
#endif
_pStaffView->setFixedHeight(this->height() - getFixedHeight());
}
#ifndef _STARTALK
_pEmptyLabel->setPixmap(QPixmap(QString(":/addressbook/image1/Artboard_%1.png").arg(AppSetting::instance().getThemeMode())));
#endif
} else {
if (lstView)
lstView->clearSelection();
}
item->setSelectState(isSelectItem);
}
}
_rightLay->setCurrentWidget(_pEmptyLabel);
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/16
*/
void AddressBookPanel::updateUserConfig(const std::vector<QTalk::Entity::ImConfig> &arConfigs) {
QVector<std::string> oldStarContact = _arStarContact;
QVector<std::string> oldBlackList = _arBlackList;
_arStarContact.clear();
_arBlackList.clear();
_mapMaskNames.clear();
auto it = arConfigs.begin();
for (; it != arConfigs.end(); it++) {
std::string subKey = it->ConfigSubKey;
if (it->ConfigKey == "kStarContact") {
if (oldStarContact.contains(subKey))
oldStarContact.removeOne(subKey);
//
_arStarContact.push_back(subKey);
} else if (it->ConfigKey == "kBlackList") {
if (oldBlackList.contains(subKey))
oldBlackList.removeOne(subKey);
//
_arBlackList.push_back(subKey);
} else if (it->ConfigKey == "kMarkupNames") {
_mapMaskNames[subKey] = it->ConfigValue;
}
}
//
addItemByType(EM_ITEM_TYPE_START, _arStarContact);
addItemByType(EM_ITEM_TYPE_BLACKLIST, _arBlackList);
removeItemByType(EM_ITEM_TYPE_START, oldStarContact);
removeItemByType(EM_ITEM_TYPE_BLACKLIST, oldBlackList);
}
void AddressBookPanel::updateUserConfig(const std::map<std::string, std::string> &deleteData,
const std::vector<QTalk::Entity::ImConfig>& arImConfig) {
{
QVector<std::string> delStarContact;
QVector<std::string> delBlackList;
for(const auto& it : deleteData)
{
if (it.second == "kStarContact") {
delStarContact.push_back(it.first);
} else if (it.second == "kBlackList") {
delBlackList.push_back(it.first);
} else if (it.second == "kMarkupNames") {
if (_mapMaskNames.contains(it.first))
_mapMaskNames.remove(it.first);
}
}
if(!delStarContact.empty())
removeItemByType(EM_ITEM_TYPE_START, delStarContact);
if(delBlackList.empty())
removeItemByType(EM_ITEM_TYPE_BLACKLIST, delBlackList);
}
//
{
QVector<std::string> addStarContact;
QVector<std::string> addBlackList;
for(const auto& it : arImConfig)
{
if (it.ConfigKey == "kStarContact") {
addStarContact.push_back(it.ConfigSubKey);
} else if (it.ConfigKey == "kBlackList") {
addBlackList.push_back(it.ConfigSubKey);
} else if (it.ConfigKey == "kMarkupNames") {
_mapMaskNames[it.ConfigSubKey] = it.ConfigValue;
}
}
if(!addStarContact.empty())
addItemByType(EM_ITEM_TYPE_START, addStarContact);
if(addBlackList.empty())
addItemByType(EM_ITEM_TYPE_BLACKLIST, addBlackList);
}
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/16
*/
void AddressBookPanel::dealNavItem(QVBoxLayout *layout) {
for(NavigationItem *item : _mapNavItems)
{
if (nullptr == item) continue;
layout->addWidget(item);
QWidget *wgt = _mapItemWidgets.value(item->getItemType());
if (wgt) {
wgt->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
item->registerWgt(wgt);
layout->addWidget(wgt);
wgt->setVisible(false);
}
connect(item, &NavigationItem::itemClicked, this, &AddressBookPanel::onNavItemClicked);
}
}
//
void AddressBookPanel::addItemByType(QUInt8 type, const QVector<std::string> &users) {
auto func = [this, type, users]() {
#ifdef _MACOS
pthread_setname_np("AddressBookPanel::addItemByType");
#endif
QMutexLocker locker(&_mutex);
ListItemView *listview = (ListItemView *) _mapItemWidgets.value(type);
if (nullptr != listview) {
for (const std::string& id : users) {
std::shared_ptr<QTalk::Entity::ImUserInfo> userInfo = dbPlatForm::instance().getUserInfo(id);
if(nullptr == userInfo)
{
userInfo = std::make_shared<QTalk::Entity::ImUserInfo>();
userInfo->XmppId = id;
_pMsgManager->getUserInfo(userInfo);
}
if (nullptr != userInfo) {
#ifdef _STARTALK
QString defaltHead = ":/QTalk/image1/StarTalk_defaultHead.png";
#else
QString defaltHead = ":/QTalk/image1/headPortrait.png";
#endif
QString iconPath = userInfo->HeaderSrc.empty() ? defaltHead :
QString::fromStdString(QTalk::GetHeadPathByUrl(userInfo->HeaderSrc));
listview->addItem(QString::fromStdString(id), EM_TYPE_USER, iconPath,
QString::fromStdString(QTalk::getUserName(userInfo)));
}
}
}
};
std::thread t(func);
t.detach();
}
/**
*
* @param type
* @param users
*/
void AddressBookPanel::removeItemByType(QUInt8 type, const QVector<std::string> &users) {
auto func = [this, type, users]() {
QMutexLocker locker(&_mutex);
ListItemView *listview = (ListItemView *) _mapItemWidgets.value(type);
if (nullptr != listview) {
for (std::string id : users) {
listview->removeItem(QString::fromStdString(id));
}
}
};
std::thread t(func);
t.detach();
}
/**
*
* @param friends
*/
void AddressBookPanel::onRecvFriends(const std::vector<QTalk::Entity::IMFriendList> &friends) {
for (const QTalk::Entity::IMFriendList &imfriend : friends) {
_arFriends.push_back(imfriend.XmppId);
}
addItemByType(EM_ITEM_TYPE_FRIENDLIST, _arFriends);
}
/**
*
* @param groups
*/
void AddressBookPanel::onRecvGroups(const std::vector<QTalk::Entity::ImGroupInfo> &groups) {
//_arGroups.fromStdVector(groups);
std::thread t([this, groups]() {
#ifdef _MACOS
pthread_setname_np("AddressBookPanel::onRecvGroups");
#endif
QMutexLocker locker(&_mutex);
ListItemView *blkListview = (ListItemView *) _mapItemWidgets.value(EM_ITEM_TYPE_GROUPLIST);
if (nullptr == blkListview) return;
for (const QTalk::Entity::ImGroupInfo &group : groups) {
_arGroups.push_back(group);
#ifdef _STARTALK
QString defaultGroupHead = ":/QTalk/image1/StarTalk_defaultGroup.png";
#else
QString defaultGroupHead = ":/QTalk/image1/defaultGroupHead.png";
#endif
QString iconPath = group.HeaderSrc.empty() ? defaultGroupHead :
QString::fromStdString(QTalk::GetHeadPathByUrl(group.HeaderSrc));
if (!QFile::exists(iconPath) || QFileInfo(iconPath).isDir())
{
iconPath = defaultGroupHead;
}
blkListview->addItem(QString::fromStdString(group.GroupId), EM_TYPE_GROUP, iconPath,
QString::fromStdString(group.Name));
}
});
t.detach();
}
/**
*
* @return
*/
int AddressBookPanel::getFixedHeight() {
return _mapNavItems.size() * 50 + 10;
}
/**
*
* @param id
* @param type
*/
void AddressBookPanel::onListItemClicked(const QString &id, const QUInt8 &type) {
// type
switch (type) {
case EM_TYPE_USER: {
showUserCard(id);
break;
}
case EM_TYPE_GROUP:
{
StSessionInfo stSession(QTalk::Enum::GroupChat, id, "");
emit sgSwitchCurFun(0);
emit sgOpenNewSession(stSession);
break;
}
default:break;
}
}
/**
*
* @param id 用户xmppid
*/
void AddressBookPanel::showUserCard(const QString &id) {
if (_pMsgManager) {
_imuserSup = std::make_shared<QTalk::Entity::ImUserSupplement>();
_userInfo = std::make_shared<QTalk::Entity::ImUserInfo>();
_userInfo->XmppId = id.toStdString();
_imuserSup->XmppId = id.toStdString();
_pMsgManager->getUserCard(_imuserSup, _userInfo);
if (nullptr == _imuserSup)
return;
if (nullptr == _pUserCard) {
_pUserCard = new UserCard(this);
}
_rightLay->addWidget(_pUserCard);
_pUserCard->showUserCard(_imuserSup, _userInfo);
int flags = _arStarContact.contains(_imuserSup->XmppId);
flags |= _arBlackList.contains(_imuserSup->XmppId) << 1;
flags |= _arFriends.contains(_imuserSup->XmppId) << 2;
_pUserCard->setFlags(flags);
if (_mapMaskNames.contains(_imuserSup->XmppId)) {
_pUserCard->setMaskName(QString::fromStdString(_mapMaskNames[_imuserSup->XmppId]));
}
_rightLay->setCurrentWidget(_pUserCard);
}
}
/**
* 显示群
* @param id 群id
*/
void AddressBookPanel::showGroupCard(const QString &id) {
}
/**
*
* @param userId
*/
void AddressBookPanel::getPhoneNo(const std::string &userId) {
std::thread t([this, userId]() {
#ifdef _MACOS
pthread_setname_np("AddressBookPanel::getPhoneNo");
#endif
QMutexLocker locker(&_mutex);
if (nullptr != _pMsgManager) {
std::string phoneNo;
_pMsgManager->getUserPhoneNo(userId, phoneNo);
if (!phoneNo.empty()) {
emit gotPhoneNo(userId, phoneNo);
}
}
});
t.detach();
}
/**
* 星标联系人
* @param userId
*/
void AddressBookPanel::starUser(const std::string &userId) {
bool isStar = _arStarContact.contains(userId);
QString val = QString::number(isStar ? 0 : 1);
if (_pMsgManager) {
_pMsgManager->setUserSetting(isStar, "kStarContact", userId, val.toStdString());
}
_rightLay->setCurrentWidget(_pEmptyLabel);
}
void AddressBookPanel::addBlackList(const std::string &userId) {
bool isBlack = _arBlackList.contains(userId);
QString val = QString::number(isBlack ? 0 : 1);
if (_pMsgManager) {
_pMsgManager->setUserSetting(isBlack, "kBlackList", userId, val.toStdString());
}
_rightLay->setCurrentWidget(_pEmptyLabel);
}
/**
* 建群
* @param structure
* @param count
*/
void AddressBookPanel::creatGroup(const QString &structure, const QString &groupName) {
// 获取群成员
std::vector<std::string> arMembers;
_pMsgManager->getStructureMembers(structure.toStdString(), arMembers);
if (!arMembers.empty()) {
// 发送建群请求
QString groupId = QString("%1@conference.%2").arg(QTalk::utils::getMessageId().c_str()).
arg(Platform::instance().getSelfDomain().c_str());
groupId = groupId.replace("-", "");
mapGroupMembers[groupId.toStdString()] = arMembers;
//
QString realName = groupName;
if (realName.isEmpty()) {
realName = structure.mid(1);
}
_pMsgManager->creatGroup(groupId.toStdString(), realName.toStdString());
}
}
///**
// * @函数名 sysTreeData
// * @功能描述 同步数据
// * @参数
// void
// * @author cc
// * @date 2018/12/23
// */
//void AddressBookPanel::sysTreeData(void *model) {
// _pStaffModel = (QStandardItemModel *) model;
//}
void AddressBookPanel::onCreatGroupRet(const std::string &groupId) {
auto it = mapGroupMembers.find(groupId);
if (it != mapGroupMembers.end()) {
_pMsgManager->addGroupMember(*it, groupId);
mapGroupMembers.erase(it);
}
}
/**
*
*/
void AddressBookPanel::jumpToUserStructre(const QString &useId) {
//_mapItemWidgets[EM_ITEM_TYPE_STAFF];
#ifdef _STARTALK
if (_mapNavItems.contains(EM_ITEM_TYPE_STAFF) && _mapNavItems[EM_ITEM_TYPE_STAFF]) {
onNavItemClicked(EM_ITEM_TYPE_STAFF);
_mapNavItems[EM_ITEM_TYPE_STAFF]->setSelectState(true);
}
//
if (_mapItemWidgets.contains(EM_ITEM_TYPE_STAFF)) {
QWidget *wgt = _mapItemWidgets[EM_ITEM_TYPE_STAFF];
if (nullptr != wgt && wgt == _pStaffView && _pStaffModel) {
_pShowItem = nullptr;
_pStaffView->collapseAll();
//
int rowCount = _pStaffModel->rowCount();
for (int row = 0; row < rowCount; ++row) {
QStandardItem *tmpItem = _pStaffModel->item(row);
getShowItem(tmpItem, useId);
if (nullptr != _pShowItem) {
break;
}
}
if (nullptr != _pShowItem) {
parentShow(_pShowItem);
_pStaffView->scrollTo(_pShowItem->index(), QAbstractItemView::PositionAtTop);
onStaffItemClicked(_pShowItem->index());
_pStaffView->setCurrentIndex(_pShowItem->index());
}
}
}
#endif
}
/**
*
* @param parentItem
* @param userId
*/
void AddressBookPanel::getShowItem(QStandardItem *parentItem, const QString &userId) {
if (nullptr != _pShowItem) {
return;
}
int rowCount = parentItem->rowCount();
for (int row = 0; row < rowCount; row++) {
QStandardItem *tmpItem = parentItem->child(row, 0);
if (nullptr == tmpItem) continue;
//
if (tmpItem->rowCount() > 0) {
getShowItem(tmpItem, userId);
} else {
QString xmppId = tmpItem->data(EM_STAFF_DATATYPE_XMPPID).toString();
if (xmppId == userId) {
_pShowItem = tmpItem;
break;
}
}
}
}
void AddressBookPanel::parentShow(QStandardItem *item) {
QStandardItem *tmpItem(item);
QList<QStandardItem *> aritems;
while (tmpItem->parent() != nullptr) {
tmpItem = tmpItem->parent();
aritems.push_front(tmpItem);
}
for(QStandardItem *i : aritems) {
_pStaffView->expand(i->index());
}
}
void AddressBookPanel::onStaffItemClicked(const QModelIndex &index) {
QString xmppid = index.data(EM_STAFF_DATATYPE_XMPPID).toString();
bool hasChild = index.data(EM_STAFF_DATATYPE_HASCHILD).toBool();
if (hasChild) {
QString structureName = index.data(EM_STAFF_DATATYPE_STRUCTURE).toString();
QString text = index.data(EM_STAFF_DATATYPE_TEXT).toString();
if (_pMsgManager) {
int count = 0;
_pMsgManager->getStructureCount(QString("%1/%2").arg(structureName, text).toStdString(), count);
_pStaffStructure->setData(structureName, text, count);
_rightLay->setCurrentWidget(_pStaffStructure);
}
} else {
showUserCard(xmppid);
}
}
/**
*
*/
void AddressBookPanel::onJumpToStructre(const QString &strureName)
{
if (_mapNavItems.contains(EM_ITEM_TYPE_STAFF) && _mapNavItems[EM_ITEM_TYPE_STAFF]) {
onNavItemClicked(EM_ITEM_TYPE_STAFF);
_mapNavItems[EM_ITEM_TYPE_STAFF]->setSelectState(true);
}
//
if (_mapItemWidgets.contains(EM_ITEM_TYPE_STAFF)) {
QWidget *wgt = _mapItemWidgets[EM_ITEM_TYPE_STAFF];
if (nullptr != wgt && wgt == _pStaffView && _pStaffModel) {
_pShowItem = nullptr;
_pStaffView->collapseAll();
//
int rowCount = _pStaffModel->rowCount();
for (int row = 0; row < rowCount; ++row) {
QStandardItem *tmpItem = _pStaffModel->item(row);
getShowItemByStructre(tmpItem, strureName);
if (nullptr != _pShowItem) {
break;
}
}
if (nullptr != _pShowItem) {
parentShow(_pShowItem);
_pStaffView->scrollTo(_pShowItem->index(), QAbstractItemView::PositionAtTop);
onStaffItemClicked(_pShowItem->index());
_pStaffView->setCurrentIndex(_pShowItem->index());
}
}
}
}
void AddressBookPanel::getShowItemByStructre(QStandardItem* parentItem, const QString& structre)
{
if (nullptr != _pShowItem) {
return;
}
QString structureName = parentItem->data(EM_STAFF_DATATYPE_STRUCTURE).toString();
QString text = parentItem->data(EM_STAFF_DATATYPE_TEXT).toString();
QString tmpStructure = structureName.isEmpty() ?
QString("/%1").arg(text) :
QString("%1/%2").arg(structureName, text);
if(tmpStructure == structre)
{
_pShowItem = parentItem;
return;
}
//
int rowCount = parentItem->rowCount();
for (int row = 0; row < rowCount; row++) {
QStandardItem *tmpItem = parentItem->child(row, 0);
if (nullptr == tmpItem) continue;
//
bool hasChild = tmpItem->data(EM_STAFF_DATATYPE_HASCHILD).toBool();
if (hasChild)
{
getShowItemByStructre(tmpItem, structre);
}
}
}
void AddressBookPanel::onDestroyGroupRet(const std::string &groupId)
{
ListItemView *blkListview = (ListItemView *) _mapItemWidgets.value(EM_ITEM_TYPE_GROUPLIST);
if (nullptr == blkListview) return;
blkListview->removeItem(QString::fromStdString(groupId));
}
void AddressBookPanel::getStructure() {
auto func = [this]() {
#ifdef _MACOS
pthread_setname_np("UIGroupManager::getStructure");
#endif
if (_pMsgManager) {
{
std::lock_guard<QTalk::util::spin_mutex> lock(sm);
std::vector<std::shared_ptr<QTalk::Entity::ImUserInfo>> structure;
_pMsgManager->getStructure(structure);
_pstStrcuture = new StStrcuture;
std::for_each(structure.begin(), structure.end(), [this](std::shared_ptr<QTalk::Entity::ImUserInfo> info) {
if(info->isVisible)
{
StStrcuture *tmp = _pstStrcuture;
QStringList sto = QString::fromStdString(info->DescInfo).split("/");
for (int i = 0; i < sto.size(); i++)
{
const QString &o = sto.at(i);
if (o.isEmpty()) continue;
if (nullptr == tmp->mapChild[o])
tmp->mapChild[o] = new StStrcuture;
tmp = tmp->mapChild[o];
tmp->curStrcutureName = getStrName(sto, i);
if (i == sto.size() - 1) {
tmp->oUsers.push_back(info);
}
}
}
});
}
emit updateUiSignal();
}
};
//
std::thread t(func);
t.detach();
}
void AddressBookPanel::updateUi() {
if (nullptr != _pstStrcuture) {
if(_pstStrcuture->mapChild.empty())
{
_pStaffView->setVisible(false);
_mapNavItems[EM_ITEM_TYPE_STAFF]->setVisible(false);
}
//
auto it = _pstStrcuture->mapChild.begin();
while (it != _pstStrcuture->mapChild.end()) {
auto *item = new QStandardItem();
item->setData(it->first, EM_STAFF_DATATYPE_TEXT);
item->setData(":/GroupManager/image1/structure.png", EM_STAFF_DATATYPE_ICONPATH);
item->setData(_pstStrcuture->curStrcutureName, EM_STAFF_DATATYPE_STRUCTURE);
item->setData(true, EM_STAFF_DATATYPE_HASCHILD);
_pStaffModel->appendRow(item);
//
it->second->item = item;
creatChildItem(it->second, item);
//
it++;
}
// _pTreeWgt->setColumnWidth(EM_COLUMNTYPE_COMTENT, 230);
// _pTreeWgt->setColumnWidth(EM_COLUMNTYPE_CHECKBOX, 30);
}
// emit setTreeDataFinised();
}
//
void AddressBookPanel::creatChildItem(const StStrcuture *os, QStandardItem *parentItem) {
// static int index = 0;
// if(++index == 10)
// {
// QApplication::processEvents(QEventLoop::AllEvents, 100);
// index = 0;
// }
if (os) {
auto it = os->mapChild.begin();
while (it != os->mapChild.end()) {
auto *item = new QStandardItem();
item->setData(it->first, EM_STAFF_DATATYPE_TEXT);
item->setData(":/GroupManager/image1/structure.png", EM_STAFF_DATATYPE_ICONPATH);
item->setData(true, EM_STAFF_DATATYPE_HASCHILD);
item->setData(os->curStrcutureName, EM_STAFF_DATATYPE_STRUCTURE);
//
parentItem->appendRow(item);
it->second->item = item;
//
creatChildItem(it->second, item);
//
it++;
}
auto itu = os->oUsers.begin();
while (itu != os->oUsers.end()) {
QStandardItem *item = new QStandardItem(QString((*itu)->Name.c_str()));
QString headrSrc = QString(QTalk::GetHeadPathByUrl((*itu)->HeaderSrc).c_str());
if (QFileInfo(headrSrc).isDir() || !QFile::exists(headrSrc)) {
#ifdef _STARTALK
headrSrc = ":/QTalk/image1/StarTalk_defaultHead.png";
#else
headrSrc = ":/QTalk/image1/headPortrait.png";
#endif
}
item->setData(QString::fromStdString((*itu)->Name), EM_STAFF_DATATYPE_TEXT);
item->setData(headrSrc, EM_STAFF_DATATYPE_ICONPATH);
item->setData(false, EM_STAFF_DATATYPE_HASCHILD);
item->setData(QString((*itu)->XmppId.c_str()), EM_STAFF_DATATYPE_XMPPID);
item->setData(QString((*itu)->SearchIndex.c_str()), EM_DATATYPE_SEARCHKEY);
auto *checkItem = new QStandardItem();
checkItem->setData(false, EM_DATATYPE_CHECKSTATE);
parentItem->appendRow(QList<QStandardItem *>() << item << checkItem);
_staffItems[(*itu)->XmppId] = item;
itu++;
}
}
}
void AddressBookPanel::gotIncrementUser(const std::vector<QTalk::Entity::ImUserInfo> &arUserInfo,
const std::vector<std::string> &arDeletes)
{
// todo 先全部刷 不考虑增量
// // add
// for(const auto& it : arUserInfo)
// {
// std::string xmppId = it.XmppId;
//
// QStringList sto = QString::fromStdString(it.DescInfo).split("/");
//
// if(nullptr == _pstStrcuture) break;
//
// StStrcuture *tmp = _pstStrcuture;
// for (int i = 0; i < sto.size(); i++)
// {
// const QString &o = sto.at(i);
//
// if (o.isEmpty()) continue;
//
// if (nullptr == tmp->mapChild[o])
// {
// tmp->mapChild[o] = new StStrcuture;
// tmp->mapChild[o]->curStrcutureName = getStrName(sto, i);
// //
// auto *item = new QStandardItem();
// item->setData(o, EM_STAFF_DATATYPE_TEXT);
// item->setData(":/GroupManager/image1/structure.png", EM_STAFF_DATATYPE_ICONPATH);
// item->setData(true, EM_STAFF_DATATYPE_HASCHILD);
// item->setData(getStrName(sto, i), EM_STAFF_DATATYPE_STRUCTURE);
// //
// if(tmp->item)
// tmp->item->appendRow(item);
// else
// _pStaffModel->appendRow(item);
//
// tmp->mapChild[o]->item = item;
// }
//
// tmp = tmp->mapChild[o];
//
// if (i == sto.size() - 1) {
// auto info = std::make_shared<QTalk::Entity::ImUserInfo>(it);
// tmp->oUsers.push_back(info);
// //
// QStandardItem *item = new QStandardItem(QString(info->Name.c_str()));
// QString headrSrc = QString(QTalk::GetHeadPathByUrl(info->HeaderSrc).c_str());
// if (QFileInfo(headrSrc).isDir() || !QFile::exists(headrSrc)) {
//#ifdef _STARTALK
// headrSrc = ":/QTalk/image1/StarTalk_defaultHead.png";
//#else
// headrSrc = ":/QTalk/image1/headPortrait.png";
//#endif
// }
// item->setData(QString::fromStdString(info->Name), EM_STAFF_DATATYPE_TEXT);
// item->setData(headrSrc, EM_STAFF_DATATYPE_ICONPATH);
// item->setData(false, EM_STAFF_DATATYPE_HASCHILD);
// item->setData(QString(info->XmppId.c_str()), EM_STAFF_DATATYPE_XMPPID);
// item->setData(QString(info->SearchIndex.c_str()), EM_DATATYPE_SEARCHKEY);
// auto *checkItem = new QStandardItem();
// checkItem->setData(false, EM_DATATYPE_CHECKSTATE);
//
// if(tmp->item)
// tmp->item->appendRow(QList<QStandardItem *>() << item << checkItem);
// else
// _pStaffModel->appendRow(QList<QStandardItem *>() << item << checkItem);
//
// _staffItems[info->XmppId] = item;
// }
// }
// }
// // delete
// for(const auto& id : arDeletes)
// {
// //
// if(_staffItems.find(id) != _staffItems.end())
// {
// auto* item = _staffItems[id];
// _pStaffModel->removeRow(item->row(), item->parent()->index());
// //
// _staffItems.erase(id);
// }
// }
// 清楚数据
delete _pstStrcuture;
_pstStrcuture = nullptr;
_pStaffModel->clear();
// 重新刷新
getStructure();
} | 32.525304 | 141 | 0.588953 | [
"vector",
"model"
] |
4fca5032608c70fd27415ce0a402a773007d01c5 | 10,303 | cpp | C++ | src/UI/settingwin.cpp | Luke-lujunxian/Live2D_VideoChat | 1913d3011e310e6e0023c8850bfc24513a455dc9 | [
"MIT"
] | null | null | null | src/UI/settingwin.cpp | Luke-lujunxian/Live2D_VideoChat | 1913d3011e310e6e0023c8850bfc24513a455dc9 | [
"MIT"
] | null | null | null | src/UI/settingwin.cpp | Luke-lujunxian/Live2D_VideoChat | 1913d3011e310e6e0023c8850bfc24513a455dc9 | [
"MIT"
] | null | null | null | #include "settingwin.h"
#include "ui_SettingWin.h"
#include "setting.h"
#include "errorwin.h"
#include <QFileDialog>
#include <QtNetwork/qtcpsocket.h>
#include <QtMultimedia/QAudioDeviceInfo>
#include <Network_QT.h>
bool allClear;
SettingWin::SettingWin(QWidget *parent) :
QWidget(parent),
ui(new Ui::SettingWin)
{
ui->setupUi(this);
//Apply funtion
QObject::connect(ui->lineEdit_Name,&QLineEdit::textChanged,this,&SettingWin::canApply);
//TODO: Name check
QObject::connect(ui->lineEdit_ListenPort,&QLineEdit::textChanged,this,&SettingWin::canApply);
QObject::connect(ui->lineEdit_CallPort,&QLineEdit::textChanged,this,&SettingWin::canApply);
QObject::connect(ui->lineEdit_AudioPort, &QLineEdit::textChanged, this, &SettingWin::canApply);
ui->lineEdit_ListenPort->setValidator(new QRegExpValidator(QRegExp("[0-9]+$")));
ui->lineEdit_CallPort->setValidator(new QRegExpValidator(QRegExp("[0-9]+$")));
ui->lineEdit_AudioPort->setValidator(new QRegExpValidator(QRegExp("[0-9]+$")));
ui->lineEdit_ListenPort->setText(QString::number( Setting::getSetting()->getListenPort()));
ui->lineEdit_CallPort->setText(QString::number(Setting::getSetting()->getCallPort()));
ui->lineEdit_AudioPort->setText(QString::number(Setting::getSetting()->getAudioPort()));
ui->lineEdit_Name->setText(QString::fromStdString(Setting::getSetting()->getName()));
QObject::connect(ui->comboBox_ProfilePhoto,&QComboBox::currentTextChanged,this,&SettingWin::canApply);
ui->comboBox_ProfilePhoto->addItem("..\\..\\res\\defaultProfile.jpg");
Setting::getSetting()->setProfile("..\\..\\res\\defaultProfile.jpg");
QObject::connect(ui->comboBox_Model,&QComboBox::currentTextChanged,this,&SettingWin::canApply);
QObject::connect(ui->comboBox_Camera,&QComboBox::currentTextChanged,this,&SettingWin::canApply);
QObject::connect(ui->comboBox_InputDevice, &QComboBox::currentTextChanged, this, &SettingWin::canApply);
QObject::connect(ui->comboBox_OutputDevice, &QComboBox::currentTextChanged, this, &SettingWin::canApply);
QObject::connect(ui->spinBox_MaxCallQueue, QOverload<int>::of(&QSpinBox::valueChanged),this,&SettingWin::canApply);
QObject::connect(ui->checkBox_Debug_Console,&QCheckBox::stateChanged,this,&SettingWin::canApply);
QObject::connect(ui->checkBox_Debug_ShowCamera,&QCheckBox::stateChanged,this,&SettingWin::canApply);
QObject::connect(ui->checkBox_Debug_ShowFEI,&QCheckBox::stateChanged,this,&SettingWin::canApply);
allClear = true;
//QObject::connect(ui->pushButton_Apply,&QPushButton::clicked,this,&Setting::applyFun);
std::vector<std::string> CamList;
int num = listDevices(CamList);
for (int i = 0; i < num; i++) {
//char* itemName[64] = { 0 }; sprintf(itemName[0], "ID: %d %s" ,i, CamList[i].c_str());//+ i + "\t" + CamList[i];);
QString name;
name.sprintf("ID:%d %s", i, CamList[i].c_str());
ui->comboBox_Camera->addItem(name);
}
for (int i = 0; i < QAudioDeviceInfo::availableDevices(QAudio::AudioInput).size()/2;i++) {
ui->comboBox_InputDevice->addItem(QAudioDeviceInfo::availableDevices(QAudio::AudioInput)[i].deviceName());
}
for (int i = 0; i < QAudioDeviceInfo::availableDevices(QAudio::AudioOutput).size() / 2; i++) {
ui->comboBox_OutputDevice->addItem(QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)[i].deviceName());
}
}
SettingWin::~SettingWin()
{
delete ui;
}
void SettingWin::canApply(){
ui->pushButton_Apply->setEnabled(true);
}
void SettingWin::on_pushButton_Apply_clicked(){
//Do something
Setting* setting = Setting::getSetting();
allClear = true;
QString errorColor = "background-color: rgba(255, 0, 0, 100)";
//background-color: rgba(255, 0, 0, 100);
allClear = setting->setName(ui->lineEdit_Name->text().toStdString()) ? clearError(ui->lineEdit_Name,allClear) : setError(ui->lineEdit_Name);
allClear = setting->setListenPort(ui->lineEdit_ListenPort->text().toInt()) ? clearError(ui->lineEdit_ListenPort, allClear) : setError(ui->lineEdit_ListenPort);
allClear = setting->setCallPort(ui->lineEdit_CallPort->text().toInt()) ? clearError(ui->lineEdit_CallPort, allClear) : setError(ui->lineEdit_CallPort);
allClear = setting->setAudioPort(ui->lineEdit_AudioPort->text().toInt()) ? clearError(ui->lineEdit_AudioPort, allClear) : setError(ui->lineEdit_AudioPort);
allClear = setting->setProfile(ui->comboBox_ProfilePhoto->currentText().toStdString()) ? clearError(ui->comboBox_ProfilePhoto, allClear) : setError(ui->comboBox_ProfilePhoto);
allClear = setting->setModelID(ui->comboBox_Model->currentText().toStdString()) ? clearError(ui->comboBox_Model, allClear) : setError(ui->comboBox_Model);
allClear = setting->setCameraID(ui->comboBox_Camera->currentIndex() == 0 ? 0 : ui->comboBox_Camera->currentIndex() - 1) ? clearError(ui->comboBox_Camera, allClear) : setError(ui->comboBox_Camera);
setting->setMaximumListenQueue(ui->spinBox_MaxCallQueue->value());
setting->debug = ui->checkBox_Debug_Console->isChecked();
setting->showCamera = ui->checkBox_Debug_ShowCamera->isChecked();
setting->ShowFR = ui->checkBox_Debug_ShowFEI->isChecked();
setting->setOutputDevice(QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)[ui->comboBox_OutputDevice->currentIndex()]);
setting->setInputDevice(QAudioDeviceInfo::availableDevices(QAudio::AudioInput)[ui->comboBox_InputDevice->currentIndex()]);
if (allClear) {
ui->pushButton_Apply->setEnabled(false);
emit settingApplySuccess();
emit Network_QT::getInstance()->restartSignal();
}
else {
ErrorWin* temp = new ErrorWin();
temp->setWindowFlags(Qt::Dialog);
temp->show();
//Error window
}
}
void SettingWin::on_pushButton_ProfilePhoto_clicked(){
//Do something`
//定义文件对话框类
QFileDialog* fileDialog = new QFileDialog(this);
//定义文件对话框标题
fileDialog->setWindowTitle(QStringLiteral("Select Profile"));
//设置默认文件路径
fileDialog->setDirectory(".");
//设置文件过滤器
fileDialog->setNameFilter(tr("Images(*.png *.jpg *.jpeg *.bmp)"));
//设置可以选择多个文件,默认为只能选择一个文件QFileDialog::ExistingFiles
fileDialog->setFileMode(QFileDialog::ExistingFiles);
//设置视图模式
fileDialog->setViewMode(QFileDialog::Detail);
//打印所有选择的文件的路径
QStringList fileNames;
if (fileDialog->exec()) {
ui->comboBox_ProfilePhoto->addItem(fileDialog->selectedFiles()[0]);
ui->comboBox_ProfilePhoto->setCurrentText(fileDialog->selectedFiles()[0]);
}
//————————————————
// 版权声明:本文为CSDN博主「wb175208」的原创文章,遵循 CC 4.0 BY - SA 版权协议,转载请附上原文出处链接及本声明。
// 原文链接:https ://blog.csdn.net/wb175208/article/details/86661722
ui->pushButton_Apply->setEnabled(true);
}
void SettingWin::on_pushButton_Model_clicked(){
//Do something
QFileDialog* fileDialog = new QFileDialog(this);
fileDialog->setWindowTitle(QStringLiteral("Select Model"));
fileDialog->setDirectory(".");
fileDialog->setNameFilter(tr("JSON(*.json)"));
fileDialog->setFileMode(QFileDialog::ExistingFiles);
fileDialog->setViewMode(QFileDialog::Detail);
QStringList fileNames;
if (fileDialog->exec()) {
ui->comboBox_Model->setCurrentText(fileDialog->selectedFiles()[0]);
ui->comboBox_Model->addItem(fileDialog->selectedFiles()[0]);
}
ui->pushButton_Apply->setEnabled(true);
}
bool setError(QWidget* obj) {//Hight light the error box
obj->setStyleSheet("background-color: rgba(255, 0, 0, 100);");
return false;
}
bool clearError(QWidget* obj, bool AC) {
obj->setStyleSheet("");
return AC;
}
void SettingWin::on_pushButton_OK_clicked() {
on_pushButton_Apply_clicked();
if (allClear)
this->close();
}
void SettingWin::on_pushButton_Cancel_clicked() {
this->close();
}
#pragma comment(lib, "setupapi.lib")
#define VI_MAX_CAMERAS 20
DEFINE_GUID(CLSID_SystemDeviceEnum, 0x62be5d10, 0x60eb, 0x11d0, 0xbd, 0x3b, 0x00, 0xa0, 0xc9, 0x11, 0xce, 0x86);
DEFINE_GUID(CLSID_VideoInputDeviceCategory, 0x860bb310, 0x5d01, 0x11d0, 0xbd, 0x3b, 0x00, 0xa0, 0xc9, 0x11, 0xce, 0x86);
DEFINE_GUID(IID_ICreateDevEnum, 0x29840822, 0x5b84, 0x11d0, 0xbd, 0x3b, 0x00, 0xa0, 0xc9, 0x11, 0xce, 0x86);
//列出硬件设备
//https://www.cnblogs.com/herd/p/9277402.html
int listDevices(std::vector<std::string>& list)
{
ICreateDevEnum* pDevEnum = NULL;
IEnumMoniker* pEnum = NULL;
int deviceCounter = 0;
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(
CLSID_SystemDeviceEnum,
NULL,
CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum,
reinterpret_cast<void**>(&pDevEnum)
);
if (SUCCEEDED(hr))
{
hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEnum, 0);
if (hr == S_OK) {
IMoniker* pMoniker = NULL;
while (pEnum->Next(1, &pMoniker, NULL) == S_OK)
{
IPropertyBag* pPropBag;
hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
(void**)(&pPropBag));
if (FAILED(hr)) {
pMoniker->Release();
continue; // Skip this one, maybe the next one will work.
}
VARIANT varName;
VariantInit(&varName);
hr = pPropBag->Read(L"Description", &varName, 0);
if (FAILED(hr))
{
hr = pPropBag->Read(L"FriendlyName", &varName, 0);
}
if (SUCCEEDED(hr))
{
hr = pPropBag->Read(L"FriendlyName", &varName, 0);
int count = 0;
char tmp[255] = { 0 };
while (varName.bstrVal[count] != 0x00 && count < 255)
{
tmp[count] = (char)varName.bstrVal[count];
count++;
}
list.push_back(tmp);
}
pPropBag->Release();
pPropBag = NULL;
pMoniker->Release();
pMoniker = NULL;
deviceCounter++;
}
pDevEnum->Release();
pDevEnum = NULL;
pEnum->Release();
pEnum = NULL;
}
}
return deviceCounter;
}
void SettingWin::on_pushButton_AudioPortTest_clicked() {
if (!checkPortAvalibility(ui->pushButton_AudioPortTest->text().toInt())) {
setError(ui->lineEdit_AudioPort);
}
else {
clearError(ui->lineEdit_AudioPort,true);
}
}
void SettingWin::on_pushButton_TestListenPort_clicked() {
if (!checkPortAvalibility(ui->pushButton_TestListenPort->text().toInt())) {
setError(ui->lineEdit_ListenPort);
}
else {
clearError(ui->lineEdit_ListenPort, true);
}
}
void SettingWin::on_pushButton_TestCallPort_clicked() {
if (!checkPortAvalibility(ui->pushButton_TestCallPort->text().toInt())) {
setError(ui->lineEdit_CallPort);
}
else {
clearError(ui->lineEdit_CallPort, true);
}
}
bool checkPortAvalibility(int port) {
QTcpSocket* temp = new QTcpSocket();
bool state;
state = temp->bind(port);
delete temp;
return state;
} | 36.278169 | 197 | 0.725711 | [
"vector",
"model"
] |
4fcfeb7bc726bf5cf2de0266a1a409514f4da337 | 40,197 | cpp | C++ | VSOptics/VSOTelescope.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSOptics/VSOTelescope.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSOptics/VSOTelescope.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
#include <sstream>
#include <algorithm>
#include <VSDataConverter.hpp>
#include <VSSimDBTables.hpp>
#include "VSOTelescope.hpp"
using namespace Physics;
using namespace VERITAS;
VSOTelescope::VSOTelescope():
fID(), fTelescopeHexID(), fPos(),
fDeltaY(), fAlphaX(), fAlphaY(),
fElevation(), fAzimuth(),
fTranslation(), fCurvatureRadius(), fAperture(),
fFacetSpacing(), fFacetSize(),
fReflectorRotation(), fAlignmentPoint(), fHexagonRingsN(),
fReflectorIP(), fMirrorParity(), fFPTranslation(), fCameraDiameter(),
fFieldOfView(), fCathodeDiameter(), fPixelSpacing(), fConcSurvProb(),
fFPRotation(), fCameraIP(), fPixelParity(),
#if 0
fHasSecondary(false),
fRefractiveIndex(), fRefractiveIndex1(), fRefractiveIndex2(),
fCE1Parameter0(), fCE1Parameter2(), fCE1Parameter3(), fCE1Parameter4(),
fCE1Parameter5(), fCE2Parameter0(), fCE2Parameter2(), fCE2Parameter3(),
fCE2Parameter4(), fCE2Parameter5(),
#endif
fMirrors(), fMirrorsByHexID(), fPixels(), fPixelsByHexID(), fRotationVector()
{
calculateRotationVector();
}
VSOTelescope::
VSOTelescope(unsigned TID, unsigned THID, const Vec3D&P,
double DY, double AX, double AY, double EL, double AZ,
const Vec3D& T, double CR, double A, double FSP, double FS,
double RR, const Vec3D& AP, unsigned HRN, double RIP, bool MP,
const Vec3D& FPT, double CD, double FOV, double D, double PS,
double CSP, const Vec3D& FPR, double CIP, bool PP
#if 0
, bool SEC, double RI, double RI1, double RI2, double C10,
double C12, double C13, double C14, double C15, double C20,
double C22, double C23,double C24, double C25
#endif
):
fID(TID), fTelescopeHexID(THID), fPos(P),
fDeltaY(DY), fAlphaX(AX), fAlphaY(AY), fElevation(EL), fAzimuth(AZ),
fTranslation(T), fCurvatureRadius(CR), fAperture(A), fFacetSpacing(FSP),
fFacetSize(FS), fReflectorRotation(RR), fAlignmentPoint(AP),
fHexagonRingsN(HRN), fReflectorIP(RIP), fMirrorParity(MP),
fFPTranslation(FPT), fCameraDiameter(CD), fFieldOfView(FOV),
fCathodeDiameter(D), fPixelSpacing(PS), fConcSurvProb(CSP),
fFPRotation(FPR), fCameraIP(CIP), fPixelParity(PP),
#if 0
fHasSecondary(SEC),
fRefractiveIndex(RI), fRefractiveIndex1(RI1), fRefractiveIndex2(RI2),
fCE1Parameter0(C10), fCE1Parameter2(C12), fCE1Parameter3(C13),
fCE1Parameter4(C14), fCE1Parameter5(C15), fCE2Parameter0(C20),
fCE2Parameter2(C22), fCE2Parameter3(C23), fCE2Parameter4(C24),
fCE2Parameter5(C25),
#endif
fMirrors(), fMirrorsByHexID(), fPixels(), fPixelsByHexID(), fRotationVector()
{
calculateRotationVector();
}
VSOTelescope::VSOTelescope(const VSOTelescope& o):
fID(o.fID), fTelescopeHexID(o.fTelescopeHexID),
fPos(o.fPos), fDeltaY(o.fDeltaY), fAlphaX(o.fAlphaX), fAlphaY(o.fAlphaY),
fElevation(o.fElevation), fAzimuth(o.fAzimuth), fTranslation(o.fTranslation),
fCurvatureRadius(o.fCurvatureRadius), fAperture(o.fAperture),
fFacetSpacing(o.fFacetSpacing), fFacetSize(o.fFacetSize),
fReflectorRotation(o.fReflectorRotation),
fAlignmentPoint(o.fAlignmentPoint), fHexagonRingsN(o.fHexagonRingsN),
fReflectorIP(o.fReflectorIP), fMirrorParity(o.fMirrorParity),
fFPTranslation(o.fFPTranslation), fCameraDiameter(o.fCameraDiameter),
fFieldOfView(o.fFieldOfView), fCathodeDiameter(o.fCathodeDiameter),
fPixelSpacing(o.fPixelSpacing), fConcSurvProb(o.fConcSurvProb),
fFPRotation(o.fFPRotation), fCameraIP(o.fCameraIP),
fPixelParity(o.fPixelParity),
#if 0
fHasSecondary(o.fHasSecondary),
fRefractiveIndex(o.fRefractiveIndex),
fRefractiveIndex1(o.fRefractiveIndex1),
fRefractiveIndex2(o.fRefractiveIndex2),
fCE1Parameter0(o.fCE1Parameter0), fCE1Parameter2(o.fCE1Parameter2),
fCE1Parameter3(o.fCE1Parameter3), fCE1Parameter4(o.fCE1Parameter4),
fCE1Parameter5(o.fCE1Parameter5), fCE2Parameter0(o.fCE2Parameter0),
fCE2Parameter2(o.fCE2Parameter2), fCE2Parameter3(o.fCE2Parameter3),
fCE2Parameter4(o.fCE2Parameter4), fCE2Parameter5(o.fCE2Parameter5),
#endif
fMirrors(), fMirrorsByHexID(), fPixels(), fPixelsByHexID(),
fRotationVector()
{
fMirrors.resize(o.fMirrors.size());
fMirrorsByHexID.resize(o.fMirrorsByHexID.size());
for(std::vector<VSOMirror*>::const_iterator i=o.fMirrors.begin();
i!=o.fMirrors.end(); i++)
{
VSOMirror* mirror = new VSOMirror(**i);
fMirrors[(*i)->id()]=mirror;
fMirrorsByHexID[(*i)->hexID()]=mirror;
}
fPixels.resize(o.fPixels.size());
fPixelsByHexID.resize(o.fPixelsByHexID.size());
for(std::vector<VSOPixel*>::const_iterator i=o.fPixels.begin();
i!=o.fPixels.end(); i++)
{
VSOPixel* pixel = new VSOPixel(**i);
fPixels[(*i)->id()]=pixel;
fPixelsByHexID[(*i)->hexID()]=pixel;
}
calculateRotationVector();
}
VSOTelescope::~VSOTelescope()
{
for(std::vector<VSOMirror*>::iterator i=fMirrors.begin();
i!=fMirrors.end(); i++)delete *i;
for(std::vector<VSOPixel*>::iterator i=fPixels.begin();
i!=fPixels.end(); i++)delete *i;
}
// Stroustrup third edition sec 11.3.4 recommends default copy assignment
const VSOTelescope& VSOTelescope::operator =(const VSOTelescope& o)
{
fID = o.fID;
fTelescopeHexID = o.fTelescopeHexID;
fPos = o.fPos;
fDeltaY = o.fDeltaY;
fAlphaX = o.fAlphaX;
fAlphaY = o.fAlphaY;
fElevation = o.fElevation;
fAzimuth = o.fAzimuth;
fTranslation = o.fTranslation;
fCurvatureRadius = o.fCurvatureRadius;
fAperture = o.fAperture;
fFacetSpacing = o.fFacetSpacing;
fFacetSize = o.fFacetSize;
fReflectorRotation = o.fReflectorRotation;
fAlignmentPoint = o.fAlignmentPoint;
fHexagonRingsN = o.fHexagonRingsN;
fReflectorIP = o.fReflectorIP;
fMirrorParity = o.fMirrorParity;
fFPTranslation = o.fFPTranslation;
fCameraDiameter = o.fCameraDiameter;
fFieldOfView = o.fFieldOfView;
fCathodeDiameter = o.fCathodeDiameter;
fPixelSpacing = o.fPixelSpacing;
fConcSurvProb = o.fConcSurvProb;
fFPRotation = o.fFPRotation;
fCameraIP = o.fCameraIP;
fPixelParity = o.fPixelParity;
#if 0
fHasSecondary = o.fHasSecondary,
fRefractiveIndex = o.fRefractiveIndex;
fRefractiveIndex1 = o.fRefractiveIndex1;
fRefractiveIndex2 = o.fRefractiveIndex2;
fCE1Parameter0 = o.fCE1Parameter0;
fCE1Parameter2 = o.fCE1Parameter2;
fCE1Parameter3 = o.fCE1Parameter3;
fCE1Parameter4 = o.fCE1Parameter4;
fCE1Parameter5 = o.fCE1Parameter5;
fCE2Parameter0 = o.fCE2Parameter0;
fCE2Parameter2 = o.fCE2Parameter2;
fCE2Parameter3 = o.fCE2Parameter3;
fCE2Parameter4 = o.fCE2Parameter4;
fCE2Parameter5 = o.fCE2Parameter5;
#endif
for(std::vector<VSOMirror*>::iterator i=fMirrors.begin();
i!=fMirrors.end(); i++)delete *i;
fMirrors.clear();
fMirrorsByHexID.clear();
fMirrors.resize(o.fMirrors.size());
fMirrorsByHexID.resize(o.fMirrorsByHexID.size());
for(std::vector<VSOMirror*>::const_iterator i=o.fMirrors.begin();
i!=o.fMirrors.end(); i++)
{
VSOMirror* mirror = new VSOMirror(**i);
fMirrors[(*i)->id()]=mirror;
fMirrorsByHexID[(*i)->hexID()]=mirror;
}
for(std::vector<VSOPixel*>::iterator i=fPixels.begin();
i!=fPixels.end(); i++)delete *i;
fPixels.clear();
fPixelsByHexID.clear();
fPixels.resize(o.fPixels.size());
fPixelsByHexID.resize(o.fPixelsByHexID.size());
for(std::vector<VSOPixel*>::const_iterator i=o.fPixels.begin();
i!=o.fPixels.end(); i++)
{
VSOPixel* pixel = new VSOPixel(**i);
fPixels[(*i)->id()]=pixel;
fPixelsByHexID[(*i)->hexID()]=pixel;
}
calculateRotationVector();
return *this;
}
// ****************************************************************************
// Accessor
// ****************************************************************************
Vec3D VSOTelescope::opticalAxis() const
{
return Vec3D(cos(fElevation)*sin(fAzimuth),
cos(fElevation)*cos(fAzimuth),
sin(fElevation));
}
// ****************************************************************************
// Repoint the telescope along a vector
// ****************************************************************************
bool VSOTelescope::pointTelescope(const Vec3D& v)
{
if(v.Norm2()==0)return false;
fElevation = atan2(v.z,sqrt(v.x*v.x + v.y*v.y));
fAzimuth = fmod(atan2(v.x,v.y)+2.0*M_PI, 2.0*M_PI);
calculateRotationVector();
return true;
}
bool VSOTelescope::pointTelescopeAzEl(const double az_rad, const double el_rad)
{
fElevation = fmod(fmod(el_rad,2.0*M_PI)+2.0*M_PI, 2.0*M_PI);
fAzimuth = fmod(fmod(az_rad,2.0*M_PI)+2.0*M_PI, 2.0*M_PI);
calculateRotationVector();
return true;
}
// ****************************************************************************
// Calculate rotation vector and map between Global and Telescope coordinates
// ****************************************************************************
void VSOTelescope::calculateRotationVector()
{
// Rotation vector maps from Reflector to Global
fRotationVector =
Vec3D(1,0,0)*fElevation &
Vec3D(0,1,0)*fDeltaY &
Vec3D(0,0,-1)*fAzimuth &
Vec3D(0,1,0)*fAlphaX &
Vec3D(1,0,0)*fAlphaY;
}
void VSOTelescope::globalToReflector(Physics::Vec3D& v) const
{
// First: Translate from center of array to drive axes intersection
v -= fPos;
// Second: Rotate coordinate system to reflector orientation
v.Rotate(-fRotationVector);
// Third: Translate from intersection of drive axes to reflector
v += fTranslation;
}
void VSOTelescope::reflectorToGlobal(Physics::Vec3D& v) const
{
// First: Translate from reflector to intersection of drive axes
v -= fTranslation;
// Second: Rotate coordinate system to ground based
v.Rotate(fRotationVector);
// Third: Translate from drive axes intersection to center of array
v += fPos;
}
void VSOTelescope::globalToReflector(Particle& p) const
{
// First: Translate from center of array to drive axes intersection
p.TranslateOrigin(Vec4D(0,fPos));
// Second: Rotate coordinate system to reflector orientation
p.Rotate(-fRotationVector);
// Third: Translate from intersection of drive axes to reflector
p.TranslateOrigin(Vec4D(0,-fTranslation));
}
void VSOTelescope::reflectorToGlobal(Particle& p) const
{
// First: Translate from reflector to intersection of drive axes
p.TranslateOrigin(Vec4D(0,fTranslation));
// Second: Rotate coordinate system to ground based
p.Rotate(fRotationVector);
// Third: Translate from drive axes intersection to center of array
p.TranslateOrigin(Vec4D(0,-fPos));
}
void VSOTelescope::focalPlaneToReflector(Physics::Particle& p) const
{
// First: Rotate coordinate system
p.Rotate(fFPRotation);
// Second: Translate from center of Focal Plane
p.TranslateOrigin(Vec4D(0,-fFPTranslation));
}
void VSOTelescope::reflectorToFocalPlane(Physics::Particle& p) const
{
// First: Translate to center of Focal Plane
p.TranslateOrigin(Vec4D(0,fFPTranslation));
// Second: Rotate coordinate system
p.Rotate(-fFPRotation);
}
// ****************************************************************************
// Fill the mirrors and pixels tables up with randomly generated objects
// ****************************************************************************
void VSOTelescope::
populateMirrorsAndPixelsRandom(const VSOArrayParameters& param,
RandomNumbers& rng)
{
// **************************************************************************
// Clear the MIRRORs table and repopulate it with randomly generated mirrors
// **************************************************************************
double reflector_r2 = fAperture*fAperture/4.0;
double reflector_c2 = fCurvatureRadius*fCurvatureRadius;
Vec3D reflector_center(0, fCurvatureRadius, 0);
std::set<unsigned> mirrors_missing;
Physics::tokenize(param.MirrorMissingList,mirrors_missing);
for(std::vector<VSOMirror*>::iterator i=fMirrors.begin();
i!=fMirrors.end(); i++)delete *i;
fMirrors.clear();
fMirrorsByHexID.clear();
int num_hex_mirror_sites = 3*fHexagonRingsN*(fHexagonRingsN+1)+1;
unsigned id = 0;
for(int i=0; i<num_hex_mirror_sites; i++)
{
int hexid = i+1;
if(mirrors_missing.find(hexid) != mirrors_missing.end())
{
fMirrorsByHexID.push_back(0);
continue; // skip mirror if on the mirring list
}
Vec3D nominal_position;
// Compute the mirror's nominal position
nh_to_xy(&hexid, &nominal_position.x, &nominal_position.z);
if(fMirrorParity)nominal_position.x=-nominal_position.x;
nominal_position.x *= fFacetSpacing;
nominal_position.z *= fFacetSpacing;
double X2 = nominal_position.x*nominal_position.x;
double Z2 = nominal_position.z*nominal_position.z;
if( (reflector_r2 - X2 - Z2) <= 0 )
{
fMirrorsByHexID.push_back(0);
continue; // skip mirror if projected hex position too far out
}
nominal_position.y = fCurvatureRadius-sqrt(reflector_c2 - X2 - Z2);
// Add Gaussian normal/tangenetial position error
Vec3D reflector_normal(reflector_center-nominal_position);
reflector_normal /= reflector_normal.Norm();
Vec3D position(nominal_position);
position += reflector_normal*(rng.Normal()*param.MirrorPosNormalDisp);
position -= reflector_center;
position.ScatterDirection(param.MirrorPosTangentDisp/fCurvatureRadius,rng);
position += reflector_center;
// Rotate by global rotation angle
position.Rotate(Vec3D(0,fReflectorRotation,0));
// Get the (perturbed) alignment angle of mirror
Vec3D alignment;
if(param.ReflectorAlignMode == 0)
{
// Standard DC alignment to a fixed point in space (with scatter)
alignment = (fAlignmentPoint-position);
alignment /= alignment.Norm();
double align_disp =
param.MirrorAlignTangentDisp/fAlignmentPoint.Norm();
alignment.ScatterDirection(align_disp,rng);
}
else
{
// Alignment to a point in the focal plane
double stheta = sin(param.ReflectorFPAlignTheta);
double ctheta = cos(param.ReflectorFPAlignTheta);
double ttheta = stheta/ctheta;
double sphi = sin(param.ReflectorFPAlignPhi);
double cphi = cos(param.ReflectorFPAlignPhi);
double y_fp = fFPTranslation.y; // Distance to focal plane
Vec3D r_fp(y_fp*ttheta*sphi ,y_fp, -y_fp*ttheta*cphi);
Vec3D e_in(-stheta*sphi, ctheta, stheta*cphi);
Vec3D e_out = r_fp-position;
e_out /= e_out.Norm();
alignment = e_in;
Vec3D e_rot = e_in^e_out;
double strot2 = e_rot.Norm();
if(strot2 != 0)
{
double ctrot2 = e_in*e_out;
double trot2 = atan2(strot2,ctrot2);
e_rot *= 0.5*trot2/strot2;
alignment.Rotate(e_rot);
}
}
double focal_length =
param.MirrorFLength + rng.Normal()*param.MirrorFLengthDisp;
double spot_size;
if(param.MirrorSpotSizeDisp > 0)
spot_size = rng.GammaByMeanAndStdDev(param.MirrorSpotSize,
param.MirrorSpotSizeDisp);
else spot_size = param.MirrorSpotSize;
// If param.MirrorSpotSizePhotonFraction not set -- assume FWHM
if((param.MirrorSpotSizePhotonFraction>0.0)&&
(param.MirrorSpotSizePhotonFraction<1.0))
spot_size /=
2.0*sqrt(log(1.0/(1.0-param.MirrorSpotSizePhotonFraction)));
else spot_size /= 2.0*sqrt(log(2.0));
VSOMirror* mirror =
new VSOMirror(this, id, hexid, false, position, alignment,
focal_length, spot_size, param.MirrorDegradingFactor);
fMirrors.push_back(mirror);
fMirrorsByHexID.push_back(mirror);
id++;
}
// **************************************************************************
// Clear the PIXELSs table and repopulate it with randomly generated pixels
// **************************************************************************
for(std::vector<VSOPixel*>::iterator i=fPixels.begin();
i!=fPixels.end(); i++)delete *i;
fPixels.clear();
fPixelsByHexID.clear();
std::set<unsigned> pixels_missing;
Physics::tokenize(param.PixelMissingList,pixels_missing);
unsigned num_hex_pixel_rings =
unsigned(floor((fCameraDiameter/2.0)/fPixelSpacing))+2;
unsigned num_hex_pixel_sites =
3*num_hex_pixel_rings*(num_hex_pixel_rings+1)+1;
id = 0;
for(unsigned i=0; i<num_hex_pixel_sites; i++)
{
int hexid = i+1;
if(pixels_missing.find(hexid) != pixels_missing.end())
{
fPixelsByHexID.push_back(0);
continue; // skip pixel if on the missing list
}
Vec3D nominal_position;
// Compute the pixel's nominal position
nh_to_xy(&hexid, &nominal_position.x, &nominal_position.z);
if(fPixelParity)nominal_position.x=-nominal_position.x;
nominal_position.x *= fPixelSpacing;
nominal_position.z *= fPixelSpacing;
nominal_position.y = 0;
if(nominal_position.Norm() > fCameraDiameter/2.0)
{
fPixelsByHexID.push_back(0);
continue; // skip pixel if position too far out
}
nominal_position.Rotate(fFPRotation);
VSOPixel* pixel = new VSOPixel(this, id, hexid, false, nominal_position);
fPixels.push_back(pixel);
fPixelsByHexID.push_back(pixel);
id++;
}
}
// ****************************************************************************
// DATABASE functions
// ****************************************************************************
VSDBStatement* VSOTelescope::createInsertQuery(VSDatabase* db)
{
#if 0
return db->createInsertQuery(VSIMDB_TABLE_NAME_TELESCOPE,52);
#else
return db->createInsertQuery(VSIMDB_TABLE_NAME_TELESCOPE,38);
#endif
}
VSDBStatement* VSOTelescope::createSelectQuery(VSDatabase* db)
{
return db->createSelectQuery(VSIMDB_TABLE_NAME_TELESCOPE,
"OpticsID=?");
}
VSOTelescope* VSOTelescope::createFromDatabaseRow(VSDBStatement* stmt)
{
VSOTelescope* telescope = new VSOTelescope;
unsigned OID;
stmt->bindToResult(OID);
stmt->bindToResult(telescope->fID);
stmt->bindToResult(telescope->fTelescopeHexID);
stmt->bindToResult(telescope->fPos.x);
stmt->bindToResult(telescope->fPos.y);
stmt->bindToResult(telescope->fPos.z);
stmt->bindToResult(telescope->fDeltaY);
stmt->bindToResult(telescope->fAlphaX);
stmt->bindToResult(telescope->fAlphaY);
stmt->bindToResult(telescope->fElevation);
stmt->bindToResult(telescope->fAzimuth);
stmt->bindToResult(telescope->fTranslation.x);
stmt->bindToResult(telescope->fTranslation.y);
stmt->bindToResult(telescope->fTranslation.z);
stmt->bindToResult(telescope->fCurvatureRadius);
stmt->bindToResult(telescope->fAperture);
stmt->bindToResult(telescope->fFacetSpacing);
stmt->bindToResult(telescope->fFacetSize);
stmt->bindToResult(telescope->fReflectorRotation);
stmt->bindToResult(telescope->fAlignmentPoint.x);
stmt->bindToResult(telescope->fAlignmentPoint.y);
stmt->bindToResult(telescope->fAlignmentPoint.z);
stmt->bindToResult(telescope->fHexagonRingsN);
stmt->bindToResult(telescope->fReflectorIP);
stmt->bindToResult(telescope->fMirrorParity);
stmt->bindToResult(telescope->fFPTranslation.x);
stmt->bindToResult(telescope->fFPTranslation.y);
stmt->bindToResult(telescope->fFPTranslation.z);
stmt->bindToResult(telescope->fCameraDiameter);
stmt->bindToResult(telescope->fFieldOfView);
stmt->bindToResult(telescope->fCathodeDiameter);
stmt->bindToResult(telescope->fPixelSpacing);
stmt->bindToResult(telescope->fConcSurvProb);
stmt->bindToResult(telescope->fFPRotation.x);
stmt->bindToResult(telescope->fFPRotation.y);
stmt->bindToResult(telescope->fFPRotation.z);
stmt->bindToResult(telescope->fCameraIP);
stmt->bindToResult(telescope->fPixelParity);
#if 0
stmt->bindToResult(telescope->fHasSecondary);
stmt->bindToResult(telescope->fRefractiveIndex);
stmt->bindToResult(telescope->fRefractiveIndex1);
stmt->bindToResult(telescope->fRefractiveIndex2);
stmt->bindToResult(telescope->fCE1Parameter0);
stmt->bindToResult(telescope->fCE1Parameter2);
stmt->bindToResult(telescope->fCE1Parameter3);
stmt->bindToResult(telescope->fCE1Parameter4);
stmt->bindToResult(telescope->fCE1Parameter5);
stmt->bindToResult(telescope->fCE2Parameter0);
stmt->bindToResult(telescope->fCE2Parameter2);
stmt->bindToResult(telescope->fCE2Parameter3);
stmt->bindToResult(telescope->fCE2Parameter4);
stmt->bindToResult(telescope->fCE2Parameter5);
#endif
int row = stmt->retrieveNextRow();
if(row == -1)
{
std::cerr << stmt->getErrorMessage();
assert(0);
}
else if(row == 0)
{
delete telescope;
return 0;
}
return telescope;
}
void VSOTelescope::populateMirrorsAndPixelsFromDatabase(VSDatabase* db,
uint32_t optics_id)
{
VSDBStatement* stmt;
// **************************************************************************
// Clear the MIRRORs table and then re-populate it from the DB
// **************************************************************************
for(std::vector<VSOMirror*>::iterator i=fMirrors.begin();
i!=fMirrors.end(); i++)delete *i;
fMirrors.clear();
fMirrorsByHexID.clear();
int num_hex_mirror_sites = 3*fHexagonRingsN*(fHexagonRingsN+1)+1;
fMirrorsByHexID.resize(num_hex_mirror_sites);
stmt = VSOMirror::createSelectQuery(db);
assert(stmt);
stmt->bindToParam(optics_id);
stmt->bindToParam(fID);
assert(stmt->execute() >= 0);
while(VSOMirror* mirror = VSOMirror::createFromDatabaseRow(stmt,this))
{
if(mirror->id() >= fMirrors.size())
fMirrors.resize(mirror->id()+1);
fMirrors[mirror->id()]=mirror;
if(mirror->hexID() > fMirrorsByHexID.size())
fMirrorsByHexID.resize(mirror->hexID());
fMirrorsByHexID[mirror->hexID()-1]=mirror;
}
delete stmt;
// **************************************************************************
// Clear the PIXELs table and then re-populate it from the DB
// **************************************************************************
for(std::vector<VSOPixel*>::iterator i=fPixels.begin();
i!=fPixels.end(); i++)delete *i;
fPixels.clear();
fPixelsByHexID.clear();
unsigned num_hex_pixel_rings =
unsigned(floor((fCameraDiameter/2.0)/fPixelSpacing))+2;
unsigned num_hex_pixel_sites =
3*num_hex_pixel_rings*(num_hex_pixel_rings+1)+1;
fPixelsByHexID.resize(num_hex_pixel_sites);
stmt = VSOPixel::createSelectQuery(db);
assert(stmt);
stmt->bindToParam(optics_id);
stmt->bindToParam(fID);
assert(stmt->execute() >= 0);
while(VSOPixel* pixel = VSOPixel::createFromDatabaseRow(stmt,this))
{
if(pixel->id() >= fPixels.size())
fPixels.resize(pixel->id()+1);
fPixels[pixel->id()]=pixel;
if(pixel->hexID() > fPixelsByHexID.size())
fPixelsByHexID.resize(pixel->hexID());
fPixelsByHexID[pixel->hexID()-1]=pixel;
}
delete stmt;
// Recalculate rotation vector
calculateRotationVector();
return;
}
void VSOTelescope::writeToDatabase(VSDatabase* db, VSDBStatement* stmt,
uint32_t optics_id) const
{
stmt->bindToParam(optics_id);
stmt->bindToParam(fID);
stmt->bindToParam(fTelescopeHexID);
stmt->bindToParam(fPos.x);
stmt->bindToParam(fPos.y);
stmt->bindToParam(fPos.z);
stmt->bindToParam(fDeltaY);
stmt->bindToParam(fAlphaX);
stmt->bindToParam(fAlphaY);
stmt->bindToParam(fElevation);
stmt->bindToParam(fAzimuth);
stmt->bindToParam(fTranslation.x);
stmt->bindToParam(fTranslation.y);
stmt->bindToParam(fTranslation.z);
stmt->bindToParam(fCurvatureRadius);
stmt->bindToParam(fAperture);
stmt->bindToParam(fFacetSpacing);
stmt->bindToParam(fFacetSize);
stmt->bindToParam(fReflectorRotation);
stmt->bindToParam(fAlignmentPoint.x);
stmt->bindToParam(fAlignmentPoint.y);
stmt->bindToParam(fAlignmentPoint.z);
stmt->bindToParam(fHexagonRingsN);
stmt->bindToParam(fReflectorIP);
stmt->bindToParam(fMirrorParity);
stmt->bindToParam(fFPTranslation.x);
stmt->bindToParam(fFPTranslation.y);
stmt->bindToParam(fFPTranslation.z);
stmt->bindToParam(fCameraDiameter);
stmt->bindToParam(fFieldOfView);
stmt->bindToParam(fCathodeDiameter);
stmt->bindToParam(fPixelSpacing);
stmt->bindToParam(fConcSurvProb);
stmt->bindToParam(fFPRotation.x);
stmt->bindToParam(fFPRotation.y);
stmt->bindToParam(fFPRotation.z);
stmt->bindToParam(fCameraIP);
stmt->bindToParam(fPixelParity);
#if 0
stmt->bindToParam(fHasSecondary);
stmt->bindToParam(fRefractiveIndex);
stmt->bindToParam(fRefractiveIndex1);
stmt->bindToParam(fRefractiveIndex2);
stmt->bindToParam(fCE1Parameter0);
stmt->bindToParam(fCE1Parameter2);
stmt->bindToParam(fCE1Parameter3);
stmt->bindToParam(fCE1Parameter4);
stmt->bindToParam(fCE1Parameter5);
stmt->bindToParam(fCE2Parameter0);
stmt->bindToParam(fCE2Parameter2);
stmt->bindToParam(fCE2Parameter3);
stmt->bindToParam(fCE2Parameter4);
stmt->bindToParam(fCE2Parameter5);
#endif
assert(stmt->execute() == 1);
VSDBStatement* sub_stmt;
sub_stmt = VSOMirror::createInsertQuery(db);
assert(sub_stmt);
for(std::vector<VSOMirror*>::const_iterator i = fMirrors.begin();
i != fMirrors.end(); i++)(*i)->writeToDatabase(sub_stmt, optics_id);
delete(sub_stmt);
sub_stmt = VSOPixel::createInsertQuery(db);
assert(sub_stmt);
for(std::vector<VSOPixel*>::const_iterator i = fPixels.begin();
i != fPixels.end(); i++)(*i)->writeToDatabase(sub_stmt, optics_id);
delete(sub_stmt);
}
void VSOTelescope::createTelescopeTable(VSDatabase* db)
{
VSOTelescope temp; // stupid to create this --- C++ should have a "typeof" operator (g++ does but it
// is not portable .. and doesn't work in a static function anyway)
unsigned OID;
db->createTable(VSIMDB_TABLE_NAME_TELESCOPE,
db->sqlSpecOf("OpticsID",OID,true,"NOT NULL")+
db->sqlSpecOf("TelescopeID",temp.fID,false,"NOT NULL")+
db->sqlSpecOf("TelescopeHexID",temp.fTelescopeHexID,false,"NOT NULL")+
db->sqlSpecOf("PosX",temp.fPos.x,false,"NOT NULL")+
db->sqlSpecOf("PosY",temp.fPos.y,false,"NOT NULL")+
db->sqlSpecOf("PosZ",temp.fPos.z,false,"NOT NULL")+
db->sqlSpecOf("DeltaY",temp.fDeltaY,false,"NOT NULL")+
db->sqlSpecOf("AlphaX",temp.fAlphaX,false,"NOT NULL")+
db->sqlSpecOf("AlphaY",temp.fAlphaY,false,"NOT NULL")+
db->sqlSpecOf("Elevation",temp.fElevation,false,"NOT NULL")+
db->sqlSpecOf("Azimuth",temp.fAzimuth,false,"NOT NULL")+
db->sqlSpecOf("TranslationX",temp.fTranslation.x,false,"NOT NULL")+
db->sqlSpecOf("TranslationY",temp.fTranslation.y,false,"NOT NULL")+
db->sqlSpecOf("TranslationZ",temp.fTranslation.z,false,"NOT NULL")+
db->sqlSpecOf("CurvatureRadius",temp.fCurvatureRadius,false,"NOT NULL")+
db->sqlSpecOf("Aperture",temp.fAperture,false,"NOT NULL")+
db->sqlSpecOf("FacetSpacing",temp.fFacetSpacing,false,"NOT NULL")+
db->sqlSpecOf("FacetSize",temp.fFacetSize,false,"NOT NULL")+
db->sqlSpecOf("ReflectorRotation",temp.fReflectorRotation,false,"NOT NULL")+
db->sqlSpecOf("AlignmentPointX",temp.fAlignmentPoint.x,false,"NOT NULL")+
db->sqlSpecOf("AlignmentPointY",temp.fAlignmentPoint.y,false,"NOT NULL")+
db->sqlSpecOf("AlignmentPointZ",temp.fAlignmentPoint.z,false,"NOT NULL")+
db->sqlSpecOf("HexagonRingsN",temp.fHexagonRingsN,false,"NOT NULL")+
db->sqlSpecOf("ReflectorIP",temp.fReflectorIP,false,"NOT NULL")+
db->sqlSpecOf("MirrorParity",temp.fMirrorParity,false,"NOT NULL")+
db->sqlSpecOf("FPTranslationX",temp.fFPTranslation.x,false,"NOT NULL")+
db->sqlSpecOf("FPTranslationY",temp.fFPTranslation.y,false,"NOT NULL")+
db->sqlSpecOf("FPTranslationZ",temp.fFPTranslation.z,false,"NOT NULL")+
db->sqlSpecOf("CameraDiameter",temp.fCameraDiameter,false,"NOT NULL")+
db->sqlSpecOf("FieldOfView",temp.fFieldOfView,false,"NOT NULL")+
db->sqlSpecOf("PixelDiameter",temp.fCathodeDiameter,false,"NOT NULL")+
db->sqlSpecOf("PixelSpacing",temp.fPixelSpacing,false,"NOT NULL")+
db->sqlSpecOf("ConcSurvProb",temp.fConcSurvProb,false,"NOT NULL")+
db->sqlSpecOf("FPRotationX",temp.fFPRotation.x,false,"NOT NULL")+
db->sqlSpecOf("FPRotationY",temp.fFPRotation.y,false,"NOT NULL")+
db->sqlSpecOf("FPRotationZ",temp.fFPRotation.z,false,"NOT NULL")+
db->sqlSpecOf("CameraIP",temp.fCameraIP,false,"NOT NULL")+
db->sqlSpecOf("PixelParity",temp.fPixelParity,false,"NOT NULL")+
#if 0
db->sqlSpecOf("HasSecondary",temp.fHasSecondary,false,"NOT NULL")+
db->sqlSpecOf("RefractiveIndex",temp.fRefractiveIndex,false,"NOT NULL")+
db->sqlSpecOf("RefractiveIndex1",temp.fRefractiveIndex1,false,"NOT NULL")+
db->sqlSpecOf("RefractiveIndex2",temp.fRefractiveIndex2,false,"NOT NULL")+
db->sqlSpecOf("CE1Parameter0",temp.fCE1Parameter0,false,"NOT NULL")+
db->sqlSpecOf("CE1Parameter2",temp.fCE1Parameter2,false,"NOT NULL")+
db->sqlSpecOf("CE1Parameter3",temp.fCE1Parameter3,false,"NOT NULL")+
db->sqlSpecOf("CE1Parameter4",temp.fCE1Parameter4,false,"NOT NULL")+
db->sqlSpecOf("CE1Parameter5",temp.fCE1Parameter5,false,"NOT NULL")+
db->sqlSpecOf("CE2Parameter0",temp.fCE1Parameter0,false,"NOT NULL")+
db->sqlSpecOf("CE2Parameter2",temp.fCE1Parameter2,false,"NOT NULL")+
db->sqlSpecOf("CE2Parameter3",temp.fCE1Parameter3,false,"NOT NULL")+
db->sqlSpecOf("CE2Parameter4",temp.fCE1Parameter4,false,"NOT NULL")+
db->sqlSpecOf("CE2Parameter5",temp.fCE1Parameter5,false,"NOT NULL")+
#endif
", PRIMARY KEY ( OpticsID, TelescopeID )",
VSDatabase::FLAG_NO_ERROR_ON_EXIST_OR_NOT_EXIST);
}
void VSOTelescope::dumpShort(std::ostream& stream) const
{
stream
<< "TELESCOPE "
<< VSDataConverter::toString(fID) << ' '
<< VSDataConverter::toString(fTelescopeHexID) << ' '
<< VSDataConverter::toString(fMirrors.size()) << ' '
<< VSDataConverter::toString(fPixels.size()) << ' '
<< VSDataConverter::toString(fPos.x) << ' '
<< VSDataConverter::toString(fPos.y) << ' '
<< VSDataConverter::toString(fPos.z) << ' '
<< VSDataConverter::toString(fDeltaY) << ' '
<< VSDataConverter::toString(fAlphaX) << ' '
<< VSDataConverter::toString(fAlphaY) << ' '
<< VSDataConverter::toString(fElevation) << ' '
<< VSDataConverter::toString(fAzimuth) << ' '
<< VSDataConverter::toString(fTranslation.x) << ' '
<< VSDataConverter::toString(fTranslation.y) << ' '
<< VSDataConverter::toString(fTranslation.z) << ' '
<< VSDataConverter::toString(fCurvatureRadius) << ' '
<< VSDataConverter::toString(fAperture) << ' '
<< VSDataConverter::toString(fFacetSpacing) << ' '
<< VSDataConverter::toString(fFacetSize) << ' '
<< VSDataConverter::toString(fReflectorRotation) << ' '
<< VSDataConverter::toString(fAlignmentPoint.x) << ' '
<< VSDataConverter::toString(fAlignmentPoint.y) << ' '
<< VSDataConverter::toString(fAlignmentPoint.z) << ' '
<< VSDataConverter::toString(fHexagonRingsN) << ' '
<< VSDataConverter::toString(fReflectorIP) << ' '
<< VSDataConverter::toString(fMirrorParity) << ' '
<< VSDataConverter::toString(fFPTranslation.x) << ' '
<< VSDataConverter::toString(fFPTranslation.y) << ' '
<< VSDataConverter::toString(fFPTranslation.z) << ' '
<< VSDataConverter::toString(fCameraDiameter) << ' '
<< VSDataConverter::toString(fFieldOfView) << ' '
<< VSDataConverter::toString(fCathodeDiameter) << ' '
<< VSDataConverter::toString(fPixelSpacing) << ' '
<< VSDataConverter::toString(fConcSurvProb) << ' '
<< VSDataConverter::toString(fFPRotation.x) << ' '
<< VSDataConverter::toString(fFPRotation.y) << ' '
<< VSDataConverter::toString(fFPRotation.z) << ' '
<< VSDataConverter::toString(fCameraIP) << ' '
<< VSDataConverter::toString(fPixelParity) << ' '
#if 0
<< VSDataConverter::toString(fHasSecondary) << ' '
<< VSDataConverter::toString(fRefractiveIndex) << ' '
<< VSDataConverter::toString(fRefractiveIndex1) << ' '
<< VSDataConverter::toString(fRefractiveIndex2) << ' '
<< VSDataConverter::toString(fCE1Parameter0) << ' '
<< VSDataConverter::toString(fCE1Parameter2) << ' '
<< VSDataConverter::toString(fCE1Parameter3) << ' '
<< VSDataConverter::toString(fCE1Parameter4) << ' '
<< VSDataConverter::toString(fCE1Parameter5) << ' '
<< VSDataConverter::toString(fCE1Parameter0) << ' '
<< VSDataConverter::toString(fCE1Parameter2) << ' '
<< VSDataConverter::toString(fCE1Parameter3) << ' '
<< VSDataConverter::toString(fCE1Parameter4) << ' '
<< VSDataConverter::toString(fCE1Parameter5)
#endif
<< std::endl;
for(std::vector<VSOMirror*> ::const_iterator i = fMirrors.begin();
i!=fMirrors.end(); i++)
(*i)->dumpShort(stream);
for(std::vector<VSOPixel*> ::const_iterator i = fPixels.begin();
i!=fPixels.end(); i++)
(*i)->dumpShort(stream);
}
void VSOTelescope::dump(std::ostream& stream, unsigned l) const
{
stream
<< FDAV("Telescope ID", fID, "", 30, l) << std::endl
<< FDAV("Telescope Hex ID", fTelescopeHexID, "", 30, l) << std::endl
<< FDAV("Num Mirrors", fMirrors.size(), "", 30, l) << std::endl
<< FDAV("Num Pixels", fPixels.size(), "", 30, l) << std::endl
<< FDAV("Position X", fPos.x, "cm", 30, l) << std::endl
<< FDAV("Position Y", fPos.y, "cm", 30, l) << std::endl
<< FDAV("Position Z", fPos.z, "cm", 30, l) << std::endl
<< FDAV("Delta Y", fDeltaY, "rad", 30, l) << std::endl
<< FDAV("Alpha X", fAlphaX, "rad", 30, l) << std::endl
<< FDAV("Alpha Y", fAlphaY, "rad", 30, l) << std::endl
<< FDAV("Elevation", fElevation, "rad", 30, l) << std::endl
<< FDAV("Azimuth", fAzimuth, "rad", 30, l) << std::endl
<< FDAV("Translation X", fTranslation.x, "cm", 30, l) << std::endl
<< FDAV("Translation Y", fTranslation.y, "cm", 30, l) << std::endl
<< FDAV("Translation Z", fTranslation.z, "cm", 30, l) << std::endl
<< FDAV("Curvature Radius", fCurvatureRadius, "cm", 30, l) << std::endl
<< FDAV("Aperture", fAperture, "cm", 30, l) << std::endl
<< FDAV("Facet Spacing", fFacetSpacing, "cm", 30, l) << std::endl
<< FDAV("Facet Size", fFacetSize, "cm", 30, l) << std::endl
<< FDAV("Reflector Rotation", fReflectorRotation, "rad", 30, l) << std::endl
<< FDAV("Alignment Point X", fAlignmentPoint.x, "cm", 30, l) << std::endl
<< FDAV("Alignment Point Y", fAlignmentPoint.y, "cm", 30, l) << std::endl
<< FDAV("Alignment Point Z", fAlignmentPoint.z, "cm", 30, l) << std::endl
<< FDAV("Num Mirror Hexagon Rings", fHexagonRingsN, "", 30, l) << std::endl
<< FDAV("Reflector IP", fReflectorIP, "cm", 30, l) << std::endl
<< FDAV("Mirror Parity", fMirrorParity, "", 30, l) << std::endl
<< FDAV("FP Translation X", fFPTranslation.x, "cm", 30, l) << std::endl
<< FDAV("FP Translation Y", fFPTranslation.y, "cm", 30, l) << std::endl
<< FDAV("FP Translation Z", fFPTranslation.z, "cm", 30, l) << std::endl
<< FDAV("CameraDiameter", fCameraDiameter, "cm", 30, l) << std::endl
<< FDAV("Field Of View", fFieldOfView, "deg", 30, l) << std::endl
<< FDAV("Pixel Diameter", fCathodeDiameter, "cm", 30, l) << std::endl
<< FDAV("Pixel Spacing", fPixelSpacing, "cm", 30, l) << std::endl
<< FDAV("Conc Surv Prob", fConcSurvProb, "", 30, l) << std::endl
<< FDAV("FP Rotation X", fFPRotation.x, "rad", 30, l) << std::endl
<< FDAV("FP Rotation Y", fFPRotation.y, "rad", 30, l) << std::endl
<< FDAV("FP Rotation Z", fFPRotation.z, "rad", 30, l) << std::endl
<< FDAV("Camera IP", fCameraIP, "cm", 30, l) << std::endl
<< FDAV("Pixel Parity", fPixelParity, "", 30, l) << std::endl;
#if 0
<< FDAV("Has Secondary", fHasSecondary, "", 30, l) << std::endl
<< FDAV("Refractive Index", fRefractiveIndex, "", 30, l) << std::endl
<< FDAV("Refractive Index 1", fRefractiveIndex1, "", 30, l) << std::endl
<< FDAV("Refractive Index 2", fRefractiveIndex2, "", 30, l) << std::endl
<< FDAV("CE1 Parameter 0", fCE1Parameter0, "", 30, l) << std::endl
<< FDAV("CE1 Parameter 2", fCE1Parameter2, "", 30, l) << std::endl
<< FDAV("CE1 Parameter 3", fCE1Parameter3, "", 30, l) << std::endl
<< FDAV("CE1 Parameter 4", fCE1Parameter4, "", 30, l) << std::endl
<< FDAV("CE1 Parameter 5", fCE1Parameter5, "", 30, l) << std::endl
<< FDAV("CE2 Parameter 0", fCE1Parameter0, "", 30, l) << std::endl
<< FDAV("CE2 Parameter 2", fCE1Parameter2, "", 30, l) << std::endl
<< FDAV("CE2 Parameter 3", fCE1Parameter3, "", 30, l) << std::endl
<< FDAV("CE2 Parameter 4", fCE1Parameter4, "", 30, l) << std::endl
<< FDAV("CE2 Parameter 5", fCE1Parameter5, "", 30, l) << std::endl;
#endif
for(std::vector<VSOMirror*> ::const_iterator i = fMirrors.begin();
i!=fMirrors.end(); i++)
{
stream << std::endl;
(*i)->dump(stream,l+1);
}
for(std::vector<VSOPixel*> ::const_iterator i = fPixels.begin();
i!=fPixels.end(); i++)
{
stream << std::endl;
(*i)->dump(stream,l+1);
}
}
VSOTelescope* VSOTelescope::createFromShortDump(std::istream& stream)
{
std::string line;
std::getline(stream,line);
if(line.empty())return 0;
std::istringstream linestream(line);
VSOTelescope* telescope = new VSOTelescope;
std::string keyword;
linestream >> keyword;
assert(keyword==std::string("TELESCOPE"));
unsigned mirrors_size;
unsigned pixels_size;
linestream
>> telescope->fID
>> telescope->fTelescopeHexID
>> mirrors_size
>> pixels_size
>> telescope->fPos.x
>> telescope->fPos.y
>> telescope->fPos.z
>> telescope->fDeltaY
>> telescope->fAlphaX
>> telescope->fAlphaY
>> telescope->fElevation
>> telescope->fAzimuth
>> telescope->fTranslation.x
>> telescope->fTranslation.y
>> telescope->fTranslation.z
>> telescope->fCurvatureRadius
>> telescope->fAperture
>> telescope->fFacetSpacing
>> telescope->fFacetSize
>> telescope->fReflectorRotation
>> telescope->fAlignmentPoint.x
>> telescope->fAlignmentPoint.y
>> telescope->fAlignmentPoint.z
>> telescope->fHexagonRingsN
>> telescope->fReflectorIP
>> telescope->fMirrorParity
>> telescope->fFPTranslation.x
>> telescope->fFPTranslation.y
>> telescope->fFPTranslation.z
>> telescope->fCameraDiameter
>> telescope->fFieldOfView
>> telescope->fCathodeDiameter
>> telescope->fPixelSpacing
>> telescope->fConcSurvProb
>> telescope->fFPRotation.x
>> telescope->fFPRotation.y
>> telescope->fFPRotation.z
>> telescope->fCameraIP
>> telescope->fPixelParity
#if 0
>> telescope->fHasSecondary
>> telescope->fRefractiveIndex
>> telescope->fRefractiveIndex1
>> telescope->fRefractiveIndex2
>> telescope->fCE1Parameter0
>> telescope->fCE1Parameter2
>> telescope->fCE1Parameter3
>> telescope->fCE1Parameter4
>> telescope->fCE1Parameter5
>> telescope->fCE1Parameter0
>> telescope->fCE1Parameter2
>> telescope->fCE1Parameter3
>> telescope->fCE1Parameter4
>> telescope->fCE1Parameter5
#endif
;
if(!linestream)
{
delete telescope;
return 0;
}
for(unsigned i=0; i<mirrors_size; i++)
{
VSOMirror* mirror = VSOMirror::createFromShortDump(stream, telescope);
if(mirror==0)
{
delete telescope;
return 0;
}
if(mirror->id() >= telescope->fMirrors.size())
telescope->fMirrors.resize(mirror->id()+1);
telescope->fMirrors[mirror->id()]=mirror;
if(mirror->hexID() > telescope->fMirrorsByHexID.size())
telescope->fMirrorsByHexID.resize(mirror->hexID());
telescope->fMirrorsByHexID[mirror->hexID()-1]=mirror;
}
for(unsigned i=0; i<pixels_size; i++)
{
VSOPixel* pixel = VSOPixel::createFromShortDump(stream, telescope);
if(pixel==0)
{
delete telescope;
return 0;
}
if(pixel->id() >= telescope->fPixels.size())
telescope->fPixels.resize(pixel->id()+1);
telescope->fPixels[pixel->id()]=pixel;
if(pixel->hexID() > telescope->fPixelsByHexID.size())
telescope->fPixelsByHexID.resize(pixel->hexID());
telescope->fPixelsByHexID[pixel->hexID()-1]=pixel;
}
// Recalculate rotation vector
telescope->calculateRotationVector();
return telescope;
}
| 34.862966 | 102 | 0.66505 | [
"vector"
] |
4fd074cd6fd878549ce73d4f0b7d3b6e8231b811 | 4,500 | hpp | C++ | src/common/boost/fiber/detail/fiber_id.hpp | ZhiQiAnSecFork/ssf | 2caaaab4ef8def710f960b8ea96937f6a80fe060 | [
"MIT"
] | 1,364 | 2015-06-01T20:30:27.000Z | 2022-03-31T20:55:50.000Z | src/common/boost/fiber/detail/fiber_id.hpp | ZhiQiAnSecFork/ssf | 2caaaab4ef8def710f960b8ea96937f6a80fe060 | [
"MIT"
] | 93 | 2015-06-09T04:32:53.000Z | 2022-03-08T21:23:02.000Z | src/common/boost/fiber/detail/fiber_id.hpp | ZhiQiAnSecFork/ssf | 2caaaab4ef8def710f960b8ea96937f6a80fe060 | [
"MIT"
] | 238 | 2015-06-08T13:38:33.000Z | 2022-03-25T00:30:39.000Z | //
// fiber/detail/fiber_id.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014-2015
//
#ifndef SSF_COMMON_BOOST_ASIO_FIBER_DETAIL_FIBER_ID_HPP_
#define SSF_COMMON_BOOST_ASIO_FIBER_DETAIL_FIBER_ID_HPP_
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <cstdint>
#include <array>
#include <vector>
#include <boost/asio/buffer.hpp>
namespace boost {
namespace asio {
namespace fiber {
namespace detail {
/// Class handling the id field of the fiber header
class fiber_id
{
public:
/// Type for a port
typedef uint32_t port_type;
/// Type for a remote fiber port
typedef port_type remote_port_type;
/// Type for a local fiber port
typedef port_type local_port_type;
public:
/// Constant used with the class
enum { field_number = 2 };
public:
/// Raw data structure to contain a fiber id
struct raw_fiber_id
{
/// Local port field
local_port_type local_port;
/// Remote port field
remote_port_type remote_port;
};
/// Get a raw id
raw_fiber_id get_raw()
{
raw_fiber_id raw;
raw.local_port = local_port_;
raw.remote_port = remote_port_;
return raw;
}
public:
/// Constructor setting only the remote port
/**
* @param remote_port The remote port to set in the id
*/
explicit fiber_id(remote_port_type remote_port)
: remote_port_(remote_port), local_port_(0)
{
}
/// Constructor setting both ports
/**
* @param remote_port The remote port to set in the id
* @param local_port The local port to set in the id
*/
fiber_id(remote_port_type remote_port, local_port_type local_port)
: remote_port_(remote_port), local_port_(local_port)
{
}
/// Operator< to enable std::map support
/**
* @param fib_id The fiber id to be compared to
*/
bool operator<(const fiber_id& fib_id) const
{
if (remote_port_ < fib_id.remote_port_)
{
return true;
}
else
{
return ((remote_port_ == fib_id.remote_port_) &&
(local_port_ < fib_id.local_port_));
}
}
/// Get the return id
fiber_id returning_id() const { return fiber_id(local_port_, remote_port_); }
/// Get the remote port
remote_port_type remote_port() const { return remote_port_; }
/// Get the local port
local_port_type local_port() const { return local_port_; }
/// Set the local port
/**
* @param src The local port to set in the id
*/
void set_local_port(local_port_type src) { local_port_ = src; }
/// Set the remote port
/**
* @param dst The remote port to set in the id
*/
void set_remote_port(remote_port_type dst) { remote_port_ = dst; }
/// Check if both port are set
bool is_set() const { return (remote_port_ != 0) && (local_port_ != 0); }
/// Get a buffer to receive a fiber ID
std::array<boost::asio::mutable_buffer, field_number> buffer()
{
std::array<boost::asio::mutable_buffer, field_number> buf = {
{ boost::asio::buffer(&local_port_, sizeof(local_port_)),
boost::asio::buffer(&remote_port_, sizeof(remote_port_)), } };
return buf;
}
/// Get a buffer to send a fiber ID
std::array<boost::asio::const_buffer, field_number> const_buffer()
{
std::array<boost::asio::const_buffer, field_number> buf = {
{ boost::asio::buffer(&local_port_, sizeof(local_port_)),
boost::asio::buffer(&remote_port_, sizeof(remote_port_)), } };
return buf;
}
/// Fill the given buffer with the fiber id fields
/**
* @param buffers The vector of buffers to fill
*/
void fill_buffer(std::vector<boost::asio::mutable_buffer>& buffers)
{
buffers.push_back(boost::asio::buffer(&local_port_, sizeof(local_port_)));
buffers.push_back(boost::asio::buffer(&remote_port_, sizeof(remote_port_)));
}
/// Fill the given buffer with the fiber id fields
/**
* @param buffers The vector of buffers to fill
*/
void fill_const_buffer(std::vector<boost::asio::const_buffer>& buffers)
{
buffers.push_back(boost::asio::buffer(&local_port_, sizeof(local_port_)));
buffers.push_back(boost::asio::buffer(&remote_port_, sizeof(remote_port_)));
}
/// Get the size of a fiber ID
static uint16_t pod_size()
{
return sizeof(local_port_type)+sizeof(remote_port_type);
}
private:
remote_port_type remote_port_;
local_port_type local_port_;
};
} // namespace detail
} // namespace fiber
} // namespace asio
} // namespace boost
#endif // SSF_COMMON_BOOST_ASIO_FIBER_DETAIL_FIBER_ID_HPP_
| 24.861878 | 80 | 0.683778 | [
"vector"
] |
4fd11bdc770626f0f707f7b7784b92344c5bb79f | 11,405 | cpp | C++ | src/usb/UsbScanTransferIn.cpp | matthewrankin/uldaq | 7568a411edecbe28dc73972358bc73c0b2fdb071 | [
"MIT"
] | null | null | null | src/usb/UsbScanTransferIn.cpp | matthewrankin/uldaq | 7568a411edecbe28dc73972358bc73c0b2fdb071 | [
"MIT"
] | null | null | null | src/usb/UsbScanTransferIn.cpp | matthewrankin/uldaq | 7568a411edecbe28dc73972358bc73c0b2fdb071 | [
"MIT"
] | null | null | null | /*
* UsbScanTransferIn.cpp
*
* Created on: Sep 18, 2015
* Author: root
*/
#include <cstring>
#include <unistd.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include "UsbScanTransferIn.h"
#include "../DaqDeviceId.h"
#include "../utility/UlLock.h"
#define STAGE_RATE 0.010
namespace ul
{
UsbScanTransferIn::UsbScanTransferIn(const UsbDaqDevice& daqDevice) : mUsbDevice(daqDevice), mXferState(TS_IDLE)
{
mIoDevice = NULL;
mDaqEventHandler = daqDev().eventHandler();
mStageRate = STAGE_RATE;
mXferStateThreadHandle = 0;
mTerminateXferStateThread = false;
mNumXferPending = 0;
mStageSize = 0;
mResubmit = true;
mNewSamplesReceived = false;
mXferError = ERR_NO_ERROR;
//UlLock::initMutex(mXferMutex, PTHREAD_MUTEX_RECURSIVE);
UlLock::initMutex(mXferStateThreadHandleMutex, PTHREAD_MUTEX_RECURSIVE);
UlLock::initMutex(mStopXferMutex, PTHREAD_MUTEX_RECURSIVE);
memset(&mXfer, 0, sizeof(mXfer));
mEnabledDaqEvents = (DaqEventType) 0;
mAvailableCount = 0;
mCurrentEventCount = 0;
mNextEventCount = 0;
}
UsbScanTransferIn::~UsbScanTransferIn()
{
//UlLock::destroyMutex(mXferMutex);
UlLock::destroyMutex(mXferStateThreadHandleMutex);
UlLock::destroyMutex(mStopXferMutex);
}
void UsbScanTransferIn::initilizeTransfers(IoDevice* ioDevice, int endpointAddress, int stageSize)
{
UlError err = ERR_NO_ERROR;
mIoDevice = ioDevice;
mXferError = ERR_NO_ERROR;
mStageSize = stageSize;
mXferState = TS_RUNNING;
mResubmit = true;
mNewSamplesReceived = false;
memset(&mXfer, 0, sizeof(mXfer));
if(mStageSize > MAX_STAGE_SIZE)
mStageSize = MAX_STAGE_SIZE;
// Just in case thread is not terminated
terminateXferStateThread();
int numOfXfers;
numOfXfers = MAX_XFER_COUNT;
mXferEvent.reset();
mXferDoneEvent.reset();
mEnabledDaqEvents = mDaqEventHandler->getEnabledEventTypes();
mDaqEventHandler->resetInputEvents(mEnabledDaqEvents);
if(mEnabledDaqEvents & DE_ON_DATA_AVAILABLE)
{
mAvailableCount = mDaqEventHandler->getEventParameter(DE_ON_DATA_AVAILABLE) * mIoDevice->scanChanCount();
mNextEventCount = mAvailableCount;
}
for(int i = 0; i < numOfXfers; i++)
{
mXfer[i].transfer = mUsbDevice.allocTransfer();
err = mUsbDevice.asyncBulkTransfer(mXfer[i].transfer, endpointAddress, mXfer[i].buffer, mStageSize, tarnsferCallback, this, 0);
if(err)
{
if(mNumXferPending)
stopTransfers();
throw(UlException(err));
}
mNumXferPending++;
}
startXferStateThread();
}
void UsbScanTransferIn::initilizeOnDemandTransfer(IoDevice* ioDevice, int endpointAddress, int stageSize)
{
UlError err = ERR_NO_ERROR;
mIoDevice = ioDevice;
mXferError = ERR_NO_ERROR;
mStageSize = stageSize;
mXferState = TS_RUNNING;
mResubmit = true;
mNewSamplesReceived = false;
memset(&mXfer, 0, sizeof(mXfer));
if(mStageSize > MAX_STAGE_SIZE)
mStageSize = MAX_STAGE_SIZE;
// Just in case thread is not terminated
terminateXferStateThread();
mXferEvent.reset();
mXferDoneEvent.reset();
mXfer[0].transfer = mUsbDevice.allocTransfer();
err = mUsbDevice.asyncBulkTransfer(mXfer[0].transfer, endpointAddress, mXfer[0].buffer, mStageSize, tarnsferCallback, this, 0);
if(err)
throw(UlException(err));
mNumXferPending++;
}
void LIBUSB_CALL UsbScanTransferIn::tarnsferCallback(libusb_transfer* transfer)
{
UsbScanTransferIn* This = (UsbScanTransferIn*)transfer->user_data;
//This->printTransferIndex(transfer); // uncomment for debugging
//UlLock lock(This->mXferMutex); //uncomment if needed
if(transfer->status == LIBUSB_TRANSFER_COMPLETED)
{
if(!This->mIoDevice->allScanSamplesTransferred() && This->mResubmit)
{
This->mIoDevice->processScanData(transfer);
unsigned long long samplesTransfered = This->mIoDevice->totalScanSamplesTransferred();
if(This->mEnabledDaqEvents & DE_ON_DATA_AVAILABLE)
{
if(isDataAvailable(samplesTransfered, This->mCurrentEventCount, This->mNextEventCount))
{
This->mCurrentEventCount = samplesTransfered;
This->mNextEventCount = This->mCurrentEventCount + This->mAvailableCount;
This->mDaqEventHandler->setCurrentEventAndData(DE_ON_DATA_AVAILABLE, This->mCurrentEventCount / This->mIoDevice->scanChanCount());
}
}
}
//check if processScanData() has set allScanSamplesTransferred to true, if that's the case then no need to resubmit
//the request. Also we should not set mNewSamplesReceived to true to prevent sending the tmr command
if(!This->mIoDevice->allScanSamplesTransferred() && This->mResubmit)
{
libusb_submit_transfer(transfer);
This->mNewSamplesReceived = true;
}
else
This->mNumXferPending--;
}
else
This->mNumXferPending--;
if(This->mNumXferPending == 0)
{
//This->terminateXferStateThread();
This->mTerminateXferStateThread = true;
// check the status of the last request to see if the device is unplugged
// do not read transfer->status because the transfer objects are freed in stopTransfers()
// when mNumXferPending is set to zero
if(transfer->status == LIBUSB_TRANSFER_ERROR || transfer->status == LIBUSB_TRANSFER_NO_DEVICE)
{
This->mXferError = ERR_DEAD_DEV;
}
// Note: Do not access the transfer object beyond here, because as soon as mXferState is set to TS_IDLE
// the stopTransfers() function calls libusb_free_transfer on all transfers and transfer objects here are not valid anymore
This->mXferState = TS_IDLE;
This->mXferDoneEvent.signal();
/*if((This->mEnabledDaqEvents & DE_ON_END_OF_INPUT_SCAN) && This->mIoDevice->allScanSamplesTransferred())
{
This->mDaqEventHandler->setCurrentEventAndData(DE_ON_END_OF_INPUT_SCAN, 0);
}*/
}
This->mXferEvent.signal();
}
void UsbScanTransferIn::stopTransfers()
{
FnLog log("UsbScanTransferIn::stopTransfers");
UlLock lock(mStopXferMutex);
mResubmit = false;
usleep(1000);
for(int i = 0; i < MAX_XFER_COUNT; i++)
{
if(mXfer[i].transfer)
libusb_cancel_transfer(mXfer[i].transfer);
}
if(mXferState == TS_RUNNING)
{
mXferDoneEvent.wait_for_signal(1000000); // wait up to 1 second
}
if(mNumXferPending > 0)
std::cout << "##### error still xfer pending. mNumXferPending =" << mNumXferPending << std::endl;
for(int i = 0; i < MAX_XFER_COUNT; i++)
{
if(mXfer[i].transfer)
{
libusb_free_transfer(mXfer[i].transfer);
mXfer[i].transfer = NULL;
}
}
}
void UsbScanTransferIn::startXferStateThread()
{
FnLog log("UsbScanTransferIn::startXferStateThread");
pthread_attr_t attr;
int status = pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if(!status)
{
mTerminateXferStateThread = false;
mStateThreadInitEvent.reset();
status = pthread_create(&mXferStateThreadHandle, &attr, &xferStateThread, this);
#ifndef __APPLE__
pthread_setname_np(mXferStateThreadHandle, "xfer_state_td");
#endif
if(status)
UL_LOG("#### Unable to start the event handler thread");
else
{
mStateThreadInitEvent.wait_for_signal(100);
}
status = pthread_attr_destroy(&attr);
}
else
UL_LOG("#### Unable to initialize attributes for the event handler thread");
}
void* UsbScanTransferIn::xferStateThread(void *arg)
{
UsbScanTransferIn* This = (UsbScanTransferIn*) arg;
int count = 0;
unsigned long long timeout = 250000; // first timeout
int niceVal = 0; // make sure this thread does not get a high priority if the parent thread is running with high priority
setpriority(PRIO_PROCESS, 0, niceVal);
This->mStateThreadInitEvent.signal();
while (!This->mTerminateXferStateThread)
{
while(This->mXferEvent.wait_for_signal(timeout) != ETIMEDOUT) // wait up to 100 ms (initial timeout is 250 ms)
{
timeout = 100000;
if(!This->mTerminateXferStateThread)
{
if(!This->mIoDevice->recycleMode() && This->mIoDevice->allScanSamplesTransferred())
{
This->mIoDevice->terminateScan();
This->mTerminateXferStateThread = true;
break;
}
count++;
if(count == 100)
{
// this function updates scan parameters such as TCR value for NI devices
This->mIoDevice->updateScanParam(SCAN_PARAM_TCR);
count = 0;
}
if(This->mNewSamplesReceived)
{
This->mIoDevice->updateScanParam(SCAN_PARAM_TMR);
This->mNewSamplesReceived = false;
}
}
else
break;
}
if(!This->mTerminateXferStateThread)
{
UL_LOG("#### retrieving status");
This->mXferError = This->mIoDevice->checkScanState();
if(This->mXferError)
{
if(This->mEnabledDaqEvents & DE_ON_INPUT_SCAN_ERROR)
{
This->mDaqEventHandler->setCurrentEventAndData(DE_ON_INPUT_SCAN_ERROR, This->mXferError);
}
This->mIoDevice->terminateScan();
}
else
{
// this function updates scan parameters such as TCR value for NI devices
This->mIoDevice->updateScanParam(SCAN_PARAM_TCR);
if(This->mNewSamplesReceived)
{
This->mIoDevice->updateScanParam(SCAN_PARAM_TMR);
This->mNewSamplesReceived = false;
}
}
}
}
// if scan stop is not initiated by the users, i.e. when scan is in finite mode and all samples received or
// an error occurred we need to set scan status here
if(This->mIoDevice->allScanSamplesTransferred() || This->mXferError)
{
This->mIoDevice->setScanState(SS_IDLE);
}
if((This->mEnabledDaqEvents & DE_ON_END_OF_INPUT_SCAN) && This->mIoDevice->allScanSamplesTransferred())
{
unsigned long long totalScanCount = This->mIoDevice->totalScanSamplesTransferred() / This->mIoDevice->scanChanCount();
This->mDaqEventHandler->setCurrentEventAndData(DE_ON_END_OF_INPUT_SCAN, totalScanCount);
}
This->mIoDevice->signalScanDoneWaitEvent();
return NULL;
}
void UsbScanTransferIn::terminateXferStateThread()
{
FnLog log("UsbScanTransferIn::terminateXferStateThread");
UlLock lock(mXferStateThreadHandleMutex);
if(mXferStateThreadHandle)
{
mTerminateXferStateThread = true;
mXferEvent.signal();
UL_LOG("waiting for state thread to complete....");
pthread_join(mXferStateThreadHandle, NULL);
mXferStateThreadHandle = 0;
mXferEvent.reset();
}
}
void UsbScanTransferIn::waitForXferStateThread()
{
FnLog log("UsbScanTransferIn::waitForXferStateThread");
UlLock lock(mXferStateThreadHandleMutex);
if(mXferStateThreadHandle)
{
// The following line is not necessary because when the last request is completed mTerminateXferStateThread is set to true
// just in case there is an unknown problem and the last request never gets completed the mTerminateXferStateThread is set to true here
if(!mTerminateXferStateThread)
mTerminateXferStateThread = true;
mXferEvent.signal();
pthread_join(mXferStateThreadHandle, NULL);
mXferStateThreadHandle = 0;
mXferEvent.reset();
}
}
bool UsbScanTransferIn::isDataAvailable(unsigned long long count, unsigned long long current, unsigned long long next)
{
bool available = false;
if (count == next)
available = true;
else if (count > next)
{
if (next > current || ((next < current) && (count < current)))//both next and count wrapped
available = true;
}
else if (count < current) //count has wrapped around 64-bit limit
{
if ((count < next) && (next > current)) //while next hasn't
available = true;
}
return available;
}
void UsbScanTransferIn::printTransferIndex(libusb_transfer* transfer)
{
for(int i = 0; i < MAX_XFER_COUNT; i++)
{
if(mXfer[i].transfer == transfer)
{
std::cout << "Transfer index: " << i << std::endl;
break;
}
}
}
} /* namespace ul */
| 25.065934 | 137 | 0.732486 | [
"object"
] |
4fd54a4e34e7b527d40ded75a7fe254c64f84f8f | 109,094 | cc | C++ | src/main.cc | Packetfahrer/tbd | f1e635cc9620d78b6666edba6a620ed24672af30 | [
"MIT"
] | 1 | 2021-06-09T11:32:57.000Z | 2021-06-09T11:32:57.000Z | src/main.cc | Packetfahrer/tbd | f1e635cc9620d78b6666edba6a620ed24672af30 | [
"MIT"
] | null | null | null | src/main.cc | Packetfahrer/tbd | f1e635cc9620d78b6666edba6a620ed24672af30 | [
"MIT"
] | null | null | null | //
// src/main.cc
// tbd
//
// Created by inoahdev on 4/16/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include <sys/stat.h>
#include <iostream>
#include <unistd.h>
#include "mach-o/utils/tbd/tbd.h"
#include "misc/recurse.h"
#include "recursive/mkdir.h"
#include "recursive/remove.h"
#include "utils/path.h"
const char *retrieve_current_directory() {
// Store current-directory as a static variable to avoid
// calling getcwd more times than necessary.
static auto current_directory = static_cast<const char *>(nullptr);
if (!current_directory) {
// getcwd(nullptr, 0) will return a dynamically
// allocated buffer just large enough to store
// the current-directory.
const auto current_directory_string = getcwd(nullptr, 0);
if (!current_directory_string) {
fprintf(stderr, "Failed to get current working-directory, failing with error: %s\n", strerror(errno));
exit(1);
}
current_directory = current_directory_string;
}
return current_directory;
}
void parse_architectures_list(uint64_t &architectures, int &index, int argc, const char *argv[]) {
while (index < argc) {
const auto &architecture_string = argv[index];
const auto &architecture_string_front = architecture_string[0];
// Quickly filter out an option or path instead of a (relatively)
// expensive call to macho::architecture_info_from_name().
if (architecture_string_front == '-' || architecture_string_front == '/' || architecture_string_front == '\\') {
// If the architectures vector is empty, the user did not provide any architectures
// but did provided the architecture option, which requires at least one architecture
// being provided.
if (!architectures) {
fputs("Please provide a list of architectures to override the ones in the provided mach-o file(s)\n", stderr);
exit(1);
}
break;
}
const auto architecture_info_table_index = macho::architecture_info_index_from_name(architecture_string);
if (architecture_info_table_index == -1) {
// macho::architecture_info_index_from_name() returning nullptr can be the result of one
// of two scenarios, The string stored in architecture being invalid,
// such as being misspelled, or the string being the path object inevitably
// following the architecture argument.
// If the architectures vector is empty, the user did not provide any architectures
// but did provide the architecture option, which requires at least one architecture
// being provided.
if (!architectures) {
fprintf(stderr, "Unrecognized architecture with name: %s\n", architecture_string);
exit(1);
}
break;
}
architectures |= (1ull << architecture_info_table_index);
index++;
}
// As the caller of this function is in a for loop,
// the index is incremented once again once this function
// returns. To make up for this, decrement index by 1.
index--;
}
void print_platforms() {
auto platform_number = 1;
auto platform = macho::utils::tbd::platform_to_string(macho::utils::tbd::platform(platform_number));
fputs(platform, stdout);
while (true) {
platform_number++;
platform = macho::utils::tbd::platform_to_string(macho::utils::tbd::platform(platform_number));
if (!platform) {
break;
}
fprintf(stdout, ", %s", platform);
}
fputc('\n', stdout);
}
enum creation_handling {
creation_handling_print_paths = 1 << 0,
creation_handling_ignore_no_provided_architectures = 1 << 1,
creation_handling_dont_print_warnings = 1 << 2
};
bool create_tbd_file(const char *macho_file_path, macho::file &file, const char *tbd_file_path, FILE *tbd, macho::utils::tbd::options options, macho::utils::tbd::flags flags, macho::utils::tbd::objc_constraint constraint, macho::utils::tbd::platform platform, macho::utils::tbd::version version, uint64_t architectures, uint64_t architecture_overrides, uint64_t creation_handling_options) {
auto result = macho::utils::tbd::create_from_macho_library(file, tbd, options, flags, constraint, platform, version, architectures, architecture_overrides);
if (result == macho::utils::tbd::creation_result::platform_not_found || result == macho::utils::tbd::creation_result::platform_not_supported || result == macho::utils::tbd::creation_result::unrecognized_platform || result == macho::utils::tbd::creation_result::multiple_platforms) {
// Allow the user, in the case where tbd failed to find a platform-indicator inside
// the provided file, to provide a platform
switch (result) {
case macho::utils::tbd::creation_result::platform_not_found:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stdout, "Failed to find platform in mach-o library (at path %s). ", macho_file_path);
} else {
fputs("Failed to find platform in provided mach-o library. ", stdout);
}
break;
case macho::utils::tbd::creation_result::platform_not_supported:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stdout, "Platform in mach-o library (at path %s) is unsupported. ", macho_file_path);
} else {
fputs("Platform in provided mach-o library is unsupported. ", stdout);
}
break;
case macho::utils::tbd::creation_result::unrecognized_platform:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stdout, "Platform in mach-o library (at path %s) is unrecognized. ", macho_file_path);
} else {
fputs("Platform in provided mach-o library is unrecognized. ", stdout);
}
break;
case macho::utils::tbd::creation_result::multiple_platforms:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stdout, "Multiple platforms found in mach-o library (at path %s). ", macho_file_path);
} else {
fputs("Multiple platforms found in provided mach-o library. ", stdout);
}
break;
case macho::utils::tbd::creation_result::ok:
case macho::utils::tbd::creation_result::stream_seek_error:
case macho::utils::tbd::creation_result::stream_read_error:
case macho::utils::tbd::creation_result::unsupported_filetype:
case macho::utils::tbd::creation_result::inconsistent_flags:
case macho::utils::tbd::creation_result::invalid_subtype:
case macho::utils::tbd::creation_result::invalid_cputype:
case macho::utils::tbd::creation_result::invalid_load_command:
case macho::utils::tbd::creation_result::invalid_segment:
case macho::utils::tbd::creation_result::invalid_sub_client:
case macho::utils::tbd::creation_result::invalid_sub_umbrella:
case macho::utils::tbd::creation_result::failed_to_iterate_load_commands:
case macho::utils::tbd::creation_result::failed_to_iterate_symbols:
case macho::utils::tbd::creation_result::contradictary_load_command_information:
case macho::utils::tbd::creation_result::empty_installation_name:
case macho::utils::tbd::creation_result::uuid_is_not_unique:
case macho::utils::tbd::creation_result::not_a_dynamic_library:
case macho::utils::tbd::creation_result::has_no_uuid:
case macho::utils::tbd::creation_result::contradictary_container_information:
case macho::utils::tbd::creation_result::no_provided_architectures:
case macho::utils::tbd::creation_result::failed_to_allocate_memory:
case macho::utils::tbd::creation_result::no_symbols_or_reexports:
break;
}
auto new_platform = macho::utils::tbd::platform::none;
auto platform_string = std::string();
do {
fputs("Please provide a replacement platform (Input --list-platform to see a list of platforms): ", stdout);
getline(std::cin, platform_string);
if (platform_string == "--list-platform") {
print_platforms();
} else {
new_platform = macho::utils::tbd::platform_from_string(platform_string.data());
}
} while (new_platform == macho::utils::tbd::platform::none);
result = macho::utils::tbd::create_from_macho_library(file, tbd, options, flags, constraint, new_platform, version, architectures, architecture_overrides);
}
if (!(creation_handling_options & creation_handling_dont_print_warnings)) {
switch (result) {
case macho::utils::tbd::creation_result::ok:
return true;
case macho::utils::tbd::creation_result::stream_seek_error:
case macho::utils::tbd::creation_result::stream_read_error:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Failed to read file-stream while parsing mach-o file (at path %s), failing with error: %s\n", macho_file_path, strerror(file.stream.error()));
} else {
fprintf(stderr, "Failed to read file-stream while parsing provided mach-o file, failing with error: %s\n", strerror(file.stream.error()));
}
break;
case macho::utils::tbd::creation_result::unsupported_filetype:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, is of an unsupported filetype\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, is of an unsupported filetype\n", stderr);
}
break;
case macho::utils::tbd::creation_result::inconsistent_flags:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s) has inconsistent information between its architectures\n", macho_file_path);
} else {
fputs("Provided mch-o file has inconsistent information between its architectures\n", stderr);
}
break;
case macho::utils::tbd::creation_result::invalid_subtype:
case macho::utils::tbd::creation_result::invalid_cputype:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, is for an unsupported machine\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, is for an unsupported machine\n", stderr);
}
break;
case macho::utils::tbd::creation_result::invalid_load_command:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, has an invalid load-command\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, has an invalid load-command\n", stderr);
}
break;
case macho::utils::tbd::creation_result::invalid_segment:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, has an invalid segment\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, has an invalid segment\n", stderr);
}
break;
case macho::utils::tbd::creation_result::invalid_sub_client:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, has an invalid sub-client command\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, has an invalid sub-client command\n", stderr);
}
break;
case macho::utils::tbd::creation_result::invalid_sub_umbrella:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, has an invalid sub-umbrella command\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, has an invalid sub-umbrella command\n", stderr);
}
break;
case macho::utils::tbd::creation_result::failed_to_iterate_load_commands:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Failed to iterate through mach-o file (at path %s), or one of its architecture's load-commands\n", macho_file_path);
} else {
fputs("Failed to iterate through provided mach-o file, or one of its architecture's load-commands\n", stderr);
}
break;
case macho::utils::tbd::creation_result::failed_to_iterate_symbols:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Failed to iterate through mach-o file (at path %s), or one of its architecture's symbols\n", macho_file_path);
} else {
fputs("Failed to iterate through provided mach-o file, or one of its architecture's symbols\n", stderr);
}
break;
case macho::utils::tbd::creation_result::contradictary_load_command_information:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, has multiple load-commands of the same type with contradictory information\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, has multiple load-commands of the same type with contradictory information\n", stderr);
}
break;
case macho::utils::tbd::creation_result::empty_installation_name:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, has an empty installation-name\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, has an empty installation-name\n", stderr);
}
break;
case macho::utils::tbd::creation_result::uuid_is_not_unique:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "One of mach-o file (at path %s)'s architectures has a uuid that is not unique from other architectures\n", macho_file_path);
} else {
fputs("One of provided mach-o file's architectures has a uuid that is not unique from other architectures\n", stderr);
}
break;
case macho::utils::tbd::creation_result::platform_not_found:
case macho::utils::tbd::creation_result::platform_not_supported:
case macho::utils::tbd::creation_result::unrecognized_platform:
case macho::utils::tbd::creation_result::multiple_platforms:
break;
case macho::utils::tbd::creation_result::not_a_dynamic_library:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, is not a mach-o library\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, is not a mach-o library\n", stderr);
}
break;
case macho::utils::tbd::creation_result::has_no_uuid:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s), or one of its architectures, does not have a uuid\n", macho_file_path);
} else {
fputs("Provided mach-o file, or one of its architectures, does not have a uuid\n", stderr);
}
break;
case macho::utils::tbd::creation_result::contradictary_container_information:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s) has information in architectures contradicting the same information in other architectures\n", macho_file_path);
} else {
fputs("Provided mach-o file has information in architectures contradicting the same information in other architectures\n", stderr);
}
break;
case macho::utils::tbd::creation_result::no_provided_architectures:
if (!(creation_handling_options & creation_handling_ignore_no_provided_architectures)) {
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s) does not have architectures provided to output tbd from\n", macho_file_path);
} else {
fputs("Provided mach-o file does not have architectures provided to output tbd from\n", stderr);
}
}
break;
case macho::utils::tbd::creation_result::failed_to_allocate_memory:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Failed to allocate memory necessary for operating on mach-o file (at path %s)\n", macho_file_path);
} else {
fputs("Failed to allocate memory necessary for operating on mach-o file at provided path\n", stderr);
}
break;
case macho::utils::tbd::creation_result::no_symbols_or_reexports:
if (creation_handling_options & creation_handling_print_paths) {
fprintf(stderr, "Mach-o file (at path %s) does not have any symbols or reexports to be outputted\n", macho_file_path);
} else {
fputs("Provided mach-o file does not have any symbols or reexports to be outputted\n", stderr);
}
break;
}
return false;
}
return true;
}
void print_usage() {
fputs("Usage: tbd [-p file-paths] [-o/--output output-paths-or-stdout]\n", stdout);
fputs("Main options:\n", stdout);
fputs(" -h, --help, Print this message\n", stdout);
fputs(" -o, --output, Path(s) to output file(s) to write converted tbd files. If provided file(s) already exists, contents will be overridden. Can also provide \"stdout\" to print to stdout\n", stdout);
fputs(" -p, --path, Path(s) to mach-o file(s) to convert to a tbd file. Can also provide \"stdin\" to use stdin\n", stdout);
fputs(" -u, --usage, Print this message\n", stdout);
fputc('\n', stdout);
fputs("Path options:\n", stdout);
fputs("Usage: tbd -p [-a/--arch architectures] [--archs architecture-overrides] [--platform platform] [-r/--recurse/ -r=once/all / --recurse=once/all] [-v/--version v1/v2] /path/to/macho/library\n", stdout);
fputs(" -a, --arch, Specify architecture(s) to output to tbd\n", stdout);
fputs(" --archs, Specify architecture(s) to use, instead of the ones in the provided mach-o file(s)\n", stdout);
fputs(" --platform, Specify platform for all mach-o library files provided\n", stdout);
fputs(" -r, --recurse, Specify directory to recurse and find mach-o library files in\n", stdout);
fputs(" -v, --version, Specify version of tbd to convert to (default is v2)\n", stdout);
fputc('\n', stdout);
fputs("Outputting options:\n", stdout);
fputs("Usage: tbd -o [--maintain-directories] /path/to/output/file\n", stdout);
fputs(" --maintain-directories, Maintain directories where mach-o library files were found in (subtracting the path provided)\n", stdout);
fputs(" --replace-path-extension, Replace path-extension on provided mach-o file(s) when creating an output-file (Replace instead of appending .tbd)\n", stdout);
fputc('\n', stdout);
fputs("Global options:\n", stdout);
fputs(" -a, --arch, Specify architecture(s) to output to tbd (where architectures were not already specified)\n", stdout);
fputs(" --archs, Specify architecture(s) to override architectures found in file (where default architecture-overrides were not already provided)\n", stdout);
fputs(" --platform, Specify platform for all mach-o library files provided (applying to all mach-o library files where platform was not provided)\n", stdout);
fputs(" -v, --version, Specify version of tbd to convert to (default is v2) (applying to all mach-o library files where tbd-version was not provided)\n", stdout);
fputc('\n', stdout);
fputs("Miscellaneous options:\n", stdout);
fputs(" --dont-print-warnings, Don't print any warnings (both path and global option)\n", stdout);
fputc('\n', stdout);
fputs("Symbol options: (Both path and global options)\n", stdout);
fputs(" --allow-all-private-symbols, Allow all non-external symbols (Not guaranteed to link at runtime)\n", stdout);
fputs(" --allow-private-normal-symbols, Allow all non-external symbols (of no type) (Not guaranteed to link at runtime)\n", stdout);
fputs(" --allow-private-weak-symbols, Allow all non-external weak symbols (Not guaranteed to link at runtime)\n", stdout);
fputs(" --allow-private-objc-symbols, Allow all non-external objc-classes and ivars\n", stdout);
fputs(" --allow-private-objc-classes, Allow all non-external objc-classes\n", stdout);
fputs(" --allow-private-objc-ivars, Allow all non-external objc-ivars\n", stdout);
fputc('\n', stdout);
fputs("tbd field options: (Both path and global options)\n", stdout);
fputs(" --flags, Specify flags to add onto ones found in provided mach-o file(s)\n", stdout);
fputs(" --ignore-missing-exports, Ignore if no symbols or reexpors to output are found in provided mach-o file(s)\n", stdout);
fputs(" --ignore-missing-uuids, Ignore if uuids are not found in provided mach-o file(s)\n", stdout);
fputs(" --ignore-non-unique-uuids, Ignore if uuids found in provided mach-o file(s) not unique\n", stdout);
fputs(" --objc-constraint, Specify objc-constraint to use instead of one(s) found in provided mach-o file(s)\n", stdout);
fputs(" --remove-current-version, Remove current-version field from outputted tbds\n", stdout);
fputs(" --remove-compatibility-version, Remove compatibility-version field from outputted tbds\n", stdout);
fputs(" --remove-exports, Remove exports field from outputted tbds\n", stdout);
fputs(" --remove-flags, Remove flags field from outputted tbds\n", stdout);
fputs(" --remove-objc-constraint, Remove objc-constraint field from outputted tbds\n", stdout);
fputs(" --remove-parent-umbrella, Remove parent-umbrella field from outputted tbds\n", stdout);
fputs(" --remove-swift-version, Remove swift-version field from outputted tbds\n", stdout);
fputs(" --remove-uuids, Remove uuids field from outputted tbds\n", stdout);
fputc('\n', stdout);
fputs("List options:\n", stdout);
fputs(" --list-architectures, List all valid architectures for tbd files. Also able to list architectures of a provided mach-o file\n", stdout);
fputs(" --list-tbd-flags, List all valid flags for tbd files\n", stdout);
fputs(" --list-macho-dynamic-libraries, List all valid mach-o libraries in current-directory (or at provided path(s))\n", stdout);
fputs(" --list-objc-constraints, List all valid objc-constraint options for tbd files\n", stdout);
fputs(" --list-platform, List all valid platforms\n", stdout);
fputs(" --list-recurse, List all valid recurse options for parsing directories\n", stdout);
fputs(" --list-versions, List all valid versions for tbd files\n", stdout);
fputc('\n', stdout);
fputs("Validation options:\n", stdout);
fputs(" --validate-macho-dynamic-library, Check if file(s) at provided path(s) are valid mach-o dynamic-libraries\n", stdout);
}
int main(int argc, const char *argv[]) {
if (argc < 2) {
fputs("Please run -h or -u to see a list of options\n", stderr);
return 1;
}
enum misc_options : uint64_t {
include_normal = 1 << 0,
include_libraries = 1 << 1,
include_dynamic_libraries = 1 << 2
};
enum misc_tbd_options : uint64_t {
recurse_directories = 1 << 24, // Use third-byte to support native tbd options
recurse_subdirectories = 1 << 25,
maintain_directories = 1 << 26,
dont_print_warnings = 1 << 27,
replace_path_extension = 1 << 28
};
typedef struct tbd_file {
std::string path;
std::string output_path;
uint64_t architectures;
uint64_t architecture_overrides;
macho::utils::tbd::flags flags;
macho::utils::tbd::objc_constraint constraint;
macho::utils::tbd::platform platform;
macho::utils::tbd::version version;
uint64_t options;
} tbd_file;
auto architectures = uint64_t();
auto architecture_overrides = uint64_t();
auto tbds = std::vector<tbd_file>();
auto output_paths_index = 0;
auto options = uint64_t();
auto flags = macho::utils::tbd::flags::none;
auto objc_constraint = macho::utils::tbd::objc_constraint::no_value;
auto platform = macho::utils::tbd::platform::none;
auto version = macho::utils::tbd::version::v2;
// To parse the argument list, the for loop below parses
// each option, and requires each option to parse its own
// user input in the argument-list.
for (auto i = 1; i < argc; i++) {
const auto &argument = argv[i];
const auto &argument_front = argument[0];
if (argument_front != '-') {
fprintf(stderr, "Unrecognized argument: %s\n", argument);
return 1;
}
auto option = &argument[1];
const auto &option_front = option[0];
if (!option_front) {
fputs("Please provide a valid option\n", stderr);
return 1;
}
if (option_front == '-') {
option++;
}
const auto is_first_argument = i == 1;
const auto is_last_argument = i == argc - 1;
if (strcmp(option, "a") == 0 || strcmp(option, "arch") == 0) {
if (is_last_argument) {
fputs("Please provide a list of architectures to output as tbd\n", stderr);
return 1;
}
i++;
parse_architectures_list(architectures, i, argc, argv);
} else if (strcmp(option, "archs") == 0) {
if (is_last_argument) {
fputs("Please provide a list of architectures to override the ones in the provided mach-o file(s)\n", stderr);
return 1;
}
i++;
parse_architectures_list(architecture_overrides, i, argc, argv);
} else if (strcmp(option, "h") == 0 || strcmp(option, "help") == 0) {
if (!is_first_argument || !is_last_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
print_usage();
return 0;
} else if (strcmp(option, "allow-all-private-symbols") == 0) {
options |= macho::utils::tbd::options::allow_all_private_symbols;
} else if (strcmp(option, "allow-private-normal-symbols") == 0) {
options |= macho::utils::tbd::options::allow_private_normal_symbols;
} else if (strcmp(option, "allow-private-weak-symbols") == 0) {
options |= macho::utils::tbd::options::allow_private_weak_symbols;
} else if (strcmp(option, "allow-private-objc-symbols") == 0) {
options |= macho::utils::tbd::options::allow_private_objc_symbols;
} else if (strcmp(option, "allow-private-objc-classes") == 0) {
options |= macho::utils::tbd::options::allow_private_objc_classes;
} else if (strcmp(option, "allow-private-objc-ivars") == 0) {
options |= macho::utils::tbd::options::allow_private_objc_ivars;
} else if (strcmp(option, "dont-print-warnings") == 0) {
options |= dont_print_warnings;
} else if (strcmp(option, "flags") == 0) {
if (is_last_argument) {
fputs("Please provide a list of flags to add onto ones found in provided mach-o file(s)\n", stderr);
return 1;
}
auto j = ++i;
for (; j < argc; j++) {
const auto argument = argv[j];
if (strcmp(argument, "flat_namespace") == 0) {
flags |= macho::utils::tbd::flags::flat_namespace;
} else if (strcmp(argument, "not_app_extension_safe") == 0) {
flags |= macho::utils::tbd::flags::not_app_extension_safe;
} else {
// Error out if the user simply provided "-flags"
// without any extra arguments,
if (j == i) {
fputs("Please provide a list of flags to add onto ones found in provided mach-o file(s)\n", stderr);
return 1;
}
// Otherwise break out, and decrement j as
// i is set to j and then incremented skipping
// over the current argument
j--;
break;
}
}
i = j;
} else if (strcmp(option, "ignore-missing-exports") == 0) {
options |= macho::utils::tbd::options::ignore_missing_exports;
} else if (strcmp(option, "ignore-missing-uuids") == 0) {
options |= macho::utils::tbd::options::ignore_missing_uuids;
} else if (strcmp(option, "ignore-non-unique-uuids") == 0) {
options |= macho::utils::tbd::options::ignore_non_unique_uuid;
} else if (strcmp(option, "list-architectures") == 0) {
if (!is_first_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
if (is_last_argument) {
auto architecture_info = macho::get_architecture_info_table();
fputs(architecture_info->name, stdout);
while (true) {
architecture_info++;
if (!architecture_info->name) {
break;
}
fprintf(stdout, ", %s", architecture_info->name);
}
fputc('\n', stdout);
} else {
i++;
// Option "--list-architectures" allows only one optional
// path-argument to be provided
if (i + 2 <= argc) {
fprintf(stderr, "Unrecognized argument: %s\n", argv[i + 1]);
return 1;
}
auto path = std::string(argv[i]);
if (const auto &path_front = path.front(); path_front != '/' && path_front != '\\') {
const auto current_directory = retrieve_current_directory();
const auto current_directory_length = strlen(current_directory);
if (const auto &back = current_directory[current_directory_length]; back != '/' && back != '\\') {
path.insert(0, 1, '/');
}
path.insert(0, current_directory);
}
struct stat sbuf;
if (stat(path.data(), &sbuf) != 0) {
fprintf(stderr, "Failed to retrieve information on object (at path %s), failing with error: %s\n", path.data(), strerror(errno));
return 1;
}
if (!S_ISREG(sbuf.st_mode)) {
fprintf(stderr, "Object at path (%s) is not a regular file\n", path.data());
return 1;
}
auto macho_file = macho::file();
auto macho_file_open_result = macho_file.open(path.data());
switch (macho_file_open_result) {
case macho::file::open_result::ok:
break;
case macho::file::open_result::failed_to_open_stream:
fprintf(stderr, "Failed to open file at provided path for reading, failing with error: %s\n", strerror(errno));
return 1;
case macho::file::open_result::failed_to_allocate_memory:
fputs("Failed to allocate memory necessary for operating on file at provided path\n", stderr);
return 1;
case macho::file::open_result::failed_to_retrieve_information:
fprintf(stderr, "Failed to retrieve information necessary to process file at provided path, failing with error: %s\n", strerror(errno));
return 1;
case macho::file::open_result::stream_seek_error:
case macho::file::open_result::stream_read_error:
fprintf(stderr, "Encountered an error while reading through file at provided path, likely not a valid mach-o. Reading failed with error: %s\n", strerror(macho_file.stream.error()));
return 1;
case macho::file::open_result::zero_architectures:
fputs("Fat mach-o file at provided path does not have any architectures\n", stderr);
return 1;
case macho::file::open_result::architectures_goes_past_end_of_file:
fputs("Fat mach-o file at provided path has more architectures than its file-size can hold\n", stderr);
return 1;
case macho::file::open_result::invalid_container:
fputs("Mach-o file at provided path is invalid\n", stderr);
return 1;
case macho::file::open_result::not_a_macho:
fputs("File at provided path is not a valid mach-o\n", stderr);
return 1;
case macho::file::open_result::not_a_library:
case macho::file::open_result::not_a_dynamic_library:
break;
}
// Store architectures into a vector before printing to
// not error out if an architecture for a container present
// is unrecognized in the middle of printing architectures
// of the other containers
const auto containers_size = macho_file.containers.size();
if (containers_size >= 2) {
auto architecture_names = std::vector<const char *>();
architecture_names.reserve(containers_size);
for (const auto &container : macho_file.containers) {
const auto container_subtype = macho::subtype_from_cputype(container.header.cputype, container.header.cpusubtype);
const auto container_arch_info = macho::architecture_info_from_cputype(container.header.cputype, container_subtype);
if (!container_arch_info) {
fputs("Mach-o file at provided path has unknown architectures\n", stderr);
return 1;
}
architecture_names.emplace_back(container_arch_info->name);
}
fputs(architecture_names.front(), stdout);
for (auto architecture_names_iter = architecture_names.cbegin() + 1; architecture_names_iter != architecture_names.cend(); architecture_names_iter++) {
fprintf(stdout, ", %s", *architecture_names_iter);
}
} else {
const auto &container = macho_file.containers.front();
const auto container_subtype = macho::subtype_from_cputype(container.header.cputype, container.header.cpusubtype);
const auto container_arch_info = macho::architecture_info_from_cputype(container.header.cputype, container_subtype);
if (!container_arch_info) {
fputs("Mach-o file at provided path is of an unknown architecture\n", stderr);
return 1;
}
fputs(container_arch_info->name, stdout);
}
fputc('\n', stdout);
}
return 0;
} else if (strcmp(option, "list-macho-dynamic-libraries") == 0) {
if (!is_first_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
if (!is_last_argument) {
auto paths = std::vector<std::pair<std::string, uint64_t>>();
auto options = static_cast<uint64_t>(include_dynamic_libraries);
for (i++; i < argc; i++) {
const auto &argument = argv[i];
const auto &argument_front = argument[0];
if (argument_front == '-') {
auto option = &argument[1];
auto option_front = option[0];
if (!option_front) {
fputs("Please provide a valid option\n", stderr);
return 1;
}
if (option_front == '-') {
option++;
}
if (strcmp(option, "dont-print-warnings") == 0) {
options |= dont_print_warnings;
} else if (strcmp(option, "r") == 0 || strcmp(option, "recurse") == 0) {
options |= recurse_directories | recurse_subdirectories;
} else if (strncmp(option, "r=", 2) == 0 || strncmp(option, "recurse=", 8) == 0) {
const auto recurse_type_string = strchr(option, '=') + 1;
const auto &recurse_type_string_front = recurse_type_string[0];
if (!recurse_type_string_front) {
fputs("Please provide a recurse type\n", stderr);
return 1;
}
if (strcmp(recurse_type_string, "once") != 0) {
options |= recurse_directories;
} else if (strcmp(recurse_type_string, "all") == 0) {
options |= recurse_directories;
options |= recurse_subdirectories;
} else {
fprintf(stderr, "Unrecognized recurse-type: %s\n", recurse_type_string);
return 1;
}
} else {
fprintf(stderr, "Unrecognized argument: %s\n", argument);
return 1;
}
continue;
}
if (argument_front != '/' && argument_front != '\\') {
auto path = std::string();
auto current_directory = retrieve_current_directory();
const auto argument_length = strlen(argument);
const auto current_directory_length = strlen(current_directory);
const auto current_directory_back = current_directory[current_directory_length];
auto path_length = argument_length + current_directory_length;
if (current_directory_back != '/' && current_directory_back != '\\') {
path_length++;
}
path.reserve(path_length);
path.append(current_directory);
if (current_directory_back != '/' && current_directory_back != '\\') {
path.append(1, '/');
}
path.append(argument);
paths.emplace_back(std::move(utils::path::clean(path)), options);
} else {
auto path = std::string(argument);
paths.emplace_back(std::move(utils::path::clean(path)), options);
}
options = 0;
}
if (paths.empty()) {
fprintf(stderr, "Please provide a path for option: %s\n", argument);
return 1;
}
const auto &paths_back = paths.back();
for (const auto &pair : paths) {
const auto &path = pair.first;
const auto &options = pair.second;
struct stat sbuf;
if (stat(path.data(), &sbuf) != 0) {
fprintf(stderr, "Failed to retrieve information on object (at path %s), failing with error: %s\n", path.data(), strerror(errno));
return 1;
}
if (!S_ISDIR(sbuf.st_mode)) {
fprintf(stderr, "Cannot recurse file (at path %s)\n", path.data());
return 1;
}
auto recurse_options = recurse::options::none;
if (!(options & dont_print_warnings)) {
recurse_options |= recurse::options::print_warnings;
}
if (options & recurse_subdirectories) {
recurse_options |= recurse::options::recurse_subdirectories;
}
const auto recursion_result = recurse::macho_file_paths(path.data(), recurse::macho_file_type::dynamic_library, recurse_options, [&](std::string &library_path) {
fprintf(stdout, "%s\n", library_path.data());
});
switch (recursion_result) {
case recurse::operation_result::ok: {
break;
}
case recurse::operation_result::failed_to_open_directory:
fprintf(stderr, "Failed to open directory (at path %s) for recursing, failing with error: %s\n", path.data(), strerror(errno));
break;
case recurse::operation_result::found_no_matching_files:
// Rather than exiting leaving the user empty-handed, it is
// better to acknowledge that no mach-o files of the relevant
// type were found
if (options & recurse_subdirectories) {
fprintf(stderr, "No mach-o dynamic-libraries were found while recursing through path (%s) and its sub-directories\n", path.data());
} else {
fprintf(stderr, "No mach-o dynamic-libraries were found while recursing through path: %s\n", path.data());
}
break;
}
// Print a newline between each pair for readability
// purposes, But an extra new-line is not needed for the
// last pair
if (pair != paths_back) {
fputc('\n', stdout);
}
}
} else {
// If a path was not provided, --list-macho-dynamic-libraries is
// expected to instead recurse the current-directory.
auto path = std::string(retrieve_current_directory());
if (const auto &back = path.back(); back != '/' && back != '\\') {
path.append(1, '/');
}
const auto recursion_result = recurse::macho_file_paths(path.data(), recurse::macho_file_type::dynamic_library, recurse::options::print_warnings | recurse::options::recurse_subdirectories, [&](std::string &library_path) {
fprintf(stdout, "%s\n", library_path.data());
});
switch (recursion_result) {
case recurse::operation_result::ok:
break;
case recurse::operation_result::failed_to_open_directory:
fprintf(stderr, "Failed to open directory (at path %s) for recursing, failing with error: %s\n", path.data(), strerror(errno));
return 1;
case recurse::operation_result::found_no_matching_files:
fprintf(stderr, "No mach-o dynamic-library files were found while recursing through path: %s\n", path.data());
break;
}
}
return 0;
} else if (strcmp(option, "list-objc-constraints") == 0) {
if (!is_first_argument || !is_last_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
auto objc_constraint_integer = 1ull;
auto objc_constraint_string = macho::utils::tbd::objc_constraint_to_string(macho::utils::tbd::objc_constraint(objc_constraint_integer));
while (objc_constraint_string != nullptr) {
fprintf(stdout, "%s\n", objc_constraint_string);
objc_constraint_integer++;
objc_constraint_string = macho::utils::tbd::objc_constraint_to_string(macho::utils::tbd::objc_constraint(objc_constraint_integer));
}
return 0;
} else if (strcmp(option, "list-platform") == 0) {
if (!is_first_argument || !is_last_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
print_platforms();
return 0;
} else if (strcmp(option, "list-recurse") == 0) {
if (!is_first_argument || !is_last_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
fputs("once, Recurse through all of a directory's files\n", stdout);
fputs("all, Recurse through all of a directory's files and sub-directories (default)\n", stdout);
return 0;
} else if (strcmp(option, "list-tbd-flags") == 0) {
if (!is_first_argument || !is_last_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
fputs("flat_namespace\nnot_app_extension_safe\n", stdout);
return 0;
} else if (strcmp(option, "list-versions") == 0) {
if (!is_first_argument || !is_last_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
fputs("v1\nv2 (default)\n", stdout);
return 0;
} else if (strcmp(option, "o") == 0 || strcmp(option, "output") == 0) {
if (is_last_argument) {
fputs("Please provide path(s) to output files\n", stderr);
return 1;
}
auto output_options = uint64_t();
auto provided_output_path = false;
// To parse options for the output command in the middle of an
// argument list, while also keeping a similar argument and option
// type, the output option handles custom output options in between
// the output option argument and the output path argument.
for (i++; i < argc; i++) {
const auto &argument = argv[i];
const auto &argument_front = argument[0];
if (argument_front == '-') {
auto option = &argument[1];
const auto &option_front = option[0];
if (!option_front) {
fputs("Please provide a valid option\n", stderr);
return 1;
}
if (option_front == '-') {
option++;
}
if (strcmp(option, "maintain-directories") == 0) {
output_options |= maintain_directories;
} else if (strcmp(option, "replace-path-extension") == 0) {
output_options |= replace_path_extension;
} else {
fprintf(stderr, "Unrecognized option: %s\n", argument);
return 1;
}
continue;
}
auto path = std::string(argument);
if (path != "stdout") {
utils::path::clean(path);
if (const auto &path_front = path.front(); path_front != '/' && path_front != '\\') {
// If the user-provided path-string does not begin with
// a forward slash, it is assumed that the path exists
// in the current-directory.
const auto current_directory = retrieve_current_directory();
const auto current_directory_length = strlen(current_directory);
if (const auto &back = current_directory[current_directory_length]; back != '/' && back != '\\') {
path.insert(0, 1, '/');
}
path.insert(0, current_directory);
}
}
const auto tbds_size = tbds.size();
if (output_paths_index >= tbds_size) {
fprintf(stderr, "No corresponding mach-o files for output-path (%s, at index %d)\n", path.data(), output_paths_index);
return 1;
}
auto &tbd = tbds.at(output_paths_index);
auto &tbd_options = tbd.options;
if (output_options & maintain_directories) {
if (!(tbd_options & recurse_directories)) {
fprintf(stderr, "Option (--maintain-directories) for file (at path %s) can only be provided when recursing a directory\n", tbd.path.data());
return 1;
}
tbd_options |= maintain_directories;
}
if (output_options & replace_path_extension) {
if (!(tbd_options & recurse_directories)) {
fprintf(stderr, "Option (--replace-path-extension) for file (at path %s) can only be provided for files found when recursing a directory\n", tbd.path.data());
return 1;
}
tbd_options |= replace_path_extension;
}
if (path == "stdout") {
if (tbd_options & recurse_directories) {
fprintf(stderr, "Can't output mach-o files found while recursing to stdout\n");
return 1;
}
}
struct stat sbuf;
if (stat(path.data(), &sbuf) == 0) {
if (S_ISDIR(sbuf.st_mode)) {
if (!(tbd_options & recurse_directories)) {
fprintf(stderr, "Cannot output a tbd file to directory (at path %s), please provide a path to a file to output to\n", path.data());
return 1;
}
if (const auto &path_back = path.back(); path_back != '/' && path_back != '\\') {
path.append(1, '/');
}
} else {
if (S_ISREG(sbuf.st_mode)) {
if (tbd_options & recurse_directories) {
fprintf(stderr, "Cannot output mach-o files found while recursing directory (at path %s) to file (at path %s). Please provide a directory to output tbd files to\n", tbd.path.data(), path.data());
return 1;
}
}
}
} else {
if (tbd_options & recurse_directories) {
if (const auto &path_back = path.back(); path_back != '/' && path_back != '\\') {
path.append(1, '/');
}
}
}
tbd.output_path = std::move(path);
provided_output_path = true;
break;
}
// To support the current format of providing output options,
// a single output option only supports a single output-path
if (!provided_output_path) {
fputs("Please provide path(s) to output files\n", stderr);
return 1;
}
output_paths_index++;
} else if (strcmp(option, "objc-constraint") == 0) {
if (is_last_argument) {
fputs("Please provide an objc-constraint\n", stderr);
return 1;
}
i++;
const auto objc_constraint_string = argv[i];
const auto objc_constraint_inner = macho::utils::tbd::objc_constraint_from_string(objc_constraint_string);
if (objc_constraint_inner == macho::utils::tbd::objc_constraint::no_value) {
fprintf(stderr, "Unrecognized objc-constraint value: %s\n", objc_constraint_string);
return 1;
}
objc_constraint = objc_constraint_inner;
} else if (strcmp(option, "p") == 0 || strcmp(option, "path") == 0) {
if (is_last_argument) {
fputs("Please provide path(s) to mach-o files\n", stderr);
return 1;
}
// To parse options for the path command in the middle of an
// argument list, while also keeping a similar argument and options
// type, the path option handles custom output options in between
// the path option argument and the mach-o library path argument.
auto local_architectures = uint64_t();
auto local_architecture_overrides = uint64_t();
auto local_options = uint64_t();
auto local_flags = macho::utils::tbd::flags::none;
auto local_objc_constraint = macho::utils::tbd::objc_constraint::no_value;
auto local_platform = macho::utils::tbd::platform::none;
auto local_tbd_version = macho::utils::tbd::version::none;
for (i++; i < argc; i++) {
const auto &argument = argv[i];
const auto &argument_front = argument[0];
if (argument_front == '-') {
auto option = &argument[1];
const auto &option_front = option[0];
if (!option_front) {
fputs("Please provide a valid option\n", stderr);
return 1;
}
if (option_front == '-') {
option++;
}
const auto is_last_argument = i == argc - 1;
if (strcmp(option, "a") == 0 || strcmp(option, "arch") == 0) {
if (is_last_argument) {
fputs("Please provide a list of architectures to override the ones in the provided mach-o file(s)\n", stderr);
return 1;
}
i++;
parse_architectures_list(local_architectures, i, argc, argv);
} else if (strcmp(option, "archs") == 0) {
if (is_last_argument) {
fputs("Please provide a list of architectures to override the ones in the provided mach-o file(s)\n", stderr);
return 1;
}
i++;
parse_architectures_list(local_architecture_overrides, i, argc, argv);
} else if (strcmp(option, "allow-all-private-symbols") == 0) {
local_options |= macho::utils::tbd::options::allow_all_private_symbols;
} else if (strcmp(option, "allow-private-normal-symbols") == 0) {
local_options |= macho::utils::tbd::options::allow_private_normal_symbols;
} else if (strcmp(option, "allow-private-weak-symbols") == 0) {
local_options |= macho::utils::tbd::options::allow_private_weak_symbols;
} else if (strcmp(option, "allow-private-objc-symbols") == 0) {
local_options |= macho::utils::tbd::options::allow_private_objc_symbols;
} else if (strcmp(option, "allow-private-objc-classes") == 0) {
local_options |= macho::utils::tbd::options::allow_private_objc_classes;
} else if (strcmp(option, "allow-private-objc-ivars") == 0) {
local_options |= macho::utils::tbd::options::allow_private_objc_ivars;
} else if (strcmp(option, "dont-print-warnings") == 0) {
local_options |= dont_print_warnings;
} else if (strcmp(option, "flags") == 0) {
if (is_last_argument) {
fputs("Please provide a list of flags to add onto ones found in provided mach-o file(s)\n", stderr);
return 1;
}
auto j = ++i;
for (; j < argc; j++) {
const auto argument = argv[j];
if (strcmp(argument, "flat_namespace") == 0) {
local_flags |= macho::utils::tbd::flags::flat_namespace;
} else if (strcmp(argument, "not_app_extension_safe") == 0) {
local_flags |= macho::utils::tbd::flags::not_app_extension_safe;
} else {
if (j == i) {
fputs("Please provide a list of flags to add onto ones found in provided mach-o file(s)\n", stderr);
return 1;
}
j--;
break;
}
}
i = j;
} else if (strcmp(option, "objc-constraint") == 0) {
if (is_last_argument) {
fputs("Please provide an objc-constraint\n", stderr);
return 1;
}
i++;
const auto objc_constraint_string = argv[i];
const auto objc_constraint_inner = macho::utils::tbd::objc_constraint_from_string(objc_constraint_string);
if (objc_constraint_inner == macho::utils::tbd::objc_constraint::no_value) {
fprintf(stderr, "Unrecognized objc-constraint value: %s\n", objc_constraint_string);
return 1;
}
local_objc_constraint = objc_constraint_inner;
} else if (strcmp(option, "p") == 0) {
fprintf(stderr, "Please provide a path for option: %s\n", argument);
return 1;
} else if (strcmp(option, "platform") == 0) {
if (is_last_argument) {
fputs("Please provide a platform-string. Run --list-platform to see a list of platforms\n", stderr);
return 1;
}
i++;
const auto &platform_string = argv[i];
local_platform = macho::utils::tbd::platform_from_string(platform_string);
if (local_platform == macho::utils::tbd::platform::none) {
fprintf(stderr, "Platform-string (%s) is invalid\n", platform_string);
return 1;
}
} else if (strcmp(option, "r") == 0 || strcmp(option, "recurse") == 0) {
local_options |= recurse_directories | recurse_subdirectories;
} else if (strncmp(option, "r=", 2) == 0 || strncmp(option, "recurse=", 8) == 0) {
const auto recurse_type_string = strchr(option, '=') + 1;
const auto &recurse_type_string_front = recurse_type_string[0];
if (!recurse_type_string_front) {
fputs("Please provide a recurse type\n", stderr);
return 1;
}
local_options |= recurse_directories;
if (strcmp(recurse_type_string, "all") == 0) {
local_options |= recurse_subdirectories;
} else if (strcmp(recurse_type_string, "once") != 0) {
fprintf(stderr, "Unrecognized recurse-type: %s\n", recurse_type_string);
return 1;
}
} else if (strcmp(option, "ignore-missing-exports") == 0) {
local_options |= macho::utils::tbd::options::ignore_missing_exports;
} else if (strcmp(option, "ignore-missing-uuids") == 0) {
local_options |= macho::utils::tbd::options::ignore_missing_uuids;
} else if (strcmp(option, "ignore-non-unique-uuids") == 0) {
local_options |= macho::utils::tbd::options::ignore_non_unique_uuid;
} else if (strcmp(option, "remove-current-version") == 0) {
local_options |= macho::utils::tbd::options::remove_current_version;
} else if (strcmp(option, "remove-compatibility-version") == 0) {
local_options |= macho::utils::tbd::options::remove_compatibility_version;
} else if (strcmp(option, "remove-exports") == 0) {
local_options |= macho::utils::tbd::options::remove_exports;
} else if (strcmp(option, "remove-flags") == 0) {
local_options |= macho::utils::tbd::options::remove_flags;
} else if (strcmp(option, "remove-objc-constraint") == 0) {
local_options |= macho::utils::tbd::options::remove_objc_constraint;
} else if (strcmp(option, "remove-swift-version") == 0) {
local_options |= macho::utils::tbd::options::remove_swift_version;
} else if (strcmp(option, "remove-uuids") == 0) {
local_options |= macho::utils::tbd::options::remove_uuids;
} else if (strcmp(option, "v") == 0 || strcmp(option, "version") == 0) {
if (is_last_argument) {
fputs("Please provide a tbd-version\n", stderr);
return 1;
}
i++;
const auto &version_string = argv[i];
local_tbd_version = macho::utils::tbd::version_from_string(version_string);
if (local_tbd_version == macho::utils::tbd::version::none) {
fprintf(stderr, "(%s) is not a valid tbd-version\n", version_string);
return 1;
}
} else {
fprintf(stderr, "Unrecognized argument: %s\n", argument);
return 1;
}
continue;
}
auto path = std::string(argument);
// If the user-provided path-string does not begin with
// a forward slash, it is assumed that the path exists
// in the current-directory
if (path == "stdin") {
if (local_options & recurse_directories) {
fputs("Cannot recurse stdin\n", stderr);
return 1;
}
if (local_options & replace_path_extension) {
fputs("Cannot replace path-extension of stdin\n", stderr);
return 1;
}
} else {
utils::path::clean(path);
if (const auto &path_front = path.front(); path_front != '/' && path_front != '\\') {
const auto current_directory = retrieve_current_directory();
const auto current_directory_length = strlen(current_directory);
if (const auto &back = current_directory[current_directory_length]; back != '/' && back != '\\') {
path.insert(0, 1, '/');
}
path.insert(0, current_directory);
}
struct stat sbuf;
if (stat(path.data(), &sbuf) != 0) {
fprintf(stderr, "Failed to retrieve information on object (at path %s), failing with error: %s\n", path.data(), strerror(errno));
return 1;
}
if (S_ISDIR(sbuf.st_mode)) {
if (!(local_options & recurse_directories)) {
fprintf(stderr, "Cannot open directory (at path %s) as a macho-file, use -r to recurse the directory\n", path.data());
return 1;
}
const auto &path_back = path.back();
if (path_back != '/') {
path.append(1, '/');
}
} else {
if (S_ISREG(sbuf.st_mode)) {
if (local_options & recurse_directories) {
fprintf(stderr, "Cannot recurse file (at path %s)\n", path.data());
return 1;
}
if (local_options & replace_path_extension) {
fputs("Replacing path-extension for output-files is meant only to be used while recursing\n", stderr);
return 1;
}
} else {
fprintf(stderr, "Object (at path %s) is not a regular file\n", path.data());
return 1;
}
}
}
auto tbd = tbd_file({});
tbd.path = std::move(path);
tbd.architectures = local_architectures;
tbd.architecture_overrides = local_architecture_overrides;
tbd.options = local_options;
tbd.platform = local_platform;
tbd.version = local_tbd_version;
tbds.emplace_back(std::move(tbd));
// Clear the local fields to signal that a
// path was provided
local_architectures = 0;
local_architecture_overrides = 0;
local_options = 0;
local_platform = macho::utils::tbd::platform::none;
local_tbd_version = macho::utils::tbd::version::none;
break;
}
// It is expected for --path to error out if the user has
// not provided a path to a mach-o library path or to a
// directory where some could be found
if (local_architectures != 0 || local_architecture_overrides != 0 || local_platform != macho::utils::tbd::platform::none || local_options != 0 || local_tbd_version != macho::utils::tbd::version::none) {
fputs("Please provide a path to a mach-o library file or to a directory to recurse through\n", stderr);
return 1;
}
} else if (strcmp(option, "platform") == 0) {
if (is_last_argument) {
fputs("Please provide a platform-string. Run --list-platform to see a list of platforms\n", stderr);
return 1;
}
i++;
const auto &platform_string = argv[i];
platform = macho::utils::tbd::platform_from_string(platform_string);
if (platform == macho::utils::tbd::platform::none) {
fprintf(stderr, "Platform-string (%s) is invalid\n", platform_string);
return 1;
}
} else if (strcmp(option, "remove-current-version") == 0) {
options |= macho::utils::tbd::options::remove_current_version;
} else if (strcmp(option, "remove-compatibility-version") == 0) {
options |= macho::utils::tbd::options::remove_compatibility_version;
} else if (strcmp(option, "remove-exports") == 0) {
options |= macho::utils::tbd::options::remove_exports;
} else if (strcmp(option, "remove-flags") == 0) {
options |= macho::utils::tbd::options::remove_flags;
} else if (strcmp(option, "remove-objc-constraint") == 0) {
options |= macho::utils::tbd::options::remove_objc_constraint;
} else if (strcmp(option, "remove-swift-version") == 0) {
options |= macho::utils::tbd::options::remove_swift_version;
} else if (strcmp(option, "remove-uuids") == 0) {
options |= macho::utils::tbd::options::remove_uuids;
} else if (strcmp(option, "u") == 0 || strcmp(option, "usage") == 0) {
if (!is_first_argument || !is_last_argument) {
fprintf(stderr, "Option (%s) should be run by itself\n", argument);
return 1;
}
print_usage();
return 0;
} else if (strcmp(option, "v") == 0 || strcmp(option, "version") == 0) {
if (is_last_argument) {
fputs("Please provide a tbd-version\n", stderr);
return 1;
}
i++;
const auto &version_string = argv[i];
const auto &version_string_front = version_string[0];
if (version_string_front == '-') {
fputs("Please provide a tbd-version\n", stderr);
return 1;
}
if (strcmp(version_string, "v1") == 0) {
version = macho::utils::tbd::version::v1;
} else if (strcmp(version_string, "v2") != 0) {
fprintf(stderr, "tbd-version (%s) is invalid\n", version_string);
return 1;
}
} else if (strcmp(option, "validate-macho-dynamic-library") == 0) {
if (!is_first_argument) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
return 1;
}
if (is_last_argument) {
fputs("Please provide path(s) to file(s) to check if they are valid mach-o dynamic-libraries\n", stderr);
return 1;
}
i++;
const auto should_print_paths = i == argc - 1;
for (; i < argc; i++) {
auto path = argv[i];
struct stat sbuf;
if (stat(path, &sbuf) != 0) {
if (should_print_paths) {
fprintf(stderr, "Failed to retrieve information on file at path (%s), failing with error: %s\n", path, strerror(errno));
} else {
fprintf(stderr, "Failed to retrieve information on file at provided path, failing with error: %s\n", strerror(errno));
}
return 1;
}
if (S_ISDIR(sbuf.st_mode)) {
if (should_print_paths) {
fprintf(stderr, "Cannot open directory at path (%s) as a valid mach-o dynamic-library\n", path);
} else {
fputs("Cannot open directory at provided path as a valid mach-o dynamic-library\n", stderr);
}
return 1;
}
if (!S_ISREG(sbuf.st_mode)) {
if (should_print_paths) {
fprintf(stderr, "Object at path (%s) is not a regular file\n", path);
} else {
fputs("Object at provided path is not a regular file\n", stderr);
}
return 1;
}
auto check_error = macho::file::check_error::ok;
const auto result = macho::file::is_valid_dynamic_library(path, &check_error);
switch (check_error) {
case macho::file::check_error::ok:
break;
case macho::file::check_error::failed_to_open_descriptor:
if (should_print_paths) {
fprintf(stderr, "Failed to open file at path: %s\n", path);
} else {
fputs("Failed to open file at provided path\n", stderr);
}
return 1;
case macho::file::check_error::failed_to_allocate_memory:
if (should_print_paths) {
fprintf(stderr, "Failed to retrieve memory necessary to check if file at path (%s) is a valid mach-o dynamic-library\n", path);
} else {
fputs("Failed to retrieve memory necessary to check if file at provided path is a valid mach-o dynamic-library\n", stderr);
}
return 1;
case macho::file::check_error::failed_to_read_descriptor:
case macho::file::check_error::failed_to_seek_descriptor:
case macho::file::check_error::failed_to_close_descriptor:
break;
}
if (result) {
if (should_print_paths) {
fprintf(stderr, "File at path (%s) is a valid mach-o dynamic-library\n", path);
} else {
fputs("File at provided path is a valid mach-o dynamic-library\n", stderr);
}
} else {
if (should_print_paths) {
fprintf(stderr, "File at path (%s) is not a valid mach-o dynamic-library\n", path);
} else {
fputs("File at provided path is not a valid mach-o dynamic-library\n", stderr);
}
}
}
return 0;
} else {
fprintf(stderr, "Unrecognized argument: %s\n", argument);
return 1;
}
}
const auto tbds_size = tbds.size();
if (!tbds_size) {
fputs("No mach-o files have been provided\n", stderr);
return 1;
}
auto should_print_paths = true;
if (tbds.size() < 2) {
const auto &tbd = tbds.front();
const auto &tbd_options = tbd.options;
if (!(tbd_options & recurse_directories)) {
should_print_paths = false;
}
} else {
// Remove any duplicates
for (auto tbd_iter = tbds.begin(); tbd_iter != tbds.end(); tbd_iter++) {
const auto &tbd = *tbd_iter;
const auto &tbd_path = tbd.path;
for (auto tbd_inner_iter = tbd_iter + 1; tbd_inner_iter != tbds.end();) {
const auto &tbd_inner_elmt = *tbd_inner_iter;
const auto &tbd_inner_path = tbd_inner_elmt.path;
if (utils::path::compare(tbd_path.cbegin(), tbd_path.cend(), tbd_inner_path.cbegin(), tbd_inner_path.cend()) != 0) {
continue;
}
auto tbd_options = tbd.options;
auto tbd_inner_options = tbd_inner_elmt.options;
if (tbd_inner_options & recurse_subdirectories) {
tbd_options |= recurse_subdirectories;
tbd_inner_options &= ~recurse_subdirectories;
}
if (tbd_inner_options != 0) {
tbd_inner_iter++;
} else {
tbd_inner_iter = tbds.erase(tbd_inner_iter);
}
}
}
}
for (auto &tbd : tbds) {
auto &tbd_path = tbd.path;
auto &tbd_output_path = tbd.output_path;
auto &tbd_flags = tbd.flags;
if ((flags & macho::utils::tbd::flags::flat_namespace) != macho::utils::tbd::flags::none) {
tbd_flags |= macho::utils::tbd::flags::flat_namespace;
}
if ((flags & macho::utils::tbd::flags::not_app_extension_safe) != macho::utils::tbd::flags::none) {
tbd_flags |= macho::utils::tbd::flags::not_app_extension_safe;
}
if (options & macho::utils::tbd::options::allow_all_private_symbols) {
tbd.options |= macho::utils::tbd::options::allow_all_private_symbols;
} else {
if (options & macho::utils::tbd::options::allow_private_normal_symbols) {
tbd.options |= macho::utils::tbd::options::allow_private_normal_symbols;
}
if (options & macho::utils::tbd::options::allow_private_weak_symbols) {
tbd.options |= macho::utils::tbd::options::allow_private_weak_symbols;
}
if (options & macho::utils::tbd::options::allow_private_objc_symbols) {
tbd.options |= macho::utils::tbd::options::allow_private_objc_symbols;
} else {
if (options & macho::utils::tbd::options::allow_private_objc_classes) {
tbd.options |= macho::utils::tbd::options::allow_private_objc_classes;
}
if (options & macho::utils::tbd::options::allow_private_objc_ivars) {
tbd.options |= macho::utils::tbd::options::allow_private_objc_ivars;
}
}
}
if (options & dont_print_warnings) {
tbd.options |= dont_print_warnings;
}
if (options & macho::utils::tbd::options::ignore_missing_exports) {
tbd.options |= macho::utils::tbd::options::ignore_missing_exports;
}
if (options & macho::utils::tbd::options::ignore_missing_uuids) {
tbd.options |= macho::utils::tbd::options::ignore_missing_uuids;
}
if (options & macho::utils::tbd::options::ignore_non_unique_uuid) {
tbd.options |= macho::utils::tbd::options::ignore_non_unique_uuid;
}
if (options & macho::utils::tbd::options::remove_current_version) {
tbd.options |= macho::utils::tbd::options::remove_current_version;
}
if (options & macho::utils::tbd::options::remove_compatibility_version) {
tbd.options |= macho::utils::tbd::options::remove_compatibility_version;
}
if (options & macho::utils::tbd::options::remove_exports) {
tbd.options |= macho::utils::tbd::options::remove_exports;
}
if (options & macho::utils::tbd::options::remove_flags) {
tbd.options |= macho::utils::tbd::options::remove_flags;
}
if (options & macho::utils::tbd::options::remove_objc_constraint) {
tbd.options |= macho::utils::tbd::options::remove_current_version;
}
if (options & macho::utils::tbd::options::remove_parent_umbrella) {
tbd.options |= macho::utils::tbd::options::remove_current_version;
}
if (options & macho::utils::tbd::options::remove_swift_version) {
tbd.options |= macho::utils::tbd::options::remove_current_version;
}
if (options & macho::utils::tbd::options::remove_uuids) {
tbd.options |= macho::utils::tbd::options::remove_current_version;
}
if (tbd.options & recurse_directories) {
// Although checks for any errors are supposed to occur during
// argument-parsing, it is not possible to check earlier when
// output-path has not been provided (user did not provide -o
// argument)
// Prefer continuing after printing error to continue work on
// other tbd operations
if (tbd_output_path.empty()) {
fprintf(stderr, "Cannot output mach-o files found while recursing directory (at path %s) to stdout. Please provide a directory to output tbd files to\n", tbd_path.data());
continue;
}
if (options & replace_path_extension) {
tbd.options |= replace_path_extension;
}
const auto tbd_path_length = tbd_path.length();
const auto tbd_output_path_length = tbd_output_path.length();
auto outputted_any_macho_libraries = false;
auto recurse_options = recurse::options::none;
if (!(tbd.options & dont_print_warnings)) {
recurse_options |= recurse::options::print_warnings;
}
if (tbd.options & recurse_subdirectories) {
recurse_options |= recurse::options::recurse_subdirectories;
}
auto recursion_result = recurse::macho_files(tbd_path.data(), recurse::macho_file_type::dynamic_library, recurse_options, [&](std::string &library_path, macho::file &file) {
auto output_path_front = std::string::npos;
if (tbd.options & maintain_directories) {
output_path_front = tbd_path_length;
} else {
output_path_front = utils::path::find_last_slash(library_path.cbegin(), library_path.cend()) - library_path.cbegin();
}
auto output_path = std::string();
auto extracted_output_path = library_path.substr(output_path_front);
auto extracted_output_path_length = extracted_output_path.length();
auto output_path_length = tbd_output_path_length + extracted_output_path_length + 4;
output_path.reserve(output_path_length);
output_path.append(tbd_output_path);
auto extracted_output_path_begin = extracted_output_path.cbegin();
auto extracted_output_path_end = extracted_output_path.cend();
if (tbd.options & replace_path_extension) {
extracted_output_path_end = utils::path::find_extension(extracted_output_path_begin, extracted_output_path_end);
}
utils::path::add_component(output_path, extracted_output_path_begin, extracted_output_path_end);
output_path.append(".tbd");
auto output_path_creation_terminator = static_cast<char *>(nullptr);
auto output_file_descriptor = -1;
// should_print_paths is always true for recursing,
// so a check here are unnecessary
const auto mkdir_result = recursive::mkdir::perform_with_last_as_file(output_path.data(), &output_path_creation_terminator, &output_file_descriptor);
if (mkdir_result != recursive::mkdir::result::ok) {
switch (mkdir_result) {
case recursive::mkdir::result::ok:
case recursive::mkdir::result::failed_to_create_last_as_directory:
case recursive::mkdir::result::last_already_exists_not_as_directory:
break;
case recursive::mkdir::result::failed_to_create_intermediate_directories:
fprintf(stderr, "Failed to create intermediate directories for output-path (%s), failing with error: %s\n", output_path.data(), strerror(errno));
break;
case recursive::mkdir::result::failed_to_create_last_as_file:
fprintf(stderr, "Failed to create file at output-path (%s), failing with error: %s\n", output_path.data(), strerror(errno));
break;
case recursive::mkdir::result::last_already_exists_not_as_file:
fprintf(stderr, "Failed to create file at output-path (%s), as object (not of type file) already exists\n", output_path.data());
break;
}
return;
}
auto output_file = static_cast<FILE *>(nullptr);
if (output_file_descriptor != -1) {
output_file = fdopen(output_file_descriptor, "w");
} else {
// Try reopening (thought likely to no avail)
output_file = fopen(output_path.data(), "w");
}
if (!output_file) {
fprintf(stderr, "Failed to open file (at path %s) for writing, failing with error: %s\n", output_path.data(), strerror(errno));
return;
}
auto tbd_creation_options = creation_handling_print_paths | creation_handling_ignore_no_provided_architectures;
if (tbd.options & dont_print_warnings) {
tbd_creation_options |= creation_handling_dont_print_warnings;
}
if (tbd.constraint == macho::utils::tbd::objc_constraint::no_value) {
tbd.constraint = objc_constraint;
}
if (tbd.platform == macho::utils::tbd::platform::none) {
tbd.platform = platform;
}
if (tbd.version == macho::utils::tbd::version::none) {
tbd.version = version;
}
if (!tbd.architectures) {
tbd.architectures = architectures;
}
if (!tbd.architecture_overrides) {
tbd.architecture_overrides = architecture_overrides;
}
const auto result = create_tbd_file(library_path.data(), file, output_path.data(), output_file, macho::utils::tbd::options(tbd.options), tbd.flags, tbd.constraint, tbd.platform, tbd.version, tbd.architectures, tbd.architecture_overrides, tbd_creation_options);
if (!result) {
if (output_path_creation_terminator != nullptr) {
const auto remove_result = recursive::remove::perform(output_path.data(), output_path_creation_terminator);
switch (remove_result) {
case recursive::remove::result::ok:
break;
case recursive::remove::result::failed_to_remove_directory:
*output_path_creation_terminator = '\0';
fprintf(stderr, "Failed to remove created-directory at path (%s), failing with error: %s\n", output_path.data(), strerror(errno));
break;
case recursive::remove::result::failed_to_remove_subdirectories: {
const auto &output_path_creation_terminator_character = *output_path_creation_terminator;
*output_path_creation_terminator = '\0';
fprintf(stderr, "Failed to remove created sub-directories of path (%s)", output_path.data());
*output_path_creation_terminator = output_path_creation_terminator_character;
fprintf(stderr, ", full path being (%s), failing with error: %s\n", output_path.data(), strerror(errno));
break;
}
case recursive::remove::result::directory_doesnt_exist: {
*output_path_creation_terminator = '\0';
fprintf(stderr, "Internal Error: Failed to remove created directory at path (%s) as directory at path has already been removed/never created", output_path.data());
break;
}
case recursive::remove::result::sub_directory_doesnt_exist: {
const auto &output_path_creation_terminator_character = *output_path_creation_terminator;
*output_path_creation_terminator = '\0';
fprintf(stderr, "Internal Error: Failed to remove created sub-directories at path (%s)", output_path.data());
*output_path_creation_terminator = output_path_creation_terminator_character;
fprintf(stderr, ", full path being (%s), as directory at path has already removed/never existed ", output_path.data());
break;
}
}
}
} else {
outputted_any_macho_libraries = true;
}
fclose(output_file);
});
switch (recursion_result) {
case recurse::operation_result::ok:
if (!outputted_any_macho_libraries) {
if (tbd.options & recurse_subdirectories) {
fprintf(stderr, "No mach-o files were found for outputting while recursing through directory (at path %s) and its sub-directories\n", tbd_path.data());
} else {
fprintf(stderr, "No mach-o files were found for outputting while recursing through directory (at path %s)\n", tbd_path.data());
}
}
break;
case recurse::operation_result::failed_to_open_directory:
fprintf(stderr, "Failed to open directory (at path %s) for recursing, failing with error: %s\n", tbd_path.data(), strerror(errno));
break;
case recurse::operation_result::found_no_matching_files:
if (tbd.options & recurse_subdirectories) {
fprintf(stderr, "No mach-o dynamic library files were found while recursing through directory (at path %s) and its sub-directories\n", tbd_path.data());
} else {
fprintf(stderr, "No mach-o dynamic library files were found while recursing through directory (at path %s)\n", tbd_path.data());
}
break;
}
} else {
auto library_file = macho::file();
auto library_file_open_result = macho::file::open_result::ok;
if (tbd_path == "stdin") {
library_file_open_result = library_file.open_from_dynamic_library(stdin);
} else {
library_file_open_result = library_file.open_from_dynamic_library(tbd_path.data());
}
switch (library_file_open_result) {
case macho::file::open_result::ok:
break;
case macho::file::open_result::failed_to_open_stream:
if (should_print_paths) {
if (tbd_path == "stdin") {
fprintf(stderr, "Failed to open file (in stdin) for reading, failing with error: %s\n", strerror(errno));
} else {
fprintf(stderr, "Failed to open file (at path %s) for reading, failing with error: %s\n", tbd_path.data(), strerror(errno));
}
} else {
fprintf(stderr, "Failed to open file at provided path for reading, failing with error: %s\n", strerror(errno));
}
break;
case macho::file::open_result::failed_to_retrieve_information:
if (should_print_paths) {
if (tbd_path == "stdin") {
fprintf(stderr, "Failed to retrieve information necessary for processing file (in stdin), failing with error: %s\n", strerror(errno));
} else {
fprintf(stderr, "Failed to retrieve information necessary for processing file (at path %s), failing with error: %s\n", tbd_path.data(), strerror(errno));
}
} else {
fprintf(stderr, "Failed to retrieve information necessary for processing file at provided path, failing with error: %s\n", strerror(errno));
}
break;
case macho::file::open_result::failed_to_allocate_memory:
if (should_print_paths) {
if (tbd_path == "stdin") {
fputs("Failed to allocate memory necessary for processing file (in stdin)\n", stderr);
} else {
fprintf(stderr, "Failed to allocate memory necessary for processing file (at path %s)\n", tbd_path.data());
}
} else {
fputs("Failed to allocate memory necessary for processing file at provided path\n", stderr);
}
break;
case macho::file::open_result::stream_seek_error:
case macho::file::open_result::stream_read_error:
if (should_print_paths) {
if (tbd_path == "stdin") {
fprintf(stderr, "Encountered an error while reading through file (in stdin), likely not a valid mach-o. Reading failed with error: %s\n", strerror(library_file.stream.error()));
} else {
fprintf(stderr, "Encountered an error while reading through file (at path %s), likely not a valid mach-o. Reading failed with error: %s\n", tbd_path.data(), strerror(library_file.stream.error()));
}
} else {
fprintf(stderr, "Encountered an error while reading through file at provided path, likely not a valid mach-o. Reading failed with error: %s\n", strerror(library_file.stream.error()));
}
break;
case macho::file::open_result::zero_architectures: {
if (should_print_paths) {
if (tbd_path == "stdin") {
fputs("Fat mach-o file (in stdin) does not have any architectures\n", stderr);
} else {
fprintf(stderr, "Fat mach-o file (at path %s) does not have any architectures\n", tbd_path.data());
}
} else {
fputs("Fat mach-o file at provided path does not have any architectures\n", stderr);
}
break;
}
case macho::file::open_result::architectures_goes_past_end_of_file: {
if (should_print_paths) {
if (tbd_path == "stdin") {
fputs("Fat mach-o file (in stdin) has more architectures than it can physically contain\n", stderr);
} else {
fprintf(stderr, "Fat mach-o file (at path %s) has more architectures than it can physically contain\n", tbd_path.data());
}
} else {
fputs("Fat mach-o file at provided path has more architectures than it can physically contain\n", stderr);
}
break;
}
case macho::file::open_result::invalid_container: {
if (should_print_paths) {
if (tbd_path == "stdin") {
fputs("Mach-o file (in stdin) is invalid\n", stderr);
} else {
fprintf(stderr, "Mach-o file (at path %s) is invalid\n", tbd_path.data());
}
} else {
fputs("Mach-o file at provided path is invalid\n", stderr);
}
break;
}
case macho::file::open_result::not_a_macho: {
if (should_print_paths) {
if (tbd_path == "stdin") {
fputs("File (in stdin) is not a valid mach-o\n", stderr);
} else {
fprintf(stderr, "File (at path %s) is not a valid mach-o\n", tbd_path.data());
}
} else {
fputs("File at provided path is not a valid mach-o\n", stderr);
}
break;
}
case macho::file::open_result::not_a_library: {
if (should_print_paths) {
if (tbd_path == "stdin") {
fputs("Mach-o file (in stdin) is not a mach-o library\n", stderr);
} else {
fprintf(stderr, "Mach-o file (at path %s) is not a mach-o library\n", tbd_path.data());
}
} else {
fputs("Mach-o file at provided path is not a valid mach-o library\n", stderr);
}
break;
}
case macho::file::open_result::not_a_dynamic_library: {
if (should_print_paths) {
if (tbd_path == "stdin") {
fputs("Mach-o file (in stdin) is not a mach-o dynamic library\n", stderr);
} else {
fprintf(stderr, "Mach-o file (at path %s) is not a mach-o dynamic library\n", tbd_path.data());
}
} else {
fputs("Mach-o file at provided path is not a valid mach-o dynamic library\n", stderr);
}
break;
}
}
if (library_file_open_result != macho::file::open_result::ok) {
continue;
}
auto output_file = stdout;
auto tbd_output_path_creation_terminator = static_cast<char *>(nullptr);
if (!tbd_output_path.empty()) {
auto last_file_descriptor = -1;
const auto result = recursive::mkdir::perform_with_last_as_file(tbd_output_path.data(), &tbd_output_path_creation_terminator, &last_file_descriptor);
if (result != recursive::mkdir::result::ok) {
switch (result) {
case recursive::mkdir::result::ok:
case recursive::mkdir::result::failed_to_create_last_as_directory:
case recursive::mkdir::result::last_already_exists_not_as_directory:
break;
case recursive::mkdir::result::failed_to_create_intermediate_directories:
if (should_print_paths) {
fprintf(stderr, "Failed to create intermediate directories for output-path (%s), failing with error: %s\n", tbd_output_path.data(), strerror(errno));
} else {
fprintf(stderr, "Failed to create intermediate directories for provided output-path, failing with error: %s\n", strerror(errno));
}
break;
case recursive::mkdir::result::failed_to_create_last_as_file:
if (should_print_paths) {
fprintf(stderr, "Failed to create file at output-path (%s), failing with error: %s\n", tbd_output_path.data(), strerror(errno));
} else {
fprintf(stderr, "Failed to create file at provided output-path, failing with error: %s\n", strerror(errno));
}
case recursive::mkdir::result::last_already_exists_not_as_file:
if (should_print_paths) {
fprintf(stderr, "Failed to create file at output-path (%s), as object (not of type file) already exists\n", tbd_output_path.data());
} else {
fputs("Failed to create file at provided output-path, as object (not of type file) already exists\n", stderr);
}
}
continue;
}
if (last_file_descriptor != -1) {
output_file = fdopen(last_file_descriptor, "w");
} else {
output_file = fopen(tbd_output_path.data(), "w");
}
if (!output_file) {
if (should_print_paths) {
fprintf(stderr, "Failed to open file (at path %s) for writing, failing with error: %s\n", tbd_output_path.data(), strerror(errno));
} else {
fprintf(stderr, "Failed to open file at provided output-path for writing, failing with error: %s\n", strerror(errno));
}
continue;
}
}
auto tbd_creation_options = static_cast<uint64_t>(creation_handling_print_paths);
if (tbd.options & dont_print_warnings) {
tbd_creation_options |= creation_handling_dont_print_warnings;
}
if (tbd.constraint == macho::utils::tbd::objc_constraint::no_value) {
tbd.constraint = objc_constraint;
}
if (tbd.platform == macho::utils::tbd::platform::none) {
tbd.platform = platform;
}
if (tbd.version == macho::utils::tbd::version::none) {
tbd.version = version;
}
if (!tbd.architectures) {
tbd.architectures = architectures;
}
if (!tbd.architecture_overrides) {
tbd.architecture_overrides = architecture_overrides;
}
const auto result = create_tbd_file(tbd_path.data(), library_file, tbd_output_path.data(), output_file, macho::utils::tbd::options(tbd.options), tbd.flags, tbd.constraint, tbd.platform, tbd.version, tbd.architectures, tbd.architecture_overrides, tbd_creation_options);
if (!tbd_output_path.empty()) {
if (!result) {
if (tbd_output_path_creation_terminator != nullptr) {
const auto remove_result = recursive::remove::perform(tbd_output_path.data(), tbd_output_path_creation_terminator);
switch (remove_result) {
case recursive::remove::result::ok:
break;
case recursive::remove::result::failed_to_remove_directory:
*tbd_output_path_creation_terminator = '\0';
fprintf(stderr, "Failed to remove created-directory at path (%s), failing with error: %s\n", tbd_output_path.data(), strerror(errno));
break;
case recursive::remove::result::failed_to_remove_subdirectories: {
const auto &tbd_output_path_creation_terminator_character = *tbd_output_path_creation_terminator;
*tbd_output_path_creation_terminator = '\0';
fprintf(stderr, "Failed to remove created sub-directories of path (%s)", tbd_output_path.data());
*tbd_output_path_creation_terminator = tbd_output_path_creation_terminator_character;
fprintf(stderr, ", full path being (%s), failing with error: %s\n", tbd_output_path.data(), strerror(errno));
break;
}
case recursive::remove::result::directory_doesnt_exist: {
*tbd_output_path_creation_terminator = '\0';
fprintf(stderr, "Internal Error: Failed to remove created directory at path (%s) as directory at path has already been removed/never created", tbd_output_path.data());
break;
}
case recursive::remove::result::sub_directory_doesnt_exist: {
const auto &tbd_output_path_creation_terminator_character = *tbd_output_path_creation_terminator;
*tbd_output_path_creation_terminator = '\0';
fprintf(stderr, "Internal Error: Failed to remove created sub-directories at path (%s)", tbd_output_path.data());
*tbd_output_path_creation_terminator = tbd_output_path_creation_terminator_character;
fprintf(stderr, ", full path being (%s), as directory at path has already removed/never existed ", tbd_output_path.data());
break;
}
}
}
}
fclose(output_file);
}
}
}
return 0;
}
| 48.855352 | 390 | 0.529213 | [
"object",
"vector"
] |
4fd601264a2e7b059b76e3b4b5edbeb9665ceae6 | 21,010 | cc | C++ | video_engine/test/auto_test/source/vie_autotest_capture.cc | TeamNuclear/external_chromium_org_third_party_webrtc | 5bd5c72d7c01872fea80698dac196ff9a01dfcba | [
"DOC",
"BSD-3-Clause"
] | 1 | 2019-02-22T05:37:57.000Z | 2019-02-22T05:37:57.000Z | video_engine/test/auto_test/source/vie_autotest_capture.cc | TeamNuclear/external_chromium_org_third_party_webrtc | 5bd5c72d7c01872fea80698dac196ff9a01dfcba | [
"DOC",
"BSD-3-Clause"
] | null | null | null | video_engine/test/auto_test/source/vie_autotest_capture.cc | TeamNuclear/external_chromium_org_third_party_webrtc | 5bd5c72d7c01872fea80698dac196ff9a01dfcba | [
"DOC",
"BSD-3-Clause"
] | 2 | 2016-04-27T21:12:18.000Z | 2016-12-25T05:26:28.000Z | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "gflags/gflags.h"
#include "webrtc/common_types.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/video_capture/include/video_capture_factory.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/video_engine/include/vie_base.h"
#include "webrtc/video_engine/include/vie_capture.h"
#include "webrtc/video_engine/include/vie_codec.h"
#include "webrtc/video_engine/include/vie_network.h"
#include "webrtc/video_engine/include/vie_render.h"
#include "webrtc/video_engine/include/vie_rtp_rtcp.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest_defines.h"
#include "webrtc/video_engine/test/libvietest/include/tb_interfaces.h"
#include "webrtc/video_engine/test/libvietest/include/tb_video_channel.h"
#include "webrtc/voice_engine/include/voe_base.h"
DEFINE_bool(capture_test_ensure_resolution_alignment_in_capture_device, true,
"If true, we will give resolutions slightly below a reasonable "
"value to test the camera's ability to choose a good resolution. "
"If false, we will provide reasonable resolutions instead.");
class CaptureObserver : public webrtc::ViECaptureObserver {
public:
CaptureObserver()
: brightness_(webrtc::Normal),
alarm_(webrtc::AlarmCleared),
frame_rate_(0) {}
virtual void BrightnessAlarm(const int capture_id,
const webrtc::Brightness brightness) {
brightness_ = brightness;
switch (brightness) {
case webrtc::Normal:
ViETest::Log(" BrightnessAlarm Normal");
break;
case webrtc::Bright:
ViETest::Log(" BrightnessAlarm Bright");
break;
case webrtc::Dark:
ViETest::Log(" BrightnessAlarm Dark");
break;
}
}
virtual void CapturedFrameRate(const int capture_id,
const unsigned char frame_rate) {
ViETest::Log(" CapturedFrameRate %u", frame_rate);
frame_rate_ = frame_rate;
}
virtual void NoPictureAlarm(const int capture_id,
const webrtc::CaptureAlarm alarm) {
alarm_ = alarm;
if (alarm == webrtc::AlarmRaised) {
ViETest::Log("NoPictureAlarm CARaised.");
} else {
ViETest::Log("NoPictureAlarm CACleared.");
}
}
webrtc::Brightness brightness_;
webrtc::CaptureAlarm alarm_;
unsigned char frame_rate_;
};
class CaptureEffectFilter : public webrtc::ViEEffectFilter {
public:
CaptureEffectFilter(unsigned int expected_width, unsigned int expected_height)
: number_of_captured_frames_(0),
expected_width_(expected_width),
expected_height_(expected_height) {
}
// Implements video_engineEffectFilter.
virtual int Transform(int size,
unsigned char* frame_buffer,
int64_t ntp_time_ms,
unsigned int timestamp,
unsigned int width,
unsigned int height) {
EXPECT_TRUE(frame_buffer != NULL);
EXPECT_EQ(expected_width_, width);
EXPECT_EQ(expected_height_, height);
++number_of_captured_frames_;
return 0;
}
int number_of_captured_frames_;
protected:
unsigned int expected_width_;
unsigned int expected_height_;
};
void ViEAutoTest::ViECaptureStandardTest() {
/// **************************************************************
// Begin create/initialize WebRTC Video Engine for testing
/// **************************************************************
/// **************************************************************
// Engine ready. Begin testing class
/// **************************************************************
TbInterfaces video_engine("video_engineCaptureStandardTest");
webrtc::VideoCaptureModule::DeviceInfo* dev_info =
webrtc::VideoCaptureFactory::CreateDeviceInfo(0);
ASSERT_TRUE(dev_info != NULL);
int number_of_capture_devices = dev_info->NumberOfDevices();
ViETest::Log("Number of capture devices %d",
number_of_capture_devices);
ASSERT_GT(number_of_capture_devices, 0)
<< "This test requires a capture device (i.e. a webcam)";
#if !defined(WEBRTC_MAC)
int capture_device_id[10] = {0};
webrtc::VideoCaptureModule* vcpms[10] = {0};
#endif
// Check capabilities
for (int device_index = 0; device_index < number_of_capture_devices;
++device_index) {
char device_name[128];
char device_unique_name[512];
EXPECT_EQ(0, dev_info->GetDeviceName(device_index,
device_name,
sizeof(device_name),
device_unique_name,
sizeof(device_unique_name)));
ViETest::Log("Found capture device %s\nUnique name %s",
device_name, device_unique_name);
#if !defined(WEBRTC_MAC) // these functions will return -1
int number_of_capabilities =
dev_info->NumberOfCapabilities(device_unique_name);
EXPECT_GT(number_of_capabilities, 0);
for (int cap_index = 0; cap_index < number_of_capabilities; ++cap_index) {
webrtc::VideoCaptureCapability capability;
EXPECT_EQ(0, dev_info->GetCapability(device_unique_name, cap_index,
capability));
ViETest::Log("Capture capability %d (of %u)", cap_index + 1,
number_of_capabilities);
ViETest::Log("width %d, height %d, frame rate %d",
capability.width, capability.height, capability.maxFPS);
ViETest::Log("expected delay %d, color type %d, encoding %d",
capability.expectedCaptureDelay, capability.rawType,
capability.codecType);
EXPECT_GT(capability.width, 0);
EXPECT_GT(capability.height, 0);
EXPECT_GT(capability.maxFPS, -1); // >= 0
EXPECT_GT(capability.expectedCaptureDelay, 0);
}
#endif
}
// Capture Capability Functions are not supported on WEBRTC_MAC.
#if !defined(WEBRTC_MAC)
// Check allocation. Try to allocate them all after each other.
for (int device_index = 0; device_index < number_of_capture_devices;
++device_index) {
char device_name[128];
char device_unique_name[512];
EXPECT_EQ(0, dev_info->GetDeviceName(device_index,
device_name,
sizeof(device_name),
device_unique_name,
sizeof(device_unique_name)));
webrtc::VideoCaptureModule* vcpm =
webrtc::VideoCaptureFactory::Create(device_index, device_unique_name);
EXPECT_TRUE(vcpm != NULL);
if (!vcpm)
continue;
vcpm->AddRef();
vcpms[device_index] = vcpm;
EXPECT_EQ(0, video_engine.capture->AllocateCaptureDevice(
*vcpm, capture_device_id[device_index]));
webrtc::VideoCaptureCapability capability;
EXPECT_EQ(0, dev_info->GetCapability(device_unique_name, 0, capability));
// Test that the camera select the closest capability to the selected
// width and height.
CaptureEffectFilter filter(capability.width, capability.height);
EXPECT_EQ(0, video_engine.image_process->RegisterCaptureEffectFilter(
capture_device_id[device_index], filter));
ViETest::Log("Testing Device %s capability width %d height %d",
device_unique_name, capability.width, capability.height);
if (FLAGS_capture_test_ensure_resolution_alignment_in_capture_device) {
// This tests that the capture device properly aligns to a
// multiple of 16 (or at least 8).
capability.height = capability.height - 2;
capability.width = capability.width - 2;
}
webrtc::CaptureCapability vie_capability;
vie_capability.width = capability.width;
vie_capability.height = capability.height;
vie_capability.codecType = capability.codecType;
vie_capability.maxFPS = capability.maxFPS;
vie_capability.rawType = capability.rawType;
EXPECT_EQ(0, video_engine.capture->StartCapture(
capture_device_id[device_index], vie_capability));
webrtc::TickTime start_time = webrtc::TickTime::Now();
while (filter.number_of_captured_frames_ < 10 &&
(webrtc::TickTime::Now() - start_time).Milliseconds() < 10000) {
AutoTestSleep(100);
}
EXPECT_GT(filter.number_of_captured_frames_, 9)
<< "Should capture at least some frames";
EXPECT_EQ(0, video_engine.image_process->DeregisterCaptureEffectFilter(
capture_device_id[device_index]));
#ifdef WEBRTC_ANDROID // Can only allocate one camera at the time on Android.
EXPECT_EQ(0, video_engine.capture->StopCapture(
capture_device_id[device_index]));
EXPECT_EQ(0, video_engine.capture->ReleaseCaptureDevice(
capture_device_id[device_index]));
#endif
}
/// **************************************************************
// Testing finished. Tear down Video Engine
/// **************************************************************
delete dev_info;
// Stop all started capture devices.
for (int device_index = 0; device_index < number_of_capture_devices;
++device_index) {
#if !defined(WEBRTC_ANDROID)
// Don't stop on Android since we can only allocate one camera.
EXPECT_EQ(0, video_engine.capture->StopCapture(
capture_device_id[device_index]));
EXPECT_EQ(0, video_engine.capture->ReleaseCaptureDevice(
capture_device_id[device_index]));
#endif // !WEBRTC_ANDROID
if (vcpms[device_index])
vcpms[device_index]->Release();
}
#endif // !WEBRTC_MAC
}
void ViEAutoTest::ViECaptureExtendedTest() {
ViECaptureExternalCaptureTest();
}
void ViEAutoTest::ViECaptureAPITest() {
/// **************************************************************
// Begin create/initialize WebRTC Video Engine for testing
/// **************************************************************
/// **************************************************************
// Engine ready. Begin testing class
/// **************************************************************
TbInterfaces video_engine("video_engineCaptureAPITest");
video_engine.capture->NumberOfCaptureDevices();
char device_name[128];
char device_unique_name[512];
int capture_id = 0;
webrtc::VideoCaptureModule::DeviceInfo* dev_info =
webrtc::VideoCaptureFactory::CreateDeviceInfo(0);
ASSERT_TRUE(dev_info != NULL);
ASSERT_GT(dev_info->NumberOfDevices(), 0u)
<< "This test requires a capture device (i.e. a webcam)";
// Get the first capture device
EXPECT_EQ(0, dev_info->GetDeviceName(0, device_name,
sizeof(device_name),
device_unique_name,
sizeof(device_unique_name)));
webrtc::VideoCaptureModule* vcpm =
webrtc::VideoCaptureFactory::Create(0, device_unique_name);
vcpm->AddRef();
EXPECT_TRUE(vcpm != NULL);
// Allocate capture device.
EXPECT_EQ(0, video_engine.capture->AllocateCaptureDevice(*vcpm, capture_id));
// Start the capture device.
EXPECT_EQ(0, video_engine.capture->StartCapture(capture_id));
// Start again. Should fail.
EXPECT_NE(0, video_engine.capture->StartCapture(capture_id));
EXPECT_EQ(kViECaptureDeviceAlreadyStarted, video_engine.LastError());
// Start invalid capture device.
EXPECT_NE(0, video_engine.capture->StartCapture(capture_id + 1));
EXPECT_EQ(kViECaptureDeviceDoesNotExist, video_engine.LastError());
// Stop invalid capture device.
EXPECT_NE(0, video_engine.capture->StopCapture(capture_id + 1));
EXPECT_EQ(kViECaptureDeviceDoesNotExist, video_engine.LastError());
// Stop the capture device.
EXPECT_EQ(0, video_engine.capture->StopCapture(capture_id));
// Stop the capture device again.
EXPECT_NE(0, video_engine.capture->StopCapture(capture_id));
EXPECT_EQ(kViECaptureDeviceNotStarted, video_engine.LastError());
// Connect to invalid channel.
EXPECT_NE(0, video_engine.capture->ConnectCaptureDevice(capture_id, 0));
EXPECT_EQ(kViECaptureDeviceInvalidChannelId,
video_engine.LastError());
TbVideoChannel channel(video_engine);
// Connect invalid capture_id.
EXPECT_NE(0, video_engine.capture->ConnectCaptureDevice(capture_id + 1,
channel.videoChannel));
EXPECT_EQ(kViECaptureDeviceDoesNotExist, video_engine.LastError());
// Connect the capture device to the channel.
EXPECT_EQ(0, video_engine.capture->ConnectCaptureDevice(capture_id,
channel.videoChannel));
// Connect the channel again.
EXPECT_NE(0, video_engine.capture->ConnectCaptureDevice(capture_id,
channel.videoChannel));
EXPECT_EQ(kViECaptureDeviceAlreadyConnected,
video_engine.LastError());
// Start the capture device.
EXPECT_EQ(0, video_engine.capture->StartCapture(capture_id));
// Release invalid capture device.
EXPECT_NE(0, video_engine.capture->ReleaseCaptureDevice(capture_id + 1));
EXPECT_EQ(kViECaptureDeviceDoesNotExist, video_engine.LastError());
// Release the capture device.
EXPECT_EQ(0, video_engine.capture->ReleaseCaptureDevice(capture_id));
// Release the capture device again.
EXPECT_NE(0, video_engine.capture->ReleaseCaptureDevice(capture_id));
EXPECT_EQ(kViECaptureDeviceDoesNotExist, video_engine.LastError());
// Test GetOrientation.
webrtc::VideoCaptureRotation orientation;
char dummy_name[5];
EXPECT_NE(0, dev_info->GetOrientation(dummy_name, orientation));
// Test SetRotation.
EXPECT_NE(0, video_engine.capture->SetRotateCapturedFrames(
capture_id, webrtc::RotateCapturedFrame_90));
EXPECT_EQ(kViECaptureDeviceDoesNotExist, video_engine.LastError());
// Allocate capture device.
EXPECT_EQ(0, video_engine.capture->AllocateCaptureDevice(*vcpm, capture_id));
EXPECT_EQ(0, video_engine.capture->SetRotateCapturedFrames(
capture_id, webrtc::RotateCapturedFrame_0));
EXPECT_EQ(0, video_engine.capture->SetRotateCapturedFrames(
capture_id, webrtc::RotateCapturedFrame_90));
EXPECT_EQ(0, video_engine.capture->SetRotateCapturedFrames(
capture_id, webrtc::RotateCapturedFrame_180));
EXPECT_EQ(0, video_engine.capture->SetRotateCapturedFrames(
capture_id, webrtc::RotateCapturedFrame_270));
// Release the capture device
EXPECT_EQ(0, video_engine.capture->ReleaseCaptureDevice(capture_id));
/// **************************************************************
// Testing finished. Tear down Video Engine
/// **************************************************************
delete dev_info;
vcpm->Release();
}
void ViEAutoTest::ViECaptureExternalCaptureTest() {
/// **************************************************************
// Begin create/initialize WebRTC Video Engine for testing
/// **************************************************************
TbInterfaces video_engine("video_engineCaptureExternalCaptureTest");
TbVideoChannel channel(video_engine);
channel.StartReceive();
channel.StartSend();
webrtc::VideoCaptureExternal* external_capture = NULL;
int capture_id = 0;
// Allocate the external capture device.
webrtc::VideoCaptureModule* vcpm =
webrtc::VideoCaptureFactory::Create(0, external_capture);
EXPECT_TRUE(vcpm != NULL);
EXPECT_TRUE(external_capture != NULL);
vcpm->AddRef();
EXPECT_EQ(0, video_engine.capture->AllocateCaptureDevice(*vcpm, capture_id));
// Connect the capture device to the channel.
EXPECT_EQ(0, video_engine.capture->ConnectCaptureDevice(capture_id,
channel.videoChannel));
// Render the local capture.
EXPECT_EQ(0, video_engine.render->AddRenderer(capture_id, _window1, 1, 0.0,
0.0, 1.0, 1.0));
// Render the remote capture.
EXPECT_EQ(0, video_engine.render->AddRenderer(channel.videoChannel, _window2,
1, 0.0, 0.0, 1.0, 1.0));
EXPECT_EQ(0, video_engine.render->StartRender(capture_id));
EXPECT_EQ(0, video_engine.render->StartRender(channel.videoChannel));
// Register observer.
CaptureObserver observer;
EXPECT_EQ(0, video_engine.capture->RegisterObserver(capture_id, observer));
// Enable brightness alarm.
EXPECT_EQ(0, video_engine.capture->EnableBrightnessAlarm(capture_id, true));
CaptureEffectFilter effect_filter(176, 144);
EXPECT_EQ(0, video_engine.image_process->RegisterCaptureEffectFilter(
capture_id, effect_filter));
// Call started.
ViETest::Log("You should see local preview from external capture\n"
"in window 1 and the remote video in window 2.\n");
/// **************************************************************
// Engine ready. Begin testing class
/// **************************************************************
const unsigned int video_frame_length = (176 * 144 * 3) / 2;
unsigned char* video_frame = new unsigned char[video_frame_length];
memset(video_frame, 128, 176 * 144);
int frame_count = 0;
webrtc::VideoCaptureCapability capability;
capability.width = 176;
capability.height = 144;
capability.rawType = webrtc::kVideoI420;
ViETest::Log("Testing external capturing and frame rate callbacks.");
// TODO(mflodman) Change when using a real file!
// while (fread(video_frame, video_frame_length, 1, foreman) == 1)
while (frame_count < 120) {
external_capture->IncomingFrame(
video_frame, video_frame_length, capability,
webrtc::TickTime::MillisecondTimestamp());
AutoTestSleep(33);
if (effect_filter.number_of_captured_frames_ > 2) {
EXPECT_EQ(webrtc::Normal, observer.brightness_) <<
"Brightness or picture alarm should not have been called yet.";
EXPECT_EQ(webrtc::AlarmCleared, observer.alarm_) <<
"Brightness or picture alarm should not have been called yet.";
}
frame_count++;
}
// Test brightness alarm.
// Test bright image.
for (int i = 0; i < 176 * 144; ++i) {
if (video_frame[i] <= 155)
video_frame[i] = video_frame[i] + 100;
else
video_frame[i] = 255;
}
ViETest::Log("Testing Brighness alarm");
for (int frame = 0; frame < 30; ++frame) {
external_capture->IncomingFrame(
video_frame, video_frame_length, capability,
webrtc::TickTime::MillisecondTimestamp());
AutoTestSleep(33);
}
EXPECT_EQ(webrtc::Bright, observer.brightness_) <<
"Should be bright at this point since we are using a bright image.";
// Test Dark image
for (int i = 0; i < 176 * 144; ++i) {
video_frame[i] = video_frame[i] > 200 ? video_frame[i] - 200 : 0;
}
for (int frame = 0; frame < 30; ++frame) {
external_capture->IncomingFrame(
video_frame, video_frame_length, capability,
webrtc::TickTime::MillisecondTimestamp());
AutoTestSleep(33);
}
EXPECT_EQ(webrtc::Dark, observer.brightness_) <<
"Should be dark at this point since we are using a dark image.";
EXPECT_GT(effect_filter.number_of_captured_frames_, 150) <<
"Frames should have been played.";
EXPECT_GE(observer.frame_rate_, 29) <<
"Frame rate callback should be approximately correct.";
EXPECT_LE(observer.frame_rate_, 30) <<
"Frame rate callback should be approximately correct.";
// Test no picture alarm
ViETest::Log("Testing NoPictureAlarm.");
AutoTestSleep(1050);
EXPECT_EQ(webrtc::AlarmRaised, observer.alarm_) <<
"No picture alarm should be raised.";
for (int frame = 0; frame < 10; ++frame) {
external_capture->IncomingFrame(
video_frame, video_frame_length, capability,
webrtc::TickTime::MillisecondTimestamp());
AutoTestSleep(33);
}
EXPECT_EQ(webrtc::AlarmCleared, observer.alarm_) <<
"Alarm should be cleared since ge just got some data.";
delete video_frame;
// Release the capture device
EXPECT_EQ(0, video_engine.capture->ReleaseCaptureDevice(capture_id));
// Release the capture device again
EXPECT_NE(0, video_engine.capture->ReleaseCaptureDevice(capture_id));
EXPECT_EQ(kViECaptureDeviceDoesNotExist, video_engine.LastError());
vcpm->Release();
/// **************************************************************
// Testing finished. Tear down Video Engine
/// **************************************************************
}
| 38.692449 | 80 | 0.652594 | [
"render",
"transform"
] |
4fd84f03fddad0e6318e9a7e535888e8041d636d | 2,238 | cpp | C++ | tests/cctlib_reader.cpp | wliuxingxiangyu/cctlib | 0d6eb43ffa813afb2c65640fc7331fbe1ebde92b | [
"MIT"
] | 8 | 2015-10-19T22:52:39.000Z | 2018-02-12T18:57:19.000Z | tests/cctlib_reader.cpp | wliuxingxiangyu/cctlib | 0d6eb43ffa813afb2c65640fc7331fbe1ebde92b | [
"MIT"
] | 1 | 2017-05-18T21:20:34.000Z | 2017-05-18T21:20:34.000Z | tests/cctlib_reader.cpp | wliuxingxiangyu/cctlib | 0d6eb43ffa813afb2c65640fc7331fbe1ebde92b | [
"MIT"
] | 4 | 2015-11-11T01:06:07.000Z | 2021-04-26T04:56:29.000Z | // @COPYRIGHT@
// Licensed under MIT license.
// See LICENSE.TXT file in the project root for more information.
// ==============================================================
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sstream>
#include "pin.H"
#include "cctlib.H"
using namespace std;
using namespace PinCCTLib;
INT32 Usage2() {
PIN_ERROR("DeadSPy is a PinTool which tracks each memory access and reports dead writes.\n" + KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
// Main for DeadSpy, initialize the tool, register instrumentation functions and call the target program.
FILE* gTraceFile;
// Initialized the needed data structures before launching the target program
void ClientInit(int argc, char* argv[]) {
// Create output file
char name[MAX_FILE_PATH] = "client.out.";
char* envPath = getenv("CCTLIB_CLIENT_OUTPUT_FILE");
if(envPath) {
// assumes max of MAX_FILE_PATH
strcpy(name, envPath);
}
gethostname(name + strlen(name), MAX_FILE_PATH - strlen(name));
pid_t pid = getpid();
sprintf(name + strlen(name), "%d", pid);
cerr << "\n Creating log file at:" << name << "\n";
gTraceFile = fopen(name, "w");
// print the arguments passed
fprintf(gTraceFile, "\n");
for(int i = 0 ; i < argc; i++) {
fprintf(gTraceFile, "%s ", argv[i]);
}
fprintf(gTraceFile, "\n");
}
int main(int argc, char* argv[]) {
// Initialize PIN
if(PIN_Init(argc, argv))
return Usage2();
// Initialize Symbols, we need them to report functions and lines
PIN_InitSymbols();
// Init Client
ClientInit(argc, argv);
// Init CCTLib postmortem analysis
PinCCTLibInitForPostmortemAnalysis(gTraceFile, "DeadSpy-CCTLib-database");
vector<Context> contextVec;
// Gather full human-readable calling context for a reasonably expected value of context handle.
ContextHandle_t ctxtHndl = 1234; // some reasonably OK handle number
GetFullCallingContext(ctxtHndl, contextVec);
// Print to the log file full human-readable calling context.
PrintFullCallingContext(ctxtHndl);
return 0;
}
| 29.064935 | 137 | 0.659964 | [
"vector"
] |
4fd8bfcccf96fe1d2796609ba2ea0687113f7e4b | 698 | cpp | C++ | src/atcoder/abc079/abc079_c/main_0.cpp | kzmsh/compete | 5cbe8062689a10bd81c97612b800fd434d93aa3f | [
"MIT"
] | null | null | null | src/atcoder/abc079/abc079_c/main_0.cpp | kzmsh/compete | 5cbe8062689a10bd81c97612b800fd434d93aa3f | [
"MIT"
] | null | null | null | src/atcoder/abc079/abc079_c/main_0.cpp | kzmsh/compete | 5cbe8062689a10bd81c97612b800fd434d93aa3f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> numbers(4);
for (size_t i = 0; i < 4; ++i) {
char c;
cin >> c;
numbers[i] = c - '0';
}
for (int i = 0; i < 1 << numbers.size() - 1; ++i) {
int sum = numbers[0];
for (size_t j = 0; j < numbers.size() - 1; ++j) {
sum += ((i & 1 << j) != 0 ? 1 : -1) * numbers[j + 1];
}
if (sum == 7) {
cout << numbers[0];
for (size_t j = 0; j < numbers.size() - 1; ++j) {
cout << ((i & 1 << j) != 0 ? '+' : '-') << numbers[j + 1];
}
cout << "=7" << endl;
return 0;
}
}
}
| 24.928571 | 74 | 0.352436 | [
"vector"
] |
4fdea5222a9a5cc1bad403a4ff2839bb22bb32dc | 1,004 | hpp | C++ | doc/html/boost_asio/example/http/server4/request.hpp | Ron2014/boost_1_48_0 | 19673f69677ffcba7c7bd6e08ec07ee3962f161c | [
"BSL-1.0"
] | 2 | 2015-12-04T17:42:55.000Z | 2015-12-04T17:43:16.000Z | libs/asio/example/http/server4/request.hpp | ksundberg/boost-svn | 5694e7831f7afc8f6e25d03d0fd375e7be758d0f | [
"BSL-1.0"
] | 1 | 2018-01-17T10:11:43.000Z | 2018-01-17T10:11:43.000Z | libs/asio/example/http/server4/request.hpp | ksundberg/boost-svn | 5694e7831f7afc8f6e25d03d0fd375e7be758d0f | [
"BSL-1.0"
] | null | null | null | //
// request.hpp
// ~~~~~~~~~~~
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef HTTP_SERVER4_REQUEST_HPP
#define HTTP_SERVER4_REQUEST_HPP
#include <string>
#include <vector>
#include "header.hpp"
namespace http {
namespace server4 {
/// A request received from a client.
struct request
{
/// The request method, e.g. "GET", "POST".
std::string method;
/// The requested URI, such as a path to a file.
std::string uri;
/// Major version number, usually 1.
int http_version_major;
/// Minor version number, usually 0 or 1.
int http_version_minor;
/// The headers included with the request.
std::vector<header> headers;
/// The optional content sent with the request.
std::string content;
};
} // namespace server4
} // namespace http
#endif // HTTP_SERVER4_REQUEST_HPP
| 21.361702 | 79 | 0.701195 | [
"vector"
] |
4fdfed4e6b68079a0895269c0a4d08bde57ba152 | 10,378 | cpp | C++ | oneEngine/oneGame/source/tool/shell_thumbnail_bpd/BpdThumbnailProvider.cpp | skarik/1Engine | 84e846544b4a89af8fd7e9236131363096538ef4 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/tool/shell_thumbnail_bpd/BpdThumbnailProvider.cpp | skarik/1Engine | 84e846544b4a89af8fd7e9236131363096538ef4 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/tool/shell_thumbnail_bpd/BpdThumbnailProvider.cpp | skarik/1Engine | 84e846544b4a89af8fd7e9236131363096538ef4 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z | #include "core/types.h"
#include "core/os.h"
#include "BpdThumbnailProvider.h"
#include "core/system/io/FileWin32Stream.h"
#include "core-ext/system/io/assets/TextureIO.h"
#include "core/math/Math.h"
#define FPF_IMPLEMENTATION
#include "five-pixel-font/five-pixel-font.h"
#include <shlwapi.h>
#include <thumbcache.h> // For IThumbnailProvider.
#include <wincodec.h> // Windows Imaging Codecs
#include <msxml6.h>
#include <new>
#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "windowscodecs.lib")
#pragma comment(lib, "Crypt32.lib")
#pragma comment(lib, "msxml6.lib")
// this thumbnail provider implements IInitializeWithStream to enable being hosted
// in an isolated process for robustness
class CBpdThumbnailProvider : public IInitializeWithStream,
public IThumbnailProvider
{
public:
CBpdThumbnailProvider()
: m_refCount(1), m_stream(NULL)
{
}
virtual ~CBpdThumbnailProvider()
{
if (m_stream)
{
m_stream->Release();
}
}
// IUnknown
virtual HRESULT STDMETHODCALLTYPE
QueryInterface( REFIID riid, void **ppv ) override
{
static const QITAB qit[] =
{
QITABENT(CBpdThumbnailProvider, IInitializeWithStream),
QITABENT(CBpdThumbnailProvider, IThumbnailProvider),
{ 0 },
};
return QISearch(this, qit, riid, ppv);
}
virtual ULONG STDMETHODCALLTYPE
AddRef( void ) override
{
return InterlockedIncrement(&m_refCount);
}
virtual ULONG STDMETHODCALLTYPE
Release( void ) override
{
ULONG refCount = InterlockedDecrement(&m_refCount);
if (refCount <= 0)
{
delete this;
}
return refCount;
}
// IInitializeWithStream
IFACEMETHODIMP Initialize(IStream *pStream, DWORD grfMode);
// IThumbnailProvider
IFACEMETHODIMP GetThumbnail(UINT cx, HBITMAP *phbmp, WTS_ALPHATYPE *pdwAlpha);
private:
long m_refCount;
IStream* m_stream; // provided during initialization.
};
HRESULT CBpdThumbnailProvider_CreateInstance ( REFIID riid, void **ppv )
{
CBpdThumbnailProvider *pNew = new (std::nothrow) CBpdThumbnailProvider();
HRESULT hr = pNew ? S_OK : E_OUTOFMEMORY;
if (SUCCEEDED(hr))
{
hr = pNew->QueryInterface(riid, ppv);
pNew->Release();
}
return hr;
}
// IInitializeWithStream
IFACEMETHODIMP CBpdThumbnailProvider::Initialize ( IStream *pStream, DWORD )
{
HRESULT hr = E_UNEXPECTED; // can only be inited once
if (m_stream == NULL)
{
// take a reference to the stream if we have not been inited yet
hr = pStream->QueryInterface(&m_stream);
}
return hr;
}
unsigned char fpf_texture [FPF_TEXTURE_WIDTH * FPF_TEXTURE_HEIGHT];
static void InitFontRendering ( void )
{
fpf_create_alpha_texture(fpf_texture, FPF_TEXTURE_WIDTH * FPF_TEXTURE_HEIGHT, FPF_TEXTURE_WIDTH, FPF_RASTER_Y_AXIS);
}
struct ByteType
{
BYTE b;
BYTE g;
BYTE r;
BYTE a;
};
static void PutCharScale ( ByteType* dest, uint x, uint y, uint w, uint h, float scale, const char character )
{
uint fpf_x = 0;
uint fpf_y = 0;
fpf_get_glyph_position( character, &fpf_x, &fpf_y );
uint scale_size = math::round(5 * scale);
for ( uint cx = 0; cx < scale_size; ++cx )
{
for ( uint cy = 0; cy < scale_size; ++cy )
{
if ( x + cx < 0 || x + cx >= w
|| y + cy < 0 || y + cy >= h )
{ // Skip out-of-bounds
continue;
}
// Get the 5x5 lookup value
uint cx_char = (uint)(5 * (cx / (float)scale_size));
uint cy_char = (uint)(5 * (cy / (float)scale_size));
uchar source_alpha = fpf_texture[ (fpf_x + cx_char) + (fpf_y + cy_char) * FPF_TEXTURE_WIDTH ];
ByteType& dest_pixel = dest[ (x + cx) + (y + cy) * w ];
dest_pixel.r = (uint8)math::lerp<float>( source_alpha / 255.0F, (float)dest_pixel.r, 255.0F );
dest_pixel.g = (uint8)math::lerp<float>( source_alpha / 255.0F, (float)dest_pixel.g, 255.0F );
dest_pixel.b = (uint8)math::lerp<float>( source_alpha / 255.0F, (float)dest_pixel.b, 255.0F );
dest_pixel.a = (uint8)math::lerp<float>( source_alpha / 255.0F, (float)dest_pixel.a, 255.0F );
}
}
}
static void PutString ( ByteType* dest, uint x, uint y, uint w, uint h, float scale, const char* str )
{
size_t len = strlen(str);
for (int i = 0; i < len; ++i )
{
PutCharScale( dest, math::round(x + i * 6 * scale), y, w, h, scale, str[i] );
}
}
// IThumbnailProvider
IFACEMETHODIMP CBpdThumbnailProvider::GetThumbnail(UINT cx, HBITMAP *phbmp, WTS_ALPHATYPE *pdwAlpha)
{
HRESULT hr;
const uint maxSize = (uint)cx;
// Get the data from the Stream
core::FileWin32StreamRead l_streamWrapper (m_stream);
core::BpdLoader l_loader;
l_loader.m_loadImageInfo = true;
l_loader.LoadBpd(&l_streamWrapper);
l_loader.m_loadImageInfo = false;
// Now that we have the image info, we allocate a buffer for Mip 0.
// BPDs default to 8-bit RGBA for now.
const core::gfx::tex::arColorFormat internalFormat = core::gfx::tex::kColorFormatRGBA8;
const size_t pixelByteSize = core::gfx::tex::getColorFormatByteSize(internalFormat);
const size_t imageByteSize = pixelByteSize * l_loader.info.width * l_loader.info.height * l_loader.info.depth;
char* imageData = new char [imageByteSize];
l_loader.m_buffer_Mipmaps[0] = imageData;
l_loader.m_loadMipmapMask = 0x01 << 0;
bool load_success = l_loader.LoadBpd();
l_loader.m_buffer_Mipmaps[0] = NULL;
// Given the stream earlier, create the raw BPD data from Mip 0.
uint16 output_width, output_height;
BYTE* output_image;
{
float downscaleFactor = std::min<float>( cx / (float)l_loader.info.width, cx / (float)l_loader.info.height );
// Downscale to the given size
const uint16 full_width = (uint16)math::round(l_loader.info.width * downscaleFactor);
const uint16 full_height = (uint16)math::round(l_loader.info.height * downscaleFactor);
const uint16 block_width = std::max<uint16>(1, l_loader.info.width / full_width);
const uint16 block_height = std::max<uint16>(1, l_loader.info.height / full_height);
// Allocate the data and clear to zero
output_image = new BYTE [full_width * full_height * 4];
memset( output_image, 0, full_width * full_height * 4 );
// Declare the pixel layout
struct trSrcPixelLayout
{
uint8 r;
uint8 g;
uint8 b;
uint8 a;
};
struct trDestPixelLayout
{
BYTE b;
BYTE g;
BYTE r;
BYTE a;
};
if (downscaleFactor <= 1.0)
{
// Downscale the image
for ( uint x = 0; x < full_width; ++x )
{
for ( uint y = 0; y < full_height; ++y )
{
uint32 agg_r = 0;
uint32 agg_g = 0;
uint32 agg_b = 0;
uint32 agg_a = 0;
for ( uint block_x = 0; block_x < block_width; ++block_x )
{
for ( uint block_y = 0; block_y < block_height; ++block_y )
{
//trSrcPixelLayout* src_pixel = (trSrcPixelLayout*)&imageData[((x * block_width + block_x) + (y * block_height + block_y) * l_loader.info.height) * pixelByteSize];
// Find closest pixel in the block
uint closest_src_x = (uint)(l_loader.info.width * (x / (float)full_width) + (block_x / (float)l_loader.info.width));
uint closest_src_y = (uint)(l_loader.info.height * (y / (float)full_height) + (block_y / (float)l_loader.info.height));
trSrcPixelLayout* src_pixel = (trSrcPixelLayout*)&imageData[(closest_src_x + closest_src_y * l_loader.info.width) * pixelByteSize];
agg_r += src_pixel->r;
agg_g += src_pixel->g;
agg_b += src_pixel->b;
agg_a += src_pixel->a;
}
}
const uint32_t block_sz = block_width * block_height;
double avg_r = agg_r / (double)(block_sz);
double avg_g = agg_g / (double)(block_sz);
double avg_b = agg_b / (double)(block_sz);
double avg_a = agg_a / (double)(block_sz);
trDestPixelLayout& dest_pixel = *(trDestPixelLayout*)&output_image[(x + y * full_width) * sizeof(trDestPixelLayout)];
dest_pixel.r = (uint8_t)std::min<uint64_t>( math::round(avg_r), 255 );
dest_pixel.g = (uint8_t)std::min<uint64_t>( math::round(avg_g), 255 );
dest_pixel.b = (uint8_t)std::min<uint64_t>( math::round(avg_b), 255 );
dest_pixel.a = (uint8_t)std::min<uint64_t>( math::round(avg_a), 255 );
}
} // End downscaling.
}
else
{
// Upscale the image
for ( uint x = 0; x < full_width; ++x )
{
for ( uint y = 0; y < full_height; ++y )
{
// Find closest pixel
uint closest_src_x = (uint)(l_loader.info.width * (x / (float)full_width));
uint closest_src_y = (uint)(l_loader.info.height * (y / (float)full_height));
trSrcPixelLayout* src_pixel = (trSrcPixelLayout*)&imageData[(closest_src_x + closest_src_y * l_loader.info.height) * pixelByteSize];
trDestPixelLayout& dest_pixel = *(trDestPixelLayout*)&output_image[(x + y * full_width) * sizeof(trDestPixelLayout)];
dest_pixel.r = src_pixel->r;
dest_pixel.g = src_pixel->g;
dest_pixel.b = src_pixel->b;
dest_pixel.a = src_pixel->a;
}
} // End upscaling.
}
// Set output params
output_width = full_width;
output_height = full_height;
}
// Done with image data
delete[] imageData;
// Draw text on the bitmap
{
InitFontRendering();
float textScale = std::max(1.0F, cx / 24.0F);
const char* typeString = "???";
switch ( l_loader.info.type )
{
case core::gfx::tex::kTextureType2D:
typeString = "2D";
break;
case core::gfx::tex::kTextureType3D:
typeString = "3D";
break;
case core::gfx::tex::kTextureType2DArray:
typeString = "2D*A";
break;
case core::gfx::tex::kTextureTypeCube:
typeString = "CUBE";
break;
}
PutString(
(ByteType*)output_image,
1, math::round(output_height - 6 * textScale),
output_width, output_height,
textScale,
typeString );
}
// Create a bitmap
{
BITMAPINFO bmi = {};
bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
bmi.bmiHeader.biWidth = output_width;
bmi.bmiHeader.biHeight = output_height;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
BYTE *pBits;
HBITMAP hbmp = CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, reinterpret_cast<void **>(&pBits), NULL, 0);
hr = hbmp ? S_OK : E_OUTOFMEMORY;
if (SUCCEEDED(hr))
{
// Copy in the rows upside down
for ( uint row = 0; row < output_height; ++row )
{
memcpy( pBits + output_width * 4 * row, output_image + output_width * 4 * (output_height - row - 1), output_width * 4 );
}
*phbmp = hbmp;
}
}
// Done with downscaled data
delete[] output_image;
// Set to ARGB
*pdwAlpha = WTSAT_ARGB;
return S_OK;
}
| 28.510989 | 170 | 0.676527 | [
"3d"
] |
4fe15327996debd500a9666f742f5aefd920e51a | 867,187 | cpp | C++ | N64 Midi Tool/N64MidiLibrary/MidiParse.cpp | RyanTheDevelopan/N64-Tools | c563f4376670f4b5d4ef750bd3773f87822513ac | [
"Unlicense"
] | 1 | 2019-10-16T00:07:45.000Z | 2019-10-16T00:07:45.000Z | N64 Midi Tool/N64MidiLibrary/MidiParse.cpp | bryanperris/N64-Tools | 31d302fbaf76a28dd736c9e8a4602e6494af4f0c | [
"Unlicense"
] | null | null | null | N64 Midi Tool/N64MidiLibrary/MidiParse.cpp | bryanperris/N64-Tools | 31d302fbaf76a28dd736c9e8a4602e6494af4f0c | [
"Unlicense"
] | null | null | null | #include "StdAfx.h"
#include "SharedFunctions.h"
#include "MidiParse.h"
#include <sys/stat.h>
#include "SupermanDecoder.h"
#include "rnc_deco.h"
#include "H20Decoder.h"
#include "TetrisphereDecoder.h"
#include "GECompression.h"
#include "MidwayDecoder.h"
#include "BlitzDecoder.h"
#include "TigDecoder.h"
#include "MarioTennisDecoder.h"
#include "yay0.h"
#include "VigilanteDecoder.h"
#include "FLA2Decoder.h"
#include "RugratsDecoder.h"
#include "flzh_rn.h"
#include "n643docompression.h"
#include "LZARIDecoder.h"
#include "SnowDecoder.h"
#include "ASMICDecoder.h"
#include "NaganoDecoder.h"
#include "yaz0.h"
#include "AidynDecoder.h"
#include "AidynToDCMConvertor.h"
#include "QuakeDecoder.h"
#include <algorithm>
#include <map>
#include <math.h>
void CMidiParse::fprintfIfDebug(FILE* outFileDebug, char* format,...)
{
va_list args;
va_start( args, format );
if (outFileDebug != NULL)
vfprintf(outFileDebug, format, args );
va_end( args );
}
unsigned long CMidiParse::GetVLBytes(byte* vlByteArray, int& offset, unsigned long& original, byte*& altPattern, byte& altOffset, byte& altLength, bool includeFERepeats)
{
unsigned long VLVal = 0; //Vlength Value.
byte TempByte; //Byte value read.
for (; ; )
{
if (altPattern != NULL)
{
TempByte = altPattern[altOffset];
altOffset++;
if (altOffset == altLength)
{
delete [] altPattern;
altPattern = NULL;
altOffset = 0;
altLength = 0;
}
}
else
{
TempByte = vlByteArray[offset];
offset++;
if ((TempByte == 0xFE) && (vlByteArray[offset] != 0xFE) && includeFERepeats)
{
byte repeatFirstByte = vlByteArray[offset];
offset++;
unsigned short repeatDistanceFromBeginningMarker = ((repeatFirstByte << 8) | vlByteArray[offset]);
offset++;
byte repeatCount = vlByteArray[offset];
offset++;
altPattern = new byte[repeatCount];
for (int copy = ((offset - 4) - repeatDistanceFromBeginningMarker); copy < (((offset - 4) - repeatDistanceFromBeginningMarker) + repeatCount); copy++)
{
altPattern[copy - ((offset - 4) - repeatDistanceFromBeginningMarker)] = vlByteArray[copy];
}
altOffset = 0;
altLength = repeatCount;
TempByte = altPattern[altOffset];
altOffset++;
}
else if ((TempByte == 0xFE) && (vlByteArray[offset] == 0xFE) && includeFERepeats)
{
// skip duplicate FEs
offset++;
}
if ((altOffset == altLength) && (altPattern != NULL))
{
delete [] altPattern;
altPattern = NULL;
altOffset = 0;
altLength = 0;
}
}
if ((TempByte >> 7) == 0x1)
{
VLVal += TempByte;
VLVal = VLVal << 8; //Shift to next byte in VLVal.
}
else
{
VLVal += TempByte;
break;
}
}
original = VLVal;
unsigned long Vlength = 0;
for (int c = 0, a = 0; ;c += 8, a+= 7)
{
Vlength += (((VLVal >> c) & 0x7F) << a);
if (c == 24)
break;
}
return Vlength;
}
void CMidiParse::WriteVLBytes(FILE* outFile, unsigned long value, unsigned long length, bool includeFERepeats)
{
byte tempByte;
if (length == 1)
{
tempByte = value & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
}
else if (length == 2)
{
tempByte = (value >> 8) & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
tempByte = value & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
}
else if (length == 3)
{
tempByte = (value >> 16) & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
tempByte = (value >> 8) & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
tempByte = value & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
}
else
{
tempByte = (value >> 24) & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
tempByte = (value >> 8) & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
tempByte = value & 0xFF;
fwrite(&tempByte, 1, 1, outFile);
}
}
unsigned long ReturnVLBytes(unsigned long value, unsigned long& length)
{
byte subValue1 = (value >> 21) & 0x7F;
byte subValue2 = (value >> 14) & 0x7F;
byte subValue3 = (value >> 7) & 0x7F;
byte subValue4 = (value >> 0) & 0x7F;
if (subValue1 > 0)
{
unsigned long newValue = 0x80808000;
newValue |= (subValue1 << 24);
newValue |= (subValue2 << 16);
newValue |= (subValue3 << 8);
newValue |= subValue4;
length = 4;
return newValue;
}
else if (subValue2 > 0)
{
unsigned long newValue = 0x00808000;
newValue |= (subValue2 << 16);
newValue |= (subValue3 << 8);
newValue |= subValue4;
length = 3;
return newValue;
}
else if (subValue3 > 0)
{
unsigned long newValue = 0x00008000;
newValue |= (subValue3 << 8);
newValue |= subValue4;
length = 2;
return newValue;
}
else
{
length = 1;
return value;
}
}
byte CMidiParse::ReadMidiByte(byte* vlByteArray, int& offset, byte*& altPattern, byte& altOffset, byte& altLength, bool includeFERepeats)
{
byte returnByte;
if (altPattern != NULL)
{
returnByte = altPattern[altOffset];
altOffset++;
}
else
{
returnByte = vlByteArray[offset];
offset++;
if ((returnByte == 0xFE) && (vlByteArray[offset] != 0xFE) && includeFERepeats)
{
byte repeatFirstByte = vlByteArray[offset];
offset++;
unsigned long repeatDistanceFromBeginningMarker = ((repeatFirstByte << 8) | vlByteArray[offset]);
offset++;
byte repeatCount = vlByteArray[offset];
offset++;
altPattern = new byte[repeatCount];
for (int copy = ((offset - 4) - repeatDistanceFromBeginningMarker); copy < (((offset - 4) - repeatDistanceFromBeginningMarker) + repeatCount); copy++)
{
altPattern[copy - ((offset - 4) - repeatDistanceFromBeginningMarker)] = vlByteArray[copy];
}
altOffset = 0;
altLength = repeatCount;
returnByte = altPattern[altOffset];
altOffset++;
}
else if ((returnByte == 0xFE) && (vlByteArray[offset] == 0xFE) && includeFERepeats)
{
// skip duplicate FEs
offset++;
}
}
if ((altOffset == altLength) && (altPattern != NULL))
{
delete [] altPattern;
altPattern = NULL;
altOffset = 0;
altLength = 0;
}
return returnByte;
}
CMidiParse::CMidiParse(void)
{
char tempFolder[8000];
::GetCurrentDirectory(8000, tempFolder);
mainFolder.Format("%s\\", tempFolder);
compress = new GECompression();
for (int i = 0; i < 0x20; i++)
trackEventCount[i] = 0;
trackEvents = new TrackEvent *[0x20];
for (unsigned int x = 0; x < 0x20; x++)
{
trackEvents[x] = new TrackEvent[0x30000];
for (int y = 0; y < 0x30000; y++)
trackEvents[x][y].contentSize = NULL;
}
}
CMidiParse::~CMidiParse(void)
{
for (unsigned int x = 0; x < 0x20; x++)
{
for (int y = 0; y < 0x30000; y++)
{
if (trackEvents[x][y].contents != NULL)
{
delete[] trackEvents[x][y].contents;
trackEvents[x][y].contents = NULL;
}
}
delete[] trackEvents[x];
}
delete [] trackEvents;
delete compress;
}
void CMidiParse::GEMidiToMidi(byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool& hasLoopPoint, int& loopStart, int& loopEnd, bool extendTracksToHighest, bool usePitchBendSensitity, int pitchBendSensitity)
{
numberInstruments = 0;
try
{
FILE* outFile = fopen(outFileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return;
}
unsigned long lengthHeader = 0x44;
// parse midi
int trackSize = 0;
for (int i = 0; i < (lengthHeader - 4); i+=4) // ignore last 00000180
{
unsigned long offset = CharArrayToLong(&inputMID[i]);
if (offset != 0)
trackSize++;
}
unsigned long tempLong = Flip32Bit(0x4D546864);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00000006);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00010000 | trackSize);
fwrite(&tempLong, 1 ,4 , outFile);
unsigned long division = CharArrayToLong(&inputMID[0x40]);
unsigned short tempShort = division;
tempShort = Flip16Bit(tempShort);
fwrite(&tempShort, 1 ,2 , outFile);
int counterTrack = 0;
int highestTrackLength = 0;
for (int iii = 0; iii < (lengthHeader - 4); iii+=4) // ignore last 00000180
{
unsigned long absoluteTime = 0;
unsigned long offset = CharArrayToLong(&inputMID[iii]);
int position = offset;
if (position != 0)
{
int previousEventValue = 0;
std::map<int, int> loopEndsWithCount;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
int timePosition = position;
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
absoluteTime += timeTag;
if (absoluteTime > highestTrackLength)
highestTrackLength = absoluteTime;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
if ((loopCount == 0xFF) || (loopCount == 0x00))
{
break;
}
else
{
std::map<int, int>::iterator it = loopEndsWithCount.find(position);
if (it != loopEndsWithCount.end())
{
int countLeft = it->second;
if (countLeft == 0)
{
loopEndsWithCount.erase(it);
}
else
{
loopEndsWithCount[position] = (countLeft - 1);
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
else
{
loopEndsWithCount[position] = loopCount - 1;
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true); // Always FF
}
else if (subType == 0x2F)
{
endFlag = true;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
}
}
}
}
for (int iii = 0; iii < (lengthHeader - 4); iii+=4) // ignore last 00000180
{
unsigned long absoluteTime = 0;
int trackEventCountSub = 0;
TrackEvent* trackEventsSub = new TrackEvent[0x30000];
for (int j = 0; j < 0x30000; j++)
{
trackEventsSub[j].contents = NULL;
trackEventsSub[j].obsoleteEvent = false;
trackEventsSub[j].deltaTime = 0;
trackEventsSub[j].absoluteTime = 0;
}
unsigned long offset = CharArrayToLong(&inputMID[iii]);
int position = offset;
if (position != 0)
{
tempLong = Flip32Bit(0x4D54726B);
fwrite(&tempLong, 1 ,4 , outFile);
int previousEventValue = 0;
std::map<int, int> loopEndsWithCount;
std::vector<int> loopNumbers;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool endFlag = false;
if (usePitchBendSensitity)
{
//https://www.midikits.net/midi_analyser/pitch_bend.htm
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x64;
trackEventsSub[trackEventCountSub].contents[1] = 0x00;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x65;
trackEventsSub[trackEventCountSub].contents[1] = 0x00;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x06;
if (pitchBendSensitity > 0x18)
pitchBendSensitity = 0x18;
trackEventsSub[trackEventCountSub].contents[1] = pitchBendSensitity;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x64;
trackEventsSub[trackEventCountSub].contents[1] = 0x7F;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x65;
trackEventsSub[trackEventCountSub].contents[1] = 0x7F;
trackEventCountSub++;
}
while ((position < inputSize) && !endFlag)
{
if (extendTracksToHighest)
{
if (absoluteTime >= highestTrackLength)
{
trackEventsSub[trackEventCountSub].absoluteTime = highestTrackLength;
trackEventsSub[trackEventCountSub].deltaTime = (highestTrackLength - absoluteTime);
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x2F;
trackEventsSub[trackEventCountSub].contents[1] = 0x0;
trackEventCountSub++;
endFlag = true;
break;
}
}
if (trackEventCountSub >= 0x30000)
{
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
if (trackEventsSub[eventCount].contents != NULL)
{
delete [] trackEventsSub[eventCount].contents;
trackEventsSub[eventCount].contents = NULL;
}
}
delete [] trackEventsSub;
return;
}
int timePosition = position;
unsigned long original;
// trackEventsSub[trackEventCountSub].deltaTime is for loops
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (extendTracksToHighest)
{
if ((absoluteTime + timeTag) > highestTrackLength)
{
trackEventsSub[trackEventCountSub].absoluteTime = highestTrackLength;
trackEventsSub[trackEventCountSub].deltaTime = (highestTrackLength - absoluteTime);
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x2F;
trackEventsSub[trackEventCountSub].contents[1] = 0x0;
trackEventCountSub++;
endFlag = true;
break;
}
}
trackEventsSub[trackEventCountSub].deltaTime += timeTag;
absoluteTime += timeTag;
trackEventsSub[trackEventCountSub].absoluteTime = absoluteTime;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 5;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x51;
trackEventsSub[trackEventCountSub].contents[1] = 0x3;
trackEventsSub[trackEventCountSub].contents[2] = ((microsecondsSinceQuarterNote >> 16) & 0xFF);
trackEventsSub[trackEventCountSub].contents[3] = ((microsecondsSinceQuarterNote >> 8) & 0xFF);
trackEventsSub[trackEventCountSub].contents[4] = ((microsecondsSinceQuarterNote >> 0) & 0xFF);
trackEventCountSub++;
int MICROSECONDS_PER_MINUTE = 60000000;
float beatsPerMinute = (float)MICROSECONDS_PER_MINUTE / (float)microsecondsSinceQuarterNote;
}
else if (subType == 0x2D) // end loop
{
int loopNumber = 0;
if (loopNumbers.size() > 0)
{
loopNumber = loopNumbers.back();
loopNumbers.pop_back();
}
// Fake loop end, controller 103
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 103;
trackEventsSub[trackEventCountSub].contents[1] = loopNumber;
trackEventCountSub++;
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
if ((loopCount == 0xFF) || (loopCount == 0x00))
{
hasLoopPoint = true;
loopEnd = absoluteTime;
if (extendTracksToHighest)
{
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
}
}
else
{
std::map<int, int>::iterator it = loopEndsWithCount.find(position);
if (it != loopEndsWithCount.end())
{
int countLeft = it->second;
if (countLeft == 0)
{
loopEndsWithCount.erase(it);
}
else
{
loopEndsWithCount[position] = (countLeft - 1);
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
else
{
loopEndsWithCount[position] = loopCount - 1;
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true); // Always FF
hasLoopPoint = true;
loopStart = absoluteTime;
// Fake loop start, controller 102
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 102;
trackEventsSub[trackEventCountSub].contents[1] = loopNumber;
trackEventCountSub++;
loopNumbers.push_back(loopNumber);
}
else if (subType == 0x2F)
{
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x2F;
trackEventsSub[trackEventCountSub].contents[1] = 0x0;
trackEventCountSub++;
endFlag = true;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
trackEventsSub[trackEventCountSub].type = previousEventValue;
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
trackEventsSub[trackEventCountSub].type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].durationTime = timeDuration; // to be filled in
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = noteNumber;
trackEventsSub[trackEventCountSub].contents[1] = velocity;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = controllerType;
trackEventsSub[trackEventCountSub].contents[1] = controllerValue;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
trackEventsSub[trackEventCountSub].contentSize = 1;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = instrument;
if (instrument >= numberInstruments)
numberInstruments = (instrument + 1);
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
trackEventsSub[trackEventCountSub].contentSize = 1;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = amount;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = valueLSB;
trackEventsSub[trackEventCountSub].contents[1] = valueMSB;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
fprintf(outFile, "%02X ERROR MISSING PARSE OF TYPE\n", eventVal);
}
}
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
if (trackEventCountSub >= 0x30000)
{
fclose(outFile);
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
if (trackEventsSub[eventCount].contents != NULL)
{
delete [] trackEventsSub[eventCount].contents;
trackEventsSub[eventCount].contents = NULL;
}
}
delete [] trackEventsSub;
return;
}
TrackEvent trackEvent = trackEventsSub[eventCount];
if ((trackEvent.type >= 0x90) && (trackEvent.type < 0xA0))
{
// need to split out
if (trackEvent.durationTime > 0)
{
unsigned long shutoffTime = (trackEvent.absoluteTime + trackEvent.durationTime);
if (eventCount != (trackEventCountSub - 1))
{
for (int i = (eventCount+1); i < trackEventCountSub; i++)
{
if ((trackEventsSub[i].absoluteTime >= shutoffTime) && (i != (trackEventCountSub - 1)))
{
for (int j = (trackEventCountSub - 1); j >= i; j--)
{
trackEventsSub[j+1].absoluteTime = trackEventsSub[j].absoluteTime;
trackEventsSub[j+1].contentSize = trackEventsSub[j].contentSize;
if (trackEventsSub[j+1].contents != NULL)
{
delete [] trackEventsSub[j+1].contents;
trackEventsSub[j+1].contents = NULL;
}
trackEventsSub[j+1].contents = new byte[trackEventsSub[j].contentSize];
for (int r = 0; r < trackEventsSub[j].contentSize; r++)
{
trackEventsSub[j+1].contents[r] = trackEventsSub[j].contents[r];
}
trackEventsSub[j+1].deltaTime = trackEventsSub[j].deltaTime;
trackEventsSub[j+1].durationTime = trackEventsSub[j].durationTime;
trackEventsSub[j+1].obsoleteEvent = trackEventsSub[j].obsoleteEvent;
trackEventsSub[j+1].type = trackEventsSub[j].type;
}
trackEventsSub[i].type = trackEventsSub[eventCount].type;
trackEventsSub[i].absoluteTime = shutoffTime;
trackEventsSub[i].deltaTime = (trackEventsSub[i].absoluteTime - trackEventsSub[i-1].absoluteTime);
trackEventsSub[i].contentSize = trackEventsSub[eventCount].contentSize;
trackEventsSub[i].durationTime = 0;
if (trackEventsSub[i].contents != NULL)
{
delete [] trackEventsSub[i].contents;
}
trackEventsSub[i].contents = new byte[trackEventsSub[i].contentSize];
trackEventsSub[i].contents[0] = trackEventsSub[eventCount].contents[0];
trackEventsSub[i].contents[1] = 0;
trackEventsSub[i+1].deltaTime = (trackEventsSub[i+1].absoluteTime - trackEventsSub[i].absoluteTime);
if (trackEventsSub[i].deltaTime > 0xFF000000)
{
int a =1;
}
trackEventCountSub++;
break;
}
else if (i == (trackEventCountSub - 1))
{
trackEventsSub[i+1].absoluteTime = shutoffTime; // move end to end
trackEventsSub[i+1].contentSize = trackEventsSub[i].contentSize;
if (trackEventsSub[i+1].contents != NULL)
{
delete [] trackEventsSub[i+1].contents;
trackEventsSub[i+1].contents = NULL;
}
trackEventsSub[i+1].contents = new byte[trackEventsSub[i].contentSize];
for (int r = 0; r < trackEventsSub[i].contentSize; r++)
{
trackEventsSub[i+1].contents[r] = trackEventsSub[i].contents[r];
}
trackEventsSub[i+1].deltaTime = trackEventsSub[i].deltaTime;
trackEventsSub[i+1].durationTime = trackEventsSub[i].durationTime;
trackEventsSub[i+1].obsoleteEvent = trackEventsSub[i].obsoleteEvent;
trackEventsSub[i+1].type = trackEventsSub[i].type;
trackEventsSub[i].type = trackEventsSub[eventCount].type;
trackEventsSub[i].absoluteTime = shutoffTime;
trackEventsSub[i].deltaTime = (trackEventsSub[i].absoluteTime - trackEventsSub[i - 1].absoluteTime);
trackEventsSub[i].contentSize = trackEventsSub[eventCount].contentSize;
trackEventsSub[i].durationTime = 0;
if (trackEventsSub[i].contents != NULL)
{
delete [] trackEventsSub[i].contents;
}
trackEventsSub[i].contents = new byte[trackEventsSub[i].contentSize];
trackEventsSub[i].contents[0] = trackEventsSub[eventCount].contents[0];
trackEventsSub[i].contents[1] = 0;
trackEventsSub[i+1].deltaTime = (trackEventsSub[i+1].absoluteTime - trackEventsSub[i].absoluteTime);
trackEventCountSub++;
break;
}
}
}
else
{
trackEventsSub[eventCount+1].absoluteTime = shutoffTime; // move end to end
trackEventsSub[eventCount+1].contentSize = trackEventsSub[eventCount].contentSize;
if (trackEventsSub[eventCount+1].contents != NULL)
{
delete [] trackEventsSub[eventCount+1].contents;
trackEventsSub[eventCount+1].contents = NULL;
}
trackEventsSub[eventCount+1].contents = new byte[trackEventsSub[eventCount].contentSize];
for (int r = 0; r < trackEventsSub[eventCount].contentSize; r++)
{
trackEventsSub[eventCount+1].contents[r] = trackEventsSub[eventCount].contents[r];
}
trackEventsSub[eventCount+1].deltaTime = trackEventsSub[eventCount].deltaTime;
trackEventsSub[eventCount+1].durationTime = trackEventsSub[eventCount].durationTime;
trackEventsSub[eventCount+1].obsoleteEvent = trackEventsSub[eventCount].obsoleteEvent;
trackEventsSub[eventCount+1].type = trackEventsSub[eventCount].type;
trackEventsSub[eventCount].type = trackEventsSub[eventCount].type;
trackEventsSub[eventCount].absoluteTime = shutoffTime;
if ((trackEventsSub[eventCount].absoluteTime - trackEventsSub[eventCount - 1].absoluteTime) > 0xFF000000)
{
int a =1;
}
trackEventsSub[eventCount].deltaTime = (trackEventsSub[eventCount].absoluteTime - trackEventsSub[eventCount - 1].absoluteTime);
trackEventsSub[eventCount].contentSize = trackEventsSub[eventCount].contentSize;
trackEventsSub[eventCount].durationTime = 0;
trackEventsSub[eventCount].contents = new byte[trackEventsSub[eventCount].contentSize];
trackEventsSub[eventCount].contents[0] = trackEventsSub[eventCount].contents[0];
trackEventsSub[eventCount].contents[1] = 0;
trackEventsSub[eventCount+1].deltaTime = (trackEventsSub[eventCount+1].absoluteTime - trackEventsSub[eventCount].absoluteTime);
if (trackEventsSub[eventCount].deltaTime > 0xFF000000)
{
int a =1;
}
trackEventCountSub++;
}
}
}
}
unsigned long timeOffset = 0;
unsigned long sizeData = 0;
byte previousTrackEvent = 0x0;
for (int j = 0; j < trackEventCountSub; j++)
{
TrackEvent trackEvent = trackEventsSub[j];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type == 0xFF))
{
sizeData += 1;
}
sizeData += trackEvent.contentSize;
previousTrackEvent = trackEvent.type;
}
}
tempLong = Flip32Bit(sizeData);
fwrite(&tempLong,1, 4, outFile);
timeOffset = 0;
previousTrackEvent = 0x0;
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
TrackEvent trackEvent = trackEventsSub[eventCount];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, true);
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type == 0xFF))
{
fwrite(&trackEvent.type, 1, 1, outFile);
}
fwrite(trackEvent.contents, 1, trackEvent.contentSize, outFile);
previousTrackEvent = trackEvent.type;
}
}
}
else
{
}
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
if (trackEventsSub[eventCount].contents != NULL)
{
delete [] trackEventsSub[eventCount].contents;
trackEventsSub[eventCount].contents = NULL;
}
}
counterTrack++;
delete [] trackEventsSub;
}
fflush(outFile);
fclose(outFile);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
void CMidiParse::MIDxMidiToMidi(byte* inputMID, int inputSize, CString outFileName, int& numberInstruments)
{
numberInstruments = 1;
try
{
FILE* outFile = fopen(outFileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return;
}
// parse midi
int trackSize = inputSize;
unsigned long tempLong = Flip32Bit(0x4D546864);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00000006);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00010000 | 0x0001); // num tracks
fwrite(&tempLong, 1 ,4 , outFile);
unsigned long division = 0x01E0;
unsigned short tempShort = division;
tempShort = Flip16Bit(tempShort);
fwrite(&tempShort, 1 ,2 , outFile);
unsigned long absoluteTime = 0;
int trackEventCount = 0;
TrackEvent* trackEvents = new TrackEvent[0x30000];
for (int j = 0; j < 0x30000; j++)
trackEvents[j].contents = NULL;
int position = 4;
tempLong = Flip32Bit(0x4D54726B);
fwrite(&tempLong, 1 ,4 , outFile);
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
int timePosition = position;
unsigned long original;
unsigned long timeTag;
timeTag = inputMID[position];
position++;
if (timeTag > 0x7F)
timeTag = (timeTag & 0x7F);
trackEvents[trackEventCount].deltaTime = timeTag;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += timeTag;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if ((eventVal >= 0xF0) && (eventVal <= 0xFF)) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
trackEvents[trackEventCount].type = 0xFF;
trackEvents[trackEventCount].contentSize = 5;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = 0x51;
trackEvents[trackEventCount].contents[1] = 0x3;
trackEvents[trackEventCount].contents[2] = ((microsecondsSinceQuarterNote >> 16) & 0xFF);
trackEvents[trackEventCount].contents[3] = ((microsecondsSinceQuarterNote >> 8) & 0xFF);
trackEvents[trackEventCount].contents[4] = ((microsecondsSinceQuarterNote >> 0) & 0xFF);
trackEventCount++;
int MICROSECONDS_PER_MINUTE = 60000000;
float beatsPerMinute = (float)MICROSECONDS_PER_MINUTE / (float)microsecondsSinceQuarterNote;
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (endLoop != 0xFF)
{
// is this used?
}
}
else if (subType == 0x2F)
{
trackEvents[trackEventCount].type = 0xFF;
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = 0x2F;
trackEvents[trackEventCount].contents[1] = 0x0;
trackEventCount++;
endFlag = true;
}
else if (subType == 0xF8)
{
// ?
}
}
else if ((eventVal >= 0x80 && eventVal < 0x90))
{
byte curEventVal;
byte noteNumber;
trackEvents[trackEventCount].type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = noteNumber;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0))
{
byte curEventVal;
byte noteNumber;
trackEvents[trackEventCount].type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = noteNumber;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].type = eventVal;
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = controllerType;
trackEvents[trackEventCount].contents[1] = controllerValue;
trackEventCount++;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0))) // change instrument
{
byte instrument;
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].type = eventVal;
trackEvents[trackEventCount].contentSize = 1;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = instrument;
if (instrument >= numberInstruments)
numberInstruments = (instrument + 1);
trackEventCount++;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0))) // channel aftertouch
{
byte amount;
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].type = eventVal;
trackEvents[trackEventCount].contentSize = 1;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = amount;
trackEventCount++;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0))) // pitch bend
{
byte valueLSB;
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].type = eventVal;
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = valueLSB;
trackEvents[trackEventCount].contents[1] = valueMSB;
trackEventCount++;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
fprintf(outFile, "%02X ERROR MISSING PARSE OF TYPE\n", eventVal);
}
}
unsigned long timeOffset = 0;
unsigned long sizeData = 0;
byte previousTrackEvent = 0x0;
for (int j = 0; j < trackEventCount; j++)
{
TrackEvent trackEvent = trackEvents[j];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type >= 0xF0))
{
sizeData += 1;
}
sizeData += trackEvent.contentSize;
previousTrackEvent = trackEvent.type;
}
}
tempLong = Flip32Bit(sizeData);
fwrite(&tempLong,1, 4, outFile);
timeOffset = 0;
previousTrackEvent = 0x0;
for (int eventCount = 0; eventCount < trackEventCount; eventCount++)
{
TrackEvent trackEvent = trackEvents[eventCount];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, false);
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type >= 0xF0))
{
fwrite(&trackEvent.type, 1, 1, outFile);
}
fwrite(trackEvent.contents, 1, trackEvent.contentSize, outFile);
previousTrackEvent = trackEvent.type;
}
}
for (int eventCount = 0; eventCount < trackEventCount; eventCount++)
{
if (trackEvents[eventCount].contents != NULL)
{
delete [] trackEvents[eventCount].contents;
trackEvents[eventCount].contents = NULL;
}
}
delete [] trackEvents;
// just one track
fflush(outFile);
fclose(outFile);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
int CMidiParse::GetSngVariableLength(unsigned char* buffer, unsigned long offset)
{
if (buffer[offset] & 0x80)
{
int value = (((buffer[offset] & 0x7F) << 8) | buffer[offset + 1]);
return value;
}
else
{
return buffer[offset];
}
}
int CMidiParse::WriteSngVariableLength(unsigned char* buffer, int& offset, int value)
{
int writeValue = value;
while (writeValue > 0x7FFE)
{
writeValue -= 0x7FFE;
}
if (writeValue < 0x80)
buffer[offset++] = writeValue;
else
{
unsigned short dataValue = 0x8000 | writeValue;
buffer[offset++] = ((dataValue >> 8) & 0xFF);
buffer[offset++] = ((dataValue) & 0xFF);
}
return (value - writeValue);
}
void CMidiParse::ParseSngTrack(int trackNumber, int& numberInstruments, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfo>& outputNotes, unsigned char* buffer, unsigned long offset, unsigned long end, unsigned short* instrumentLookup, unsigned long adsrPointer, unsigned long drumPointer, std::vector<SngTimeValue> volumeByAbsoluteTime, std::vector<SngTimeValue> pitchBendByAbsoluteTime, SngStyle sngStyle, int& noteUniqueId, int totalInstruments)
{
std::vector<SngNoteInfo> trackOutputNotes;
unsigned char command = 0x00;
unsigned long spot = offset;
bool useDefinedLength = false;
int definedLength = 0;
bool useDefinedVelocity = false;
int definedVelocity = 0x7F;
bool useDefinedReleaseTime = false;
int definedReleaseTime = 0x01;
if ((sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::Bfx) || (sngStyle == SngStyle::PtrBfx))
{
useDefinedVelocity = true;
definedVelocity = 0x7F;
}
unsigned long absoluteTime = 0;
unsigned char currentPan = 0x80;
unsigned short currentInstrument = 0x00;
unsigned char currentVolume = 0x7F;
signed char currentPitchBend = 0x40;
int currentDrumOffset = -1;
int currentTranspose = 0;
int currentEffect = 0;
bool isWobbling = false;
unsigned char wobbleOffset = 0x00;
unsigned char wobbleTransposeCounter = 0x00;
unsigned char wobbleNormalCounter = 0x00;
unsigned long currentTempo = (unsigned long)(60000000.0 / (float)120.0);
while ((command != 0x80) && (spot < end))
{
// Not Master Track
if (trackNumber >= 0)
{
currentTempo = (unsigned long)(60000000.0 / (float)120.0);
// Mini not using tempo?
if (sngStyle == SngStyle::Normal || ((sngStyle == SngStyle::Old) && (trackNumber > 0)) || ((sngStyle == SngStyle::OldDD) && (trackNumber > 0)))
{
for (int y = 0; y < tempoPositions.size(); y++)
{
if (tempoPositions[y].absoluteTime <= absoluteTime)
{
currentTempo = tempoPositions[y].value;
}
else
{
break;
}
}
}
}
command = buffer[spot];
//fprintf(outFile, "%08X Time: %08X Command: %02X ", spot, absoluteTime, command);
spot++;
if (command < 0x80) // Note or Rest
{
unsigned char note = command;
if (note == 0x60)
{
//fprintf(outFile, " Rest");
}
else if (note < 0x60)
{
//fprintf(outFile, " Note %02X", note);
}
else
{
//fprintf(outFile, " UNKNOWN Note %02X", note);
}
int velocity;
if (useDefinedVelocity)
{
velocity = definedVelocity;
//fprintf(outFile, " [Velocity %02X (%d)]", definedVelocity, definedVelocity);
}
else
{
//fprintf(outFile, " Velocity %02X (%d)", buffer[spot] & 0x7F, buffer[spot] & 0x7F);
if (buffer[spot] & 0x80)
{
useDefinedVelocity = true;
definedVelocity = buffer[spot] & 0x7F;
//fprintf(outFile, " and Repeat");
}
velocity = (buffer[spot] & 0x7F);
spot++;
}
int noteLength;
if (useDefinedLength)
{
noteLength = definedLength;
//fprintf(outFile, " [Length %02X (%d)]", definedLength, definedLength);
}
else
{
noteLength = GetSngVariableLength(buffer, spot);
if (noteLength < 0x80)
{
//fprintf(outFile, " Length %02X (%d)", buffer[spot], length);
spot++;
}
else
{
//fprintf(outFile, " Length %02X%02X (%d)", buffer[spot], buffer[spot+1], length);
spot += 2;
}
}
// Add note to batch
if (note < 0x60)
{
if (currentDrumOffset != -1)
{
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
unsigned long drumNoteOffset = drumPointer + (currentDrumOffset * 0x6) + (note * 0x6);
unsigned char instrumentIndex = buffer[drumNoteOffset + 1];
unsigned char adsrIndex = buffer[drumNoteOffset + 3];
unsigned char pan = buffer[drumNoteOffset + 4];
unsigned char note = buffer[drumNoteOffset + 5];
int instrument;
if ((sngStyle == SngStyle::Old) || (sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::PtrBfx))
{
instrument = instrumentIndex;
if (instrument > numberInstruments)
numberInstruments = instrument + 1;
}
else
instrument = instrumentLookup[instrumentIndex];
songNoteInfo.effect = currentEffect;
songNoteInfo.noteNumber = note + 0xC + currentTranspose;
songNoteInfo.velocity = velocity;
// From Master Track
songNoteInfo.tempo = currentTempo;
// TODO multiple banks
songNoteInfo.instrument = instrument;
songNoteInfo.pan = ((pan >> 1) & 0xFF);
songNoteInfo.pitchBend = currentPitchBend;
songNoteInfo.volume = currentVolume;
if (useDefinedReleaseTime)
{
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + definedReleaseTime;
}
else
{
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
}
trackOutputNotes.push_back(songNoteInfo);
}
else
{
if (isWobbling)
{
int totalLengthTime;
if (useDefinedReleaseTime)
{
totalLengthTime = definedReleaseTime;
}
else
{
totalLengthTime = noteLength;
}
int wobbleCounter = 0;
while (wobbleCounter < totalLengthTime)
{
int left = totalLengthTime - (int)wobbleCounter;
if (left <= 0)
break;
if (left > wobbleTransposeCounter)
left = wobbleTransposeCounter;
SngNoteInfo songNoteInfoWobble;
songNoteInfoWobble.originalTrack = trackNumber;
songNoteInfoWobble.originalNoteUniqueId = noteUniqueId++;
songNoteInfoWobble.startAbsoluteTime = absoluteTime + wobbleCounter;
songNoteInfoWobble.endAbsoluteTime = songNoteInfoWobble.startAbsoluteTime + left;
songNoteInfoWobble.noteNumber = note + 0xC + currentTranspose + wobbleOffset;
songNoteInfoWobble.velocity = velocity;
songNoteInfoWobble.effect = currentEffect;
// From Master Track
songNoteInfoWobble.tempo = currentTempo;
songNoteInfoWobble.instrument = currentInstrument;
songNoteInfoWobble.pan = ((currentPan >> 1) & 0xFF);;
songNoteInfoWobble.pitchBend = currentPitchBend;
songNoteInfoWobble.volume = currentVolume;
trackOutputNotes.push_back(songNoteInfoWobble);
wobbleCounter += left;
left = totalLengthTime - (int)wobbleCounter;
if (left <= 0)
break;
if (left > wobbleNormalCounter)
left = wobbleNormalCounter;
SngNoteInfo songNoteInfoNormal;
songNoteInfoNormal.originalTrack = trackNumber;
songNoteInfoNormal.originalNoteUniqueId = noteUniqueId++;
songNoteInfoNormal.startAbsoluteTime = absoluteTime + wobbleCounter;
songNoteInfoNormal.endAbsoluteTime = songNoteInfoNormal.startAbsoluteTime + left;
songNoteInfoNormal.noteNumber = note + 0xC + currentTranspose;
songNoteInfoNormal.velocity = velocity;
songNoteInfoNormal.effect = currentEffect;
// From Master Track
songNoteInfoNormal.tempo = currentTempo;
songNoteInfoNormal.instrument = currentInstrument;
songNoteInfoNormal.pan = ((currentPan >> 1) & 0xFF);;
songNoteInfoNormal.pitchBend = currentPitchBend;
songNoteInfoNormal.volume = currentVolume;
trackOutputNotes.push_back(songNoteInfoNormal);
wobbleCounter += left;
}
}
else
{
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + 0xC + currentTranspose;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = currentEffect;
// From Master Track
songNoteInfo.tempo = currentTempo;
songNoteInfo.instrument = currentInstrument;
songNoteInfo.pan = ((currentPan >> 1) & 0xFF);;
songNoteInfo.pitchBend = currentPitchBend;
songNoteInfo.volume = currentVolume;
if (useDefinedReleaseTime)
{
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + definedReleaseTime;
}
else
{
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
}
trackOutputNotes.push_back(songNoteInfo);
}
}
}
absoluteTime += noteLength;
}
else
{
if (command == 0x80)
{
//End?
//fprintf(outFile, " End");
break;
}
else if (command == 0x81)
{
//XX, Instrument # In List
//fprintf(outFile, " Instrument");
//fprintf(outFile, " %02X (Looked up %02X)", buffer[spot], instrumentLookup[buffer[spot]]);
if ((sngStyle == SngStyle::Old) || (sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::PtrBfx))
{
currentInstrument = GetSngVariableLength(buffer, spot);
if (currentInstrument > numberInstruments)
numberInstruments = currentInstrument + 1;
if (currentInstrument < 0x80)
{
spot++;
}
else
{
spot += 2;
}
}
else if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Bfx) || (sngStyle == SngStyle::OldDD))
{
int instrumentLookupValue = GetSngVariableLength(buffer, spot);
if (instrumentLookupValue < 0x80)
{
spot++;
}
else
{
spot += 2;
}
if (instrumentLookupValue >= totalInstruments)
{
currentInstrument = instrumentLookupValue;
}
else
{
currentInstrument = instrumentLookup[instrumentLookupValue];
}
}
}
else if (command == 0x82)
{
if ((sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::Bfx) || (sngStyle == SngStyle::PtrBfx))
{
//??
//fprintf(outFile, " ?");
}
else
{
//Set Slide
//fprintf(outFile, " Set Slide");
//fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
}
else if (command == 0x83)
{
// ?
}
else if (command == 0x84)
{
// ADSR Set
spot += 7;
}
else if (command == 0x85)
{
//XX Master Track Tempo, 0x28 = 40, 0x78 = 120
//fprintf(outFile, " Master Track Tempo");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
unsigned char tempo = buffer[spot];
currentTempo = (unsigned long)(60000000.0 / (float)tempo);
if (((sngStyle == SngStyle::Normal) && (trackNumber == -1)) || ((sngStyle == SngStyle::Old) && (trackNumber == 0))|| ((sngStyle == SngStyle::OldDD) && (trackNumber == 0)))// Master Track
{
tempoPositions.push_back(TimeAndValue(absoluteTime, currentTempo));
}
spot++;
}
else if (command == 0x86)
{
//XXXX Set Release Time for upcoming notes
//fprintf(outFile, " Set Release Time");
//fprintf(outFile, " %04X (%d)", CharArrayToShort(&buffer[spot]), CharArrayToShort(&buffer[spot]));
useDefinedReleaseTime = true;
definedReleaseTime = CharArrayToShort(&buffer[spot]);
spot+=2;
}
else if (command == 0x87)
{
//XX 01 Set Release Time back to full note (01)
//fprintf(outFile, " Set Release Time Back to Full");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
useDefinedReleaseTime = false;
spot++;
}
else if (command == 0x88)
{
//XX YY ZZ Vibrato Up - Delay, Amount, Speed
//fprintf(outFile, " Vibrato Up");
//fprintf(outFile, " Delay %02X (%d) Amount %02X (%d) Speed %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot+=3;
}
else if (command == 0x89)
{
//XX YY ZZ Vibrato Down - Delay, Amount, Speed
//fprintf(outFile, " Vibrato Down");
//fprintf(outFile, " Delay %02X (%d) Amount %02X (%d) Speed %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot+=3;
}
else if (command == 0x89)
{
//?
}
else if (command == 0x8A)
{
//Solo
//fprintf(outFile, " Solo");
}
else if (command == 0x8B)
{
//LL Set Length notes following and disable in list (variable time)
//fprintf(outFile, " Set Length Notes and Disable in Note Format");
definedLength = GetSngVariableLength(buffer, spot);
// Probably just old style, uses 0x00 to turn off?
if (definedLength == 0x00)
{
useDefinedLength = false;
spot++;
}
else if (definedLength < 0x80)
{
useDefinedLength = true;
//fprintf(outFile, " Length %02X (%d)", buffer[spot], definedLength);
spot++;
}
else
{
useDefinedLength = true;
//fprintf(outFile, " Length %02X%02X (%d)", buffer[spot], buffer[spot+1], definedLength);
spot += 2;
}
}
else if (command == 0x8D)
{
//XX Transpose, 00 default, 01, etc
//fprintf(outFile, " Transpose");
//fprintf(outFile, " %02X (%d)", buffer[spot], (signed char)buffer[spot]);
currentTranspose = (signed char)buffer[spot];
spot++;
}
else if (command == 0x8F)
{
//XX Detune (signed)
//fprintf(outFile, " Detune");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0x90)
{
//XX ADSR SubIndex
//fprintf(outFile, " ADSR Index");
//fprintf(outFile, " %02X", buffer[spot]);
//fprintf(outFile, " Rate %02X (%d)", buffer[adsrPointer + buffer[spot] * 7], buffer[adsrPointer + buffer[spot] * 7]);
//fprintf(outFile, " Start Level %02X (%d)", buffer[adsrPointer + buffer[spot] * 7 + 1], buffer[adsrPointer + buffer[spot] * 7 + 1]);
//fprintf(outFile, " Attack Rate %02X (%d)", buffer[adsrPointer + buffer[spot] * 7 + 2], buffer[adsrPointer + buffer[spot] * 7 + 2]);
//fprintf(outFile, " Peak Level %02X (%d)", buffer[adsrPointer + buffer[spot] * 7 + 3], buffer[adsrPointer + buffer[spot] * 7 + 3]);
//fprintf(outFile, " Decay Rate %02X (%d)", buffer[adsrPointer + buffer[spot] * 7 + 4], buffer[adsrPointer + buffer[spot] * 7 + 4]);
//fprintf(outFile, " Sustain Level %02X (%d)", buffer[adsrPointer + buffer[spot] * 7 + 5], buffer[adsrPointer + buffer[spot] * 7 + 5]);
//fprintf(outFile, " Release Rate %02X (%d)", buffer[adsrPointer + buffer[spot] * 7 + 6], buffer[adsrPointer + buffer[spot] * 7 + 6]);
spot++;
}
else if (command == 0x91)
{
//Envelope Trigger Off
//fprintf(outFile, " Envelope Trigger Off");
}
else if (command == 0x92)
{
//Envelope Trigger On
//fprintf(outFile, " Envelope Trigger On");
}
else if (command == 0x93)
{
//Sample Trigger Off
//fprintf(outFile, " Sample Trigger Off");
}
else if (command == 0x94)
{
//Sample Trigger On
//fprintf(outFile, " Sample Trigger On");
}
else if (command == 0x95)
{
//XX Loop Start FF Count?
//fprintf(outFile, " Loop Start");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0x96)
{
//Loop
//fprintf(outFile, " Loop Back");
break;
}
else if (command == 0x97)
{
//XX YY ZZ Wobble - Offset, Transpose, Normal
//fprintf(outFile, " Wobble");
//fprintf(outFile, " Offset %02X (%d) Transpose %02X (%d) Normal %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
wobbleOffset = buffer[spot];
wobbleTransposeCounter = buffer[spot + 1];
wobbleNormalCounter = buffer[spot + 2];
/*if ((wobbleOffset != 0) && ((wobbleTransposeCounter != 0) || (wobbleNormalCounter != 0)))
isWobbling = true;
else
isWobbling = false;*/
// Disable for now
isWobbling = false;
spot+=3;
}
else if (command == 0x98)
{
//?
}
else if (command == 0x99)
{
useDefinedVelocity = false;
//Reenable velocity on notes
//fprintf(outFile, " Reenable Velocity on Notes Format");
}
else if (command == 0x9A) // Old Style Only
{
// Enable Velocity Defined in Notes
useDefinedVelocity = true;
//fprintf(outFile, " Enable Velocity Defined in Notes");
}
else if (command == 0x9B) // Old Style Only
{
// Set Repeat Velocity
//fprintf(outFile, " Set Repeat Velocity");
//fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
definedVelocity = buffer[spot];
useDefinedVelocity = true;
spot++;
}
else if (command == 0x9C)
{
//XX Pan, 0x00
//fprintf(outFile, " Pan");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentPan = buffer[spot];
spot++;
}
else if (command == 0x9E)
{
//XX Drum map on
//fprintf(outFile, " Drum Map On");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentDrumOffset = buffer[spot];
spot++;
}
else if (command == 0x9F)
{
//Drum map off
//fprintf(outFile, " Drum Map Off");
currentDrumOffset = -1;
}
else if (command == 0xA2)
{
//XX Effect, 0x00
//fprintf(outFile, " Effect");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentEffect = buffer[spot];
spot++;
}
else if (command == 0xA3)
{
//XX YY Set Min/Max Transpose
//fprintf(outFile, " Set Min/Max Transpose");
//fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command == 0xA4)
{
//XX YY Set Min/Max Volume
//fprintf(outFile, " Set Min/Max Volume");
//fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command == 0xA5)
{
//XX YY Set Min/Max Pan
//fprintf(outFile, " Set Min/Max Pan");
//fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command == 0xA6)
{
// Set Note Volume
//fprintf(outFile, " ?");
currentVolume = buffer[spot];
spot++;
}
else if (command == 0xA7)
{
//LL ?
//fprintf(outFile, " Load Track #");
//fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
int length = GetSngVariableLength(buffer, spot);
if (length < 0x80)
{
//fprintf(outFile, " Length %02X (%d)\n", inputMID[spot], length);
spot++;
}
else
{
//fprintf(outFile, " Length %02X%02X (%d)\n", inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else if (command == 0xA8)
{
//XX Pitch Bend
//fprintf(outFile, " Pitch Bend");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentPitchBend = buffer[spot];
spot++;
}
else if (command == 0xA9)
{
//XX Stereo Sweep Speed
//fprintf(outFile, " Stereo Sweep Speed");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xAA)
{
//XX Master Track Effect 00 = None, 01 = Small Room, 02 = Big Room, 03 = Chorus, 04 = Flange, 05 = Echo
//fprintf(outFile, " Master Track Effect");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
if (buffer[spot] == 0)
{
//fprintf(outFile, "None");
}
else if (buffer[spot] == 1)
{
//fprintf(outFile, "Small Room");
}
else if (buffer[spot] == 2)
{
//fprintf(outFile, "Big Room");
}
else if (buffer[spot] == 3)
{
//fprintf(outFile, "Chorus");
}
else if (buffer[spot] == 4)
{
//fprintf(outFile, "Flange");
}
else if (buffer[spot] == 5)
{
//fprintf(outFile, "Echo");
}
spot++;
}
else if (command == 0xAB)
{
//XX Master Track Sync - 1
//fprintf(outFile, " Master Track Sync");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xAC)
{
// Reenable length on notes
useDefinedLength = false;
//fprintf(outFile, " Reenable length on notes");
}
else if (command == 0xB0)
{
//XX ?
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else
{
CString tempStr;
tempStr.Format("Unknown Command %02X at Spot %04X", command, spot);
MessageBox(NULL, tempStr, "Error", NULL);
//fprintf(outFile, " UNKNOWN");
return;
}
}
//fprintf(outFile, "\n");
}
// Add in Volume
for (int x = 0; x < trackOutputNotes.size(); x++)
{
for (int y = 0; y < volumeByAbsoluteTime.size(); y++)
{
// Volume To Left/Equal Ending in Middle
if (
(trackOutputNotes[x].startAbsoluteTime >= volumeByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (trackOutputNotes[x].volume != volumeByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = trackOutputNotes[x];
trackOutputNotes[x].startAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.volume = volumeByAbsoluteTime[y].value;
trackOutputNotes.push_back(newNoteInfo);
x--;
break;
}
}
//Volume In Middle, Ending to Right
else if (
(trackOutputNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime <= volumeByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (trackOutputNotes[x].volume != volumeByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = trackOutputNotes[x];
trackOutputNotes[x].endAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.volume = volumeByAbsoluteTime[y].value;
trackOutputNotes.push_back(newNoteInfo);
x--;
break;
}
}
// Volume Completely Inside
else if (
(trackOutputNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (trackOutputNotes[x].volume != volumeByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = trackOutputNotes[x];
SngNoteInfo newNoteInfo2 = trackOutputNotes[x];
trackOutputNotes[x].endAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.volume = volumeByAbsoluteTime[y].value;
trackOutputNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
trackOutputNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// Volume Completely Outside
else if (
(trackOutputNotes[x].startAbsoluteTime >= volumeByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime <= volumeByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
trackOutputNotes[x].volume = volumeByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
// Add in Pitch Bend
for (int x = 0; x < trackOutputNotes.size(); x++)
{
for (int y = 0; y < pitchBendByAbsoluteTime.size(); y++)
{
// PitchBend To Left/Equal Ending in Middle
if (
(trackOutputNotes[x].startAbsoluteTime >= pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (trackOutputNotes[x].pitchBend != pitchBendByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = trackOutputNotes[x];
trackOutputNotes[x].startAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.pitchBend = pitchBendByAbsoluteTime[y].value;
trackOutputNotes.push_back(newNoteInfo);
x--;
break;
}
}
//PitchBend In Middle, Ending to Right
else if (
(trackOutputNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime <= pitchBendByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (trackOutputNotes[x].pitchBend != pitchBendByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = trackOutputNotes[x];
trackOutputNotes[x].endAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.pitchBend = pitchBendByAbsoluteTime[y].value;
trackOutputNotes.push_back(newNoteInfo);
x--;
break;
}
}
// PitchBend Completely Inside
else if (
(trackOutputNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (trackOutputNotes[x].pitchBend != pitchBendByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = trackOutputNotes[x];
SngNoteInfo newNoteInfo2 = trackOutputNotes[x];
trackOutputNotes[x].endAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.pitchBend = pitchBendByAbsoluteTime[y].value;
trackOutputNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
trackOutputNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// PitchBend Completely Outside
else if (
(trackOutputNotes[x].startAbsoluteTime >= pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (trackOutputNotes[x].endAbsoluteTime <= pitchBendByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
trackOutputNotes[x].pitchBend = pitchBendByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
// Add to end
for (int x = 0; x < trackOutputNotes.size(); x++)
{
outputNotes.push_back(trackOutputNotes[x]);
}
}
void CMidiParse::SngToDebugTextFile(CString gameName, unsigned long address, CString midiFile, CString textFileOut, unsigned long extra)
{
CString filepath = midiFile;
FILE* inFile = fopen(filepath, "rb");
if (inFile == NULL)
{
MessageBox(NULL, "Can't read input file " + filepath, "Error", NULL);
return;
}
fseek(inFile, 0, SEEK_END);
int inputSize = ftell(inFile);
rewind(inFile);
unsigned char* inputMID = new unsigned char[inputSize];
fread(inputMID, 1, inputSize, inFile);
fclose(inFile);
SngToDebugTextFile(gameName, address, inputMID, inputSize, textFileOut, extra);
delete [] inputMID;
}
void CMidiParse::SngToDebugTextFile(CString gameName, unsigned long address, byte* inputMID, int inputSize, CString textFileOut, unsigned long extra)
{
CString addressStr;
addressStr.Format("%08X", address);
if (inputMID[0x0] == 0x80) // Ptr Sng
{
unsigned long startDataNegative = (signed long)inputSize;
unsigned long initialPointer = extra;
unsigned long numberTracks = 0;
int pointerSpot = 0;
while (inputMID[pointerSpot] == 0x80)
{
numberTracks++;
pointerSpot += 4;
}
unsigned long adsrPointer = 0x00000000;
unsigned long drumPointer = 0x00000000;
unsigned long instrumentPointer = 0x00000000;
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, gameName + " - " + addressStr + "\n");
fprintf(outFile, "Ptr BFX Song Style\n\n");
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[(x * 4)]) - initialPointer;
unsigned long trackEnd = 0x00000000;
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[((x + 1) * 4)]) - initialPointer;
}
else
{
trackEnd = address;
}
fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X (%08X)\n------------------------------------------------------\n", x + 1, trackDataPointer + address + (signed long)inputSize, CharArrayToLong(&inputMID[(x * 4)]));
fprintf(outFile, "\nTrack Data\n");
SngTrackToDebugTextFile(outFile, inputMID + (signed long)startDataNegative, trackDataPointer, trackEnd, instrumentPointer, adsrPointer, drumPointer, SngStyle::PtrBfx, -1);
}
fclose(outFile);
}
// Second check to avoid false positive of bfx, if count is 0x215, Mario Golf E
else if ((CharArrayToLong(&inputMID[0x0]) == 0x00000215) && (CharArrayToLong(&inputMID[0x4]) != 0x00000215)) // Binary Sng style
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x4]);
unsigned long totalInstruments = CharArrayToLong(&inputMID[0x8]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0xC]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0x10]);
unsigned long pitchBendPointer = CharArrayToLong(&inputMID[0x14]);
unsigned long adsrPointer = CharArrayToLong(&inputMID[0x18]);
unsigned long drumPointer = CharArrayToLong(&inputMID[0x1C]);
unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x20]);
unsigned long masterTrackPointer = CharArrayToLong(&inputMID[0x24]);
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, gameName + " - " + addressStr + "\n");
fprintf(outFile, "Binary Song Style\n\n");
fprintf(outFile, "Instruments: %08X\n", instrumentPointer);
for (int x = 0; x < totalInstruments; x++)
{
fprintf(outFile, "%02X: %04X\n", x, CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]));
}
fprintf(outFile, "\n\n---------------------------\nMaster Track: %08X\n---------------------------\n", masterTrackPointer);
unsigned long trackDataPointerFirst = CharArrayToLong(&inputMID[trackPointer]);
SngTrackToDebugTextFile(outFile, inputMID, masterTrackPointer, trackDataPointerFirst, instrumentPointer, adsrPointer, drumPointer, SngStyle::Normal, totalInstruments);
for (int x = 0; x < numberTracks; x++)
{
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
unsigned long volumeEnd = 0;
if (volumeDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long volumeDataPointerTest = CharArrayToLong(&inputMID[volumePointer + (y * 4)]);
if (volumeDataPointerTest != 0)
{
volumeEnd = volumeDataPointerTest;
break;
}
}
if (volumeEnd == 0)
{
volumeEnd = masterTrackPointer;
}
}
unsigned long pitchBendDataPointer = CharArrayToLong(&inputMID[pitchBendPointer + (x * 4)]);
unsigned long pitchBendEnd = 0;
if (pitchBendDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
pitchBendEnd = pitchBendDataPointerTest;
break;
}
}
if (pitchBendEnd == 0)
{
pitchBendEnd = masterTrackPointer;
}
}
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long trackEnd = inputSize;
if (x < (numberTracks - 1))
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume End %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumeDataPointer, volumeEnd);
if (volumeDataPointer != 0)
{
fprintf(outFile, "\nVolume\n");
unsigned long absoluteTime = 0;
unsigned long spot = volumeDataPointer;
while (spot < volumeEnd)
{
unsigned char volume = inputMID[spot];
bool singleLength = !(volume & 0x80);
volume = volume & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X%02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length 01*\n", spot-1, absoluteTime, volume);
}
absoluteTime += length;
}
}
if (pitchBendDataPointer != 0)
{
fprintf(outFile, "\nPitch Bend\n");
unsigned long absoluteTime = 0;
unsigned long spot = pitchBendDataPointer;
while (spot < pitchBendEnd)
{
unsigned char pitchBend = inputMID[spot];
bool singleLength = !(pitchBend & 0x80);
pitchBend = pitchBend & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X%02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length 01*\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40));
}
absoluteTime += length;
}
}
fprintf(outFile, "\nTrack Data\n");
SngTrackToDebugTextFile(outFile, inputMID, trackDataPointer, trackEnd, instrumentPointer, adsrPointer, drumPointer, SngStyle::Normal, totalInstruments);
}
fclose(outFile);
}
else if (CharArrayToLong(&inputMID[0x4]) == 0x00000000) // Pokemon Stadium
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0x8]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0xC]);
unsigned long adsrPointer = 0x00000000;
unsigned long drumPointer = 0x00000000;
unsigned long instrumentPointer = 0x00000000;
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, gameName + " - " + addressStr + "\n");
fprintf(outFile, "Mini Song Style\n\n");
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
if (trackEnd == 0x00000000)
trackEnd = inputSize;
}
else
{
trackEnd = inputSize;
}
}
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Priority Start %08X Priority Data %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumePointer + (x * 4), volumeDataPointer);
fprintf(outFile, "\nTrack Data\n");
SngTrackToDebugTextFile(outFile, inputMID, trackDataPointer, trackEnd, instrumentPointer, adsrPointer, drumPointer, SngStyle::OldBfx, -1);
}
}
else if (CharArrayToLong(&inputMID[0xC]) == 0x00000000) // BFX
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
unsigned long trackPointer = 0x18;
unsigned long adsrPointer = 0x00000000;
unsigned long drumPointer = 0x00000000;
unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x14]);
int totalInstruments = (inputSize - instrumentPointer) / 0x4;
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, "Instruments: %08X\n", instrumentPointer);
for (int x = 0; x < totalInstruments; x++)
{
fprintf(outFile, "%02X: %04X\n", x, CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]));
}
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 8)]);
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 8)]);
if (trackEnd == 0x00000000)
trackEnd = instrumentPointer;
}
else
{
trackEnd = instrumentPointer;
}
}
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[trackDataPointer + (x * 8) + 4]);
fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Priority Start %08X Priority Data %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, trackDataPointer + (x * 8) + 4, volumeDataPointer);
fprintf(outFile, "\nTrack Data\n");
SngTrackToDebugTextFile(outFile, inputMID, trackDataPointer, trackEnd, instrumentPointer, adsrPointer, drumPointer, SngStyle::Bfx, totalInstruments);
}
fclose(outFile);
}
else if (CharArrayToLong(&inputMID[0x8]) == 0x00000020) // N64 DD Style
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
unsigned long totalInstruments = CharArrayToLong(&inputMID[0x4]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0x8]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0xC]);
unsigned long pitchBendPointer = CharArrayToLong(&inputMID[0x10]);
unsigned long adsrPointer = CharArrayToLong(&inputMID[0x14]);
unsigned long drumPointer = CharArrayToLong(&inputMID[0x18]);
unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x1C]);
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, "Instruments: %08X\n", instrumentPointer);
for (int x = 0; x < totalInstruments; x++)
{
fprintf(outFile, "%02X: %04X\n", x, CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]));
}
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
unsigned long volumeEnd = 0;
if (volumeDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long volumeDataPointerTest = CharArrayToLong(&inputMID[volumePointer + (y * 4)]);
if (volumeDataPointerTest != 0)
{
volumeEnd = volumeDataPointerTest;
break;
}
}
if (volumeEnd == 0)
{
volumeEnd = CharArrayToLong(&inputMID[trackPointer]);
}
}
unsigned long pitchBendDataPointer = CharArrayToLong(&inputMID[pitchBendPointer + (x * 4)]);
unsigned long pitchBendEnd = 0;
if (pitchBendDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
pitchBendEnd = pitchBendDataPointerTest;
break;
}
}
if (pitchBendEnd == 0)
{
pitchBendEnd = CharArrayToLong(&inputMID[trackPointer]);;
}
}
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
if (trackEnd == 0x00000000)
trackEnd = inputSize;
}
else
{
trackEnd = inputSize;
}
}
fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume End %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumeDataPointer, volumeEnd);
if (volumeDataPointer != 0)
{
fprintf(outFile, "\nVolume\n");
unsigned long absoluteTime = 0;
unsigned long spot = volumeDataPointer;
while (spot < volumeEnd)
{
unsigned char volume = inputMID[spot];
bool singleLength = !(volume & 0x80);
volume = volume & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X%02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length 01*\n", spot-1, absoluteTime, volume);
}
absoluteTime += length;
}
}
if (pitchBendDataPointer != 0)
{
fprintf(outFile, "\nPitch Bend\n");
unsigned long absoluteTime = 0;
unsigned long spot = pitchBendDataPointer;
while (spot < pitchBendEnd)
{
unsigned char pitchBend = inputMID[spot];
bool singleLength = !(pitchBend & 0x80);
pitchBend = pitchBend & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X%02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length 01*\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40));
}
absoluteTime += length;
}
}
fprintf(outFile, "\nTrack Data\n");
SngTrackToDebugTextFile(outFile, inputMID, trackDataPointer, trackEnd, instrumentPointer, adsrPointer, drumPointer, SngStyle::OldDD, totalInstruments);
}
fclose(outFile);
}
else // Old Style
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
//unsigned long numberInstruments = CharArrayToLong(&inputMID[0x8]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0x4]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0x8]);
unsigned long pitchBendPointer = CharArrayToLong(&inputMID[0xC]);
unsigned long adsrPointer = CharArrayToLong(&inputMID[0x10]);
unsigned long drumPointer = CharArrayToLong(&inputMID[0x14]);
//unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x20]);
unsigned long instrumentPointer = 0x00000000;
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, gameName + " - " + addressStr + "\n");
fprintf(outFile, "Old Song Style\n\n");
/*fprintf(outFile, "Instruments: %08X\n", instrumentPointer);
for (int x = 0; x < numberInstruments; x++)
{
fprintf(outFile, "%02X: %04X\n", x, CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]));
}
fprintf(outFile, "\n\n---------------------------\nMaster Track: %08X\n---------------------------\n", masterTrackPointer);
unsigned long trackDataPointerFirst = CharArrayToLong(&inputMID[trackPointer]);
SngTrackToDebugTextFile(outFile, inputMID, masterTrackPointer, trackDataPointerFirst, instrumentPointer, adsrPointer, drumPointer);
*/
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
unsigned long volumeEnd = 0;
unsigned long pitchBendDataPointer = CharArrayToLong(&inputMID[pitchBendPointer + (x * 4)]);
unsigned long pitchBendEnd = 0;
if (volumeDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long volumeDataPointerTest = CharArrayToLong(&inputMID[volumePointer + (y * 4)]);
if (volumeDataPointerTest != 0)
{
volumeEnd = volumeDataPointerTest;
break;
}
}
if (volumeEnd == 0)
{
if (pitchBendDataPointer != 0)
{
for (int y = 0; y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
volumeEnd = pitchBendDataPointerTest;
break;
}
}
}
if (volumeEnd == 0)
{
// First track
volumeEnd = CharArrayToLong(&inputMID[trackPointer]);;
}
}
}
if (pitchBendDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
pitchBendEnd = pitchBendDataPointerTest;
break;
}
}
if (pitchBendEnd == 0)
{
pitchBendEnd = CharArrayToLong(&inputMID[trackPointer]);
}
}
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
if (trackEnd == 0x00000000)
trackEnd = inputSize;
}
else
{
trackEnd = inputSize;
}
}
fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume End %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumeDataPointer, volumeEnd);
if (volumeDataPointer != 0)
{
fprintf(outFile, "\nVolume\n");
unsigned long absoluteTime = 0;
unsigned long spot = volumeDataPointer;
while (spot < volumeEnd)
{
unsigned char volume = inputMID[spot];
bool singleLength = !(volume & 0x80);
volume = volume & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X%02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
fprintf(outFile, "%08X Time: %08X Volume %02X Length 01*\n", spot-1, absoluteTime, volume);
}
absoluteTime += length;
}
}
if (pitchBendDataPointer != 0)
{
fprintf(outFile, "\nPitch Bend\n");
unsigned long absoluteTime = 0;
unsigned long spot = pitchBendDataPointer;
while (spot < pitchBendEnd)
{
unsigned char pitchBend = inputMID[spot];
bool singleLength = !(pitchBend & 0x80);
pitchBend = pitchBend & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X%02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length 01*\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40));
}
absoluteTime += length;
}
}
fprintf(outFile, "\nTrack Data\n");
SngTrackToDebugTextFile(outFile, inputMID, trackDataPointer, trackEnd, instrumentPointer, adsrPointer, drumPointer, SngStyle::Old, -1);
}
fclose(outFile);
}
}
void CMidiParse::SngTrackToDebugTextFile(FILE* outFile, unsigned char* inputMID, unsigned long offset, unsigned long end, unsigned long instrumentPointer, unsigned long adsrPointer, unsigned long drumPointer, SngStyle sngStyle, int totalInstruments)
{
unsigned char command = 0x00;
unsigned long spot = offset;
bool useDefinedLength = false;
int definedLength = 0;
bool useDefinedVelocity = false;
int definedVelocity;
if ((sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::Bfx) || (sngStyle == SngStyle::PtrBfx))
{
useDefinedVelocity = true;
definedVelocity = 0x7F;
}
int drumBankOffset = -1;
unsigned long absoluteTime = 0;
while ((command != 0x80) && (spot < end))
{
command = inputMID[spot];
fprintf(outFile, "%08X Time: %08X Command: %02X ", spot, absoluteTime, command);
spot++;
if (command < 0x80) // Note or Rest
{
unsigned char note = command;
if (drumBankOffset == -1)
{
if (note == 0x60)
fprintf(outFile, " Rest");
else if (note < 0x60)
fprintf(outFile, " Note %02X", note);
else
fprintf(outFile, " UNKNOWN Note %02X", note);
}
else
{
if (note == 0x60)
fprintf(outFile, " Rest");
else
fprintf(outFile, " Drum SubIndex %02X", note);
}
if (useDefinedVelocity)
{
fprintf(outFile, " [Velocity %02X (%d)]", definedVelocity, definedVelocity);
}
else
{
fprintf(outFile, " Velocity %02X (%d)", inputMID[spot] & 0x7F, inputMID[spot] & 0x7F);
if (inputMID[spot] & 0x80)
{
useDefinedVelocity = true;
definedVelocity = inputMID[spot] & 0x7F;
fprintf(outFile, " and Repeat");
}
spot++;
}
if (useDefinedLength)
{
fprintf(outFile, " [Length %02X (%d)]", definedLength, definedLength);
absoluteTime += definedLength;
}
else
{
int length = GetSngVariableLength(inputMID, spot);
if (length < 0x80)
{
fprintf(outFile, " Length %02X (%d)", inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, " Length %02X%02X (%d)", inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
absoluteTime += length;
}
if ((drumBankOffset != -1) && (note != 0x60))
{
unsigned long drumNoteOffset = drumPointer + (drumBankOffset * 6) + (note * 6);
unsigned char instrumentIndex = inputMID[drumNoteOffset + 1];
unsigned char adsrIndex = inputMID[drumNoteOffset + 3];
unsigned char pan = inputMID[drumNoteOffset + 4];
unsigned char note = inputMID[drumNoteOffset + 5];
if (sngStyle == SngStyle::Old)
fprintf(outFile, " Drum Instrument %02X Address %08X Pan %02X Note %02X", instrumentIndex, drumNoteOffset, pan, note);
else
fprintf(outFile, " Drum Instrument %02X (Looked up %02X) Address %08X Pan %02X Note %02X", instrumentIndex, CharArrayToShort(&inputMID[instrumentPointer + (instrumentIndex * 2)]), drumNoteOffset, pan, note);
fprintf(outFile, " ADSR Rate %02X (%d)", inputMID[adsrPointer + adsrIndex * 7], inputMID[adsrPointer + adsrIndex * 7]);
fprintf(outFile, " ADSR Start Level %02X (%d)", inputMID[adsrPointer + adsrIndex * 7 + 1], inputMID[adsrPointer + adsrIndex * 7 + 1]);
fprintf(outFile, " ADSR Attack Rate %02X (%d)", inputMID[adsrPointer + adsrIndex * 7 + 2], inputMID[adsrPointer + adsrIndex * 7 + 2]);
fprintf(outFile, " ADSR Peak Level %02X (%d)", inputMID[adsrPointer + adsrIndex * 7 + 3], inputMID[adsrPointer + adsrIndex * 7 + 3]);
fprintf(outFile, " ADSR Decay Rate %02X (%d)", inputMID[adsrPointer + adsrIndex * 7 + 4], inputMID[adsrPointer + adsrIndex * 7 + 4]);
fprintf(outFile, " ADSR Sustain Level %02X (%d)", inputMID[adsrPointer + adsrIndex * 7 + 5], inputMID[adsrPointer + adsrIndex * 7 + 5]);
fprintf(outFile, " ADSR Release Rate %02X (%d)", inputMID[adsrPointer + adsrIndex * 7 + 6], inputMID[adsrPointer + adsrIndex * 7 + 6]);
}
}
else
{
if (command == 0x80)
{
//End?
fprintf(outFile, " End");
break;
}
else if (command == 0x81)
{
//XX, Instrument # In List
fprintf(outFile, " Instrument");
int instrument = GetSngVariableLength(inputMID, spot);
if ((sngStyle == SngStyle::Old) || (sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::PtrBfx))
{
if (instrument < 0x80)
{
fprintf(outFile, " Instrument %02X (%d)", inputMID[spot], instrument);
spot++;
}
else
{
fprintf(outFile, " Instrument %02X%02X (%d)", inputMID[spot], inputMID[spot+1], instrument);
spot += 2;
}
}
else if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Bfx) || (sngStyle == SngStyle::OldDD))
{
if (instrument >= totalInstruments)
{
if (instrument < 0x80)
{
fprintf(outFile, " Instrument %02X (%d) (TOO BIG Looked up)", inputMID[spot], instrument);
spot++;
}
else
{
fprintf(outFile, " Instrument %02X%02X (%d) (TOO BIG Looked up)", inputMID[spot], inputMID[spot+1], instrument);
spot += 2;
}
}
else
{
if (instrument < 0x80)
{
fprintf(outFile, " Instrument %02X (%d) (Looked up %02X)", inputMID[spot], instrument, CharArrayToShort(&inputMID[instrumentPointer + (inputMID[spot] * 2)]));
spot++;
}
else
{
fprintf(outFile, " Instrument %02X%02X (%d) (Looked up %02X)", inputMID[spot], inputMID[spot+1], instrument, CharArrayToShort(&inputMID[instrumentPointer + (inputMID[spot] * 2)]));
spot += 2;
}
}
}
}
else if (command == 0x82)
{
if ((sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::Bfx) || (sngStyle == SngStyle::PtrBfx))
{
//??
fprintf(outFile, " ?");
}
else
{
//Set Slide XX
fprintf(outFile, " Set Slide");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
}
else if (command == 0x83)
{
// ?
fprintf(outFile, " ?");
}
else if (command == 0x84)
{
//XX ADSR SubIndex
fprintf(outFile, " ADSR Data");
fprintf(outFile, " Rate %02X (%d)", inputMID[spot], inputMID[spot]);
fprintf(outFile, " Start Level %02X (%d)", inputMID[spot + 1], inputMID[spot + 1]);
fprintf(outFile, " Attack Rate %02X (%d)", inputMID[spot + 2], inputMID[spot + 2]);
fprintf(outFile, " Peak Level %02X (%d)", inputMID[spot + 3], inputMID[spot + 3]);
fprintf(outFile, " Decay Rate %02X (%d)", inputMID[spot + 4], inputMID[spot + 4]);
fprintf(outFile, " Sustain Level %02X (%d)", inputMID[spot + 5], inputMID[spot + 5]);
fprintf(outFile, " Release Rate %02X (%d)", inputMID[spot + 6], inputMID[spot + 6]);
spot += 7;
}
else if (command == 0x85)
{
//XX Master Track Tempo, 0x28 = 40, 0x78 = 120
fprintf(outFile, " Master Track Tempo");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0x86)
{
//XXXX Set Release Time for upcoming notes
fprintf(outFile, " Set Release Time");
fprintf(outFile, " %04X (%d)", CharArrayToShort(&inputMID[spot]), CharArrayToShort(&inputMID[spot]));
spot+=2;
}
else if (command == 0x87)
{
//XX 01 Set Release Time back to full note (01)
fprintf(outFile, " Set Release Time Back to Full");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0x88)
{
//XX YY ZZ Vibrato Up - Delay, Amount, Speed
fprintf(outFile, " Vibrato Up");
fprintf(outFile, " Delay %02X (%d) Amount %02X (%d) Speed %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot+=3;
}
else if (command == 0x89)
{
//XX YY ZZ Vibrato Down - Delay, Amount, Speed
fprintf(outFile, " Vibrato Down");
fprintf(outFile, " Delay %02X (%d) Amount %02X (%d) Speed %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot+=3;
}
else if (command == 0x8A)
{
//Solo
fprintf(outFile, " Solo");
}
else if (command == 0x8B)
{
//LL Set Length notes following and disable in list (variable time)
if ((sngStyle == SngStyle::Old) || (sngStyle == SngStyle::OldDD))
{
fprintf(outFile, " Set Length Notes and Disable in Note Format");
definedLength = GetSngVariableLength(inputMID, spot);
if (definedLength == 0x00)
{
fprintf(outFile, " Disabled %02X (%d)", inputMID[spot], definedLength);
useDefinedLength = false;
spot++;
}
else if (definedLength < 0x80)
{
useDefinedLength = true;
fprintf(outFile, " Length %02X (%d)", inputMID[spot], definedLength);
spot++;
}
else
{
useDefinedLength = true;
fprintf(outFile, " Length %02X%02X (%d)", inputMID[spot], inputMID[spot+1], definedLength);
spot += 2;
}
}
else
{
fprintf(outFile, " Set Length Notes and Disable in Note Format");
useDefinedLength = true;
definedLength = GetSngVariableLength(inputMID, spot);
if (definedLength < 0x80)
{
fprintf(outFile, " Length %02X (%d)", inputMID[spot], definedLength);
spot++;
}
else
{
fprintf(outFile, " Length %02X%02X (%d)", inputMID[spot], inputMID[spot+1], definedLength);
spot += 2;
}
}
}
else if (command == 0x8D)
{
//XX Transpose, 00 default, 01, etc
fprintf(outFile, " Transpose");
fprintf(outFile, " %02X (%d)", inputMID[spot], (signed char)inputMID[spot]);
spot++;
}
else if (command == 0x8F)
{
//XX Detune (signed)
fprintf(outFile, " Detune");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0x90)
{
//XX ADSR SubIndex
fprintf(outFile, " ADSR Index");
fprintf(outFile, " %02X", inputMID[spot]);
fprintf(outFile, " Rate %02X (%d)", inputMID[adsrPointer + inputMID[spot] * 7], inputMID[adsrPointer + inputMID[spot] * 7]);
fprintf(outFile, " Start Level %02X (%d)", inputMID[adsrPointer + inputMID[spot] * 7 + 1], inputMID[adsrPointer + inputMID[spot] * 7 + 1]);
fprintf(outFile, " Attack Rate %02X (%d)", inputMID[adsrPointer + inputMID[spot] * 7 + 2], inputMID[adsrPointer + inputMID[spot] * 7 + 2]);
fprintf(outFile, " Peak Level %02X (%d)", inputMID[adsrPointer + inputMID[spot] * 7 + 3], inputMID[adsrPointer + inputMID[spot] * 7 + 3]);
fprintf(outFile, " Decay Rate %02X (%d)", inputMID[adsrPointer + inputMID[spot] * 7 + 4], inputMID[adsrPointer + inputMID[spot] * 7 + 4]);
fprintf(outFile, " Sustain Level %02X (%d)", inputMID[adsrPointer + inputMID[spot] * 7 + 5], inputMID[adsrPointer + inputMID[spot] * 7 + 5]);
fprintf(outFile, " Release Rate %02X (%d)", inputMID[adsrPointer + inputMID[spot] * 7 + 6], inputMID[adsrPointer + inputMID[spot] * 7 + 6]);
spot++;
}
else if (command == 0x91)
{
//Envelope Trigger Off
fprintf(outFile, " Envelope Trigger Off");
}
else if (command == 0x92)
{
//Envelope Trigger On
fprintf(outFile, " Envelope Trigger On");
}
else if (command == 0x93)
{
//Sample Trigger Off
fprintf(outFile, " Sample Trigger Off");
}
else if (command == 0x94)
{
//Sample Trigger On
fprintf(outFile, " Sample Trigger On");
}
else if (command == 0x95)
{
//XX Loop Start FF Count?
fprintf(outFile, " Loop Start");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0x96)
{
//Loop
fprintf(outFile, " Loop Back");
break;
}
else if (command == 0x97)
{
//XX YY ZZ Wobble - Offset, Transpose, Normal
fprintf(outFile, " Wobble");
fprintf(outFile, " Offset %02X (%d) Transpose %02X (%d) Normal %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot+=3;
}
else if (command == 0x98)
{
// ?
fprintf(outFile, " ?");
}
else if (command == 0x99)
{
useDefinedVelocity = false;
//Reenable velocity on notes
fprintf(outFile, " Reenable Velocity on Notes Format");
}
else if (command == 0x9A) // Old Style Only
{
// ?
useDefinedVelocity = true;
fprintf(outFile, " Enable Velocity Defined in Notes");
}
else if (command == 0x9B) // Old Style Only
{
// ?
fprintf(outFile, " Set Repeat Velocity");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
definedVelocity = inputMID[spot];
useDefinedVelocity = true;
spot++;
}
else if (command == 0x9C)
{
//XX Pan, 0x00
fprintf(outFile, " Pan");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0x9E)
{
//XX Drum map on
fprintf(outFile, " Drum Map Start Index");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
drumBankOffset = inputMID[spot];
spot++;
}
else if (command == 0x9F)
{
//Drum map off
drumBankOffset = -1;
fprintf(outFile, " Drum Map Off");
}
else if (command == 0xA2)
{
//XX Effect, 0x00
fprintf(outFile, " Effect");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xA3)
{
//XX YY ?
fprintf(outFile, " ?");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xA3)
{
//XX YY Set Min/Max Transpose
fprintf(outFile, " Set Min/Max Tranpose");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command == 0xA4)
{
//XX YY Set Min/Max Volume
fprintf(outFile, " Set Min/Max Volume");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command == 0xA5)
{
//XX YY Set Min/Max Pan
fprintf(outFile, " Set Min/Max Pan");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command == 0xA6)
{
//XX Set Note Volume (Mini Style)
fprintf(outFile, " Set Note Volume (Mini Style)");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xA7)
{
//LL ?
fprintf(outFile, " Load Track #");
int length = GetSngVariableLength(inputMID, spot);
if (length < 0x80)
{
fprintf(outFile, " %02X (%d)\n", inputMID[spot], length);
spot++;
}
else
{
fprintf(outFile, " %02X%02X (%d)\n", inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else if (command == 0xA8)
{
//XX Pitch Bend
fprintf(outFile, " Pitch Bend");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xA9)
{
//XX Stereo Sweep Speed
fprintf(outFile, " Stereo Sweep Speed");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xAA)
{
//XX Master Track Effect 00 = None, 01 = Small Room, 02 = Big Room, 03 = Chorus, 04 = Flange, 05 = Echo
fprintf(outFile, " Master Track Effect");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
if (inputMID[spot] == 0)
fprintf(outFile, "None");
else if (inputMID[spot] == 1)
fprintf(outFile, "Small Room");
else if (inputMID[spot] == 2)
fprintf(outFile, "Big Room");
else if (inputMID[spot] == 3)
fprintf(outFile, "Chorus");
else if (inputMID[spot] == 4)
fprintf(outFile, "Flange");
else if (inputMID[spot] == 5)
fprintf(outFile, "Echo");
spot++;
}
else if (command == 0xAB)
{
//XX Master Track Sync - 1
fprintf(outFile, " Master Track Sync");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xAC)
{
// Reenable length on notes
useDefinedLength = false;
fprintf(outFile, " Reenable length on notes");
}
else if (command == 0xB0)
{
//XX ?
fprintf(outFile, " ?");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else
{
fprintf(outFile, " UNKNOWN");
return;
}
}
fprintf(outFile, "\n");
}
}
void CMidiParse::KonamiTrackToDebugTextFile(FILE* outFile, unsigned char* inputMID, unsigned long offset, unsigned long end, ExtraGameMidiInfo extraGameMidiInfo, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, int highestTrackLength)
{
unsigned char command = 0x00;
unsigned long spot = offset;
unsigned char lastDuration = 0x00;
unsigned char lastLength = 0x00;
unsigned long absoluteTime = 0;
unsigned char loopAmountsLeft = 0x00;
unsigned long loopSpot = 0;
unsigned long loopEndSpot = 0;
unsigned char loopNestedAmountsLeft = 0x00;
unsigned long loopNestedSpot = 0;
unsigned long loopNestedEndSpot = 0;
unsigned long masterLoopMarkerStartOffset;
unsigned long masterLoopMarkerEndOffset;
int totalLoopsToOutputLeft = 0;
if (writeOutLoops)
totalLoopsToOutputLeft = loopWriteCount;
int currentEDOffset = 0;
int currentEEEndOffset = 0;
int eeCountOverall = 0;
while ((command != 0x80) && (spot < end))
{
if (extendTracksToHighest)
{
if (absoluteTime >= highestTrackLength)
break;
}
command = inputMID[spot];
if (command < 0xD0)
{
if (command >= 0x68)
{
fprintf(outFile, "%08X Time: %08X NOTE : %02X*", spot, absoluteTime, (command - 0x68));
}
else
{
fprintf(outFile, "%08X Time: %08X NOTE : %02X ", spot, absoluteTime, command);
}
}
else
fprintf(outFile, "%08X Time: %08X Command: %02X ", spot, absoluteTime, command);
spot++;
if (command < 0xD0)
{
if ((command == 0x67) || (command == (0x67 + 0x68)))
{
fprintf(outFile, " Drum Instrument Lookup %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
if (command >= 0x68)
{
command -= 0x68;
fprintf(outFile, " [Repeated Duration %02X (%d)]", lastDuration, lastDuration);
}
else
{
fprintf(outFile, " Duration %02X (%d)", inputMID[spot], inputMID[spot]);
lastDuration = inputMID[spot];
spot++;
}
if (inputMID[spot] < 0x80)
{
fprintf(outFile, " Length %02X (%d) Velocity %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
lastLength = inputMID[spot];
spot += 2;
}
else
{
fprintf(outFile, " [Repeated Length %02X (%d)] Velocity %02X* (%d)", lastLength, lastLength, inputMID[spot] & 0x7F, inputMID[spot] & 0x7F);
spot++;
}
if (command < 0x48)
{
fprintf(outFile, " Keyboard");
}
else
{
if (command == 0x67)
{
fprintf(outFile, " Drums Instrument");
}
else
{
fprintf(outFile, " Drums");
}
}
absoluteTime += lastDuration;
}
else
{
if (command == 0xD0)
{
fprintf(outFile, " ((Tempo))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xD1)
{
fprintf(outFile, " ((Tempo Change Fade))");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xD2)
{
fprintf(outFile, " ((Instrument Change))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xD3)
{
fprintf(outFile, " ((Instrument/Volume Change))");
fprintf(outFile, " Volume %02X (%d) Instrument %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xD4)
{
fprintf(outFile, " ((Instrument/Volume/Pan Initial))");
fprintf(outFile, " Volume %02X (%d) Instrument %02X (%d) Pan %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xD5)
{
fprintf(outFile, " ((Volume))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xD6)
{
fprintf(outFile, " ((Volume))");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xD7)
{
fprintf(outFile, " ((Fade Out))");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xD8)
{
fprintf(outFile, " ((Staccato))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xD9)
{
fprintf(outFile, " ((Section Hold Note))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xDA)
{
fprintf(outFile, " ((Reverb))");
fprintf(outFile, " Type/Separation %02X (%d) Amount %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xDB)
{
fprintf(outFile, " UNKNOWN (Invalid)");
break;
}
else if (command == 0xDC)
{
fprintf(outFile, " UNKNOWN (Invalid)");
break;
}
else if (command == 0xDD)
{
fprintf(outFile, " ((Pan))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xDE)
{
fprintf(outFile, " Stereo Pan");
fprintf(outFile, " Left %02X (%d) to Right %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xDF)
{
fprintf(outFile, " ((Coarse Tune))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xE0)
{
fprintf(outFile, " ((Fine Tune))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xE1)
{
fprintf(outFile, " ((Tremolo))");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xE2) //Jikkyou Powerful Pro Yakyuu 2000 (J) (V1.0)
{
fprintf(outFile, " ?");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xE3) // Start new game and let go to hit
{
fprintf(outFile, " ?");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
// E4??
else if (command == 0xE4) // Something weird about this, seems like a followup to a note, trying this for now
{
fprintf(outFile, " ((Pitch Bend Previous Note))");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xE5) // No. 47 music
{
fprintf(outFile, " ((Pitch Ascend Next Note))");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xE6)
{
fprintf(outFile, " ((Slide Notes in Section))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xE7)
{
loopSpot = spot - 1;
fprintf(outFile, " ((Marker))");
}
else if (command == 0xE8)
{
fprintf(outFile, " ((Loop from Marker))");
fprintf(outFile, " %02X (%d) Times %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
unsigned char readAmount = inputMID[spot];
spot += 3;
if (readAmount > 0x01)
{
if (loopEndSpot != spot)
{
loopEndSpot = spot;
spot = loopSpot;
loopAmountsLeft = readAmount - 1;
}
else
{
loopAmountsLeft--;
if (loopAmountsLeft > 0)
{
spot = loopSpot;
}
else
{
// Reset
loopEndSpot = 0;
}
}
}
else if (readAmount == 0x00)
{
// Similar to master loop
if (extendTracksToHighest)
{
fprintf(outFile, "...Extending Tracks to Highest, Going to %08X", loopSpot);
spot = loopSpot;
}
else if (totalLoopsToOutputLeft > 0)
{
fprintf(outFile, "...Master Loop, Going to %08X", loopSpot);
spot = loopSpot;
totalLoopsToOutputLeft--;
}
}
}
else if (command == 0xE9)
{
fprintf(outFile, " ((Nested Loop Marker))");
loopNestedSpot = spot - 1;
}
else if (command == 0xEA)
{
fprintf(outFile, " ((Nested Loop from Marker))");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
unsigned char readAmount = inputMID[spot];
spot += 3;
if (readAmount > 0x01)
{
if (loopNestedEndSpot != spot)
{
loopNestedEndSpot = spot;
spot = loopNestedSpot;
loopNestedAmountsLeft = readAmount - 1;
}
else
{
loopNestedAmountsLeft--;
if (loopNestedAmountsLeft > 0)
{
spot = loopNestedSpot;
}
else
{
// Reset
loopNestedEndSpot = 0;
}
}
}
else if (readAmount == 0x00)
{
// Similar to master loop
if (extendTracksToHighest)
{
fprintf(outFile, "...Extending Tracks to Highest, Going to %08X", loopNestedSpot);
spot = loopNestedSpot;
}
else if (totalLoopsToOutputLeft > 0)
{
fprintf(outFile, "...Master Loop, Going to %08X", loopNestedSpot);
spot = loopNestedSpot;
totalLoopsToOutputLeft--;
}
}
}
else if (command == 0xEB)
{
fprintf(outFile, " ((Master Loop Start))");
masterLoopMarkerStartOffset = spot;
}
else if (command == 0xEC)
{
fprintf(outFile, " ((Master Loop End))");
masterLoopMarkerEndOffset = spot - 1;
if (extendTracksToHighest)
{
fprintf(outFile, "...Extending Tracks to Highest, Going to %08X", masterLoopMarkerStartOffset);
spot = masterLoopMarkerStartOffset;
}
else if (totalLoopsToOutputLeft > 0)
{
fprintf(outFile, "...Master Loop, Going to %08X", masterLoopMarkerStartOffset);
spot = masterLoopMarkerStartOffset;
totalLoopsToOutputLeft--;
}
}
else if (command == 0xED)
{
fprintf(outFile, " ((Loop Skip Start))");
currentEDOffset = spot;
currentEEEndOffset = 0;
eeCountOverall = 0;
}
else if (command == 0xEE)
{
fprintf(outFile, " ((Loop Skip Middle))");
if (eeCountOverall == 0)
{
if (currentEEEndOffset != 0x00000000)
{
fprintf(outFile, "...Going to %08X", currentEEEndOffset);
spot = currentEEEndOffset;
}
eeCountOverall = 1;
}
else if (eeCountOverall == 1)
{
currentEEEndOffset = spot;
spot = currentEDOffset;
eeCountOverall = 0;
fprintf(outFile, "...Going to %08X", currentEDOffset);
}
}
else if (command == 0xEF)
{
fprintf(outFile, " ((Effect Delay))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xF0)
{
fprintf(outFile, " ((Bank Select))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xF1)
{
fprintf(outFile, " ?");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xF2)
{
fprintf(outFile, " ((Delay Note))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
absoluteTime += inputMID[spot];
spot++;
}
else if (command == 0xF3)
{
fprintf(outFile, " ((Previous Note Hold))");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
unsigned long noteDuration = inputMID[spot];;
unsigned long noteLength = inputMID[spot+1];
absoluteTime += noteDuration;
spot += 2;
}
// FA/FB Goemon's Great Adventure (U) - 0053D780, not sure if legit
else if (command == 0xFA)
{
fprintf(outFile, " ?");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xFB)
{
fprintf(outFile, " ?");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command >= 0xF4)
{
fprintf(outFile, " End");
break;
}
else
{
fprintf(outFile, " UNKNOWN");
return;
}
}
fprintf(outFile, "\n");
}
}
void CMidiParse::KonamiToDebugTextFile(unsigned char* ROM, int romSize, CString gameName, unsigned long address, CString midiFile, CString textFileOut, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long extra)
{
CString filepath = midiFile;
FILE* inFile = fopen(filepath, "rb");
if (inFile == NULL)
{
MessageBox(NULL, "Can't read input file " + filepath, "Error", NULL);
return;
}
fseek(inFile, 0, SEEK_END);
int inputSize = ftell(inFile);
rewind(inFile);
unsigned char* inputMID = new unsigned char[inputSize];
fread(inputMID, 1, inputSize, inFile);
fclose(inFile);
KonamiToDebugTextFile(ROM, romSize, gameName, address, inputMID, inputSize, textFileOut, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
delete [] inputMID;
}
void CMidiParse::KonamiToDebugTextFile(unsigned char* ROM, int romSize, CString gameName, unsigned long address, byte* inputMID, int inputSize, CString textFileOut, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long extra)
{
CString addressStr;
addressStr.Format("%08X", address);
int numberTracks = 0x0;
if (numberTracks == 0x0)
{
numberTracks = CharArrayToShort(&inputMID[0]) / 2;
}
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, gameName + " - " + addressStr + "\n");
int highestTrackLength = 0;
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToShort(&inputMID[(x * 2)]);
if (trackDataPointer >= inputSize)
{
numberTracks = x;
break;
}
// Fake track
if ((x > 0) && (inputMID[trackDataPointer-1] != 0xFF))
{
break;
}
unsigned long trackEnd;
/*if (x < (numberTracks - 1))
{
trackEnd = CharArrayToShort(&inputMID[((x + 1) * 2)]);
}
else*/
{
trackEnd = inputSize;
}
int trackLength = FindHighestKonamiLengthTrack(x, inputMID, trackDataPointer, trackEnd);
if (trackLength > highestTrackLength)
highestTrackLength = trackLength;
}
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToShort(&inputMID[(x * 2)]);
if (trackDataPointer >= inputSize)
{
numberTracks = x;
break;
}
// Fake track
if ((x > 0) && (inputMID[trackDataPointer-1] != 0xFF))
{
numberTracks = x;
break;
}
unsigned long trackEnd;
/*if (x < (numberTracks - 1))
trackEnd = CharArrayToShort(&inputMID[((x + 1) * 2)]);
else*/
trackEnd = inputSize;
fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X\n------------------------------------------------------\n", x + 1, trackDataPointer);
fprintf(outFile, "\nTrack Data\n");
KonamiTrackToDebugTextFile(outFile, inputMID, trackDataPointer, trackEnd, extraGameMidiInfo, writeOutLoops, loopWriteCount, extendTracksToHighest, highestTrackLength);
}
fclose(outFile);
}
void CMidiParse::SSEQTrackToDebugTextFile(FILE* outFile, unsigned char* inputMID, unsigned long offset, unsigned long end, ExtraGameMidiInfo extraGameMidiInfo, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, int highestTrackLength)
{
unsigned char command = 0x00;
int spot = offset;
int loopSpot = 0;
unsigned long absoluteTime = 0;
while (spot < end)
{
if (extendTracksToHighest)
{
if (absoluteTime >= highestTrackLength)
break;
}
int startSpot = spot;
unsigned long original;
unsigned char* altPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
unsigned long deltaTime = GetVLBytes(inputMID, spot, original, altPattern, altOffset, altLength, false);
absoluteTime += deltaTime;
command = inputMID[spot];
fprintf(outFile, "%08X:Absolute Time: %08X (Delta %08X) Command %02X", startSpot, absoluteTime, deltaTime, command);
if (command == 0x7)
{
fprintf(outFile, " Instrument %02X%02X [Instrument Change]", inputMID[spot + 2], inputMID[spot + 1]);
}
else if (command == 0x11)
{
fprintf(outFile, " Note %02X Velocity %02X [Note On]", inputMID[spot + 1], inputMID[spot + 2]);
}
else if (command == 0x12)
{
fprintf(outFile, " Note %02X [Note Off]", inputMID[spot + 1]);
}
else if (command == 0x20)
{
fprintf(outFile, " %02X %02X [Loop]", inputMID[spot + 1], inputMID[spot + 2]);
if (extendTracksToHighest)
{
fprintf(outFile, "...Extending Tracks to Highest, Going to %08X", loopSpot);
spot = loopSpot;
}
}
else if (command == 0x22)
{
fprintf(outFile, " [End]\n");
break;
}
else if (command == 0x23)
{
loopSpot = spot;
fprintf(outFile, " [Loop Start]");
}
else
{
for (int x = 1; x < sseqCommandSizes[command]; x++)
{
fprintf(outFile, " %02X", inputMID[spot + x]);
}
}
spot += sseqCommandSizes[command];
fprintf(outFile, "\n");
}
}
void CMidiParse::SSEQToDebugTextFile(unsigned char* ROM, int romSize, CString gameName, unsigned long address, CString midiFile, CString textFileOut, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long extra)
{
CString filepath = midiFile;
FILE* inFile = fopen(filepath, "rb");
if (inFile == NULL)
{
MessageBox(NULL, "Can't read input file " + filepath, "Error", NULL);
return;
}
fseek(inFile, 0, SEEK_END);
int inputSize = ftell(inFile);
rewind(inFile);
unsigned char* inputMID = new unsigned char[inputSize];
fread(inputMID, 1, inputSize, inFile);
fclose(inFile);
SSEQToDebugTextFile(ROM, romSize, gameName, address, inputMID, inputSize, textFileOut, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
delete [] inputMID;
}
void CMidiParse::SSEQToDebugTextFile(unsigned char* ROM, int romSize, CString gameName, unsigned long address, byte* inputMID, int inputSize, CString textFileOut, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long extra)
{
numberTracks = extra;
CString addressStr;
addressStr.Format("%08X", address);
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, gameName + " - " + addressStr + "\n");
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
try
{
std::vector<SngNoteInfo> sngNoteList;
int trackRealLength = 0;
int loopStart = 0;
int loopEnd = 0;
int maxTrackLength = 0;
int highestTrackLength = 0;
int trackLength = FindHighestSSEQLengthTrack(inputMID, inputSize, numberTracks);
if (trackLength > highestTrackLength)
highestTrackLength = trackLength;
unsigned long offsetData = 0;
for (int track = 0; track < numberTracks; track++)
{
unsigned long division = CharArrayToLong(&inputMID[offsetData + 8]);
unsigned short division2 = CharArrayToShort(&inputMID[offsetData + 0xC]);
unsigned short extraFlag = CharArrayToShort(&inputMID[offsetData + 0xE]);
unsigned long sizeTrack = CharArrayToLong(&inputMID[offsetData + 0x10]);
fprintf(outFile, "Track %X - %08X Division %08X Division2 %04X", track, offsetData, division, division2);
if (extraFlag)
{
fprintf(outFile, " Extra %08X", CharArrayToLong(&inputMID[offsetData + 0x14]));
offsetData += 4;
}
fprintf(outFile, "\n");
offsetData += 0x14;
SSEQTrackToDebugTextFile(outFile, inputMID, offsetData, inputSize, extraGameMidiInfo, writeOutLoops, loopWriteCount, extendTracksToHighest, highestTrackLength);
offsetData += sizeTrack;
}
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
fclose(outFile);
}
void CMidiParse::WriteSngToMidiTrack(FILE* outFile, FILE* outDebug, std::vector<TrackEvent> trackEvents)
{
unsigned long timeOffset = 0;
unsigned long sizeData = 0;
byte previousTrackEvent = 0x0;
for (int eventCount = 0; eventCount < trackEvents.size(); eventCount++)
{
TrackEvent trackEvent = trackEvents[eventCount];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type >= 0xF0))
{
sizeData += 1;
}
sizeData += trackEvent.contentSize;
previousTrackEvent = trackEvent.type;
}
}
unsigned long tempLong = Flip32Bit(0x4D54726B);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(sizeData);
fwrite(&tempLong,1, 4, outFile);
timeOffset = 0;
previousTrackEvent = 0x0;
int currentPos = 0;
for (int eventCount = 0; eventCount < trackEvents.size(); eventCount++)
{
TrackEvent trackEvent = trackEvents[eventCount];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, false);
if (outDebug != NULL)
fprintf(outDebug, "Offset %08X Time Length %02X Time Value %08X Delta Time %d ", currentPos, lengthTimeDelta, timeDelta, trackEvent.deltaTime);
currentPos += lengthTimeDelta;
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type >= 0xF0))
{
fwrite(&trackEvent.type, 1, 1, outFile);
if (outDebug != NULL)
fprintf(outDebug, " Write Type %02X", trackEvent.type);
currentPos++;
}
fwrite(trackEvent.contents, 1, trackEvent.contentSize, outFile);
if (outDebug != NULL)
fprintf(outDebug, " Content Size %02X ", trackEvent.contentSize);
if (outDebug != NULL)
{
for (int r = 0; r < trackEvent.contentSize; r++)
{
fprintf(outDebug, "%02X", trackEvent.contents[r]);
}
}
if (outDebug != NULL)
fprintf(outDebug, "\n");
currentPos += trackEvent.contentSize;
previousTrackEvent = trackEvent.type;
}
}
}
void CMidiParse::SngToMidi(byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool calculateInstrumentCountOnly, bool separateByInstrument, unsigned long extra)
{
numberInstruments = 1;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
try
{
std::vector<SngNoteInfo> sngNoteList;
if (inputMID[0x0] == 0x80) // Ptr Sng
{
unsigned long startDataNegative = (signed long)inputSize;
unsigned long initialPointer = extra;
unsigned long numberTracks = 0;
int pointerSpot = 0;
while (inputMID[pointerSpot] == 0x80)
{
numberTracks++;
pointerSpot += 4;
}
unsigned long adsrPointer = 0x00000000;
unsigned long drumPointer = 0x00000000;
unsigned long instrumentPointer = 0x00000000;
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[(x * 4)]) - initialPointer;
unsigned long trackEnd = 0x00000000;
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[((x + 1) * 4)]) - initialPointer;
}
else
{
trackEnd = inputSize;
}
std::vector<SngTimeValue> volumeByAbsoluteTime;
std::vector<SngTimeValue> pitchBendByAbsoluteTime;
ParseSngTrack(x, numberInstruments, tempoPositions, sngNoteList, inputMID + (signed long)startDataNegative, trackDataPointer, trackEnd, NULL, adsrPointer, drumPointer, volumeByAbsoluteTime, pitchBendByAbsoluteTime, SngStyle::PtrBfx, noteUniqueId, -1);
}
}
// Second check to avoid false positive of bfx, if count is 0x215, Mario Golf E
else if ((CharArrayToLong(&inputMID[0x0]) == 0x00000215) && (CharArrayToLong(&inputMID[0x4]) != 0x00000215)) // Binary Sng style
{
// parse sng
unsigned long numberTracks = CharArrayToLong(&inputMID[0x4]);
unsigned long totalInstruments = CharArrayToLong(&inputMID[0x8]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0xC]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0x10]);
unsigned long pitchBendPointer = CharArrayToLong(&inputMID[0x14]);
unsigned long adsrPointer = CharArrayToLong(&inputMID[0x18]);
unsigned long drumPointer = CharArrayToLong(&inputMID[0x1C]);
unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x20]);
unsigned long masterTrackPointer = CharArrayToLong(&inputMID[0x24]);
unsigned short* instrumentLookup = new unsigned short[totalInstruments];
for (int x = 0; x < totalInstruments; x++)
{
instrumentLookup[x] = CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]);
if (instrumentLookup[x] > numberInstruments)
{
numberInstruments = instrumentLookup[x] + 1;
}
}
if (calculateInstrumentCountOnly)
{
delete [] instrumentLookup;
return;
}
std::vector<SngTimeValue> masterVolumeByAbsoluteTime;
std::vector<SngTimeValue> masterPitchBendByAbsoluteTime;
unsigned long trackDataPointerFirst = CharArrayToLong(&inputMID[trackPointer]);
ParseSngTrack(-1, numberInstruments, tempoPositions, sngNoteList, inputMID, masterTrackPointer, trackDataPointerFirst, instrumentLookup, adsrPointer, drumPointer, masterVolumeByAbsoluteTime, masterPitchBendByAbsoluteTime, SngStyle::Normal, noteUniqueId, totalInstruments);
for (int x = 0; x < numberTracks; x++)
{
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
unsigned long volumeEnd = 0;
if (volumeDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long volumeDataPointerTest = CharArrayToLong(&inputMID[volumePointer + (y * 4)]);
if (volumeDataPointerTest != 0)
{
volumeEnd = volumeDataPointerTest;
break;
}
}
if (volumeEnd == 0)
{
volumeEnd = masterTrackPointer;
}
}
unsigned long pitchBendDataPointer = CharArrayToLong(&inputMID[pitchBendPointer + (x * 4)]);
unsigned long pitchBendEnd = 0;
if (pitchBendDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
pitchBendEnd = pitchBendDataPointerTest;
break;
}
}
if (pitchBendEnd == 0)
{
pitchBendEnd = masterTrackPointer;
}
}
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long trackEnd = inputSize;
if (x < (numberTracks - 1))
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
//fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume End %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumeDataPointer, volumeEnd);
std::vector<SngTimeValue> volumeByAbsoluteTime;
if (volumeDataPointer != 0)
{
//fprintf(outFile, "\nVolume\n");
unsigned long absoluteTime = 0;
unsigned long spot = volumeDataPointer;
while (spot < volumeEnd)
{
unsigned char volume = inputMID[spot];
bool singleLength = !(volume & 0x80);
volume = volume & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x80)
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], length);
spot++;
}
else
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X%02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length 01*\n", spot-1, absoluteTime, volume);
}
SngTimeValue volumePair;
volumePair.value = volume;
volumePair.startAbsoluteTime = absoluteTime;
volumePair.endAbsoluteTime = absoluteTime + length;
volumeByAbsoluteTime.push_back(volumePair);
absoluteTime += length;
}
}
std::vector<SngTimeValue> pitchBendByAbsoluteTime;
if (pitchBendDataPointer != 0)
{
//fprintf(outFile, "\nPitch Bend\n");
unsigned long absoluteTime = 0;
unsigned long spot = pitchBendDataPointer;
while (spot < pitchBendEnd)
{
unsigned char pitchBend = inputMID[spot];
bool singleLength = !(pitchBend & 0x80);
pitchBend = pitchBend & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x80)
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], length);
spot++;
}
else
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X%02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length 01*\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40));
}
SngTimeValue pitchBendPair;
pitchBendPair.value = pitchBend;
pitchBendPair.startAbsoluteTime = absoluteTime;
pitchBendPair.endAbsoluteTime = pitchBendPair.startAbsoluteTime + length;
pitchBendByAbsoluteTime.push_back(pitchBendPair);
absoluteTime += length;
}
}
//fprintf(outFile, "\nTrack Data\n");
ParseSngTrack(x, numberInstruments, tempoPositions, sngNoteList, inputMID, trackDataPointer, trackEnd, instrumentLookup, adsrPointer, drumPointer, volumeByAbsoluteTime, pitchBendByAbsoluteTime, SngStyle::Normal, noteUniqueId, totalInstruments);
}
delete [] instrumentLookup;
}
else if (CharArrayToLong(&inputMID[0x4]) == 0x00000000) // Pokemon Stadium, some Sngs for some reason
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0x8]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0xC]);
unsigned long adsrPointer = 0x00000000;
unsigned long drumPointer = 0x00000000;
unsigned long instrumentPointer = 0x00000000;
//FILE* outFile = fopen("C:\\temp\\trackparse.txt", "w");
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
if (trackEnd == 0x00000000)
trackEnd = inputSize;
}
else
{
trackEnd = inputSize;
}
}
unsigned long priorityDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
//fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume Data %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumePointer + (x * 4), volumeDataPointer);
//fprintf(outFile, "\nTrack Data\n");
std::vector<SngTimeValue> volumeByAbsoluteTime;
std::vector<SngTimeValue> pitchBendByAbsoluteTime;
ParseSngTrack(x, numberInstruments, tempoPositions, sngNoteList, inputMID, trackDataPointer, trackEnd, NULL, adsrPointer, drumPointer, volumeByAbsoluteTime, pitchBendByAbsoluteTime, SngStyle::OldBfx, noteUniqueId, -1);
}
}
else if (CharArrayToLong(&inputMID[0xC]) == 0x00000000) // BFX
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
unsigned long trackPointer = 0x18;
unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x14]);
int totalInstruments = (inputSize - instrumentPointer) / 0x4;
unsigned long adsrPointer = 0x00000000;
unsigned long drumPointer = 0x00000000;
unsigned short* instrumentLookup = new unsigned short[totalInstruments];
for (int x = 0; x < totalInstruments; x++)
{
instrumentLookup[x] = CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]);
if (instrumentLookup[x] > numberInstruments)
{
numberInstruments = instrumentLookup[x] + 1;
}
}
if (calculateInstrumentCountOnly)
{
delete [] instrumentLookup;
return;
}
//FILE* outFile = fopen("C:\\temp\\trackparse.txt", "w");
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 8)]);
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 8)]);
if (trackEnd == 0x00000000)
trackEnd = inputSize;
}
else
{
trackEnd = inputSize;
}
}
unsigned long priorityDataPointer = CharArrayToLong(&inputMID[trackDataPointer + (x * 8) + 4]);
//fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume Data %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumePointer + (x * 4), volumeDataPointer);
//fprintf(outFile, "\nTrack Data\n");
std::vector<SngTimeValue> volumeByAbsoluteTime;
std::vector<SngTimeValue> pitchBendByAbsoluteTime;
ParseSngTrack(x, numberInstruments, tempoPositions, sngNoteList, inputMID, trackDataPointer, trackEnd, instrumentLookup, adsrPointer, drumPointer, volumeByAbsoluteTime, pitchBendByAbsoluteTime, SngStyle::Bfx, noteUniqueId, totalInstruments);
}
delete [] instrumentLookup;
}
else if (CharArrayToLong(&inputMID[0x8]) == 0x00000020) // N64 DD Style
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
unsigned long totalInstruments = CharArrayToLong(&inputMID[0x4]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0x8]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0xC]);
unsigned long pitchBendPointer = CharArrayToLong(&inputMID[0x10]);
unsigned long adsrPointer = CharArrayToLong(&inputMID[0x14]);
unsigned long drumPointer = CharArrayToLong(&inputMID[0x18]);
unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x1C]);
unsigned short* instrumentLookup = new unsigned short[totalInstruments];
for (int x = 0; x < totalInstruments; x++)
{
instrumentLookup[x] = CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]);
if (instrumentLookup[x] > numberInstruments)
{
numberInstruments = instrumentLookup[x] + 1;
}
}
if (calculateInstrumentCountOnly)
{
delete [] instrumentLookup;
return;
}
for (int x = 0; x < numberTracks; x++)
{
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
unsigned long volumeEnd = 0;
if (volumeDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long volumeDataPointerTest = CharArrayToLong(&inputMID[volumePointer + (y * 4)]);
if (volumeDataPointerTest != 0)
{
volumeEnd = volumeDataPointerTest;
break;
}
}
if (volumeEnd == 0)
{
volumeEnd = CharArrayToLong(&inputMID[trackPointer]);
}
}
unsigned long pitchBendDataPointer = CharArrayToLong(&inputMID[pitchBendPointer + (x * 4)]);
unsigned long pitchBendEnd = 0;
if (pitchBendDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
pitchBendEnd = pitchBendDataPointerTest;
break;
}
}
if (pitchBendEnd == 0)
{
pitchBendEnd = CharArrayToLong(&inputMID[trackPointer]);
}
}
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
if (trackEnd == 0x00000000)
trackEnd = inputSize;
}
else
{
trackEnd = inputSize;
}
}
//fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume End %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumeDataPointer, volumeEnd);
std::vector<SngTimeValue> volumeByAbsoluteTime;
if (volumeDataPointer != 0)
{
//fprintf(outFile, "\nVolume\n");
unsigned long absoluteTime = 0;
unsigned long spot = volumeDataPointer;
while (spot < volumeEnd)
{
unsigned char volume = inputMID[spot];
bool singleLength = !(volume & 0x80);
volume = volume & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x80)
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], length);
spot++;
}
else
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X%02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length 01*\n", spot-1, absoluteTime, volume);
}
SngTimeValue volumePair;
volumePair.value = volume;
volumePair.startAbsoluteTime = absoluteTime;
volumePair.endAbsoluteTime = absoluteTime + length;
volumeByAbsoluteTime.push_back(volumePair);
absoluteTime += length;
}
}
std::vector<SngTimeValue> pitchBendByAbsoluteTime;
if (pitchBendDataPointer != 0)
{
//fprintf(outFile, "\nPitch Bend\n");
unsigned long absoluteTime = 0;
unsigned long spot = pitchBendDataPointer;
while (spot < pitchBendEnd)
{
unsigned char pitchBend = inputMID[spot];
bool singleLength = !(pitchBend & 0x80);
pitchBend = pitchBend & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x80)
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], length);
spot++;
}
else
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X%02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length 01*\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40));
}
SngTimeValue pitchBendPair;
pitchBendPair.value = pitchBend;
pitchBendPair.startAbsoluteTime = absoluteTime;
pitchBendPair.endAbsoluteTime = pitchBendPair.startAbsoluteTime + length;
pitchBendByAbsoluteTime.push_back(pitchBendPair);
absoluteTime += length;
}
}
//fprintf(outFile, "\nTrack Data\n");
ParseSngTrack(x, numberInstruments, tempoPositions, sngNoteList, inputMID, trackDataPointer, trackEnd, instrumentLookup, adsrPointer, drumPointer, volumeByAbsoluteTime, pitchBendByAbsoluteTime, SngStyle::Normal, noteUniqueId, totalInstruments);
}
delete [] instrumentLookup;
}
else // Old Style
{
unsigned long numberTracks = CharArrayToLong(&inputMID[0x0]);
//unsigned long numberInstruments = CharArrayToLong(&inputMID[0x8]);
unsigned long trackPointer = CharArrayToLong(&inputMID[0x4]);
unsigned long volumePointer = CharArrayToLong(&inputMID[0x8]);
unsigned long pitchBendPointer = CharArrayToLong(&inputMID[0xC]);
unsigned long drumPointer = CharArrayToLong(&inputMID[0x10]);
unsigned long adsrPointer = CharArrayToLong(&inputMID[0x14]);
//unsigned long instrumentPointer = CharArrayToLong(&inputMID[0x20]);
unsigned long instrumentPointer = 0x00000000;
//FILE* outFile = fopen("C:\\temp\\trackparse.txt", "w");
/*//fprintf(outFile, "Instruments: %08X\n", instrumentPointer);
for (int x = 0; x < numberInstruments; x++)
{
//fprintf(outFile, "%02X: %04X\n", x, CharArrayToShort(&inputMID[instrumentPointer + (2 * x)]));
}
//fprintf(outFile, "\n\n---------------------------\nMaster Track: %08X\n---------------------------\n", masterTrackPointer);
unsigned long trackDataPointerFirst = CharArrayToLong(&inputMID[trackPointer]);
SngTrackToDebugTextFile(outFile, inputMID, masterTrackPointer, trackDataPointerFirst, instrumentPointer, adsrPointer, drumPointer);
*/
unsigned long tempo = 0;
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToLong(&inputMID[trackPointer + (x * 4)]);
unsigned long volumeDataPointer = CharArrayToLong(&inputMID[volumePointer + (x * 4)]);
unsigned long volumeEnd = 0;
unsigned long pitchBendDataPointer = CharArrayToLong(&inputMID[pitchBendPointer + (x * 4)]);
unsigned long pitchBendEnd = 0;
std::vector<SngTimeValue> volumeByAbsoluteTime;
if (volumeDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long volumeDataPointerTest = CharArrayToLong(&inputMID[volumePointer + (y * 4)]);
if (volumeDataPointerTest != 0)
{
volumeEnd = volumeDataPointerTest;
break;
}
}
if (volumeEnd == 0)
{
if (pitchBendDataPointer != 0)
{
for (int y = 0; y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
volumeEnd = pitchBendDataPointerTest;
break;
}
}
}
if (volumeEnd == 0)
{
// First track
volumeEnd = CharArrayToLong(&inputMID[trackPointer]);;
}
}
}
std::vector<SngTimeValue> pitchBendByAbsoluteTime;
if (pitchBendDataPointer != 0)
{
for (int y = (x + 1); y < numberTracks; y++)
{
unsigned long pitchBendDataPointerTest = CharArrayToLong(&inputMID[pitchBendPointer + (y * 4)]);
if (pitchBendDataPointerTest != 0)
{
pitchBendEnd = pitchBendDataPointerTest;
break;
}
}
if (pitchBendEnd == 0)
{
pitchBendEnd = CharArrayToLong(&inputMID[trackPointer]);
}
}
unsigned long trackEnd = 0x00000000;
if (trackDataPointer != 0x00000000)
{
if (x < (numberTracks - 1))
{
trackEnd = CharArrayToLong(&inputMID[trackPointer + ((x + 1) * 4)]);
if (trackEnd == 0x00000000)
trackEnd = inputSize;
}
else
{
trackEnd = inputSize;
}
}
//fprintf(outFile, "\n\n------------------------------------------------------\nTrack %d: %08X Volume Start %08X Volume End %08X\n------------------------------------------------------\n", x + 1, trackDataPointer, volumeDataPointer, volumeEnd);
if (volumeDataPointer != 0)
{
//fprintf(outFile, "\nVolume\n");
unsigned long absoluteTime = 0;
unsigned long spot = volumeDataPointer;
while (spot < volumeEnd)
{
unsigned char volume = inputMID[spot];
bool singleLength = !(volume & 0x80);
volume = volume & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], length);
spot++;
}
else
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length %02X%02X (%d)\n", spot-1, absoluteTime, volume, inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
//fprintf(outFile, "%08X Time: %08X Volume %02X Length 01*\n", spot-1, absoluteTime, volume);
}
SngTimeValue volumePair;
volumePair.value = volume;
volumePair.startAbsoluteTime = absoluteTime;
volumePair.endAbsoluteTime = absoluteTime + length;
volumeByAbsoluteTime.push_back(volumePair);
absoluteTime += length;
}
}
if (pitchBendDataPointer != 0)
{
//fprintf(outFile, "\nPitch Bend\n");
unsigned long absoluteTime = 0;
unsigned long spot = pitchBendDataPointer;
while (spot < pitchBendEnd)
{
unsigned char pitchBend = inputMID[spot];
bool singleLength = !(pitchBend & 0x80);
pitchBend = pitchBend & 0x7F;
spot++;
int length = 1;
if (!singleLength)
{
length = GetSngVariableLength(inputMID, spot) + 2;
if (length < 0x82)
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], length);
spot++;
}
else
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length %02X%02X (%d)\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40), inputMID[spot], inputMID[spot+1], length);
spot += 2;
}
}
else
{
//fprintf(outFile, "%08X Time: %08X PitchBend %02X (%d) Length 01*\n", spot-1, absoluteTime, pitchBend, (signed char)(pitchBend - 0x40));
}
SngTimeValue pitchBendPair;
pitchBendPair.value = pitchBend;
pitchBendPair.startAbsoluteTime = absoluteTime;
pitchBendPair.endAbsoluteTime = pitchBendPair.startAbsoluteTime + length;
pitchBendByAbsoluteTime.push_back(pitchBendPair);
absoluteTime += length;
}
}
//fprintf(outFile, "\nTrack Data\n");
ParseSngTrack(x, numberInstruments, tempoPositions, sngNoteList, inputMID, trackDataPointer, trackEnd, NULL, adsrPointer, drumPointer, volumeByAbsoluteTime, pitchBendByAbsoluteTime, SngStyle::Old, noteUniqueId, -1);
}
//fclose(outFile);
}
WriteSngList(sngNoteList, tempoPositions, outFileName, separateByInstrument, 0x0030, false, 24);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
bool CMidiParse::IsOverlap(float x1, float x2, float y1, float y2)
{
return x2 > y1 && y2 > x1;
}
int CMidiParse::GetSizeFile(CString filename)
{
FILE* inFile = fopen(filename, "rb");
if (inFile == 0)
return 0;
fseek(inFile, 0, SEEK_END);
int fileSize = ftell(inFile);
fclose(inFile);
return fileSize;
}
bool CMidiParse::MidiToPaperMarioSngList(CString input, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfoMidiImport> channels[MAXCHANNELS], int& numChannels, std::vector<int>& instruments, int& lowestAbsoluteTime, int& highestAbsoluteTime, bool loop, unsigned long loopPoint, unsigned short & division)
{
numChannels = 0;
lowestAbsoluteTime = 0x7FFFFFFF;
highestAbsoluteTime = 0;
int noteUniqueId = 0;
numberTracks = 0;
CString tempFileName = input;
struct stat results;
stat(tempFileName, &results);
FILE* inFile1 = fopen(tempFileName, "rb");
if (inFile1 == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
byte* inputMID = new byte[results.st_size];
fread(inputMID, 1, results.st_size, inFile1);
fclose(inFile1);
unsigned long header = CharArrayToLong(&inputMID[0]);
if (header != 0x4D546864)
{
delete [] inputMID;
MessageBox(NULL, "Invalid midi hdr", "Error", NULL);
return false;
}
unsigned long headerLength = CharArrayToLong(&inputMID[4]);
unsigned short type = CharArrayToShort(&inputMID[8]);
unsigned short numTracks = CharArrayToShort(&inputMID[0xA]);
division = CharArrayToShort(&inputMID[0xC]);
if (numTracks > 0x10)
{
delete [] inputMID;
MessageBox(NULL, "Invalid, can only support 16 tracks, first 1 only tempo", "Error", NULL);
return false;
}
float noteTimeDivisor = division / 0x30;
loopPoint = (float)loopPoint / noteTimeDivisor;
if (type == 0)
{
}
else if (type == 1)
{
}
else
{
delete [] inputMID;
MessageBox(NULL, "Invalid midi type", "Error", NULL);
return false;
}
int position = 0xE;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool unknownsHit = false;
for (int trackNum = 0; trackNum < numTracks; trackNum++)
{
std::vector<SngNoteInfoMidiImport> pendingNoteList;
int currentSegment[0x10];
unsigned char currentPan[0x10];
unsigned char currentVolume[0x10];
unsigned char currentReverb[0x10];
signed char currentPitchBend[0x10];
unsigned char currentMSBBank[0x10];
unsigned char currentLSBBank[0x10];
unsigned char currentInstrument[0x10];
// Controllers defaults
for (int x = 0; x < 0x10; x++)
{
currentPan[x] = 0x40;
currentVolume[x] = 0x7F;
currentReverb[x] = 0x00;
currentInstrument[x] = 0x00;
currentPitchBend[x] = 0x40;
currentMSBBank[x] = 0x00;
currentLSBBank[x] = 0x00;
currentSegment[x] = 0x00;
}
unsigned long absoluteTime = 0;
float absoluteTimeFloat = 0;
unsigned long trackHeader = ((((((inputMID[position] << 8) | inputMID[position+1]) << 8) | inputMID[position+2]) << 8) | inputMID[position+3]);
if (trackHeader != 0x4D54726B)
{
delete [] inputMID;
MessageBox(NULL, "Invalid track midi hdr", "Error", NULL);
return false;
}
unsigned long trackLength = ((((((inputMID[position+4] << 8) | inputMID[position+5]) << 8) | inputMID[position+6]) << 8) | inputMID[position+7]);
position += 8;
byte previousEventValue = 0xFF;
bool endFlag = false;
while (!endFlag && (position < results.st_size))
{
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
absoluteTimeFloat += (float)timeTag / noteTimeDivisor;
absoluteTime = absoluteTimeFloat;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
bool statusBit = false;
if (eventVal <= 0x7F)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if (eventVal == 0xFF) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x2F) //End of Track Event.
{
endFlag = true;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
}
else if (subType == 0x51) //Set Tempo Event.
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned char byteData[3];
byteData[0] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byteData[1] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byteData[2] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned long microSecondsSinceQuarterNote = ((((byteData[0] << 8) | byteData[1]) << 8) | byteData[2]);
unsigned long tempTempo = 60000000.0 / microSecondsSinceQuarterNote;
if (tempTempo > 255)
tempTempo = 255;
else if (tempTempo < 1)
tempTempo = 1;
else
tempTempo = (unsigned char)tempTempo;
bool matchTempo = false;
for (int y = 0; y < tempoPositions.size(); y++)
{
if (tempoPositions[y].absoluteTime == absoluteTime)
{
matchTempo = true;
}
}
if (!matchTempo)
{
tempoPositions.push_back(TimeAndValue(absoluteTime, tempTempo));
}
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
//newTrackEvent->type = 0xFF;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int i = 0; i < length; i++)
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
//newTrackEvent->type = 0xFF;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
previousEventValue = eventVal;
}
// Note off
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
if (velocity == 0)
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
}
else
{
// If wasn't shut off, turn it off from before, then start new note
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
SngNoteInfoMidiImport newSongInfo;
newSongInfo.originalController = controller;
newSongInfo.originalTrack = trackNum;
newSongInfo.originalNoteUniqueId = noteUniqueId++;
newSongInfo.noteNumber = noteNumber;
newSongInfo.velocity = velocity;
// Apply tempo later as master track
//newSongInfo.tempo = currentTempo;
newSongInfo.pan = currentPan[controller];
newSongInfo.volume = currentVolume[controller];
newSongInfo.effect = currentReverb[controller];
newSongInfo.instrument = currentInstrument[controller] + (currentLSBBank[controller] * 0x80) + (currentMSBBank[controller] * 0x8000);
newSongInfo.segmentNumber = currentSegment[controller];
newSongInfo.pitchBend = currentPitchBend[controller];
newSongInfo.startAbsoluteTime = absoluteTime;
pendingNoteList.push_back(newSongInfo);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change
{
byte controllerType;
unsigned char curEventVal;
if (statusBit)
{
controllerType = eventVal;
curEventVal = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
int controller = (curEventVal & 0xF);
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (controllerType == 0) // MSB Instrument Bank
{
currentMSBBank[controller] = controllerValue;
}
else if (controllerType == 7) // Volume
{
if (controllerValue != currentVolume[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].volume = controllerValue;
}
}
currentVolume[controller] = controllerValue;
}
else if (controllerType == 10) // Pan
{
if (controllerValue != currentPan[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].pan = controllerValue;
}
}
currentPan[controller] = controllerValue;
}
else if (controllerType == 32) // LSB Instrument Bank
{
currentLSBBank[controller] = controllerValue;
}
else if (controllerType == 91) // Reverb
{
if (controllerValue != currentReverb[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].effect = controllerValue;
}
}
currentReverb[controller] = controllerValue;
}
else if (controllerType == 104) // Segment
{
if (controllerValue >= currentSegment[controller])
{
currentSegment[controller] = controllerValue;
}
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument
{
byte instrument;
unsigned char curEventVal;
if (statusBit)
{
instrument = eventVal;
curEventVal = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
if ((eventVal & 0xF) == 9) // Drums in GM
instrument = instrument;
else
instrument = instrument;
int controller = (curEventVal & 0xF);
unsigned short tempInstrument = instrument + (currentLSBBank[controller] * 0x80) + (currentMSBBank[controller] * 0x8000);
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
if (pendingNoteList[p].instrument != tempInstrument)
{
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].instrument = tempInstrument;
}
}
currentInstrument[controller] = instrument;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch
{
unsigned char curEventVal;
byte amount;
if (statusBit)
{
amount = eventVal;
curEventVal = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
// Pitch Bend
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
unsigned char curEventVal;
if (statusBit)
{
valueLSB = eventVal;
curEventVal = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
if (currentPitchBend[controller] != valueMSB)
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[trackNum].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].pitchBend = valueMSB;
}
}
currentPitchBend[controller] = valueMSB;
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xF0 || eventVal == 0xF7)
{
unsigned char curEventVal = eventVal;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
else
{
if (!unknownsHit)
{
MessageBox(NULL, "Invalid midi character found", "Error", NULL);
unknownsHit = true;
}
}
}
for (int p = 0; p < pendingNoteList.size(); p++)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
channels[trackNum].push_back(pendingNoteList[p]);
}
// Clear empty notes
for (int x = (channels[trackNum].size() - 1); x >= 0; x--)
{
if (channels[trackNum][x].startAbsoluteTime == channels[trackNum][x].endAbsoluteTime)
channels[trackNum].erase(channels[trackNum].begin() + x);
}
for (int x = 0; x < channels[trackNum].size(); x++)
{
SngNoteInfoMidiImport tempNoteInfo = channels[trackNum][x];
if (tempNoteInfo.endAbsoluteTime > highestAbsoluteTime)
highestAbsoluteTime = tempNoteInfo.endAbsoluteTime;
if (tempNoteInfo.startAbsoluteTime < lowestAbsoluteTime)
lowestAbsoluteTime = tempNoteInfo.startAbsoluteTime;
}
}
delete [] inputMID;
//FILE* outDebug = fopen("C:\\GoldeneyeStuff\\GE Editor Source\\debug.txt", "w");
FILE* outDebug = NULL;
if (outDebug != NULL)
{
for (int trackNum = 0; trackNum < numTracks; trackNum++)
{
for (int x = 0; x < channels[trackNum].size(); x++)
{
fprintf(outDebug, "Start %08X End %08X Instrument %02X Note %02X Volume %02X Pitch Bend %02X Pan %02X Velocity %02X\n", channels[trackNum][x].startAbsoluteTime, channels[trackNum][x].endAbsoluteTime, channels[trackNum][x].instrument, channels[trackNum][x].noteNumber, channels[trackNum][x].volume, channels[trackNum][x].pitchBend, channels[trackNum][x].pan, channels[trackNum][x].velocity);
}
}
}
if (outDebug != NULL)
fclose(outDebug);
numChannels = numTracks;
if (numChannels == 0)
{
MessageBox(NULL, "No Channels", "Error", NULL);
return false;
}
if (loop && (loopPoint > highestAbsoluteTime))
{
MessageBox(NULL, "Error, loop point is beyond end of midi", "Error", NULL);
return false;
}
std::sort(tempoPositions.begin(), tempoPositions.end(), timeAndValueSortByTime());
for (int x = 0; x < numChannels; x++)
{
bool renumberedLoop = false;
int renumberSegment = -1;
// Separate
if (loop && (loopPoint != 0))
{
for (int y = (channels[x].size() - 1); y >= 0; y--)
{
SngNoteInfoMidiImport noteMidiImport = channels[x][y];
if ((loopPoint > noteMidiImport.startAbsoluteTime) && (loopPoint < noteMidiImport.endAbsoluteTime))
{
// Need to split
channels[x][y].endAbsoluteTime = loopPoint;
noteMidiImport.startAbsoluteTime = loopPoint;
channels[x].push_back(noteMidiImport);
renumberedLoop = true;
renumberSegment = noteMidiImport.segmentNumber;
}
}
}
std::sort(channels[x].begin(), channels[x].end(), sngSortByStartTime());
if (renumberedLoop)
{
for (int y = 0; y < channels[x].size(); y++)
{
if (channels[x][y].segmentNumber == renumberSegment)
{
if (channels[x][y].startAbsoluteTime >= loopPoint)
{
channels[x][y].segmentNumber = -1;
}
}
}
}
}
return true;
}
bool CMidiParse::MidiToSngList(CString input, std::vector<SngNoteInfoMidiImport>& sngNoteList, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfoMidiImport> channels[MAXCHANNELS], int& numChannels, std::vector<int>& instruments, int& lowestAbsoluteTime, int& highestAbsoluteTime, bool loop, unsigned long& loopPoint)
{
numChannels = 0;
lowestAbsoluteTime = 0x7FFFFFFF;
highestAbsoluteTime = 0;
int noteUniqueId = 0;
numberTracks = 0;
std::vector<CString> inputMidiNames;
inputMidiNames.push_back(input);
int checkAdditional = 1;
while (true)
{
CString midiNameStr = input;
bool isMidiExtension = false;
int indexEnd = midiNameStr.ReverseFind('.');
if (indexEnd == -1)
break;
CString extension = midiNameStr.Mid(indexEnd);
if (extension == ".midi")
{
midiNameStr = midiNameStr.Mid(0, indexEnd);
isMidiExtension = true;
}
else if (extension == ".mid")
{
midiNameStr = midiNameStr.Mid(0, indexEnd);
}
else
{
break;
}
CString tempStr;
tempStr.Format("%d", checkAdditional);
midiNameStr += "_AdditionalPart" + tempStr;
if (isMidiExtension)
midiNameStr += ".midi";
else
midiNameStr += ".mid";
if (GetSizeFile(midiNameStr) == 0)
break;
else if (checkAdditional == 1)
{
int iResults = MessageBox(NULL, "Do you want to incorporate the additional midi portions automatically found using the _AdditionalPart[#].mid", "Do you want to use additional midi portions?", MB_YESNO);
if (iResults == IDNO)
break;
}
inputMidiNames.push_back(midiNameStr);
checkAdditional++;
}
int trackOffset = 0;
for (int portion = 0; portion < inputMidiNames.size(); portion++)
{
CString tempFileName = inputMidiNames[portion];
struct stat results;
stat(tempFileName, &results);
FILE* inFile1 = fopen(tempFileName, "rb");
if (inFile1 == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
byte* inputMID = new byte[results.st_size];
fread(inputMID, 1, results.st_size, inFile1);
fclose(inFile1);
unsigned long header = CharArrayToLong(&inputMID[0]);
if (header != 0x4D546864)
{
delete [] inputMID;
MessageBox(NULL, "Invalid midi hdr", "Error", NULL);
return false;
}
unsigned long headerLength = CharArrayToLong(&inputMID[4]);
unsigned short type = CharArrayToShort(&inputMID[8]);
unsigned short numTracks = CharArrayToShort(&inputMID[0xA]);
unsigned short division = CharArrayToShort(&inputMID[0xC]);
float noteTimeDivisor = division / 0x30;
loopPoint = (float)loopPoint / noteTimeDivisor;
if (type == 0)
{
}
else if (type == 1)
{
}
else
{
delete [] inputMID;
MessageBox(NULL, "Invalid midi type", "Error", NULL);
return false;
}
int position = 0xE;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool unknownsHit = false;
for (int trackNum = 0; trackNum < numTracks; trackNum++)
{
std::vector<SngNoteInfoMidiImport> pendingNoteList;
unsigned char currentPan[0x10];
unsigned char currentVolume[0x10];
unsigned char currentReverb[0x10];
signed char currentPitchBend[0x10];
unsigned char currentMSBBank[0x10];
unsigned char currentLSBBank[0x10];
unsigned char currentInstrument[0x10];
// Controllers defaults
for (int x = 0; x < 0x10; x++)
{
currentPan[x] = 0x40;
currentVolume[x] = 0x7F;
currentReverb[x] = 0x00;
currentInstrument[x] = 0x00;
currentPitchBend[x] = 0x40;
currentMSBBank[x] = 0x00;
currentLSBBank[x] = 0x00;
currentInstrument[x] = 0x00;
}
unsigned long absoluteTime = 0;
float absoluteTimeFloat = 0;
unsigned long trackHeader = ((((((inputMID[position] << 8) | inputMID[position+1]) << 8) | inputMID[position+2]) << 8) | inputMID[position+3]);
if (trackHeader != 0x4D54726B)
{
delete [] inputMID;
MessageBox(NULL, "Invalid track midi hdr", "Error", NULL);
return false;
}
unsigned long trackLength = ((((((inputMID[position+4] << 8) | inputMID[position+5]) << 8) | inputMID[position+6]) << 8) | inputMID[position+7]);
position += 8;
byte previousEventValue = 0xFF;
bool endFlag = false;
while (!endFlag && (position < results.st_size))
{
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
absoluteTimeFloat += (float)timeTag / noteTimeDivisor;
absoluteTime = absoluteTimeFloat;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
bool statusBit = false;
if (eventVal <= 0x7F)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if (eventVal == 0xFF) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x2F) //End of Track Event.
{
endFlag = true;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
}
else if (subType == 0x51) //Set Tempo Event.
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned char byteData[3];
byteData[0] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byteData[1] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byteData[2] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned long microSecondsSinceQuarterNote = ((((byteData[0] << 8) | byteData[1]) << 8) | byteData[2]);
unsigned long tempTempo = 60000000.0 / microSecondsSinceQuarterNote;
if (tempTempo > 255)
tempTempo = 255;
else if (tempTempo < 1)
tempTempo = 1;
else
tempTempo = (unsigned char)tempTempo;
bool matchTempo = false;
for (int y = 0; y < tempoPositions.size(); y++)
{
if (tempoPositions[y].absoluteTime == absoluteTime)
{
matchTempo = true;
}
}
if (!matchTempo)
{
tempoPositions.push_back(TimeAndValue(absoluteTime, tempTempo));
}
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
//newTrackEvent->type = 0xFF;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int i = 0; i < length; i++)
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
//newTrackEvent->type = 0xFF;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
previousEventValue = eventVal;
}
// Note off
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
if (velocity == 0)
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
}
else
{
// If wasn't shut off, turn it off from before, then start new note
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
SngNoteInfoMidiImport newSongInfo;
newSongInfo.originalController = controller + (portion * 0x10);
newSongInfo.originalTrack = trackNum + trackOffset;
newSongInfo.originalNoteUniqueId = noteUniqueId++;
newSongInfo.noteNumber = noteNumber;
newSongInfo.velocity = velocity;
// Apply tempo later as master track
//newSongInfo.tempo = currentTempo;
newSongInfo.pan = currentPan[controller];
newSongInfo.volume = currentVolume[controller];
newSongInfo.effect = currentReverb[controller];
newSongInfo.instrument = currentInstrument[controller] + (currentLSBBank[controller] * 0x80) + (currentMSBBank[controller] * 0x8000);
newSongInfo.pitchBend = currentPitchBend[controller];
newSongInfo.startAbsoluteTime = absoluteTime;
pendingNoteList.push_back(newSongInfo);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change
{
byte controllerType;
unsigned char curEventVal;
if (statusBit)
{
controllerType = eventVal;
curEventVal = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
int controller = (curEventVal & 0xF);
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (controllerType == 0) // MSB Instrument Bank
{
currentMSBBank[controller] = controllerValue;
}
else if (controllerType == 7) // Volume
{
if (controllerValue != currentVolume[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].volume = controllerValue;
}
}
currentVolume[controller] = controllerValue;
}
else if (controllerType == 10) // Pan
{
if (controllerValue != currentPan[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].pan = controllerValue;
}
}
currentPan[controller] = controllerValue;
}
else if (controllerType == 32) // LSB Instrument Bank
{
currentLSBBank[controller] = controllerValue;
}
else if (controllerType == 91) // Reverb
{
if (controllerValue != currentReverb[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].effect = controllerValue;
}
}
currentReverb[controller] = controllerValue;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument
{
byte instrument;
unsigned char curEventVal;
if (statusBit)
{
instrument = eventVal;
curEventVal = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
if ((eventVal & 0xF) == 9) // Drums in GM
instrument = instrument;
else
instrument = instrument;
int controller = (curEventVal & 0xF);
unsigned short tempInstrument = instrument + (currentLSBBank[controller] * 0x80) + (currentMSBBank[controller] * 0x8000);
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
if (pendingNoteList[p].instrument != tempInstrument)
{
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].instrument = tempInstrument;
}
}
currentInstrument[controller] = instrument;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch
{
unsigned char curEventVal;
byte amount;
if (statusBit)
{
amount = eventVal;
curEventVal = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
// Pitch Bend
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
unsigned char curEventVal;
if (statusBit)
{
valueLSB = eventVal;
curEventVal = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
if (currentPitchBend[controller] != valueMSB)
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller + (portion * 0x10)))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
sngNoteList.push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].pitchBend = valueMSB;
}
}
currentPitchBend[controller] = valueMSB;
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xF0 || eventVal == 0xF7)
{
unsigned char curEventVal = eventVal;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
else
{
if (!unknownsHit)
{
MessageBox(NULL, "Invalid midi character found", "Error", NULL);
unknownsHit = true;
}
}
}
for (int p = 0; p < pendingNoteList.size(); p++)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
sngNoteList.push_back(pendingNoteList[p]);
}
}
trackOffset += numTracks;
delete [] inputMID;
}
// Clear empty notes
for (int x = (sngNoteList.size() - 1); x >= 0; x--)
{
if (sngNoteList[x].startAbsoluteTime == sngNoteList[x].endAbsoluteTime)
sngNoteList.erase(sngNoteList.begin() + x);
}
//FILE* outDebug = fopen("C:\\GoldeneyeStuff\\GE Editor Source\\debug.txt", "w");
FILE* outDebug = NULL;
if (outDebug != NULL)
{
for (int x = 0; x < sngNoteList.size(); x++)
{
fprintf(outDebug, "Start %08X End %08X Instrument %02X Note %02X Volume %02X Pitch Bend %02X Pan %02X Velocity %02X\n", sngNoteList[x].startAbsoluteTime, sngNoteList[x].endAbsoluteTime, sngNoteList[x].instrument, sngNoteList[x].noteNumber, sngNoteList[x].volume, sngNoteList[x].pitchBend, sngNoteList[x].pan, sngNoteList[x].velocity);
}
}
if (outDebug != NULL)
fclose(outDebug);
// Now assign to tracks
for (int x = 0; x < sngNoteList.size(); x++)
{
SngNoteInfoMidiImport tempNoteInfo = sngNoteList[x];
if (tempNoteInfo.endAbsoluteTime > highestAbsoluteTime)
highestAbsoluteTime = tempNoteInfo.endAbsoluteTime;
if (tempNoteInfo.startAbsoluteTime < lowestAbsoluteTime)
lowestAbsoluteTime = tempNoteInfo.startAbsoluteTime;
if(std::find(instruments.begin(), instruments.end(), tempNoteInfo.instrument) == instruments.end())
{
instruments.push_back(tempNoteInfo.instrument);
}
int appliedChannel = -1;
for (int channel = 0; channel < MAXCHANNELS; channel++)
{
bool allowOnChannel = true;
for (int y = 0; y < channels[channel].size(); y++)
{
// Check if is valid
SngNoteInfo matchNoteInfo = channels[channel][y];
// Any overlap
if (IsOverlap(tempNoteInfo.startAbsoluteTime, tempNoteInfo.endAbsoluteTime, matchNoteInfo.startAbsoluteTime, matchNoteInfo.endAbsoluteTime))
{
allowOnChannel = false;
break;
}
}
if (allowOnChannel)
{
appliedChannel = channel;
break;
}
}
if (appliedChannel == -1)
{
MessageBox(NULL, "Error, too many channels for midi", "Error", NULL);
return false;
}
else
{
if ((appliedChannel + 1) > numChannels)
numChannels = (appliedChannel + 1);
channels[appliedChannel].push_back(tempNoteInfo);
}
}
if (numChannels == 0)
{
MessageBox(NULL, "No Channels", "Error", NULL);
return false;
}
if (loop && (loopPoint > highestAbsoluteTime))
{
MessageBox(NULL, "Error, loop point is beyond end of midi", "Error", NULL);
return false;
}
std::sort(tempoPositions.begin(), tempoPositions.end(), timeAndValueSortByTime());
for (int x = 0; x < numChannels; x++)
{
std::sort(channels[x].begin(), channels[x].end(), sngSortByStartTime());
}
return true;
}
bool CMidiParse::MidiToKonami(CString input, CString output, bool loop, unsigned long loopPoint, int& numberTracks, unsigned char separationAmount, unsigned char echoLength)
{
try
{
std::vector<SngNoteInfoMidiImport> sngNoteList;
std::vector<TimeAndValue> tempoPositions;
std::vector<SngNoteInfoMidiImport> channels[MAXCHANNELS];
int numChannels = 0;
std::vector<int> instruments;
int lowestAbsoluteTime = 0x7FFFFFFF;
int highestAbsoluteTime = 0;
if (!MidiToSngList(input, sngNoteList, tempoPositions, channels, numChannels, instruments, lowestAbsoluteTime, highestAbsoluteTime, loop, loopPoint))
return false;
for (int x = 0; x < sngNoteList.size(); x++)
{
if (sngNoteList[x].noteNumber < 0)
sngNoteList[x].noteNumber = 0x00;
else if (sngNoteList[x].noteNumber > 0x47)
sngNoteList[x].noteNumber = 0x47;
}
for (int x = (numChannels - 1); x >= 0; x--)
{
// Remove 0 sized
if (channels[x].size() == 0)
{
channels[x].erase(channels[x].begin() + x);
}
}
int outputPosition = 0;
unsigned char* outputBuffer = new unsigned char[0x100000];
for (int x = 0; x < 0x100000; x++)
outputBuffer[x] = 0x00;
unsigned long trackOffsetsPointersStart = 0x00000000;
for (int x = 0; x < numChannels; x++)
{
// Merge notes with same everything except volume and pitch bend
for (int y = 0; y < channels[x].size(); y++)
{
SngNoteInfoMidiImport tempSongNote = channels[x][y];
if (y == (channels[x].size() - 1))
break;
SngNoteInfoMidiImport tempSongNoteNext = channels[x][y + 1];
if (
(tempSongNote.endAbsoluteTime == tempSongNoteNext.startAbsoluteTime)
&& (tempSongNote.effect == tempSongNoteNext.effect)
&& (tempSongNote.instrument == tempSongNoteNext.instrument)
&& (tempSongNote.noteNumber == tempSongNoteNext.noteNumber)
&& (tempSongNote.pan == tempSongNoteNext.pan)
&& (tempSongNote.velocity == tempSongNoteNext.velocity)
&& (tempSongNote.pitchBend == tempSongNoteNext.pitchBend)
&& (tempSongNote.volume == tempSongNoteNext.volume)
&& (tempSongNote.originalTrack == tempSongNoteNext.originalTrack)
&& (tempSongNote.originalController == tempSongNoteNext.originalController)
&& (tempSongNote.originalNoteUniqueId == tempSongNoteNext.originalNoteUniqueId)
)
{
// Merge
channels[x][y].endAbsoluteTime = tempSongNoteNext.endAbsoluteTime;
channels[x].erase(channels[x].begin() + y + 1);
// Redo Note
y--;
}
}
}
// Skip Track Headers
outputPosition += (numChannels * 0x2);
for (int x = 0; x < numChannels; x++)
{
WriteShortToBuffer(outputBuffer, (x * 2), outputPosition);
bool wroteChannelLoop = false;
unsigned long absoluteTime = 0;
if (loop && !wroteChannelLoop && (loopPoint == 0))
{
outputBuffer[outputPosition++] = 0xEB;
wroteChannelLoop = true;
}
unsigned short currentInstrument = 0xFFFF;
int currentPan = -1;
int currentEffect = -1;
int currentVolume = -1;
unsigned char currentBank = 0x00;
signed char currentCoarseTune = 0x00;
int lastLength = 0xFF;
int lastDuration = 0xFF;
int tempoIndex = 0;
unsigned char currentTempo = 0x00;
bool wroteTempo = false;
for (int y = 0; y < channels[x].size(); y++)
{
if ((x == 0) && (y == 0))
{
if ((separationAmount != 0) || (echoLength != 0))
{
outputBuffer[outputPosition++] = 0xDA;
outputBuffer[outputPosition++] = separationAmount;
outputBuffer[outputPosition++] = echoLength;
}
}
if (tempoPositions.size() > 0)
{
for (int z = tempoIndex; z < tempoPositions.size(); z++)
{
if ((tempoPositions[z].absoluteTime >= absoluteTime) && (tempoPositions[z].absoluteTime <= channels[x][y].startAbsoluteTime))
{
if (loop && !wroteChannelLoop && ((loopPoint >= absoluteTime) && (loopPoint <= tempoPositions[z].absoluteTime)))
{
unsigned long delta = (loopPoint - absoluteTime);
while (delta > 0)
{
outputBuffer[outputPosition++] = 0xF2;
if (delta < 0x80)
{
outputBuffer[outputPosition++] = delta;
absoluteTime += delta;
delta = 0;
}
else
{
outputBuffer[outputPosition++] = 0x7F;
absoluteTime += 0x7F;
delta -= 0x7F;
}
}
outputBuffer[outputPosition++] = 0xEB;
wroteChannelLoop = true;
lastLength = 0xFF;
lastDuration = 0xFF;
currentInstrument = 0xFFFF;
currentPan = -1;
currentEffect = -1;
currentVolume = -1;
outputBuffer[outputPosition++] = 0xF0;
outputBuffer[outputPosition++] = currentBank;
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = currentCoarseTune;
outputBuffer[outputPosition++] = 0xD0;
outputBuffer[outputPosition++] = currentTempo;
}
unsigned long delta = (tempoPositions[z].absoluteTime - absoluteTime);
while (delta > 0)
{
outputBuffer[outputPosition++] = 0xF2;
if (delta < 0x80)
{
outputBuffer[outputPosition++] = delta;
absoluteTime += delta;
delta = 0;
}
else
{
outputBuffer[outputPosition++] = 0x7F;
absoluteTime += 0x7F;
delta -= 0x7F;
}
}
if (!wroteTempo)
{
outputBuffer[outputPosition++] = 0xD0;
outputBuffer[outputPosition++] = tempoPositions[z].value;
currentTempo = tempoPositions[z].value;
wroteTempo = true;
}
else
{
/*outputBuffer[outputPosition++] = 0xD1;
outputBuffer[outputPosition++] = 0x60;
outputBuffer[outputPosition++] = tempoPositions[z].value;*/
outputBuffer[outputPosition++] = 0xD0;
outputBuffer[outputPosition++] = tempoPositions[z].value;
currentTempo = tempoPositions[z].value;
}
tempoIndex = z + 1;
}
else if ((tempoPositions[z].absoluteTime >= absoluteTime) && (tempoPositions[z].absoluteTime >= channels[x][y].startAbsoluteTime) && (tempoPositions[z].absoluteTime < channels[x][y].endAbsoluteTime))
{
// Split note
SngNoteInfoMidiImport tempSongInfoCopy = channels[x][y];
channels[x][y].endAbsoluteTime = tempoPositions[z].absoluteTime;
tempSongInfoCopy.startAbsoluteTime = tempoPositions[z].absoluteTime;
channels[x].insert(channels[x].begin() + y + 1, tempSongInfoCopy);
}
else
{
break;
}
}
}
// Split note out
if (loop && !wroteChannelLoop && ((loopPoint > absoluteTime) && (loopPoint > channels[x][y].startAbsoluteTime) && (loopPoint < channels[x][y].endAbsoluteTime)))
{
SngNoteInfoMidiImport tempSongInfoCopy = channels[x][y];
channels[x][y].endAbsoluteTime = loopPoint;
tempSongInfoCopy.startAbsoluteTime = loopPoint;
channels[x].insert(channels[x].begin() + y + 1, tempSongInfoCopy);
}
if (loop && !wroteChannelLoop && ((loopPoint >= absoluteTime) && (loopPoint <= channels[x][y].startAbsoluteTime)))
{
unsigned long delta = (loopPoint - absoluteTime);
while (delta > 0)
{
outputBuffer[outputPosition++] = 0xF2;
if (delta < 0x80)
{
outputBuffer[outputPosition++] = delta;
absoluteTime += delta;
delta = 0;
}
else
{
outputBuffer[outputPosition++] = 0x7F;
absoluteTime += 0x7F;
delta -= 0x7F;
}
}
outputBuffer[outputPosition++] = 0xEB;
wroteChannelLoop = true;
lastLength = 0xFF;
lastDuration = 0xFF;
currentInstrument = 0xFFFF;
currentPan = -1;
currentEffect = -1;
currentVolume = -1;
outputBuffer[outputPosition++] = 0xF0;
outputBuffer[outputPosition++] = currentBank;
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = currentCoarseTune;
outputBuffer[outputPosition++] = 0xD0;
outputBuffer[outputPosition++] = currentTempo;
}
// Write initial rest
if (channels[x][y].startAbsoluteTime > absoluteTime)
{
// Write rest
unsigned long delta = channels[x][y].startAbsoluteTime - absoluteTime;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0xF2;
if (delta < 0x80)
{
outputBuffer[outputPosition++] = delta;
absoluteTime += delta;
delta = 0;
}
else
{
outputBuffer[outputPosition++] = 0x7F;
absoluteTime += 0x7F;
delta -= 0x7F;
}
}
}
SngNoteInfoMidiImport tempSongInfo = channels[x][y];
bool isDrum = (tempSongInfo.instrument >= 0x8000);
if (tempSongInfo.instrument != currentInstrument)
{
if (!isDrum) // Skip Drums
{
unsigned char newBank = ((tempSongInfo.instrument >> 8) & 0xFF);
if (currentBank != newBank)
{
outputBuffer[outputPosition++] = 0xF0;
outputBuffer[outputPosition++] = newBank;
currentBank = newBank;
}
}
}
if (
(tempSongInfo.instrument != currentInstrument)
&& (tempSongInfo.pan != currentPan)
&& (tempSongInfo.volume != currentVolume)
&& (!isDrum)
)
{
currentVolume = tempSongInfo.volume;
currentInstrument = tempSongInfo.instrument;
currentPan = tempSongInfo.pan;
outputBuffer[outputPosition++] = 0xD4;
outputBuffer[outputPosition++] = currentVolume * 2;
outputBuffer[outputPosition++] = currentInstrument;
outputBuffer[outputPosition++] = currentPan;
}
else if (
(tempSongInfo.instrument != currentInstrument)
&& (tempSongInfo.volume != currentVolume)
&& (!isDrum)
)
{
currentVolume = tempSongInfo.volume;
currentInstrument = tempSongInfo.instrument;
outputBuffer[outputPosition++] = 0xD3;
outputBuffer[outputPosition++] = currentVolume * 2;
outputBuffer[outputPosition++] = currentInstrument;
}
else
{
if (
(tempSongInfo.instrument != currentInstrument)
&& (!isDrum)
)
{
currentInstrument = tempSongInfo.instrument;
outputBuffer[outputPosition++] = 0xD2;
outputBuffer[outputPosition++] = currentInstrument;
}
if (
(tempSongInfo.volume != currentVolume)
)
{
currentVolume = tempSongInfo.volume;
outputBuffer[outputPosition++] = 0xD5;
outputBuffer[outputPosition++] = currentVolume * 2;
}
if (
(tempSongInfo.pan != currentPan)
)
{
currentPan = tempSongInfo.pan;
outputBuffer[outputPosition++] = 0xDD;
outputBuffer[outputPosition++] = currentPan;
}
}
if (tempSongInfo.effect != currentEffect)
{
currentEffect = tempSongInfo.effect;
outputBuffer[outputPosition++] = 0xEF;
outputBuffer[outputPosition++] = tempSongInfo.effect;
}
/*int noteLength = tempSongInfo.endAbsoluteTime - tempSongInfo.startAbsoluteTime;
int noteDuration;
if (y == (channels[x].size() - 1))
noteDuration = highestAbsoluteTime - tempSongInfo.startAbsoluteTime;
else
noteDuration = channels[x][y+1].startAbsoluteTime - tempSongInfo.startAbsoluteTime;
if (noteLength > 0x7F)
{
unsigned char noteNumber = tempSongInfo.noteNumber;
if (isDrum)
{
signed char newCoarseTune = noteNumber - 0x3C;
if (currentCoarseTune != newCoarseTune)
{
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
}
unsigned char drumInstrument = (tempSongInfo.instrument & 0xFF);
if (drumInstrument >= 0x1F)
{
noteNumber = 0x67;
outputBuffer[outputPosition++] = noteNumber;
outputBuffer[outputPosition++] = drumInstrument;
}
else
{
noteNumber = drumInstrument + 0x48;
outputBuffer[outputPosition++] = noteNumber;
}
}
else
{
int writtenNote = noteNumber - currentCoarseTune;
if (writtenNote > 0x47)
{
int newCoarseTune = noteNumber - 0x48;
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
writtenNote = noteNumber - currentCoarseTune;
}
outputBuffer[outputPosition++] = writtenNote;
}
outputBuffer[outputPosition++] = 0x7F;
lastDuration = 0x7F;
outputBuffer[outputPosition++] = 0x00;
lastLength = 0x00;
outputBuffer[outputPosition++] = tempSongInfo.velocity;
noteLength -= 0x7F;
absoluteTime += 0x7F;
noteDuration -= 0x7F;
while (noteLength > 0)
{
outputBuffer[outputPosition++] = 0xF3;
if (noteLength > 0x7F)
{
outputBuffer[outputPosition++] = 0x7F;
outputBuffer[outputPosition++] = 0x00;
noteLength -= 0x7F;
absoluteTime += 0x7F;
noteDuration -= 0x7F;
}
else
{
if (noteDuration > 0x7F)
{
outputBuffer[outputPosition++] = 0x7F;
outputBuffer[outputPosition++] = noteLength;
absoluteTime += 0x7F;
noteDuration -= 0x7F;
}
else
{
outputBuffer[outputPosition++] = noteDuration;
outputBuffer[outputPosition++] = noteLength;
absoluteTime += noteDuration;
noteDuration = 0;
}
noteLength = 0;
}
}
}
else
{
if (noteDuration > 0x7F)
noteDuration = 0x7F;
unsigned char noteNumber = tempSongInfo.noteNumber;
if (isDrum)
{
signed char newCoarseTune = noteNumber - 0x3C;
if (currentCoarseTune != newCoarseTune)
{
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
}
unsigned char drumInstrument = (tempSongInfo.instrument & 0xFF);
if (drumInstrument >= 0x1F)
{
noteNumber = 0x67;
if (lastDuration == noteDuration)
{
outputBuffer[outputPosition++] = noteNumber + 0x68;
outputBuffer[outputPosition++] = drumInstrument;
}
else
{
outputBuffer[outputPosition++] = noteNumber;
outputBuffer[outputPosition++] = drumInstrument;
outputBuffer[outputPosition++] = noteDuration;
lastDuration = noteDuration;
}
outputBuffer[outputPosition++] = drumInstrument;
}
else
{
noteNumber = drumInstrument + 0x48;
if (lastDuration == noteDuration)
{
outputBuffer[outputPosition++] = noteNumber + 0x68;
}
else
{
outputBuffer[outputPosition++] = noteNumber;
outputBuffer[outputPosition++] = noteDuration;
lastDuration = noteDuration;
}
}
}
else
{
int writtenNote = noteNumber - currentCoarseTune;
if (writtenNote > 0x47)
{
int newCoarseTune = noteNumber - 0x47;
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
writtenNote = noteNumber - currentCoarseTune;
}
if (lastDuration == noteDuration)
{
outputBuffer[outputPosition++] = writtenNote + 0x68;
}
else
{
outputBuffer[outputPosition++] = writtenNote;
outputBuffer[outputPosition++] = noteDuration;
lastDuration = noteDuration;
}
}
if (lastLength == noteLength)
{
outputBuffer[outputPosition++] = tempSongInfo.velocity + 0x80;
}
else
{
outputBuffer[outputPosition++] = noteLength;
outputBuffer[outputPosition++] = tempSongInfo.velocity;
}
lastLength = noteLength;
absoluteTime += noteDuration;
}*/
int noteDuration = tempSongInfo.endAbsoluteTime - tempSongInfo.startAbsoluteTime;
if (noteDuration > 0x7F)
{
unsigned char noteNumber = tempSongInfo.noteNumber;
if (isDrum)
{
signed char newCoarseTune = noteNumber - 0x3C;
if (currentCoarseTune != newCoarseTune)
{
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
}
unsigned char drumInstrument = (tempSongInfo.instrument & 0xFF);
if (drumInstrument >= 0x1F)
{
noteNumber = 0x67;
outputBuffer[outputPosition++] = noteNumber;
outputBuffer[outputPosition++] = drumInstrument;
}
else
{
noteNumber = drumInstrument + 0x48;
outputBuffer[outputPosition++] = noteNumber;
}
}
else
{
int writtenNote = noteNumber - currentCoarseTune;
if (writtenNote > 0x47)
{
int newCoarseTune = noteNumber - 0x48;
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
writtenNote = noteNumber - currentCoarseTune;
}
outputBuffer[outputPosition++] = writtenNote;
}
outputBuffer[outputPosition++] = 0x7F;
lastDuration = 0x7F;
outputBuffer[outputPosition++] = 0x00;
lastLength = 0x00;
outputBuffer[outputPosition++] = tempSongInfo.velocity;
absoluteTime += 0x7F;
noteDuration -= 0x7F;
while (noteDuration > 0)
{
outputBuffer[outputPosition++] = 0xF3;
if (noteDuration > 0x7F)
{
outputBuffer[outputPosition++] = 0x7F;
outputBuffer[outputPosition++] = 0x00;
absoluteTime += 0x7F;
noteDuration -= 0x7F;
}
else
{
outputBuffer[outputPosition++] = noteDuration;
outputBuffer[outputPosition++] = 0x7F;
absoluteTime += noteDuration;
noteDuration = 0;
}
}
}
else
{
unsigned char noteNumber = tempSongInfo.noteNumber;
if (isDrum)
{
signed char newCoarseTune = noteNumber - 0x3C;
if (currentCoarseTune != newCoarseTune)
{
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
}
unsigned char drumInstrument = (tempSongInfo.instrument & 0xFF);
if (drumInstrument >= 0x1F)
{
noteNumber = 0x67;
if (lastDuration == noteDuration)
{
outputBuffer[outputPosition++] = noteNumber + 0x68;
outputBuffer[outputPosition++] = drumInstrument;
}
else
{
outputBuffer[outputPosition++] = noteNumber;
outputBuffer[outputPosition++] = drumInstrument;
outputBuffer[outputPosition++] = noteDuration;
lastDuration = noteDuration;
}
outputBuffer[outputPosition++] = drumInstrument;
}
else
{
noteNumber = drumInstrument + 0x48;
if (lastDuration == noteDuration)
{
outputBuffer[outputPosition++] = noteNumber + 0x68;
}
else
{
outputBuffer[outputPosition++] = noteNumber;
outputBuffer[outputPosition++] = noteDuration;
lastDuration = noteDuration;
}
}
}
else
{
int writtenNote = noteNumber - currentCoarseTune;
if (writtenNote > 0x47)
{
int newCoarseTune = noteNumber - 0x47;
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = newCoarseTune;
currentCoarseTune = newCoarseTune;
writtenNote = noteNumber - currentCoarseTune;
}
if (lastDuration == noteDuration)
{
outputBuffer[outputPosition++] = writtenNote + 0x68;
}
else
{
outputBuffer[outputPosition++] = writtenNote;
outputBuffer[outputPosition++] = noteDuration;
lastDuration = noteDuration;
}
}
if (lastLength == 0x7F)
{
outputBuffer[outputPosition++] = tempSongInfo.velocity + 0x80;
}
else
{
outputBuffer[outputPosition++] = 0x7F;
outputBuffer[outputPosition++] = tempSongInfo.velocity;
}
lastLength = 0x7F;
absoluteTime += noteDuration;
}
if (
(tempSongInfo.pitchBend != 0x40)
)
{
if (tempSongInfo.pitchBend >= 0x7F)
{
if (tempSongInfo.noteNumber < 0x46)
{
outputBuffer[outputPosition++] = 0xE4;
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x04;
outputBuffer[outputPosition++] = tempSongInfo.noteNumber + 2;
}
}
else if (tempSongInfo.pitchBend >= 0x60)
{
if (tempSongInfo.noteNumber < 0x47)
{
outputBuffer[outputPosition++] = 0xE4;
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x04;
outputBuffer[outputPosition++] = tempSongInfo.noteNumber + 1;
}
}
else if (tempSongInfo.pitchBend <= 0x00)
{
if (tempSongInfo.noteNumber > 1)
{
outputBuffer[outputPosition++] = 0xE4;
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x04;
outputBuffer[outputPosition++] = tempSongInfo.noteNumber - 2;
}
}
else if (tempSongInfo.pitchBend <= 0x20)
{
if (tempSongInfo.noteNumber > 0)
{
outputBuffer[outputPosition++] = 0xE4;
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x04;
outputBuffer[outputPosition++] = tempSongInfo.noteNumber - 1;
}
}
}
}
if (loop && (!wroteChannelLoop))
{
unsigned long delta = (loopPoint - absoluteTime);
while (delta > 0)
{
outputBuffer[outputPosition++] = 0xF2;
if (delta < 0x80)
{
outputBuffer[outputPosition++] = delta;
absoluteTime += delta;
delta = 0;
}
else
{
outputBuffer[outputPosition++] = 0x7F;
absoluteTime += 0x7F;
delta -= 0x7F;
}
}
outputBuffer[outputPosition++] = 0xEB;
wroteChannelLoop = true;
lastLength = 0xFF;
lastDuration = 0xFF;
currentInstrument = 0xFFFF;
currentPan = -1;
currentEffect = -1;
currentVolume = -1;
outputBuffer[outputPosition++] = 0xF0;
outputBuffer[outputPosition++] = currentBank;
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = currentCoarseTune;
outputBuffer[outputPosition++] = 0xD0;
outputBuffer[outputPosition++] = currentTempo;
}
unsigned long delta = (highestAbsoluteTime - absoluteTime);
while (delta > 0)
{
outputBuffer[outputPosition++] = 0xF2;
if (delta < 0x80)
{
outputBuffer[outputPosition++] = delta;
absoluteTime += delta;
delta = 0;
}
else
{
outputBuffer[outputPosition++] = 0x7F;
absoluteTime += 0x7F;
delta -= 0x7F;
}
}
if (wroteChannelLoop)
{
outputBuffer[outputPosition++] = 0xEC;
}
outputBuffer[outputPosition++] = 0xFF;
}
numberTracks = numChannels;
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] outputBuffer;
MessageBox(NULL, "Error outputting file", "Error", NULL);
return false;
}
fwrite(outputBuffer, 1, outputPosition, outFile);
delete [] outputBuffer;
fclose(outFile);
}
catch (...)
{
MessageBox(NULL, "Error converting", "Error", NULL);
return false;
}
return true;
}
bool CMidiParse::MidiToSng(CString input, CString output, bool loop, unsigned long loopPoint, SngStyle sngStyle, unsigned char masterTrackEffect)
{
try
{
std::vector<SngNoteInfoMidiImport> sngNoteList;
std::vector<TimeAndValue> tempoPositions;
std::vector<SngNoteInfoMidiImport> channels[MAXCHANNELS];
int numChannels = 0;
std::vector<int> instruments;
int lowestAbsoluteTime = 0x7FFFFFFF;
int highestAbsoluteTime = 0;
if (!MidiToSngList(input, sngNoteList, tempoPositions, channels, numChannels, instruments, lowestAbsoluteTime, highestAbsoluteTime, loop, loopPoint))
return false;
std::vector<TimeAndValue> volumeData[MAXCHANNELS];
std::vector<TimeAndValue> pitchBendData[MAXCHANNELS];
for (int x = 0; x < numChannels; x++)
{
unsigned char currentVolume = 0x7F;
unsigned char currentPitchBend = 0x40;
for (int y = 0; y < channels[x].size(); y++)
{
SngNoteInfoMidiImport tempNoteInfo = channels[x][y];
if (tempNoteInfo.volume != currentVolume)
{
if ((volumeData[x].size() == 0) || (volumeData[x].back().absoluteTime < tempNoteInfo.startAbsoluteTime))
{
volumeData[x].push_back(TimeAndValue(tempNoteInfo.startAbsoluteTime, tempNoteInfo.volume));
}
else
{
volumeData[x][volumeData[x].size()-1] = TimeAndValue(tempNoteInfo.startAbsoluteTime, tempNoteInfo.volume);
}
currentVolume = tempNoteInfo.volume;
}
if (tempNoteInfo.pitchBend != currentPitchBend)
{
if ((pitchBendData[x].size() == 0) || (pitchBendData[x].back().absoluteTime < tempNoteInfo.startAbsoluteTime))
{
pitchBendData[x].push_back(TimeAndValue(tempNoteInfo.startAbsoluteTime, tempNoteInfo.pitchBend));
}
else
{
pitchBendData[x][pitchBendData[x].size()-1] = TimeAndValue(tempNoteInfo.startAbsoluteTime, tempNoteInfo.pitchBend);
}
currentPitchBend = tempNoteInfo.pitchBend;
}
}
}
int outputPosition = 0;
unsigned char* outputBuffer = new unsigned char[0x100000];
for (int x = 0; x < 0x100000; x++)
outputBuffer[x] = 0x00;
unsigned long trackOffsetsPointersStart = 0x00000000;
unsigned long volumePointersStart = 0x00000000;
unsigned long pitchBendPointersStart = 0x00000000;
if (sngStyle == SngStyle::Normal)
{
WriteLongToBuffer(outputBuffer, outputPosition, 0x00000215);
outputPosition += 4;
WriteLongToBuffer(outputBuffer, outputPosition, numChannels);
outputPosition += 4;
WriteLongToBuffer(outputBuffer, outputPosition, instruments.size());
outputPosition += 4;
trackOffsetsPointersStart = 0x00000038;
WriteLongToBuffer(outputBuffer, outputPosition, trackOffsetsPointersStart);
outputPosition += 4;
outputPosition = 0x38;
// Track Offsets, 0x00000038
outputPosition += (numChannels * 0x4);
// Write Volume tracks
WriteLongToBuffer(outputBuffer, 0x10, outputPosition);
volumePointersStart = outputPosition;
outputPosition += (numChannels * 0x4);
// Write PitchBend tracks
WriteLongToBuffer(outputBuffer, 0x14, outputPosition);
pitchBendPointersStart = outputPosition;
outputPosition += (numChannels * 0x4);
// Write Instruments
WriteLongToBuffer(outputBuffer, 0x20, outputPosition);
unsigned long instrumentsPointersStart = outputPosition;
for (int x = 0; x < instruments.size(); x++)
{
WriteShortToBuffer(outputBuffer, outputPosition, instruments[x]);
outputPosition += 2;
}
// Skip Drums
WriteLongToBuffer(outputBuffer, 0x1C, outputPosition);
// Skip ADSR
WriteLongToBuffer(outputBuffer, 0x18, outputPosition);
// ADSR Rate
outputBuffer[outputPosition++] = 0x01;
// ADSR Start Level
outputBuffer[outputPosition++] = 0x7F;
// ADSR Attack Rate
outputBuffer[outputPosition++] = 0x01;
// ADSR Peak Level
outputBuffer[outputPosition++] = 0x7F;
// ADSR Decay Rate
outputBuffer[outputPosition++] = 0x20;
// ADSR Sustain Level
outputBuffer[outputPosition++] = 0x7F;
// ADSR Release Rate
outputBuffer[outputPosition++] = 0x03;
}
else if (sngStyle == SngStyle::Old)
{
if ((numChannels % 8) != 0)
numChannels = numChannels + (8 - (numChannels % 8));
WriteLongToBuffer(outputBuffer, 0x0, numChannels);
outputPosition += 4;
// Track Offset
trackOffsetsPointersStart = 0x00000018;
WriteLongToBuffer(outputBuffer, 0x4, trackOffsetsPointersStart);
outputPosition = 0x18;
outputPosition += (numChannels * 0x4);
// Write Volume tracks
WriteLongToBuffer(outputBuffer, 0x8, outputPosition);
volumePointersStart = outputPosition;
outputPosition += (numChannels * 0x4);
// Write PitchBend tracks
WriteLongToBuffer(outputBuffer, 0xC, outputPosition);
pitchBendPointersStart = outputPosition;
outputPosition += (numChannels * 0x4);
// Skip Drums
WriteLongToBuffer(outputBuffer, 0x14, outputPosition);
// Skip ADSR
WriteLongToBuffer(outputBuffer, 0x10, outputPosition);
// ADSR Rate
outputBuffer[outputPosition++] = 0x01;
// ADSR Start Level
outputBuffer[outputPosition++] = 0x7F;
// ADSR Attack Rate
outputBuffer[outputPosition++] = 0x01;
// ADSR Peak Level
outputBuffer[outputPosition++] = 0x7F;
// ADSR Decay Rate
outputBuffer[outputPosition++] = 0x20;
// ADSR Sustain Level
outputBuffer[outputPosition++] = 0x7F;
// ADSR Release Rate
outputBuffer[outputPosition++] = 0x03;
}
else if (sngStyle == SngStyle::OldBfx)
{
WriteLongToBuffer(outputBuffer, 0x0, numChannels);
WriteLongToBuffer(outputBuffer, 0x4, 0x00000000);
// Write Volume tracks
volumePointersStart = 0x00000010;
WriteLongToBuffer(outputBuffer, 0x8, volumePointersStart);
outputPosition = 0x10;
for (int x = 0; x < numChannels; x++)
{
if (x == 0)
WriteLongToBuffer(outputBuffer, 0x4, 0x00000000);
else
WriteLongToBuffer(outputBuffer, 0x4, 0x00000064);
outputPosition += 4;
}
// Track Offset
trackOffsetsPointersStart = outputPosition;
WriteLongToBuffer(outputBuffer, 0xC, trackOffsetsPointersStart);
outputPosition += (numChannels * 0x4);
}
else if (sngStyle == SngStyle::OldBfx)
{
WriteLongToBuffer(outputBuffer, 0x0, numChannels);
WriteLongToBuffer(outputBuffer, 0x4, numChannels);
WriteLongToBuffer(outputBuffer, 0x8, numChannels);
WriteLongToBuffer(outputBuffer, 0xC, 0x00000000);
WriteLongToBuffer(outputBuffer, 0x10, 0x00000000);
outputPosition = 0x18;
trackOffsetsPointersStart = outputPosition;
outputPosition += 4;
for (int x = 0; x < numChannels; x++)
{
WriteLongToBuffer(outputBuffer, 0x4, 0x00000064);
outputPosition += 8;
}
}
else if (sngStyle == SngStyle::PtrBfx)
{
return false;
}
// Data starts now
unsigned long absoluteTime = 0;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
for (int x = 0; x < numChannels; x++)
{
unsigned long volumeDataOffset = outputPosition;
if (volumeData[x].size() == 0)
WriteLongToBuffer(outputBuffer, (volumePointersStart + (x * 0x4)), 0x00000000);
else
WriteLongToBuffer(outputBuffer, (volumePointersStart + (x * 0x4)), volumeDataOffset);
if (volumeData[x].size() > 0)
{
if (volumeData[x][0].absoluteTime > 0)
{
// Write initial length
int totalVolumeLength = volumeData[x][0].absoluteTime;
while (totalVolumeLength > 0)
{
// Default
outputBuffer[outputPosition] = 0x7F;
int volumeLength = totalVolumeLength;
if (volumeLength > 0x8000)
volumeLength = 0x8000;
if (volumeLength == 1)
{
outputPosition++;
}
else
{
outputBuffer[outputPosition] |= 0x80;
outputPosition++;
WriteSngVariableLength(outputBuffer, outputPosition, (volumeLength - 2));
}
totalVolumeLength -= volumeLength;
}
}
}
for (int y = 0; y < volumeData[x].size(); y++)
{
outputBuffer[outputPosition] = volumeData[x][y].value;
int totalVolumeLength;
if (y != (volumeData[x].size()-1))
{
totalVolumeLength = volumeData[x][y+1].absoluteTime - volumeData[x][y].absoluteTime;
}
else
{
totalVolumeLength = highestAbsoluteTime;
}
while (totalVolumeLength > 0)
{
int volumeLength = totalVolumeLength;
if (volumeLength > 0x8000)
volumeLength = 0x8000;
if (volumeLength == 1)
{
outputPosition++;
}
else
{
// Stored 0 value = 2, etc
outputBuffer[outputPosition] |= 0x80;
outputPosition++;
WriteSngVariableLength(outputBuffer, outputPosition, (volumeLength - 2));
}
totalVolumeLength -= volumeLength;
}
}
}
absoluteTime = 0;
for (int x = 0; x < numChannels; x++)
{
unsigned long pitchBendDataOffset = outputPosition;
if (pitchBendData[x].size() == 0)
WriteLongToBuffer(outputBuffer, (pitchBendPointersStart + (x * 0x4)), 0x00000000);
else
WriteLongToBuffer(outputBuffer, (pitchBendPointersStart + (x * 0x4)), pitchBendDataOffset);
if (pitchBendData[x].size() > 0)
{
if (pitchBendData[x][0].absoluteTime > 0)
{
// Write initial length
int totalPitchBendLength = pitchBendData[x][0].absoluteTime;
while (totalPitchBendLength > 0)
{
// Default
outputBuffer[outputPosition] = 0x40;
int pitchBendLength = totalPitchBendLength;
if (pitchBendLength > 0x8000)
pitchBendLength = 0x8000;
if (pitchBendLength == 1)
{
outputPosition++;
}
else
{
outputBuffer[outputPosition] |= 0x80;
outputPosition++;
WriteSngVariableLength(outputBuffer, outputPosition, (pitchBendLength - 2));
}
totalPitchBendLength -= pitchBendLength;
}
}
}
for (int y = 0; y < pitchBendData[x].size(); y++)
{
outputBuffer[outputPosition] = pitchBendData[x][y].value;
int totalPitchBendLength;
if (y != (pitchBendData[x].size()-1))
{
totalPitchBendLength = pitchBendData[x][y+1].absoluteTime - pitchBendData[x][y].absoluteTime;
}
else
{
totalPitchBendLength = highestAbsoluteTime;
}
while (totalPitchBendLength > 0)
{
int pitchBendLength = totalPitchBendLength;
if (pitchBendLength > 0x8000)
pitchBendLength = 0x8000;
if (pitchBendLength == 1)
{
outputPosition++;
}
else
{
outputBuffer[outputPosition] |= 0x80;
outputPosition++;
WriteSngVariableLength(outputBuffer, outputPosition, (pitchBendLength - 2));
}
totalPitchBendLength -= pitchBendLength;
}
}
}
}
if (sngStyle == SngStyle::Normal)
{
// Master Track Pointer
WriteLongToBuffer(outputBuffer, 0x24, outputPosition);
unsigned long masterTrackIndex = outputPosition;
bool wroteMasterLoop = false;
bool sharedMasterVelocity = false;
unsigned long currentTempo = 0xFFFFFFFF;
int countMasterTempoChanges = 0;
for (int x = 0; x < tempoPositions.size(); x++)
{
if (currentTempo == tempoPositions[x].value)
continue;
countMasterTempoChanges++;
currentTempo = tempoPositions[x].value;
}
currentTempo = 0xFFFFFFFF;
absoluteTime = 0;
if (masterTrackEffect != 0x00)
{
outputBuffer[outputPosition++] = 0xAA;
outputBuffer[outputPosition++] = masterTrackEffect;
}
// Write Master Track
for (int x = 0; x < tempoPositions.size(); x++)
{
if (currentTempo == tempoPositions[x].value)
continue;
if (loop && !wroteMasterLoop && ((loopPoint >= absoluteTime) && (loopPoint <= tempoPositions[x].absoluteTime)))
{
unsigned long delta = (loopPoint - absoluteTime);
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if (!sharedMasterVelocity)
{
outputBuffer[outputPosition] = 0x00;
if (countMasterTempoChanges > 3)
{
outputBuffer[outputPosition] |= 0x80;
sharedMasterVelocity = true;
}
outputPosition++;
}
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
sharedMasterVelocity = false;
outputBuffer[outputPosition++] = 0x99;
wroteMasterLoop = true;
}
unsigned long delta = (tempoPositions[x].absoluteTime - absoluteTime);
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if (!sharedMasterVelocity)
{
outputBuffer[outputPosition] = 0x00;
if (countMasterTempoChanges > 3)
{
outputBuffer[outputPosition] |= 0x80;
sharedMasterVelocity = true;
}
outputPosition++;
}
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
outputBuffer[outputPosition++] = 0x85;
outputBuffer[outputPosition++] = tempoPositions[x].value;
currentTempo = tempoPositions[x].value;
}
if (loop && (!wroteMasterLoop))
{
unsigned long delta = (loopPoint - absoluteTime);
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if (!sharedMasterVelocity)
{
outputBuffer[outputPosition] = 0x00;
if (countMasterTempoChanges > 3)
{
outputBuffer[outputPosition] |= 0x80;
sharedMasterVelocity = true;
}
outputPosition++;
}
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
sharedMasterVelocity = false;
outputBuffer[outputPosition++] = 0x99;
wroteMasterLoop = true;
}
unsigned long delta = (highestAbsoluteTime - absoluteTime);
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if (!sharedMasterVelocity)
{
outputBuffer[outputPosition] = 0x00;
if (countMasterTempoChanges > 3)
{
outputBuffer[outputPosition] |= 0x80;
sharedMasterVelocity = true;
}
outputPosition++;
}
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
// Seems like even if not turned on, turned off
sharedMasterVelocity = false;
outputBuffer[outputPosition++] = 0x99;
if (wroteMasterLoop)
{
outputBuffer[outputPosition++] = 0x96;
}
else
{
outputBuffer[outputPosition++] = 0x80;
}
}
for (int x = 0; x < numChannels; x++)
{
// Merge notes with same everything except volume and pitch bend
for (int y = 0; y < channels[x].size(); y++)
{
SngNoteInfoMidiImport tempSongNote = channels[x][y];
if (y == (channels[x].size() - 1))
break;
SngNoteInfoMidiImport tempSongNoteNext = channels[x][y + 1];
if (
(tempSongNote.endAbsoluteTime == tempSongNoteNext.startAbsoluteTime)
&& (tempSongNote.effect == tempSongNoteNext.effect)
&& (tempSongNote.instrument == tempSongNoteNext.instrument)
&& (tempSongNote.noteNumber == tempSongNoteNext.noteNumber)
&& (tempSongNote.pan == tempSongNoteNext.pan)
&& (tempSongNote.velocity == tempSongNoteNext.velocity)
&& (tempSongNote.originalTrack == tempSongNoteNext.originalTrack)
&& (tempSongNote.originalController == tempSongNoteNext.originalController)
&& (tempSongNote.originalNoteUniqueId == tempSongNoteNext.originalNoteUniqueId)
)
{
// Merge
channels[x][y].endAbsoluteTime = tempSongNoteNext.endAbsoluteTime;
channels[x].erase(channels[x].begin() + y + 1);
// Redo Note
y--;
}
}
}
unsigned long currentOldSngTempo = 0xFFFFFFFF;
for (int x = 0; x < numChannels; x++)
{
if (sngStyle == SngStyle::Old)
{
if (channels[x].size() == 0)
{
WriteLongToBuffer(outputBuffer, trackOffsetsPointersStart + (x * 4), 0x00000000);
continue;
}
if (x == 0)
{
if (masterTrackEffect != 0x00)
{
outputBuffer[outputPosition++] = 0xAA;
outputBuffer[outputPosition++] = masterTrackEffect;
}
}
}
if (sngStyle == SngStyle::Bfx)
{
WriteLongToBuffer(outputBuffer, trackOffsetsPointersStart + (x * 8), outputPosition);
}
else if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old) || (sngStyle == SngStyle::OldBfx))
{
WriteLongToBuffer(outputBuffer, trackOffsetsPointersStart + (x * 4), outputPosition);
}
absoluteTime = 0;
if (channels[x].size() == 0)
{
bool sharedChannelVelocity = false;
if ((sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::Bfx))
sharedChannelVelocity = true;
if (loop)
{
if (loopPoint == 0)
{
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
sharedChannelVelocity = false;
outputBuffer[outputPosition++] = 0x99;
}
}
else
{
unsigned long delta = loopPoint;
absoluteTime += delta;
while (delta > 0)
{
if (sngStyle == SngStyle::Old)
{
if (!sharedChannelVelocity)
{
sharedChannelVelocity = true;
outputBuffer[outputPosition++] = 0x9B;
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x9A;
}
}
outputBuffer[outputPosition++] = 0x60;
if (sngStyle == SngStyle::Normal)
{
if (!sharedChannelVelocity)
{
sharedChannelVelocity = true;
outputBuffer[outputPosition++] = 0x80;
}
}
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
sharedChannelVelocity = false;
outputBuffer[outputPosition++] = 0x99;
}
}
unsigned long delta = (highestAbsoluteTime - absoluteTime);
absoluteTime += delta;
while (delta > 0)
{
if (sngStyle == SngStyle::Old)
{
if (!sharedChannelVelocity)
{
sharedChannelVelocity = true;
outputBuffer[outputPosition++] = 0x9B;
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x9A;
}
}
outputBuffer[outputPosition++] = 0x60;
if (!sharedChannelVelocity)
{
if (sngStyle == SngStyle::Normal)
{
outputBuffer[outputPosition++] = 0x80;
sharedChannelVelocity = true;
}
}
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
if (sharedChannelVelocity)
{
outputBuffer[outputPosition++] = 0x99;
sharedChannelVelocity = false;
}
}
outputBuffer[outputPosition++] = 0x96;
}
else
{
outputBuffer[outputPosition++] = 0x80;
}
}
else
{
bool sharedChannelVelocity = false;
unsigned char currentVelocity = 0x7F;
bool setLength = false;
int currentLength = 0;
bool wroteChannelLoop = false;
if (loop && !wroteChannelLoop && (loopPoint == 0))
{
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
sharedChannelVelocity = false;
outputBuffer[outputPosition++] = 0x99;
}
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
wroteChannelLoop = true;
}
// Not sure what this does
outputBuffer[outputPosition++] = 0x82;
outputBuffer[outputPosition++] = 0x00;
// Set Release Time Back to Full 01
outputBuffer[outputPosition++] = 0x87;
outputBuffer[outputPosition++] = 0x01;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
// Reenable velocity on notes
sharedChannelVelocity = false;
outputBuffer[outputPosition++] = 0x99;
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
// Default Effect 00
outputBuffer[outputPosition++] = 0xA2;
outputBuffer[outputPosition++] = 0x00;
// Transpose 00
outputBuffer[outputPosition++] = 0x8D;
outputBuffer[outputPosition++] = 0x00;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
outputBuffer[outputPosition++] = 0x90;
outputBuffer[outputPosition++] = 0x00;
}
else if ((sngStyle == SngStyle::Bfx) || (sngStyle == SngStyle::OldBfx))
{
outputBuffer[outputPosition++] = 0x84;
outputBuffer[outputPosition++] = 0x01;
outputBuffer[outputPosition++] = 0x7F;
outputBuffer[outputPosition++] = 0x01;
outputBuffer[outputPosition++] = 0x7F;
outputBuffer[outputPosition++] = 0x01;
outputBuffer[outputPosition++] = 0x7F;
outputBuffer[outputPosition++] = 0x10;
}
unsigned short currentInstrument = 0xFFFF;
unsigned char currentPan = 0x40;
unsigned char currentEffect = 0xFF;
int tempoIndex = 0;
for (int y = 0; y < channels[x].size(); y++)
{
if (sngStyle == SngStyle::Old)
{
if (x == 0)
{
if (tempoPositions.size() > 0)
{
for (int z = tempoIndex; z < tempoPositions.size(); z++)
{
if ((tempoPositions[z].absoluteTime >= absoluteTime) && (tempoPositions[z].absoluteTime <= channels[x][y].startAbsoluteTime))
{
if (loop && !wroteChannelLoop && ((loopPoint >= absoluteTime) && (loopPoint <= tempoPositions[z].absoluteTime)))
{
unsigned long delta = (loopPoint - absoluteTime);
if (setLength)
{
if (delta != currentLength)
{
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
}
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
// Don't try and share, but if is, is ok
if (!sharedChannelVelocity)
{
outputBuffer[outputPosition++] = 0x00;
currentVelocity = 0x00;
}
}
if (!setLength)
{
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
else
{
delta = 0;
}
}
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
wroteChannelLoop = true;
}
unsigned long delta = (tempoPositions[z].absoluteTime - absoluteTime);
if (setLength)
{
if (delta != currentLength)
{
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
}
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
// Don't try and share, but if is, is ok
if (!sharedChannelVelocity)
{
outputBuffer[outputPosition++] = 0x00;
currentVelocity = 0x00;
}
}
if (!setLength)
{
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
else
{
delta = 0;
}
}
outputBuffer[outputPosition++] = 0x85;
outputBuffer[outputPosition++] = tempoPositions[z].value;
currentOldSngTempo = tempoPositions[z].value;
tempoIndex = z + 1;
}
else if ((tempoPositions[z].absoluteTime >= absoluteTime) && (tempoPositions[z].absoluteTime >= channels[x][y].startAbsoluteTime) && (tempoPositions[z].absoluteTime < channels[x][y].endAbsoluteTime))
{
// Split note
SngNoteInfoMidiImport tempSongInfoCopy = channels[x][y];
channels[x][y].endAbsoluteTime = tempoPositions[z].absoluteTime;
tempSongInfoCopy.startAbsoluteTime = tempoPositions[z].absoluteTime;
channels[x].insert(channels[x].begin() + y + 1, tempSongInfoCopy);
}
else
{
break;
}
}
}
}
}
// Split note out
if (loop && !wroteChannelLoop && ((loopPoint > absoluteTime) && (loopPoint > channels[x][y].startAbsoluteTime) && (loopPoint < channels[x][y].endAbsoluteTime)))
{
SngNoteInfoMidiImport tempSongInfoCopy = channels[x][y];
channels[x][y].endAbsoluteTime = loopPoint;
tempSongInfoCopy.startAbsoluteTime = loopPoint;
channels[x].insert(channels[x].begin() + y + 1, tempSongInfoCopy);
}
if (loop && !wroteChannelLoop && ((loopPoint >= absoluteTime) && (loopPoint <= channels[x][y].startAbsoluteTime)))
{
unsigned long delta = (loopPoint - absoluteTime);
if (setLength)
{
if (delta != currentLength)
{
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
}
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
// Don't try and share, but if is, is ok
if (!sharedChannelVelocity)
{
outputBuffer[outputPosition++] = 0x00;
currentVelocity = 0x00;
}
}
if (!setLength)
{
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
else
{
delta = 0;
}
}
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
sharedChannelVelocity = false;
outputBuffer[outputPosition++] = 0x99;
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
wroteChannelLoop = true;
}
// Write initial rest
if (channels[x][y].startAbsoluteTime > absoluteTime)
{
int restLength = channels[x][y].startAbsoluteTime - absoluteTime;
if (setLength)
{
if (restLength != currentLength)
{
int countSameLength = 1;
unsigned long tempAbsoluteTime = absoluteTime;
for (int z = y; z < channels[x].size(); z++)
{
if (
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == restLength)
||
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == 0)
)
{
}
else
break;
tempAbsoluteTime = channels[x][z].startAbsoluteTime;
if ((channels[x][z].endAbsoluteTime - tempAbsoluteTime) == restLength)
countSameLength++;
else
break;
tempAbsoluteTime = channels[x][z].endAbsoluteTime;
}
if ((countSameLength >= 3) && (restLength <= 0x7FFE))
{
outputBuffer[outputPosition++] = 0x8B;
WriteSngVariableLength(outputBuffer, outputPosition, restLength);
setLength = true;
currentLength = restLength;
}
else
{
if (sngStyle == SngStyle::Normal)
{
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
setLength = false;
}
}
}
else
{
int countSameLength = 1;
unsigned long tempAbsoluteTime = absoluteTime;
for (int z = y; z < channels[x].size(); z++)
{
if (
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == restLength)
||
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == 0)
)
{
}
else
break;
tempAbsoluteTime = channels[x][z].startAbsoluteTime;
if ((channels[x][z].endAbsoluteTime - tempAbsoluteTime) == restLength)
countSameLength++;
else
break;
tempAbsoluteTime = channels[x][z].endAbsoluteTime;
}
if ((countSameLength >= 3) && (restLength <= 0x7FFE))
{
outputBuffer[outputPosition++] = 0x8B;
WriteSngVariableLength(outputBuffer, outputPosition, restLength);
setLength = true;
currentLength = restLength;
}
}
int countSameVelocity = 0;
for (int z = (y + 1); z < channels[x].size(); z++)
{
if ((channels[x][y].velocity) == channels[x][z].velocity)
countSameVelocity++;
else
break;
}
if (!sharedChannelVelocity)
{
if (sngStyle == SngStyle::Old)
{
if (countSameVelocity >= 3)
{
sharedChannelVelocity = true;
currentVelocity = channels[x][y].velocity;
outputBuffer[outputPosition++] = 0x9B;
outputBuffer[outputPosition++] = currentVelocity;
outputBuffer[outputPosition++] = 0x9A;
}
}
}
// Write rest
outputBuffer[outputPosition++] = 0x60;
if (!sharedChannelVelocity)
{
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
// Should be same as previous velocity, the rest velocity
outputBuffer[outputPosition] = channels[x][y].velocity;
if (sngStyle == SngStyle::Normal)
{
if (countSameVelocity >= 3)
{
sharedChannelVelocity = true;
currentVelocity = channels[x][y].velocity;
outputBuffer[outputPosition] |= 0x80;
}
}
outputPosition++;
}
}
if (!setLength)
{
WriteSngVariableLength(outputBuffer, outputPosition, restLength);
}
absoluteTime += restLength;
}
SngNoteInfoMidiImport tempSongInfo = channels[x][y];
if (tempSongInfo.instrument != currentInstrument)
{
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Bfx))
{
for (int z = 0; z < instruments.size(); z++)
{
if (instruments[z] == tempSongInfo.instrument)
{
outputBuffer[outputPosition++] = 0x81;
outputBuffer[outputPosition++] = z;
currentInstrument = instruments[z];
break;
}
}
}
else if ((sngStyle == SngStyle::OldBfx) || (sngStyle == SngStyle::Old))
{
outputBuffer[outputPosition++] = 0x81;
WriteSngVariableLength(outputBuffer, outputPosition, tempSongInfo.instrument);
currentInstrument = tempSongInfo.instrument;
}
}
int noteLength = tempSongInfo.endAbsoluteTime - tempSongInfo.startAbsoluteTime;
if (setLength)
{
if (noteLength != currentLength)
{
int countSameLength = 1;
unsigned long tempAbsoluteTime = absoluteTime;
for (int z = (y + 1); z < channels[x].size(); z++)
{
if (
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == noteLength)
||
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == 0)
)
{
}
else
break;
tempAbsoluteTime = channels[x][z].startAbsoluteTime;
if ((channels[x][z].endAbsoluteTime - tempAbsoluteTime) == noteLength)
countSameLength++;
else
break;
tempAbsoluteTime = channels[x][z].endAbsoluteTime;
}
if ((countSameLength >= 3) && (noteLength <= 0x7FFE))
{
outputBuffer[outputPosition++] = 0x8B;
WriteSngVariableLength(outputBuffer, outputPosition, noteLength);
setLength = true;
currentLength = noteLength;
}
else
{
if (sngStyle == SngStyle::Normal)
{
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
setLength = false;
}
}
}
else
{
int countSameLength = 1;
unsigned long tempAbsoluteTime = absoluteTime;
for (int z = (y + 1); z < channels[x].size(); z++)
{
if (
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == noteLength)
||
((channels[x][z].startAbsoluteTime - tempAbsoluteTime) == 0)
)
{
}
else
break;
tempAbsoluteTime = channels[x][z].startAbsoluteTime;
if ((channels[x][z].endAbsoluteTime - tempAbsoluteTime) == noteLength)
countSameLength++;
else
break;
tempAbsoluteTime = channels[x][z].endAbsoluteTime;
}
if ((countSameLength >= 3) && (noteLength <= 0x7FFE))
{
outputBuffer[outputPosition++] = 0x8B;
WriteSngVariableLength(outputBuffer, outputPosition, noteLength);
setLength = true;
currentLength = noteLength;
}
}
int countSameVelocity = 1;
for (int z = (y + 1); z < channels[x].size(); z++)
{
if ((channels[x][z].velocity) == tempSongInfo.velocity)
countSameVelocity++;
else
break;
}
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
if (sharedChannelVelocity)
{
if (currentVelocity != tempSongInfo.velocity)
{
outputBuffer[outputPosition++] = 0x99;
sharedChannelVelocity = false;
}
}
}
if (!sharedChannelVelocity)
{
if (sngStyle == SngStyle::Old)
{
if (countSameVelocity >= 3)
{
sharedChannelVelocity = true;
currentVelocity = channels[x][y].velocity;
outputBuffer[outputPosition++] = 0x9B;
outputBuffer[outputPosition++] = currentVelocity;
outputBuffer[outputPosition++] = 0x9A;
}
}
}
if (tempSongInfo.effect != currentEffect)
{
outputBuffer[outputPosition++] = 0xA2;
outputBuffer[outputPosition++] = tempSongInfo.effect;
currentEffect = tempSongInfo.effect;
}
if (tempSongInfo.pan != currentPan)
{
outputBuffer[outputPosition++] = 0x9C;
if (tempSongInfo.pan == 0x7F)
outputBuffer[outputPosition++] = 255;
else if (tempSongInfo.pan == 0x40)
outputBuffer[outputPosition++] = 127;
else
outputBuffer[outputPosition++] = tempSongInfo.pan * 2;
currentPan = tempSongInfo.pan;
}
// Write note
if (tempSongInfo.noteNumber <= 0xC)
outputBuffer[outputPosition++] = 0;
else if (tempSongInfo.noteNumber >= 0x6B)
outputBuffer[outputPosition++] = 0x5F;
else
outputBuffer[outputPosition++] = tempSongInfo.noteNumber - 0xC;
if (!sharedChannelVelocity)
{
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
outputBuffer[outputPosition] = tempSongInfo.velocity;
if (sngStyle == SngStyle::Normal)
{
if (countSameVelocity >= 3)
{
sharedChannelVelocity = true;
outputBuffer[outputPosition] |= 0x80;
}
}
outputPosition++;
}
}
if (!setLength)
{
WriteSngVariableLength(outputBuffer, outputPosition, noteLength);
}
absoluteTime += noteLength;
}
if (setLength)
{
if (sngStyle == SngStyle::Normal)
{
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
setLength = false;
}
if (loop && (!wroteChannelLoop))
{
unsigned long delta = (loopPoint - absoluteTime);
if (setLength)
{
if (delta != currentLength)
{
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
}
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
if (!sharedChannelVelocity)
{
outputBuffer[outputPosition++] = 0x00;
currentVelocity = 0x00;
}
}
if (!setLength)
{
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
else
{
delta = 0;
}
}
outputBuffer[outputPosition++] = 0x95;
outputBuffer[outputPosition++] = 0xFF;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
sharedChannelVelocity = false;
outputBuffer[outputPosition++] = 0x99;
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
wroteChannelLoop = true;
}
unsigned long delta = (highestAbsoluteTime - absoluteTime);
if (setLength)
{
if (delta != currentLength)
{
if (sngStyle == SngStyle::Normal)
{
setLength = false;
outputBuffer[outputPosition++] = 0xAC;
}
else if (sngStyle == SngStyle::Old)
{
setLength = false;
outputBuffer[outputPosition++] = 0x8B;
outputBuffer[outputPosition++] = 0x00;
}
}
}
absoluteTime += delta;
while (delta > 0)
{
outputBuffer[outputPosition++] = 0x60;
if ((sngStyle == SngStyle::Normal) || (sngStyle == SngStyle::Old))
{
if (!sharedChannelVelocity)
{
outputBuffer[outputPosition++] = 0x00;
currentVelocity = 0x00;
}
}
if (!setLength)
{
delta = WriteSngVariableLength(outputBuffer, outputPosition, delta);
}
else
{
delta = 0;
}
}
if (wroteChannelLoop)
{
outputBuffer[outputPosition++] = 0x96;
}
else
{
outputBuffer[outputPosition++] = 0x80;
}
}
}
if (sngStyle == SngStyle::Bfx)
{
WriteLongToBuffer(outputBuffer, 0x14, outputPosition);
unsigned long instrumentsPointersStart = outputPosition;
for (int x = 0; x < instruments.size(); x++)
{
WriteShortToBuffer(outputBuffer, outputPosition, instruments[x]);
outputPosition += 2;
}
}
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] outputBuffer;
MessageBox(NULL, "Error outputting file", "Error", NULL);
return false;
}
fwrite(outputBuffer, 1, outputPosition, outFile);
delete [] outputBuffer;
fclose(outFile);
}
catch (...)
{
MessageBox(NULL, "Error converting", "Error", NULL);
return false;
}
return true;
}
void CMidiParse::BTMidiToMidi(byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool& hasLoopPoint, int& loopStart, int& loopEnd, bool extendTracksToHighest, bool usePitchBendSensitity, int pitchBendSensitity)
{
numberInstruments = 0;
try
{
FILE* outFile = fopen(outFileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return;
}
// parse midi
int trackSize = CharArrayToLong(&inputMID[0x4]);
unsigned long tempLong = Flip32Bit(0x4D546864);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00000006);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00010000 | trackSize);
fwrite(&tempLong, 1 ,4 , outFile);
unsigned long division = CharArrayToLong(&inputMID[0x0]);
unsigned short tempShort = division;
tempShort = Flip16Bit(tempShort);
fwrite(&tempShort, 1 ,2 , outFile);
int counterTrack = 0;
int highestTrackLength = 0;
for (int iii = 0; iii < trackSize; iii++)
{
unsigned long absoluteTime = 0;
unsigned long offset = CharArrayToLong(&inputMID[(iii * 4) + 0x8]);
int position = offset;
if (position != 0)
{
int previousEventValue = 0;
std::map<int, int> loopEndsWithCount;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
int timePosition = position;
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
absoluteTime += timeTag;
if (absoluteTime > highestTrackLength)
highestTrackLength = absoluteTime;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
if ((loopCount == 0xFF) || (loopCount == 0x00))
{
}
else
{
std::map<int, int>::iterator it = loopEndsWithCount.find(position);
if (it != loopEndsWithCount.end())
{
int countLeft = it->second;
if (countLeft == 0)
{
loopEndsWithCount.erase(it);
}
else
{
loopEndsWithCount[position] = (countLeft - 1);
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
else
{
loopEndsWithCount[position] = loopCount - 1;
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true); // Always FF
}
else if (subType == 0x2F)
{
endFlag = true;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
}
}
}
}
for (int iii = 0; iii < trackSize; iii++)
{
unsigned long absoluteTime = 0;
int trackEventCountSub = 0;
TrackEvent* trackEventsSub = new TrackEvent[0x30000];
for (int j = 0; j < 0x30000; j++)
{
trackEventsSub[j].contents = NULL;
trackEventsSub[j].contentSize = 0;
trackEventsSub[j].obsoleteEvent = false;
trackEventsSub[j].deltaTime = 0;
trackEventsSub[j].absoluteTime = 0;
}
unsigned long offset = CharArrayToLong(&inputMID[(iii * 4) + 0x8]);
int position = offset;
if (position != 0)
{
tempLong = Flip32Bit(0x4D54726B);
fwrite(&tempLong, 1 ,4 , outFile);
int previousEventValue = 0;
std::vector<int> loopNumbers;
std::map<int, int> loopEndsWithCount;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
if (usePitchBendSensitity)
{
//https://www.midikits.net/midi_analyser/pitch_bend.htm
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x64;
trackEventsSub[trackEventCountSub].contents[1] = 0x00;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x65;
trackEventsSub[trackEventCountSub].contents[1] = 0x00;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x06;
if (pitchBendSensitity > 0x18)
pitchBendSensitity = 0x18;
trackEventsSub[trackEventCountSub].contents[1] = pitchBendSensitity;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x64;
trackEventsSub[trackEventCountSub].contents[1] = 0x7F;
trackEventCountSub++;
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x65;
trackEventsSub[trackEventCountSub].contents[1] = 0x7F;
trackEventCountSub++;
}
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
if (extendTracksToHighest)
{
if (absoluteTime >= highestTrackLength)
{
trackEventsSub[trackEventCountSub].absoluteTime = highestTrackLength;
trackEventsSub[trackEventCountSub].deltaTime = (highestTrackLength - absoluteTime);
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x2F;
trackEventsSub[trackEventCountSub].contents[1] = 0x0;
trackEventCountSub++;
endFlag = true;
break;
}
}
int timePosition = position;
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (extendTracksToHighest)
{
if ((absoluteTime + timeTag) > highestTrackLength)
{
trackEventsSub[trackEventCountSub].absoluteTime = highestTrackLength;
trackEventsSub[trackEventCountSub].deltaTime = (highestTrackLength - absoluteTime);
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x2F;
trackEventsSub[trackEventCountSub].contents[1] = 0x0;
trackEventCountSub++;
endFlag = true;
break;
}
}
trackEventsSub[trackEventCountSub].deltaTime += timeTag;
absoluteTime += timeTag;
trackEventsSub[trackEventCountSub].absoluteTime = absoluteTime;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 5;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x51;
trackEventsSub[trackEventCountSub].contents[1] = 0x3;
trackEventsSub[trackEventCountSub].contents[2] = ((microsecondsSinceQuarterNote >> 16) & 0xFF);
trackEventsSub[trackEventCountSub].contents[3] = ((microsecondsSinceQuarterNote >> 8) & 0xFF);
trackEventsSub[trackEventCountSub].contents[4] = ((microsecondsSinceQuarterNote >> 0) & 0xFF);
trackEventCountSub++;
int MICROSECONDS_PER_MINUTE = 60000000;
float beatsPerMinute = (float)MICROSECONDS_PER_MINUTE / (float)microsecondsSinceQuarterNote;
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
int loopNumber = 0;
if (loopNumbers.size() > 0)
{
loopNumber = loopNumbers.back();
loopNumbers.pop_back();
}
// Fake loop end, controller 103
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 103;
trackEventsSub[trackEventCountSub].contents[1] = loopNumber;
trackEventCountSub++;
if ((loopCount == 0xFF) || (loopCount == 0x00))
{
hasLoopPoint = true;
loopEnd = absoluteTime;
if (extendTracksToHighest)
{
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
}
}
else
{
std::map<int, int>::iterator it = loopEndsWithCount.find(position);
if (it != loopEndsWithCount.end())
{
int countLeft = it->second;
if (countLeft == 0)
{
loopEndsWithCount.erase(it);
}
else
{
loopEndsWithCount[position] = (countLeft - 1);
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
else
{
loopEndsWithCount[position] = loopCount - 1;
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
// Fake loop start, controller 102
trackEventsSub[trackEventCountSub].type = 0xB0 | ((iii / 4) & 0xF);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 102;
trackEventsSub[trackEventCountSub].contents[1] = loopNumber;
trackEventCountSub++;
hasLoopPoint = true;
loopStart = absoluteTime;
loopNumbers.push_back(loopNumber);
}
else if (subType == 0x2F)
{
trackEventsSub[trackEventCountSub].type = 0xFF;
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = 0x2F;
trackEventsSub[trackEventCountSub].contents[1] = 0x0;
trackEventCountSub++;
endFlag = true;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
trackEventsSub[trackEventCountSub].type = previousEventValue;
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
trackEventsSub[trackEventCountSub].type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].durationTime = timeDuration; // to be filled in
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = noteNumber;
trackEventsSub[trackEventCountSub].contents[1] = velocity;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = controllerType;
trackEventsSub[trackEventCountSub].contents[1] = controllerValue;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
trackEventsSub[trackEventCountSub].contentSize = 1;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = instrument;
if (instrument >= numberInstruments)
numberInstruments = (instrument + 1);
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
trackEventsSub[trackEventCountSub].contentSize = 1;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = amount;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
trackEventsSub[trackEventCountSub].type = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].type = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEventsSub[trackEventCountSub].contentSize = 2;
trackEventsSub[trackEventCountSub].contents = new byte[trackEventsSub[trackEventCountSub].contentSize];
trackEventsSub[trackEventCountSub].contents[0] = valueLSB;
trackEventsSub[trackEventCountSub].contents[1] = valueMSB;
trackEventCountSub++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
fprintf(outFile, "%02X ERROR MISSING PARSE OF TYPE\n", eventVal);
}
}
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
TrackEvent trackEvent = trackEventsSub[eventCount];
if ((trackEvent.type >= 0x90) && (trackEvent.type < 0xA0))
{
// need to split out
if (trackEvent.durationTime > 0)
{
unsigned long shutoffTime = (trackEvent.absoluteTime + trackEvent.durationTime);
if (eventCount != (trackEventCountSub - 1))
{
for (int i = (eventCount+1); i < trackEventCountSub; i++)
{
if ((trackEventsSub[i].absoluteTime >= shutoffTime) && (i != (trackEventCountSub - 1)))
{
for (int j = (trackEventCountSub - 1); j >= i; j--)
{
trackEventsSub[j+1].absoluteTime = trackEventsSub[j].absoluteTime;
trackEventsSub[j+1].contentSize = trackEventsSub[j].contentSize;
if (trackEventsSub[j+1].contents != NULL)
{
delete [] trackEventsSub[j+1].contents;
trackEventsSub[j+1].contents = NULL;
}
trackEventsSub[j+1].contents = new byte[trackEventsSub[j].contentSize];
for (int r = 0; r < trackEventsSub[j].contentSize; r++)
{
trackEventsSub[j+1].contents[r] = trackEventsSub[j].contents[r];
}
trackEventsSub[j+1].deltaTime = trackEventsSub[j].deltaTime;
trackEventsSub[j+1].durationTime = trackEventsSub[j].durationTime;
trackEventsSub[j+1].obsoleteEvent = trackEventsSub[j].obsoleteEvent;
trackEventsSub[j+1].type = trackEventsSub[j].type;
}
trackEventsSub[i].type = trackEventsSub[eventCount].type;
trackEventsSub[i].absoluteTime = shutoffTime;
trackEventsSub[i].deltaTime = (trackEventsSub[i].absoluteTime - trackEventsSub[i-1].absoluteTime);
trackEventsSub[i].contentSize = trackEventsSub[eventCount].contentSize;
trackEventsSub[i].durationTime = 0;
trackEventsSub[i].contents = new byte[trackEventsSub[i].contentSize];
trackEventsSub[i].contents[0] = trackEventsSub[eventCount].contents[0];
trackEventsSub[i].contents[1] = 0;
trackEventsSub[i+1].deltaTime = (trackEventsSub[i+1].absoluteTime - trackEventsSub[i].absoluteTime);
if (trackEventsSub[i].deltaTime > 0xFF000000)
{
int a =1;
}
trackEventCountSub++;
break;
}
else if (i == (trackEventCountSub - 1))
{
trackEventsSub[i+1].absoluteTime = shutoffTime; // move end to end
trackEventsSub[i+1].contentSize = trackEventsSub[i].contentSize;
if (trackEventsSub[i+1].contents != NULL)
{
delete [] trackEventsSub[i+1].contents;
trackEventsSub[i+1].contents = NULL;
}
trackEventsSub[i+1].contents = new byte[trackEventsSub[i].contentSize];
for (int r = 0; r < trackEventsSub[i].contentSize; r++)
{
trackEventsSub[i+1].contents[r] = trackEventsSub[i].contents[r];
}
trackEventsSub[i+1].deltaTime = trackEventsSub[i].deltaTime;
trackEventsSub[i+1].durationTime = trackEventsSub[i].durationTime;
trackEventsSub[i+1].obsoleteEvent = trackEventsSub[i].obsoleteEvent;
trackEventsSub[i+1].type = trackEventsSub[i].type;
trackEventsSub[i].type = trackEventsSub[eventCount].type;
trackEventsSub[i].absoluteTime = shutoffTime;
trackEventsSub[i].deltaTime = (trackEventsSub[i].absoluteTime - trackEventsSub[i - 1].absoluteTime);
trackEventsSub[i].contentSize = trackEventsSub[eventCount].contentSize;
trackEventsSub[i].durationTime = 0;
trackEventsSub[i].contents = new byte[trackEventsSub[i].contentSize];
trackEventsSub[i].contents[0] = trackEventsSub[eventCount].contents[0];
trackEventsSub[i].contents[1] = 0;
trackEventsSub[i+1].deltaTime = (trackEventsSub[i+1].absoluteTime - trackEventsSub[i].absoluteTime);
if (trackEventsSub[i].deltaTime > 0xFF000000)
{
int a =1;
}
trackEventCountSub++;
break;
}
}
}
else
{
trackEventsSub[eventCount+1].absoluteTime = shutoffTime; // move end to end
trackEventsSub[eventCount+1].contentSize = trackEventsSub[eventCount].contentSize;
if (trackEventsSub[eventCount+1].contents != NULL)
{
delete [] trackEventsSub[eventCount+1].contents;
trackEventsSub[eventCount+1].contents = NULL;
}
trackEventsSub[eventCount+1].contents = new byte[trackEventsSub[eventCount].contentSize];
for (int r = 0; r < trackEventsSub[eventCount].contentSize; r++)
{
trackEventsSub[eventCount+1].contents[r] = trackEventsSub[eventCount].contents[r];
}
trackEventsSub[eventCount+1].deltaTime = trackEventsSub[eventCount].deltaTime;
trackEventsSub[eventCount+1].durationTime = trackEventsSub[eventCount].durationTime;
trackEventsSub[eventCount+1].obsoleteEvent = trackEventsSub[eventCount].obsoleteEvent;
trackEventsSub[eventCount+1].type = trackEventsSub[eventCount].type;
trackEventsSub[eventCount].type = trackEventsSub[eventCount].type;
trackEventsSub[eventCount].absoluteTime = shutoffTime;
if ((trackEventsSub[eventCount].absoluteTime - trackEventsSub[eventCount - 1].absoluteTime) > 0xFF000000)
{
int a =1;
}
trackEventsSub[eventCount].deltaTime = (trackEventsSub[eventCount].absoluteTime - trackEventsSub[eventCount - 1].absoluteTime);
trackEventsSub[eventCount].contentSize = trackEventsSub[eventCount].contentSize;
trackEventsSub[eventCount].durationTime = 0;
trackEventsSub[eventCount].contents = new byte[trackEventsSub[eventCount].contentSize];
trackEventsSub[eventCount].contents[0] = trackEventsSub[eventCount].contents[0];
trackEventsSub[eventCount].contents[1] = 0;
trackEventsSub[eventCount+1].deltaTime = (trackEventsSub[eventCount+1].absoluteTime - trackEventsSub[eventCount].absoluteTime);
if (trackEventsSub[eventCount].deltaTime > 0xFF000000)
{
int a =1;
}
trackEventCountSub++;
}
}
}
}
unsigned long timeOffset = 0;
unsigned long sizeData = 0;
byte previousTrackEvent = 0x0;
for (int j = 0; j < trackEventCountSub; j++)
{
TrackEvent trackEvent = trackEventsSub[j];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type == 0xFF))
{
sizeData += 1;
}
sizeData += trackEvent.contentSize;
previousTrackEvent = trackEvent.type;
}
}
tempLong = Flip32Bit(sizeData);
fwrite(&tempLong,1, 4, outFile);
timeOffset = 0;
previousTrackEvent = 0x0;
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
TrackEvent trackEvent = trackEventsSub[eventCount];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, true);
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type == 0xFF))
{
fwrite(&trackEvent.type, 1, 1, outFile);
}
fwrite(trackEvent.contents, 1, trackEvent.contentSize, outFile);
previousTrackEvent = trackEvent.type;
}
}
for (int eventCount = 0; eventCount < trackEventCountSub; eventCount++)
{
if (trackEventsSub[eventCount].contents != NULL)
{
delete [] trackEventsSub[eventCount].contents;
trackEventsSub[eventCount].contents = NULL;
}
}
}
else
{
}
counterTrack++;
delete [] trackEventsSub;
}
fflush(outFile);
fclose(outFile);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
bool CMidiParse::MidiToBTFormat(CString input, CString output, bool loop, unsigned long loopPoint, bool useRepeaters)
{
numberTracks = 0;
for (unsigned int x = 0; x < 0x20; x++)
{
for (int y = 0; y < 0x30000; y++)
{
if (trackEvents[x][y].contents != NULL)
{
delete[] trackEvents[x][y].contents;
trackEvents[x][y].contents = NULL;
}
}
trackEventCount[x] = 0;
}
CString tempOutput = (output + "temp.bin");
unsigned short numberTracks = 0x20;
if (MidiToBTFormatStageOne(input, tempOutput, loop, loopPoint, useRepeaters, numberTracks))
{
FILE* inFile = fopen(tempOutput, "rb");
if (inFile == NULL)
{
MessageBox(NULL, "Error opening temp file", "Error", NULL);
return false;
}
fseek(inFile, 0, SEEK_END);
int sizeOut = ftell(inFile);
rewind(inFile);
byte* inArray = new byte[sizeOut];
fread(inArray, 1, sizeOut, inFile);
fclose(inFile);
::DeleteFile(tempOutput);
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] inArray;
MessageBox(NULL, "Error opening output", "Error", NULL);
return false;
}
unsigned long speed = CharArrayToLong(&inArray[0x80]);
unsigned long offsetheader[0x20];
for (int x = 0; x < 0x80; x+=4)
{
offsetheader[x/4] = ((((((inArray[x] << 8) | inArray[x+1]) << 8) | inArray[x+2]) << 8) | inArray[x+3]);
if (offsetheader[x/4] == 0)
{
break;
}
}
unsigned long lessOffset = 0x84 - ((numberTracks * 0x4) + 0x8);
unsigned long tempLong = Flip32Bit(speed);
fwrite(&tempLong, 1, 4, outFile);
tempLong = Flip32Bit((unsigned long)numberTracks);
fwrite(&tempLong, 1, 4, outFile);
for (int x = 0; x < numberTracks; x++)
{
tempLong = Flip32Bit(((unsigned long)offsetheader[x] - lessOffset));
fwrite(&tempLong, 1, 4, outFile);
}
for (int x = 0x84; x < sizeOut; x++)
{
fwrite(&inArray[x], 1, 1, outFile);
}
fclose(outFile);
}
else
{
return false;
}
return true;
}
bool CMidiParse::AddLoopGEFormat(byte* inputMID, CString output, int inputSize, bool loop, unsigned long loopPoint, bool useRepeaters)
{
unsigned long highestAbsoluteTime = 0;
unsigned long highestAbsoluteTimeByTrack[0x10];
for (int x = 0; x < 0x10; x++)
highestAbsoluteTimeByTrack[x] = 0;
unsigned long division = CharArrayToLong(&inputMID[0x40]);
int numberInstruments = 0;
numberTracks = 0x10;
for (unsigned int x = 0; x < 0x20; x++)
{
for (int y = 0; y < 0x30000; y++)
{
if (trackEvents[x][y].contents != NULL)
{
delete[] trackEvents[x][y].contents;
trackEvents[x][y].contents = NULL;
}
}
trackEventCount[x] = 0;
}
try
{
unsigned long lengthHeader = 0x44;
// parse midi
int trackSize = 0;
for (int i = 0; i < (lengthHeader - 4); i+=4) // ignore last 00000180
{
unsigned long offset = CharArrayToLong(&inputMID[i]);
if (offset != 0)
trackSize++;
}
for (int iii = 0; iii < (lengthHeader - 4); iii+=4) // ignore last 00000180
{
int trackNum = iii / 4;
unsigned long absoluteTime = 0;
unsigned long offset = CharArrayToLong(&inputMID[iii]);
int position = offset;
if (position != 0)
{
int previousEventValue = 0;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
int timePosition = position;
unsigned long original;
// trackEvents[trackEventCount].deltaTime is for loops
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
absoluteTime += timeTag;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
int MICROSECONDS_PER_MINUTE = 60000000;
float beatsPerMinute = (float)MICROSECONDS_PER_MINUTE / (float)microsecondsSinceQuarterNote;
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (endLoop != 0xFF)
{
// is this used?
}
}
else if (subType == 0x2F)
{
endFlag = true;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
}
}
}
if (absoluteTime > highestAbsoluteTime)
{
highestAbsoluteTime = absoluteTime;
}
if (absoluteTime > highestAbsoluteTimeByTrack[trackNum])
{
highestAbsoluteTimeByTrack[trackNum] = absoluteTime;
}
}
int counterTrack = 0;
for (int iii = 0; iii < (lengthHeader - 4); iii+=4) // ignore last 00000180
{
counterTrack = iii / 4;
unsigned long absoluteTime = 0;
trackEventCount[counterTrack] = 0;
for (int j = 0; j < 0x30000; j++)
{
trackEvents[counterTrack][j].contents = NULL;
trackEvents[counterTrack][j].obsoleteEvent = false;
trackEvents[counterTrack][j].deltaTime = 0;
trackEvents[counterTrack][j].absoluteTime = 0;
}
unsigned long offset = CharArrayToLong(&inputMID[iii]);
int position = offset;
if (position != 0)
{
bool didLoop = false;
if ((loop) && (loopPoint == 0) && (highestAbsoluteTimeByTrack[counterTrack] > 0))
{
TrackEvent* newTrackEvent = (TrackEvent*)&(trackEvents[counterTrack][trackEventCount[counterTrack]]);
newTrackEvent->type = 0xFF;
newTrackEvent->absoluteTime = 0;
newTrackEvent->contentSize = 3;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2E;
newTrackEvent->contents[1] = 0x00;
newTrackEvent->contents[2] = 0xFF;
newTrackEvent->deltaTime = 0;
newTrackEvent->obsoleteEvent = false;
trackEventCount[counterTrack]++;
didLoop = true;
}
int previousEventValue = 0;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
if (trackEventCount[counterTrack] >= 0x30000)
return false;
int timePosition = position;
unsigned long original;
// trackEvents[counterTrack][trackEventCount[counterTrack]].deltaTime is for loops
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].deltaTime += timeTag;
absoluteTime += timeTag;
trackEvents[counterTrack][trackEventCount[counterTrack]].absoluteTime = absoluteTime;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
trackEvents[counterTrack][trackEventCount[counterTrack]].type = 0xFF;
trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize = 4;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents = new byte[trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize];
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[0] = 0x51;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[1] = ((microsecondsSinceQuarterNote >> 16) & 0xFF);
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[2] = ((microsecondsSinceQuarterNote >> 8) & 0xFF);
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[3] = ((microsecondsSinceQuarterNote >> 0) & 0xFF);
trackEventCount[counterTrack]++;
int MICROSECONDS_PER_MINUTE = 60000000;
float beatsPerMinute = (float)MICROSECONDS_PER_MINUTE / (float)microsecondsSinceQuarterNote;
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (endLoop != 0xFF)
{
// is this used?
}
}
else if (subType == 0x2F)
{
TrackEvent* newTrackEvent = ((TrackEvent*)&(trackEvents[counterTrack][trackEventCount[counterTrack]]));
endFlag = true;
if (trackEventCount[counterTrack] > 0)
{
if (loop)
{
TrackEvent* prevEvent = ((TrackEvent*)&(trackEvents[counterTrack][trackEventCount[counterTrack]-1]));
newTrackEvent->type = 0xFF;
if (highestAbsoluteTime > (prevEvent->absoluteTime))
{
newTrackEvent->deltaTime = (highestAbsoluteTime - (prevEvent->absoluteTime));
newTrackEvent->absoluteTime = highestAbsoluteTime;
}
else
{
newTrackEvent->deltaTime = 0;
newTrackEvent->absoluteTime = prevEvent->absoluteTime;
}
newTrackEvent->contentSize = 7;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2D;
newTrackEvent->contents[1] = 0xFF;
newTrackEvent->contents[2] = 0xFF;
newTrackEvent->contents[3] = 0x0; // todo write location
newTrackEvent->contents[4] = 0x0;
newTrackEvent->contents[5] = 0x0;
newTrackEvent->contents[6] = 0x0;
newTrackEvent->obsoleteEvent = false;
trackEventCount[counterTrack]++;
endFlag = true;
}
else
{
newTrackEvent->contentSize = 7;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2D;
newTrackEvent->contents[1] = 0xFF;
newTrackEvent->contents[2] = 0xFF;
newTrackEvent->contents[3] = 0x0; // todo write location
newTrackEvent->contents[4] = 0x0;
newTrackEvent->contents[5] = 0x0;
newTrackEvent->contents[6] = 0x0;
newTrackEvent->obsoleteEvent = false;
trackEventCount[counterTrack]++;
}
}
trackEvents[counterTrack][trackEventCount[counterTrack]].type = 0xFF;
trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize = 2;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents = new byte[trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize];
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[0] = 0x2F;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[1] = 0x0;
trackEventCount[counterTrack]++;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
trackEvents[counterTrack][trackEventCount[counterTrack]].type = previousEventValue;
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
trackEvents[counterTrack][trackEventCount[counterTrack]].type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].durationTime = timeDuration; // to be filled in
trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize = 2;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents = new byte[trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize];
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[0] = noteNumber;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[1] = velocity;
trackEventCount[counterTrack]++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
trackEvents[counterTrack][trackEventCount[counterTrack]].type = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].type = eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize = 2;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents = new byte[trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize];
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[0] = controllerType;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[1] = controllerValue;
trackEventCount[counterTrack]++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
trackEvents[counterTrack][trackEventCount[counterTrack]].type = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].type = eventVal;
}
trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize = 1;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents = new byte[trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize];
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[0] = instrument;
if (instrument >= numberInstruments)
numberInstruments = (instrument + 1);
trackEventCount[counterTrack]++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
trackEvents[counterTrack][trackEventCount[counterTrack]].type = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].type = eventVal;
}
trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize = 1;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents = new byte[trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize];
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[0] = amount;
trackEventCount[counterTrack]++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
trackEvents[counterTrack][trackEventCount[counterTrack]].type = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].type = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize = 2;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents = new byte[trackEvents[counterTrack][trackEventCount[counterTrack]].contentSize];
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[0] = valueLSB;
trackEvents[counterTrack][trackEventCount[counterTrack]].contents[1] = valueMSB;
trackEventCount[counterTrack]++;
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
}
}
}
}
}
catch(...)
{
MessageBox(NULL, "Error processing inpt file", "Error", NULL);
return false;
}
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return false;
}
unsigned long timeOffset = 0;
unsigned long startPosition = 0x44;
// get offsets
for (int i = 0; i < numberTracks; i++)
{
unsigned long sizeData = 0;
int loopStartPosition = 0;
bool foundLoopStart = false;
byte previousTrackEvent = 0x0;
if (trackEventCount[i] > 0)
{
unsigned long tempLong = Flip32Bit(startPosition);
fwrite(&tempLong, 1, 4, outFile);
for (int j = 0; j < trackEventCount[i]; j++)
{
TrackEvent* trackEvent = &(trackEvents[i][j]);
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent->deltaTime + timeOffset), lengthTimeDelta);
if (trackEvent->obsoleteEvent)
{
timeOffset += trackEvent->deltaTime;
}
else
{
if ((trackEvent->type == 0xFF) && (trackEvent->contents[0] == 0x2E))
{
foundLoopStart = true;
loopStartPosition = (startPosition + sizeData + 1 + trackEvent->contentSize + lengthTimeDelta);
}
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent->type == 0xFF) && (trackEvent->contents[0] == 0x2D))
{
unsigned long offsetBack = ((startPosition + sizeData) - loopStartPosition + 8);
trackEvent->contents[3] = ((offsetBack >> 24) & 0xFF);
trackEvent->contents[4] = ((offsetBack >> 16) & 0xFF);
trackEvent->contents[5] = ((offsetBack >> 8) & 0xFF);
trackEvent->contents[6] = ((offsetBack >> 0) & 0xFF);
}
if ((trackEvent->type != previousTrackEvent) || (trackEvent->type == 0xFF))
{
sizeData += 1;
}
sizeData += trackEvent->contentSize;
if ((trackEvent->type >= 0x90) && (trackEvent->type < 0xA0))
{
unsigned long lengthDurationBytes = 0;
unsigned long duration = ReturnVLBytes(trackEvent->durationTime, lengthDurationBytes);
sizeData += lengthDurationBytes;
}
previousTrackEvent = trackEvent->type;
}
}
startPosition += sizeData;
}
else
{
unsigned long zero = 0;
fwrite(&zero, 1, 4, outFile);
}
}
for (int i = numberTracks; i < 16; i++)
{
unsigned long zero = 0;
fwrite(&zero, 1, 4, outFile);
}
unsigned long divisionFlipped = Flip32Bit((unsigned long)division);
fwrite(&divisionFlipped, 1, 4, outFile);
//FILE* outDebug = fopen("C:\\GoldeneyeStuff\\GE Editor Source\\debug.txt", "w");
FILE* outDebug = NULL;
for (int i = 0; i < numberTracks; i++)
{
if (trackEventCount[i] > 0)
{
if (outDebug != NULL)
fprintf(outDebug, "Track %X\n", i);
byte previousTrackEvent = 0x0;
for (int j = 0; j < trackEventCount[i]; j++)
{
TrackEvent* trackEvent = &(trackEvents[i][j]);
if (trackEvent->obsoleteEvent)
{
timeOffset += trackEvent->deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent->deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, false);
for (int ii = 0; ii < lengthTimeDelta; ii++)
if (outDebug != NULL) fprintf(outDebug, "%02X", ((timeDelta >> ((lengthTimeDelta * 8) - 8 - (ii * 8))) & 0xFF));
if ((trackEvent->type != previousTrackEvent) || (trackEvent->type == 0xFF))
{
fwrite(&trackEvent->type, 1, 1, outFile);
if (outDebug != NULL) fprintf(outDebug, "%02X", trackEvent->type);
}
fwrite(trackEvent->contents, 1, trackEvent->contentSize, outFile);
for (int ii = 0; ii < trackEvent->contentSize; ii++)
{
if (outDebug != NULL) fprintf(outDebug, "%02X", trackEvent->contents[ii]);
}
if ((trackEvent->type >= 0x90) && (trackEvent->type < 0xA0))
{
unsigned long lengthDurationBytes = 0;
unsigned long duration = ReturnVLBytes(trackEvent->durationTime, lengthDurationBytes); // todo real trackevent
WriteVLBytes(outFile, duration, lengthDurationBytes, false);
for (int ii = 0; ii < lengthDurationBytes; ii++)
if (outDebug != NULL) fprintf(outDebug, "%02X", ((duration >> ((lengthDurationBytes * 8) - 8 - (ii * 8))) & 0xFF));
}
if (outDebug != NULL) fprintf(outDebug, "\n");
previousTrackEvent = trackEvent->type;
}
}
}
for (int j = 0; j < trackEventCount[i]; j++)
{
if (trackEvents[i][j].contents != NULL)
{
delete [] trackEvents[i][j].contents;
trackEvents[i][j].contents = NULL;
}
}
}
fflush(outDebug);
fclose(outFile);
// write FEFE in case see FE
outFile = fopen(output, "rb");
if (outFile == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
fseek(outFile, 0, SEEK_END);
int sizeOut = ftell(outFile);
rewind(outFile);
byte* inArray = new byte[sizeOut];
fread(inArray, 1, sizeOut, outFile);
fclose(outFile);
unsigned long offsetheader[0x10];
int extraOffsets[0x10];
for (int x = 0; x < 0x40; x+=4)
{
offsetheader[x/4] = ((((((inArray[x] << 8) | inArray[x+1]) << 8) | inArray[x+2]) << 8) | inArray[x+3]);
extraOffsets[x/4] = 0x00000000;
}
for (int x = 0; x < sizeOut; x++)
{
if (x > 0x44)
{
if (inArray[x] == 0xFE) // need to write twice
{
for (int y = 0; y < numberTracks; y++)
{
if (offsetheader[y] > x)
{
extraOffsets[y]++;
}
}
}
}
}
outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] inArray;
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
for (int x = 0; x < 0x10; x++)
{
WriteLongToBuffer(inArray, x*4, offsetheader[x] + extraOffsets[x]);
}
for (int x = 0; x < sizeOut; x++)
{
fwrite(&inArray[x], 1, 1, outFile);
if (x > 0x44)
{
if (inArray[x] == 0xFE) // need to write twice
fwrite(&inArray[x], 1, 1, outFile);
}
}
fclose(outFile);
delete [] inArray;
//return true;
if (useRepeaters)
{
// "compress"
outFile = fopen(output, "rb");
if (outFile == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
fseek(outFile, 0, SEEK_END);
int sizeIn = ftell(outFile);
rewind(outFile);
inArray = new byte[sizeIn];
fread(inArray, 1, sizeIn, outFile);
fclose(outFile);
unsigned long offset[0x10];
for (int x = 0; x < 0x40; x+=4)
{
offset[x/4] = ((((((inArray[x] << 8) | inArray[x+1]) << 8) | inArray[x+2]) << 8) | inArray[x+3]);
}
unsigned quarternote = ((((((inArray[0x40] << 8) | inArray[0x41]) << 8) | inArray[0x42]) << 8) | inArray[0x43]);
unsigned char* outArray = new unsigned char[sizeIn * 4];
for (int x = 0x0; x < (sizeIn * 4); x++)
{
outArray[x] = 0x0;
}
unsigned long offsetNew[0x10];
for (int x = 0; x < 0x10; x++)
{
offsetNew[x] = 0;
}
int outputSpot = 0x44;
for (int x = 0x0; x < 0x10; x++)
{
if (offset[x] != 0)
{
offsetNew[x] = outputSpot;
int outputStart = outputSpot;
int endSpot = sizeIn;
if (x < 0xF)
{
if (offset[x+1] != 0)
{
endSpot = offset[x+1];
}
}
int y = offset[x];
// loop till end of file
while (y < endSpot)
{
int bestMatchOffset = -1;
int bestMatchLoopCount = -1;
// check from past to now for results
for (int z = outputStart; z < outputSpot; z++)
{
int match = 0;
int matchOffset = 0;
// one spot match start here
while ((outArray[z+matchOffset] == inArray[y+matchOffset]) && ((y+matchOffset) < endSpot) && (outArray[z+matchOffset] != 0xFE) && (outArray[z+matchOffset] != 0xFF) && ((z+matchOffset) < outputSpot))
{
bool seeAnFF = false;
for (int checkFF = y+matchOffset; ((checkFF < endSpot) && (checkFF < (y+matchOffset + 5))); checkFF++)
{
if (inArray[checkFF] == 0xFF)
seeAnFF = true;
}
if (seeAnFF)
{
break;
}
matchOffset++;
}
if ((matchOffset > bestMatchLoopCount) && (matchOffset > 6))
{
bestMatchLoopCount = matchOffset;
bestMatchOffset = z;
}
}
int loopCheck = ((y - offset[x]) / 2);
if (loopCheck > 0xFD)
loopCheck = 0xFD;
if (bestMatchLoopCount > 6)
{
if (bestMatchLoopCount > 0xFD)
bestMatchLoopCount = 0xFD;
outArray[outputSpot++] = 0xFE;
int distBack = ((outputSpot - bestMatchOffset) - 1);
outArray[outputSpot++] = ((distBack >> 8) & 0xFF);
outArray[outputSpot++] = (distBack & 0xFF);
outArray[outputSpot++] = bestMatchLoopCount;
y += bestMatchLoopCount;
}
else
{
// write one
outArray[outputSpot++] = inArray[y];
y++;
}
}
}
else
break;
if ((outputSpot % 4) != 0)
outputSpot += (4 - (outputSpot % 4));
}
// correct loops
for (int x = 0x0; x < 0x10; x++)
{
if (offsetNew[x] != 0)
{
int outputStart = offsetNew[x];
int endSpot = outputSpot;
if (x < 0xF)
{
if (offsetNew[x+1] != 0)
{
endSpot = offsetNew[x+1];
}
}
int y = offsetNew[x];
// loop till end of file
bool foundStart = false;
int startPos = 0;
while (y < endSpot)
{
if ((outArray[y] == 0xFF) && (outArray[y+1] == 0x2E) && (outArray[y+2] == 0x00) && (outArray[y+3] == 0xFF))
{
foundStart = true;
startPos = y + 4;
y+=4;
}
else if ((outArray[y] == 0xFF) && (outArray[y+1] == 0x2D) && (outArray[y+2] == 0xFF) && (outArray[y+3] == 0xFF))
{
if (foundStart)
{
int distance = ((y + 8) - startPos);
WriteLongToBuffer(outArray, y+4, distance);
foundStart = false;
}
y+=8;
}
else
{
y++;
}
}
}
}
for (int x = 0x0; x < 0x10; x++)
{
WriteLongToBuffer(outArray, x*4, offsetNew[x]);
}
WriteLongToBuffer(outArray, 0x40, quarternote);
outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] inArray;
delete [] outArray;
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
for (int x = 0; x < outputSpot; x++)
{
fwrite(&outArray[x], 1, 1, outFile);
}
fclose(outFile);
delete [] inArray;
delete [] outArray;
}
return true;
}
bool CMidiParse::MidiToBTFormatStageOne(CString input, CString output, bool loop, unsigned long loopPoint, bool useRepeaters, unsigned short& numTracks)
{
try
{
CString tempFileName = input;
struct stat results;
stat(tempFileName, &results);
FILE* inFile1 = fopen(input, "rb");
if (inFile1 == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
byte* inputMID = new byte[results.st_size];
fread(inputMID, 1, results.st_size, inFile1);
fclose(inFile1);
unsigned long header = CharArrayToLong(&inputMID[0]);
if (header != 0x4D546864)
{
MessageBox(NULL, "Invalid midi hdr", "Error", NULL);
return false;
}
unsigned long headerLength = CharArrayToLong(&inputMID[4]);
unsigned short type = CharArrayToShort(&inputMID[8]);
numTracks = CharArrayToShort(&inputMID[0xA]);
unsigned short tempo = CharArrayToShort(&inputMID[0xC]);
if (numTracks > 32)
{
MessageBox(NULL, "Too many tracks, truncated to 32", "Warning", NULL);
numTracks = 32;
}
unsigned long lessOffset = 0x84 - ((numTracks * 0x4) + 0x8);
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return false;
}
numberTracks = numTracks;
if (type == 0)
{
}
else if (type == 1)
{
}
else
{
fclose(outFile);
MessageBox(NULL, "Invalid midi type", "Error", NULL);
return false;
}
int position = 0xE;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool unknownsHit = false;
unsigned long highestAbsoluteTime = 0;
unsigned long highestAbsoluteTimeByTrack[0x20];
for (int x = 0; x < 0x20; x++)
highestAbsoluteTimeByTrack[x] = 0;
for (int trackNum = 0; trackNum < numberTracks; trackNum++)
{
unsigned long absoluteTime = 0;
unsigned long trackHeader = ((((((inputMID[position] << 8) | inputMID[position+1]) << 8) | inputMID[position+2]) << 8) | inputMID[position+3]);
if (trackHeader != 0x4D54726B)
{
MessageBox(NULL, "Invalid track midi hdr", "Error", NULL);
return false;
}
unsigned long trackLength = ((((((inputMID[position+4] << 8) | inputMID[position+5]) << 8) | inputMID[position+6]) << 8) | inputMID[position+7]);
position += 8;
byte previousEventValue = 0xFF;
bool endFlag = false;
while (!endFlag && (position < results.st_size))
{
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
absoluteTime += timeTag;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
bool statusBit = false;
if (eventVal <= 0x7F)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if (eventVal == 0xFF) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x2F) //End of Track Event.
{
// remove time till end
absoluteTime -= timeTag;
endFlag = true;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
}
else if (subType == 0x51) //Set Tempo Event.
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int i = 0; i < length; i++)
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
previousEventValue = eventVal;
}
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change
{
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xF0 || eventVal == 0xF7)
{
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
else
{
if (!unknownsHit)
{
MessageBox(NULL, "Invalid midi character found", "Error", NULL);
unknownsHit = true;
}
}
}
if (absoluteTime > highestAbsoluteTime)
{
highestAbsoluteTime = absoluteTime;
}
if (absoluteTime > highestAbsoluteTimeByTrack[trackNum])
{
highestAbsoluteTimeByTrack[trackNum] = absoluteTime;
}
}
position = 0xE;
repeatPattern = NULL;
altOffset = 0;
altLength = 0;
for (int trackNum = 0; trackNum < numberTracks; trackNum++)
{
unsigned long absoluteTime = 0;
unsigned long trackHeader = ((((((inputMID[position] << 8) | inputMID[position+1]) << 8) | inputMID[position+2]) << 8) | inputMID[position+3]);
if (trackHeader != 0x4D54726B)
{
MessageBox(NULL, "Invalid track midi hdr", "Error", NULL);
return false;
}
unsigned long trackLength = ((((((inputMID[position+4] << 8) | inputMID[position+5]) << 8) | inputMID[position+6]) << 8) | inputMID[position+7]);
position += 8;
byte previousEventValue = 0xFF;
bool endFlag = false;
bool didLoop = false;
if ((loop) && (loopPoint == 0) && (highestAbsoluteTimeByTrack[trackNum] > 0))
{
TrackEvent* newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->type = 0xFF;
newTrackEvent->absoluteTime = 0;
newTrackEvent->contentSize = 3;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2E;
newTrackEvent->contents[1] = 0x00;
newTrackEvent->contents[2] = 0xFF;
newTrackEvent->deltaTime = 0;
newTrackEvent->obsoleteEvent = false;
trackEventCount[trackNum]++;
didLoop = true;
}
while (!endFlag && (position < results.st_size))
{
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
absoluteTime += timeTag;
TrackEvent* newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->deltaTime = timeTag;
newTrackEvent->obsoleteEvent = false;
newTrackEvent->contents = NULL;
newTrackEvent->absoluteTime = absoluteTime;
if ((loop) && (!didLoop) && (highestAbsoluteTimeByTrack[trackNum] > loopPoint))
{
if (absoluteTime == loopPoint)
{
TrackEvent* newTrackEventLoop = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEventLoop->type = 0xFF;
newTrackEventLoop->absoluteTime = absoluteTime;
newTrackEventLoop->contentSize = 3;
newTrackEventLoop->contents = new byte[newTrackEventLoop->contentSize];
newTrackEventLoop->contents[0] = 0x2E;
newTrackEventLoop->contents[1] = 0x00;
newTrackEventLoop->contents[2] = 0xFF;
newTrackEventLoop->deltaTime = timeTag;
newTrackEventLoop->obsoleteEvent = false;
trackEventCount[trackNum]++;
newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->deltaTime = 0;
newTrackEvent->obsoleteEvent = false;
newTrackEvent->contents = NULL;
newTrackEvent->absoluteTime = absoluteTime;
didLoop = true;
}
else if (absoluteTime > loopPoint)
{
TrackEvent* newTrackEventLoop = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEventLoop->type = 0xFF;
newTrackEventLoop->absoluteTime = loopPoint;
newTrackEventLoop->contentSize = 3;
newTrackEventLoop->contents = new byte[newTrackEventLoop->contentSize];
newTrackEventLoop->contents[0] = 0x2E;
newTrackEventLoop->contents[1] = 0x00;
newTrackEventLoop->contents[2] = 0xFF;
if (trackEventCount[trackNum] > 0)
newTrackEventLoop->deltaTime = (loopPoint - ((TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]-1]))->absoluteTime);
else
newTrackEventLoop->deltaTime = loopPoint;
newTrackEventLoop->obsoleteEvent = false;
trackEventCount[trackNum]++;
newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->deltaTime = (absoluteTime - loopPoint);
newTrackEvent->obsoleteEvent = false;
newTrackEvent->contents = NULL;
newTrackEvent->absoluteTime = absoluteTime;
didLoop = true;
}
}
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
bool statusBit = false;
if (eventVal <= 0x7F)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if (eventVal == 0xFF) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x2F) //End of Track Event.
{
endFlag = true;
if (loop && (highestAbsoluteTimeByTrack[trackNum] > loopPoint))
{
TrackEvent* prevEvent = ((TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]-1]));
if (
(prevEvent->type == 0xFF)
&& (prevEvent->contentSize > 0)
&& (prevEvent->contents[0] == 0x2E)
)
{
newTrackEvent = prevEvent;
delete [] newTrackEvent->contents;
newTrackEvent->type = 0xFF;
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2F;
}
else
{
TrackEvent* newTrackEventLast = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]+1]);
newTrackEventLast->absoluteTime = highestAbsoluteTime;
newTrackEventLast->deltaTime = 0;
newTrackEventLast->durationTime = newTrackEvent->durationTime;
newTrackEventLast->obsoleteEvent = newTrackEvent->obsoleteEvent;
newTrackEventLast->type = 0xFF;
newTrackEventLast->contentSize = 1;
newTrackEventLast->contents = new byte[newTrackEventLast->contentSize];
newTrackEventLast->contents[0] = 0x2F;
newTrackEvent->type = 0xFF;
if (highestAbsoluteTime > (prevEvent->absoluteTime + prevEvent->durationTime))
{
newTrackEvent->deltaTime = (highestAbsoluteTime - (prevEvent->absoluteTime + prevEvent->durationTime));
newTrackEvent->absoluteTime = highestAbsoluteTime;
}
else
{
newTrackEvent->deltaTime = 0;
newTrackEvent->absoluteTime = prevEvent->absoluteTime;
}
newTrackEvent->contentSize = 7;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2D;
newTrackEvent->contents[1] = 0xFF;
newTrackEvent->contents[2] = 0xFF;
newTrackEvent->contents[3] = 0x0; // todo write location
newTrackEvent->contents[4] = 0x0;
newTrackEvent->contents[5] = 0x0;
newTrackEvent->contents[6] = 0x0;
newTrackEvent->obsoleteEvent = false;
trackEventCount[trackNum]++;
}
}
else
{
newTrackEvent->type = 0xFF;
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2F;
}
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
}
else if (subType == 0x51) //Set Tempo Event.
{
newTrackEvent->type = 0xFF;
newTrackEvent->contentSize = 4;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x51;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contents[1] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contents[2] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contents[3] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
newTrackEvent->type = 0xFF;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int i = 0; i < length; i++)
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->obsoleteEvent = true;
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
newTrackEvent->type = 0xFF;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
newTrackEvent->obsoleteEvent = true;
}
previousEventValue = eventVal;
}
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
newTrackEvent->type = previousEventValue;
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
newTrackEvent->type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--)
{
if ((trackEvents[trackNum][testBackwards].type == (0x90 | (curEventVal & 0xF))) && !(trackEvents[trackNum][testBackwards].obsoleteEvent))
{
if (trackEvents[trackNum][testBackwards].contents[0] == noteNumber)
{
trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime);
break;
}
}
}
newTrackEvent->durationTime = 0;
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = noteNumber;
newTrackEvent->contents[1] = velocity;
newTrackEvent->obsoleteEvent = true;
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
newTrackEvent->type = previousEventValue;
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
newTrackEvent->type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (velocity == 0)
{
// simulate note off
for (int testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--)
{
if (((trackEvents[trackNum][testBackwards].type == curEventVal)) && !(trackEvents[trackNum][testBackwards].obsoleteEvent))
{
if (trackEvents[trackNum][testBackwards].contents[0] == noteNumber)
{
trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime);
break;
}
}
}
newTrackEvent->durationTime = 0;
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = noteNumber;
newTrackEvent->contents[1] = velocity;
newTrackEvent->obsoleteEvent = true;
}
else
{
// check if no note off received, if so, turn it off and restart note
for (int testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--)
{
if (((trackEvents[trackNum][testBackwards].type == curEventVal)) && !(trackEvents[trackNum][testBackwards].obsoleteEvent))
{
if (trackEvents[trackNum][testBackwards].contents[0] == noteNumber)
{
if (trackEvents[trackNum][testBackwards].durationTime == 0) // means unfinished note
trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime);
break;
}
}
}
newTrackEvent->durationTime = 0; // to be filled in
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = noteNumber;
newTrackEvent->contents[1] = velocity;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change
{
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = controllerType;
newTrackEvent->contents[1] = controllerValue;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
if ((eventVal & 0xF) == 9) // drums in GM
instrument = instrument;
else
instrument = instrument;
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = instrument;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch
{
newTrackEvent->type = eventVal;
byte amount;
if (statusBit)
{
amount = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = amount;
//newTrackEvent->obsoleteEvent = true; // temporary?
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend
{
newTrackEvent->type = eventVal;
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = valueLSB;
newTrackEvent->contents[1] = valueMSB;
//newTrackEvent->obsoleteEvent = true; // temporary?
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xF0 || eventVal == 0xF7)
{
newTrackEvent->type = eventVal;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
newTrackEvent->obsoleteEvent = true;
}
else
{
if (!unknownsHit)
{
MessageBox(NULL, "Invalid midi character found", "Error", NULL);
unknownsHit = true;
}
}
trackEventCount[trackNum]++;
}
}
unsigned long timeOffset = 0;
unsigned long startPosition = 0x84;
// get offsets
for (int i = 0; i < numberTracks; i++)
{
unsigned long sizeData = 0;
int loopStartPosition = 0;
bool foundLoopStart = false;
byte previousTrackEvent = 0x0;
if (trackEventCount[i] > 0)
{
unsigned long tempLong = Flip32Bit(startPosition);
fwrite(&tempLong, 1, 4, outFile);
for (int j = 0; j < trackEventCount[i]; j++)
{
TrackEvent* trackEvent = &(trackEvents[i][j]);
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent->deltaTime + timeOffset), lengthTimeDelta);
if (trackEvent->obsoleteEvent)
{
timeOffset += trackEvent->deltaTime;
}
else
{
if ((trackEvent->type == 0xFF) && (trackEvent->contents[0] == 0x2E))
{
foundLoopStart = true;
loopStartPosition = (startPosition + sizeData + 1 + trackEvent->contentSize + lengthTimeDelta);
}
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent->type == 0xFF) && (trackEvent->contents[0] == 0x2D))
{
unsigned long offsetBack = ((startPosition + sizeData) - loopStartPosition + 8);
trackEvent->contents[3] = ((offsetBack >> 24) & 0xFF);
trackEvent->contents[4] = ((offsetBack >> 16) & 0xFF);
trackEvent->contents[5] = ((offsetBack >> 8) & 0xFF);
trackEvent->contents[6] = ((offsetBack >> 0) & 0xFF);
}
if ((trackEvent->type != previousTrackEvent) || (trackEvent->type == 0xFF))
{
sizeData += 1;
}
sizeData += trackEvent->contentSize;
if ((trackEvent->type >= 0x90) && (trackEvent->type < 0xA0))
{
unsigned long lengthDurationBytes = 0;
unsigned long duration = ReturnVLBytes(trackEvent->durationTime, lengthDurationBytes);
sizeData += lengthDurationBytes;
}
previousTrackEvent = trackEvent->type;
}
}
startPosition += sizeData;
}
else
{
unsigned long zero = 0;
fwrite(&zero, 1, 4, outFile);
}
}
for (int i = numberTracks; i < 32; i++)
{
unsigned long zero = 0;
fwrite(&zero, 1, 4, outFile);
}
unsigned long divisionFlipped = Flip32Bit((unsigned long)tempo);
fwrite(&divisionFlipped, 1, 4, outFile);
//FILE* outDebug = fopen("C:\\GoldeneyeStuff\\GE Editor Source\\debug.txt", "w");
FILE* outDebug = NULL;
for (int i = 0; i < numberTracks; i++)
{
if (trackEventCount[i] > 0)
{
if (outDebug != NULL) fprintf(outDebug, "Track %X\n", i);
byte previousTrackEvent = 0x0;
for (int j = 0; j < trackEventCount[i]; j++)
{
TrackEvent* trackEvent = &(trackEvents[i][j]);
if (trackEvent->obsoleteEvent)
{
timeOffset += trackEvent->deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent->deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, false);
for (int ii = 0; ii < lengthTimeDelta; ii++)
if (outDebug != NULL) fprintf(outDebug, "%02X", ((timeDelta >> ((lengthTimeDelta * 8) - 8 - (ii * 8))) & 0xFF));
if ((trackEvent->type != previousTrackEvent) || (trackEvent->type == 0xFF))
{
fwrite(&trackEvent->type, 1, 1, outFile);
if (outDebug != NULL) fprintf(outDebug, "%02X", trackEvent->type);
}
fwrite(trackEvent->contents, 1, trackEvent->contentSize, outFile);
for (int ii = 0; ii < trackEvent->contentSize; ii++)
{
if (outDebug != NULL) fprintf(outDebug, "%02X", trackEvent->contents[ii]);
}
if ((trackEvent->type >= 0x90) && (trackEvent->type < 0xA0))
{
unsigned long lengthDurationBytes = 0;
unsigned long duration = ReturnVLBytes(trackEvent->durationTime, lengthDurationBytes); // todo real trackevent
WriteVLBytes(outFile, duration, lengthDurationBytes, false);
for (int ii = 0; ii < lengthDurationBytes; ii++)
if (outDebug != NULL) fprintf(outDebug, "%02X", ((duration >> ((lengthDurationBytes * 8) - 8 - (ii * 8))) & 0xFF));
}
if (outDebug != NULL) fprintf(outDebug, "\n");
previousTrackEvent = trackEvent->type;
}
}
}
for (int j = 0; j < trackEventCount[i]; j++)
{
if (trackEvents[i][j].contents != NULL)
{
delete [] trackEvents[i][j].contents;
trackEvents[i][j].contents = NULL;
}
}
}
fflush(outDebug);
fclose(outFile);
// write FEFE in case see FE
outFile = fopen(output, "rb");
if (outFile == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
fseek(outFile, 0, SEEK_END);
int sizeOut = ftell(outFile);
rewind(outFile);
byte* inArray = new byte[sizeOut];
fread(inArray, 1, sizeOut, outFile);
fclose(outFile);
unsigned long offsetheader[0x20];
int extraOffsets[0x20];
for (int x = 0; x < 0x80; x+=4)
{
offsetheader[x/4] = ((((((inArray[x] << 8) | inArray[x+1]) << 8) | inArray[x+2]) << 8) | inArray[x+3]);
extraOffsets[x/4] = 0x00000000;
}
for (int x = 0; x < sizeOut; x++)
{
if (x > 0x84)
{
if (inArray[x] == 0xFE) // need to write twice
{
for (int y = 0; y < numberTracks; y++)
{
if (offsetheader[y] > x)
{
extraOffsets[y]++;
}
}
}
}
}
outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] inArray;
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
for (int x = 0; x < 0x20; x++)
{
WriteLongToBuffer(inArray, x*4, offsetheader[x] + extraOffsets[x]);
}
for (int x = 0; x < sizeOut; x++)
{
fwrite(&inArray[x], 1, 1, outFile);
if (x > 0x84)
{
if (inArray[x] == 0xFE) // need to write twice
fwrite(&inArray[x], 1, 1, outFile);
}
}
fclose(outFile);
delete [] inArray;
//return true;
if (useRepeaters)
{
// "compress"
outFile = fopen(output, "rb");
if (outFile == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
fseek(outFile, 0, SEEK_END);
int sizeIn = ftell(outFile);
rewind(outFile);
inArray = new byte[sizeIn];
fread(inArray, 1, sizeIn, outFile);
fclose(outFile);
unsigned long offset[0x20];
for (int x = 0; x < 0x80; x+=4)
{
offset[x/4] = ((((((inArray[x] << 8) | inArray[x+1]) << 8) | inArray[x+2]) << 8) | inArray[x+3]);
}
unsigned quarternote = ((((((inArray[0x80] << 8) | inArray[0x81]) << 8) | inArray[0x82]) << 8) | inArray[0x83]);
unsigned char* outArray = new unsigned char[sizeIn * 4];
for (int x = 0x0; x < (sizeIn * 4); x++)
{
outArray[x] = 0x0;
}
unsigned long offsetNew[0x20];
for (int x = 0; x < 0x20; x++)
{
offsetNew[x] = 0;
}
int outputSpot = 0x84;
for (int x = 0x0; x < 0x20; x++)
{
if (offset[x] != 0)
{
offsetNew[x] = outputSpot;
int outputStart = outputSpot;
int endSpot = sizeIn;
if (x < 0xF)
{
if (offset[x+1] != 0)
{
endSpot = offset[x+1];
}
}
int y = offset[x];
// loop till end of file
while (y < endSpot)
{
int bestMatchOffset = -1;
int bestMatchLoopCount = -1;
// check from past to now for results
for (int z = outputStart; z < outputSpot; z++)
{
int match = 0;
int matchOffset = 0;
// one spot match start here
while ((outArray[z+matchOffset] == inArray[y+matchOffset]) && ((y+matchOffset) < endSpot) && (outArray[z+matchOffset] != 0xFE) && (outArray[z+matchOffset] != 0xFF) && ((z+matchOffset) < outputSpot))
{
bool seeAnFF = false;
for (int checkFF = y+matchOffset; ((checkFF < endSpot) && (checkFF < (y+matchOffset + 5))); checkFF++)
{
if (inArray[checkFF] == 0xFF)
seeAnFF = true;
}
if (seeAnFF)
{
break;
}
matchOffset++;
}
if ((matchOffset > bestMatchLoopCount) && (matchOffset > 6))
{
bestMatchLoopCount = matchOffset;
bestMatchOffset = z;
}
}
int loopCheck = ((y - offset[x]) / 2);
if (loopCheck > 0xFD)
loopCheck = 0xFD;
if (bestMatchLoopCount > 6)
{
if (bestMatchLoopCount > 0xFD)
bestMatchLoopCount = 0xFD;
outArray[outputSpot++] = 0xFE;
int distBack = ((outputSpot - bestMatchOffset) - 1);
outArray[outputSpot++] = ((distBack >> 8) & 0xFF);
outArray[outputSpot++] = (distBack & 0xFF);
outArray[outputSpot++] = bestMatchLoopCount;
y += bestMatchLoopCount;
}
else
{
// write one
outArray[outputSpot++] = inArray[y];
y++;
}
}
}
else
break;
if ((outputSpot % 4) != 0)
outputSpot += (4 - (outputSpot % 4));
}
// correct loops
for (int x = 0x0; x < 0x20; x++)
{
if (offsetNew[x] != 0)
{
int outputStart = offsetNew[x];
int endSpot = outputSpot;
if (x < 0xF)
{
if (offsetNew[x+1] != 0)
{
endSpot = offsetNew[x+1];
}
}
int y = offsetNew[x];
// loop till end of file
bool foundStart = false;
int startPos = 0;
while (y < endSpot)
{
if ((outArray[y] == 0xFF) && (outArray[y+1] == 0x2E) && (outArray[y+2] == 0x00) && (outArray[y+3] == 0xFF))
{
foundStart = true;
startPos = y + 4;
y+=4;
}
else if ((outArray[y] == 0xFF) && (outArray[y+1] == 0x2D) && (outArray[y+2] == 0xFF) && (outArray[y+3] == 0xFF))
{
if (foundStart)
{
int distance = ((y + 8) - startPos);
WriteLongToBuffer(outArray, y+4, distance);
foundStart = false;
}
y+=8;
}
else
{
y++;
}
}
}
}
for (int x = 0x0; x < 0x20; x++)
{
WriteLongToBuffer(outArray, x*4, offsetNew[x]);
}
WriteLongToBuffer(outArray, 0x80, quarternote);
outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] inArray;
delete [] outArray;
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
for (int x = 0; x < outputSpot; x++)
{
fwrite(&outArray[x], 1, 1, outFile);
}
fclose(outFile);
delete [] inArray;
delete [] outArray;
}
}
catch (...)
{
MessageBox(NULL, "Error converting", "Error", NULL);
return false;
}
return true;
}
bool CMidiParse::MidiToGEFormat(CString input, CString output, bool loop, unsigned long loopPoint, bool useRepeaters)
{
try
{
numberTracks = 0;
for (unsigned int x = 0; x < 0x20; x++)
{
for (int y = 0; y < 0x30000; y++)
{
if (trackEvents[x][y].contents != NULL)
{
delete[] trackEvents[x][y].contents;
trackEvents[x][y].contents = NULL;
}
}
trackEventCount[x] = 0;
}
CString tempFileName = input;
struct stat results;
stat(tempFileName, &results);
FILE* inFile1 = fopen(input, "rb");
if (inFile1 == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
byte* inputMID = new byte[results.st_size];
fread(inputMID, 1, results.st_size, inFile1);
fclose(inFile1);
unsigned long header = CharArrayToLong(&inputMID[0]);
if (header != 0x4D546864)
{
MessageBox(NULL, "Invalid midi hdr", "Error", NULL);
return false;
}
unsigned long headerLength = CharArrayToLong(&inputMID[4]);
unsigned short type = CharArrayToShort(&inputMID[8]);
unsigned short numTracks = CharArrayToShort(&inputMID[0xA]);
unsigned short tempo = CharArrayToShort(&inputMID[0xC]);
if (numTracks > 16)
{
MessageBox(NULL, "Too many tracks, truncated to 16", "Warning", NULL);
numTracks = 16;
}
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return false;
}
numberTracks = numTracks;
if (type == 0)
{
}
else if (type == 1)
{
}
else
{
fclose(outFile);
MessageBox(NULL, "Invalid midi type", "Error", NULL);
return false;
}
int position = 0xE;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool unknownsHit = false;
unsigned long highestAbsoluteTime = 0;
unsigned long highestAbsoluteTimeByTrack[0x10];
for (int x = 0; x < 0x10; x++)
highestAbsoluteTimeByTrack[x] = 0;
for (int trackNum = 0; trackNum < numberTracks; trackNum++)
{
unsigned long absoluteTime = 0;
unsigned long trackHeader = ((((((inputMID[position] << 8) | inputMID[position+1]) << 8) | inputMID[position+2]) << 8) | inputMID[position+3]);
if (trackHeader != 0x4D54726B)
{
MessageBox(NULL, "Invalid track midi hdr", "Error", NULL);
return false;
}
unsigned long trackLength = ((((((inputMID[position+4] << 8) | inputMID[position+5]) << 8) | inputMID[position+6]) << 8) | inputMID[position+7]);
position += 8;
byte previousEventValue = 0xFF;
bool endFlag = false;
while (!endFlag && (position < results.st_size))
{
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
absoluteTime += timeTag;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
bool statusBit = false;
if (eventVal <= 0x7F)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if (eventVal == 0xFF) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x2F) //End of Track Event.
{
// remove time till end
absoluteTime -= timeTag;
endFlag = true;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
}
else if (subType == 0x51) //Set Tempo Event.
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int i = 0; i < length; i++)
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
previousEventValue = eventVal;
}
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change
{
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xF0 || eventVal == 0xF7)
{
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
else
{
if (!unknownsHit)
{
MessageBox(NULL, "Invalid midi character found", "Error", NULL);
unknownsHit = true;
}
}
}
if (absoluteTime > highestAbsoluteTime)
{
highestAbsoluteTime = absoluteTime;
}
if (absoluteTime > highestAbsoluteTimeByTrack[trackNum])
{
highestAbsoluteTimeByTrack[trackNum] = absoluteTime;
}
}
position = 0xE;
repeatPattern = NULL;
altOffset = 0;
altLength = 0;
for (int trackNum = 0; trackNum < numberTracks; trackNum++)
{
unsigned long absoluteTime = 0;
unsigned long trackHeader = ((((((inputMID[position] << 8) | inputMID[position+1]) << 8) | inputMID[position+2]) << 8) | inputMID[position+3]);
if (trackHeader != 0x4D54726B)
{
MessageBox(NULL, "Invalid track midi hdr", "Error", NULL);
return false;
}
unsigned long trackLength = ((((((inputMID[position+4] << 8) | inputMID[position+5]) << 8) | inputMID[position+6]) << 8) | inputMID[position+7]);
position += 8;
byte previousEventValue = 0xFF;
bool endFlag = false;
bool didLoop = false;
if ((loop) && (loopPoint == 0) && (highestAbsoluteTimeByTrack[trackNum] > 0))
{
TrackEvent* newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->type = 0xFF;
newTrackEvent->absoluteTime = 0;
newTrackEvent->contentSize = 3;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2E;
newTrackEvent->contents[1] = 0x00;
newTrackEvent->contents[2] = 0xFF;
newTrackEvent->deltaTime = 0;
newTrackEvent->obsoleteEvent = false;
trackEventCount[trackNum]++;
didLoop = true;
}
while (!endFlag && (position < results.st_size))
{
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
absoluteTime += timeTag;
TrackEvent* newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->deltaTime = timeTag;
newTrackEvent->obsoleteEvent = false;
newTrackEvent->contents = NULL;
newTrackEvent->absoluteTime = absoluteTime;
if ((loop) && (!didLoop) && (highestAbsoluteTimeByTrack[trackNum] > loopPoint))
{
if (absoluteTime == loopPoint)
{
TrackEvent* newTrackEventLoop = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEventLoop->type = 0xFF;
newTrackEventLoop->absoluteTime = absoluteTime;
newTrackEventLoop->contentSize = 3;
newTrackEventLoop->contents = new byte[newTrackEventLoop->contentSize];
newTrackEventLoop->contents[0] = 0x2E;
newTrackEventLoop->contents[1] = 0x00;
newTrackEventLoop->contents[2] = 0xFF;
newTrackEventLoop->deltaTime = timeTag;
newTrackEventLoop->obsoleteEvent = false;
trackEventCount[trackNum]++;
newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->deltaTime = 0;
newTrackEvent->obsoleteEvent = false;
newTrackEvent->contents = NULL;
newTrackEvent->absoluteTime = absoluteTime;
didLoop = true;
}
else if (absoluteTime > loopPoint)
{
TrackEvent* newTrackEventLoop = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEventLoop->type = 0xFF;
newTrackEventLoop->absoluteTime = loopPoint;
newTrackEventLoop->contentSize = 3;
newTrackEventLoop->contents = new byte[newTrackEventLoop->contentSize];
newTrackEventLoop->contents[0] = 0x2E;
newTrackEventLoop->contents[1] = 0x00;
newTrackEventLoop->contents[2] = 0xFF;
if (trackEventCount[trackNum] > 0)
newTrackEventLoop->deltaTime = (loopPoint - ((TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]-1]))->absoluteTime);
else
newTrackEventLoop->deltaTime = loopPoint;
newTrackEventLoop->obsoleteEvent = false;
trackEventCount[trackNum]++;
newTrackEvent = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]]);
newTrackEvent->deltaTime = (absoluteTime - loopPoint);
newTrackEvent->obsoleteEvent = false;
newTrackEvent->contents = NULL;
newTrackEvent->absoluteTime = absoluteTime;
didLoop = true;
}
}
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
bool statusBit = false;
if (eventVal <= 0x7F)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if (eventVal == 0xFF) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x2F) //End of Track Event.
{
endFlag = true;
if (loop && (highestAbsoluteTimeByTrack[trackNum] > loopPoint))
{
TrackEvent* prevEvent = ((TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]-1]));
if (
(prevEvent->type == 0xFF)
&& (prevEvent->contentSize > 0)
&& (prevEvent->contents[0] == 0x2E)
)
{
newTrackEvent = prevEvent;
delete [] newTrackEvent->contents;
newTrackEvent->type = 0xFF;
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2F;
}
else
{
TrackEvent* newTrackEventLast = (TrackEvent*)&(trackEvents[trackNum][trackEventCount[trackNum]+1]);
newTrackEventLast->absoluteTime = highestAbsoluteTime;
newTrackEventLast->deltaTime = 0;
newTrackEventLast->durationTime = newTrackEvent->durationTime;
newTrackEventLast->obsoleteEvent = newTrackEvent->obsoleteEvent;
newTrackEventLast->type = 0xFF;
newTrackEventLast->contentSize = 1;
newTrackEventLast->contents = new byte[newTrackEventLast->contentSize];
newTrackEventLast->contents[0] = 0x2F;
newTrackEvent->type = 0xFF;
if (highestAbsoluteTime > (prevEvent->absoluteTime + prevEvent->durationTime))
{
newTrackEvent->deltaTime = (highestAbsoluteTime - (prevEvent->absoluteTime + prevEvent->durationTime));
newTrackEvent->absoluteTime = highestAbsoluteTime;
}
else
{
newTrackEvent->deltaTime = 0;
newTrackEvent->absoluteTime = prevEvent->absoluteTime;
}
newTrackEvent->contentSize = 7;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2D;
newTrackEvent->contents[1] = 0xFF;
newTrackEvent->contents[2] = 0xFF;
newTrackEvent->contents[3] = 0x0; // todo write location
newTrackEvent->contents[4] = 0x0;
newTrackEvent->contents[5] = 0x0;
newTrackEvent->contents[6] = 0x0;
newTrackEvent->obsoleteEvent = false;
trackEventCount[trackNum]++;
}
}
else
{
newTrackEvent->type = 0xFF;
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x2F;
}
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
}
else if (subType == 0x51) //Set Tempo Event.
{
newTrackEvent->type = 0xFF;
newTrackEvent->contentSize = 4;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = 0x51;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contents[1] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contents[2] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contents[3] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
newTrackEvent->type = 0xFF;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int i = 0; i < length; i++)
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->obsoleteEvent = true;
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
newTrackEvent->type = 0xFF;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
newTrackEvent->obsoleteEvent = true;
}
previousEventValue = eventVal;
}
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
newTrackEvent->type = previousEventValue;
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
newTrackEvent->type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--)
{
if ((trackEvents[trackNum][testBackwards].type == (0x90 | (curEventVal & 0xF))) && !(trackEvents[trackNum][testBackwards].obsoleteEvent))
{
if (trackEvents[trackNum][testBackwards].contents[0] == noteNumber)
{
trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime);
break;
}
}
}
newTrackEvent->durationTime = 0;
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = noteNumber;
newTrackEvent->contents[1] = velocity;
newTrackEvent->obsoleteEvent = true;
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
newTrackEvent->type = previousEventValue;
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
newTrackEvent->type = eventVal;
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (velocity == 0)
{
// simulate note off
for (int testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--)
{
if (((trackEvents[trackNum][testBackwards].type == curEventVal)) && !(trackEvents[trackNum][testBackwards].obsoleteEvent))
{
if (trackEvents[trackNum][testBackwards].contents[0] == noteNumber)
{
trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime);
break;
}
}
}
newTrackEvent->durationTime = 0;
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = noteNumber;
newTrackEvent->contents[1] = velocity;
newTrackEvent->obsoleteEvent = true;
}
else
{
// check if no note off received, if so, turn it off and restart note
for (int testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--)
{
if (((trackEvents[trackNum][testBackwards].type == curEventVal)) && !(trackEvents[trackNum][testBackwards].obsoleteEvent))
{
if (trackEvents[trackNum][testBackwards].contents[0] == noteNumber)
{
if (trackEvents[trackNum][testBackwards].durationTime == 0) // means unfinished note
trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime);
break;
}
}
}
newTrackEvent->durationTime = 0; // to be filled in
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = noteNumber;
newTrackEvent->contents[1] = velocity;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change
{
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = controllerType;
newTrackEvent->contents[1] = controllerValue;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
if ((eventVal & 0xF) == 9) // Drums in GM
instrument = instrument;
else
instrument = instrument;
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = instrument;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch
{
newTrackEvent->type = eventVal;
byte amount;
if (statusBit)
{
amount = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
newTrackEvent->contentSize = 1;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = amount;
//newTrackEvent->obsoleteEvent = true; // temporary?
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend
{
newTrackEvent->type = eventVal;
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
newTrackEvent->type = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->type = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
newTrackEvent->contentSize = 2;
newTrackEvent->contents = new byte[newTrackEvent->contentSize];
newTrackEvent->contents[0] = valueLSB;
newTrackEvent->contents[1] = valueMSB;
//newTrackEvent->obsoleteEvent = true; // temporary?
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xF0 || eventVal == 0xF7)
{
newTrackEvent->type = eventVal;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
newTrackEvent->obsoleteEvent = true;
}
else
{
if (!unknownsHit)
{
MessageBox(NULL, "Invalid midi character found", "Error", NULL);
unknownsHit = true;
}
}
trackEventCount[trackNum]++;
}
}
unsigned long timeOffset = 0;
unsigned long startPosition = 0x44;
// get offsets
for (int i = 0; i < numberTracks; i++)
{
unsigned long sizeData = 0;
int loopStartPosition = 0;
bool foundLoopStart = false;
byte previousTrackEvent = 0x0;
if (trackEventCount[i] > 0)
{
unsigned long tempLong = Flip32Bit(startPosition);
fwrite(&tempLong, 1, 4, outFile);
for (int j = 0; j < trackEventCount[i]; j++)
{
TrackEvent* trackEvent = &(trackEvents[i][j]);
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent->deltaTime + timeOffset), lengthTimeDelta);
if (trackEvent->obsoleteEvent)
{
timeOffset += trackEvent->deltaTime;
}
else
{
if ((trackEvent->type == 0xFF) && (trackEvent->contents[0] == 0x2E))
{
foundLoopStart = true;
loopStartPosition = (startPosition + sizeData + 1 + trackEvent->contentSize + lengthTimeDelta);
}
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent->type == 0xFF) && (trackEvent->contents[0] == 0x2D))
{
unsigned long offsetBack = ((startPosition + sizeData) - loopStartPosition + 8);
trackEvent->contents[3] = ((offsetBack >> 24) & 0xFF);
trackEvent->contents[4] = ((offsetBack >> 16) & 0xFF);
trackEvent->contents[5] = ((offsetBack >> 8) & 0xFF);
trackEvent->contents[6] = ((offsetBack >> 0) & 0xFF);
}
if ((trackEvent->type != previousTrackEvent) || (trackEvent->type == 0xFF))
{
sizeData += 1;
}
sizeData += trackEvent->contentSize;
if ((trackEvent->type >= 0x90) && (trackEvent->type < 0xA0))
{
unsigned long lengthDurationBytes = 0;
unsigned long duration = ReturnVLBytes(trackEvent->durationTime, lengthDurationBytes);
sizeData += lengthDurationBytes;
}
previousTrackEvent = trackEvent->type;
}
}
startPosition += sizeData;
}
else
{
unsigned long zero = 0;
fwrite(&zero, 1, 4, outFile);
}
}
for (int i = numberTracks; i < 16; i++)
{
unsigned long zero = 0;
fwrite(&zero, 1, 4, outFile);
}
unsigned long divisionFlipped = Flip32Bit((unsigned long)tempo);
fwrite(&divisionFlipped, 1, 4, outFile);
//FILE* outDebug = fopen("C:\\GoldeneyeStuff\\GE Editor Source\\debug.txt", "w");
FILE* outDebug = NULL;
for (int i = 0; i < numberTracks; i++)
{
if (trackEventCount[i] > 0)
{
if (outDebug != NULL) fprintf(outDebug, "Track %X\n", i);
byte previousTrackEvent = 0x0;
for (int j = 0; j < trackEventCount[i]; j++)
{
TrackEvent* trackEvent = &(trackEvents[i][j]);
if (trackEvent->obsoleteEvent)
{
timeOffset += trackEvent->deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent->deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, false);
for (int ii = 0; ii < lengthTimeDelta; ii++)
if (outDebug != NULL) fprintf(outDebug, "%02X", ((timeDelta >> ((lengthTimeDelta * 8) - 8 - (ii * 8))) & 0xFF));
if ((trackEvent->type != previousTrackEvent) || (trackEvent->type == 0xFF))
{
fwrite(&trackEvent->type, 1, 1, outFile);
if (outDebug != NULL) fprintf(outDebug, "%02X", trackEvent->type);
}
fwrite(trackEvent->contents, 1, trackEvent->contentSize, outFile);
for (int ii = 0; ii < trackEvent->contentSize; ii++)
{
if (outDebug != NULL) fprintf(outDebug, "%02X", trackEvent->contents[ii]);
}
if ((trackEvent->type >= 0x90) && (trackEvent->type < 0xA0))
{
unsigned long lengthDurationBytes = 0;
unsigned long duration = ReturnVLBytes(trackEvent->durationTime, lengthDurationBytes); // todo real trackevent
WriteVLBytes(outFile, duration, lengthDurationBytes, false);
for (int ii = 0; ii < lengthDurationBytes; ii++)
if (outDebug != NULL) fprintf(outDebug, "%02X", ((duration >> ((lengthDurationBytes * 8) - 8 - (ii * 8))) & 0xFF));
}
if (outDebug != NULL) fprintf(outDebug, "\n");
previousTrackEvent = trackEvent->type;
}
}
}
for (int j = 0; j < trackEventCount[i]; j++)
{
if (trackEvents[i][j].contents != NULL)
{
delete [] trackEvents[i][j].contents;
trackEvents[i][j].contents = NULL;
}
}
}
fflush(outDebug);
fclose(outFile);
// write FEFE in case see FE
outFile = fopen(output, "rb");
if (outFile == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
fseek(outFile, 0, SEEK_END);
int sizeOut = ftell(outFile);
rewind(outFile);
byte* inArray = new byte[sizeOut];
fread(inArray, 1, sizeOut, outFile);
fclose(outFile);
unsigned long offsetheader[0x10];
int extraOffsets[0x10];
for (int x = 0; x < 0x40; x+=4)
{
offsetheader[x/4] = ((((((inArray[x] << 8) | inArray[x+1]) << 8) | inArray[x+2]) << 8) | inArray[x+3]);
extraOffsets[x/4] = 0x00000000;
}
for (int x = 0; x < sizeOut; x++)
{
if (x > 0x44)
{
if (inArray[x] == 0xFE) // need to write twice
{
for (int y = 0; y < numberTracks; y++)
{
if (offsetheader[y] > x)
{
extraOffsets[y]++;
}
}
}
}
}
outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] inArray;
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
for (int x = 0; x < 0x10; x++)
{
WriteLongToBuffer(inArray, x*4, offsetheader[x] + extraOffsets[x]);
}
for (int x = 0; x < sizeOut; x++)
{
fwrite(&inArray[x], 1, 1, outFile);
if (x > 0x44)
{
if (inArray[x] == 0xFE) // need to write twice
fwrite(&inArray[x], 1, 1, outFile);
}
}
fclose(outFile);
delete [] inArray;
//return true;
if (useRepeaters)
{
// "compress"
outFile = fopen(output, "rb");
if (outFile == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
fseek(outFile, 0, SEEK_END);
int sizeIn = ftell(outFile);
rewind(outFile);
inArray = new byte[sizeIn];
fread(inArray, 1, sizeIn, outFile);
fclose(outFile);
unsigned long offset[0x10];
for (int x = 0; x < 0x40; x+=4)
{
offset[x/4] = ((((((inArray[x] << 8) | inArray[x+1]) << 8) | inArray[x+2]) << 8) | inArray[x+3]);
}
unsigned quarternote = ((((((inArray[0x40] << 8) | inArray[0x41]) << 8) | inArray[0x42]) << 8) | inArray[0x43]);
unsigned char* outArray = new unsigned char[sizeIn * 4];
for (int x = 0x0; x < (sizeIn * 4); x++)
{
outArray[x] = 0x0;
}
unsigned long offsetNew[0x10];
for (int x = 0; x < 0x10; x++)
{
offsetNew[x] = 0;
}
int outputSpot = 0x44;
for (int x = 0x0; x < 0x10; x++)
{
if (offset[x] != 0)
{
offsetNew[x] = outputSpot;
int outputStart = outputSpot;
int endSpot = sizeIn;
if (x < 0xF)
{
if (offset[x+1] != 0)
{
endSpot = offset[x+1];
}
}
int y = offset[x];
// loop till end of file
while (y < endSpot)
{
int bestMatchOffset = -1;
int bestMatchLoopCount = -1;
// check from past to now for results
for (int z = outputStart; z < outputSpot; z++)
{
int match = 0;
int matchOffset = 0;
// one spot match start here
while ((outArray[z+matchOffset] == inArray[y+matchOffset]) && ((y+matchOffset) < endSpot) && (outArray[z+matchOffset] != 0xFE) && (outArray[z+matchOffset] != 0xFF) && ((z+matchOffset) < outputSpot))
{
bool seeAnFF = false;
for (int checkFF = y+matchOffset; ((checkFF < endSpot) && (checkFF < (y+matchOffset + 5))); checkFF++)
{
if (inArray[checkFF] == 0xFF)
seeAnFF = true;
}
if (seeAnFF)
{
break;
}
matchOffset++;
}
if ((matchOffset > bestMatchLoopCount) && (matchOffset > 6))
{
bestMatchLoopCount = matchOffset;
bestMatchOffset = z;
}
}
int loopCheck = ((y - offset[x]) / 2);
if (loopCheck > 0xFD)
loopCheck = 0xFD;
if (bestMatchLoopCount > 6)
{
if (bestMatchLoopCount > 0xFD)
bestMatchLoopCount = 0xFD;
outArray[outputSpot++] = 0xFE;
int distBack = ((outputSpot - bestMatchOffset) - 1);
outArray[outputSpot++] = ((distBack >> 8) & 0xFF);
outArray[outputSpot++] = (distBack & 0xFF);
outArray[outputSpot++] = bestMatchLoopCount;
y += bestMatchLoopCount;
}
else
{
// write one
outArray[outputSpot++] = inArray[y];
y++;
}
}
}
else
break;
if ((outputSpot % 4) != 0)
outputSpot += (4 - (outputSpot % 4));
}
// correct loops
for (int x = 0x0; x < 0x10; x++)
{
if (offsetNew[x] != 0)
{
int outputStart = offsetNew[x];
int endSpot = outputSpot;
if (x < 0xF)
{
if (offsetNew[x+1] != 0)
{
endSpot = offsetNew[x+1];
}
}
int y = offsetNew[x];
// loop till end of file
bool foundStart = false;
int startPos = 0;
while (y < endSpot)
{
if ((outArray[y] == 0xFF) && (outArray[y+1] == 0x2E) && (outArray[y+2] == 0x00) && (outArray[y+3] == 0xFF))
{
foundStart = true;
startPos = y + 4;
y+=4;
}
else if ((outArray[y] == 0xFF) && (outArray[y+1] == 0x2D) && (outArray[y+2] == 0xFF) && (outArray[y+3] == 0xFF))
{
if (foundStart)
{
int distance = ((y + 8) - startPos);
WriteLongToBuffer(outArray, y+4, distance);
foundStart = false;
}
y+=8;
}
else
{
y++;
}
}
}
}
for (int x = 0x0; x < 0x10; x++)
{
WriteLongToBuffer(outArray, x*4, offsetNew[x]);
}
WriteLongToBuffer(outArray, 0x40, quarternote);
outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] inArray;
delete [] outArray;
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
for (int x = 0; x < outputSpot; x++)
{
fwrite(&outArray[x], 1, 1, outFile);
}
fclose(outFile);
delete [] inArray;
delete [] outArray;
}
}
catch (...)
{
MessageBox(NULL, "Error converting", "Error", NULL);
return false;
}
return true;
}
unsigned long CMidiParse::Flip32Bit(unsigned long inLong)
{
return (((inLong & 0xFF000000) >> 24) | ((inLong & 0x00FF0000) >> 8) | ((inLong & 0x0000FF00) << 8) | ((inLong & 0x000000FF) << 24));
}
void CMidiParse::WriteLongToBuffer(unsigned char* Buffer, unsigned long address, unsigned long data)
{
Buffer[address] = ((data >> 24) & 0xFF);
Buffer[address+1] = ((data >> 16) & 0xFF);
Buffer[address+2] = ((data >> 8) & 0xFF);
Buffer[address+3] = ((data) & 0xFF);
}
void CMidiParse::WriteShortToBuffer(unsigned char* Buffer, unsigned long address, unsigned short data)
{
Buffer[address] = ((data >> 8) & 0xFF);
Buffer[address+1] = ((data) & 0xFF);
}
unsigned short CMidiParse::CharArrayToShort(unsigned char* currentSpot)
{
return Flip16Bit(*reinterpret_cast<unsigned short*> (currentSpot));
}
unsigned short CMidiParse::Flip16bit(unsigned short tempShort)
{
return (((tempShort & 0xFF00) >> 8) | ((tempShort & 0x00FF) << 8));
}
unsigned long CMidiParse::CharArrayToLong(unsigned char* currentSpot)
{
return Flip32Bit(*reinterpret_cast<unsigned long*> (currentSpot));
}
unsigned char CMidiParse::StringToUnsignedChar(CString inString)
{
inString.Trim();
int tempA = inString.GetLength();
if (inString.GetLength() < 2)
{
CString tempStr = inString;
inString = "";
for (int x = 0; x < (2-tempStr.GetLength()); x++)
{
inString = inString + "0";
}
inString = inString + tempStr;
}
char* b;
b = inString.GetBuffer(0);
unsigned long tempLong = 0;
for (int x = 0;x < 2; x++)
{
char tempChar = b[x];
int hexInt = HexToInt(tempChar);
tempLong = tempLong | hexInt<<((1-x)*4);
}
return (unsigned char) tempLong;
}
unsigned long CMidiParse::StringHexToLong(CString inString)
{
inString.Trim();
int tempA = inString.GetLength();
if (inString.GetLength() < 8)
{
CString tempStr = inString;
inString = "";
for (int x = 0; x < (8-tempStr.GetLength()); x++)
{
inString = inString + "0";
}
inString = inString + tempStr;
}
char* b;
b = inString.GetBuffer(0);
unsigned long tempLong = 0;
for (int x = 0;x < 8; x++)
{
char tempChar = b[x];
int hexInt = HexToInt(tempChar);
tempLong = tempLong | hexInt<<((7-x)*4);
}
return tempLong;
}
void CMidiParse::GEMidiToDebugTextFile(byte* inputMID, int inputSize, CString textFileOut, bool extendTracksToHighest)
{
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return;
}
unsigned long lengthHeader = 0x44;
fprintf(outFile, "Offset Start Midi Events: %08X \n", lengthHeader);
fprintf(outFile, "Tracks\n");
// parse midi
int counterTrack = 0;
int highestTrackLength = 0;
for (int iii = 0; iii < (lengthHeader - 4); iii+=4) // ignore last 00000180
{
unsigned long absoluteTime = 0;
unsigned long offset = CharArrayToLong(&inputMID[iii]);
int position = offset;
if (position != 0)
{
int previousEventValue = 0;
std::map<int, int> loopEndsWithCount;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
int timePosition = position;
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
absoluteTime += timeTag;
if (absoluteTime > highestTrackLength)
highestTrackLength = absoluteTime;
int vlLength = 0;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
if ((loopCount == 0xFF) || (loopCount == 0x00))
{
break;
}
else
{
std::map<int, int>::iterator it = loopEndsWithCount.find(position);
if (it != loopEndsWithCount.end())
{
int countLeft = it->second;
if (countLeft == 0)
{
loopEndsWithCount.erase(it);
}
else
{
loopEndsWithCount[position] = (countLeft - 1);
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
else
{
loopEndsWithCount[position] = loopCount - 1;
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
}
else
{
loopEndsWithCount.erase(it);
}
}
}
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true); // Always FF
}
else if (subType == 0x2F)
{
endFlag = true;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
{
controllerType = eventVal;
previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
{
instrument = eventVal;
previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
{
amount = eventVal;
previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
if (statusBit)
{
valueLSB = eventVal;
previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
}
}
}
}
for (int i = 0; i < (lengthHeader - 4); i+=4) // ignore last 00000180
{
unsigned long offset = CharArrayToLong(&inputMID[i]);
fprintf(outFile, "Track %X Offset %X: Track Offset %08X\n", counterTrack, i, offset);
int position = offset;
if (position != 0)
{
int previousEventValue = 0;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
std::map<int, int> loopEndsWithCount;
int timeAbsolute = 0;
bool endFlag = false;
while ((position < inputSize) && !endFlag)
{
int timePosition = position;
if (extendTracksToHighest)
{
if (timeAbsolute >= highestTrackLength)
{
endFlag = true;
break;
}
}
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (extendTracksToHighest)
{
if ((timeAbsolute + timeTag) > highestTrackLength)
{
endFlag = true;
break;
}
}
timeAbsolute += timeTag;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
fprintf(outFile, "Offset: %08X - Event Delta Time: %d -Abs %d (%08X) - ", timePosition, timeTag, timeAbsolute, original);
}
else
{
statusBit = false;
fprintf(outFile, "Offset: %08X - Event Delta Time: %d -Abs %d (%08X) - ", timePosition, timeTag, timeAbsolute, original);
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x51) // tempo
{
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
int MICROSECONDS_PER_MINUTE = 60000000;
float beatsPerMinute = (float)MICROSECONDS_PER_MINUTE / (float)microsecondsSinceQuarterNote;
if (statusBit)
fprintf(outFile, "!%02X%06X - MicroSecondSinceQuarterNote %d (BPM: %f)\n", subType, microsecondsSinceQuarterNote, microsecondsSinceQuarterNote, beatsPerMinute);
else
fprintf(outFile, "%02X%02X%06X - MicroSecondSinceQuarterNote %d (BPM: %f)\n", eventVal, subType, microsecondsSinceQuarterNote, microsecondsSinceQuarterNote, beatsPerMinute);
}
else if (subType == 0x2D) // end loop
{
byte loopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte currentLoopCount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long offsetToBeginningLoop = ((((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false));
if (statusBit)
fprintf(outFile, "!%02X%02X%02X%08X Count %u LoopCount %u OffsetBeginning %u (%04X)", subType, loopCount, currentLoopCount, offsetToBeginningLoop, loopCount, currentLoopCount, offsetToBeginningLoop, (position - offsetToBeginningLoop));
else
fprintf(outFile, "%02X%02X%02X%02X%08X Count %u LoopCount %u OffsetBeginning %u (%04X)", eventVal, subType, loopCount, currentLoopCount, offsetToBeginningLoop, loopCount, currentLoopCount, offsetToBeginningLoop, (position - offsetToBeginningLoop));
//meta status byte (0xFF), a loop end subtype byte (0x2D), a loop count byte (0-255), a current loop count (should be the same as the loop count byte), and four bytes that specify the number of bytes difference between the end of the loop end event, and the begining of the loop start event. (note that if this value is calculated before the pattern matching compression takes place, this value will have to be adjusted to compensate for any compression of data that takes place between the loop end and the loop start.) The loop count value should be a zero to loop forever, otherwise it should be set to one less than the number of times the section should repeat. (i.e. to hear a section eight times, you would set the loop count to seven.)
if ((loopCount == 0xFF) || (loopCount == 0x00))
{
if (extendTracksToHighest)
{
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
fprintf(outFile, " ...Going to %08X", position);
}
}
}
else
{
std::map<int, int>::iterator it = loopEndsWithCount.find(position);
if (it != loopEndsWithCount.end())
{
int countLeft = it->second;
if (countLeft == 0)
{
loopEndsWithCount.erase(it);
}
else
{
loopEndsWithCount[position] = (countLeft - 1);
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
fprintf(outFile, " ...Going to %08X for count left of %02X", position, loopEndsWithCount[position]);
}
else
{
loopEndsWithCount.erase(it);
}
}
}
else
{
loopEndsWithCount[position] = loopCount - 1;
if (repeatPattern == NULL)
{
position = position - offsetToBeginningLoop;
fprintf(outFile, " ...Going to %08X for count left of %02X", position, loopEndsWithCount[position]);
}
else
{
loopEndsWithCount.erase(it);
}
}
}
fprintf(outFile, "\n");
}
else if (subType == 0x2E) // start loop
{
byte loopNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte endLoop = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
fprintf(outFile, "!%02X%02X%02X Loop #%u\n", subType, loopNumber, endLoop, loopNumber);
else
fprintf(outFile, "%02X%02X%02X%02X Loop #%u\n", eventVal, subType, loopNumber, endLoop, loopNumber);
}
else if (subType == 0x2F)
{
if (statusBit)
fprintf(outFile, "!%02X End of Track\n", subType);
else
fprintf(outFile, "%02X%02X End of Track\n", eventVal, subType);
endFlag = true;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte noteNumber;
if (statusBit)
noteNumber = eventVal;
else
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
unsigned long timeDuration = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
if (statusBit)
fprintf(outFile, "!%02X%02X Duration (%X) - Midi Channel %d NoteNumber %d Velocity %d Duration %d\n", noteNumber, velocity, timeDuration, (previousEventValue&0xF), noteNumber, velocity, timeDuration);
else
fprintf(outFile, "%02X%02X%02X Duration (%X) - Midi Channel %d NoteNumber %d Velocity %d Duration %d\n", eventVal, noteNumber, velocity, timeDuration, (eventVal&0xF), noteNumber, velocity, timeDuration);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
controllerType = eventVal;
else
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (controllerType == 0x00) controllerTypeText = "BankSelect";
else if (controllerType == 0x01) controllerTypeText = "Modulation";
else if (controllerType == 0x02) controllerTypeText = "BreathController";
else if (controllerType == 0x04) controllerTypeText = "FootController";
else if (controllerType == 0x05) controllerTypeText = "PortamentoTime";
else if (controllerType == 0x06) controllerTypeText = "DataEntryMSB";
else if (controllerType == 0x07) controllerTypeText = "MainVolume";
else if (controllerType == 0x08) controllerTypeText = "Balance";
else if (controllerType == 0x0A) controllerTypeText = "Pan";
else if (controllerType == 0x0B) controllerTypeText = "ExpressionController";
else if (controllerType == 0x0C) controllerTypeText = "EffectControl1";
else if (controllerType == 0x0D) controllerTypeText = "EffectControl2";
else if ((controllerType >= 0x10) && (controllerType <= 0x13)) controllerTypeText = "General-PurposeControllers01/04/09";
else if ((controllerType >= 0x20) && (controllerType <= 0x3F)) controllerTypeText = "LSBforcontrollers0-31";
else if (controllerType == 0x40) controllerTypeText = "Damperpedalsustain";
else if (controllerType == 0x41) controllerTypeText = "Portamento";
else if (controllerType == 0x42) controllerTypeText = "Sostenuto";
else if (controllerType == 0x43) controllerTypeText = "SoftPedal";
else if (controllerType == 0x44) controllerTypeText = "LegatoFootswitch";
else if (controllerType == 0x45) controllerTypeText = "Hold2";
else if (controllerType == 0x46) controllerTypeText = "SoundController1default:TimberVariation";
else if (controllerType == 0x47) controllerTypeText = "SoundController2default:Timber/HarmonicContent";
else if (controllerType == 0x48) controllerTypeText = "SoundController3default:ReleaseTime";
else if (controllerType == 0x49) controllerTypeText = "SoundController4default:AttackTime";
else if ((controllerType >= 0x4A) && (controllerType <= 0x4F)) controllerTypeText = "SoundController06/10/09";
else if ((controllerType >= 0x50) && (controllerType <= 0x53)) controllerTypeText = "General-PurposeControllers05/08/09";
else if (controllerType == 0x54) controllerTypeText = "PortamentoControl";
else if (controllerType == 0x5B) controllerTypeText = "Effects1DepthformerlyExternalEffectsDepth";
else if (controllerType == 0x5C) controllerTypeText = "Effects2DepthformerlyTremoloDepth";
else if (controllerType == 0x5D) controllerTypeText = "Effects3DepthformerlyChorusDepth";
else if (controllerType == 0x5E) controllerTypeText = "Effects4DepthformerlyCelesteDetune";
else if (controllerType == 0x5F) controllerTypeText = "Effects5DepthformerlyPhaserDepth";
else if (controllerType == 0x60) controllerTypeText = "DataIncrement";
else if (controllerType == 0x61) controllerTypeText = "DataDecrement";
else if (controllerType == 0x62) controllerTypeText = "Non-RegisteredParameterNumberLSB";
else if (controllerType == 0x63) controllerTypeText = "Non-RegisteredParameterNumberMSB";
else if (controllerType == 0x64) controllerTypeText = "RegisteredParameterNumberLSB";
else if (controllerType == 0x65) controllerTypeText = "RegisteredParameterNumberMSB";
else if ((controllerType >= 0x79) && (controllerType <= 0x7F)) controllerTypeText = "ModeMessages";
if (statusBit)
fprintf(outFile, "!%02X%02X - Midi Channel %d ControllerType %d (%s) Value %d\n", controllerType, controllerValue, (previousEventValue&0xF), controllerType, controllerTypeText, controllerValue);
else
fprintf(outFile, "%02X%02X%02X - Midi Channel %d ControllerType %d (%s) Value %d\n", eventVal, controllerType, controllerValue, (eventVal&0xF), controllerType, controllerTypeText, controllerValue);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
instrument = eventVal;
else
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
{
if ((previousEventValue & 0xF) == 9)
fprintf(outFile, "!%02X - Midi Channel %d Instrument %d\n", instrument, (previousEventValue&0xF), instrument);
else
fprintf(outFile, "!%02X - Midi Channel %d Instrument %d\n", instrument, (previousEventValue&0xF), instrument);
}
else
{
if ((eventVal & 0xF) == 9)
fprintf(outFile, "%02X%02X - Midi Channel %d Instrument %d\n", eventVal, instrument, (eventVal&0xF), instrument);
else
fprintf(outFile, "%02X%02X - Midi Channel %d Instrument %d\n", eventVal, instrument, (eventVal&0xF), instrument);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
amount = eventVal;
else
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
{
if ((previousEventValue & 0xF) == 9)
fprintf(outFile, "!%02X - Midi Channel %d Amount %d\n", amount, (previousEventValue&0xF), amount);
else
fprintf(outFile, "!%02X - Midi Channel %d Amount %d\n", amount, (previousEventValue&0xF), amount);
}
else
{
if ((eventVal & 0xF) == 9)
fprintf(outFile, "%02X%02X - Midi Channel %d Amount %d\n", eventVal, amount, (eventVal&0xF), amount);
else
fprintf(outFile, "%02X%02X - Midi Channel %d Amount %d\n", eventVal, amount, (eventVal&0xF), amount);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte lsb;
if (statusBit)
lsb = eventVal;
else
lsb = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte msb = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
{
if ((previousEventValue & 0xF) == 9)
fprintf(outFile, "!%02X%02X - Midi Channel %d lsb %d msb %d\n", lsb, msb, (previousEventValue&0xF), lsb, msb);
else
fprintf(outFile, "!%02X%02X - Midi Channel %d lsb %d msb %d\n", lsb, msb, (previousEventValue&0xF), lsb, msb);
}
else
{
if ((eventVal & 0xF) == 9)
fprintf(outFile, "%02X%02X%02X - Midi Channel %d lsb %d msb %d\n", eventVal, lsb, msb, (eventVal&0xF), lsb, msb);
else
fprintf(outFile, "%02X%02X%02X - Midi Channel %d lsb %d msb %d\n", eventVal, lsb, msb, (eventVal&0xF), lsb, msb);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
fprintf(outFile, "%02X ERROR MISSING PARSE OF TYPE\n", eventVal);
}
}
}
else
{
fprintf(outFile, "No Track Data\n");
}
fprintf(outFile, "\n");
counterTrack++;
}
fclose(outFile);
}
void CMidiParse::GEMidiToDebugTextFile(CString midiFile, CString textFileOut, bool extendTracksToHighest)
{
CString filepath = midiFile;
FILE* inFile = fopen(filepath, "rb");
if (inFile == NULL)
{
MessageBox(NULL, "Can't read input file " + filepath, "Error", NULL);
return;
}
fseek(inFile, 0, SEEK_END);
int inputSize = ftell(inFile);
rewind(inFile);
unsigned char* inputMID = new unsigned char[inputSize];
fread(inputMID, 1, inputSize, inFile);
fclose(inFile);
GEMidiToDebugTextFile(inputMID, inputSize, textFileOut, extendTracksToHighest);
delete [] inputMID;
}
void CMidiParse::MidiToDebugTextFile(CString midiFile, CString textFileOut)
{
CString tempFileName = midiFile;
struct stat results;
stat(tempFileName, &results);
FILE* inFile1 = fopen(midiFile, "rb");
if (inFile1 == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return;
}
byte* inputMID = new byte[results.st_size];
fread(inputMID, 1, results.st_size, inFile1);
fclose(inFile1);
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
delete [] inputMID;
MessageBox(NULL, "Error outputting file", "Error", NULL);
return;
}
if (CharArrayToLong(&inputMID[0]) != 0x4D546864)
{
delete [] inputMID;
fflush(outFile);
fclose(outFile);
MessageBox(NULL, "Invalid Midi MThd header", "Error", NULL);
return;
}
int lengthHeader = CharArrayToShort(&inputMID[6]);
int numTracks = CharArrayToShort(&inputMID[0xA]);
int division = CharArrayToShort(&inputMID[0xC]);
fprintf(outFile, "MThd Header Size %08X, Format %02X, # Tracks %02X, Division %04X\n", lengthHeader, CharArrayToShort(&inputMID[8]), numTracks, division);
fprintf(outFile, "Tracks\n");
// parse midi
int truePosition = 8 + lengthHeader;
int counterTrack = 0;
for (int i = 0; i < numTracks; i++)
{
if (CharArrayToLong(&inputMID[truePosition]) != 0x4D54726B)
{
delete [] inputMID;
fclose(outFile);
MessageBox(NULL, "Invalid Midi MTrk header", "Error", NULL);
return;
}
unsigned long midiTrackSize = CharArrayToLong(&inputMID[truePosition + 4]);
if ((truePosition + 8 + midiTrackSize) > results.st_size)
{
delete [] inputMID;
MessageBox(NULL, "Too big midi track", "Error", NULL);
fclose(outFile);
return;
}
unsigned long offset = truePosition + 8;
fprintf(outFile, "Track %X Offset %X: Track Offset %08X\n", counterTrack, i, offset);
int position = offset;
if (position != 0)
{
int previousEventValue = 0;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
int timeAbsolute = 0;
bool endFlag = false;
while ((position < results.st_size) && !endFlag)
{
int timePosition = position;
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, true);
timeAbsolute += timeTag;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
bool statusBit = false;
if (eventVal < 0x80)
{
// continuation
statusBit = true;
fprintf(outFile, "Offset: %08X - Event Delta Time: %d -Abs %d (%08X) - ", timePosition, timeTag, timeAbsolute, original);
}
else
{
statusBit = false;
fprintf(outFile, "Offset: %08X - Event Delta Time: %d -Abs %d (%08X) - ", timePosition, timeTag, timeAbsolute, original);
}
if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) // meta event
{
byte subType;
if (statusBit)
subType = eventVal;
else
subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (subType == 0x2F) //End of Track Event.
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
if (statusBit)
fprintf(outFile, "!%02X End of Track\n", subType);
else
fprintf(outFile, "%02X%02X End of Track\n", eventVal, subType);
endFlag = true;
}
else if (subType == 0x51) //Set Tempo Event.
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int microsecondsSinceQuarterNote = ((((ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true)) << 8) | ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true));
int MICROSECONDS_PER_MINUTE = 60000000;
float beatsPerMinute = (float)MICROSECONDS_PER_MINUTE / (float)microsecondsSinceQuarterNote;
if (statusBit)
fprintf(outFile, "!%02X%06X - MicroSecondSinceQuarterNote %d (BPM: %f)\n", subType, microsecondsSinceQuarterNote, microsecondsSinceQuarterNote, beatsPerMinute);
else
fprintf(outFile, "%02X%02X%06X - MicroSecondSinceQuarterNote %d (BPM: %f)\n", eventVal, subType, microsecondsSinceQuarterNote, microsecondsSinceQuarterNote, beatsPerMinute);
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (statusBit)
fprintf(outFile, "!%02X Unused Meta Events ", subType);
else
fprintf(outFile, "%02X%02X Unused Meta Events ", eventVal, subType);
for (int i = 0; i < length; i++)
{
unsigned char tempByte = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
fprintf(outFile, "%02X", tempByte);
}
fprintf(outFile, "\n");
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
if (statusBit)
fprintf(outFile, "!%02X Unused Sequencer Specific Event ", subType);
else
fprintf(outFile, "%02X%02X Unused Sequencer Specific Event ", eventVal, subType);
// subtract length
for (int i = 0; i < length; i++)
{
unsigned char tempByte = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
fprintf(outFile, "%02X", tempByte);
}
fprintf(outFile, "\n");
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80) && (previousEventValue < 0x90)))
{
byte noteNumber;
if (statusBit)
noteNumber = eventVal;
else
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
fprintf(outFile, "!%02X%02X - Midi Channel OFF %d NoteNumber %d Velocity %d\n", noteNumber, velocity, (previousEventValue&0xF), noteNumber, velocity);
else
fprintf(outFile, "%02X%02X%02X - Midi Channel OFF %d NoteNumber %d Velocity %d\n", eventVal, noteNumber, velocity, (eventVal&0xF), noteNumber, velocity);
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0)))
{
byte noteNumber;
if (statusBit)
noteNumber = eventVal;
else
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
fprintf(outFile, "!%02X%02X - Midi Channel ON %d NoteNumber %d Velocity %d\n", noteNumber, velocity, (previousEventValue&0xF), noteNumber, velocity);
else
fprintf(outFile, "%02X%02X%02X - Midi Channel ON %d NoteNumber %d Velocity %d\n", eventVal, noteNumber, velocity, (eventVal&0xF), noteNumber, velocity);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change
{
CString controllerTypeText = "";
byte controllerType;
if (statusBit)
controllerType = eventVal;
else
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (controllerType == 0x00) controllerTypeText = "BankSelect";
else if (controllerType == 0x01) controllerTypeText = "Modulation";
else if (controllerType == 0x02) controllerTypeText = "BreathController";
else if (controllerType == 0x04) controllerTypeText = "FootController";
else if (controllerType == 0x05) controllerTypeText = "PortamentoTime";
else if (controllerType == 0x06) controllerTypeText = "DataEntryMSB";
else if (controllerType == 0x07) controllerTypeText = "MainVolume";
else if (controllerType == 0x08) controllerTypeText = "Balance";
else if (controllerType == 0x0A) controllerTypeText = "Pan";
else if (controllerType == 0x0B) controllerTypeText = "ExpressionController";
else if (controllerType == 0x0C) controllerTypeText = "EffectControl1";
else if (controllerType == 0x0D) controllerTypeText = "EffectControl2";
else if ((controllerType >= 0x10) && (controllerType <= 0x13)) controllerTypeText = "General-PurposeControllers01/04/09";
else if ((controllerType >= 0x20) && (controllerType <= 0x3F)) controllerTypeText = "LSBforcontrollers0-31";
else if (controllerType == 0x40) controllerTypeText = "Damperpedalsustain";
else if (controllerType == 0x41) controllerTypeText = "Portamento";
else if (controllerType == 0x42) controllerTypeText = "Sostenuto";
else if (controllerType == 0x43) controllerTypeText = "SoftPedal";
else if (controllerType == 0x44) controllerTypeText = "LegatoFootswitch";
else if (controllerType == 0x45) controllerTypeText = "Hold2";
else if (controllerType == 0x46) controllerTypeText = "SoundController1default:TimberVariation";
else if (controllerType == 0x47) controllerTypeText = "SoundController2default:Timber/HarmonicContent";
else if (controllerType == 0x48) controllerTypeText = "SoundController3default:ReleaseTime";
else if (controllerType == 0x49) controllerTypeText = "SoundController4default:AttackTime";
else if ((controllerType >= 0x4A) && (controllerType <= 0x4F)) controllerTypeText = "SoundController06/10/09";
else if ((controllerType >= 0x50) && (controllerType <= 0x53)) controllerTypeText = "General-PurposeControllers05/08/09";
else if (controllerType == 0x54) controllerTypeText = "PortamentoControl";
else if (controllerType == 0x5B) controllerTypeText = "Effects1DepthformerlyExternalEffectsDepth";
else if (controllerType == 0x5C) controllerTypeText = "Effects2DepthformerlyTremoloDepth";
else if (controllerType == 0x5D) controllerTypeText = "Effects3DepthformerlyChorusDepth";
else if (controllerType == 0x5E) controllerTypeText = "Effects4DepthformerlyCelesteDetune";
else if (controllerType == 0x5F) controllerTypeText = "Effects5DepthformerlyPhaserDepth";
else if (controllerType == 0x60) controllerTypeText = "DataIncrement";
else if (controllerType == 0x61) controllerTypeText = "DataDecrement";
else if (controllerType == 0x62) controllerTypeText = "Non-RegisteredParameterNumberLSB";
else if (controllerType == 0x63) controllerTypeText = "Non-RegisteredParameterNumberMSB";
else if (controllerType == 0x64) controllerTypeText = "RegisteredParameterNumberLSB";
else if (controllerType == 0x65) controllerTypeText = "RegisteredParameterNumberMSB";
else if ((controllerType >= 0x79) && (controllerType <= 0x7F)) controllerTypeText = "ModeMessages";
if (statusBit)
fprintf(outFile, "!%02X%02X - Midi Channel %d ControllerType %d (%s) Value %d\n", controllerType, controllerValue, (previousEventValue&0xF), controllerType, controllerTypeText, controllerValue);
else
fprintf(outFile, "%02X%02X%02X - Midi Channel %d ControllerType %d (%s) Value %d\n", eventVal, controllerType, controllerValue, (eventVal&0xF), controllerType, controllerTypeText, controllerValue);
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument
{
byte instrument;
if (statusBit)
instrument = eventVal;
else
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
{
if ((previousEventValue & 0xF) == 9)
fprintf(outFile, "!%02X - Midi Channel %d Instrument %d\n", instrument, (previousEventValue&0xF), instrument);
else
fprintf(outFile, "!%02X - Midi Channel %d Instrument %d\n", instrument, (previousEventValue&0xF), instrument);
}
else
{
if ((eventVal & 0xF) == 9)
fprintf(outFile, "%02X%02X - Midi Channel %d Instrument %d\n", eventVal, instrument, (eventVal&0xF), instrument);
else
fprintf(outFile, "%02X%02X - Midi Channel %d Instrument %d\n", eventVal, instrument, (eventVal&0xF), instrument);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch
{
byte amount;
if (statusBit)
amount = eventVal;
else
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
{
if ((previousEventValue & 0xF) == 9)
fprintf(outFile, "!%02X - Channel Aftertouch %d Amount %d\n", amount, (previousEventValue&0xF), amount);
else
fprintf(outFile, "!%02X - Channel Aftertouch %d Amount %d\n", amount, (previousEventValue&0xF), amount);
}
else
{
if ((eventVal & 0xF) == 9)
fprintf(outFile, "%02X%02X - Channel Aftertouch %d Amount %d\n", eventVal, amount, (eventVal&0xF), amount);
else
fprintf(outFile, "%02X%02X - Channel Aftertouch %d Amount %d\n", eventVal, amount, (eventVal&0xF), amount);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend
{
byte lsb;
if (statusBit)
lsb = eventVal;
else
lsb = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
byte msb = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, true);
if (statusBit)
{
if ((previousEventValue & 0xF) == 9)
fprintf(outFile, "!%02X%02X - Pitch Bend %d lsb %d msb %d\n", lsb, msb, (previousEventValue&0xF), lsb, msb);
else
fprintf(outFile, "!%02X%02X - Pitch Bend %d lsb %d msb %d\n", lsb, msb, (previousEventValue&0xF), lsb, msb);
}
else
{
if ((eventVal & 0xF) == 9)
fprintf(outFile, "%02X%02X%02X - Pitch Bend %d lsb %d msb %d\n", eventVal, lsb, msb, (eventVal&0xF), lsb, msb);
else
fprintf(outFile, "%02X%02X%02X - Pitch Bend %d lsb %d msb %d\n", eventVal, lsb, msb, (eventVal&0xF), lsb, msb);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xFE) // repeat operation
{
// should not be here...
// no prev event set
}
else
{
fprintf(outFile, "%02X ERROR MISSING PARSE OF TYPE\n", eventVal);
}
}
}
else
{
fprintf(outFile, "No Track Data\n");
}
fprintf(outFile, "\n");
counterTrack++;
truePosition = truePosition + 8 + midiTrackSize;
}
fclose(outFile);
}
void CMidiParse::GenerateTestPattern(int type, CString outputFile)
{
try
{
FILE* outFile = fopen(outputFile, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Error outputting file", "Error", NULL);
return;
}
// parse midi
unsigned long tempLong = Flip32Bit(0x4D546864);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00000006);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00010000 | 0x0001); // num tracks
fwrite(&tempLong, 1 ,4 , outFile);
unsigned long division = 0x01E0;
unsigned short tempShort = division;
tempShort = Flip16Bit(tempShort);
fwrite(&tempShort, 1 ,2 , outFile);
unsigned long absoluteTime = 0;
int trackEventCount = 0;
TrackEvent* trackEvents = new TrackEvent[0x30000];
for (int j = 0; j < 0x30000; j++)
trackEvents[j].contents = NULL;
int position = 4;
tempLong = Flip32Bit(0x4D54726B);
fwrite(&tempLong, 1 ,4 , outFile);
int trackNumber = 1;
int instrumentNumber = 0;
float tempo = 120;
unsigned long tempoVal = 60000000.0 / tempo;
trackEvents[trackEventCount].type = 0xFF;
trackEvents[trackEventCount].contentSize = 5;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = 0x51;
trackEvents[trackEventCount].contents[1] = 0x3;
trackEvents[trackEventCount].contents[2] = (tempoVal >> 16) & 0xFF;
trackEvents[trackEventCount].contents[3] = (tempoVal >> 8) & 0xFF;
trackEvents[trackEventCount].contents[4] = (tempoVal) & 0xFF;
trackEventCount++;
trackEvents[trackEventCount].type = 0xC0 | trackNumber;
trackEvents[trackEventCount].contentSize = 1;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = instrumentNumber;
trackEventCount++;
byte controllerType = 0x07;
byte controllerValue = 0x7F;
trackEvents[trackEventCount].type = 0xB0 | trackNumber;
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = controllerType;
trackEvents[trackEventCount].contents[1] = controllerValue;
trackEventCount++;
if ((type == 0) || (type == 1) || (type == 2))
{
for (unsigned char note = 0x18; note < 0x78; note++)
{
if (type == 0)
{
trackEvents[trackEventCount].deltaTime = 0;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x90 | trackNumber;
byte velocity = 0x7F;
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
trackEvents[trackEventCount].deltaTime = 10;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x90 | trackNumber;
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note - 5;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
trackEvents[trackEventCount].deltaTime = 10;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x80 | trackNumber;
velocity = 0x2F;
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
trackEvents[trackEventCount].deltaTime = 10;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x80 | trackNumber;
velocity = 0x2F;
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note - 5;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
}
else if (type == 1)
{
trackEvents[trackEventCount].deltaTime = 200;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x90 | trackNumber;
byte velocity = 0x7F;
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
trackEvents[trackEventCount].deltaTime = 200;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x80 | trackNumber;
velocity = 0x2F;
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
}
else if (type == 2)
{
trackEvents[trackEventCount].deltaTime = 200;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x90 | trackNumber;
byte velocity = 0x7F;
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = 0x78;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
trackEvents[trackEventCount].deltaTime = 200;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x80 | trackNumber;
velocity = 0x2F;
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = 0x78;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
}
}
}
else if (type == 3)
{
int note = 0x78;
for (int x = 0; x < 2000; x+=10)
{
trackEvents[trackEventCount].deltaTime = 0;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x90 | trackNumber;
byte velocity = 0x7F; // seems ignored on import
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
trackEvents[trackEventCount].deltaTime = x;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x80 | trackNumber;
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
}
trackEvents[trackEventCount].deltaTime = 0;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x90 | trackNumber;
byte velocity = 0x7F; // seems ignored on import
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
trackEvents[trackEventCount].deltaTime = 48;
trackEvents[trackEventCount].obsoleteEvent = false;
absoluteTime += trackEvents[trackEventCount].deltaTime;
trackEvents[trackEventCount].absoluteTime = absoluteTime;
trackEvents[trackEventCount].type = 0x80 | trackNumber;
trackEvents[trackEventCount].durationTime = 0; // to be filled in
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = note;
trackEvents[trackEventCount].contents[1] = velocity;
trackEventCount++;
}
trackEvents[trackEventCount].type = 0xFF;
trackEvents[trackEventCount].contentSize = 2;
trackEvents[trackEventCount].contents = new byte[trackEvents[trackEventCount].contentSize];
trackEvents[trackEventCount].contents[0] = 0x2F;
trackEvents[trackEventCount].contents[1] = 0x0;
trackEventCount++;
unsigned long timeOffset = 0;
unsigned long sizeData = 0;
byte previousTrackEvent = 0x0;
for (int j = 0; j < trackEventCount; j++)
{
TrackEvent trackEvent = trackEvents[j];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
sizeData += lengthTimeDelta;
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type >= 0xF0))
{
sizeData += 1;
}
sizeData += trackEvent.contentSize;
previousTrackEvent = trackEvent.type;
}
}
tempLong = Flip32Bit(sizeData);
fwrite(&tempLong,1, 4, outFile);
timeOffset = 0;
previousTrackEvent = 0x0;
for (int eventCount = 0; eventCount < trackEventCount; eventCount++)
{
TrackEvent trackEvent = trackEvents[eventCount];
if (trackEvent.obsoleteEvent)
{
timeOffset += trackEvent.deltaTime;
}
else
{
unsigned long lengthTimeDelta = 0;
unsigned long timeDelta = ReturnVLBytes((trackEvent.deltaTime + timeOffset), lengthTimeDelta);
timeOffset = 0;
WriteVLBytes(outFile, timeDelta, lengthTimeDelta, false);
if ((trackEvent.type != previousTrackEvent) || (trackEvent.type >= 0xF0))
{
fwrite(&trackEvent.type, 1, 1, outFile);
}
fwrite(trackEvent.contents, 1, trackEvent.contentSize, outFile);
previousTrackEvent = trackEvent.type;
}
}
for (int eventCount = 0; eventCount < trackEventCount; eventCount++)
{
if (trackEvents[eventCount].contents != NULL)
{
delete [] trackEvents[eventCount].contents;
trackEvents[eventCount].contents = NULL;
}
}
delete [] trackEvents;
// just one track
fflush(outFile);
fclose(outFile);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
int CMidiParse::HexToInt(char inChar)
{
switch(inChar)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
return 10;
case 'a':
return 10;
case 'B':
return 11;
case 'b':
return 11;
case 'C':
return 12;
case 'c':
return 12;
case 'D':
return 13;
case 'd':
return 13;
case 'E':
return 14;
case 'e':
return 14;
case 'F':
return 15;
case 'f':
return 15;
default:
return 0;
}
}
unsigned short CMidiParse::Flip16Bit(unsigned short ShortValue)
{
return ((ShortValue >> 8) | ((ShortValue << 8)));
}
void CMidiParse::ExportToBin(CString gameName, unsigned char* buffer, unsigned long address, unsigned long size, CString fileName, bool& compressed)
{
gameName.Trim();
if (compressed)
{
if (gameName.CompareNoCase("MidiLZSSWilliams") == 0)
{
int fileSizeCompressed = size;
CMidwayDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed, "WILLIAMS");
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("LZSS_0BSng") == 0)
{
int fileSizeCompressed = size;
CMidwayDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address+4], fileSizeCompressed, outputDecompressed, "LZSS_0");
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("AVL_0Sng") == 0)
{
int fileSizeCompressed = size;
CMidwayDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed, "LZSS");
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("VigilanteSng") == 0)
{
int fileSizeCompressed = size;
CVigilanteDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("RugratsSng") == 0)
{
int fileSizeCompressed = size;
CRugratsDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("RNCSng") == 0)
{
int fileSizeCompressed = -1;
RncDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.unpackM1(&buffer[address], outputDecompressed, 0x0000, fileSizeCompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("ASMICSng") == 0)
{
int fileSizeCompressed = -1;
CASMICDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("SnowSng") == 0)
{
int fileSizeCompressed = size;
CSnowDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("ArmySargeSng") == 0)
{
int fileSizeCompressed = -1;
n643docompression decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.uncompressedSize(&buffer[address], true);
expectedSize = decode.dec(&buffer[address], expectedSize, outputDecompressed, fileSizeCompressed, true, false);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("ArmySarge2Sng") == 0)
{
int fileSizeCompressed = -1;
n643docompression decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.uncompressedSize(&buffer[address], true);
expectedSize = decode.dec(&buffer[address], expectedSize, outputDecompressed, fileSizeCompressed, true, true);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("Quake2Sng") == 0)
{
int fileSizeCompressed = -1;
CQuakeDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int decompressedSize = decode.aridecode(&buffer[address], 0x50000, outputDecompressed, decompressedSize);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < decompressedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("TazSng") == 0)
{
CString inTempFileName;
inTempFileName.Format("tempASAS%08X.mus", address);
CString outTempFileName;
outTempFileName.Format("tempASAS%08X.musb", address);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
FILE* outTempIn = fopen(inTempFileName, "wb");
if (outTempIn == NULL)
{
return;
}
int musSize = size;
unsigned long expectedSize = CharArrayToLong(&buffer[address+4]) - 0x14;
fwrite(&expectedSize, 1, 4, outTempIn);
fwrite(&buffer[address+0x14], 1, musSize-0x14, outTempIn);
fflush(outTempIn);
fclose(outTempIn);
flzh huffman;
huffman.infile = fopen(inTempFileName, "rb");
if (huffman.infile == NULL)
{
::DeleteFile(inTempFileName);
return;
}
huffman.outfile = fopen(outTempFileName, "wb");
if (huffman.outfile == NULL)
{
return;
}
huffman.Decode();
fflush(huffman.outfile);
fclose(huffman.infile);
fclose(huffman.outfile);
musSize = CSharedFunctions::GetSizeFile(outTempFileName);
FILE* inTempIn = fopen(outTempFileName, "rb");
if (inTempIn == NULL)
{
return;
}
unsigned char* outputDecompressed = new unsigned char[musSize];
fread(outputDecompressed, 1, musSize, inTempIn);
fclose(inTempIn);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
delete [] outputDecompressed;
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("ARISng") == 0)
{
CString inTempFileName;
inTempFileName.Format("tempASAS%08X.mus", address);
CString outTempFileName;
outTempFileName.Format("tempASAS%08X.musb", address);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
FILE* outTempIn = fopen(inTempFileName, "wb");
if (outTempIn == NULL)
{
return;
}
int musSize = size;
unsigned long expectedSize = CharArrayToLong(&buffer[address-4]);
fwrite(&expectedSize, 1, 4, outTempIn);
fwrite(&buffer[address], 1, musSize, outTempIn);
fflush(outTempIn);
fclose(outTempIn);
CLZARIDecoder lzari;
lzari.infile = fopen(inTempFileName, "rb");
if (lzari.infile == NULL)
{
::DeleteFile(inTempFileName);
return;
}
lzari.outfile = fopen(outTempFileName, "wb");
if (lzari.outfile == NULL)
{
return;
}
lzari.Decode();
fflush(lzari.outfile);
fclose(lzari.infile);
fclose(lzari.outfile);
musSize = CSharedFunctions::GetSizeFile(outTempFileName);
FILE* inTempIn = fopen(outTempFileName, "rb");
if (inTempIn == NULL)
{
return;
}
unsigned char* outputDecompressed = new unsigned char[musSize];
fread(outputDecompressed, 1, musSize, inTempIn);
fclose(inTempIn);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
delete [] outputDecompressed;
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("FLA2Sng") == 0)
{
int fileSizeCompressed = -1;
CFLA2Decoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSizeUncompressed = Flip32Bit(CharArrayToLong(&buffer[address+4]));
int expectedSize = decode.decFLA2(&buffer[address+8], fileSizeCompressed, expectedSizeUncompressed, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("RNCSngOffset") == 0)
{
int fileSizeCompressed = -1;
RncDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.unpackM1(&buffer[address], outputDecompressed, 0x0000, fileSizeCompressed);
unsigned long offset = CharArrayToLong(&outputDecompressed[0]);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize - offset; x++)
{
fwrite(&outputDecompressed[offset + x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("Yay0Sng") == 0)
{
int fileSizeCompressed = -1;
YAY0 decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.decodeAll(&buffer[address], outputDecompressed, fileSizeCompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("BlitzSng") == 0)
{
int fileSizeCompressed = -1;
CBlitzDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], outputDecompressed, fileSizeCompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("MarioTennisSng") == 0)
{
int fileSizeCompressed = -1;
CMarioTennisDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else if (gameName.CompareNoCase("MultiPartTigSng") == 0)
{
MessageBox(NULL, "Can't write Tig to bin, not supported", "Error", NULL);
}
else if (gameName.CompareNoCase("Konami") == 0)
{
int fileSizeCompressed = size;
CNaganoDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&buffer[address], fileSizeCompressed, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else
{
DecompressToFile(&buffer[address], size, fileName);
}
}
else
{
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < size; x++)
{
fwrite(&buffer[address+x], 1, 1, outFile);
}
fclose(outFile);
}
}
void CMidiParse::ExportToMidi(CString gameName, unsigned char* gamebuffer, int gamebufferSize, unsigned long address, unsigned long size, CString fileName, CString gameType, int& numberInstruments, unsigned long division, bool& compressed, bool& hasLoopPoint, int& loopStart, int& loopEnd, bool calculateInstrumentCountOnly, bool separateByInstrument, bool generateDebugTextFile, unsigned long extra, unsigned long extra2, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo)
{
ExportToMidi(gameName, gamebuffer, gamebufferSize, address, size, fileName, gameType, numberInstruments, division, compressed, hasLoopPoint, loopStart, loopEnd, calculateInstrumentCountOnly, separateByInstrument, generateDebugTextFile, extra, extra2, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, false, 4);
}
void CMidiParse::ExportToMidi(CString gameName, unsigned char* gamebuffer, int gamebufferSize, unsigned long address, unsigned long size, CString fileName, CString gameType, int& numberInstruments, unsigned long division, bool& compressed, bool& hasLoopPoint, int& loopStart, int& loopEnd, bool calculateInstrumentCountOnly, bool separateByInstrument, bool generateDebugTextFile, unsigned long extra, unsigned long extra2, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, bool usePitchBendSensitity, int pitchBendSensitity)
{
gameName.Trim();
gameType.Trim();
if (gameType.CompareNoCase("BanjoTooie") == 0)
{
if (compressed)
{
compress->SetGame(BANJOTOOIE);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], size, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
BTMidiToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, hasLoopPoint, loopStart, loopEnd, extendTracksToHighest, usePitchBendSensitity, pitchBendSensitity);
delete [] outputBuffer;
}
}
else
{
BTMidiToMidi(&gamebuffer[address], size, fileName, numberInstruments, hasLoopPoint, loopStart, loopEnd, extendTracksToHighest, usePitchBendSensitity, pitchBendSensitity);
}
}
else if (gameType.CompareNoCase("MIDx") == 0)
{
if (compressed)
{
}
else
{
MIDxMidiToMidi(&gamebuffer[address], size, fileName, numberInstruments);
}
}
else if (gameType.CompareNoCase("Sng") == 0)
{
if (compressed)
{
}
else
{
SngToMidi(&gamebuffer[address], size, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, &gamebuffer[address], size, fileName + " TrackParseDebug.txt", extra);
}
}
else if (gameType.CompareNoCase("Konami") == 0)
{
if (compressed)
{
int fileSizeCompressed = size;
CNaganoDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed);
KonamiToMidi(gamebuffer, gamebufferSize, outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
if (generateDebugTextFile)
KonamiToDebugTextFile(gamebuffer, gamebufferSize, gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
delete [] outputDecompressed;
}
else
{
KonamiToMidi(gamebuffer, gamebufferSize, &gamebuffer[address], size, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
if (generateDebugTextFile)
KonamiToDebugTextFile(gamebuffer, gamebufferSize, gameName, address, &gamebuffer[address], size, fileName + " TrackParseDebug.txt", writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
}
}
else if (gameType.CompareNoCase("ZLIBSSEQ") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
GECompression gedecompress;
gedecompress.SetGame(MORTALKOMBAT);
gedecompress.SetCompressedBuffer(&gamebuffer[address], size);
int fileSizeUncompressed;
unsigned char* outputDecompressedSSEQ = gedecompress.OutputDecompressedBuffer(fileSizeUncompressed, fileSizeCompressed);
SSEQToMidi(gamebuffer, gamebufferSize, outputDecompressedSSEQ, fileSizeUncompressed, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
if (generateDebugTextFile)
SSEQToDebugTextFile(gamebuffer, gamebufferSize, gameName, address, &gamebuffer[address], size, fileName + " TrackParseDebug.txt", writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
delete [] outputDecompressedSSEQ;
}
else
{
SSEQToMidi(gamebuffer, gamebufferSize, &gamebuffer[address], size, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
if (generateDebugTextFile)
SSEQToDebugTextFile(gamebuffer, gamebufferSize, gameName, address, &gamebuffer[address], size, fileName + " TrackParseDebug.txt", writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
}
}
else if (gameType.CompareNoCase("SSEQ") == 0)
{
if (compressed)
{
}
else
{
SSEQToMidi(gamebuffer, gamebufferSize, &gamebuffer[address], size, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
if (generateDebugTextFile)
SSEQToDebugTextFile(gamebuffer, gamebufferSize, gameName, address, &gamebuffer[address], size, fileName + " TrackParseDebug.txt", writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
}
}
else if (gameType.CompareNoCase("PaperMario") == 0)
{
if (compressed)
{
}
else
{
std::vector<SngInstrumentPaperMario> usedInstruments;
std::vector<SngDrumPaperMario> usedPercussionSet;
std::vector<int> usedExtraInstruments;
PaperMarioToMidi(gamebuffer, gamebufferSize, &gamebuffer[address], size, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, usedInstruments, usedPercussionSet, usedExtraInstruments, extendTracksToHighest);
if (generateDebugTextFile)
PaperMarioToDebugTextFile(gamebuffer, gamebufferSize, gameName, address, &gamebuffer[address], size, fileName + " TrackParseDebug.txt", writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
}
}
else if (gameType.CompareNoCase("RNCSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
RncDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.unpackM1(&gamebuffer[address], outputDecompressed, 0x0000, fileSizeCompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("ASMICSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
CASMICDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("SnowSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = size;
CSnowDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("ArmySargeSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
n643docompression decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.uncompressedSize(&gamebuffer[address], true);
expectedSize = decode.dec(&gamebuffer[address], expectedSize, outputDecompressed, fileSizeCompressed, true, false);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("ArmySarge2Sng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
n643docompression decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.uncompressedSize(&gamebuffer[address], true);
expectedSize = decode.dec(&gamebuffer[address], expectedSize, outputDecompressed, fileSizeCompressed, true, true);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("Quake2Sng") == 0)
{
if (compressed)
{
CQuakeDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int decompressedSize = decode.aridecode(&gamebuffer[address], 0x50000, outputDecompressed, decompressedSize);
SngToMidi(outputDecompressed, decompressedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, decompressedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("TazSng") == 0)
{
if (compressed)
{
CString inTempFileName;
inTempFileName.Format("tempASAS%08X.mus", address);
CString outTempFileName;
outTempFileName.Format("tempASAS%08X.musb", address);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
FILE* outTempIn = fopen(inTempFileName, "wb");
if (outTempIn == NULL)
{
return;
}
int musSize = size;
unsigned long expectedSize = CharArrayToLong(&gamebuffer[address+4]) - 0x14;
fwrite(&expectedSize, 1, 4, outTempIn);
fwrite(&gamebuffer[address+0x14], 1, musSize-0x14, outTempIn);
fflush(outTempIn);
fclose(outTempIn);
flzh huffman;
huffman.infile = fopen(inTempFileName, "rb");
if (huffman.infile == NULL)
{
::DeleteFile(inTempFileName);
return;
}
huffman.outfile = fopen(outTempFileName, "wb");
if (huffman.outfile == NULL)
{
return;
}
huffman.Decode();
fflush(huffman.outfile);
fclose(huffman.infile);
fclose(huffman.outfile);
musSize = CSharedFunctions::GetSizeFile(outTempFileName);
FILE* inTempIn = fopen(outTempFileName, "rb");
if (inTempIn == NULL)
{
return;
}
unsigned char* outputDecompressed = new unsigned char[musSize];
fread(outputDecompressed, 1, musSize, inTempIn);
fclose(inTempIn);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("ARISng") == 0)
{
if (compressed)
{
CString inTempFileName;
inTempFileName.Format("tempASAS%08X.mus", address);
CString outTempFileName;
outTempFileName.Format("tempASAS%08X.musb", address);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
FILE* outTempIn = fopen(inTempFileName, "wb");
if (outTempIn == NULL)
{
return;
}
int musSize = size;
unsigned long expectedSize = CharArrayToLong(&gamebuffer[address-4]);
fwrite(&expectedSize, 1, 4, outTempIn);
fwrite(&gamebuffer[address], 1, musSize, outTempIn);
fflush(outTempIn);
fclose(outTempIn);
CLZARIDecoder lzari;
lzari.infile = fopen(inTempFileName, "rb");
if (lzari.infile == NULL)
{
::DeleteFile(inTempFileName);
return;
}
lzari.outfile = fopen(outTempFileName, "wb");
if (lzari.outfile == NULL)
{
return;
}
lzari.Decode();
fflush(lzari.outfile);
fclose(lzari.infile);
fclose(lzari.outfile);
musSize = CSharedFunctions::GetSizeFile(outTempFileName);
FILE* inTempIn = fopen(outTempFileName, "rb");
if (inTempIn == NULL)
{
return;
}
unsigned char* outputDecompressed = new unsigned char[musSize];
fread(outputDecompressed, 1, musSize, inTempIn);
fclose(inTempIn);
::DeleteFile(inTempFileName);
::DeleteFile(outTempFileName);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("FLA2Sng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
CFLA2Decoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSizeUncompressed = Flip32Bit(CharArrayToLong(&gamebuffer[address+4]));
int expectedSize = decode.decFLA2(&gamebuffer[address+8], fileSizeCompressed, expectedSizeUncompressed, outputDecompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("RNCSngOffset") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
RncDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.unpackM1(&gamebuffer[address], outputDecompressed, 0x0000, fileSizeCompressed);
unsigned long offset = CharArrayToLong(&outputDecompressed[0]);
SngToMidi(&outputDecompressed[offset], expectedSize - offset, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, &outputDecompressed[offset], expectedSize - offset, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("Yay0Sng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
YAY0 decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.decodeAll(&gamebuffer[address], outputDecompressed, fileSizeCompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("BlitzSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
CBlitzDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], outputDecompressed, fileSizeCompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("MarioTennisSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
CMarioTennisDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("ZLibSng") == 0)
{
if (compressed)
{
compress->SetGame(NOHEADER);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], size, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
SngToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputBuffer, decompressedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputBuffer;
}
}
else
{
}
}
else if (gameType.CompareNoCase("Factor5Zlb") == 0)
{
if ((gamebuffer[address] == 0x78) && (gamebuffer[address+1] == 0xDA))
{
compress->SetGame(STUNTRACER64);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], size, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
Factor5ToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, true);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, outputBuffer, decompressedSize, fileName + " TrackParseDebug.txt", true);
delete [] outputBuffer;
}
}
else if ((gamebuffer[address] == 0x68) && (gamebuffer[address+1] == 0xDE))
{
compress->SetGame(RESIDENTEVIL2);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], size, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
Factor5ToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, true);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, outputBuffer, decompressedSize, fileName + " TrackParseDebug.txt", true);
delete [] outputBuffer;
}
}
else
{
Factor5ToMidi(&gamebuffer[address], size, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, true);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, gamebuffer, size, fileName + " TrackParseDebug.txt", true);
}
}
else if (gameType.CompareNoCase("Factor5ZlbGCStyle") == 0)
{
if ((gamebuffer[address] == 0x78) && (gamebuffer[address+1] == 0xDA))
{
compress->SetGame(STUNTRACER64);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], size, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
Factor5ToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, false);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, outputBuffer, decompressedSize, fileName + " TrackParseDebug.txt", false);
delete [] outputBuffer;
}
}
else if ((gamebuffer[address] == 0x68) && (gamebuffer[address+1] == 0xDE))
{
compress->SetGame(RESIDENTEVIL2);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], size, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
Factor5ToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, false);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, outputBuffer, decompressedSize, fileName + " TrackParseDebug.txt", false);
delete [] outputBuffer;
}
}
else
{
Factor5ToMidi(&gamebuffer[address], size, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, false);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, gamebuffer, size, fileName + " TrackParseDebug.txt", false);
}
}
else if (gameType.CompareNoCase("Factor5ZlbNoHeaderGCStyle") == 0)
{
compress->SetGame(NOHEADER);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], size, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
Factor5ToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, false);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, outputBuffer, decompressedSize, fileName + " TrackParseDebug.txt", false);
delete [] outputBuffer;
}
}
else if (gameType.CompareNoCase("Factor5LZGCStyle") == 0)
{
CMidwayDecoder decode;
unsigned char* outputBuffer = new unsigned char[0x50000];
int fileSizeCompressed = size;
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputBuffer, "MIDWAY");
if (outputBuffer != NULL)
{
Factor5ToMidi(outputBuffer, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, false);
if (generateDebugTextFile)
Factor5ToDebugTextFile(gameName, address, outputBuffer, expectedSize, fileName + " TrackParseDebug.txt", false);
delete [] outputBuffer;
}
}
else if (gameType.CompareNoCase("ZLibIndexedSng") == 0)
{
if (compressed)
{
compress->SetGame(NOHEADER);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], gamebufferSize - address, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
unsigned long offset = CharArrayToLong(&outputBuffer[4 + (size * 4)]);
unsigned long offsetEnd = CharArrayToLong(&outputBuffer[4 + (size * 4) + 4]);
if (offsetEnd == 0)
offsetEnd = decompressedSize;
SngToMidi(&outputBuffer[offset], (offsetEnd - offset), fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputBuffer, (offsetEnd - offset), fileName + " TrackParseDebug.txt", extra);
delete [] outputBuffer;
}
}
else
{
}
}
else if (gameType.CompareNoCase("MultiPartTigSng") == 0)
{
if (compressed)
{
TigDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x90000];
unsigned char* sngBinaryPre = new unsigned char[0x100000];
unsigned long sngSize = 0;
int totalCompressedSize = 0;
unsigned long tempAddress = address;
while (totalCompressedSize < (size-1))
{
unsigned long compressedsize = Flip32Bit((((((gamebuffer[tempAddress] << 8) | gamebuffer[tempAddress+1]) << 8) | gamebuffer[tempAddress+2]) << 8) | gamebuffer[tempAddress+3]);
unsigned char type = gamebuffer[tempAddress+4];
if (type == 1) // no compression
{
memcpy(&sngBinaryPre[sngSize], &gamebuffer[tempAddress+8], compressedsize-8);
sngSize += compressedsize-8;
}
else if (type == 0)
{
int fileSize = decode.dec(&gamebuffer[tempAddress+8], compressedsize, outputDecompressed);
if (fileSize > 0x1000)
fileSize = 0x1008;
memcpy(&sngBinaryPre[sngSize], outputDecompressed, fileSize-8);
sngSize += fileSize-8;
}
tempAddress += compressedsize;
totalCompressedSize += compressedsize;
if ((gamebuffer[tempAddress] == 0x00) || ((Flip32Bit(CharArrayToLong(&gamebuffer[tempAddress]))) > 0x1010))
{
tempAddress++;
totalCompressedSize++;
}
}
SngToMidi(sngBinaryPre, sngSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, sngSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
delete [] sngBinaryPre;
}
else
{
}
}
else if (gameType.CompareNoCase("LZSS_0BSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = size;
CMidwayDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address+4], fileSizeCompressed, outputDecompressed, "LZSS_0");
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("AVL_0Sng") == 0)
{
if (compressed)
{
int fileSizeCompressed = size;
CMidwayDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed, "LZSS");
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("VigilanteSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = size;
CVigilanteDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("RugratsSng") == 0)
{
if (compressed)
{
int fileSizeCompressed = size;
CRugratsDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed);
SngToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extra);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("MidiLZSSWilliams") == 0)
{
if (compressed)
{
int fileSizeCompressed = size;
CMidwayDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.dec(&gamebuffer[address], fileSizeCompressed, outputDecompressed, "WILLIAMS");
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
}
else if (gameType.CompareNoCase("Midi") == 0)
{
if (compressed)
{
}
else
{
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < size; x++)
{
fwrite(&gamebuffer[address+x], 1, 1, outFile);
}
fclose(outFile);
}
}
else if (gameType.CompareNoCase("Yaz0EADZelda") == 0)
{
YAZ0 yaz0;
int fileSizeCompressed = -1;
int sizeUncompressed = yaz0.yaz0_get_size(&gamebuffer[address]);
unsigned char* outputDecompressed = new unsigned char[sizeUncompressed];
unsigned long sizeDecompressed = yaz0.yaz0_decode(&gamebuffer[address], outputDecompressed, fileSizeCompressed);
if (sizeDecompressed == 0)
{
delete [] outputDecompressed;
MessageBox(NULL, "Error decompressing", "Error", NULL);
return;
}
unsigned long audioSeqIndex = extra2;
unsigned long audioSeqOffset = size;
unsigned long numberMidi = CharArrayToShort(&outputDecompressed[audioSeqIndex]);
unsigned long start = CharArrayToLong(&outputDecompressed[audioSeqIndex + 0x10 + (extra * 0x10)]);
unsigned long length = CharArrayToLong(&outputDecompressed[audioSeqIndex + 0x10 + (extra * 0x10) + 4]);
int pitchBendRange = outputDecompressed[audioSeqIndex + 0x10 + (extra * 0x10) + 9] * 6;
EADMusicToMidi(gameName, EADMUSICSTYLEZELDA, gamebuffer, audioSeqOffset + start, length, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra, generateDebugTextFile, fileName + " TrackParseDebug.txt", pitchBendRange);
delete [] outputDecompressed;
}
else if (gameType.CompareNoCase("ZLibEADZelda") == 0)
{
int fileSizeCompressed = -1;
GECompression gedecompress;
gedecompress.SetGame(MORTALKOMBAT);
gedecompress.SetCompressedBuffer(&gamebuffer[address], size);
int fileSizeUncompressed;
unsigned char* outputDecompressed = gedecompress.OutputDecompressedBuffer(fileSizeUncompressed, fileSizeCompressed);
if (outputDecompressed == NULL)
{
delete [] outputDecompressed;
MessageBox(NULL, "Error decompressing", "Error", NULL);
return;
}
unsigned long audioSeqIndex = extra2;
unsigned long audioSeqOffset = size;
unsigned long numberMidi = CharArrayToShort(&outputDecompressed[audioSeqIndex]);
unsigned long start = CharArrayToLong(&outputDecompressed[audioSeqIndex + 0x10 + (extra * 0x10)]);
unsigned long length = CharArrayToLong(&outputDecompressed[audioSeqIndex + 0x10 + (extra * 0x10) + 4]);
int pitchBendRange = outputDecompressed[audioSeqIndex + 0x10 + (extra * 0x10) + 9] * 6;
EADMusicToMidi(gameName, EADMUSICSTYLEZELDA, gamebuffer, audioSeqOffset + start, length, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra, generateDebugTextFile, fileName + " TrackParseDebug.txt", pitchBendRange);
delete [] outputDecompressed;
}
else if (
(gameType.CompareNoCase("EADZelda") == 0)
||
(gameType.CompareNoCase("Seq64Zelda") == 0)
)
{
if (compressed)
{
}
else
{
unsigned long audioSeqIndex = address;
unsigned long audioSeqOffset = size;
unsigned long numberMidi = CharArrayToShort(&gamebuffer[audioSeqIndex]);
unsigned long start = CharArrayToLong(&gamebuffer[audioSeqIndex + 0x10 + (extra * 0x10)]);
unsigned long length = CharArrayToLong(&gamebuffer[audioSeqIndex + 0x10 + (extra * 0x10) + 4]);
int pitchBendRange = gamebuffer[audioSeqIndex + 0x10 + (extra * 0x10) + 9] * 6;
EADMusicToMidi(gameName, EADMUSICSTYLEZELDA, gamebuffer, audioSeqOffset + start, length, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra, generateDebugTextFile, fileName + " TrackParseDebug.txt", pitchBendRange);
}
}
else if (
(gameType.CompareNoCase("EADMario") == 0)
||
(gameType.CompareNoCase("Seq64Mario") == 0)
)
{
if (compressed)
{
}
else
{
unsigned long audioSeqIndex = address;
unsigned long audioSeqOffset = size;
unsigned long numberMidi = CharArrayToShort(&gamebuffer[audioSeqIndex]);
unsigned long start = CharArrayToLong(&gamebuffer[audioSeqIndex + 4 + (extra * 8)]);
unsigned long length = CharArrayToLong(&gamebuffer[audioSeqIndex + 4 + (extra * 8) + 4]);
EADMusicToMidi(gameName, EADMUSICSTYLEMARIO, gamebuffer, audioSeqOffset + start, length, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra, generateDebugTextFile, fileName + " TrackParseDebug.txt", 6);
}
}
else if (gameType.CompareNoCase("EADStarFox") == 0)
{
if (compressed)
{
}
else
{
unsigned long audioSeqIndex = address;
unsigned long audioSeqOffset = size;
unsigned long numberMidi = CharArrayToShort(&gamebuffer[audioSeqIndex]);
unsigned long start = CharArrayToLong(&gamebuffer[audioSeqIndex + 0x10 + (extra * 0x10)]);
unsigned long length = CharArrayToLong(&gamebuffer[audioSeqIndex + 0x10 + (extra * 0x10) + 4]);
int pitchBendRange = gamebuffer[audioSeqIndex + 0x10 + (extra * 0x10) + 9] * 6;
EADMusicToMidi(gameName, EADMUSICSTYLESTARFOX, gamebuffer, audioSeqOffset + start, length, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra, generateDebugTextFile, fileName + " TrackParseDebug.txt", pitchBendRange);
}
}
else if (gameType.CompareNoCase("Seq64Mario") == 0)
{
CString tempROMStr = mainFolder + "TempASEQ64ROM.rom";
FILE* outTempROM = fopen(tempROMStr, "wb");
if (outTempROM == NULL)
{
MessageBox(NULL, "Cannot Write temp ROM File", "Error", NULL);
return;
}
fwrite(gamebuffer, 1, gamebufferSize, outTempROM);
fclose(outTempROM);
CString tempStr;
::DeleteFile(fileName);
tempStr.Format("seq64.exe --rom=\"%s\" --romdesc=\"%s\" --export_midi=%d --output=\"%s\"", tempROMStr, mainFolder + "romdesc\\" + gameName + ".xml", extra, fileName);
hiddenExec(_T(tempStr.GetBuffer()), (mainFolder));
::DeleteFile(tempROMStr);
}
else if (gameType.CompareNoCase("Seq64Zelda") == 0)
{
CString tempROMStr = mainFolder + "TempASEQ64ROM.rom";
FILE* outTempROM = fopen(tempROMStr, "wb");
if (outTempROM == NULL)
{
MessageBox(NULL, "Cannot Write temp ROM File", "Error", NULL);
return;
}
fwrite(gamebuffer, 1, gamebufferSize, outTempROM);
fclose(outTempROM);
CString tempStr;
::DeleteFile(fileName);
tempStr.Format("seq64.exe --rom=\"%s\" --romdesc=\"%s\" --export_midi=%d --output=\"%s\"", tempROMStr, mainFolder + "romdesc\\" + gameName + ".xml", extra, fileName);
hiddenExec(_T(tempStr.GetBuffer()), (mainFolder));
::DeleteFile(tempROMStr);
}
else if (gameType.CompareNoCase("Yaz0Seq64") == 0)
{
CString tempROMStr = mainFolder + "TempASEQ64ROM.rom";
unsigned char* tempGameBuffer = new unsigned char[gamebufferSize];
memcpy(tempGameBuffer, gamebuffer, gamebufferSize);
YAZ0 yaz0;
int fileSizeCompressed = -1;
int sizeUncompressed = yaz0.yaz0_get_size(&tempGameBuffer[extra]);
unsigned char* outputDecompressed = new unsigned char[sizeUncompressed];
unsigned long sizeDecompressed = yaz0.yaz0_decode(&tempGameBuffer[extra], outputDecompressed, fileSizeCompressed);
if (sizeDecompressed == 0)
{
delete [] outputDecompressed;
delete [] tempGameBuffer;
MessageBox(NULL, "Error decompressing", "Error", NULL);
return;
}
FILE* outTempROM = fopen(tempROMStr, "wb");
if (outTempROM == NULL)
{
delete [] outputDecompressed;
delete [] tempGameBuffer;
MessageBox(NULL, "Cannot Write temp ROM File", "Error", NULL);
return;
}
memcpy(&tempGameBuffer[extra], outputDecompressed, sizeDecompressed);
delete [] outputDecompressed;
fwrite(tempGameBuffer, 1, gamebufferSize, outTempROM);
fclose(outTempROM);
CString tempStr;
::DeleteFile(fileName);
tempStr.Format("seq64.exe --rom=\"%s\" --romdesc=\"%s\" --export_midi=%d --output=\"%s\"", tempROMStr, mainFolder + "romdesc\\" + gameName + ".xml", extra, fileName);
hiddenExec(_T(tempStr.GetBuffer()), (mainFolder));
::DeleteFile(tempROMStr);
delete [] tempGameBuffer;
}
else if (gameType.CompareNoCase("ZipSng") == 0)
{
CString tempROMStr = mainFolder + "TempASEQ64ROM.rom";
FILE* outTempROM = fopen(tempROMStr, "wb");
if (outTempROM == NULL)
{
MessageBox(NULL, "Cannot Write temp ROM File", "Error", NULL);
return;
}
fwrite(gamebuffer, 1, gamebufferSize, outTempROM);
fclose(outTempROM);
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
::SetCurrentDirectory(mainFolder);
HANDLE h = CreateFile(_T(mainFolder + "templist.txt"),
GENERIC_WRITE,
FILE_SHARE_WRITE,
&sa,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL );
CString tempStr;
::DeleteFile(fileName);
tempStr.Format("7z.exe l \"%s\" -o\"%s\" *.bin -r -y", tempROMStr, mainFolder);
if (!hiddenExec(_T(tempStr.GetBuffer()), mainFolder, h))
{
CloseHandle(h);
return;
}
CloseHandle(h);
FILE* inFile = fopen(mainFolder + "templist.txt", "r");
if (inFile == NULL)
{
return;
}
std::vector<CString> lines;
while (!feof(inFile))
{
char currentLine[1000];
fgets(currentLine, 1000, inFile);
lines.push_back(currentLine);
}
fclose(inFile);
int counter = 0;
for (int x = 0; x < lines.size(); x++)
{
if (lines[x].Find("Sound\\") != -1)
{
if (counter == address)
{
int fileNameSpot = lines[x].Find("Sound\\") + 6;
CString fileNamePull = lines[x].Mid(fileNameSpot);
fileNamePull.Trim();
tempStr.Format("7z.exe e \"%s\" -o\"%s\" %s -r -y", tempROMStr, mainFolder, fileNamePull);
if (!hiddenExec(_T(tempStr.GetBuffer()), (mainFolder)))
return;
FILE* inFileSng = fopen(mainFolder + fileNamePull, "rb");
if (inFileSng == NULL)
return;
fseek(inFile, 0, SEEK_END);
int inputSize = ftell(inFile);
rewind(inFile);
unsigned char* inputMID = new unsigned char[inputSize];
fread(inputMID, 1, inputSize, inFile);
fclose(inFile);
fclose(inFileSng);
SngToMidi(inputMID, inputSize, fileName, numberInstruments, calculateInstrumentCountOnly, separateByInstrument, extra);
if (generateDebugTextFile)
SngToDebugTextFile(gameName, address, &gamebuffer[address], inputSize, fileName + " TrackParseDebug.txt", extra);
delete [] inputMID;
::DeleteFile(mainFolder + fileNamePull);
}
counter++;
}
}
::DeleteFile("templist.txt");
::DeleteFile(tempROMStr);
}
else if (gameType.CompareNoCase("MultipartZLibXMFastTracker2") == 0)
{
if (compressed)
{
compress->SetGame(STUNTRACER64);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
unsigned long compressedMainSize = CharArrayToLong(&gamebuffer[address]);
unsigned long uncompressedMainSize = CharArrayToLong(&gamebuffer[address+4]);
unsigned long step = CharArrayToLong(&gamebuffer[address+0x8]);
int readSize = 0;
while ((readSize < compressedMainSize) && (CharArrayToLong(&gamebuffer[address+0xC+readSize]) != 0))
{
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address+0xC+readSize], size, decompressedSize, compressedSize);
for (int x = 0; x < decompressedSize; x++)
{
fwrite(&outputBuffer[x], 1, 1, outFile);
}
readSize += step;
if (((address+0xC+readSize) % 2) != 0)
{
readSize += (2-((address+0xC+readSize) % 2));
}
step = CharArrayToLong(&gamebuffer[address+0xC+readSize]);
readSize += 4;
delete [] outputBuffer;
}
fclose(outFile);
}
else
{
}
}
else if (gameType.CompareNoCase("DCM") == 0)
{
if (compressed)
{
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
CH20DecoderMidiTool h20dec;
int compressedSize = -1;
unsigned char* outputDecompressed = new unsigned char[0x50000];
unsigned char* cleanDecompressed = new unsigned char[0x50000];
int decSize = h20dec.decPolaris(&gamebuffer[address], compressedSize, outputDecompressed);
decSize = h20dec.decPolaris(&gamebuffer[address], compressedSize, cleanDecompressed);
for (int x = 14; x < (14 + (outputDecompressed[5] * 0x10)); x+=0x10)
{
unsigned char tempValue1 = outputDecompressed[x];
unsigned char tempValue2 = outputDecompressed[x+1];
outputDecompressed[x] = outputDecompressed[x+3];
outputDecompressed[x+1] = outputDecompressed[x+2];
outputDecompressed[x+2] = tempValue2;
outputDecompressed[x+3] = tempValue1;
tempValue1 = outputDecompressed[x+4];
tempValue2 = outputDecompressed[x+5];
outputDecompressed[x+4] = outputDecompressed[x+7];
outputDecompressed[x+5] = outputDecompressed[x+6];
outputDecompressed[x+6] = tempValue2;
outputDecompressed[x+7] = tempValue1;
tempValue1 = outputDecompressed[x+8];
tempValue2 = outputDecompressed[x+9];
outputDecompressed[x+8] = outputDecompressed[x+11];
outputDecompressed[x+9] = outputDecompressed[x+10];
outputDecompressed[x+10] = tempValue2;
outputDecompressed[x+11] = tempValue1;
unsigned char tempValue = outputDecompressed[x+12];
outputDecompressed[x+12] = outputDecompressed[x+13];
outputDecompressed[x+13] = tempValue;
tempValue = outputDecompressed[x+14];
outputDecompressed[x+14] = outputDecompressed[x+15];
outputDecompressed[x+15] = tempValue;
}
int position = (14 + (outputDecompressed[5] * 0x10));
if (cleanDecompressed[position] == 0x00)
{
unsigned long length = CharArrayToLong(&cleanDecompressed[position]);
if (length > decSize)
{
cleanDecompressed[6] = (length & 0xFF);
cleanDecompressed[7] = ((length >> 8) & 0xFF);
cleanDecompressed[8] = ((length >> 16) & 0xFF);
cleanDecompressed[9] = ((length >> 24) & 0xFF);
fwrite(cleanDecompressed, 1, position, outFile);
CTetrisphereDecoder tetDec;
unsigned char* outputLz = new unsigned char[0x100000];
int returnSize = tetDec.decompressLZ(&cleanDecompressed[position+4], length, outputLz, true);
returnSize = returnSize;
fwrite(outputLz, 1, length, outFile);
delete [] outputLz;
}
else
{
cleanDecompressed[6] = (length & 0xFF);
cleanDecompressed[7] = ((length >> 8) & 0xFF);
cleanDecompressed[8] = ((length >> 16) & 0xFF);
cleanDecompressed[9] = ((length >> 24) & 0xFF);
fwrite(cleanDecompressed, 1, position, outFile);
length = (decSize - (position + 4));
fwrite(&cleanDecompressed[position+4], 1, length, outFile);
}
}
else
{
fwrite(cleanDecompressed, 1, position, outFile);
int length = (decSize - (position));
fwrite(&cleanDecompressed[position], 1, length, outFile);
}
for (int x = 0; x < outputDecompressed[5]; x++)
{
unsigned short instrumentNumber = CharArrayToShort(&outputDecompressed[14+(16*(x))+14]);
unsigned long sampleSize = CharArrayToLong(&outputDecompressed[14+(16*(x))]);
unsigned short flags = CharArrayToShort(&outputDecompressed[14+(16*(x))+12]);
if (flags & 1)
{
sampleSize = sampleSize * 2;
}
unsigned long location = address + size + CharArrayToLong(&gamebuffer[address + size + (instrumentNumber * 4) + 2]);
unsigned char* outputDecompressedInstrument = new unsigned char[0x50000];
int decSizeInstrument = h20dec.decPolaris(&gamebuffer[location], compressedSize, outputDecompressedInstrument);
fwrite(outputDecompressedInstrument, 1, sampleSize, outFile);
delete [] outputDecompressedInstrument;
}
delete [] outputDecompressed;
delete [] cleanDecompressed;
fclose(outFile);
}
else
{
}
}
else if (gameType.CompareNoCase("Aidyn") == 0)
{
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
int decompressedSize = -1;
int fileTable = size;
int fileID = address;
int fileTableData = extra;
unsigned char* tempInput = CAidynDecoder::DecompressAidynFile(gamebuffer, fileTable, fileTableData, fileID, decompressedSize);
if (tempInput != NULL)
{
std::map<int, fileData> smp;
unsigned char* outputDecompressed = new unsigned char[0x100000];
int dcmSize = -1;
CAidynToDCMConvertor::convert(tempInput, gamebuffer, fileTable, fileTableData, smp, "", outputDecompressed, dcmSize);
fwrite(outputDecompressed, 1, dcmSize, outFile);
if (outputDecompressed)
{
delete [] outputDecompressed;
outputDecompressed = NULL;
}
delete [] tempInput;
}
fclose(outFile);
}
else if (gameType.CompareNoCase("LZSamplesDCM") == 0)
{
if (compressed)
{
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
unsigned long decSize = ((((((gamebuffer[address+0x9] << 8) | gamebuffer[address+0x8]) << 8) | gamebuffer[address+0x7]) << 8) | gamebuffer[address+0x6]);
unsigned char* outputDecompressed = new unsigned char[0x50000];
unsigned char* cleanDecompressed = new unsigned char[0x50000];
memcpy(outputDecompressed, &gamebuffer[address], decSize + 4 + (14 + (outputDecompressed[5] * 0x10)));
memcpy(cleanDecompressed, &gamebuffer[address], decSize + 4 + (14 + (outputDecompressed[5] * 0x10)));
for (int x = 14; x < (14 + (outputDecompressed[5] * 0x10)); x+=0x10)
{
unsigned char tempValue1 = outputDecompressed[x];
unsigned char tempValue2 = outputDecompressed[x+1];
outputDecompressed[x] = outputDecompressed[x+3];
outputDecompressed[x+1] = outputDecompressed[x+2];
outputDecompressed[x+2] = tempValue2;
outputDecompressed[x+3] = tempValue1;
tempValue1 = outputDecompressed[x+4];
tempValue2 = outputDecompressed[x+5];
outputDecompressed[x+4] = outputDecompressed[x+7];
outputDecompressed[x+5] = outputDecompressed[x+6];
outputDecompressed[x+6] = tempValue2;
outputDecompressed[x+7] = tempValue1;
tempValue1 = outputDecompressed[x+8];
tempValue2 = outputDecompressed[x+9];
outputDecompressed[x+8] = outputDecompressed[x+11];
outputDecompressed[x+9] = outputDecompressed[x+10];
outputDecompressed[x+10] = tempValue2;
outputDecompressed[x+11] = tempValue1;
unsigned char tempValue = outputDecompressed[x+12];
outputDecompressed[x+12] = outputDecompressed[x+13];
outputDecompressed[x+13] = tempValue;
tempValue = outputDecompressed[x+14];
outputDecompressed[x+14] = outputDecompressed[x+15];
outputDecompressed[x+15] = tempValue;
}
int position = (14 + (outputDecompressed[5] * 0x10));
if (cleanDecompressed[position] == 0x00)
{
unsigned long length = CharArrayToLong(&cleanDecompressed[position]);
if (length > decSize)
{
cleanDecompressed[6] = (length & 0xFF);
cleanDecompressed[7] = ((length >> 8) & 0xFF);
cleanDecompressed[8] = ((length >> 16) & 0xFF);
cleanDecompressed[9] = ((length >> 24) & 0xFF);
fwrite(cleanDecompressed, 1, position, outFile);
CTetrisphereDecoder tetDec;
unsigned char* outputLz = new unsigned char[0x100000];
int returnSize = tetDec.decompressLZ(&cleanDecompressed[position+4], (decSize - 4), outputLz, true);
returnSize = returnSize;
fwrite(outputLz, 1, length, outFile);
delete [] outputLz;
position += returnSize;
}
else
{
cleanDecompressed[6] = (length & 0xFF);
cleanDecompressed[7] = ((length >> 8) & 0xFF);
cleanDecompressed[8] = ((length >> 16) & 0xFF);
cleanDecompressed[9] = ((length >> 24) & 0xFF);
fwrite(cleanDecompressed, 1, position, outFile);
length = (decSize - (position + 4));
fwrite(&cleanDecompressed[position+4], 1, length, outFile);
position += length;
}
}
else
{
fwrite(cleanDecompressed, 1, position, outFile);
int length = decSize;
fwrite(&cleanDecompressed[position], 1, length, outFile);
position += length;
}
for (int x = 0; x < outputDecompressed[5]; x++)
{
unsigned short instrumentNumber = CharArrayToShort(&outputDecompressed[14+(16*(x))+14]);
unsigned long sampleSize = CharArrayToLong(&outputDecompressed[14+(16*(x))]);
unsigned short flags = CharArrayToShort(&outputDecompressed[14+(16*(x))+12]);
if (flags & 1)
{
sampleSize = sampleSize * 2;
}
unsigned long location = address + size + CharArrayToLong(&gamebuffer[address + size + (instrumentNumber * 4) + 2]);
unsigned char* outputDecompressedInstrument = new unsigned char[0x50000];
CTetrisphereDecoder tetDec;
tetDec.sphereDecompress(&gamebuffer[location], outputDecompressedInstrument);
fwrite(outputDecompressedInstrument, 1, sampleSize, outFile);
position += sampleSize;
delete [] outputDecompressedInstrument;
}
delete [] outputDecompressed;
delete [] cleanDecompressed;
fclose(outFile);
}
else
{
}
}
else if (gameType.CompareNoCase("TitusMidi") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
SupermanDecoder decode;
int expectedSize = decode.header(&gamebuffer[address], fileSizeCompressed);
unsigned char* outputDecompressed = new unsigned char[expectedSize];
decode.dec(&gamebuffer[address+0x11], fileSizeCompressed, expectedSize, outputDecompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
}
else
{
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < size; x++)
{
fwrite(&gamebuffer[address+x], 1, 1, outFile);
}
fclose(outFile);
}
}
else if (gameType.CompareNoCase("RNCMidi") == 0)
{
if (compressed)
{
int fileSizeCompressed = -1;
RncDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x50000];
int expectedSize = decode.unpackM1(&gamebuffer[address], outputDecompressed, 0x0000, fileSizeCompressed);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = 0; x < expectedSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
GEMidiToMidi(outputDecompressed, expectedSize, fileName, numberInstruments, hasLoopPoint, loopStart, loopEnd, extendTracksToHighest, usePitchBendSensitity, pitchBendSensitity);
if (generateDebugTextFile)
GEMidiToDebugTextFile(outputDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extendTracksToHighest);
delete [] outputDecompressed;
}
else
{
}
}
else if (gameType.CompareNoCase("RNCSeq") == 0)
{
if (compressed)
{
int realSpot = size;
int fileSizeCompressed = -1;
RncDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x100000];
int expectedSize = decode.unpackM1(&gamebuffer[address], outputDecompressed, 0x0000, fileSizeCompressed);
unsigned long realStart = CharArrayToLong(&outputDecompressed[0x8]) + CharArrayToLong(&outputDecompressed[realSpot]);
unsigned long realSize = CharArrayToLong(&outputDecompressed[realSpot + 4]) - CharArrayToLong(&outputDecompressed[realSpot]);
FILE* outFile = fopen(fileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return;
}
for (int x = realStart; x < (realStart + realSize); x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
unsigned char* tempDecompressed = new unsigned char[realSize];
memcpy(tempDecompressed, &outputDecompressed[realStart], realSize);
GEMidiToMidi(tempDecompressed, expectedSize, fileName, numberInstruments, hasLoopPoint, loopStart, loopEnd, extendTracksToHighest, usePitchBendSensitity, pitchBendSensitity);
if (generateDebugTextFile)
GEMidiToDebugTextFile(tempDecompressed, expectedSize, fileName + " TrackParseDebug.txt", extendTracksToHighest);
delete [] tempDecompressed;
delete [] outputDecompressed;
}
else
{
}
}
else
{
if (compressed)
{
if (gameType.CompareNoCase("GoldenEye") == 0)
{
compress->SetGame(GOLDENEYE);
}
else if (gameType.CompareNoCase("PerfectDark") == 0)
{
compress->SetGame(PD);
}
else if (gameType.CompareNoCase("BanjoKazooie") == 0)
{
compress->SetGame(BANJOKAZOOIE);
}
else if (gameType.CompareNoCase("BanjoTooie") == 0)
{
compress->SetGame(BANJOTOOIE);
}
else if (gameType.CompareNoCase("DonkeyKong") == 0)
{
compress->SetGame(DONKEYKONG64);
}
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&gamebuffer[address], (size + 20000), decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
if ((outputBuffer[0] == 0x0) && (outputBuffer[1] == 0x0)
&& (outputBuffer[2] == 0x0) && (outputBuffer[3] == 0x44))
{
GEMidiToMidi(outputBuffer, decompressedSize, fileName, numberInstruments, hasLoopPoint, loopStart, loopEnd, extendTracksToHighest, usePitchBendSensitity, pitchBendSensitity);
if (generateDebugTextFile)
GEMidiToDebugTextFile(outputBuffer, decompressedSize, fileName + " TrackParseDebug.txt", extendTracksToHighest);
}
delete [] outputBuffer;
}
}
else
{
GEMidiToMidi(&gamebuffer[address], size, fileName, numberInstruments, hasLoopPoint, loopStart, loopEnd, extendTracksToHighest, usePitchBendSensitity, pitchBendSensitity);
if (generateDebugTextFile)
GEMidiToDebugTextFile(&gamebuffer[address], size, fileName + " TrackParseDebug.txt", extendTracksToHighest);
}
}
}
byte* CMidiParse::Decompress(unsigned char* Buffer, unsigned long size, int& fileSize, int& compressedSize)
{
compress->SetCompressedBuffer(Buffer, size);
fileSize = 0; // is by reference, overwritten
byte* outputDecompressed = compress->OutputDecompressedBuffer(fileSize, compressedSize);
if (outputDecompressed == NULL)
{
MessageBox(NULL, "Error Decompressing", "Error", NULL);
return NULL;
}
return outputDecompressed;
}
bool CMidiParse::DecompressToFile(unsigned char* Buffer, unsigned long size, CString outputFile)
{
int fileSize = 0; // is by reference, overwritten
int compressedSize = -1;
byte* outputDecompressed = Decompress(Buffer, size, fileSize, compressedSize);
if (outputDecompressed == NULL)
{
MessageBox(NULL, "Error Decompressing", "Error", NULL);
return false;
}
FILE* outFile = fopen(outputFile, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot Write File", "Error", NULL);
return false;
}
for (int x = 0; x < fileSize; x++)
{
fwrite(&outputDecompressed[x], 1, 1, outFile);
}
fclose(outFile);
delete [] outputDecompressed;
return false;
}
void CMidiParse::ParseKonamiTrack(int trackNumber, int& numberInstruments, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfo>& outputNotes, unsigned char* buffer, unsigned long offset, unsigned long end, int& noteUniqueId, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, int highestTrackLength)
{
std::vector<SngNoteInfo> trackOutputNotes;
unsigned char command = 0x00;
unsigned long spot = offset;
unsigned long absoluteTime = 0;
unsigned char currentPan = 0x40;
unsigned long currentInstrument = 0x00;
unsigned char currentVolume = 0x7F;
unsigned char currentBank = 0x00;
int currentEffect = 0;
unsigned char lastDuration = 0xFF;
unsigned char lastLength = 0xFF;
unsigned long currentTempo = (unsigned long)(60000000.0 / (float)120.0);
signed long currentCoarseTune = 0x00;
unsigned char loopAmountsLeft = 0x00;
unsigned long loopSpot = 0;
unsigned long loopEndSpot = 0;
unsigned char loopNestedAmountsLeft = 0x00;
unsigned long loopNestedSpot = 0;
unsigned long loopNestedEndSpot = 0;
unsigned char lastNoteValue = 0x00;
unsigned long masterLoopMarkerStartOffset;
unsigned long masterLoopMarkerEndOffset;
int totalLoopsToOutputLeft = 0;
if (writeOutLoops)
totalLoopsToOutputLeft = loopWriteCount;
int currentEDOffset = 0;
int currentEEEndOffset = 0;
int eeCountOverall = 0;
bool lastNote00Length = false;
unsigned char lastNote = 0xFF;
unsigned char lastVelocity = 0xFF;
int previousCmd = -1;
unsigned char sectionNoteHold = 0x00;
while ((command != 0xFF) && (spot < end))
{
if (extendTracksToHighest)
{
if (absoluteTime >= highestTrackLength)
break;
}
if (trackNumber >= 0)
{
currentTempo = (unsigned long)(60000000.0 / (float)120.0);
if (trackNumber > 0)
{
for (int y = 0; y < tempoPositions.size(); y++)
{
if (tempoPositions[y].absoluteTime <= absoluteTime)
{
currentTempo = tempoPositions[y].value;
}
else
{
break;
}
}
}
}
command = buffer[spot];
spot++;
if (command < 0xD0) // Note or Rest
{
unsigned char note = command;
unsigned char drumInstrumentValue = 0x00;
if ((command == 0x67) || (command == (0x67 + 0x68))) // Rest?
{
drumInstrumentValue = buffer[spot];
spot++;
}
if (note >= 0x68)
{
note -= 0x68;
}
else
{
lastDuration = buffer[spot];
spot++;
}
bool firstSetNote00Length = false;
if (buffer[spot] < 0x80)
{
lastLength = buffer[spot];
spot++;
if (lastLength == 0)
lastNote00Length = true;
else
lastNote00Length = false;
firstSetNote00Length = true;
}
else
{
if (lastLength == 0)
lastNote00Length = true;
else
lastNote00Length = false;
if ((lastLength == 0) && (previousCmd == 0xF2))
{
firstSetNote00Length = true;
}
else
{
firstSetNote00Length = false;
}
}
unsigned char velocity = buffer[spot] & 0x7F;
spot++;
unsigned long noteDuration = lastDuration;
unsigned long noteLength = lastLength;
if (noteLength == 0)
noteLength = noteDuration;
else if (noteLength > noteDuration)
noteLength = noteDuration;
else if (noteLength <= noteDuration)
{
if (noteLength == 0x7F)
noteLength = noteDuration;
//else if ((noteLength == 0x01) && (sectionNoteHold != 0x00) && (sectionNoteHold < noteDuration))
//noteLength = sectionNoteHold;
else
noteLength = noteLength;
}
if (!firstSetNote00Length && lastNote00Length && (lastLength == 0x00))
{
// Set to same as previous, this is an extension
noteUniqueId--;
}
if (note < 0x48)
{
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentCoarseTune;
lastNoteValue = note;
songNoteInfo.instrument = currentInstrument + (currentBank * 0x100);
songNoteInfo.velocity = velocity;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
songNoteInfo.pan = currentPan & 0x7F;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = ((currentVolume >> 1) & 0x7F);
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
trackOutputNotes.push_back(songNoteInfo);
}
else if (note < 0x67)
{
// Drums
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = 0x3C + currentCoarseTune;
songNoteInfo.velocity = velocity;
lastNoteValue = 0x3C;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
unsigned long drumInstrumentLookedUp = (note - 0x48);
songNoteInfo.instrument = drumInstrumentLookedUp + 0x8000;
songNoteInfo.pan = currentPan & 0x7F;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = ((currentVolume >> 1) & 0x7F);
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
trackOutputNotes.push_back(songNoteInfo);
}
else if (note == 0x67)
{
// Drum Instrument
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = 0x3C + currentCoarseTune;
songNoteInfo.velocity = velocity;
lastNoteValue = 0x3C;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
unsigned long drumInstrumentLookedUp = (drumInstrumentValue - 0x48);
songNoteInfo.instrument = drumInstrumentLookedUp + 0x8000;
songNoteInfo.pan = currentPan & 0x7F;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = ((currentVolume >> 1) & 0x7F);
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
trackOutputNotes.push_back(songNoteInfo);
}
lastVelocity = velocity;
lastNote = note;
absoluteTime += noteDuration;
}
else
{
if (command == 0xD0)
{
//fprintf(outFile, " ((Tempo))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
unsigned char tempo = buffer[spot];
currentTempo = (unsigned long)(60000000.0 / (float)tempo);
if (trackNumber == 0)
{
tempoPositions.push_back(TimeAndValue(absoluteTime, currentTempo));
}
spot++;
}
else if (command == 0xD1)
{
//fprintf(outFile, " ((Tempo Change Fade))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
unsigned char tempo = buffer[spot+1];
currentTempo = (unsigned long)(60000000.0 / (float)tempo);
if (trackNumber == 0)
{
tempoPositions.push_back(TimeAndValue(absoluteTime, currentTempo));
}
spot += 2;
}
else if (command == 0xD2)
{
//fprintf(outFile, " ((Instrument Change))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentInstrument = buffer[spot];
if (currentInstrument >= numberInstruments)
numberInstruments = currentInstrument + 1;
spot++;
}
else if (command == 0xD3)
{
//fprintf(outFile, " ((Instrument/Volume Change))");
//fprintf(outFile, " Volume %02X (%d) Instrument %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
currentVolume = buffer[spot];
currentInstrument = buffer[spot+1];
if (currentInstrument >= numberInstruments)
numberInstruments = currentInstrument + 1;
spot += 2;
}
else if (command == 0xD4)
{
//fprintf(outFile, " ((Instrument/Volume/Pan Initial))");
//fprintf(outFile, " Volume %02X (%d) Instrument %02X (%d) Pan %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
currentVolume = buffer[spot];
currentInstrument = buffer[spot+1];
if (currentInstrument >= numberInstruments)
numberInstruments = currentInstrument + 1;
currentPan = buffer[spot+2];
spot += 3;
}
else if (command == 0xD5)
{
//fprintf(outFile, " ((Volume))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentVolume = buffer[spot];
spot++;
}
else if (command == 0xD6)
{
//fprintf(outFile, " ((Fade In/Out))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
currentVolume = buffer[spot + 1];
spot += 2;
}
else if (command == 0xD7)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xD8)
{
//fprintf(outFile, " ((Release Time))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xD9)
{
//fprintf(outFile, " ((Section Hold Note))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
sectionNoteHold = buffer[spot];
spot++;
}
else if (command == 0xDA)
{
//fprintf(outFile, " ((Reverb))");
//fprintf(outFile, " Type/Separation %02X (%d) Amount %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xDB)
{
//fprintf(outFile, " UNKNOWN (Invalid)");
break;
}
else if (command == 0xDC)
{
//fprintf(outFile, " UNKNOWN (Invalid)");
break;
}
else if (command == 0xDD)
{
//fprintf(outFile, " ((Pan))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentPan = buffer[spot];
spot++;
}
else if (command == 0xDE)
{
//fprintf(outFile, " Stereo Pan");
//fprintf(outFile, " Left %02X (%d) to Right %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xDF)
{
//fprintf(outFile, " ((Coarse Tune))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentCoarseTune = (signed char)buffer[spot];
spot++;
}
else if (command == 0xE0)
{
//fprintf(outFile, " ((Fine Tune))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE1)
{
//fprintf(outFile, " ((Tremolo))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xE2) // Jikkyou Powerful Pro Yakyuu 2000 (J) (V1.0) [!]
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE3) // Start new game and let go to hit
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
// E4??
else if (command == 0xE4) // Something weird about this, seems like a followup to a note, trying this for now
{
//fprintf(outFile, " ((Pitch Bend Previous Note))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
/*if (trackOutputNotes.size() > 0)
{
unsigned char endPitchBend = buffer[spot+2];
int pitchBendChange = endPitchBend - lastNoteValue;
if (pitchBendChange >= 2)
trackOutputNotes.back().pitchBend = 0x7F;
else if (pitchBendChange >= 1)
trackOutputNotes.back().pitchBend = 0x60;
else if (pitchBendChange <= -2)
trackOutputNotes.back().pitchBend = 0x00;
else if (pitchBendChange <= -1)
trackOutputNotes.back().pitchBend = 0x20;
else
trackOutputNotes.back().pitchBend = 0x40;
}*/
spot += 3;
}
else if (command == 0xE5) // No. 47 music
{
//fprintf(outFile, " ((Pitch Ascend Next Note))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xE6)
{
//fprintf(outFile, " ((Slide Notes in Section))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE7)
{
//fprintf(outFile, " ((Marker))");
loopSpot = spot - 1;
}
else if (command == 0xE8)
{
//fprintf(outFile, " ((Loop from Marker))");
//fprintf(outFile, " %02X (%d) Times %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
unsigned char readAmount = buffer[spot];
spot += 3;
if (readAmount > 0x01)
{
if (loopEndSpot != spot)
{
loopEndSpot = spot;
spot = loopSpot;
loopAmountsLeft = readAmount - 1;
}
else
{
loopAmountsLeft--;
if (loopAmountsLeft > 0)
{
spot = loopSpot;
}
else
{
// Reset
loopEndSpot = 0;
}
}
}
else if (readAmount == 0x00)
{
// Similar to master loop
if (extendTracksToHighest)
{
spot = loopSpot;
}
else if (totalLoopsToOutputLeft > 0)
{
spot = loopSpot;
totalLoopsToOutputLeft--;
}
}
}
else if (command == 0xE9)
{
//fprintf(outFile, " ((Nested Loop Marker))");
loopNestedSpot = spot - 1;
}
else if (command == 0xEA)
{
//fprintf(outFile, " ((Nested Loop from Marker))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
unsigned char readAmount = buffer[spot];
spot += 3;
if (readAmount > 0x01)
{
if (loopNestedEndSpot != spot)
{
loopNestedEndSpot = spot;
spot = loopNestedSpot;
loopNestedAmountsLeft = readAmount - 1;
}
else
{
loopNestedAmountsLeft--;
if (loopNestedAmountsLeft > 0)
{
spot = loopNestedSpot;
}
else
{
// Reset
loopNestedEndSpot = 0;
}
}
}
else if (readAmount == 0x00)
{
// Similar to master loop
if (extendTracksToHighest)
{
spot = loopNestedSpot;
}
else if (totalLoopsToOutputLeft > 0)
{
spot = loopNestedSpot;
totalLoopsToOutputLeft--;
}
}
}
else if (command == 0xEB)
{
//fprintf(outFile, " ((Master Loop Start))");
masterLoopMarkerStartOffset = spot;
}
else if (command == 0xEC)
{
//fprintf(outFile, " ((Master Loop End))");
masterLoopMarkerEndOffset = spot - 1;
if (extendTracksToHighest)
{
spot = masterLoopMarkerStartOffset;
}
else if (totalLoopsToOutputLeft > 0)
{
spot = masterLoopMarkerStartOffset;
totalLoopsToOutputLeft--;
}
}
else if (command == 0xED)
{
//fprintf(outFile, " ((Loop Skip Start))");
currentEDOffset = spot;
currentEEEndOffset = 0;
eeCountOverall = 0;
}
else if (command == 0xEE)
{
//fprintf(outFile, " ((Loop Skip Middle))");
if (eeCountOverall == 0)
{
if (currentEEEndOffset != 0x00000000)
{
spot = currentEEEndOffset;
}
eeCountOverall = 1;
}
else if (eeCountOverall == 1)
{
currentEEEndOffset = spot;
spot = currentEDOffset;
eeCountOverall = 0;
}
}
else if (command == 0xEF)
{
//fprintf(outFile, " ((Effect Delay))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentEffect = buffer[spot];
spot++;
}
else if (command == 0xF0)
{
currentBank = buffer[spot];
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF1)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF2)
{
//fprintf(outFile, " ((Delay Note))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
absoluteTime += buffer[spot];
lastNote00Length = false;
spot++;
}
else if (command == 0xF3)
{
//fprintf(outFile, " ((Previous Note Hold))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
lastNote00Length = false;
unsigned long noteDuration = buffer[spot];;
unsigned long noteLength = buffer[spot+1];
if (noteLength == 0)
noteLength = noteDuration;
else if (noteLength > noteDuration)
noteLength = noteDuration;
else if (noteLength <= noteDuration)
{
if (noteLength == 0x7F)
noteLength = noteDuration;
else
noteLength = noteLength;
}
if (trackOutputNotes.size() > 0)
{
trackOutputNotes.back().endAbsoluteTime += noteLength;
}
absoluteTime += noteDuration;
spot += 2;
}
// FA/FB Goemon's Great Adventure (U) - 0053D780, not sure if legit
else if (command == 0xFA)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xFB)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command >= 0xF4)
{
//fprintf(outFile, " End");
break;
}
else
{
CString tempStr;
tempStr.Format("Unknown Command %02X at Spot %04X", command, spot);
MessageBox(NULL, tempStr, "Error", NULL);
return;
}
}
previousCmd = command;
}
// Add to end
for (int x = 0; x < trackOutputNotes.size(); x++)
{
outputNotes.push_back(trackOutputNotes[x]);
}
}
void CMidiParse::ParseSSEQTrack(int trackNumber, int& numberInstruments, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfo>& outputNotes, unsigned char* inputMID, unsigned long offset, unsigned long end, int& noteUniqueId, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, int highestTrackLength)
{
std::vector<SngNoteInfo> trackOutputNotes;
unsigned char command = 0x00;
int spot = offset;
unsigned long absoluteTime = 0;
unsigned char currentPan = 0x40;
unsigned long currentInstrument = 0x00;
unsigned char currentVolume = 0x7F;
unsigned char currentBank = 0x00;
int currentEffect = 0;
unsigned long currentTempo = (unsigned long)(60000000.0 / (float)120.0);
signed long currentCoarseTune = 0x00;
unsigned char loopAmountsLeft = 0x00;
unsigned long loopSpot = 0;
unsigned long loopEndSpot = 0;
unsigned long masterLoopMarkerStartOffset;
unsigned long masterLoopMarkerEndOffset;
int totalLoopsToOutputLeft = 0;
if (writeOutLoops)
totalLoopsToOutputLeft = loopWriteCount;
unsigned char sectionNoteHold = 0x00;
std::map<int, SngNoteInfo> activeSngNotes;
while (spot < end)
{
if (extendTracksToHighest)
{
if (absoluteTime >= highestTrackLength)
break;
}
int startSpot = spot;
unsigned long original;
unsigned char* altPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
unsigned long deltaTime = GetVLBytes(inputMID, spot, original, altPattern, altOffset, altLength, false);
absoluteTime += deltaTime;
command = inputMID[spot];
if (command == 0x7)
{
currentInstrument = ((inputMID[spot + 2] << 8) | inputMID[spot + 1]);
//fprintf(outFile, " Instrument %02X%02X [Instrument Change]", inputMID[spot + 2], inputMID[spot + 1]);
if (currentInstrument > numberInstruments)
numberInstruments = currentInstrument + 1;
}
else if (command == 0xC)
{
currentVolume = inputMID[spot + 1];
}
else if (command == 0xD)
{
currentPan = inputMID[spot + 1];
}
else if (command == 0x11)
{
//fprintf(outFile, " Note %02X Velocity %02X [Note On]", inputMID[spot + 1], inputMID[spot + 2]);
unsigned char note = inputMID[spot + 1];
unsigned char velocity = inputMID[spot + 2];
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentCoarseTune;
songNoteInfo.instrument = currentInstrument;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
songNoteInfo.pan = currentPan & 0x7F;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = currentVolume & 0x7F;
songNoteInfo.endAbsoluteTime = 0;
activeSngNotes[note] = songNoteInfo;
}
else if (command == 0x12)
{
//fprintf(outFile, " Note %02X [Note Off]", inputMID[spot + 1]);
unsigned char note = inputMID[spot + 1];
if (activeSngNotes.find(note) != activeSngNotes.end())
{
activeSngNotes[note].endAbsoluteTime = absoluteTime;
trackOutputNotes.push_back(activeSngNotes[note]);
activeSngNotes.erase(activeSngNotes.find(note));
}
}
else if (command == 0x20)
{
//fprintf(outFile, " %02X %02X [Loop]", inputMID[spot + 1], inputMID[spot + 2]);
if (extendTracksToHighest)
{
spot = loopSpot;
}
}
else if (command == 0x22)
{
//fprintf(outFile, " [End]\n");
break;
}
else if (command == 0x23)
{
//fprintf(outFile, " [Loop Start]");
loopSpot = spot;
}
else
{
}
spot += sseqCommandSizes[command];
}
// Add to end
for (int x = 0; x < trackOutputNotes.size(); x++)
{
outputNotes.push_back(trackOutputNotes[x]);
}
}
void CMidiParse::WriteSngList(std::vector<SngNoteInfo> sngNoteList, std::vector<TimeAndValue> tempoPositions, CString outFileName, bool separateByInstrument, unsigned short division, bool expandBendRange, int bendRange)
{
// Convert SngList to Tracks, hopefully
int numChannels = 0;
std::vector<SngNoteInfo> channels[MAXCHANNELS];
// Combine Controllers
/*for (int x = 0; x < sngNoteList.size(); x++)
{
SngNoteInfo tempNoteInfo = sngNoteList[x];
int appliedChannel = -1;
for (int channel = 0; channel < MAXCHANNELS; channel++)
{
bool allowOnChannel = true;
for (int y = 0; y < channels[channel].size(); y++)
{
// Check if is valid
SngNoteInfo matchNoteInfo = channels[channel][y];
// Any overlap
if (IsOverlap(tempNoteInfo.startAbsoluteTime, tempNoteInfo.endAbsoluteTime, matchNoteInfo.startAbsoluteTime, matchNoteInfo.endAbsoluteTime))
{
if (
(tempNoteInfo.instrument != matchNoteInfo.instrument)
|| (tempNoteInfo.pan != matchNoteInfo.pan)
|| (tempNoteInfo.pitchBend != matchNoteInfo.pitchBend)
|| (tempNoteInfo.tempo != matchNoteInfo.tempo)
|| (tempNoteInfo.volume != matchNoteInfo.volume)
|| (tempNoteInfo.effect != matchNoteInfo.effect)
|| (tempNoteInfo.vibrato != matchNoteInfo.vibrato)
|| (tempNoteInfo.noteNumber == matchNoteInfo.noteNumber)
)
{
allowOnChannel = false;
break;
}
}
}
if (allowOnChannel)
{
appliedChannel = channel;
break;
}
}
if (appliedChannel == -1)
{
MessageBox(NULL, "Error, too many channels for midi", "Error", NULL);
delete [] instrumentLookup;
return;
}
else
{
if ((appliedChannel + 1) > numChannels)
numChannels = (appliedChannel + 1);
channels[appliedChannel].push_back(tempNoteInfo);
}
}*/
// Fix Transpose issues
for (int x = 0; x < sngNoteList.size(); x++)
{
if (sngNoteList[x].noteNumber < 0)
sngNoteList[x].noteNumber = 0x00;
else if (sngNoteList[x].noteNumber > 0x7F)
sngNoteList[x].noteNumber = 0x7F;
if (sngNoteList[x].pan > 0x7F)
sngNoteList[x].pan = 0x7F;
else if (sngNoteList[x].pan < 0)
sngNoteList[x].pan = 0x0;
if (sngNoteList[x].volume > 0x7F)
sngNoteList[x].volume = 0x7F;
else if (sngNoteList[x].volume < 0)
sngNoteList[x].volume = 0x0;
if (sngNoteList[x].effect > 0x7F)
sngNoteList[x].effect = 0x7F;
if (sngNoteList[x].pitchBend > 0x7F)
sngNoteList[x].pitchBend = 0x7F;
if (sngNoteList[x].vibrato > 0x7F)
sngNoteList[x].vibrato = 0x7F;
}
if (separateByInstrument)
{
for (int x = 0; x < sngNoteList.size(); x++)
{
SngNoteInfo tempNoteInfo = sngNoteList[x];
int appliedChannel = -1;
for (int channel = 0; channel < MAXCHANNELS; channel++)
{
for (int y = 0; y < channels[channel].size(); y++)
{
// Check if is valid
SngNoteInfo matchNoteInfo = channels[channel][y];
if (tempNoteInfo.instrument == matchNoteInfo.instrument)
{
appliedChannel = channel;
break;
}
}
if (appliedChannel != -1)
{
break;
}
}
if (appliedChannel == -1)
{
if (numChannels == (MAXCHANNELS - 1))
{
MessageBox(NULL, "Error, too many channels for midi", "Error", NULL);
return;
}
appliedChannel = numChannels;
}
channels[appliedChannel].push_back(tempNoteInfo);
if ((appliedChannel + 1) > numChannels)
numChannels = (appliedChannel + 1);
}
}
else
{
for (int x = 0; x < sngNoteList.size(); x++)
{
SngNoteInfo tempNoteInfo = sngNoteList[x];
int appliedChannel = tempNoteInfo.originalTrack;
if (appliedChannel == -1)
appliedChannel = 0;
if (appliedChannel > MAXCHANNELS)
{
MessageBox(NULL, "Error, too many channels for midi", "Error", NULL);
return;
}
channels[appliedChannel].push_back(tempNoteInfo);
if ((appliedChannel + 1) > numChannels)
numChannels = (appliedChannel + 1);
}
}
for (int x = 0; x < numChannels; x++)
{
std::sort(channels[x].begin(), channels[x].end(), sngSortByStartTime());
}
std::vector<SngNoteInfo> overlappingNotes;
// Check for note overlaps
for (int channel = 0; channel < numChannels; channel++)
{
for (int x = 0; x < channels[channel].size(); x++)
{
for (int y = (x + 1); y < channels[channel].size(); y++)
{
SngNoteInfo tempNoteInfo = channels[channel][x];
SngNoteInfo matchNoteInfo = channels[channel][y];
if (IsOverlap(tempNoteInfo.startAbsoluteTime, tempNoteInfo.endAbsoluteTime, matchNoteInfo.startAbsoluteTime, matchNoteInfo.endAbsoluteTime))
{
if (
(tempNoteInfo.instrument != matchNoteInfo.instrument)
|| (tempNoteInfo.pan != matchNoteInfo.pan)
|| (tempNoteInfo.pitchBend != matchNoteInfo.pitchBend)
|| (tempNoteInfo.volume != matchNoteInfo.volume)
|| (tempNoteInfo.effect != matchNoteInfo.effect)
|| (tempNoteInfo.vibrato != matchNoteInfo.vibrato)
)
{
overlappingNotes.push_back(channels[channel][y]);
channels[channel].erase(channels[channel].begin() + y);
y--;
}
}
}
}
}
std::sort(overlappingNotes.begin(), overlappingNotes.end(), sngSortByStartTime());
int startChannel = numChannels;
for (int x = 0; x < overlappingNotes.size(); x++)
{
int appliedChannel = -1;
for (int z = startChannel; z < MAXCHANNELS; z++)
{
bool overlapped = false;
for (int y = 0; y < channels[z].size(); y++)
{
SngNoteInfo tempNoteInfo = overlappingNotes[x];
SngNoteInfo matchNoteInfo = channels[z][y];
if (IsOverlap(tempNoteInfo.startAbsoluteTime, tempNoteInfo.endAbsoluteTime, matchNoteInfo.startAbsoluteTime, matchNoteInfo.endAbsoluteTime))
{
if (
(tempNoteInfo.instrument != matchNoteInfo.instrument)
|| (tempNoteInfo.pan != matchNoteInfo.pan)
|| (tempNoteInfo.pitchBend != matchNoteInfo.pitchBend)
|| (tempNoteInfo.volume != matchNoteInfo.volume)
|| (tempNoteInfo.effect != matchNoteInfo.effect)
|| (tempNoteInfo.vibrato != matchNoteInfo.vibrato)
)
{
overlapped = true;
break;
}
}
}
if (!overlapped)
{
appliedChannel = z;
break;
}
}
if ((appliedChannel > MAXCHANNELS) || (appliedChannel == -1))
{
MessageBox(NULL, "Error, too many channels for midi", "Error", NULL);
return;
}
channels[appliedChannel].push_back(overlappingNotes[x]);
if ((appliedChannel + 1) > numChannels)
numChannels = (appliedChannel + 1);
}
if (numChannels == 0)
{
// No Notes
::DeleteFile(outFileName);
return;
}
FILE* outFile = NULL;
for (int channel = 0; channel < numChannels; channel++)
{
FILE* outDebug = NULL;
CString tempChannelStr;
tempChannelStr.Format("%02X", channel);
//FILE* outDebug = fopen("C:\\temp\\outDebug_" + tempChannelStr + ".txt", "w");
/*if (outDebug != NULL)
{
for (int x = 0; x < channels[channel].size(); x++)
{
fprintf(outDebug, "Note %02X Start %08X End %08X\n", channels[channel][x].noteNumber, channels[channel][x].startAbsoluteTime, channels[channel][x].endAbsoluteTime);
}
}*/
if ((channel % 0x10) == 0)
{
if (outFile != NULL)
{
// just one track
fflush(outFile);
fclose(outFile);
outFile = NULL;
}
int midiNumber = channel / 0x10;
if (midiNumber == 0)
{
outFile = fopen(outFileName, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot open file for output midi " + outFileName, "Error", NULL);
return;
}
}
else
{
bool midiName = (outFileName.Find(".midi") != -1);
CString tempMidiNumber;
tempMidiNumber.Format("%s_AdditionalPart%d", outFileName, midiNumber);
tempMidiNumber.Replace(".midi", "");
tempMidiNumber.Replace(".mid", "");
if (midiName)
tempMidiNumber += ".midi";
else
tempMidiNumber += ".mid";
outFile = fopen(tempMidiNumber, "wb");
if (outFile == NULL)
{
MessageBox(NULL, "Cannot open file for output midi " + tempMidiNumber, "Error", NULL);
return;
}
}
// 1 For Tempo Positions
int numTracks = 0x11;
if ((numChannels - channel) < 0x10)
{
numTracks = (numChannels - channel) + 1;
}
unsigned long tempLong = Flip32Bit(0x4D546864);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00000006);
fwrite(&tempLong, 1 ,4 , outFile);
tempLong = Flip32Bit(0x00010000 | numTracks); // num tracks
fwrite(&tempLong, 1 ,4 , outFile);
unsigned short tempShort = division;
tempShort = Flip16Bit(tempShort);
fwrite(&tempShort, 1 ,2 , outFile);
unsigned long absoluteTimeTempo = 0;
std::vector<TrackEvent> trackEventsTempo;
// Write tempo track
for (int tempoIndex = 0; tempoIndex < tempoPositions.size(); tempoIndex++)
{
TrackEvent trackEventNewTempo;
unsigned long deltaTimeTempo = tempoPositions[tempoIndex].absoluteTime - absoluteTimeTempo;
trackEventNewTempo.deltaTime = deltaTimeTempo;
absoluteTimeTempo += deltaTimeTempo;
trackEventNewTempo.obsoleteEvent = false;
trackEventNewTempo.absoluteTime = absoluteTimeTempo;
trackEventNewTempo.type = 0xFF;
trackEventNewTempo.contentSize = 5;
trackEventNewTempo.contents = new byte[trackEventNewTempo.contentSize];
trackEventNewTempo.contents[0] = 0x51;
trackEventNewTempo.contents[1] = 0x3;
trackEventNewTempo.contents[2] = ((tempoPositions[tempoIndex].value >> 16) & 0xFF);
trackEventNewTempo.contents[3] = ((tempoPositions[tempoIndex].value >> 8) & 0xFF);
trackEventNewTempo.contents[4] = ((tempoPositions[tempoIndex].value >> 0) & 0xFF);
trackEventsTempo.push_back(trackEventNewTempo);
}
TrackEvent trackEventEndTempo;
trackEventEndTempo.deltaTime = 0;
trackEventEndTempo.obsoleteEvent = false;
trackEventEndTempo.absoluteTime = absoluteTimeTempo;
trackEventEndTempo.type = 0xFF;
trackEventEndTempo.contentSize = 2;
trackEventEndTempo.contents = new byte[trackEventEndTempo.contentSize];
trackEventEndTempo.contents[0] = 0x2F;
trackEventEndTempo.contents[1] = 0x0;
trackEventsTempo.push_back(trackEventEndTempo);
WriteSngToMidiTrack(outFile, outDebug, trackEventsTempo);
for (int eventCount = 0; eventCount < trackEventsTempo.size(); eventCount++)
{
if (trackEventsTempo[eventCount].contents != NULL)
{
delete [] trackEventsTempo[eventCount].contents;
trackEventsTempo[eventCount].contents = NULL;
}
}
}
unsigned long absoluteTime = 0;
std::vector<TrackEvent> trackEvents;
// MTrk
unsigned char currentPan = 0x40;
unsigned long currentInstrument = 0xFF;
unsigned char currentVolume = 0x7F;
unsigned char currentPitchBend = 0x40;
int currentEffect = 0;
unsigned char currentVibrato = 0x00;
int controller = channel % 0x10;
int currentSegmentNumber = -1;
if (channels[channel].size() > 0)
{
if (expandBendRange && (bendRange > 0))
{
if (bendRange > 24)
bendRange = 24;
if (bendRange < 1)
bendRange = 1;
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 101;
trackEventNew.contents[1] = 0;
trackEvents.push_back(trackEventNew);
}
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 100;
trackEventNew.contents[1] = 0;
trackEvents.push_back(trackEventNew);
}
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 6;
trackEventNew.contents[1] = bendRange;
trackEvents.push_back(trackEventNew);
}
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 38;
trackEventNew.contents[1] = 0;
trackEvents.push_back(trackEventNew);
}
}
}
std::vector<SngNoteInfo> pendingShutOffNotes;
for (int x = 0; x < channels[channel].size(); x++)
{
SngNoteInfo songNoteInfo = channels[channel][x];
bool errorStartEnd = (songNoteInfo.endAbsoluteTime <= songNoteInfo.startAbsoluteTime);
if (outDebug != NULL)
fprintf(outDebug, "Time: %08X ON %02X %04X: Start %08X End %08X Error %d\n", absoluteTime, songNoteInfo.noteNumber, x, songNoteInfo.startAbsoluteTime, songNoteInfo.endAbsoluteTime, errorStartEnd);
while (pendingShutOffNotes.size() > 0)
{
std::sort(pendingShutOffNotes.begin(), pendingShutOffNotes.end(), sngSortByEndTime());
if (pendingShutOffNotes[0].endAbsoluteTime < songNoteInfo.startAbsoluteTime)
{
if (outDebug != NULL)
fprintf(outDebug, "Time: %08X Note %02X Shut off: Start %08X End %08X Error %d\n", absoluteTime, pendingShutOffNotes[0].noteNumber, pendingShutOffNotes[0].startAbsoluteTime, pendingShutOffNotes[0].endAbsoluteTime, errorStartEnd);
unsigned long deltaTime = pendingShutOffNotes[0].endAbsoluteTime - absoluteTime;
TrackEvent trackEventNewNoteOff;
trackEventNewNoteOff.deltaTime = deltaTime;
trackEventNewNoteOff.obsoleteEvent = false;
trackEventNewNoteOff.absoluteTime = absoluteTime;
trackEventNewNoteOff.type = 0x80 | controller;
trackEventNewNoteOff.durationTime = 0; // to be filled in
trackEventNewNoteOff.contentSize = 2;
trackEventNewNoteOff.contents = new byte[trackEventNewNoteOff.contentSize];
trackEventNewNoteOff.contents[0] = pendingShutOffNotes[0].noteNumber;
trackEventNewNoteOff.contents[1] = pendingShutOffNotes[0].velocity;
trackEvents.push_back(trackEventNewNoteOff);
absoluteTime += deltaTime;
pendingShutOffNotes.erase(pendingShutOffNotes.begin());
}
else if (pendingShutOffNotes[0].endAbsoluteTime == songNoteInfo.startAbsoluteTime)
{
bool skipOff = false;
for (int y = x; y < channels[channel].size(); y++)
{
SngNoteInfo tempSongNoteInfo = channels[channel][y];
if (
(pendingShutOffNotes[0].endAbsoluteTime == tempSongNoteInfo.startAbsoluteTime)
&& (pendingShutOffNotes[0].noteNumber == tempSongNoteInfo.noteNumber)
&& (pendingShutOffNotes[0].instrument == tempSongNoteInfo.instrument)
&& (pendingShutOffNotes[0].originalTrack == tempSongNoteInfo.originalTrack)
&& (pendingShutOffNotes[0].originalNoteUniqueId == tempSongNoteInfo.originalNoteUniqueId)
)
{
if (outDebug != NULL)
fprintf(outDebug, "Time: %08X Merged Note %02X : Start %08X End %08X Start %08X End %08X Error %d\n", absoluteTime, pendingShutOffNotes[0].noteNumber, pendingShutOffNotes[0].startAbsoluteTime, pendingShutOffNotes[0].endAbsoluteTime, tempSongNoteInfo.startAbsoluteTime, tempSongNoteInfo.endAbsoluteTime, errorStartEnd);
pendingShutOffNotes[0] = tempSongNoteInfo;
channels[channel][y].ignoreNoteOn = true;
if (y == x)
songNoteInfo.ignoreNoteOn = true;
skipOff = true;
break;
}
else if (pendingShutOffNotes[0].endAbsoluteTime < tempSongNoteInfo.startAbsoluteTime)
{
break;
}
}
if (!skipOff)
{
unsigned long deltaTime = pendingShutOffNotes[0].endAbsoluteTime - absoluteTime;
TrackEvent trackEventNewNoteOff;
trackEventNewNoteOff.deltaTime = deltaTime;
trackEventNewNoteOff.obsoleteEvent = false;
trackEventNewNoteOff.absoluteTime = absoluteTime;
trackEventNewNoteOff.type = 0x80 | controller;
trackEventNewNoteOff.durationTime = 0; // to be filled in
trackEventNewNoteOff.contentSize = 2;
trackEventNewNoteOff.contents = new byte[trackEventNewNoteOff.contentSize];
trackEventNewNoteOff.contents[0] = pendingShutOffNotes[0].noteNumber;
trackEventNewNoteOff.contents[1] = pendingShutOffNotes[0].velocity;
trackEvents.push_back(trackEventNewNoteOff);
absoluteTime += deltaTime;
if (outDebug != NULL)
fprintf(outDebug, "Time: %08X Note %02X Shut off Couldn't Skip: Start %08X End %08X Error %d\n", absoluteTime, pendingShutOffNotes[0].noteNumber, pendingShutOffNotes[0].startAbsoluteTime, pendingShutOffNotes[0].endAbsoluteTime, errorStartEnd);
pendingShutOffNotes.erase(pendingShutOffNotes.begin());
}
}
else
{
break;
}
}
if (!separateByInstrument)
{
if (songNoteInfo.segmentNumber != currentSegmentNumber)
{
// Pending should be clear cause new segment
if (pendingShutOffNotes.size() > 0)
{
// Error
pendingShutOffNotes = pendingShutOffNotes;
}
TrackEvent trackEventNew;
trackEventNew.deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 104;
trackEventNew.contents[1] = songNoteInfo.segmentNumber;
trackEvents.push_back(trackEventNew);
currentSegmentNumber = songNoteInfo.segmentNumber;
}
}
unsigned long deltaTime = songNoteInfo.startAbsoluteTime - absoluteTime;
// Changed to master track
/*if (songNoteInfo.tempo != currentTempo)
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xFF;
trackEventNew.contentSize = 5;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 0x51;
trackEventNew.contents[1] = 0x3;
trackEventNew.contents[2] = ((songNoteInfo.tempo >> 16) & 0xFF);
trackEventNew.contents[3] = ((songNoteInfo.tempo >> 8) & 0xFF);
trackEventNew.contents[4] = ((songNoteInfo.tempo >> 0) & 0xFF);
trackEvents.push_back(trackEventNew);
currentTempo = songNoteInfo.tempo;
}*/
if (songNoteInfo.effect != currentEffect)
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 91; // reverb
trackEventNew.contents[1] = songNoteInfo.effect;
trackEvents.push_back(trackEventNew);
currentEffect = songNoteInfo.effect;
}
if (songNoteInfo.instrument != currentInstrument)
{
TrackEvent trackEventNewMSB;
trackEventNewMSB.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNewMSB.obsoleteEvent = false;
trackEventNewMSB.absoluteTime = absoluteTime;
trackEventNewMSB.type = 0xB0 | controller;
trackEventNewMSB.contentSize = 2;
trackEventNewMSB.contents = new byte[trackEventNewMSB.contentSize];
trackEventNewMSB.contents[0] = 00;
trackEventNewMSB.contents[1] = songNoteInfo.instrument / 0x8000;
trackEvents.push_back(trackEventNewMSB);
TrackEvent trackEventNewLSB;
trackEventNewLSB.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNewLSB.obsoleteEvent = false;
trackEventNewLSB.absoluteTime = absoluteTime;
trackEventNewLSB.type = 0xB0 | controller;
trackEventNewLSB.contentSize = 2;
trackEventNewLSB.contents = new byte[trackEventNewLSB.contentSize];
trackEventNewLSB.contents[0] = 32;
trackEventNewLSB.contents[1] = songNoteInfo.instrument / 0x80;
trackEvents.push_back(trackEventNewLSB);
TrackEvent trackEventNew;
trackEventNew.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xC0 | controller;
trackEventNew.contentSize = 1;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = songNoteInfo.instrument & 0x7F;
trackEvents.push_back(trackEventNew);
currentInstrument = songNoteInfo.instrument;
}
if (songNoteInfo.pan != currentPan)
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 10;
trackEventNew.contents[1] = songNoteInfo.pan;
trackEvents.push_back(trackEventNew);
currentPan = songNoteInfo.pan;
}
if (songNoteInfo.volume != currentVolume)
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 0x07;
trackEventNew.contents[1] = songNoteInfo.volume;
trackEvents.push_back(trackEventNew);
currentVolume = songNoteInfo.volume;
}
if (songNoteInfo.vibrato != currentVibrato)
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xB0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 0x01;
trackEventNew.contents[1] = songNoteInfo.vibrato;
trackEvents.push_back(trackEventNew);
currentVibrato = songNoteInfo.vibrato;
}
if (songNoteInfo.pitchBend != currentPitchBend)
{
TrackEvent trackEventNew;
trackEventNew.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNew.obsoleteEvent = false;
trackEventNew.absoluteTime = absoluteTime;
trackEventNew.type = 0xE0 | controller;
trackEventNew.contentSize = 2;
trackEventNew.contents = new byte[trackEventNew.contentSize];
trackEventNew.contents[0] = 0x00; // LSB
trackEventNew.contents[1] = songNoteInfo.pitchBend; // MSB
trackEvents.push_back(trackEventNew);
currentPitchBend = songNoteInfo.pitchBend;
}
if (!songNoteInfo.ignoreNoteOn)
{
// Note On
TrackEvent trackEventNewNoteOn;
trackEventNewNoteOn.deltaTime = deltaTime;
absoluteTime += deltaTime;
deltaTime = 0;
trackEventNewNoteOn.obsoleteEvent = false;
trackEventNewNoteOn.absoluteTime = absoluteTime;
trackEventNewNoteOn.type = 0x90 | controller;
trackEventNewNoteOn.contentSize = 2;
trackEventNewNoteOn.contents = new byte[trackEventNewNoteOn.contentSize];
trackEventNewNoteOn.contents[0] = songNoteInfo.noteNumber;
trackEventNewNoteOn.contents[1] = songNoteInfo.velocity;
trackEvents.push_back(trackEventNewNoteOn);
pendingShutOffNotes.push_back(songNoteInfo);
}
}
if (pendingShutOffNotes.size() > 0)
{
std::sort(pendingShutOffNotes.begin(), pendingShutOffNotes.end(), sngSortByEndTime());
while (pendingShutOffNotes.size() > 0)
{
unsigned long deltaTime = pendingShutOffNotes[0].endAbsoluteTime - absoluteTime;
TrackEvent trackEventNewNoteOff;
trackEventNewNoteOff.deltaTime = deltaTime;
trackEventNewNoteOff.obsoleteEvent = false;
trackEventNewNoteOff.absoluteTime = absoluteTime;
trackEventNewNoteOff.type = 0x80 | controller;
trackEventNewNoteOff.durationTime = 0; // to be filled in
trackEventNewNoteOff.contentSize = 2;
trackEventNewNoteOff.contents = new byte[trackEventNewNoteOff.contentSize];
trackEventNewNoteOff.contents[0] = pendingShutOffNotes[0].noteNumber;
trackEventNewNoteOff.contents[1] = pendingShutOffNotes[0].velocity;
trackEvents.push_back(trackEventNewNoteOff);
absoluteTime += deltaTime;
pendingShutOffNotes.erase(pendingShutOffNotes.begin());
}
}
TrackEvent trackEventEnd;
trackEventEnd.deltaTime = 0;
trackEventEnd.obsoleteEvent = false;
trackEventEnd.absoluteTime = absoluteTime;
trackEventEnd.type = 0xFF;
trackEventEnd.contentSize = 2;
trackEventEnd.contents = new byte[trackEventEnd.contentSize];
trackEventEnd.contents[0] = 0x2F;
trackEventEnd.contents[1] = 0x0;
trackEvents.push_back(trackEventEnd);
WriteSngToMidiTrack(outFile, outDebug, trackEvents);
if (outDebug != NULL)
fclose(outDebug);
for (int eventCount = 0; eventCount < trackEvents.size(); eventCount++)
{
if (trackEvents[eventCount].contents != NULL)
{
delete [] trackEvents[eventCount].contents;
trackEvents[eventCount].contents = NULL;
}
}
}
// just one track
if (outFile != NULL)
{
fflush(outFile);
fclose(outFile);
outFile = NULL;
}
}
int CMidiParse::FindHighestKonamiLengthTrack(int trackNumber, unsigned char* buffer, unsigned long offset, unsigned long end)
{
unsigned char command = 0x00;
unsigned long spot = offset;
unsigned long absoluteTime = 0;
unsigned char lastDuration = 0xFF;
unsigned char lastLength = 0xFF;
unsigned char loopAmountsLeft = 0x00;
unsigned long loopSpot = 0;
unsigned long loopEndSpot = 0;
unsigned char loopNestedAmountsLeft = 0x00;
unsigned long loopNestedSpot = 0;
unsigned long loopNestedEndSpot = 0;
unsigned char lastNoteValue = 0x00;
int currentEDOffset = 0;
int currentEEEndOffset = 0;
int eeCountOverall = 0;
bool lastNote00Length = false;
unsigned char lastNote = 0xFF;
unsigned char lastVelocity = 0xFF;
int previousCmd = -1;
while ((command != 0xFF) && (spot < end))
{
command = buffer[spot];
spot++;
if (command < 0xD0) // Note or Rest
{
unsigned char note = command;
unsigned char drumInstrumentValue = 0x00;
if ((command == 0x67) || (command == (0x67 + 0x68))) // Rest?
{
drumInstrumentValue = buffer[spot];
spot++;
}
if (note >= 0x68)
{
note -= 0x68;
}
else
{
lastDuration = buffer[spot];
spot++;
}
bool firstSetNote00Length = false;
if (buffer[spot] < 0x80)
{
lastLength = buffer[spot];
spot++;
if (lastLength == 0)
lastNote00Length = true;
else
lastNote00Length = false;
firstSetNote00Length = true;
}
else
{
if (lastLength == 0)
lastNote00Length = true;
else
lastNote00Length = false;
if ((lastLength == 0) && (previousCmd == 0xF2))
{
firstSetNote00Length = true;
}
else
{
firstSetNote00Length = false;
}
}
unsigned char velocity = buffer[spot] & 0x7F;
spot++;
unsigned long noteDuration = lastDuration;
unsigned long noteLength = lastLength;
if (noteLength == 0)
noteLength = noteDuration;
else if (noteLength > noteDuration)
noteLength = noteDuration;
else if (noteLength <= noteDuration)
{
if (noteLength == 0x7F)
noteLength = noteDuration;
else
noteLength = noteLength;
}
lastVelocity = velocity;
lastNote = note;
absoluteTime += noteDuration;
}
else
{
if (command == 0xD0)
{
//fprintf(outFile, " ((Tempo))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xD1)
{
//fprintf(outFile, " ((Tempo Change Fade))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xD2)
{
//fprintf(outFile, " ((Instrument Change))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xD3)
{
//fprintf(outFile, " ((Instrument/Volume Change))");
//fprintf(outFile, " Volume %02X (%d) Instrument %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xD4)
{
//fprintf(outFile, " ((Instrument/Volume/Pan Initial))");
//fprintf(outFile, " Volume %02X (%d) Instrument %02X (%d) Pan %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xD5)
{
//fprintf(outFile, " ((Volume))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xD6)
{
//fprintf(outFile, " ((Fade In/Out))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xD7)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xD8)
{
//fprintf(outFile, " ((Release Time))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xD9)
{
//fprintf(outFile, " ((Section Hold Note))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xDA)
{
//fprintf(outFile, " ((Reverb))");
//fprintf(outFile, " Type/Separation %02X (%d) Amount %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xDB)
{
//fprintf(outFile, " UNKNOWN (Invalid)");
break;
}
else if (command == 0xDC)
{
//fprintf(outFile, " UNKNOWN (Invalid)");
break;
}
else if (command == 0xDD)
{
//fprintf(outFile, " ((Pan))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xDE)
{
//fprintf(outFile, " Stereo Pan");
//fprintf(outFile, " Left %02X (%d) to Right %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xDF)
{
//fprintf(outFile, " ((Coarse Tune))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE0)
{
//fprintf(outFile, " ((Fine Tune))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE1)
{
//fprintf(outFile, " ((Tremolo))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xE2) // Jikkyou Powerful Pro Yakyuu 2000 (J) (V1.0) [!]
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE3) // Start new game and let go to hit
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
// E4??
else if (command == 0xE4) // Something weird about this, seems like a followup to a note, trying this for now
{
//fprintf(outFile, " ((Pitch Bend Previous Note))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
/*if (trackOutputNotes.size() > 0)
{
unsigned char endPitchBend = buffer[spot+2];
int pitchBendChange = endPitchBend - lastNoteValue;
if (pitchBendChange >= 2)
trackOutputNotes.back().pitchBend = 0x7F;
else if (pitchBendChange >= 1)
trackOutputNotes.back().pitchBend = 0x60;
else if (pitchBendChange <= -2)
trackOutputNotes.back().pitchBend = 0x00;
else if (pitchBendChange <= -1)
trackOutputNotes.back().pitchBend = 0x20;
else
trackOutputNotes.back().pitchBend = 0x40;
}*/
spot += 3;
}
else if (command == 0xE5) // No. 47 music
{
//fprintf(outFile, " ((Pitch Ascend Next Note))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xE6)
{
//fprintf(outFile, " ((Slide Notes in Section))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE7)
{
//fprintf(outFile, " ((Marker))");
loopSpot = spot - 1;
}
else if (command == 0xE8)
{
//fprintf(outFile, " ((Loop from Marker))");
//fprintf(outFile, " %02X (%d) Times %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
unsigned char readAmount = buffer[spot];
spot += 3;
if (readAmount > 0x01)
{
if (loopEndSpot != spot)
{
loopEndSpot = spot;
spot = loopSpot;
loopAmountsLeft = readAmount - 1;
}
else
{
loopAmountsLeft--;
if (loopAmountsLeft > 0)
{
spot = loopSpot;
}
else
{
// Reset
loopEndSpot = 0;
}
}
}
}
else if (command == 0xE9)
{
//fprintf(outFile, " ((Nested Loop Marker))");
loopNestedSpot = spot - 1;
}
else if (command == 0xEA)
{
//fprintf(outFile, " ((Nested Loop from Marker))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
unsigned char readAmount = buffer[spot];
spot += 3;
if (readAmount > 0x01)
{
if (loopNestedEndSpot != spot)
{
loopNestedEndSpot = spot;
spot = loopNestedSpot;
loopNestedAmountsLeft = readAmount - 1;
}
else
{
loopNestedAmountsLeft--;
if (loopNestedAmountsLeft > 0)
{
spot = loopNestedSpot;
}
else
{
// Reset
loopNestedEndSpot = 0;
}
}
}
}
else if (command == 0xEB)
{
//fprintf(outFile, " ((Master Loop Start))");
}
else if (command == 0xEC)
{
//fprintf(outFile, " ((Master Loop End))");
}
else if (command == 0xED)
{
//fprintf(outFile, " ((Loop Skip Start))");
currentEDOffset = spot;
currentEEEndOffset = 0;
eeCountOverall = 0;
}
else if (command == 0xEE)
{
//fprintf(outFile, " ((Loop Skip Middle))");
if (eeCountOverall == 0)
{
if (currentEEEndOffset != 0x00000000)
{
spot = currentEEEndOffset;
}
eeCountOverall = 1;
}
else if (eeCountOverall == 1)
{
currentEEEndOffset = spot;
spot = currentEDOffset;
eeCountOverall = 0;
}
}
else if (command == 0xEF)
{
//fprintf(outFile, " ((Effect Delay))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF0)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF1)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF2)
{
//fprintf(outFile, " ((Delay Note))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
absoluteTime += buffer[spot];
lastNote00Length = false;
spot++;
}
else if (command == 0xF3)
{
//fprintf(outFile, " ((Previous Note Hold))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
lastNote00Length = false;
unsigned long noteDuration = buffer[spot];;
unsigned long noteLength = buffer[spot+1];
if (noteLength == 0)
noteLength = noteDuration;
else if (noteLength > noteDuration)
noteLength = noteDuration;
else if (noteLength <= noteDuration)
{
if (noteLength == 0x7F)
noteLength = noteDuration;
else
noteLength = noteLength;
}
absoluteTime += noteDuration;
spot += 2;
}
// FA/FB Goemon's Great Adventure (U) - 0053D780, not sure if legit
else if (command == 0xFA)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xFB)
{
//fprintf(outFile, " ?");
//fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot+=2;
}
else if (command >= 0xF4)
{
//fprintf(outFile, " End");
break;
}
else
{
CString tempStr;
tempStr.Format("Unknown Command %02X at Spot %04X", command, spot);
MessageBox(NULL, tempStr, "Error", NULL);
return 0;
}
}
previousCmd = command;
}
return absoluteTime;
}
unsigned char CMidiParse::sseqCommandSizes[0x24] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x02, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x03, 0x02, 0x04, 0x05, 0x05, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x01, 0x01, 0x03, 0x03,
0x03, 0x01, 0x01, 0x01,
};
int CMidiParse::FindHighestSSEQLengthTrack(unsigned char* inputMID, int endSize, int numberTracks)
{
int highestTime = 0;
unsigned long offsetData = 0;
for (int track = 0; track < numberTracks; track++)
{
unsigned short extraFlag = CharArrayToShort(&inputMID[offsetData + 0xE]);
unsigned long sizeTrack = CharArrayToLong(&inputMID[offsetData + 0x10]);
if (extraFlag)
{
offsetData += 4;
}
offsetData += 0x14;
unsigned char command = 0x00;
int spot = offsetData;
unsigned long absoluteTime = 0;
while (spot < endSize)
{
unsigned long original;
unsigned char* altPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
unsigned long deltaTime = GetVLBytes(inputMID, spot, original, altPattern, altOffset, altLength, false);
absoluteTime += deltaTime;
command = inputMID[spot];
if (command == 0x22)
{
break;
}
spot += sseqCommandSizes[command];
}
if (absoluteTime > highestTime)
highestTime = absoluteTime;
offsetData += sizeTrack;
}
return highestTime;
}
void CMidiParse::ParsePaperMarioTrack(unsigned char* ROM, int romSize, int trackNumber, int& numberInstruments, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfo>& outputNotes, unsigned char* buffer, unsigned long offset, unsigned long end, int& noteUniqueId, unsigned long drumDataPointer, int numberDrum, unsigned long instrumentDataPointer, int numberInst, unsigned short trackFlags, std::vector<int>& usedExtraInstruments, unsigned char& currentPan, unsigned long& currentInstrument, unsigned char& currentVolume, int& currentEffect, unsigned long& currentTempo, signed long& currentCoarseTune, bool& setReverb, bool& setVolume, bool& setPan, int& absoluteTimeStart, int subSegmentCounter)
{
bool isDrumTrack = ((trackFlags & 0x80) == 0x80);
std::vector<SngNoteInfo> trackOutputNotes;
unsigned char command = 0xFF;
unsigned long spot = offset;
unsigned long absoluteTime = absoluteTimeStart;
std::vector<int> subroutineJumpSpots;
std::vector<int> subroutineEndSpot;
unsigned long randomJumpBackSpot = 0;
int randomJumpOffsetBackCounter = -1;
unsigned long absoluteTimeBeforeRandomJump = 0;
int numberSets = 0;
while (command != 0x00)
{
if (trackNumber >= 0)
{
if (trackNumber > 0)
{
for (int y = 0; y < tempoPositions.size(); y++)
{
if (tempoPositions[y].absoluteTime <= absoluteTime)
{
currentTempo = tempoPositions[y].value;
}
else
{
break;
}
}
}
}
if (subroutineJumpSpots.size() > 0)
{
if (subroutineEndSpot[subroutineEndSpot.size()-1] == spot)
{
//fprintf(outFile, "...((SubroutineEnd, going to %04X)) \n", subroutineJumpSpots[subroutineJumpSpots.size()-1]);
spot = subroutineJumpSpots[subroutineJumpSpots.size()-1];
subroutineJumpSpots.pop_back();
subroutineEndSpot.pop_back();
}
}
command = buffer[spot];
//fprintf(outFile, "%08X Time: %08X", spot, absoluteTime);
spot++;
if (command < 0x80)
{
if (command == 0x00)
{
if (randomJumpOffsetBackCounter == -1)
{
//fprintf(outFile, " 00 ((End)) \n");
break;
}
else
{
command = 0xFC;
//fprintf(outFile, "...((Random Jump End, going back to %04X)) \n", randomJumpBackSpot);
spot = randomJumpBackSpot;
}
}
else if (command < 0x78)
{
//fprintf(outFile, " ((Delay))");
//fprintf(outFile, " %02X (%d)", command, command);
absoluteTime += command;
}
else
{
unsigned long value = 0x78 + buffer[spot] + ((command & 0x7) << 8);
//fprintf(outFile, " ((Delay))");
//fprintf(outFile, " %02X (%d) %02X - %04X (%d)", command, command, buffer[spot], value, value);
spot++;
absoluteTime += value;
}
}
else
{
// 0x80 to 0xD4
if (command < 0xD4)
{
//fprintf(outFile, " Note: ");
unsigned char note = command & 0x7F;
unsigned char velocity = buffer[spot];
unsigned long length;
if (buffer[spot+1] < 0xC0)
{
length = buffer[spot+1];
//fprintf(outFile, " %02X (%d) [Really %02X (%0d)] Velocity %02X (%d) Length %02X (%d)", note, note, command, command, buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else
{
length = 0xC0 + ((buffer[spot+1] & 0x3F) << 8) + buffer[spot+2];
//fprintf(outFile, " %02X (%d) [Really %02X (%0d)] Velocity %02X (%d) Length %02X%02X - Means %04X (%d)", note, note, command, command, buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+2], length, length);
spot += 3;
}
if (!isDrumTrack)
{
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentCoarseTune + 0xC;
songNoteInfo.instrument = currentInstrument;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
songNoteInfo.pan = currentPan & 0x7F;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = ((currentVolume) & 0x7F);
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + length;
songNoteInfo.segmentNumber = subSegmentCounter;
trackOutputNotes.push_back(songNoteInfo);
}
else
{
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = trackNumber;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
if (note < 0x48)
{
songNoteInfo.noteNumber = note + 0xC;
songNoteInfo.instrument = (2 * 0x80);
}
else
{
songNoteInfo.noteNumber = 0x3C + currentCoarseTune + 0xC;
songNoteInfo.instrument = (note - 0x48) + (1 * 0x80);
int actualInstrument = buffer[drumDataPointer + ((note - 0x48) * 0xC) + 1];
if (!setVolume)
{
currentVolume = buffer[drumDataPointer + ((note - 0x48) * 0xC) + 4];
if (currentVolume > 0x7F)
currentVolume = 0x7F;
}
if (!setPan)
{
currentPan = (buffer[drumDataPointer + ((note - 0x48) * 0xC) + 5] & 0x7F);
}
if (!setReverb)
{
currentEffect = buffer[drumDataPointer + ((note - 0x48) * 0xC) + 6];
}
}
songNoteInfo.velocity = velocity;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
songNoteInfo.pan = currentPan & 0x7F;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = ((currentVolume) & 0x7F);
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + length;
songNoteInfo.segmentNumber = subSegmentCounter;
trackOutputNotes.push_back(songNoteInfo);
}
}
else
{
//fprintf(outFile, " Command: %02X ", command);
if (command == 0xE0)
{
//fprintf(outFile, " ((Master Tempo))");
//fprintf(outFile, " %04X (%d)", CharArrayToShort(&buffer[spot]), CharArrayToShort(&buffer[spot]));
unsigned short tempo = (buffer[spot] << 8) | buffer[spot+1];
currentTempo = (unsigned long)(60000000.0 / (float)tempo);
if (trackNumber == 0)
{
tempoPositions.push_back(TimeAndValue(absoluteTime, currentTempo));
}
spot += 2;
}
else if (command == 0xE1)
{
//fprintf(outFile, " ((Master Volume))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE2)
{
//fprintf(outFile, " ((Master Transpose))");
//fprintf(outFile, " %02X (%d)", buffer[spot], (signed char)buffer[spot]);
spot++;
}
else if (command == 0xE3)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xE4)
{
//fprintf(outFile, " ((Master Change Tempo))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2], buffer[spot+3], buffer[spot+3]);
unsigned short tempo = (buffer[spot+2] << 8) | buffer[spot+3];
currentTempo = (unsigned long)(60000000.0 / (float)tempo);
if (trackNumber == 0)
{
tempoPositions.push_back(TimeAndValue(absoluteTime, currentTempo));
}
spot += 4;
}
else if (command == 0xE5)
{
//fprintf(outFile, " ((Master Volume Fade In))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xE6)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xE7)
{
//fprintf(outFile, " ((?))");
}
else if (command == 0xE8)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
currentInstrument = buffer[spot+1] + (10 * 0x80);
if (std::find(usedExtraInstruments.begin(), usedExtraInstruments.end(), buffer[spot+1]) == usedExtraInstruments.end())
{
usedExtraInstruments.push_back(buffer[spot+1]);
}
spot += 2;
}
else if (command == 0xE9)
{
//fprintf(outFile, " ((Track Volume))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentVolume = buffer[spot];
if (currentVolume > 0x7F)
currentVolume = 0x7F;
spot++;
setVolume = true;
}
else if (command == 0xEA)
{
//fprintf(outFile, " ((Track Pan))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentPan = buffer[spot] & 0x7F;
spot++;
setPan = true;
}
else if (command == 0xEB)
{
//fprintf(outFile, " ((Reverb))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentEffect = buffer[spot];
spot++;
setReverb = true;
}
else if (command == 0xEC)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xED)
{
//fprintf(outFile, " ((Coarse Tune))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
currentCoarseTune = (signed char)buffer[spot];
spot++;
}
else if (command == 0xEE)
{
//fprintf(outFile, " ((Fine Tune))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xEF)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xF0)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xF1)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF2)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF3)
{
//fprintf(outFile, " ((?))");
}
else if (command == 0xF4)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1]);
spot += 2;
}
else if (command == 0xF5)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
if (!isDrumTrack)
{
currentInstrument = buffer[spot];
int actualInstrument = buffer[instrumentDataPointer + (currentInstrument * 8) + 1];
if (!setVolume)
{
currentVolume = buffer[instrumentDataPointer + (currentInstrument * 8) + 2];
if (currentVolume > 0x7F)
currentVolume = 0x7F;
}
if (!setPan)
{
currentPan = (buffer[instrumentDataPointer + (currentInstrument * 8) + 3] & 0x7F);
}
if (!setReverb)
{
currentEffect = buffer[instrumentDataPointer + (currentInstrument * 8) + 4];
}
}
/*if (currentInstrument < numberInst)
{
currentInstrument = buffer[instrumentDataPointer + (currentInstrument * 0x8) + 1];
}*/
spot++;
}
else if (command == 0xF6)
{
//fprintf(outFile, " ((Fade out/in volume of track))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
currentVolume = buffer[spot+2];
spot += 3;
}
else if (command == 0xF7)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d)", buffer[spot], buffer[spot]);
spot++;
}
else if (command == 0xF8)
{
//fprintf(outFile, " ((?))");
}
else if (command == 0xF9)
{
//fprintf(outFile, " ((?))");
}
else if (command == 0xFA)
{
//fprintf(outFile, " ((?))");
}
else if (command == 0xFB)
{
//fprintf(outFile, " ((?))");
}
else if (command == 0xFC)
{
unsigned short offsetsAt = ((buffer[spot] << 8) | buffer[spot+1]);
numberSets = buffer[spot+2];
if (randomJumpBackSpot != (spot - 1))
{
absoluteTimeBeforeRandomJump = absoluteTime;
randomJumpBackSpot = spot - 1;
randomJumpOffsetBackCounter = 0;
}
if (randomJumpOffsetBackCounter == 0)
{
//fprintf(outFile, " ((Jump from set))");
//fprintf(outFile, " Offset %02X%02X # Random Offsets %02X (%d) Entry #%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2], randomJumpOffsetBackCounter);
unsigned short jumpOffset = ((buffer[offsetsAt + (randomJumpOffsetBackCounter * 3)] << 8) | buffer[offsetsAt + (randomJumpOffsetBackCounter * 3) + 1]);
//fprintf(outFile, " #%02X Offset %02X%02X %02X", randomJumpOffsetBackCounter, inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3)], inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3) + 1], inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3) + 2]);
spot = jumpOffset;
randomJumpOffsetBackCounter++;
}
else
{
randomJumpOffsetBackCounter = -1;
spot += 3;
}
}
else if (command == 0xFD)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else if (command == 0xFE)
{
//fprintf(outFile, " ((Subroutine))");
//fprintf(outFile, " %02X (%d) %02X (%d) Length %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
unsigned short subroutineOffset = ((buffer[spot] << 8) | buffer[spot+1]);
int subroutineLengthLeft = buffer[spot + 2];
spot += 3;
subroutineJumpSpots.push_back(spot);
subroutineEndSpot.push_back(subroutineOffset + subroutineLengthLeft);
spot = subroutineOffset;
}
else if (command == 0xFF)
{
//fprintf(outFile, " ((?))");
//fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", buffer[spot], buffer[spot], buffer[spot+1], buffer[spot+1], buffer[spot+2], buffer[spot+2]);
spot += 3;
}
else
{
//fprintf(outFile, " UNKNOWN\n");
return;
}
}
}
//fprintf(outFile, "\n");
}
// Add to end
for (int x = 0; x < trackOutputNotes.size(); x++)
{
outputNotes.push_back(trackOutputNotes[x]);
}
absoluteTimeStart = absoluteTime;
}
void CMidiParse::PaperMarioToDebugTextFile(unsigned char* ROM, int romSize, CString gameName, unsigned long address, CString midiFile, CString textFileOut, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long extra)
{
CString filepath = midiFile;
FILE* inFile = fopen(filepath, "rb");
if (inFile == NULL)
{
MessageBox(NULL, "Can't read input file " + filepath, "Error", NULL);
return;
}
fseek(inFile, 0, SEEK_END);
int inputSize = ftell(inFile);
rewind(inFile);
unsigned char* inputMID = new unsigned char[inputSize];
fread(inputMID, 1, inputSize, inFile);
fclose(inFile);
PaperMarioToDebugTextFile(ROM, romSize, gameName, address, inputMID, inputSize, textFileOut, writeOutLoops, loopWriteCount, extendTracksToHighest, extraGameMidiInfo, extra);
delete [] inputMID;
}
void CMidiParse::PaperMarioToDebugTextFile(unsigned char* ROM, int romSize, CString gameName, unsigned long address, byte* inputMID, int inputSize, CString textFileOut, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long extra)
{
CString addressStr;
addressStr.Format("%08X", address);
FILE* outFile = fopen(textFileOut, "w");
if (outFile == NULL)
{
MessageBox(NULL,"Can't open output file " + textFileOut, "Error", NULL);
return;
}
fprintf(outFile, gameName + " - " + addressStr + "\n");
CString bgmName = ((char*)&inputMID[8]);
fprintf(outFile, "Header %02X %02X - Name %s\n", inputMID[6], inputMID[7], bgmName);
int numberSegments = inputMID[0x10];
fprintf(outFile, "# Segments %02X\n", numberSegments);
fprintf(outFile, "\n");
unsigned long drumDataPointer = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (0 * 2)]) << 2;
int numberDrums = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (1 * 2)]);
unsigned long instrumentDataPointer = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (2 * 2)]) << 2;
int numberInstruments = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (3 * 2)]);
for (int x = 0; x < numberDrums; x++)
{
unsigned long tempOffset = drumDataPointer + (x * 0xC);
fprintf(outFile, "Drum #%02X: Bank Start %02X Instrument %02X Coarse Tune %02X Fine Tune %02X Volume %02X Pan %02X Reverb %02X %02X %02X %02X %02X %02X\n", x, inputMID[tempOffset+0], inputMID[tempOffset+1], inputMID[tempOffset+2], inputMID[tempOffset+3], inputMID[tempOffset+4], inputMID[tempOffset+5], inputMID[tempOffset+6], inputMID[tempOffset+7], inputMID[tempOffset+8], inputMID[tempOffset+9], inputMID[tempOffset+0xA], inputMID[tempOffset+0xB]);
}
fprintf(outFile, "\n");
for (int x = 0; x < numberInstruments; x++)
{
unsigned long tempOffset = instrumentDataPointer + (x * 0x8);
fprintf(outFile, "Instrument #%02X: Bank Start %02X Instrument %02X Volume %02X Pan %02X Reverb %02X Coarse Tune %02X Fine Tune %02X %02X\n", x, inputMID[tempOffset+0], inputMID[tempOffset+1], inputMID[tempOffset+2], inputMID[tempOffset+3], inputMID[tempOffset+4], inputMID[tempOffset+5], inputMID[tempOffset+6], inputMID[tempOffset+7]);
}
fprintf(outFile, "\n");
for (int x = 0; x < numberSegments; x++)
{
unsigned long segmentDataPointer = CharArrayToShort(&inputMID[0x14 + (x * 2)]) << 2;
if (segmentDataPointer == 0x0000)
continue;
fprintf(outFile, "-----------------------------------------------------------\n");
fprintf(outFile, "Segment #%02X Data Offset %08X\n", x, segmentDataPointer);
fprintf(outFile, "-----------------------------------------------------------\n");
fprintf(outFile, "\n");
unsigned long segmentTempDataPointer = segmentDataPointer;
int segmentCounter = 0;
while (true)
{
if ((inputMID[segmentTempDataPointer] & 0x70) == 0x10)
{
unsigned long segmentDataOffset = segmentDataPointer + (CharArrayToShort(&inputMID[segmentTempDataPointer + 2]) << 2);
fprintf(outFile, "\n**********************************************\n");
fprintf(outFile, "Sub-Segment #%02X: Data Offset %08X\n", segmentCounter, segmentDataOffset);
fprintf(outFile, "**********************************************\n");
for (int trackNumber = 0; trackNumber < 0x10; trackNumber++)
{
if (CharArrayToLong(&inputMID[segmentDataOffset + (trackNumber * 4)]) != 0x00000000)
{
unsigned long trackDataOffset = segmentDataOffset + (CharArrayToShort(&inputMID[segmentDataOffset + (trackNumber * 4)]));
unsigned short trackFlags = (CharArrayToShort(&inputMID[segmentDataOffset + (trackNumber * 4 + 2)]));
CString extraTrackFlagsInfo;
if (trackFlags & 0x80)
extraTrackFlagsInfo + " Drum Track";
fprintf(outFile, "\nTrack #%02X: Data Offset %08X Track Flags %04X%s\n", trackNumber, trackDataOffset, trackFlags, extraTrackFlagsInfo);
PaperMarioTrackToDebugTextFile(outFile, inputMID, trackDataOffset, trackFlags);
}
}
}
else if ((inputMID[segmentTempDataPointer] & 0x70) == 0x00)
{
break;
}
segmentTempDataPointer += 4;
segmentCounter++;
}
fprintf(outFile, "\n\n");
}
fclose(outFile);
}
void CMidiParse::PaperMarioTrackToDebugTextFile(FILE* outFile, unsigned char* inputMID, unsigned long offset, unsigned short trackFlags)
{
bool isDrumTrack = ((trackFlags & 0x80) == 0x80);
unsigned char command = 0xFF;
unsigned long spot = offset;
unsigned long absoluteTime = 0;
std::vector<int> subroutineJumpSpots;
std::vector<int> subroutineEndSpot;
unsigned long randomJumpBackSpot = 0;
int randomJumpOffsetBackCounter = -1;
unsigned long absoluteTimeBeforeRandomJump = 0;
int numberSets = 0;
while (command != 0x00)
{
if (subroutineJumpSpots.size() > 0)
{
if (subroutineEndSpot[subroutineEndSpot.size()-1] == spot)
{
fprintf(outFile, "...((SubroutineEnd, going back to %04X)) \n", subroutineJumpSpots[subroutineJumpSpots.size()-1]);
spot = subroutineJumpSpots[subroutineJumpSpots.size()-1];
subroutineJumpSpots.pop_back();
subroutineEndSpot.pop_back();
}
}
command = inputMID[spot];
fprintf(outFile, "%08X Time: %08X (%d)", spot, absoluteTime, absoluteTime);
spot++;
if (command < 0x80)
{
if (command == 0x00)
{
if (randomJumpOffsetBackCounter == -1)
{
fprintf(outFile, " 00 ((End)) \n");
break;
}
else
{
command = 0xFC;
fprintf(outFile, "...((Random Jump End, going back to %04X)) \n", randomJumpBackSpot);
spot = randomJumpBackSpot;
if (randomJumpOffsetBackCounter < numberSets)
{
absoluteTime = absoluteTimeBeforeRandomJump;
}
}
}
else if (command < 0x78)
{
fprintf(outFile, " ((Delay))");
fprintf(outFile, " %02X (%d)", command, command);
absoluteTime += command;
}
else
{
unsigned long value = 0x78 + inputMID[spot] + ((command & 0x7) << 8);
fprintf(outFile, " ((Delay))");
fprintf(outFile, " %02X (%d) %02X - %04X (%d)", command, command, inputMID[spot], value, value);
spot++;
absoluteTime += value;
}
}
else
{
// 0x80 to 0xD4
if (command < 0xD4)
{
if (!isDrumTrack)
{
fprintf(outFile, " Note: ");
}
else
{
fprintf(outFile, " Drum: ");
}
unsigned char note = command & 0x7F;
unsigned char velocity = inputMID[spot];
unsigned long length;
if (inputMID[spot+1] < 0xC0)
{
length = inputMID[spot+1];
fprintf(outFile, " %02X (%d) [Really %02X (%0d)] Velocity %02X (%d) Length %02X (%d)", note, note, command, command, inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else
{
length = 0xC0 + ((inputMID[spot+1] & 0x3F) << 8) | inputMID[spot+2];
fprintf(outFile, " %02X (%d) [Really %02X (%0d)] Velocity %02X (%d) Length %02X%02X - Means %04X (%d)", note, note, command, command, inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+2], length, length);
spot += 3;
}
if (isDrumTrack)
{
if (note < 0x48)
{
fprintf(outFile, " Percussion Bank # %02X ", note);
}
else
{
fprintf(outFile, " Drum Bank Instrument # %02X ", note - 0x48);
}
}
}
else
{
fprintf(outFile, " Command: %02X ", command);
if (command == 0xE0)
{
fprintf(outFile, " ((Master Tempo))");
fprintf(outFile, " %04X (%d)", CharArrayToShort(&inputMID[spot]), CharArrayToShort(&inputMID[spot]));
spot += 2;
}
else if (command == 0xE1)
{
fprintf(outFile, " ((Master Volume))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xE2)
{
fprintf(outFile, " ((Master Transpose))");
fprintf(outFile, " %02X (%d)", inputMID[spot], (signed char)inputMID[spot]);
spot++;
}
else if (command == 0xE3)
{
fprintf(outFile, " ((?))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xE4)
{
fprintf(outFile, " ((Master Change Tempo))");
fprintf(outFile, " Delay %02X%02X (%d) Tempo %02X%02X (%d)", inputMID[spot], inputMID[spot+1], ((inputMID[spot] << 8) | inputMID[spot+1]), inputMID[spot+2], inputMID[spot+3], ((inputMID[spot+2] << 8) | inputMID[spot+3]));
spot += 4;
}
else if (command == 0xE5)
{
fprintf(outFile, " ((Master Volume Fade In))");
fprintf(outFile, " Delay %02X%02X (%d) Volume %02X (%d)", inputMID[spot], inputMID[spot+1], ((inputMID[spot] << 8) | inputMID[spot+1]), inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xE6)
{
fprintf(outFile, " ((Master Effect))");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xE7)
{
fprintf(outFile, " ((?))");
}
else if (command == 0xE8)
{
fprintf(outFile, " ((Load Instrument))");
fprintf(outFile, " Bank Type %02X (%d) Instrument %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xE9)
{
fprintf(outFile, " ((Track Volume))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xEA)
{
fprintf(outFile, " ((Track Pan))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xEB)
{
fprintf(outFile, " ((Track Reverb))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xEC)
{
fprintf(outFile, " ((Segment Track Volume))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xED)
{
fprintf(outFile, " ((Coarse Tune))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xEE)
{
fprintf(outFile, " ((Fine Tune))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xEF)
{
fprintf(outFile, " ((Coarse/Fine Tune Track))");
fprintf(outFile, " Coarse %02X (%d) Fine %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xF0)
{
fprintf(outFile, " ((Tremolo))");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xF1)
{
fprintf(outFile, " ((?))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xF2)
{
fprintf(outFile, " ((?))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xF3)
{
fprintf(outFile, " ((Stop Tremolo))");
}
else if (command == 0xF4)
{
fprintf(outFile, " ((?))");
fprintf(outFile, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
spot += 2;
}
else if (command == 0xF5)
{
fprintf(outFile, " ((Instrument))");
fprintf(outFile, " Instrument %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xF6)
{
fprintf(outFile, " ((Fade out/in volume of track))");
fprintf(outFile, " Delay %02X%02X (%d) Volume %02X (%d)", inputMID[spot], inputMID[spot+1], ((inputMID[spot] << 8) | inputMID[spot+1]), inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xF7)
{
fprintf(outFile, " ((Track Reverb Type))");
fprintf(outFile, " %02X (%d)", inputMID[spot], inputMID[spot]);
spot++;
}
else if (command == 0xF8)
{
fprintf(outFile, " ((?))");
}
else if (command == 0xF9)
{
fprintf(outFile, " ((?))");
}
else if (command == 0xFA)
{
fprintf(outFile, " ((?))");
}
else if (command == 0xFB)
{
fprintf(outFile, " ((?))");
}
else if (command == 0xFC)
{
unsigned short offsetsAt = ((inputMID[spot] << 8) | inputMID[spot+1]);
numberSets = inputMID[spot+2];
if (randomJumpBackSpot != (spot - 1))
{
absoluteTimeBeforeRandomJump = absoluteTime;
randomJumpBackSpot = spot - 1;
randomJumpOffsetBackCounter = 0;
}
if (randomJumpOffsetBackCounter < numberSets)
{
fprintf(outFile, " ((Jump from set))");
fprintf(outFile, " Offset %02X%02X # Random Offsets %02X (%d) Entry #%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2], randomJumpOffsetBackCounter);
unsigned short jumpOffset = ((inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3)] << 8) | inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3) + 1]);
fprintf(outFile, " #%02X Offset %02X%02X %02X", randomJumpOffsetBackCounter, inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3)], inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3) + 1], inputMID[offsetsAt + (randomJumpOffsetBackCounter * 3) + 2]);
spot = jumpOffset;
randomJumpOffsetBackCounter++;
}
else
{
randomJumpOffsetBackCounter = -1;
spot += 3;
}
}
else if (command == 0xFD)
{
fprintf(outFile, " ((?))");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else if (command == 0xFE)
{
fprintf(outFile, " ((Subroutine))");
fprintf(outFile, " Offset %02X%02X Length %02X (%d)", inputMID[spot], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
unsigned short subroutineOffset = ((inputMID[spot] << 8) | inputMID[spot+1]);
int subroutineLengthLeft = inputMID[spot + 2];
spot += 3;
subroutineJumpSpots.push_back(spot);
subroutineEndSpot.push_back(subroutineOffset + subroutineLengthLeft);
spot = subroutineOffset;
}
else if (command == 0xFF)
{
fprintf(outFile, " ((?))");
fprintf(outFile, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
spot += 3;
}
else
{
fprintf(outFile, " UNKNOWN\n");
return;
}
}
}
fprintf(outFile, "\n");
}
}
void CMidiParse::WritePaperMarioDelay(unsigned long delay, unsigned char* outputBuffer, int& outputPosition)
{
while (delay > 0)
{
if (delay < 0x78)
{
outputBuffer[outputPosition++] = delay;
delay = 0;
}
else
{
delay = delay - 0x78;
unsigned long maskLowExtra = delay >> 8;
if (maskLowExtra > 7)
maskLowExtra = 7;
outputBuffer[outputPosition++] = 0x78 | maskLowExtra;
delay = delay - (maskLowExtra << 8);
unsigned long extraByte = 0;
if (delay > 0)
{
if (delay > 0x78)
extraByte = 0x78;
else
extraByte = delay;
}
outputBuffer[outputPosition++] = extraByte;
delay = delay - extraByte;
}
}
}
bool CMidiParse::MidiToPaperMario(CString input[4], CString output, bool loop, unsigned long& loopPoint, unsigned long name)
{
SngSegmentInfoPaperMario sngSegments[4];
for (int segmentNumber = 0; segmentNumber < 4; segmentNumber++)
{
if (input[segmentNumber] == "")
continue;
std::vector<TimeAndValue> tempoPositions;
std::vector<SngNoteInfoMidiImport> channels[0x10];
int numChannels = 0;
std::vector<int> instruments;
int lowestAbsoluteTime = 0x7FFFFFFF;
int highestAbsoluteTime = 0;
unsigned short division = 0x30;
if (!MidiToPaperMarioSngList(input[segmentNumber], tempoPositions, channels, numChannels, instruments, lowestAbsoluteTime, highestAbsoluteTime, loop, loopPoint, division))
return false;
std::vector<int> subSegments;
for (int trackNum = 0; trackNum < 0x10; trackNum++)
{
for (int x = 0; x < channels[trackNum].size(); x++)
{
if (std::find(subSegments.begin(), subSegments.end(), channels[trackNum][x].segmentNumber) == subSegments.end())
{
subSegments.push_back(channels[trackNum][x].segmentNumber);
}
}
}
float noteTimeDivisor = division / 0x30;
unsigned long loopPointReal = (float)loopPoint / noteTimeDivisor;
// Renumber segments
for (int trackNum = 0; trackNum < 0x10; trackNum++)
{
for (int x = 0; x < channels[trackNum].size(); x++)
{
int oldSegment = channels[trackNum][x].segmentNumber;
bool notFoundSeg = false;
for (int s = 0; s < subSegments.size(); s++)
{
if (oldSegment == subSegments[s])
{
int newSegmentNumber = s;
if (loop && (channels[trackNum][x].startAbsoluteTime >= loopPointReal))
newSegmentNumber++;
channels[trackNum][x].segmentNumber = newSegmentNumber;
notFoundSeg = true;
break;
}
}
if (!notFoundSeg)
{
// Should never happen
channels[trackNum][x].segmentNumber = 0;
}
}
}
subSegments.clear();
for (int trackNum = 0; trackNum < 0x10; trackNum++)
{
for (int x = 0; x < channels[trackNum].size(); x++)
{
if (std::find(subSegments.begin(), subSegments.end(), channels[trackNum][x].segmentNumber) == subSegments.end())
{
subSegments.push_back(channels[trackNum][x].segmentNumber);
}
}
}
std::vector<int> subSegmentStarts;
std::vector<int> subSegmentEnds;
subSegmentStarts.resize(subSegments.size());
subSegmentEnds.resize(subSegments.size());
for (int subSegment = 0; subSegment < subSegments.size(); subSegment++)
{
int startSegment = 0x7FFFFFFF;
int endSegment = 0;
for (int trackNum = 0; trackNum < 0x10; trackNum++)
{
for (int x = 0; x < channels[trackNum].size(); x++)
{
if (subSegment == channels[trackNum][x].segmentNumber)
{
if (channels[trackNum][x].startAbsoluteTime < startSegment)
startSegment = channels[trackNum][x].startAbsoluteTime;
if (channels[trackNum][x].endAbsoluteTime > endSegment)
endSegment = channels[trackNum][x].endAbsoluteTime;
}
}
}
if (subSegment == 0)
{
subSegmentStarts[subSegment] = 0;
}
else
{
subSegmentStarts[subSegment] = startSegment;
}
subSegmentEnds[subSegment] = endSegment;
}
for (int x = 0; x < subSegments.size(); x++)
{
for (int y = 0; y < subSegments.size(); y++)
{
if (x != y)
{
if (IsOverlap(subSegmentStarts[x], subSegmentEnds[x], subSegmentStarts[y], subSegmentEnds[y]))
{
int iResults = MessageBox(NULL, "Warning Overlap of sub-segments", "Do you want to continue?", MB_YESNO);
if (iResults == IDNO)
return false;
x = subSegments.size();
y = subSegments.size();
break;
}
}
}
}
for (int trackNum = 0; trackNum < 0x10; trackNum++)
{
for (int x = 0; x < channels[trackNum].size(); x++)
{
sngSegments[segmentNumber].sngSegmentTracks[trackNum].sngNoteList.push_back(channels[trackNum][x]);
}
}
sngSegments[segmentNumber].tempoPositions = tempoPositions;
}
std::vector<SngDrumPaperMario> drumsList;
std::vector<SngInstrumentPaperMario> instrumentsList;
return MidiToPaperMario(output, drumsList, instrumentsList, sngSegments, name, loop);
}
bool CMidiParse::MidiToPaperMario(CString output, std::vector<SngDrumPaperMario> drums, std::vector<SngInstrumentPaperMario> instruments, SngSegmentInfoPaperMario sngSegments[4], unsigned long name, bool loop)
{
/*{
FILE* testoutFile = fopen("C:\\temp\\a.txt", "w");
for (int x = 1; x < 32151; x++)
{
unsigned char* testoutputBuffer = new unsigned char[0x110];
for (int x = 0; x < 0x110; x++)
testoutputBuffer[x] = 0;
int testPos = 0;
WritePaperMarioDelay(x, testoutputBuffer, testPos);
fprintf(testoutFile, "%d,", x);
for (int y = 0; y < testPos; y++)
fprintf(testoutFile, "%02X", testoutputBuffer[y]);
fprintf(testoutFile, ",");
unsigned long value = 0;
int newPos = 0;
while (testoutputBuffer[newPos] != 0)
{
if (testoutputBuffer[newPos] < 0x78)
{
fprintf(testoutFile, " ((Delay))");
fprintf(testoutFile, " %02X (%d)", testoutputBuffer[newPos], testoutputBuffer[newPos]);
value += testoutputBuffer[newPos];
newPos++;
}
else
{
value += 0x78 + testoutputBuffer[newPos + 1] + ((testoutputBuffer[newPos] & 0x7) << 8);
fprintf(testoutFile, " ((Delay))");
fprintf(testoutFile, " %02X (%d) %02X - %04X (%d)", testoutputBuffer[newPos], testoutputBuffer[newPos], testoutputBuffer[newPos + 1], value, value);
newPos += 2;
}
}
if (value != x)
{
value = value;
}
fprintf(testoutFile, ",Match %d \n", value);
}
fclose(testoutFile);
}*/
int outputPosition = 0;
unsigned char* outputBuffer = new unsigned char[0x100000];
for (int x = 0; x < 0x100000; x++)
outputBuffer[x] = 0x00;
WriteLongToBuffer(outputBuffer, outputPosition, 0x42474D20);
outputPosition += 4;
int finalSizePosition = outputPosition;
// Size here
outputPosition += 4;
WriteLongToBuffer(outputBuffer, outputPosition, name);
outputPosition += 4;
WriteLongToBuffer(outputBuffer, outputPosition, 0x00000000);
outputPosition += 4;
int numberSegments = 4;
outputBuffer[outputPosition] = 0x04;
outputBuffer[outputPosition + 1] = 0x00;
outputBuffer[outputPosition + 2] = 0x00;
outputBuffer[outputPosition + 3] = 0x00;
outputPosition += 4;
int segmentOffsetPosition = outputPosition;
outputPosition += (2 * numberSegments);
int drumOffsetPosition = outputPosition;
outputPosition += 2;
WriteShortToBuffer(outputBuffer, outputPosition, drums.size());
outputPosition += 2;
int instrumentOffsetPosition = outputPosition;
outputPosition += 2;
WriteShortToBuffer(outputBuffer, outputPosition, instruments.size());
outputPosition += 2;
if (drums.size() > 0)
WriteShortToBuffer(outputBuffer, drumOffsetPosition, (outputPosition >> 2));
else
WriteShortToBuffer(outputBuffer, drumOffsetPosition, 0);
for (int x = 0; x < drums.size(); x++)
{
outputBuffer[outputPosition++] = drums[x].flags;
outputBuffer[outputPosition++] = drums[x].instrument;
outputBuffer[outputPosition++] = drums[x].unknown2;
outputBuffer[outputPosition++] = drums[x].unknown3;
outputBuffer[outputPosition++] = drums[x].volume;
outputBuffer[outputPosition++] = drums[x].pan;
outputBuffer[outputPosition++] = drums[x].effect;
outputBuffer[outputPosition++] = drums[x].unknown7;
outputBuffer[outputPosition++] = drums[x].unknown8;
outputBuffer[outputPosition++] = drums[x].unknown9;
outputBuffer[outputPosition++] = drums[x].unknownA;
outputBuffer[outputPosition++] = drums[x].unknownB;
}
if (instruments.size() > 0)
WriteShortToBuffer(outputBuffer, instrumentOffsetPosition, (outputPosition >> 2));
else
WriteShortToBuffer(outputBuffer, instrumentOffsetPosition, 0x0000);
for (int x = 0; x < instruments.size(); x++)
{
outputBuffer[outputPosition++] = instruments[x].flags;
outputBuffer[outputPosition++] = instruments[x].instrument;
outputBuffer[outputPosition++] = instruments[x].volume;
outputBuffer[outputPosition++] = instruments[x].pan;
outputBuffer[outputPosition++] = instruments[x].effect;
outputBuffer[outputPosition++] = instruments[x].unknown5;
outputBuffer[outputPosition++] = instruments[x].unknown6;
outputBuffer[outputPosition++] = instruments[x].unknown7;
}
int segmentOffsetPointers[4];
std::vector<int> subSegments[4];
for (int segment = 0; segment < numberSegments; segment++)
{
bool hasNote = false;
for (int trackNumber = 0; trackNumber < 0x10; trackNumber++)
{
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList.size() > 0)
{
hasNote = true;
break;
}
}
if (hasNote)
{
WriteShortToBuffer(outputBuffer, segmentOffsetPosition + (segment * 2), (outputPosition >> 2));
segmentOffsetPointers[segment] = outputPosition;
}
else
{
WriteShortToBuffer(outputBuffer, segmentOffsetPosition + (segment * 2), 0x0000);
segmentOffsetPointers[segment] = 0x00000000;
continue;
}
for (int trackNumber = 0; trackNumber < 0x10; trackNumber++)
{
for (int y = 0; y < sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList.size(); y++)
{
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].segmentNumber != -1)
{
if (std::find(subSegments[segment].begin(), subSegments[segment].end(), sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].segmentNumber) == subSegments[segment].end())
{
subSegments[segment].push_back(sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].segmentNumber);
}
}
}
}
std::sort(subSegments[segment].begin(), subSegments[segment].end());
bool didSpecial30 = false;
if (subSegments[segment].size() > 0)
{
for (int x = 0; x < (subSegments[segment][subSegments[segment].size() - 1] + 1); x++)
{
// Skip one
if (std::find(subSegments[segment].begin(), subSegments[segment].end(), x) == subSegments[segment].end())
{
WriteLongToBuffer(outputBuffer, outputPosition, 0x30000000);
didSpecial30 = true;
}
outputPosition += 4;
}
}
if (didSpecial30)
{
WriteLongToBuffer(outputBuffer, outputPosition, 0x50000000);
outputPosition += 4;
}
// Last 00000000 terminator
outputPosition += 4;
}
for (int segment = 0; segment < numberSegments; segment++)
{
if (subSegments[segment].size() > 0)
{
bool isAfterLoopSubSegment = false;
for (int x = 0; x < (subSegments[segment][subSegments[segment].size() - 1] + 1); x++)
{
int maxAbsoluteTime = 0;
if (std::find(subSegments[segment].begin(), subSegments[segment].end(), x) != subSegments[segment].end())
{
for (int trackNumber = 0; trackNumber < 0x10; trackNumber++)
{
for (int y = 0; y < sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList.size(); y++)
{
if (x == sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].segmentNumber)
{
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].endAbsoluteTime > maxAbsoluteTime)
{
maxAbsoluteTime = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].endAbsoluteTime;
}
}
}
}
if (sngSegments[segment].sngSubSegmentInfo.find(x) != sngSegments[segment].sngSubSegmentInfo.end())
{
if (maxAbsoluteTime < sngSegments[segment].sngSubSegmentInfo[x].endSegmentTime)
{
maxAbsoluteTime = sngSegments[segment].sngSubSegmentInfo[x].endSegmentTime;
}
}
bool isDrumTrack = false;
WriteLongToBuffer(outputBuffer, segmentOffsetPointers[segment] + (x * 4), 0x10000000 | ((outputPosition - segmentOffsetPointers[segment]) >> 2));
int trackPointerOffset = outputPosition;
outputPosition += 0x40;
for (int trackNumber = 0; trackNumber < 0x10; trackNumber++)
{
if ((trackNumber == 0) || (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList.size() > 0))
{
// Flags
//0x0080 Drum Track
if (isDrumTrack)
{
WriteShortToBuffer(outputBuffer, trackPointerOffset + (trackNumber * 0x4), ((outputPosition - trackPointerOffset)));
// Flags
WriteShortToBuffer(outputBuffer, trackPointerOffset + (trackNumber * 0x4) + 2, 0xE080);
}
else
{
WriteShortToBuffer(outputBuffer, trackPointerOffset + (trackNumber * 0x4), ((outputPosition - trackPointerOffset)));
// Flags
WriteShortToBuffer(outputBuffer, trackPointerOffset + (trackNumber * 0x4) + 2, 0xA000);
}
}
else
{
WriteShortToBuffer(outputBuffer, trackPointerOffset + (trackNumber * 0x4), 0x0000);
WriteShortToBuffer(outputBuffer, trackPointerOffset + (trackNumber * 0x4) + 2, 0x0000);
continue;
}
int absoluteTime = 0;
int startAbsoluteTime = 0;
if (sngSegments[segment].sngSubSegmentInfo.find(x) != sngSegments[segment].sngSubSegmentInfo.end())
{
absoluteTime = sngSegments[segment].sngSubSegmentInfo[x].startSegmentTime;
startAbsoluteTime = sngSegments[segment].sngSubSegmentInfo[x].startSegmentTime;;
}
if (trackNumber == 0)
{
// Tempo only
for (int t = 0; t < sngSegments[segment].tempoPositions.size(); t++)
{
if (sngSegments[segment].tempoPositions[t].absoluteTime >= startAbsoluteTime)
{
if (sngSegments[segment].tempoPositions[t].absoluteTime >= maxAbsoluteTime)
break;
if ((t > 0) && (sngSegments[segment].tempoPositions[t].value == sngSegments[segment].tempoPositions[t - 1].value))
continue;
if (sngSegments[segment].tempoPositions[t].absoluteTime > absoluteTime)
{
WritePaperMarioDelay((sngSegments[segment].tempoPositions[t].absoluteTime - absoluteTime), outputBuffer, outputPosition);
absoluteTime = sngSegments[segment].tempoPositions[t].absoluteTime;
}
unsigned short tempoValue = sngSegments[segment].tempoPositions[t].value;
outputBuffer[outputPosition++] = 0xE0;
WriteShortToBuffer(outputBuffer, outputPosition, tempoValue);
outputPosition += 2;
if (t == 0)
{
// Write Master Volume
outputBuffer[outputPosition++] = 0xE1;
outputBuffer[outputPosition++] = 0x64;
// Write Effect
outputBuffer[outputPosition++] = 0xE6;
WriteShortToBuffer(outputBuffer, outputPosition, 0x0001);
outputPosition += 2;
}
}
}
}
else
{
int currentInstrument = -1;
int currentVolume = -1;
int currentPan = -1;
int currentReverb = -1;
for (int y = 0; y < sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList.size(); y++)
{
if (x == sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].segmentNumber)
{
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].startAbsoluteTime > absoluteTime)
{
WritePaperMarioDelay((sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].startAbsoluteTime - absoluteTime), outputBuffer, outputPosition);
absoluteTime = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].startAbsoluteTime;
}
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].effect != currentReverb)
{
outputBuffer[outputPosition++] = 0xEB;
outputBuffer[outputPosition++] = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].effect;
currentReverb = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].effect;
}
if (isDrumTrack)
{
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].volume != currentVolume)
{
outputBuffer[outputPosition++] = 0xE9;
outputBuffer[outputPosition++] = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].volume;
currentVolume = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].volume;
}
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].pan != currentPan)
{
outputBuffer[outputPosition++] = 0xEA;
outputBuffer[outputPosition++] = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].pan;
currentPan = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].pan;
}
// TODO do this
}
else
{
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].instrument != currentInstrument)
{
bool foundInstrument = false;
for (int i = 0; i < instruments.size(); i++)
{
if (instruments[i].instrument == sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].instrument)
{
foundInstrument = true;
outputBuffer[outputPosition++] = 0xF5;
outputBuffer[outputPosition++] = instruments[i].instrument;
currentInstrument = instruments[i].instrument;
break;
}
}
if (!foundInstrument)
{
outputBuffer[outputPosition++] = 0xE8;
outputBuffer[outputPosition++] = 0x30;
outputBuffer[outputPosition++] = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].instrument;
currentInstrument = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].instrument;
}
}
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].volume != currentVolume)
{
outputBuffer[outputPosition++] = 0xE9;
outputBuffer[outputPosition++] = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].volume;
currentVolume = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].volume;
}
if (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].pan != currentPan)
{
outputBuffer[outputPosition++] = 0xEA;
outputBuffer[outputPosition++] = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].pan;
currentPan = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].pan;
}
unsigned char noteNumber = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].noteNumber - 0xC;
if (noteNumber > 0x53)
noteNumber = 0x53;
unsigned long noteLength = (sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].endAbsoluteTime - sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].startAbsoluteTime);
int originalLength = noteLength;
if (noteLength > 0xD3FF)
noteLength = 0xD3FF;
outputBuffer[outputPosition++] = noteNumber + 0x80;
outputBuffer[outputPosition++] = sngSegments[segment].sngSegmentTracks[trackNumber].sngNoteList[y].velocity;
if (noteLength < 0xC0)
{
outputBuffer[outputPosition++] = noteLength;
noteLength = 0;
}
else
{
noteLength = noteLength - 0xC0;
unsigned long maskLowExtra = noteLength >> 8;
if (maskLowExtra > 0x3F)
maskLowExtra = 0x3F;
outputBuffer[outputPosition++] = 0xC0 | maskLowExtra;
noteLength = noteLength - (maskLowExtra << 8);
unsigned long extraByte = 0;
if (noteLength > 0)
{
if (noteLength > 0xFF)
extraByte = 0xFF;
else
extraByte = noteLength;
}
outputBuffer[outputPosition++] = extraByte;
noteLength = noteLength - extraByte;
}
}
}
}
}
if (absoluteTime < maxAbsoluteTime)
{
WritePaperMarioDelay((maxAbsoluteTime - absoluteTime), outputBuffer, outputPosition);
absoluteTime = maxAbsoluteTime;
}
// End
outputBuffer[outputPosition++] = 0x00;
if ((outputPosition % 4) != 0)
{
int pad = 4 - (outputPosition % 4);
for (int p = 0; p < pad; p++)
outputBuffer[outputPosition++] = 0x00;
}
}
isAfterLoopSubSegment = false;
}
else
{
isAfterLoopSubSegment = true;
}
}
}
}
WriteLongToBuffer(outputBuffer, finalSizePosition, outputPosition);
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] outputBuffer;
MessageBox(NULL, "Error outputting file", "Error", NULL);
return false;
}
fwrite(outputBuffer, 1, outputPosition, outFile);
delete [] outputBuffer;
fclose(outFile);
return true;
}
void CMidiParse::TestPaperMarioToMidi(unsigned char* ROM, int romSize, byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool calculateInstrumentCountOnly, bool separateByInstrument, std::vector<SngInstrumentPaperMario>& usedInstruments, std::vector<SngDrumPaperMario>& usedPercussionSet, std::vector<int>& usedExtraInstruments, bool combineSegments)
{
numberInstruments = 1;
int numberSegments = inputMID[0x10];
unsigned long name = CharArrayToLong(&inputMID[8]);
unsigned long drumDataPointer = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (0 * 2)]) << 2;
int numberDrum = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (1 * 2)]);
unsigned long instrumentDataPointer = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (2 * 2)]) << 2;
int numberInst = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (3 * 2)]);
// Test Output
std::vector<SngDrumPaperMario> drums;
for (int x = 0; x < numberDrum; x++)
{
SngDrumPaperMario drumInfo;
drumInfo.flags = inputMID[drumDataPointer + (x * 0xC) + 0x0];
drumInfo.instrument = inputMID[drumDataPointer + (x * 0xC) + 0x1];
drumInfo.unknown2 = inputMID[drumDataPointer + (x * 0xC) + 0x2];
drumInfo.unknown3 = inputMID[drumDataPointer + (x * 0xC) + 0x3];
drumInfo.volume = inputMID[drumDataPointer + (x * 0xC) + 0x4];
drumInfo.pan = inputMID[drumDataPointer + (x * 0xC) + 0x5];
drumInfo.effect = inputMID[drumDataPointer + (x * 0xC) + 0x6];
drumInfo.unknown7 = inputMID[drumDataPointer + (x * 0xC) + 0x7];
drumInfo.unknown8 = inputMID[drumDataPointer + (x * 0xC) + 0x8];
drumInfo.unknown9 = inputMID[drumDataPointer + (x * 0xC) + 0x9];
drumInfo.unknownA = inputMID[drumDataPointer + (x * 0xC) + 0xA];
drumInfo.unknownB = inputMID[drumDataPointer + (x * 0xC) + 0xB];
drums.push_back(drumInfo);
usedPercussionSet.push_back(drumInfo);
}
std::vector<SngInstrumentPaperMario> instruments;
for (int x = 0; x < numberInst; x++)
{
SngInstrumentPaperMario instrumentInfo;
instrumentInfo.flags = inputMID[instrumentDataPointer + (x * 0x8) + 0x0];
instrumentInfo.instrument = inputMID[instrumentDataPointer + (x * 0x8) + 0x1];
instrumentInfo.volume = inputMID[instrumentDataPointer + (x * 0x8) + 0x2];
instrumentInfo.pan = inputMID[instrumentDataPointer + (x * 0x8) + 0x3];
instrumentInfo.effect = inputMID[instrumentDataPointer + (x * 0x8) + 0x4];
instrumentInfo.unknown5 = inputMID[instrumentDataPointer + (x * 0x8) + 0x5];
instrumentInfo.unknown6 = inputMID[instrumentDataPointer + (x * 0x8) + 0x6];
instrumentInfo.unknown7 = inputMID[instrumentDataPointer + (x * 0x8) + 0x7];
instruments.push_back(instrumentInfo);
usedInstruments.push_back(instrumentInfo);
}
SngSegmentInfoPaperMario sngSegments[4];
for (int x = 0; x < numberSegments; x++)
{
unsigned long segmentDataPointer = CharArrayToShort(&inputMID[0x14 + (x * 2)]) << 2;
if (segmentDataPointer == 0x0000)
continue;
unsigned long segmentTempDataPointer = segmentDataPointer;
int segmentCounter = 0;
unsigned char currentPan = 0x40;
unsigned long currentInstrument = 0x00;
unsigned char currentVolume = 0x7F;
int currentEffect = 0;
unsigned long currentTempo = (unsigned long)(60000000.0 / (float)120.0);
signed long currentCoarseTune = 0x00;
bool setReverb = false;
bool setVolume = false;
bool setPan = false;
std::vector<SngNoteInfo> sngNoteList;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
int absoluteTimeStart[0x10];
for (int a = 0; a < 0x10; a++)
absoluteTimeStart[a] = 0;
while (true)
{
if ((inputMID[segmentTempDataPointer] & 0x70) == 0x10)
{
unsigned long segmentDataOffset = segmentDataPointer + (CharArrayToShort(&inputMID[segmentTempDataPointer + 2]) << 2);
unsigned long previousTempo = currentTempo;
sngSegments[x].sngSubSegmentInfo[segmentCounter].startSegmentTime = absoluteTimeStart[0];
for (int trackNumber = 0; trackNumber < 0x10; trackNumber++)
{
if (CharArrayToLong(&inputMID[segmentDataOffset + (trackNumber * 4)]) != 0x00000000)
{
unsigned long trackDataOffset = segmentDataOffset + (CharArrayToShort(&inputMID[segmentDataOffset + (trackNumber * 4)]));
unsigned short trackFlags = (CharArrayToShort(&inputMID[segmentDataOffset + (trackNumber * 4 + 2)]));
SngSegmentInfoPaperMario* sngSegmentInfo = &(sngSegments[x]);
sngSegmentInfo->sngSubSegmentInfo[segmentCounter].trackFlags = trackFlags;
SngSegmentTrackInfoPaperMario* sngSegmentTrackInfo = &(sngSegmentInfo->sngSegmentTracks[trackNumber]);
ParsePaperMarioTrack(ROM, romSize, trackNumber, numberInstruments, tempoPositions, sngSegmentTrackInfo->sngNoteList, inputMID, trackDataOffset, inputSize, noteUniqueId, drumDataPointer, numberDrum, instrumentDataPointer, numberInst, trackFlags, usedExtraInstruments, currentPan, currentInstrument, currentVolume, currentEffect, currentTempo, currentCoarseTune, setReverb, setVolume, setPan, absoluteTimeStart[trackNumber], segmentCounter);
sngSegmentTrackInfo->sngNoteList = sngSegmentTrackInfo->sngNoteList;
}
}
sngSegments[x].sngSubSegmentInfo[segmentCounter].endSegmentTime = absoluteTimeStart[0];
if (tempoPositions.size() == 0)
{
tempoPositions.push_back(TimeAndValue(0, currentTempo));
}
if (tempoPositions[0].absoluteTime != 0)
{
tempoPositions.insert(tempoPositions.begin(), TimeAndValue(0, previousTempo));
}
sngSegments[x].tempoPositions = tempoPositions;
}
else if ((inputMID[segmentTempDataPointer] & 0x70) == 0x00)
{
break;
}
segmentTempDataPointer += 4;
segmentCounter++;
}
}
MidiToPaperMario("C:\\GoldeneyeStuff\\N64Hack\\ROMs\\GoodSet\\papermariooutput.bin", drums, instruments, sngSegments, name, false);
}
void CMidiParse::PaperMarioToMidi(unsigned char* ROM, int romSize, byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool calculateInstrumentCountOnly, bool separateByInstrument, std::vector<SngInstrumentPaperMario>& usedInstruments, std::vector<SngDrumPaperMario>& usedPercussionSet, std::vector<int>& usedExtraInstruments, bool combineSegments)
{
numberInstruments = 1;
int numberSegments = inputMID[0x10];
unsigned long drumDataPointer = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (0 * 2)]) << 2;
int numberDrum = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (1 * 2)]);
unsigned long instrumentDataPointer = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (2 * 2)]) << 2;
int numberInst = CharArrayToShort(&inputMID[0x14 + (numberSegments * 2) + (3 * 2)]);
std::vector<SngDrumPaperMario> drums;
for (int x = 0; x < numberDrum; x++)
{
SngDrumPaperMario drumInfo;
drumInfo.flags = inputMID[drumDataPointer + (x * 0xC) + 0x0];
drumInfo.instrument = inputMID[drumDataPointer + (x * 0xC) + 0x1];
drumInfo.unknown2 = inputMID[drumDataPointer + (x * 0xC) + 0x2];
drumInfo.unknown3 = inputMID[drumDataPointer + (x * 0xC) + 0x3];
drumInfo.volume = inputMID[drumDataPointer + (x * 0xC) + 0x4];
drumInfo.pan = inputMID[drumDataPointer + (x * 0xC) + 0x5];
drumInfo.effect = inputMID[drumDataPointer + (x * 0xC) + 0x6];
drumInfo.unknown7 = inputMID[drumDataPointer + (x * 0xC) + 0x7];
drumInfo.unknown8 = inputMID[drumDataPointer + (x * 0xC) + 0x8];
drumInfo.unknown9 = inputMID[drumDataPointer + (x * 0xC) + 0x9];
drumInfo.unknownA = inputMID[drumDataPointer + (x * 0xC) + 0xA];
drumInfo.unknownB = inputMID[drumDataPointer + (x * 0xC) + 0xB];
usedPercussionSet.push_back(drumInfo);
}
std::vector<SngInstrumentPaperMario> instruments;
for (int x = 0; x < numberInst; x++)
{
SngInstrumentPaperMario instrumentInfo;
instrumentInfo.flags = inputMID[instrumentDataPointer + (x * 0x8) + 0x0];
instrumentInfo.instrument = inputMID[instrumentDataPointer + (x * 0x8) + 0x1];
instrumentInfo.volume = inputMID[instrumentDataPointer + (x * 0x8) + 0x2];
instrumentInfo.pan = inputMID[instrumentDataPointer + (x * 0x8) + 0x3];
instrumentInfo.effect = inputMID[instrumentDataPointer + (x * 0x8) + 0x4];
instrumentInfo.unknown5 = inputMID[instrumentDataPointer + (x * 0x8) + 0x5];
instrumentInfo.unknown6 = inputMID[instrumentDataPointer + (x * 0x8) + 0x6];
instrumentInfo.unknown7 = inputMID[instrumentDataPointer + (x * 0x8) + 0x7];
usedInstruments.push_back(instrumentInfo);
}
for (int x = 0; x < numberSegments; x++)
{
unsigned long segmentDataPointer = CharArrayToShort(&inputMID[0x14 + (x * 2)]) << 2;
if (segmentDataPointer == 0x0000)
continue;
unsigned long segmentTempDataPointer = segmentDataPointer;
int segmentCounter = 0;
unsigned char currentPan = 0x40;
unsigned long currentInstrument = 0x00;
unsigned char currentVolume = 0x7F;
int currentEffect = 0;
unsigned long currentTempo = (unsigned long)(60000000.0 / (float)120.0);
signed long currentCoarseTune = 0x00;
bool setReverb = false;
bool setVolume = false;
bool setPan = false;
std::vector<SngNoteInfo> sngNoteList;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
int absoluteTimeStartTempo = 0;
while (true)
{
if ((inputMID[segmentTempDataPointer] & 0x70) == 0x10)
{
unsigned long segmentDataOffset = segmentDataPointer + (CharArrayToShort(&inputMID[segmentTempDataPointer + 2]) << 2);
if (!combineSegments)
{
sngNoteList.clear();
noteUniqueId = 0;
tempoPositions.clear();
}
unsigned long previousTempo = absoluteTimeStartTempo;
int currentAbsoluteStart = absoluteTimeStartTempo;
for (int trackNumber = 0; trackNumber < 0x10; trackNumber++)
{
if (CharArrayToLong(&inputMID[segmentDataOffset + (trackNumber * 4)]) != 0x00000000)
{
unsigned long trackDataOffset = segmentDataOffset + (CharArrayToShort(&inputMID[segmentDataOffset + (trackNumber * 4)]));
unsigned short trackFlags = (CharArrayToShort(&inputMID[segmentDataOffset + (trackNumber * 4 + 2)]));
int absoluteTimeStart;
if (!combineSegments)
absoluteTimeStart = 0;
else
absoluteTimeStart = previousTempo;
ParsePaperMarioTrack(ROM, romSize, trackNumber, numberInstruments, tempoPositions, sngNoteList, inputMID, trackDataOffset, inputSize, noteUniqueId, drumDataPointer, numberDrum, instrumentDataPointer, numberInst, trackFlags, usedExtraInstruments, currentPan, currentInstrument, currentVolume, currentEffect, currentTempo, currentCoarseTune, setReverb, setVolume, setPan, absoluteTimeStart, segmentCounter);
if (trackNumber == 0)
absoluteTimeStartTempo = absoluteTimeStart;
}
}
if (tempoPositions.size() == 0)
{
tempoPositions.push_back(TimeAndValue(0, currentTempo));
}
if (tempoPositions[0].absoluteTime != 0)
{
tempoPositions.insert(tempoPositions.begin(), TimeAndValue(0, previousTempo));
}
if (!combineSegments)
{
// Adjust for empty master track
for (int x = 0; x < sngNoteList.size(); x++)
{
if (sngNoteList[x].originalTrack > 0)
sngNoteList[x].originalTrack--;
}
}
if (!combineSegments)
{
bool midiName = (outFileName.Find(".midi") != -1);
CString tempMidiNumber;
tempMidiNumber.Format("%s_Segment%d_SubSegment%d", outFileName, x, segmentCounter);
tempMidiNumber.Replace(".midi", "");
tempMidiNumber.Replace(".mid", "");
if (midiName)
tempMidiNumber += ".midi";
else
tempMidiNumber += ".mid";
WriteSngList(sngNoteList, tempoPositions, tempMidiNumber, separateByInstrument, 0x0030, false, 24);
}
}
else if ((inputMID[segmentTempDataPointer] & 0x70) == 0x00)
{
break;
}
segmentTempDataPointer += 4;
segmentCounter++;
}
if (combineSegments)
{
// Adjust for empty master track
for (int x = 0; x < sngNoteList.size(); x++)
{
if (sngNoteList[x].originalTrack > 0)
sngNoteList[x].originalTrack--;
}
bool midiName = (outFileName.Find(".midi") != -1);
CString tempMidiNumber;
tempMidiNumber.Format("%s_Segment%d", outFileName, x);
tempMidiNumber.Replace(".midi", "");
tempMidiNumber.Replace(".mid", "");
if (midiName)
tempMidiNumber += ".midi";
else
tempMidiNumber += ".mid";
WriteSngList(sngNoteList, tempoPositions, tempMidiNumber, separateByInstrument, 0x0030, false, 24);
}
}
}
bool CMidiParse::MidiToEADMusicSngList(CString input, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfoMidiImport> channels[0x10], int& numChannels, int& lowestAbsoluteTime, int& highestAbsoluteTime, bool loop, unsigned long loopPoint, unsigned short & division)
{
numChannels = 0;
lowestAbsoluteTime = 0x7FFFFFFF;
highestAbsoluteTime = 0;
int noteUniqueId = 0;
numberTracks = 0;
CString tempFileName = input;
struct stat results;
stat(tempFileName, &results);
FILE* inFile1 = fopen(tempFileName, "rb");
if (inFile1 == NULL)
{
MessageBox(NULL, "Error reading file", "Error", NULL);
return false;
}
byte* inputMID = new byte[results.st_size];
fread(inputMID, 1, results.st_size, inFile1);
fclose(inFile1);
unsigned long header = CharArrayToLong(&inputMID[0]);
if (header != 0x4D546864)
{
delete [] inputMID;
MessageBox(NULL, "Invalid midi hdr", "Error", NULL);
return false;
}
unsigned long headerLength = CharArrayToLong(&inputMID[4]);
unsigned short type = CharArrayToShort(&inputMID[8]);
unsigned short numTracks = CharArrayToShort(&inputMID[0xA]);
division = CharArrayToShort(&inputMID[0xC]);
float noteTimeDivisor = division / 0x30;
loopPoint = (float)loopPoint / noteTimeDivisor;
if (type == 0)
{
}
else if (type == 1)
{
}
else
{
delete [] inputMID;
MessageBox(NULL, "Invalid midi type", "Error", NULL);
return false;
}
int position = 0xE;
byte* repeatPattern = NULL;
byte altOffset = 0;
byte altLength = 0;
bool unknownsHit = false;
for (int trackNum = 0; trackNum < numTracks; trackNum++)
{
std::vector<SngNoteInfoMidiImport> pendingNoteList;
unsigned char currentPan[0x10];
unsigned char currentVolume[0x10];
unsigned char currentReverb[0x10];
signed char currentPitchBend[0x10];
unsigned char currentVibrato[0x10];
unsigned char currentMSBBank[0x10];
unsigned char currentLSBBank[0x10];
unsigned char currentInstrument[0x10];
// Controllers defaults
for (int x = 0; x < 0x10; x++)
{
currentPan[x] = 0x40;
currentVolume[x] = 0x7F;
currentReverb[x] = 0x00;
currentInstrument[x] = 0x00;
currentPitchBend[x] = 0x40;
currentVibrato[x] = 0x00;
currentMSBBank[x] = 0x00;
currentLSBBank[x] = 0x00;
}
unsigned long absoluteTime = 0;
float absoluteTimeFloat = 0;
unsigned long trackHeader = ((((((inputMID[position] << 8) | inputMID[position+1]) << 8) | inputMID[position+2]) << 8) | inputMID[position+3]);
if (trackHeader != 0x4D54726B)
{
delete [] inputMID;
MessageBox(NULL, "Invalid track midi hdr", "Error", NULL);
return false;
}
unsigned long trackLength = ((((((inputMID[position+4] << 8) | inputMID[position+5]) << 8) | inputMID[position+6]) << 8) | inputMID[position+7]);
position += 8;
byte previousEventValue = 0xFF;
bool endFlag = false;
while (!endFlag && (position < results.st_size))
{
unsigned long original;
unsigned long timeTag = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
absoluteTimeFloat += (float)timeTag / noteTimeDivisor;
absoluteTime = absoluteTimeFloat;
byte eventVal = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
bool statusBit = false;
if (eventVal <= 0x7F)
{
// continuation
statusBit = true;
}
else
{
statusBit = false;
}
if (eventVal == 0xFF) // meta event
{
byte subType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (subType == 0x2F) //End of Track Event.
{
endFlag = true;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false); // end 00 in real mid
}
else if (subType == 0x51) //Set Tempo Event.
{
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned char byteData[3];
byteData[0] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byteData[1] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
byteData[2] = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
unsigned long microSecondsSinceQuarterNote = ((((byteData[0] << 8) | byteData[1]) << 8) | byteData[2]);
unsigned long tempTempo = 60000000.0 / microSecondsSinceQuarterNote;
if (tempTempo > 255)
tempTempo = 255;
else if (tempTempo < 1)
tempTempo = 1;
else
tempTempo = (unsigned char)tempTempo;
bool matchTempo = false;
for (int y = 0; y < tempoPositions.size(); y++)
{
if (tempoPositions[y].absoluteTime == absoluteTime)
{
matchTempo = true;
}
}
if (!matchTempo)
{
tempoPositions.push_back(TimeAndValue(absoluteTime, tempTempo));
}
}
//Various Unused Meta Events.
else if ((subType < 0x7F) && !(subType == 0x51 || subType == 0x2F))
{
//newTrackEvent->type = 0xFF;
unsigned long length = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
for (int i = 0; i < length; i++)
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
else if (subType == 0x7F) //Unused Sequencer Specific Event.
{
//newTrackEvent->type = 0xFF;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
previousEventValue = eventVal;
}
// Note off
else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
if (!statusBit)
previousEventValue = eventVal;
}
else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0)))
{
byte curEventVal;
byte noteNumber;
if (statusBit)
{
noteNumber = eventVal;
curEventVal = previousEventValue;
}
else
{
noteNumber = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte velocity = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
if (velocity == 0)
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
}
else
{
// If wasn't shut off, turn it off from before, then start new note
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Go backwards in list
if (pendingNoteList[p].noteNumber == noteNumber)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
pendingNoteList.erase(pendingNoteList.begin() + p);
break;
}
}
SngNoteInfoMidiImport newSongInfo;
newSongInfo.originalController = controller;
newSongInfo.originalTrack = trackNum;
newSongInfo.originalNoteUniqueId = noteUniqueId++;
newSongInfo.noteNumber = noteNumber;
newSongInfo.velocity = velocity;
// Apply tempo later as master track
//newSongInfo.tempo = currentTempo;
newSongInfo.pan = currentPan[controller];
newSongInfo.volume = currentVolume[controller];
newSongInfo.vibrato = currentVibrato[controller];
newSongInfo.effect = currentReverb[controller];
newSongInfo.instrument = currentInstrument[controller] + (currentLSBBank[controller] * 0x80) + (currentMSBBank[controller] * 0x8000);
newSongInfo.pitchBend = currentPitchBend[controller];
newSongInfo.startAbsoluteTime = absoluteTime;
pendingNoteList.push_back(newSongInfo);
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change
{
byte controllerType;
unsigned char curEventVal;
if (statusBit)
{
controllerType = eventVal;
curEventVal = previousEventValue;
}
else
{
controllerType = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
int controller = (curEventVal & 0xF);
byte controllerValue = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
if (controllerType == 0) // MSB Instrument Bank
{
currentMSBBank[controller] = controllerValue;
}
else if (controllerType == 1) // Mod Wheel (Vibrato)
{
if (controllerValue != currentVibrato[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].vibrato = controllerValue;
}
}
currentVibrato[controller] = controllerValue;
}
else if (controllerType == 7) // Volume
{
if (controllerValue != currentVolume[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].volume = controllerValue;
}
}
currentVolume[controller] = controllerValue;
}
else if (controllerType == 10) // Pan
{
if (controllerValue != currentPan[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].pan = controllerValue;
}
}
currentPan[controller] = controllerValue;
}
else if (controllerType == 32) // LSB Instrument Bank
{
currentLSBBank[controller] = controllerValue;
}
else if (controllerType == 91) // Reverb
{
if (controllerValue != currentReverb[controller])
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].effect = controllerValue;
}
}
currentReverb[controller] = controllerValue;
}
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument
{
byte instrument;
unsigned char curEventVal;
if (statusBit)
{
instrument = eventVal;
curEventVal = previousEventValue;
}
else
{
instrument = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
if ((eventVal & 0xF) == 9) // Drums in GM
instrument = instrument;
else
instrument = instrument;
int controller = (curEventVal & 0xF);
unsigned short tempInstrument = instrument + (currentLSBBank[controller] * 0x80) + (currentMSBBank[controller] * 0x8000);
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
if (pendingNoteList[p].instrument != tempInstrument)
{
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].instrument = tempInstrument;
}
}
currentInstrument[controller] = instrument;
if (!statusBit)
previousEventValue = eventVal;
}
else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch
{
unsigned char curEventVal;
byte amount;
if (statusBit)
{
amount = eventVal;
curEventVal = previousEventValue;
}
else
{
amount = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
if (!statusBit)
previousEventValue = eventVal;
}
// Pitch Bend
else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend
{
byte valueLSB;
unsigned char curEventVal;
if (statusBit)
{
valueLSB = eventVal;
curEventVal = previousEventValue;
}
else
{
valueLSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
curEventVal = eventVal;
}
byte valueMSB = ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
int controller = (curEventVal & 0xF);
if (currentPitchBend[controller] != valueMSB)
{
for (int p = 0; p < pendingNoteList.size(); p++)
{
if (pendingNoteList[p].originalController != (controller))
continue;
// Reopen
if (pendingNoteList[p].startAbsoluteTime != absoluteTime)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
// Promote to regular
channels[controller].push_back(pendingNoteList[p]);
// Reset
pendingNoteList[p].startAbsoluteTime = absoluteTime;
pendingNoteList[p].endAbsoluteTime = 0xFFFFFFFF;
}
pendingNoteList[p].pitchBend = valueMSB;
}
}
currentPitchBend[controller] = valueMSB;
if (!statusBit)
previousEventValue = eventVal;
}
else if (eventVal == 0xF0 || eventVal == 0xF7)
{
unsigned char curEventVal = eventVal;
int length = GetVLBytes(inputMID, position, original, repeatPattern, altOffset, altLength, false);
// subtract length
for (int i = 0; i < length; i++)
{
ReadMidiByte(inputMID, position, repeatPattern, altOffset, altLength, false);
}
}
else
{
if (!unknownsHit)
{
MessageBox(NULL, "Invalid midi character found", "Error", NULL);
unknownsHit = true;
}
}
}
for (int p = 0; p < pendingNoteList.size(); p++)
{
pendingNoteList[p].endAbsoluteTime = absoluteTime;
channels[pendingNoteList[p].originalController].push_back(pendingNoteList[p]);
}
}
numChannels = 0x10;
for (int y = 0; y < numChannels; y++)
{
// Clear empty notes
for (int x = (channels[y].size() - 1); x >= 0; x--)
{
if (channels[y][x].startAbsoluteTime == channels[y][x].endAbsoluteTime)
channels[y].erase(channels[y].begin() + x);
}
for (int x = 0; x < channels[y].size(); x++)
{
SngNoteInfoMidiImport tempNoteInfo = channels[y][x];
if (tempNoteInfo.endAbsoluteTime > highestAbsoluteTime)
highestAbsoluteTime = tempNoteInfo.endAbsoluteTime;
if (tempNoteInfo.startAbsoluteTime < lowestAbsoluteTime)
lowestAbsoluteTime = tempNoteInfo.startAbsoluteTime;
}
}
delete [] inputMID;
//FILE* outDebug = fopen("C:\\GoldeneyeStuff\\GE Editor Source\\debug.txt", "w");
FILE* outDebug = NULL;
if (outDebug != NULL)
{
for (int channel = 0; channel < numChannels; channel++)
{
for (int x = 0; x < channels[channel].size(); x++)
{
fprintf(outDebug, "Start %08X End %08X Instrument %02X Note %02X Volume %02X Vibrato %02X Pitch Bend %02X Pan %02X Velocity %02X\n", channels[channel][x].startAbsoluteTime, channels[channel][x].endAbsoluteTime, channels[channel][x].instrument, channels[channel][x].noteNumber, channels[channel][x].volume, channels[channel][x].vibrato, channels[channel][x].pitchBend, channels[channel][x].pan, channels[channel][x].velocity);
}
}
}
if (outDebug != NULL)
fclose(outDebug);
if (loop && (loopPoint > highestAbsoluteTime))
{
MessageBox(NULL, "Error, loop point is beyond end of midi", "Error", NULL);
return false;
}
std::sort(tempoPositions.begin(), tempoPositions.end(), timeAndValueSortByTime());
// Weed out equal tempos
for (int t = 0; t < tempoPositions.size(); t++)
{
if ((t + 1) < tempoPositions.size())
{
if (tempoPositions[t].value == tempoPositions[t+1].value)
{
tempoPositions.erase(tempoPositions.begin() + t + 1);
t--;
}
}
}
for (int x = 0; x < numChannels; x++)
{
// Separate
if (loop && (loopPoint != 0))
{
for (int y = (channels[x].size() - 1); y >= 0; y--)
{
SngNoteInfoMidiImport noteMidiImport = channels[x][y];
if ((loopPoint > noteMidiImport.startAbsoluteTime) && (loopPoint < noteMidiImport.endAbsoluteTime))
{
// Need to split
channels[x][y].endAbsoluteTime = loopPoint;
noteMidiImport.startAbsoluteTime = loopPoint;
channels[x].push_back(noteMidiImport);
}
}
}
std::sort(channels[x].begin(), channels[x].end(), sngSortByStartTime());
}
return true;
}
bool CMidiParse::MidiToEADMusic(int gameStyle, CString input, CString output, bool loop, unsigned long loopPoint)
{
try
{
std::vector<TimeAndValue> tempoPositions;
std::vector<SngNoteInfoMidiImport> channels[0x10];
int numChannels = 0;
int lowestAbsoluteTime = 0x7FFFFFFF;
int highestAbsoluteTime = 0;
unsigned short division = 0x30;
if (!MidiToEADMusicSngList(input, tempoPositions, channels, numChannels, lowestAbsoluteTime, highestAbsoluteTime, loop, loopPoint, division))
return false;
for (int x = 0; x < numChannels; x++)
{
for (int y = 0; y < channels[x].size(); y++)
{
// Max in Zelda is FF
channels[x][y].effect *= 2;
// Fix Note Range
if (channels[x][y].noteNumber <= 0x15)
channels[x][y].noteNumber = 0x00;
else if (channels[x][y].noteNumber >= 0x54)
channels[x][y].noteNumber = 0x3F;
else
channels[x][y].noteNumber = channels[x][y].noteNumber - 0x15;
// Adjust Pitch Bend from 00-7F to Signed Char
channels[x][y].pitchBend = ((signed char)channels[x][y].pitchBend - 0x40) * 2;
if (channels[x][y].pitchBend < 0)
channels[x][y].pitchBend = 0;
if (channels[x][y].pitchBend > 0x7F)
channels[x][y].pitchBend = 0x7F;
}
}
for (int x = 0; x < numChannels; x++)
{
for (int y = 0; y < channels[x].size(); y++)
{
SngNoteInfoMidiImport tempSongNote = channels[x][y];
if (y == (channels[x].size() - 1))
break;
SngNoteInfoMidiImport tempSongNoteNext = channels[x][y + 1];
if (
(tempSongNote.endAbsoluteTime == tempSongNoteNext.startAbsoluteTime)
&& (tempSongNote.effect == tempSongNoteNext.effect)
&& (tempSongNote.instrument == tempSongNoteNext.instrument)
&& (tempSongNote.noteNumber == tempSongNoteNext.noteNumber)
&& (tempSongNote.pan == tempSongNoteNext.pan)
&& (tempSongNote.velocity == tempSongNoteNext.velocity)
&& (tempSongNote.pitchBend == tempSongNoteNext.pitchBend)
&& (tempSongNote.volume == tempSongNoteNext.volume)
&& (tempSongNote.vibrato == tempSongNoteNext.vibrato)
&& (tempSongNote.originalTrack == tempSongNoteNext.originalTrack)
&& (tempSongNote.originalController == tempSongNoteNext.originalController)
&& (tempSongNote.originalNoteUniqueId == tempSongNoteNext.originalNoteUniqueId)
)
{
// Merge
channels[x][y].endAbsoluteTime = tempSongNoteNext.endAbsoluteTime;
channels[x].erase(channels[x].begin() + y + 1);
// Redo Note
y--;
}
}
}
float noteTimeDivisor = division / 0x30;
unsigned long loopPointReal = (float)loopPoint / noteTimeDivisor;
int outputPosition = 0;
unsigned char* outputBuffer = new unsigned char[0x100000];
for (int x = 0; x < 0x100000; x++)
outputBuffer[x] = 0x00;
// Sequence Format
outputBuffer[outputPosition++] = 0xD3;
outputBuffer[outputPosition++] = 0x20;
// Sequence Type
outputBuffer[outputPosition++] = 0xD5;
outputBuffer[outputPosition++] = 0x32;
unsigned short channelsEnabled = 0;
for (int x = 0; x < numChannels; x++)
{
if (channels[x].size() > 0)
{
channelsEnabled |= (1 << x);
}
}
// Enable Channels
outputBuffer[outputPosition++] = 0xD7;
outputBuffer[outputPosition++] = ((channelsEnabled >> 8) & 0xFF);
outputBuffer[outputPosition++] = ((channelsEnabled) & 0xFF);
int loopCounter = 1;
if (loop && (loopPointReal != 0))
{
loopCounter = 2;
}
int loopPointByteOffset = 0;
int currentTempo = 0x78;
int currentInstrument = -1;
int currentEffect = 0;
int currentPan = 0x40;
int currentVolume = 0x7F;
int currentVibrato = 0x00;
int currentPitchBend = -1;
// Write out the sequence first
int absoluteTempoTime = 0;
int absoluteTimeSequence = 0;
int absoluteChanPointerLocations[2][0x10];
for (int currentGroup = 0; currentGroup < loopCounter; currentGroup++)
{
int previousAbsoluteTimeSequence = absoluteTimeSequence;
if (loop)
{
if (currentGroup == (loopCounter - 1))
loopPointByteOffset = outputPosition;
}
std::vector<TimeAndValue> subTempoPositions;
std::vector<SngNoteInfoMidiImport> subChannels[0x10];
if (loopCounter == 1)
{
subTempoPositions = tempoPositions;
for (int x = 0; x < numChannels; x++)
{
subChannels[x] = channels[x];
}
}
else
{
if (currentGroup == 0)
{
for (int t = 0; t < tempoPositions.size(); t++)
{
if (tempoPositions[t].absoluteTime < loopPointReal)
{
subTempoPositions.push_back(tempoPositions[t]);
}
}
}
else if (currentGroup == 1)
{
for (int t = 0; t < tempoPositions.size(); t++)
{
if (tempoPositions[t].absoluteTime >= loopPointReal)
{
subTempoPositions.push_back(tempoPositions[t]);
}
}
}
for (int x = 0; x < numChannels; x++)
{
for (int y = 0; y < channels[x].size(); y++)
{
if (currentGroup == 0)
{
if (channels[x][y].startAbsoluteTime < loopPointReal)
{
subChannels[x].push_back(channels[x][y]);
}
}
else if (currentGroup == 1)
{
if (channels[x][y].startAbsoluteTime >= loopPointReal)
{
subChannels[x].push_back(channels[x][y]);
}
}
}
}
}
// Placeholder channel offsets
for (int x = 0; x < numChannels; x++)
{
if (subChannels[x].size() > 0)
{
outputBuffer[outputPosition++] = 0x90 | x;
absoluteChanPointerLocations[currentGroup][x] = outputPosition;
// Placeholder
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x00;
}
else
{
absoluteChanPointerLocations[currentGroup][x] = -1;
}
}
// Write Master Volume
outputBuffer[outputPosition++] = 0xDB;
outputBuffer[outputPosition++] = 0x46;
if ((subTempoPositions.size() == 0) || (subTempoPositions[0].absoluteTime > previousAbsoluteTimeSequence))
{
outputBuffer[outputPosition++] = 0xDD;
outputBuffer[outputPosition++] = currentTempo;
}
// Write Tempos
for (int t = 0; t < subTempoPositions.size(); t++)
{
while (subTempoPositions[t].absoluteTime > absoluteTempoTime)
{
int delta = (subTempoPositions[t].absoluteTime - absoluteTempoTime);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTempoTime += delta;
}
outputBuffer[outputPosition++] = 0xDD;
outputBuffer[outputPosition++] = subTempoPositions[t].value;
currentTempo = subTempoPositions[t].value;
}
// Timestamp channel to get to end of section
if ((loop == true) && (loopPointReal != 0))
{
if (currentGroup == 0)
{
while (loopPointReal > absoluteTimeSequence)
{
int delta = (loopPointReal - absoluteTimeSequence);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeSequence += delta;
}
}
else if (currentGroup == 1)
{
while (highestAbsoluteTime > absoluteTimeSequence)
{
int delta = (highestAbsoluteTime - absoluteTimeSequence);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeSequence += delta;
}
}
}
else
{
while (highestAbsoluteTime > absoluteTimeSequence)
{
int delta = (highestAbsoluteTime - absoluteTimeSequence);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeSequence += delta;
}
}
if (currentGroup == (loopCounter - 1))
{
if (loop)
{
outputBuffer[outputPosition++] = 0xFB;
outputBuffer[outputPosition++] = ((loopPointByteOffset >> 8) & 0xFF);
outputBuffer[outputPosition++] = ((loopPointByteOffset) & 0xFF);
}
// Disable Channels
outputBuffer[outputPosition++] = 0xD6;
outputBuffer[outputPosition++] = ((channelsEnabled >> 8) & 0xFF);
outputBuffer[outputPosition++] = ((channelsEnabled) & 0xFF);
// Terminator Sequence
outputBuffer[outputPosition++] = 0xFF;
}
if (loop && (loopPoint != 0))
{
absoluteTimeSequence = loopPointReal;
}
else
{
absoluteTimeSequence = highestAbsoluteTime;
}
}
absoluteTimeSequence = 0;
for (int currentGroup = 0; currentGroup < loopCounter; currentGroup++)
{
int previousAbsoluteTimeSequence = absoluteTimeSequence;
std::vector<SngNoteInfoMidiImport> subChannels[0x10];
if (loopCounter == 1)
{
for (int x = 0; x < numChannels; x++)
{
subChannels[x] = channels[x];
}
}
else
{
for (int x = 0; x < numChannels; x++)
{
for (int y = 0; y < channels[x].size(); y++)
{
if (currentGroup == 0)
{
if (channels[x][y].startAbsoluteTime < loopPointReal)
{
subChannels[x].push_back(channels[x][y]);
}
}
else if (currentGroup == 1)
{
if (channels[x][y].startAbsoluteTime >= loopPointReal)
{
subChannels[x].push_back(channels[x][y]);
}
}
}
}
}
bool warnedMissingNotes = false;
for (int x = 0; x < numChannels; x++)
{
if (subChannels[x].size() > 0)
{
int absoluteTimeChannel = previousAbsoluteTimeSequence;
int previousAbsoluteTimeChannel = absoluteTimeChannel;
// Write channel location
WriteShortToBuffer(outputBuffer, absoluteChanPointerLocations[currentGroup][x], outputPosition);
std::vector<SngNoteInfoMidiImport> tracks[0x10];
int maxTracks = 0;
std::vector<TimeAndValueAndType> instrumentByAbsoluteTime;
std::vector<TimeAndValueAndType> effectByAbsoluteTime;
std::vector<TimeAndValueAndType> volumeByAbsoluteTime;
std::vector<TimeAndValueAndType> panByAbsoluteTime;
std::vector<TimeAndValueAndType> pitchBendByAbsoluteTime;
std::vector<TimeAndValueAndType> vibratoByAbsoluteTime;
for (int y = 0; y < subChannels[x].size(); y++)
{
instrumentByAbsoluteTime.push_back(TimeAndValueAndType(subChannels[x][y].startAbsoluteTime, subChannels[x][y].instrument, INSTRUMENTTYPE));
effectByAbsoluteTime.push_back(TimeAndValueAndType(subChannels[x][y].startAbsoluteTime, subChannels[x][y].effect, EFFECTTYPE));
volumeByAbsoluteTime.push_back(TimeAndValueAndType(subChannels[x][y].startAbsoluteTime, subChannels[x][y].volume, VOLUMETYPE));
panByAbsoluteTime.push_back(TimeAndValueAndType(subChannels[x][y].startAbsoluteTime, subChannels[x][y].pan, PANTYPE));
pitchBendByAbsoluteTime.push_back(TimeAndValueAndType(subChannels[x][y].startAbsoluteTime, subChannels[x][y].pitchBend, PITCHBENDTYPE));
vibratoByAbsoluteTime.push_back(TimeAndValueAndType(subChannels[x][y].startAbsoluteTime, subChannels[x][y].vibrato, VIBRATOTYPE));
}
std::sort(instrumentByAbsoluteTime.begin(), instrumentByAbsoluteTime.end(), timeAndValueAndTypeSortByTime());
std::sort(effectByAbsoluteTime.begin(), effectByAbsoluteTime.end(), timeAndValueAndTypeSortByTime());
std::sort(volumeByAbsoluteTime.begin(), volumeByAbsoluteTime.end(), timeAndValueAndTypeSortByTime());
std::sort(panByAbsoluteTime.begin(), panByAbsoluteTime.end(), timeAndValueAndTypeSortByTime());
std::sort(pitchBendByAbsoluteTime.begin(), pitchBendByAbsoluteTime.end(), timeAndValueAndTypeSortByTime());
std::sort(vibratoByAbsoluteTime.begin(), vibratoByAbsoluteTime.end(), timeAndValueAndTypeSortByTime());
for (int y = 0; y < instrumentByAbsoluteTime.size(); y++)
{
int size = instrumentByAbsoluteTime.size();
if ((y + 1) < (instrumentByAbsoluteTime.size()))
{
if (instrumentByAbsoluteTime[y].value == instrumentByAbsoluteTime[y+1].value)
{
instrumentByAbsoluteTime.erase(instrumentByAbsoluteTime.begin() + y + 1);
y--;
}
}
}
// Not sure what to do if no instrument and beginning
if (currentGroup > 0)
{
if (currentInstrument != -1)
{
if ((instrumentByAbsoluteTime.size() == 0) || (instrumentByAbsoluteTime[0].absoluteTime > previousAbsoluteTimeSequence))
{
instrumentByAbsoluteTime.insert(instrumentByAbsoluteTime.begin(), TimeAndValueAndType(previousAbsoluteTimeSequence, currentInstrument, INSTRUMENTTYPE));
}
}
}
for (int y = 0; y < effectByAbsoluteTime.size(); y++)
{
if ((y + 1) < (effectByAbsoluteTime.size()))
{
if (effectByAbsoluteTime[y].value == effectByAbsoluteTime[y+1].value)
{
effectByAbsoluteTime.erase(effectByAbsoluteTime.begin() + y + 1);
y--;
}
}
}
if ((effectByAbsoluteTime.size() == 0) || (effectByAbsoluteTime[0].absoluteTime > previousAbsoluteTimeSequence))
{
if ((effectByAbsoluteTime.size() > 0) && (effectByAbsoluteTime[0].value == currentEffect))
effectByAbsoluteTime[0].absoluteTime = previousAbsoluteTimeSequence;
else
effectByAbsoluteTime.insert(effectByAbsoluteTime.begin(), TimeAndValueAndType(previousAbsoluteTimeSequence, currentEffect, EFFECTTYPE));
}
for (int y = 0; y < volumeByAbsoluteTime.size(); y++)
{
if ((y + 1) < (volumeByAbsoluteTime.size()))
{
if (volumeByAbsoluteTime[y].value == volumeByAbsoluteTime[y+1].value)
{
volumeByAbsoluteTime.erase(volumeByAbsoluteTime.begin() + y + 1);
y--;
}
}
}
if ((volumeByAbsoluteTime.size() == 0) || (volumeByAbsoluteTime[0].absoluteTime > previousAbsoluteTimeSequence))
{
if ((volumeByAbsoluteTime.size() > 0) && (volumeByAbsoluteTime[0].value == currentVolume))
volumeByAbsoluteTime[0].absoluteTime = previousAbsoluteTimeSequence;
else
volumeByAbsoluteTime.insert(volumeByAbsoluteTime.begin(), TimeAndValueAndType(previousAbsoluteTimeSequence, currentVolume, VOLUMETYPE));
}
for (int y = 0; y < panByAbsoluteTime.size(); y++)
{
if ((y + 1) < (panByAbsoluteTime.size()))
{
if (panByAbsoluteTime[y].value == panByAbsoluteTime[y+1].value)
{
panByAbsoluteTime.erase(panByAbsoluteTime.begin() + y + 1);
y--;
}
}
}
if ((panByAbsoluteTime.size() == 0) || (panByAbsoluteTime[0].absoluteTime > previousAbsoluteTimeSequence))
{
if ((panByAbsoluteTime.size() > 0) && (panByAbsoluteTime[0].value == currentPan))
panByAbsoluteTime[0].absoluteTime = previousAbsoluteTimeSequence;
else
panByAbsoluteTime.insert(panByAbsoluteTime.begin(), TimeAndValueAndType(previousAbsoluteTimeSequence, currentPan, PANTYPE));
}
for (int y = 0; y < pitchBendByAbsoluteTime.size(); y++)
{
if ((y + 1) < (pitchBendByAbsoluteTime.size()))
{
if (pitchBendByAbsoluteTime[y].value == pitchBendByAbsoluteTime[y+1].value)
{
pitchBendByAbsoluteTime.erase(pitchBendByAbsoluteTime.begin() + y + 1);
y--;
}
}
}
if ((currentPitchBend == -1) && (pitchBendByAbsoluteTime.size() == 1) && (pitchBendByAbsoluteTime[0].value == 0x40))
{
// Clear if 0x40, defaulted
pitchBendByAbsoluteTime.clear();
}
// Pitch Bend probably doesn't need 0 value
if (currentGroup > 0)
{
if (currentPitchBend != -1)
{
if ((pitchBendByAbsoluteTime.size() == 0) || (pitchBendByAbsoluteTime[0].absoluteTime > previousAbsoluteTimeSequence))
{
pitchBendByAbsoluteTime.insert(pitchBendByAbsoluteTime.begin(), TimeAndValueAndType(previousAbsoluteTimeSequence, currentPitchBend, PITCHBENDTYPE));
}
}
}
for (int y = 0; y < vibratoByAbsoluteTime.size(); y++)
{
if ((y + 1) < (vibratoByAbsoluteTime.size()))
{
if (vibratoByAbsoluteTime[y].value == vibratoByAbsoluteTime[y+1].value)
{
vibratoByAbsoluteTime.erase(vibratoByAbsoluteTime.begin() + y + 1);
y--;
}
}
}
if ((currentVibrato == 0x00) && (vibratoByAbsoluteTime.size() == 1) && (vibratoByAbsoluteTime[0].value == 0x00))
{
// Clear if 0x00, defaulted
vibratoByAbsoluteTime.clear();
}
// Vibrato doesn't need 0 value
if (currentGroup > 0)
{
if (currentVibrato != 0x00)
{
if ((vibratoByAbsoluteTime.size() == 0) || (vibratoByAbsoluteTime[0].absoluteTime > previousAbsoluteTimeSequence))
{
vibratoByAbsoluteTime.insert(vibratoByAbsoluteTime.begin(), TimeAndValueAndType(previousAbsoluteTimeSequence, currentVibrato, VIBRATOTYPE));
}
}
}
// Merge all
std::vector<TimeAndValueAndType> mergedChannelActions;
for (int y = 0; y < instrumentByAbsoluteTime.size(); y++)
{
mergedChannelActions.push_back(instrumentByAbsoluteTime[y]);
}
for (int y = 0; y < effectByAbsoluteTime.size(); y++)
{
mergedChannelActions.push_back(effectByAbsoluteTime[y]);
}
for (int y = 0; y < volumeByAbsoluteTime.size(); y++)
{
mergedChannelActions.push_back(volumeByAbsoluteTime[y]);
}
for (int y = 0; y < panByAbsoluteTime.size(); y++)
{
mergedChannelActions.push_back(panByAbsoluteTime[y]);
}
for (int y = 0; y < pitchBendByAbsoluteTime.size(); y++)
{
mergedChannelActions.push_back(pitchBendByAbsoluteTime[y]);
}
for (int y = 0; y < vibratoByAbsoluteTime.size(); y++)
{
mergedChannelActions.push_back(vibratoByAbsoluteTime[y]);
}
std::sort(mergedChannelActions.begin(), mergedChannelActions.end(), timeAndValueAndTypeSortByTime());
// Merge notes now that had same of those values that are part of channel
for (int y = 0; y < subChannels[x].size(); y++)
{
SngNoteInfoMidiImport tempSongNote = subChannels[x][y];
for (int z = 0; z < subChannels[x].size(); z++)
{
if (y == z)
continue;
SngNoteInfoMidiImport tempSongNoteNext = subChannels[x][z];
if (
(tempSongNote.endAbsoluteTime == tempSongNoteNext.startAbsoluteTime)
&& (tempSongNote.instrument == tempSongNoteNext.instrument)
&& (tempSongNote.noteNumber == tempSongNoteNext.noteNumber)
&& (tempSongNote.velocity == tempSongNoteNext.velocity)
&& (tempSongNote.originalTrack == tempSongNoteNext.originalTrack)
&& (tempSongNote.originalController == tempSongNoteNext.originalController)
&& (tempSongNote.originalNoteUniqueId == tempSongNoteNext.originalNoteUniqueId)
)
{
// Merge
subChannels[x][y].endAbsoluteTime = tempSongNoteNext.endAbsoluteTime;
subChannels[x].erase(subChannels[x].begin() + z);
// Redo Note
y--;
break;
}
}
}
for (int y = 0; y < subChannels[x].size(); y++)
{
int selectedTrack = -1;
int maxAvailableTracks = 4;
if (gameStyle == EADMUSICSTYLEZELDA)
maxAvailableTracks = 4;
else if (gameStyle == EADMUSICSTYLESTARFOX)
maxAvailableTracks = 0x10;
else if (gameStyle == EADMUSICSTYLEMARIO)
maxAvailableTracks = 4;
for (int t = 0; t < maxAvailableTracks; t++)
{
bool overlap = false;
for (int z = 0; z < tracks[t].size(); z++)
{
if (IsOverlap(subChannels[x][y].startAbsoluteTime, subChannels[x][y].endAbsoluteTime, tracks[t][z].startAbsoluteTime, tracks[t][z].endAbsoluteTime))
{
overlap = true;
break;
}
}
if (!overlap)
{
selectedTrack = t;
break;
}
}
if (selectedTrack == -1)
{
// Skip
if (!warnedMissingNotes)
{
warnedMissingNotes = true;
CString trackStr;
trackStr.Format("%02X", x);
MessageBox(NULL, "Too many simultaneous notes on track " + trackStr, "Error", NULL);
}
}
else
{
if ((selectedTrack + 1) > maxTracks)
maxTracks = selectedTrack + 1;
tracks[selectedTrack].push_back(subChannels[x][y]);
}
}
// Channel Start
outputBuffer[outputPosition++] = 0xC4;
int absoluteTrackOffset[0x10];
for (int y = 0; y < maxTracks; y++)
{
// Placeholder
if (gameStyle == EADMUSICSTYLEZELDA)
{
// Max 4
outputBuffer[outputPosition++] = 0x88 + y;
}
else if (gameStyle == EADMUSICSTYLEMARIO)
{
// Max 4
outputBuffer[outputPosition++] = 0x90 + y;
}
else if (gameStyle == EADMUSICSTYLESTARFOX)
{
// Max 0x10
outputBuffer[outputPosition++] = 0x90 + y;
}
absoluteTrackOffset[y] = outputPosition;
outputBuffer[outputPosition++] = 0x00;
outputBuffer[outputPosition++] = 0x00;
}
// Priority default
outputBuffer[outputPosition++] = 0xE9;
outputBuffer[outputPosition++] = 0x02;
// Now write the events
for (int y = 0; y < mergedChannelActions.size(); y++)
{
while (mergedChannelActions[y].absoluteTime > absoluteTimeChannel)
{
int delta = (mergedChannelActions[y].absoluteTime - absoluteTimeChannel);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeChannel += delta;
}
if (mergedChannelActions[y].type == INSTRUMENTTYPE)
{
outputBuffer[outputPosition++] = 0xC1;
outputBuffer[outputPosition++] = mergedChannelActions[y].value;
currentInstrument = mergedChannelActions[y].value;
}
else if (mergedChannelActions[y].type == EFFECTTYPE)
{
outputBuffer[outputPosition++] = 0xD4;
outputBuffer[outputPosition++] = mergedChannelActions[y].value;
currentEffect = mergedChannelActions[y].value;
}
else if (mergedChannelActions[y].type == VOLUMETYPE)
{
outputBuffer[outputPosition++] = 0xDF;
outputBuffer[outputPosition++] = mergedChannelActions[y].value;
currentVolume = mergedChannelActions[y].value;
}
else if (mergedChannelActions[y].type == PANTYPE)
{
outputBuffer[outputPosition++] = 0xDD;
outputBuffer[outputPosition++] = mergedChannelActions[y].value;
currentPan = mergedChannelActions[y].value;
}
else if (mergedChannelActions[y].type == PITCHBENDTYPE)
{
outputBuffer[outputPosition++] = 0xD3;
outputBuffer[outputPosition++] = mergedChannelActions[y].value;
currentPitchBend = mergedChannelActions[y].value;
}
else if (mergedChannelActions[y].type == VIBRATOTYPE)
{
outputBuffer[outputPosition++] = 0xD8;
outputBuffer[outputPosition++] = mergedChannelActions[y].value;
currentVibrato = mergedChannelActions[y].value;
}
}
// Timestamp channel to get to end of section
if ((loop == true) && (loopPointReal != 0))
{
if (currentGroup == 0)
{
while (loopPointReal > absoluteTimeChannel)
{
int delta = (loopPointReal - absoluteTimeChannel);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeChannel += delta;
}
}
else if (currentGroup == 1)
{
while (highestAbsoluteTime > absoluteTimeChannel)
{
int delta = (highestAbsoluteTime - absoluteTimeChannel);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeChannel += delta;
}
}
}
else
{
while (highestAbsoluteTime > absoluteTimeChannel)
{
int delta = (highestAbsoluteTime - absoluteTimeChannel);
outputBuffer[outputPosition++] = 0xFD;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeChannel += delta;
}
}
// Terminator Sequence Channel
outputBuffer[outputPosition++] = 0xFF;
// Now write tracks
for (int z = 0; z < maxTracks; z++)
{
// Wite offset
WriteShortToBuffer(outputBuffer, absoluteTrackOffset[z], outputPosition);
int absoluteTimeTrack = previousAbsoluteTimeChannel;
int lastNoteTimeStamp = -1;
for (int y = 0; y < tracks[z].size(); y++)
{
while (tracks[z][y].startAbsoluteTime > absoluteTimeTrack)
{
int delta = (tracks[z][y].startAbsoluteTime - absoluteTimeTrack);
outputBuffer[outputPosition++] = 0xC0;
WriteEADMusicTimeValue(outputBuffer, outputPosition, delta);
absoluteTimeTrack += delta;
}
// 1 - NoteLength = (((duration / 256))
// /
// TimeTillNextNote
int noteLength = tracks[z][y].endAbsoluteTime - tracks[z][y].startAbsoluteTime;
int timeStamp = noteLength;
int ratio = -1;
bool useDuration = false;
if ((y + 1) < (tracks[z].size()))
{
int nextNote = tracks[z][y+1].startAbsoluteTime - tracks[z][y].startAbsoluteTime;
if (nextNote == noteLength)
{
useDuration = false;
}
else
{
double fractionalRatio = ((1.0 - ((double)noteLength / (double)nextNote)) * 256.0);
ratio = ceil(fractionalRatio);
int noteLengthCalculated = (nextNote - ((ratio * nextNote) >> 8));
if ((ratio >= 0x100) || (ratio <= 0))
{
useDuration = false;
}
else if (noteLengthCalculated != noteLength)
{
useDuration = false;
}
else
{
useDuration = true;
timeStamp = nextNote;
}
}
}
if ((!useDuration) || ((y + 1) == (tracks[z].size())))
{
// Do TV always
outputBuffer[outputPosition++] = 0x40 | tracks[z][y].noteNumber;
WriteEADMusicTimeValue(outputBuffer, outputPosition, timeStamp);
outputBuffer[outputPosition++] = tracks[z][y].velocity;
}
else if (timeStamp == lastNoteTimeStamp)
{
// VG
outputBuffer[outputPosition++] = 0x80 | tracks[z][y].noteNumber;
outputBuffer[outputPosition++] = tracks[z][y].velocity;
outputBuffer[outputPosition++] = (unsigned char)ratio;
}
else
{
// Do TVG
outputBuffer[outputPosition++] = tracks[z][y].noteNumber;
WriteEADMusicTimeValue(outputBuffer, outputPosition, timeStamp);
outputBuffer[outputPosition++] = tracks[z][y].velocity;
outputBuffer[outputPosition++] = (unsigned char)ratio;
}
lastNoteTimeStamp = timeStamp;
absoluteTimeTrack += timeStamp;
}
outputBuffer[outputPosition++] = 0xFF;
}
}
}
if (loop && (loopPoint != 0))
{
absoluteTimeSequence = loopPointReal;
}
else
{
absoluteTimeSequence = highestAbsoluteTime;
}
}
FILE* outFile = fopen(output, "wb");
if (outFile == NULL)
{
delete [] outputBuffer;
MessageBox(NULL, "Error outputting file", "Error", NULL);
return false;
}
fwrite(outputBuffer, 1, outputPosition, outFile);
delete [] outputBuffer;
fclose(outFile);
}
catch (...)
{
MessageBox(NULL, "Error converting", "Error", NULL);
return false;
}
return true;
}
int CMidiParse::IncrementSpot(unsigned long& spot, int count, unsigned char* coverage)
{
if (coverage)
{
for (int x = spot; x < spot + count; x++)
{
coverage[x] = 0x00;
}
}
spot += count;
return spot;
}
int CMidiParse::ReadEADMusicTimeValue(unsigned char* inputMID, unsigned long& offset, unsigned char* coverage)
{
if (inputMID[offset] & 0x80)
{
int timevalue = (((inputMID[offset] & 0x7F) << 8) | inputMID[offset+1]);
IncrementSpot(offset, 2, coverage);
return timevalue;
}
else
{
int timevalue = inputMID[offset];
IncrementSpot(offset, 1, coverage);
return timevalue;
}
}
int CMidiParse::WriteEADMusicTimeValue(unsigned char* outputMID, int& offset, int value)
{
int delta = value;
if (delta > 0x7FFF)
delta = 0x7FFF;
if (delta < 0x80)
{
outputMID[offset++] = delta;
}
else
{
outputMID[offset++] = 0x80 | (delta >> 8);
outputMID[offset++] = (delta & 0xFF);
}
return delta;
}
void CMidiParse::ParseEADMusicTrackLayer(int gameStyle, FILE* outFileDebug, unsigned char* inputMID, int end, int offset, int channel, int layer, unsigned long absoluteTime,
int& numberInstruments, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfo>& trackOutputNotes,
int& noteUniqueId,
std::vector<unsigned long>& jumpStarts, std::vector<unsigned long>& jumpsTaken, bool attemptJumps, unsigned char* coverage, bool channelStarted)
{
fprintfIfDebug(outFileDebug, "-------------------Track Chn %X Layer %X-------------------\n", channel, layer);
unsigned char command = 0x00;
unsigned long spot = offset;
std::vector<int> returnBackOffset;
std::vector<int> returnBackAlternateChoices;
int currentCoarseTune = 0;
int lastTimestamp = 0x0;
loopAgain:
while ((command != 0xFF) && (spot < end))
{
command = inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (command >= 0xC0)
{
fprintfIfDebug(outFileDebug, "TRK %08X Time: %08X CMD: %02X", spot-1, absoluteTime, command);
if (command == 0xC0)
{
fprintfIfDebug(outFileDebug, " Timestamp");
int timestamp = ReadEADMusicTimeValue(inputMID, spot, coverage);
if (timestamp < 0x80)
fprintfIfDebug(outFileDebug, " %02X (%d)", timestamp, timestamp);
else
fprintfIfDebug(outFileDebug, " %02X%02X - %04X (%d)", inputMID[spot-2], inputMID[spot+1-2], timestamp, timestamp);
absoluteTime += timestamp;
}
else if (command == 0xC1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC2)
{
fprintfIfDebug(outFileDebug, " Coarse Tune");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
currentCoarseTune = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC3)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC4)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC5)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC6)
{
fprintfIfDebug(outFileDebug, " SFX Id");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC7)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xC8)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC9)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCA)
{
fprintfIfDebug(outFileDebug, " SFX Pan");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCB)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X %02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xCC)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xCD)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCE)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCF)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD0)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD1)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD2)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD3)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD4)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD5)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD6)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD7)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD8)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD9)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xDA)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xDB)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xDC)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xDD)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xDE)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xDF)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE0)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE1)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE2)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE3)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE4)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE5)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE6)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE7)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE8)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE9)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEA)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEB)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEC)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xED)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEE)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEF)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF0)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF1)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF2)
{
fprintfIfDebug(outFileDebug, " Go to Relative Offset if Play Value < 0");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
}
}
}
else if (command == 0xF3)
{
fprintfIfDebug(outFileDebug, " Go to Relative Offset if Play Value == 0");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
}
}
}
else if (command == 0xF4)
{
fprintfIfDebug(outFileDebug, " Go to relative offset");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], (signed char)inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
break;
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
else
{
break;
}
}
}
}
else if (command == 0xF5)
{
fprintfIfDebug(outFileDebug, " Go to absolute offset if Play Value >= 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xF6)
{
fprintfIfDebug(outFileDebug, " Restart Song");
if (attemptJumps)
{
int startSpot = 0;
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), startSpot) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(startSpot);
offset = startSpot;
}
}
}
else if (command == 0xF7)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF8)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xF9)
{
fprintfIfDebug(outFileDebug, " Go to Absolute Offset if Play Value < 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
offset = absoluteOffset;
}
}
}
}
else if (command == 0xFA)
{
fprintfIfDebug(outFileDebug, " Go to Absolute Offset if Play Value == 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xFB)
{
fprintfIfDebug(outFileDebug, " Go to absolute offset");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
break;
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
else
{
break;
}
}
}
}
else if (command == 0xFC)
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
fprintfIfDebug(outFileDebug, " Jump and Link");
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
IncrementSpot(spot, 2, coverage);
returnBackOffset.push_back(spot);
spot = offset;
}
else if (command == 0xFD)
{
fprintfIfDebug(outFileDebug, " Delay");
int timestamp = ReadEADMusicTimeValue(inputMID, spot, coverage);
if (timestamp < 0x80)
fprintfIfDebug(outFileDebug, " %02X (%d)", timestamp, timestamp);
else
fprintfIfDebug(outFileDebug, " %02X%02X - %04X (%d)", inputMID[spot-2], inputMID[spot+1-2], timestamp, timestamp);
absoluteTime += timestamp;
}
else if (command == 0xFE)
{
fprintfIfDebug(outFileDebug, " RETURN");
}
else if (command == 0xFF)
{
fprintfIfDebug(outFileDebug, " END");
}
else
{
fprintfIfDebug(outFileDebug, " UNKNOWN");
}
}
else if (!channelStarted)
{
// Note + Time
int preTimestampSpot = spot;
int timestamp = ReadEADMusicTimeValue(inputMID, spot, coverage);
lastTimestamp = timestamp;
fprintfIfDebug(outFileDebug, "TRK %08X Time: %08X Note T: %02X Note %02X", preTimestampSpot-1, absoluteTime, command, command);
if (timestamp < 0x80)
fprintfIfDebug(outFileDebug, " Length %02X (%d)", timestamp, timestamp);
else
fprintfIfDebug(outFileDebug, " Length %02X%02X - %04X (%d)", inputMID[spot-2], inputMID[spot+1-2], timestamp, timestamp);
int note = command & 0x3F;
int velocity = inputMID[spot];
int noteLength = timestamp;
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = channel;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentCoarseTune + 0x15;
songNoteInfo.instrument = 0x00;
songNoteInfo.velocity = 0x7F;
songNoteInfo.effect = 0x00;
songNoteInfo.tempo = 0x78;
songNoteInfo.pan = 0x40;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.vibrato = 0x00;
songNoteInfo.volume = 0x7F;
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
trackOutputNotes.push_back(songNoteInfo);
absoluteTime += timestamp;
}
else if (command & 0x40)
{
int preTimestampSpot = spot;
int timestamp = ReadEADMusicTimeValue(inputMID, spot, coverage);
lastTimestamp = timestamp;
fprintfIfDebug(outFileDebug, "TRK %08X Time: %08X Note TV: %02X Note %02X", preTimestampSpot-1, absoluteTime, command, command & 0x3F);
if (timestamp < 0x80)
fprintfIfDebug(outFileDebug, " Length %02X (%d)", timestamp, timestamp);
else
fprintfIfDebug(outFileDebug, " Length %02X%02X - %04X (%d)", inputMID[spot-2], inputMID[spot+1-2], timestamp, timestamp);
fprintfIfDebug(outFileDebug, " Velocity %02X (%d) [True Note Length %04X]", inputMID[spot], inputMID[spot], timestamp);
int note = command & 0x3F;
int velocity = inputMID[spot];
int noteLength = timestamp;
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = channel;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentCoarseTune + 0x15;
songNoteInfo.instrument = 0x00;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = 0x00;
songNoteInfo.tempo = 0x78;
songNoteInfo.pan = 0x40;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.vibrato = 0x00;
songNoteInfo.volume = 0x7F;
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
trackOutputNotes.push_back(songNoteInfo);
absoluteTime += timestamp;
IncrementSpot(spot, 1, coverage);
}
else if (command & 0x80)
{
fprintfIfDebug(outFileDebug, "TRK %08X Time: %08X Note VD: %02X Note %02X", spot-1, absoluteTime, command, command & 0x3F);
int duration = inputMID[spot+1];
fprintfIfDebug(outFileDebug, " [Timestamp %04X] Velocity %02X (%d) Duration %02X (%d) [True Note Length %04X]", lastTimestamp, inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], (lastTimestamp - ((duration * lastTimestamp) >> 8)));
int note = command & 0x3F;
int velocity = inputMID[spot];
int noteLength = (lastTimestamp - ((duration * lastTimestamp) >> 8));
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = channel;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentCoarseTune + 0x15;
songNoteInfo.instrument = 0x00;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = 0x00;
songNoteInfo.tempo = 0x78;
songNoteInfo.pan = 0x40;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.vibrato = 0x00;
songNoteInfo.volume = 0x7F;
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
trackOutputNotes.push_back(songNoteInfo);
absoluteTime += lastTimestamp;
IncrementSpot(spot, 2, coverage);
}
else
{
int preTimestampSpot = spot;
int timestamp = ReadEADMusicTimeValue(inputMID, spot, coverage);
lastTimestamp = timestamp;
fprintfIfDebug(outFileDebug, "TRK %08X Time: %08X Note TVD: %02X Note %02X", preTimestampSpot-1, absoluteTime, command, command & 0x3F);
if (timestamp < 0x80)
fprintfIfDebug(outFileDebug, " Length %02X (%d)", timestamp, timestamp);
else
fprintfIfDebug(outFileDebug, " Length %02X%02X - %04X (%d)", inputMID[spot-2], inputMID[spot+1-2], timestamp, timestamp);
int duration = inputMID[spot+1];
fprintfIfDebug(outFileDebug, " Velocity %02X (%d) Duration %02X (%d) [True Note Length %04X]", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], (timestamp - ((duration * timestamp) >> 8)));
int note = command & 0x3F;
int velocity = inputMID[spot];
int noteLength = (timestamp - ((duration * timestamp) >> 8));
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = channel;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentCoarseTune + 0x15;
songNoteInfo.instrument = 0x00;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = 0x00;
songNoteInfo.tempo = 0x78;
songNoteInfo.pan = 0x40;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.vibrato = 0x00;
songNoteInfo.volume = 0x7F;
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
trackOutputNotes.push_back(songNoteInfo);
absoluteTime += timestamp;
//Time %02X Velocity %02X Duration %02X
//, inputMID[spot], inputMID[spot+1], inputMID[spot+2]
IncrementSpot(spot, 2, coverage);
// This goes backwards or something odd...figure out later, command was 00FFFF00 1080 Snowboarding Midi 0
/*if (duration == 0)
{
fprintfIfDebug(outFileDebug, "\n");
break;
}*/
}
fprintfIfDebug(outFileDebug, "\n");
}
if (returnBackAlternateChoices.size() > 0)
{
// Return from Jump and Link
spot = returnBackAlternateChoices.back();
returnBackAlternateChoices.pop_back();
command = 0x00;
fprintfIfDebug(outFileDebug, "... Taking Alternate Path to %08X\n", spot);
goto loopAgain;
}
if (returnBackOffset.size() > 0)
{
// Return from Jump and Link
spot = returnBackOffset.back();
returnBackOffset.pop_back();
command = 0x00;
fprintfIfDebug(outFileDebug, "... Returning from Subroutine to %08X\n", spot);
goto loopAgain;
}
}
void CMidiParse::ParseEADMusicChannel(int gameStyle, FILE* outFileDebug, unsigned char* inputMID, int end, int offset, int channel, unsigned long absoluteTime,
int& numberInstruments, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfo>& outputNotes,
int& noteUniqueId, int currentInstrument[0x10], int currentPan[0x10], int currentVolume[0x10], int currentPitchBend[0x10], int currentEffect[0x10],
std::vector<unsigned long>& jumpStarts, std::vector<unsigned long>& jumpsTaken, bool attemptJumps, unsigned char* coverage, bool channelStarted[0x10],
int currentVibrato[0x10])
{
fprintfIfDebug(outFileDebug, "-------------------Channel %X-------------------\n", channel);
unsigned long startAbsoluteTime = absoluteTime;
unsigned char command = 0x00;
unsigned long spot = offset;
std::vector<int> returnBackOffset;
std::vector<int> returnBackAlternateChoices;
std::vector<SngNoteInfo> pendingChannelNotes;
std::vector<SngTimeValue> instrumentByAbsoluteTime;
std::vector<SngTimeValue> effectByAbsoluteTime;
std::vector<SngTimeValue> volumeByAbsoluteTime;
std::vector<SngTimeValue> panByAbsoluteTime;
std::vector<SngTimeValue> pitchBendByAbsoluteTime;
std::vector<SngTimeValue> vibratoByAbsoluteTime;
loopAgain:
while ((command != 0xFF) && (spot < end))
{
command = inputMID[spot];
fprintfIfDebug(outFileDebug, "CHN %08X Time: %08X CMD: %02X", spot, absoluteTime, command);
IncrementSpot(spot, 1, coverage);
if (command == 0xFF)
{
fprintfIfDebug(outFileDebug, " END\n");
break;
}
else if (command == 0xFE)
{
fprintfIfDebug(outFileDebug, " RETURN\n");
break;
}
else if ((command >= 0x0) && (command < 0x10))
{
if ((gameStyle == EADMUSICSTYLEZELDA) || (gameStyle == EADMUSICSTYLEMARIO))
{
fprintfIfDebug(outFileDebug, " Delay");
fprintfIfDebug(outFileDebug, " %02X (%d)", command, command);
absoluteTime += command;
}
else
{
fprintfIfDebug(outFileDebug, " ?");
}
}
else if ((command >= 0x10) && (command < 0x20))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x20) && (command < 0x30))
{
// 1080
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
fprintfIfDebug(outFileDebug, " Change Channel %02X to Offset?", command & 0xF);
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
int callChannel = command & 0xF;
fprintfIfDebug(outFileDebug, "\n");
ParseEADMusicChannel(gameStyle, outFileDebug, inputMID, end, offset, callChannel, absoluteTime, numberInstruments, tempoPositions, outputNotes, noteUniqueId, currentInstrument, currentPan, currentVolume, currentPitchBend, currentEffect, jumpStarts, jumpsTaken, attemptJumps, coverage, channelStarted, currentVibrato);
}
else if ((command >= 0x30) && (command < 0x40))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x40) && (command < 0x50))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x50) && (command < 0x60))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x60) && (command < 0x70))
{
if (gameStyle == EADMUSICSTYLESTARFOX)
{
fprintfIfDebug(outFileDebug, " Delay");
fprintfIfDebug(outFileDebug, " %02X (%d) [Real delay %02X (%d)]", command, command, command & 0xF, command & 0xF);
absoluteTime += (command & 0xF);
}
else
{
fprintfIfDebug(outFileDebug, " ?");
}
}
else if ((command >= 0x70) && (command < 0x78))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x78) && (command < 0x7C))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
int layer = command & 0x3;
fprintfIfDebug(outFileDebug, " Track Layer Offset %02X", (command & 0x3));
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
fprintfIfDebug(outFileDebug, "\n");
IncrementSpot(spot, 2, coverage);
if (offset > 0)
{
std::vector<unsigned long> jumpStartsTrack;
std::vector<unsigned long> jumpsTakenTrack;
ParseEADMusicTrackLayer(gameStyle, outFileDebug, inputMID, end, spot + offset, channel, layer, absoluteTime, numberInstruments, tempoPositions, pendingChannelNotes, noteUniqueId, jumpStartsTrack, jumpsTakenTrack, attemptJumps, coverage, channelStarted[channel]);
}
}
else if ((command >= 0x7C) && (command < 0x80))
{
// Looks like placeholder, defaults back to 0 in Zelda
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
int layer = 0;
fprintfIfDebug(outFileDebug, " Track Layer Offset %02X", layer);
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
fprintfIfDebug(outFileDebug, "\n");
IncrementSpot(spot, 2, coverage);
if (offset > 0)
{
std::vector<unsigned long> jumpStartsTrack;
std::vector<unsigned long> jumpsTakenTrack;
ParseEADMusicTrackLayer(gameStyle, outFileDebug, inputMID, end, spot + offset, channel, layer, absoluteTime, numberInstruments, tempoPositions, pendingChannelNotes, noteUniqueId, jumpStartsTrack, jumpsTakenTrack, attemptJumps, coverage, channelStarted[channel]);
}
}
else if ((command >= 0x80) && (command < 0x84))
{
// & 0x3 Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x84) && (command < 0x88))
{
// Default 0 placeholder Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((gameStyle == EADMUSICSTYLEZELDA) && ((command >= 0x88) && (command < 0x8C)))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
int layer = command & 0x3;
fprintfIfDebug(outFileDebug, " Track Layer %02X", (command & 0x3));
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
fprintfIfDebug(outFileDebug, "\n");
std::vector<unsigned long> jumpStartsTrack;
std::vector<unsigned long> jumpsTakenTrack;
ParseEADMusicTrackLayer(gameStyle, outFileDebug, inputMID, end, offset, channel, layer, absoluteTime, numberInstruments, tempoPositions, pendingChannelNotes, noteUniqueId, jumpStartsTrack, jumpsTakenTrack, attemptJumps, coverage, channelStarted[channel]);
IncrementSpot(spot, 2, coverage);
}
else if ((gameStyle == EADMUSICSTYLEZELDA) && ((command >= 0x8C) && (command < 0x90)))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
int layer = 0;
fprintfIfDebug(outFileDebug, " Track Layer %02X", 0);
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
fprintfIfDebug(outFileDebug, "\n");
std::vector<unsigned long> jumpStartsTrack;
std::vector<unsigned long> jumpsTakenTrack;
ParseEADMusicTrackLayer(gameStyle, outFileDebug, inputMID, end, offset, channel, layer, absoluteTime, numberInstruments, tempoPositions, pendingChannelNotes, noteUniqueId, jumpStartsTrack, jumpsTakenTrack, attemptJumps, coverage, channelStarted[channel]);
IncrementSpot(spot, 2, coverage);
}
else if ((gameStyle == EADMUSICSTYLEMARIO) && ((command >= 0x88) && (command < 0x90)))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if ((gameStyle == EADMUSICSTYLESTARFOX) && ((command >= 0x88) && (command < 0x90)))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if ((gameStyle == EADMUSICSTYLEZELDA) && ((command >= 0x90) && (command < 0x94)))
{
// & 0x3 Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((gameStyle == EADMUSICSTYLEZELDA) && ((command >= 0x94) && (command < 0x98)))
{
// Default 0 Placeholder Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((gameStyle == EADMUSICSTYLEMARIO) && ((command >= 0x90) && (command < 0x94)))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
int layer = command & 0x3;
fprintfIfDebug(outFileDebug, " Track Layer %02X", (command & 0x3));
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
fprintfIfDebug(outFileDebug, "\n");
std::vector<unsigned long> jumpStartsTrack;
std::vector<unsigned long> jumpsTakenTrack;
ParseEADMusicTrackLayer(gameStyle, outFileDebug, inputMID, end, offset, channel, layer, absoluteTime, numberInstruments, tempoPositions, pendingChannelNotes, noteUniqueId, jumpStartsTrack, jumpsTakenTrack, attemptJumps, coverage, channelStarted[channel]);
IncrementSpot(spot, 2, coverage);
}
else if ((gameStyle == EADMUSICSTYLEMARIO) && ((command >= 0x94) && (command < 0x98)))
{
// Not sure just put in
IncrementSpot(spot, 2, coverage);
}
else if ((gameStyle == EADMUSICSTYLEMARIO) && ((command >= 0x98) && (command < 0x9C)))
{
// & 0x3 Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((gameStyle == EADMUSICSTYLEZELDA) && ((command >= 0x98) && (command < 0x9C)))
{
// & 0x3 Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((gameStyle == EADMUSICSTYLEMARIO) && ((command >= 0x9C) && (command < 0xA0)))
{
// Default 0 Placeholder Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((gameStyle == EADMUSICSTYLEZELDA) && ((command >= 0x9C) && (command < 0xA0)))
{
// Default 0 Placeholder Track Layer
fprintfIfDebug(outFileDebug, " ?");
}
else if ((gameStyle == EADMUSICSTYLESTARFOX) && ((command >= 0x90) && (command < 0xA0)))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
int layer = command & 0xF;
fprintfIfDebug(outFileDebug, " Track Layer %02X", (command & 0xF));
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
fprintfIfDebug(outFileDebug, "\n");
std::vector<unsigned long> jumpStartsTrack;
std::vector<unsigned long> jumpsTakenTrack;
ParseEADMusicTrackLayer(gameStyle, outFileDebug, inputMID, end, offset, channel, layer, absoluteTime, numberInstruments, tempoPositions, pendingChannelNotes, noteUniqueId, jumpStartsTrack, jumpsTakenTrack, attemptJumps, coverage, channelStarted[channel]);
IncrementSpot(spot, 2, coverage);
}
else if ((command >= 0xA0) && (command < 0xB0))
{
// NOOP in Zelda
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xB0)
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
fprintfIfDebug(outFileDebug, " Add to 80100000 and ?");
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
IncrementSpot(spot, 2, coverage);
break;
}
else if (command == 0xB1)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xB2)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xB3)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xB4)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xB5)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xB6)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xB7)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xB8)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xB9)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xBA)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xBB)
{
fprintfIfDebug(outFileDebug, " Control Change?");
fprintfIfDebug(outFileDebug, " %02X %02X%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xBC)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xBD)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X %02X%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2], inputMID[spot+3]);
IncrementSpot(spot, 4, coverage);
}
else if (command == 0xBE)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xBF)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC0)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC1)
{
fprintfIfDebug(outFileDebug, " Instrument");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
currentInstrument[channel] = inputMID[spot];
SngTimeValue pair;
pair.value = currentInstrument[channel];
pair.startAbsoluteTime = absoluteTime;
pair.endAbsoluteTime = absoluteTime;
instrumentByAbsoluteTime.push_back(pair);
if (currentInstrument[channel] >= numberInstruments)
numberInstruments = (currentInstrument[channel] + 1);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC2)
{
if (outFileDebug)
{
fflush(outFileDebug);
}
// Really uses play values and external to set...can probably not ever get this right sadly.
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
std::vector<unsigned short> values;
fprintfIfDebug(outFileDebug, " Set Jump Table Channel");
fprintfIfDebug(outFileDebug, " Offset with Data %02X%02X", inputMID[spot], inputMID[spot+1]);
unsigned short previousValueTemp = 0;
while (true)
{
unsigned short valueTemp = CharArrayToShort(&inputMID[offset + (values.size() * 2)]);
if ((valueTemp >= end) || (valueTemp <= previousValueTemp))
break;
fprintfIfDebug(outFileDebug, " Value %02X %04X", (values.size()), valueTemp);
values.push_back(valueTemp);
previousValueTemp = valueTemp;
}
IncrementSpot(spot, 2, coverage);
fprintfIfDebug(outFileDebug, "\n");
for (int v = 0; v < values.size(); v++)
{
if ((offset + (v * 2 + 1)) < end)
{
coverage[offset + (v * 2)] = 0x00;
coverage[offset + (v * 2) + 1] = 0x00;
ParseEADMusicChannel(gameStyle, outFileDebug, inputMID, end, values[v], channel, absoluteTime, numberInstruments, tempoPositions, outputNotes, noteUniqueId, currentInstrument, currentPan, currentVolume, currentPitchBend, currentEffect, jumpStarts, jumpsTaken, attemptJumps, coverage, channelStarted, currentVibrato);
}
}
}
else if (command == 0xC3)
{
fprintfIfDebug(outFileDebug, " Channel End (Disable Velocity/Duration on Notes)");
channelStarted[channel] = false;
}
else if (command == 0xC4)
{
fprintfIfDebug(outFileDebug, " Channel Start (Enable Velocity/Duration on Notes)");
channelStarted[channel] = true;
}
else if (command == 0xC5)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC6)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC7)
{
fprintfIfDebug(outFileDebug, " Write Value to Memory");
fprintfIfDebug(outFileDebug, " %02X %02X%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xC8)
{
fprintfIfDebug(outFileDebug, " Subtract Play Value - Value");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC9)
{
fprintfIfDebug(outFileDebug, " And Play Value and Value");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCA)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCB)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xCC)
{
fprintfIfDebug(outFileDebug, " Set Play Value");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCD)
{
fprintfIfDebug(outFileDebug, " ? [Value is channel number]");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCE)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xCF)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xD0)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD2)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD3)
{
fprintfIfDebug(outFileDebug, " Pitch Bend");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
// signed char to 00-7F range
currentPitchBend[channel] = (signed char)inputMID[spot];
if (currentPitchBend[channel] == 0)
currentPitchBend[channel] = 0x40;
else if (currentPitchBend[channel] < 0)
currentPitchBend[channel] = currentPitchBend[channel] / 2 + 0x40;
else if (currentPitchBend[channel] > 0)
currentPitchBend[channel] = currentPitchBend[channel] / 2 + 0x40;
SngTimeValue pair;
pair.value = currentPitchBend[channel];
pair.startAbsoluteTime = absoluteTime;
pair.endAbsoluteTime = absoluteTime;
pitchBendByAbsoluteTime.push_back(pair);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD4)
{
fprintfIfDebug(outFileDebug, " Reverb");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
currentEffect[channel] = inputMID[spot] / 2;
SngTimeValue pair;
pair.value = currentEffect[channel];
pair.startAbsoluteTime = absoluteTime;
pair.endAbsoluteTime = absoluteTime;
effectByAbsoluteTime.push_back(pair);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD5)
{
fprintfIfDebug(outFileDebug, " Reverb");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD6)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD7)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD8)
{
fprintfIfDebug(outFileDebug, " Vibrato");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
currentVibrato[channel] = inputMID[spot];
SngTimeValue pair;
pair.value = currentVibrato[channel];
pair.startAbsoluteTime = absoluteTime;
pair.endAbsoluteTime = absoluteTime;
vibratoByAbsoluteTime.push_back(pair);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD9)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xDA)
{
// Absolute offset
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xDB)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xDC)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xDD)
{
fprintfIfDebug(outFileDebug, " Pan");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
currentPan[channel] = inputMID[spot];
SngTimeValue pair;
pair.value = currentPan[channel];
pair.startAbsoluteTime = absoluteTime;
pair.endAbsoluteTime = absoluteTime;
panByAbsoluteTime.push_back(pair);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xDE)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xDF)
{
fprintfIfDebug(outFileDebug, " Volume");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
currentVolume[channel] = inputMID[spot];
SngTimeValue pair;
pair.value = currentVolume[channel];
pair.startAbsoluteTime = absoluteTime;
pair.endAbsoluteTime = absoluteTime;
volumeByAbsoluteTime.push_back(pair);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE0)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xE2)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X %02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xE3)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE4)
{
fprintfIfDebug(outFileDebug, " Use Play Value to Offset into Jump Table (from last Command C2)");
}
else if (command == 0xE5)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE6)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE7)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xE8)
{
// NUD-DMGJ
//E800000E003F7F0000
fprintfIfDebug(outFileDebug, " Envelope");
fprintfIfDebug(outFileDebug, " %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d)",
inputMID[spot], inputMID[spot],
inputMID[spot+1], inputMID[spot+1],
inputMID[spot+2], inputMID[spot+2],
inputMID[spot+3], inputMID[spot+3],
inputMID[spot+4], inputMID[spot+4],
inputMID[spot+5], inputMID[spot+5],
inputMID[spot+6], inputMID[spot+6],
inputMID[spot+7], inputMID[spot+7]
);
IncrementSpot(spot, 8, coverage);
}
else if (command == 0xE9)
{
fprintfIfDebug(outFileDebug, " Priority");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xEA)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEB)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xEC)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xED)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xEE)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xEF)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X %02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xF0)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xF2)
{
fprintfIfDebug(outFileDebug, " Go to Relative Offset if Play Value < 0");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
}
}
}
else if (command == 0xF3)
{
fprintfIfDebug(outFileDebug, " Go to Relative Offset if Play Value == 0");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
}
}
}
else if (command == 0xF4)
{
fprintfIfDebug(outFileDebug, " Go to relative offset");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], (signed char)inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
break;
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
else
{
break;
}
}
}
}
else if (command == 0xF5)
{
fprintfIfDebug(outFileDebug, " Go to absolute offset if Play Value >= 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xF6)
{
fprintfIfDebug(outFileDebug, " Restart Song");
if (attemptJumps)
{
int startSpot = 0;
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), startSpot) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(startSpot);
spot = startSpot;
}
}
}
else if (command == 0xF7)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF8)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xF9)
{
fprintfIfDebug(outFileDebug, " Go to Absolute Offset if Play Value < 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xFA)
{
fprintfIfDebug(outFileDebug, " Go to Absolute Offset if Play Value == 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xFB)
{
fprintfIfDebug(outFileDebug, " Go to absolute offset");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
break;
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
else
{
break;
}
}
}
}
else if (command == 0xFC)
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
fprintfIfDebug(outFileDebug, " Jump and Link");
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
IncrementSpot(spot, 2, coverage);
returnBackOffset.push_back(spot);
spot = offset;
}
else if (command == 0xFD)
{
fprintfIfDebug(outFileDebug, " Delay");
int timestamp = ReadEADMusicTimeValue(inputMID, spot, coverage);
if (timestamp < 0x80)
fprintfIfDebug(outFileDebug, " %02X (%d)", timestamp, timestamp);
else
fprintfIfDebug(outFileDebug, " %02X%02X - %04X (%d)", inputMID[spot-2], inputMID[spot+1-2], timestamp, timestamp);
absoluteTime += timestamp;
}
else
{
fprintfIfDebug(outFileDebug, " UNKNOWN");
return;
}
fprintfIfDebug(outFileDebug, "\n");
}
if (returnBackAlternateChoices.size() > 0)
{
// Return from Jump and Link
spot = returnBackAlternateChoices.back();
returnBackAlternateChoices.pop_back();
command = 0x00;
fprintfIfDebug(outFileDebug, "... Taking Alternate Path to %08X\n", spot);
goto loopAgain;
}
if (returnBackOffset.size() > 0)
{
// Return from Jump and Link
spot = returnBackOffset.back();
returnBackOffset.pop_back();
command = 0x00;
fprintfIfDebug(outFileDebug, "... Returning from Subroutine to %08X\n", spot);
goto loopAgain;
}
int maxAbsoluteTime = 0;
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
if (pendingChannelNotes[x].endAbsoluteTime > maxAbsoluteTime)
maxAbsoluteTime = pendingChannelNotes[x].endAbsoluteTime;
}
std::sort(pendingChannelNotes.begin(), pendingChannelNotes.end(), sngSortByStartTime());
if (pendingChannelNotes.size() > 0)
{
if (instrumentByAbsoluteTime.size() == 0)
{
SngTimeValue pair;
pair.value = currentInstrument[channel];
pair.startAbsoluteTime = startAbsoluteTime;
pair.endAbsoluteTime = startAbsoluteTime;
instrumentByAbsoluteTime.push_back(pair);
}
if (effectByAbsoluteTime.size() == 0)
{
SngTimeValue pair;
pair.value = currentEffect[channel];
pair.startAbsoluteTime = startAbsoluteTime;
pair.endAbsoluteTime = startAbsoluteTime;
effectByAbsoluteTime.push_back(pair);
}
if (volumeByAbsoluteTime.size() == 0)
{
SngTimeValue pair;
pair.value = currentVolume[channel];
pair.startAbsoluteTime = startAbsoluteTime;
pair.endAbsoluteTime = startAbsoluteTime;
volumeByAbsoluteTime.push_back(pair);
}
if (panByAbsoluteTime.size() == 0)
{
SngTimeValue pair;
pair.value = currentPan[channel];
pair.startAbsoluteTime = startAbsoluteTime;
pair.endAbsoluteTime = startAbsoluteTime;
panByAbsoluteTime.push_back(pair);
}
if (pitchBendByAbsoluteTime.size() == 0)
{
SngTimeValue pair;
pair.value = currentPitchBend[channel];
pair.startAbsoluteTime = startAbsoluteTime;
pair.endAbsoluteTime = startAbsoluteTime;
pitchBendByAbsoluteTime.push_back(pair);
}
if (vibratoByAbsoluteTime.size() == 0)
{
SngTimeValue pair;
pair.value = currentVibrato[channel];
pair.startAbsoluteTime = startAbsoluteTime;
pair.endAbsoluteTime = startAbsoluteTime;
vibratoByAbsoluteTime.push_back(pair);
}
}
if (instrumentByAbsoluteTime.size() > 0)
{
if (instrumentByAbsoluteTime.size() > 1)
{
for (int x = (instrumentByAbsoluteTime.size() - 2); x >= 0; x--)
{
instrumentByAbsoluteTime[x].endAbsoluteTime = instrumentByAbsoluteTime[x+1].startAbsoluteTime;
}
}
instrumentByAbsoluteTime[instrumentByAbsoluteTime.size() - 1].endAbsoluteTime = maxAbsoluteTime;
}
if (effectByAbsoluteTime.size() > 0)
{
if (effectByAbsoluteTime.size() > 1)
{
for (int x = (effectByAbsoluteTime.size() - 2); x >= 0; x--)
{
effectByAbsoluteTime[x].endAbsoluteTime = effectByAbsoluteTime[x+1].startAbsoluteTime;
}
}
effectByAbsoluteTime[effectByAbsoluteTime.size() - 1].endAbsoluteTime = maxAbsoluteTime;
}
if (volumeByAbsoluteTime.size() > 0)
{
if (volumeByAbsoluteTime.size() > 1)
{
for (int x = (volumeByAbsoluteTime.size() - 2); x >= 0; x--)
{
volumeByAbsoluteTime[x].endAbsoluteTime = volumeByAbsoluteTime[x+1].startAbsoluteTime;
}
}
volumeByAbsoluteTime[volumeByAbsoluteTime.size() - 1].endAbsoluteTime = maxAbsoluteTime;
}
if (panByAbsoluteTime.size() > 0)
{
if (panByAbsoluteTime.size() > 1)
{
for (int x = (panByAbsoluteTime.size() - 2); x >= 0; x--)
{
panByAbsoluteTime[x].endAbsoluteTime = panByAbsoluteTime[x+1].startAbsoluteTime;
}
}
panByAbsoluteTime[panByAbsoluteTime.size() - 1].endAbsoluteTime = maxAbsoluteTime;
}
if (pitchBendByAbsoluteTime.size() > 0)
{
if (pitchBendByAbsoluteTime.size() > 1)
{
for (int x = (pitchBendByAbsoluteTime.size() - 2); x >= 0; x--)
{
pitchBendByAbsoluteTime[x].endAbsoluteTime = pitchBendByAbsoluteTime[x+1].startAbsoluteTime;
}
}
pitchBendByAbsoluteTime[pitchBendByAbsoluteTime.size() - 1].endAbsoluteTime = maxAbsoluteTime;
}
if (vibratoByAbsoluteTime.size() > 0)
{
if (vibratoByAbsoluteTime.size() > 1)
{
for (int x = (vibratoByAbsoluteTime.size() - 2); x >= 0; x--)
{
vibratoByAbsoluteTime[x].endAbsoluteTime = vibratoByAbsoluteTime[x+1].startAbsoluteTime;
}
}
vibratoByAbsoluteTime[vibratoByAbsoluteTime.size() - 1].endAbsoluteTime = maxAbsoluteTime;
}
// Add in Volume
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
for (int y = 0; y < volumeByAbsoluteTime.size(); y++)
{
// Volume To Left/Equal Ending in Middle
if (
(pendingChannelNotes[x].startAbsoluteTime >= volumeByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (pendingChannelNotes[x].volume != volumeByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].startAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.volume = volumeByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
//Volume In Middle, Ending to Right
else if (
(pendingChannelNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= volumeByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (pendingChannelNotes[x].volume != volumeByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.volume = volumeByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
// Volume Completely Inside
else if (
(pendingChannelNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (pendingChannelNotes[x].volume != volumeByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
SngNoteInfo newNoteInfo2 = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = volumeByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.volume = volumeByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = volumeByAbsoluteTime[y].endAbsoluteTime;
pendingChannelNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// Volume Completely Outside
else if (
(pendingChannelNotes[x].startAbsoluteTime >= volumeByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < volumeByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > volumeByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= volumeByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
pendingChannelNotes[x].volume = volumeByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
// Add in Pitch Bend
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
for (int y = 0; y < pitchBendByAbsoluteTime.size(); y++)
{
// PitchBend To Left/Equal Ending in Middle
if (
(pendingChannelNotes[x].startAbsoluteTime >= pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (pendingChannelNotes[x].pitchBend != pitchBendByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].startAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.pitchBend = pitchBendByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
//PitchBend In Middle, Ending to Right
else if (
(pendingChannelNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= pitchBendByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (pendingChannelNotes[x].pitchBend != pitchBendByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.pitchBend = pitchBendByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
// PitchBend Completely Inside
else if (
(pendingChannelNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (pendingChannelNotes[x].pitchBend != pitchBendByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
SngNoteInfo newNoteInfo2 = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = pitchBendByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.pitchBend = pitchBendByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = pitchBendByAbsoluteTime[y].endAbsoluteTime;
pendingChannelNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// PitchBend Completely Outside
else if (
(pendingChannelNotes[x].startAbsoluteTime >= pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < pitchBendByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > pitchBendByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= pitchBendByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
pendingChannelNotes[x].pitchBend = pitchBendByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
// Add in Pan
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
for (int y = 0; y < panByAbsoluteTime.size(); y++)
{
// Pan To Left/Equal Ending in Middle
if (
(pendingChannelNotes[x].startAbsoluteTime >= panByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < panByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > panByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > panByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (pendingChannelNotes[x].pan != panByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].startAbsoluteTime = panByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = panByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.pan = panByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
//Pan In Middle, Ending to Right
else if (
(pendingChannelNotes[x].startAbsoluteTime < panByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < panByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > panByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= panByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (pendingChannelNotes[x].pan != panByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = panByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = panByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.pan = panByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
// Pan Completely Inside
else if (
(pendingChannelNotes[x].startAbsoluteTime < panByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < panByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > panByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > panByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (pendingChannelNotes[x].pan != panByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
SngNoteInfo newNoteInfo2 = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = panByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = panByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = panByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.pan = panByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = panByAbsoluteTime[y].endAbsoluteTime;
pendingChannelNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// Pan Completely Outside
else if (
(pendingChannelNotes[x].startAbsoluteTime >= panByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < panByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > panByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= panByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
pendingChannelNotes[x].pan = panByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
// Add in Effect
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
for (int y = 0; y < effectByAbsoluteTime.size(); y++)
{
// Effect To Left/Equal Ending in Middle
if (
(pendingChannelNotes[x].startAbsoluteTime >= effectByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < effectByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > effectByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > effectByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (pendingChannelNotes[x].effect != effectByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].startAbsoluteTime = effectByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = effectByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.effect = effectByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
//Effect In Middle, Ending to Right
else if (
(pendingChannelNotes[x].startAbsoluteTime < effectByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < effectByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > effectByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= effectByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (pendingChannelNotes[x].effect != effectByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = effectByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = effectByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.effect = effectByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
// Effect Completely Inside
else if (
(pendingChannelNotes[x].startAbsoluteTime < effectByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < effectByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > effectByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > effectByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (pendingChannelNotes[x].effect != effectByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
SngNoteInfo newNoteInfo2 = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = effectByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = effectByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = effectByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.effect = effectByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = effectByAbsoluteTime[y].endAbsoluteTime;
pendingChannelNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// Effect Completely Outside
else if (
(pendingChannelNotes[x].startAbsoluteTime >= effectByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < effectByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > effectByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= effectByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
pendingChannelNotes[x].effect = effectByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
// Add in Instrument
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
for (int y = 0; y < instrumentByAbsoluteTime.size(); y++)
{
// Instrument To Left/Equal Ending in Middle
if (
(pendingChannelNotes[x].startAbsoluteTime >= instrumentByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < instrumentByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > instrumentByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > instrumentByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (pendingChannelNotes[x].instrument != instrumentByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].startAbsoluteTime = instrumentByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = instrumentByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.instrument = instrumentByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
//Instrument In Middle, Ending to Right
else if (
(pendingChannelNotes[x].startAbsoluteTime < instrumentByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < instrumentByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > instrumentByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= instrumentByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (pendingChannelNotes[x].instrument != instrumentByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = instrumentByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = instrumentByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.instrument = instrumentByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
// Instrument Completely Inside
else if (
(pendingChannelNotes[x].startAbsoluteTime < instrumentByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < instrumentByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > instrumentByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > instrumentByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (pendingChannelNotes[x].instrument != instrumentByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
SngNoteInfo newNoteInfo2 = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = instrumentByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = instrumentByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = instrumentByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.instrument = instrumentByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = instrumentByAbsoluteTime[y].endAbsoluteTime;
pendingChannelNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// Instrument Completely Outside
else if (
(pendingChannelNotes[x].startAbsoluteTime >= instrumentByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < instrumentByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > instrumentByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= instrumentByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
pendingChannelNotes[x].instrument = instrumentByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
// Add in Vibrato
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
for (int y = 0; y < vibratoByAbsoluteTime.size(); y++)
{
// Vibrato To Left/Equal Ending in Middle
if (
(pendingChannelNotes[x].startAbsoluteTime >= vibratoByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < vibratoByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > vibratoByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > vibratoByAbsoluteTime[y].startAbsoluteTime)
)
{
//Split at Middle, Apply to Beginning
if (pendingChannelNotes[x].vibrato != vibratoByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].startAbsoluteTime = vibratoByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.endAbsoluteTime = vibratoByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.vibrato = vibratoByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
//Vibrato In Middle, Ending to Right
else if (
(pendingChannelNotes[x].startAbsoluteTime < vibratoByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < vibratoByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > vibratoByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= vibratoByAbsoluteTime[y].endAbsoluteTime)
)
{
//Split at Middle, Apply to End
if (pendingChannelNotes[x].vibrato != vibratoByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = vibratoByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = vibratoByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.vibrato = vibratoByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
x--;
break;
}
}
// Vibrato Completely Inside
else if (
(pendingChannelNotes[x].startAbsoluteTime < vibratoByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < vibratoByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > vibratoByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > vibratoByAbsoluteTime[y].endAbsoluteTime)
)
{
// Split at Mid-Left and Mid-Right
if (pendingChannelNotes[x].vibrato != vibratoByAbsoluteTime[y].value)
{
SngNoteInfo newNoteInfo = pendingChannelNotes[x];
SngNoteInfo newNoteInfo2 = pendingChannelNotes[x];
pendingChannelNotes[x].endAbsoluteTime = vibratoByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.startAbsoluteTime = vibratoByAbsoluteTime[y].startAbsoluteTime;
newNoteInfo.endAbsoluteTime = vibratoByAbsoluteTime[y].endAbsoluteTime;
newNoteInfo.vibrato = vibratoByAbsoluteTime[y].value;
pendingChannelNotes.push_back(newNoteInfo);
newNoteInfo2.startAbsoluteTime = vibratoByAbsoluteTime[y].endAbsoluteTime;
pendingChannelNotes.push_back(newNoteInfo2);
x--;
break;
}
}
// Vibrato Completely Outside
else if (
(pendingChannelNotes[x].startAbsoluteTime >= vibratoByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].startAbsoluteTime < vibratoByAbsoluteTime[y].endAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime > vibratoByAbsoluteTime[y].startAbsoluteTime)
&& (pendingChannelNotes[x].endAbsoluteTime <= vibratoByAbsoluteTime[y].endAbsoluteTime)
)
{
// Apply to whole
pendingChannelNotes[x].vibrato = vibratoByAbsoluteTime[y].value;
}
// No Overlap
else
{
}
}
}
for (int x = 0; x < pendingChannelNotes.size(); x++)
{
outputNotes.push_back(pendingChannelNotes[x]);
}
}
void CMidiParse::ParseEADMusicSequence(int gameStyle, FILE* outFileDebug, unsigned char* inputMID, int offset ,int end, unsigned long& absoluteTime, std::vector<unsigned long>& jumpStarts, std::vector<unsigned long>& jumpsTaken, bool attemptJumps,
int& numberInstruments, std::vector<TimeAndValue>& tempoPositions, std::vector<SngNoteInfo>& outputNotes,
int& noteUniqueId,
int currentInstrument[0x10], int currentPan[0x10], int currentVolume[0x10], int currentPitchBend[0x10], int currentReverb[0x10], bool& hitConditional, unsigned char* coverage, bool channelStarted[0x10],
int currentVibrato[0x10]
)
{
unsigned char command = 0x00;
unsigned long spot = offset;
fprintfIfDebug(outFileDebug, "-------------------SEQUENCE %08X-------------------\n", offset);
std::vector<int> returnBackOffset;
std::vector<int> returnBackAlternateChoices;
loopAgain:
while ((command != 0xFF) && (spot < end))
{
command = inputMID[spot];
fprintfIfDebug(outFileDebug, "SEQ %08X Time: %08X CMD: %02X", spot, absoluteTime, command);
IncrementSpot(spot, 1, coverage);
if (command == 0xFF)
{
fprintfIfDebug(outFileDebug, " END\n");
break;
}
else if (command == 0xFE)
{
fprintfIfDebug(outFileDebug, " RETURN\n");
break;
}
else if ((command >= 0x0) && (command < 0x10))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x10) && (command < 0x40))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x40) && (command < 0x50))
{
fprintfIfDebug(outFileDebug, " ?");
}
else if ((command >= 0x50) && (command < 0x60))
{
fprintfIfDebug(outFileDebug, " Set Play Value to (Play Value - Channel Value %02X)", command & 0xF);
}
else if ((command >= 0x60) && (command < 0x70))
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if ((command >= 0x70) && (command < 0x80))
{
fprintfIfDebug(outFileDebug, " Set Channel Value %02X to Play Value", command & 0xF);
}
else if ((command >= 0x80) && (command < 0x90))
{
// READMusic Values Set 1
// Write to Values Set 2 if >= 2
// else Write FFFF (-1)
fprintfIfDebug(outFileDebug, " Set Play Value to Channel Value %02X If Channel >= 2 Else -1", command & 0xF);
}
else if ((command >= 0x90) && (command < 0xA0))
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
unsigned char channel = command & 0xF;
fprintfIfDebug(outFileDebug, " Channel Pointer Channel %X", command & 0xF);
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
fprintfIfDebug(outFileDebug, "\n");
std::vector<unsigned long> jumpStartsChannel;
std::vector<unsigned long> jumpsTakenChannel;
ParseEADMusicChannel(gameStyle, outFileDebug, inputMID, end, offset, channel, absoluteTime, numberInstruments, tempoPositions, outputNotes, noteUniqueId, currentInstrument, currentPan, currentVolume, currentPitchBend, currentReverb, jumpStartsChannel, jumpsTakenChannel, attemptJumps, coverage, channelStarted, currentVibrato);
}
else if ((command >= 0xA0) && (command < 0xB0))
{
// Not sure about this
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
unsigned char channel = command & 0xF;
fprintfIfDebug(outFileDebug, " Channel Pointer Offset Channel %X", command & 0xF);
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
fprintfIfDebug(outFileDebug, "\n");
std::vector<unsigned long> jumpStartsChannel;
std::vector<unsigned long> jumpsTakenChannel;
ParseEADMusicChannel(gameStyle, outFileDebug, inputMID, end, spot + offset, channel, absoluteTime, numberInstruments, tempoPositions, outputNotes, noteUniqueId, currentInstrument, currentPan, currentVolume, currentPitchBend, currentReverb, jumpStartsChannel, jumpsTakenChannel, attemptJumps, coverage, channelStarted, currentVibrato);
}
else if ((command >= 0xB0) && (command < 0xC0))
{
unsigned char index = inputMID[spot];
unsigned short offset = ((inputMID[spot + 1] << 8) | inputMID[spot+2]);
fprintfIfDebug(outFileDebug, " Load And Goto Sequence at Offset");
fprintfIfDebug(outFileDebug, " %02X At %02X%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
fprintfIfDebug(outFileDebug, "\n");
break;
}
else if (command == 0xC0)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC2)
{
// Really uses play values and external to set...can probably not ever get this right sadly.
//DMGJ 0x10
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
std::vector<unsigned short> values;
fprintfIfDebug(outFileDebug, " Set Jump Table Sequence");
fprintfIfDebug(outFileDebug, " Offset with Data %02X%02X", inputMID[spot], inputMID[spot+1]);
unsigned short previousValueTemp = 0;
while (true)
{
unsigned short valueTemp = CharArrayToShort(&inputMID[offset + (values.size() * 2)]);
if ((valueTemp >= end) || (valueTemp <= previousValueTemp))
break;
fprintfIfDebug(outFileDebug, " Value %02X %04X", (values.size()), valueTemp);
values.push_back(valueTemp);
previousValueTemp = valueTemp;
}
IncrementSpot(spot, 2, coverage);
fprintfIfDebug(outFileDebug, "\n");
for (int v = 0; v < values.size(); v++)
{
if ((offset + (v * 2 + 1)) < end)
{
coverage[offset + (v * 2)] = 0x00;
coverage[offset + (v * 2) + 1] = 0x00;
ParseEADMusicSequence(gameStyle, outFileDebug, inputMID, values[v], end, absoluteTime, jumpStarts, jumpsTaken, attemptJumps, numberInstruments, tempoPositions, outputNotes, noteUniqueId, currentInstrument, currentPan, currentVolume, currentPitchBend, currentReverb, hitConditional, coverage, channelStarted, currentVibrato);
}
}
}
else if (command == 0xC3)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xC4)
{
fprintfIfDebug(outFileDebug, " DONE?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
fprintfIfDebug(outFileDebug, "\n");
break;
}
else if (command == 0xC5)
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xC6)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC7)
{
fprintfIfDebug(outFileDebug, " ? Pitch Related");
fprintfIfDebug(outFileDebug, " %02X%02X%02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xC8)
{
fprintfIfDebug(outFileDebug, " Subtract Play Value - Value");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xC9)
{
fprintfIfDebug(outFileDebug, " And Play Value and Value");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCA)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xCB)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xCC)
{
fprintfIfDebug(outFileDebug, " Set Play Value");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCD)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
fprintfIfDebug(outFileDebug, "\n");
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xCE)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xCF)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xD0)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD2)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xD3)
{
fprintfIfDebug(outFileDebug, " Begin Sequence");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD4)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xD5)
{
fprintfIfDebug(outFileDebug, " Sequence Type");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD6)
{
fprintfIfDebug(outFileDebug, " Channel Disable");
fprintfIfDebug(outFileDebug, " %02X%02X Channels", inputMID[spot], inputMID[spot+1]);
unsigned short channelEnables = ((inputMID[spot] << 8) | inputMID[spot + 1]);
for (int x = 0; x < 0x10; x++)
{
if (channelEnables & 0x1)
fprintfIfDebug(outFileDebug, " %X", x);
channelEnables >>= 1;
}
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xD7)
{
fprintfIfDebug(outFileDebug, " Channel Enable");
fprintfIfDebug(outFileDebug, " %02X%02X Channels", inputMID[spot], inputMID[spot+1]);
unsigned short channelEnables = ((inputMID[spot] << 8) | inputMID[spot + 1]);
for (int x = 0; x < 0x10; x++)
{
if (channelEnables & 0x1)
fprintfIfDebug(outFileDebug, " %X", x);
channelEnables >>= 1;
}
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xD8)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xD9)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xDA)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d) %02X (%d) %02X (%d)", inputMID[spot], inputMID[spot], inputMID[spot+1], inputMID[spot+1], inputMID[spot+2], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xDB)
{
fprintfIfDebug(outFileDebug, " Master Volume");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xDC)
{
fprintfIfDebug(outFileDebug, " SFX Volume");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xDD)
{
fprintfIfDebug(outFileDebug, " Tempo");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
unsigned char tempo = inputMID[spot];
unsigned long currentTempo = (unsigned long)(60000000.0 / (float)tempo);
tempoPositions.push_back(TimeAndValue(absoluteTime, currentTempo));
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xDE)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
IncrementSpot(spot, 2, coverage);
}
else if (command == 0xDF)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE0)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X %02X %02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xE2)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X %02X %02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xE3)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE4)
{
fprintfIfDebug(outFileDebug, " Use Play Value to Offset into Jump Table (from last Command C2)");
}
else if (command == 0xE5)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE6)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xE7)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xE8)
{
// NUD-DMGJ
//E800000E003F7F0000
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d) %02X (%d)",
inputMID[spot], inputMID[spot],
inputMID[spot+1], inputMID[spot+1],
inputMID[spot+2], inputMID[spot+2],
inputMID[spot+3], inputMID[spot+3],
inputMID[spot+4], inputMID[spot+4],
inputMID[spot+5], inputMID[spot+5],
inputMID[spot+6], inputMID[spot+6],
inputMID[spot+7], inputMID[spot+7]
);
IncrementSpot(spot, 8, coverage);
}
else if (command == 0xE9)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xEA)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEB)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEC)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xED)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEE)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xEF)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X%02X %02X", inputMID[spot], inputMID[spot+1], inputMID[spot+2]);
IncrementSpot(spot, 3, coverage);
}
else if (command == 0xF0)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF1)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xF2)
{
hitConditional = true;
fprintfIfDebug(outFileDebug, " Go to Relative Offset if Play Value < 0");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
}
}
}
else if (command == 0xF3)
{
hitConditional = true;
fprintfIfDebug(outFileDebug, " Go to Relative Offset if Play Value == 0");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
}
}
}
else if (command == 0xF4)
{
hitConditional = true;
fprintfIfDebug(outFileDebug, " Go to relative offset");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], (signed char)inputMID[spot]);
int relativeOffset = (signed char)inputMID[spot];
IncrementSpot(spot, 1, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 2);
break;
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), relativeOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(relativeOffset);
spot = spot + relativeOffset;
}
else
{
break;
}
}
}
}
else if (command == 0xF5)
{
hitConditional = true;
fprintfIfDebug(outFileDebug, " Go to absolute offset if Play Value >= 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xF6)
{
fprintfIfDebug(outFileDebug, " Restart Song");
if (attemptJumps)
{
int startSpot = 0;
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), startSpot) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(startSpot);
spot = startSpot;
}
}
}
else if (command == 0xF7)
{
fprintfIfDebug(outFileDebug, " ?");
}
else if (command == 0xF8)
{
fprintfIfDebug(outFileDebug, " ?");
fprintfIfDebug(outFileDebug, " %02X (%d)", inputMID[spot], inputMID[spot]);
IncrementSpot(spot, 1, coverage);
}
else if (command == 0xF9)
{
hitConditional = true;
fprintfIfDebug(outFileDebug, " Go to Absolute Offset if Play Value < 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xFA)
{
hitConditional = true;
fprintfIfDebug(outFileDebug, " Go to Absolute Offset if Play Value == 0");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
}
}
}
else if (command == 0xFB)
{
fprintfIfDebug(outFileDebug, " Go to absolute offset");
fprintfIfDebug(outFileDebug, " %02X%02X", inputMID[spot], inputMID[spot+1]);
int absoluteOffset = CharArrayToShort(&inputMID[spot]);
IncrementSpot(spot, 2, coverage);
// Assume if next Channel Disable, is actually end of song for a real loop
if (inputMID[spot] == 0xD6)
{
if (!hitConditional)
{
fprintfIfDebug(outFileDebug, "...Assuming End of Song\n");
break;
}
}
if (attemptJumps)
{
if (std::find(jumpStarts.begin(), jumpStarts.end(), spot) == jumpStarts.end())
{
fprintfIfDebug(outFileDebug, "...Skipping First Time\n");
jumpStarts.push_back(spot);
returnBackAlternateChoices.push_back(spot - 3);
break;
}
else
{
if (std::find(jumpsTaken.begin(), jumpsTaken.end(), absoluteOffset) == jumpsTaken.end())
{
fprintfIfDebug(outFileDebug, "...Taking\n");
jumpsTaken.push_back(absoluteOffset);
spot = absoluteOffset;
}
else
{
break;
}
}
}
}
else if (command == 0xFC)
{
unsigned short offset = ((inputMID[spot] << 8) | inputMID[spot+1]);
fprintfIfDebug(outFileDebug, " Jump and Link");
fprintfIfDebug(outFileDebug, " Offset %04X", offset);
IncrementSpot(spot, 2, coverage);
returnBackOffset.push_back(spot);
spot = offset;
}
else if (command == 0xFD)
{
fprintfIfDebug(outFileDebug, " Delay");
int timestamp = ReadEADMusicTimeValue(inputMID, spot, coverage);
if (timestamp < 0x80)
fprintfIfDebug(outFileDebug, " %02X (%d)", timestamp, timestamp);
else
fprintfIfDebug(outFileDebug, " %02X%02X - %04X (%d)", inputMID[spot-2], inputMID[spot+1-2], timestamp, timestamp);
absoluteTime += timestamp;
}
else
{
fprintfIfDebug(outFileDebug, " UNKNOWN");
return;
}
fprintfIfDebug(outFileDebug, "\n");
}
if (returnBackAlternateChoices.size() > 0)
{
// Return from Jump and Link
spot = returnBackAlternateChoices.back();
returnBackAlternateChoices.pop_back();
command = 0x00;
fprintfIfDebug(outFileDebug, "... Taking Alternate Path to %08X\n", spot);
goto loopAgain;
}
if (returnBackOffset.size() > 0)
{
// Return from Jump and Link
spot = returnBackOffset.back();
returnBackOffset.pop_back();
command = 0x00;
fprintfIfDebug(outFileDebug, "... Returning from Subroutine to %08X\n", spot);
goto loopAgain;
}
}
void CMidiParse::EADMusicToMidi(CString gameName, int gameStyle, byte* inputMID, int address, int inputSize, CString outFileName,
int& numberInstruments, bool calculateInstrumentCountOnly, bool separateByInstrument, unsigned long extra,
bool writeDebug, CString debugFilename, int pitchBendRange)
{
numberInstruments = 1;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
try
{
std::vector<SngNoteInfo> sngNoteList;
numberInstruments = 1;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
int currentInstrument[0x10];
int currentPan[0x10];
int currentVolume[0x10];
int currentPitchBend[0x10];
int currentReverb[0x10];
bool channelStarted[0x10];
int currentVibrato[0x10];
for (int x = 0; x < 0x10; x++)
{
currentInstrument[x] = 0x00;
currentPan[x] = 0x40;
currentVolume[x] = 0x7F;
currentPitchBend[x] = 0x40;
currentReverb[x] = 0x00;
channelStarted[x] = false;
currentVibrato[x] = 0x00;
}
FILE* outFileDebug = NULL;
if (writeDebug)
{
outFileDebug = fopen(debugFilename, "w");
CString addressStr;
addressStr.Format("%08X", address);
fprintf(outFileDebug, gameName + " - " + addressStr + "\n");
fprintf(outFileDebug, "EAD Music\n\n");
}
unsigned long absoluteTime = 0;
std::vector<unsigned long> jumpStarts;
std::vector<unsigned long> jumpsTaken;
bool attemptJumps = true;
bool hitConditional = false;
unsigned char* coverage = new unsigned char[inputSize];
memcpy(coverage, &inputMID[address], inputSize);
ParseEADMusicSequence(gameStyle, outFileDebug, &inputMID[address], 0, inputSize, absoluteTime, jumpStarts, jumpsTaken, attemptJumps, numberInstruments, tempoPositions, sngNoteList, noteUniqueId, currentInstrument, currentPan, currentVolume, currentPitchBend, currentReverb, hitConditional, coverage, channelStarted, currentVibrato);
WriteSngList(sngNoteList, tempoPositions, outFileName, separateByInstrument, 0x0030, true, pitchBendRange);
if (outFileDebug)
{
fflush(outFileDebug);
fclose(outFileDebug);
outFileDebug = NULL;
FILE* outDebugCoverage = fopen(debugFilename + "Coverage.bin", "wb");
if (outDebugCoverage)
{
fwrite(coverage, 1, inputSize, outDebugCoverage);
}
fclose(outDebugCoverage);
delete [] coverage;
}
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
void CMidiParse::Factor5ToDebugTextFile(CString gameName, unsigned long address, CString midiFile, CString textFileOut, bool isRogueStyle)
{
CString filepath = midiFile;
FILE* inFile = fopen(filepath, "rb");
if (inFile == NULL)
{
MessageBox(NULL, "Can't read input file " + filepath, "Error", NULL);
return;
}
fseek(inFile, 0, SEEK_END);
int inputSize = ftell(inFile);
rewind(inFile);
unsigned char* inputMID = new unsigned char[inputSize];
fread(inputMID, 1, inputSize, inFile);
fclose(inFile);
Factor5ToDebugTextFile(gameName, address, inputMID, inputSize, textFileOut, isRogueStyle);
delete [] inputMID;
}
void CMidiParse::Factor5ToDebugTextFile(CString gameName, unsigned long address, byte* inputMID, int inputSize, CString textFileOut, bool isRogueStyle)
{
FILE* outFile = fopen(textFileOut, "w");
unsigned long instrumentOffset = CharArrayToLong(&inputMID[0x8]);
fprintf(outFile, "Instruments\n");
for (int x = 0; x < 0x40; x++)
{
if (inputMID[instrumentOffset + x] != 0xFF)
fprintf(outFile, "%02X:%02X\n", x, inputMID[instrumentOffset + x]);
}
fprintf(outFile, "\n");
fprintf(outFile, "Initial Tempo %08X", CharArrayToLong(&inputMID[0x10]));
fprintf(outFile, "\n");
unsigned long tempoOffset = CharArrayToLong(&inputMID[0xC]);
if (tempoOffset != 0x00000000)
{
fprintf(outFile, "Tempos\n");
int tempoIndex = 0;
while (true)
{
if (CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8)]) == 0xFFFFFFFF)
break;
else
{
fprintf(outFile, "%08X:%08X\n", CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8)]), CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8) + 4]));
tempoIndex++;
}
}
}
fprintf(outFile, "\n");
fprintf(outFile, "Channels\n");
fprintf(outFile, "-----------------------------------------\n");
unsigned long channelOffsets = CharArrayToLong(&inputMID[0x0]);
unsigned long trackOffsets = CharArrayToLong(&inputMID[0x4]);
int numberChannels = 0;
while (true)
{
if (
(CharArrayToLong(&inputMID[channelOffsets + (numberChannels * 0x4)]) == 0x00000000) && (!isRogueStyle)
)
{
numberChannels++;
if (numberChannels == 64)
break;
else
continue;
}
else if (CharArrayToLong(&inputMID[channelOffsets + (numberChannels * 0x4)]) == 0x00000000)
{
break;
}
else
{
unsigned long channelOffset = CharArrayToLong(&inputMID[channelOffsets + (numberChannels * 0x4)]);
fprintf(outFile, "Channel #%02X Offset: %08X\n", numberChannels, channelOffset);
fprintf(outFile, "-----------------------------------------\n");
while ((inputMID[channelOffset+5] != 0x00) && ((signed short)CharArrayToShort(&inputMID[channelOffset+8]) >= 0))
{
fprintf(outFile, "Start Tick: %08X\n", CharArrayToLong(&inputMID[channelOffset]));
fprintf(outFile, "Continuation: %08X\n", CharArrayToLong(&inputMID[channelOffset+4]));
fprintf(outFile, "Track Index: %04X\n", CharArrayToShort(&inputMID[channelOffset+8]));
fprintf(outFile, "Flags?: %04X\n", CharArrayToShort(&inputMID[channelOffset+0xA]));
fprintf(outFile, "\n");
unsigned long startTick = CharArrayToLong(&inputMID[channelOffset]);
unsigned short trackIndex = CharArrayToShort(&inputMID[channelOffset+8]);
unsigned long trackOffset = CharArrayToLong(&inputMID[trackOffsets + (trackIndex * 0x4)]);
fprintf(outFile, "Track %02X Offset: %08X\n", trackIndex, trackOffset);
fprintf(outFile, "-----------------------------------------\n");
unsigned long headerSize = CharArrayToLong(&inputMID[trackOffset]);
fprintf(outFile, "Header Size: %08X\n", headerSize);
if (CharArrayToLong(&inputMID[trackOffset+4]) != NULL)
{
fprintf(outFile, "Pitch Wheel Offset: %08X\n", CharArrayToLong(&inputMID[trackOffset+4]));
}
else
fprintf(outFile, "No Pitch Wheel\n");
if (CharArrayToLong(&inputMID[trackOffset+8]) != NULL)
{
fprintf(outFile, "Mod Wheel Offset: %08X\n", CharArrayToLong(&inputMID[trackOffset+8]));
}
else
fprintf(outFile, "No Mod Wheel\n");
trackOffset += 4 + headerSize;
fprintf(outFile, "\n");
unsigned long absoluteTime = startTick;
while (true)
{
if (isRogueStyle)
{
absoluteTime = startTick + CharArrayToLong(&inputMID[trackOffset]);
trackOffset += 4;
if ((CharArrayToLong(&inputMID[trackOffset]) & 0x0000FFFF) == 0x0000FFFF)
{
fprintf(outFile, "%08X Time %08X End\n", trackOffset, absoluteTime);
trackOffset += 4;
break;
}
if (((inputMID[trackOffset]) & 0x80) == 0x00)
{
if ((inputMID[trackOffset+2] & 0x80) == 0x00)
{
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset]);
unsigned char note = (inputMID[trackOffset+2] & 0x7F);
unsigned char velocity = (inputMID[trackOffset + 3] & 0x7F);
fprintf(outFile, "%08X Time %08X Length %04X Note %02X Velocity %02X\n", trackOffset, absoluteTime, noteLength, note, velocity);
}
else
{
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset]);
unsigned char value = (inputMID[trackOffset+2] & 0x7F);
unsigned char command = (inputMID[trackOffset + 3] & 0x7F);
fprintf(outFile, "%08X Time %08X Length %04X Cmd %02X Value %02X\n", trackOffset, absoluteTime, noteLength, command, value);
}
trackOffset += 4;
}
else if (((inputMID[trackOffset]) & 0x80) == 0x80)
{
unsigned char value = (inputMID[trackOffset] & 0x7F);
unsigned char controller = (inputMID[trackOffset + 1] & 0x7F);
fprintf(outFile, "%08X Time %08X Controller %02X Value %02X\n", trackOffset, absoluteTime, controller, value);
trackOffset += 2;
}
}
else
{
if ((CharArrayToLong(&inputMID[trackOffset]) & 0x0000FFFF) == 0x0000FFFF)
{
fprintf(outFile, "%08X Time %08X End\n", trackOffset, absoluteTime);
trackOffset += 4;
break;
}
absoluteTime += DecodeFactor5DeltaTimeRLE(inputMID, trackOffset);
if (((inputMID[trackOffset]) & 0x80) == 0x00)
{
unsigned char note = (inputMID[trackOffset] & 0x7F);
unsigned char velocity = (inputMID[trackOffset+1] & 0x7F);
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset+2]);
fprintf(outFile, "%08X Time %08X Note %02X Velocity %02X Length %04X \n", trackOffset, absoluteTime, note, velocity, noteLength);
trackOffset += 4;
}
else
{
unsigned char value = (inputMID[trackOffset] & 0x7F);
unsigned char controller = (inputMID[trackOffset + 1] & 0x7F);
fprintf(outFile, "%08X Time %08X Controller %02X Value %02X\n", trackOffset, absoluteTime, controller, value);
trackOffset += 2;
}
}
}
fprintf(outFile, "\n");
channelOffset += 0xC;
}
fprintf(outFile, "Start Tick: %08X\n", CharArrayToLong(&inputMID[channelOffset]));
fprintf(outFile, "Continuation: %08X (End)\n", CharArrayToLong(&inputMID[channelOffset+4]));
fprintf(outFile, "Track Index: %04X\n", CharArrayToShort(&inputMID[channelOffset+8]));
fprintf(outFile, "Flags?: %04X\n", CharArrayToShort(&inputMID[channelOffset+0xA]));
fprintf(outFile, "\n");
channelOffset += 0xC;
fprintf(outFile, "\n");
}
numberChannels++;
}
fprintf(outFile, "\n\n\n\n\n");
fprintf(outFile, "Tracks Individually\n");
fprintf(outFile, "-----------------------------------------\n");
int numberTracks = 0;
while (true)
{
unsigned long trackOffset = CharArrayToLong(&inputMID[trackOffsets + (numberTracks * 0x4)]);
if (
(CharArrayToLong(&inputMID[trackOffsets + (numberTracks * 0x4)]) == 0x00000000)
|| (CharArrayToLong(&inputMID[trackOffsets + (numberTracks * 0x4)]) == 0x00000008)
)
{
break;
}
else
{
fprintf(outFile, "Track %02X Offset: %08X\n", numberTracks, trackOffset);
fprintf(outFile, "-----------------------------------------\n");
unsigned long headerSize = CharArrayToLong(&inputMID[trackOffset]);
fprintf(outFile, "Header Size: %08X\n", headerSize);
if (CharArrayToLong(&inputMID[trackOffset+4]) != NULL)
{
fprintf(outFile, "Pitch Wheel Offset: %08X\n", CharArrayToLong(&inputMID[trackOffset+4]));
}
else
fprintf(outFile, "No Pitch Wheel\n");
if (CharArrayToLong(&inputMID[trackOffset+8]) != NULL)
{
fprintf(outFile, "Mod Wheel Offset: %08X\n", CharArrayToLong(&inputMID[trackOffset+8]));
}
else
fprintf(outFile, "No Mod Wheel\n");
trackOffset += 4 + headerSize;
fprintf(outFile, "\n");
unsigned long absoluteTime = 0x00000000;
while (true)
{
if (isRogueStyle)
{
absoluteTime = CharArrayToLong(&inputMID[trackOffset]);
trackOffset += 4;
if ((CharArrayToLong(&inputMID[trackOffset]) & 0x0000FFFF) == 0x0000FFFF)
{
fprintf(outFile, "%08X Time %08X End\n", trackOffset, absoluteTime);
trackOffset += 4;
break;
}
if (((inputMID[trackOffset]) & 0x80) == 0x00)
{
if ((inputMID[trackOffset+2] & 0x80) == 0x00)
{
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset]);
unsigned char note = (inputMID[trackOffset+2] & 0x7F);
unsigned char velocity = (inputMID[trackOffset + 3] & 0x7F);
fprintf(outFile, "%08X Time %08X Length %04X Note %02X Velocity %02X\n", trackOffset, absoluteTime, noteLength, note, velocity);
}
else
{
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset]);
unsigned char value = (inputMID[trackOffset+2] & 0x7F);
unsigned char command = (inputMID[trackOffset + 3] & 0x7F);
fprintf(outFile, "%08X Time %08X Length %04X Cmd %02X Value %02X\n", trackOffset, absoluteTime, noteLength, command, value);
}
trackOffset += 4;
}
else if (((inputMID[trackOffset]) & 0x80) == 0x80)
{
unsigned char value = (inputMID[trackOffset] & 0x7F);
unsigned char controller = (inputMID[trackOffset + 1] & 0x7F);
fprintf(outFile, "%08X Time %08X Controller %02X Value %02X\n", trackOffset, absoluteTime, controller, value);
trackOffset += 2;
}
}
else
{
if ((CharArrayToLong(&inputMID[trackOffset]) & 0x0000FFFF) == 0x0000FFFF)
{
fprintf(outFile, "%08X Time %08X End\n", trackOffset, absoluteTime);
trackOffset += 4;
break;
}
unsigned short timeDelta = DecodeFactor5DeltaTimeRLE(inputMID, trackOffset);
absoluteTime += timeDelta;
if (((inputMID[trackOffset]) & 0x80) == 0x00)
{
unsigned char note = (inputMID[trackOffset] & 0x7F);
unsigned char velocity = (inputMID[trackOffset+1] & 0x7F);
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset+2]);
fprintf(outFile, "%08X Time %08X Note %02X Velocity %02X Length %04X \n", trackOffset, absoluteTime, note, velocity, noteLength);
trackOffset += 4;
}
else
{
unsigned char value = (inputMID[trackOffset] & 0x7F);
unsigned char controller = (inputMID[trackOffset + 1] & 0x7F);
fprintf(outFile, "%08X Time %08X Controller %02X Value %02X\n", trackOffset, absoluteTime, controller, value);
trackOffset += 2;
}
}
}
fprintf(outFile, "\n\n");
}
numberTracks++;
}
fprintf(outFile, "\n");
fclose(outFile);
}
int CMidiParse::DecodeFactor5DeltaTimeRLE(unsigned char* input, unsigned long& offset)
{
int total = 0;
while (true)
{
int term = CharArrayToShort(&input[offset]);
offset += 2;
if (term == 0xffff)
{
total += 0xffff;
int dummy = CharArrayToShort(&input[offset]);
offset += 2;
continue;
}
total += term;
return total;
}
}
void CMidiParse::Factor5ToMidi(byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool calculateInstrumentCountOnly, bool separateByInstrument, bool isRogueStyle)
{
// Contributions to figuring out this format were thanks to the GameCube work of Jack Anderson
// http://www.metroid2002.com/retromodding/wiki/CSNG_(File_Format)
try
{
numberInstruments = 1;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
std::vector<SngNoteInfo> sngNoteList;
unsigned long instrumentOffset = CharArrayToLong(&inputMID[0x8]);
//fprintf(outFile, "\n");
//fprintf(outFile, "Initial Something %08X", CharArrayToLong(&inputMID[0x10]));
//fprintf(outFile, "\n");
unsigned long tempoOffset = CharArrayToLong(&inputMID[0xC]);
if (tempoOffset != 0x00000000)
{
//fprintf(outFile, "Tempos\n");
int tempoIndex = 0;
while (true)
{
if (CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8)]) == 0xFFFFFFFF)
break;
else
{
unsigned long tempo = CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8) + 4]);
tempo = (unsigned long)(60000000.0 / (float)tempo);
tempoPositions.push_back(TimeAndValue(CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8)]), tempo));
//fprintf(outFile, "%08X:%08X\n", CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8)]), CharArrayToLong(&inputMID[tempoOffset + (tempoIndex * 0x8) + 4]));
tempoIndex++;
}
}
}
else
{
unsigned long tempo = CharArrayToLong(&inputMID[0x10]);
tempo = (unsigned long)(60000000.0 / (float)tempo);
tempoPositions.push_back(TimeAndValue(0x00000000, tempo));
}
//fprintf(outFile, "\n");
//fprintf(outFile, "Channels\n");
//fprintf(outFile, "-----------------------------------------\n");
unsigned long trackOffsets = CharArrayToLong(&inputMID[0x4]);
unsigned long channelOffsets = CharArrayToLong(&inputMID[0x0]);
int numberChannels = 0;
while (true)
{
if (
(CharArrayToLong(&inputMID[channelOffsets + (numberChannels * 0x4)]) == 0x00000000) && (!isRogueStyle)
)
{
numberChannels++;
if (numberChannels == 64)
break;
else
continue;
}
else if (CharArrayToLong(&inputMID[channelOffsets + (numberChannels * 0x4)]) == 0x00000000)
{
break;
}
else
{
unsigned long channelOffset = CharArrayToLong(&inputMID[channelOffsets + (numberChannels * 0x4)]);
unsigned short currentInstrument = inputMID[instrumentOffset + numberChannels];
if (currentInstrument > numberInstruments)
numberInstruments = currentInstrument + 1;
//fprintf(outFile, "Channel #%02X Offset: %08X\n", numberChannels, channelOffset);
//fprintf(outFile, "-----------------------------------------\n");
while ((inputMID[channelOffset+5] != 0x00) && ((signed short)CharArrayToShort(&inputMID[channelOffset+8]) >= 0))
{
//fprintf(outFile, "Start Tick: %08X\n", CharArrayToLong(&inputMID[channelOffset]));
//fprintf(outFile, "Continuation: %08X\n", CharArrayToLong(&inputMID[channelOffset+4]));
//fprintf(outFile, "Track Index: %04X\n", CharArrayToShort(&inputMID[channelOffset+8]));
//fprintf(outFile, "Flags?: %04X\n", CharArrayToShort(&inputMID[channelOffset+0xA]));
//fprintf(outFile, "\n");
unsigned long startTick = CharArrayToLong(&inputMID[channelOffset]);
unsigned short trackIndex = CharArrayToShort(&inputMID[channelOffset+8]);
unsigned char currentPan = 0x40;
unsigned char currentVolume = 0x7F;
signed char currentPitchBend = 0x40;
int currentTranspose = 0;
int currentEffect = 0;
unsigned long trackOffset = CharArrayToLong(&inputMID[trackOffsets + (trackIndex * 0x4)]);
//fprintf(outFile, "Track %02X Offset: %08X\n", numberTracks, trackOffset);
//fprintf(outFile, "-----------------------------------------\n");
unsigned long headerSize = CharArrayToLong(&inputMID[trackOffset]);
//fprintf(outFile, "Header Size: %08X\n", headerSize);
if (CharArrayToLong(&inputMID[trackOffset+4]) != NULL)
{
unsigned long pitchWheelOffset = CharArrayToLong(&inputMID[trackOffset+4]);
//fprintf(outFile, "Pitch Wheel Offset: %08X\n", CharArrayToLong(&inputMID[trackOffset+4]));
}
//else
//fprintf(outFile, "No Pitch Wheel\n");
if (CharArrayToLong(&inputMID[trackOffset+8]) != NULL)
{
unsigned long modWheelOffset = CharArrayToLong(&inputMID[trackOffset+8]);
//fprintf(outFile, "Mod Wheel Offset: %08X\n", CharArrayToLong(&inputMID[trackOffset+8]));
}
//else
//fprintf(outFile, "No Mod Wheel\n");
trackOffset += 4 + headerSize;
//fprintf(outFile, "\n");
unsigned long absoluteTime = startTick;
while (true)
{
unsigned long currentTempo = (unsigned long)(60000000.0 / (float)120.0);
for (int y = 0; y < tempoPositions.size(); y++)
{
if (tempoPositions[y].absoluteTime <= absoluteTime)
{
currentTempo = tempoPositions[y].value;
}
else
{
break;
}
}
if (isRogueStyle)
{
absoluteTime = startTick + CharArrayToLong(&inputMID[trackOffset]);
trackOffset += 4;
if ((CharArrayToLong(&inputMID[trackOffset]) & 0x0000FFFF) == 0x0000FFFF)
{
//fprintf(outFile, "%08X Time %08X End\n", trackOffset, absoluteTime);
trackOffset += 4;
break;
}
else if (((inputMID[trackOffset]) & 0x80) == 0x00)
{
if ((inputMID[trackOffset+2] & 0x80) == 0x00)
{
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset]);
unsigned char note = (inputMID[trackOffset+2] & 0x7F);
unsigned char velocity = (inputMID[trackOffset + 3] & 0x7F);
//fprintf(outFile, "%08X Time %08X Length %04X Note %02X Velocity %02X\n", trackOffset, absoluteTime, noteLength, note, velocity);
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = numberChannels;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentTranspose;
songNoteInfo.instrument = numberChannels;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
songNoteInfo.pan = currentPan;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = currentVolume;
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
sngNoteList.push_back(songNoteInfo);
}
else
{
unsigned short length = CharArrayToShort(&inputMID[trackOffset]);
unsigned char value = (inputMID[trackOffset+2] & 0x7F);
unsigned char command = (inputMID[trackOffset + 3] & 0x7F);
//fprintf(outFile, "%08X Time %08X Length %04X Cmd %02X Value %02X\n", trackOffset, absoluteTime, noteLength, command, value);
if (command == 7)
currentVolume = value & 0x7F;
else if (command == 10)
currentPan = value & 0x7F;
else if (command == 91)
currentEffect = value & 0x7F;
}
trackOffset += 4;
}
else if (((inputMID[trackOffset]) & 0x80) == 0x80)
{
unsigned char value = (inputMID[trackOffset] & 0x7F);
unsigned char controller = (inputMID[trackOffset + 1] & 0x7F);
//fprintf(outFile, "%08X Time %08X Controller %02X Value %02X\n", trackOffset, absoluteTime, controller, value);
trackOffset += 2;
}
}
else
{
if ((CharArrayToLong(&inputMID[trackOffset]) & 0x0000FFFF) == 0x0000FFFF)
{
//fprintf(outFile, "%08X Time %08X End\n", trackOffset, absoluteTime);
trackOffset += 4;
break;
}
absoluteTime += DecodeFactor5DeltaTimeRLE(inputMID, trackOffset);
if (((inputMID[trackOffset]) & 0x80) == 0x00)
{
unsigned char note = (inputMID[trackOffset] & 0x7F);
unsigned char velocity = (inputMID[trackOffset+1] & 0x7F);
unsigned short noteLength = CharArrayToShort(&inputMID[trackOffset+2]);
//fprintf(outFile, "%08X Time %08X Note %02X Velocity %02X Length %04X \n", trackOffset, absoluteTime, note, velocity, noteLength);
SngNoteInfo songNoteInfo;
songNoteInfo.originalTrack = numberChannels;
songNoteInfo.originalNoteUniqueId = noteUniqueId++;
songNoteInfo.startAbsoluteTime = absoluteTime;
songNoteInfo.noteNumber = note + currentTranspose;
songNoteInfo.instrument = numberChannels;
songNoteInfo.velocity = velocity;
songNoteInfo.effect = currentEffect;
songNoteInfo.tempo = currentTempo;
songNoteInfo.pan = currentPan;
songNoteInfo.pitchBend = 0x40;
songNoteInfo.volume = currentVolume;
songNoteInfo.endAbsoluteTime = songNoteInfo.startAbsoluteTime + noteLength;
sngNoteList.push_back(songNoteInfo);
trackOffset += 4;
}
else
{
unsigned char value = (inputMID[trackOffset] & 0x7F);
unsigned char controller = (inputMID[trackOffset + 1] & 0x7F);
//fprintf(outFile, "%08X Time %08X Controller %02X Value %02X\n", trackOffset, absoluteTime, controller, value);
trackOffset += 2;
}
}
}
channelOffset += 0xC;
}
//fprintf(outFile, "Start Tick: %08X\n", CharArrayToLong(&inputMID[channelOffset]));
//fprintf(outFile, "Continuation: %08X (End)\n", CharArrayToLong(&inputMID[channelOffset+4]));
//fprintf(outFile, "Track Index: %04X\n", CharArrayToShort(&inputMID[channelOffset+8]));
//fprintf(outFile, "Flags?: %04X\n", CharArrayToShort(&inputMID[channelOffset+0xA]));
//fprintf(outFile, "\n");
channelOffset += 0xC;
//fprintf(outFile, "\n");
}
numberChannels++;
}
//fprintf(outFile, "\n");
WriteSngList(sngNoteList, tempoPositions, outFileName, separateByInstrument, 0x0180, false, 24);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
void CMidiParse::KonamiToMidi(unsigned char* ROM, int romSize, byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool calculateInstrumentCountOnly, bool separateByInstrument, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long extra)
{
int numberTracks = 0x0;
/*int numberTracksCompare = 0x0;
if (!extraGameMidiInfo.naganoCompressed && !extraGameMidiInfo.zlbCompressed)
{
int trackCountOffset = extraGameMidiInfo.trackOffset + (extraGameMidiInfo.trackIncrement * extra);
numberTracksCompare = ROM[trackCountOffset];
}
else if (extraGameMidiInfo.naganoCompressed)
{
int fileSizeCompressed = extraGameMidiInfo.compressedFileEndOffset - extraGameMidiInfo.compressedFileOffset;
CNaganoDecoder decode;
unsigned char* outputDecompressed = new unsigned char[0x200000];
int expectedSize = decode.dec(&ROM[extraGameMidiInfo.compressedFileOffset], fileSizeCompressed, outputDecompressed);
int trackCountOffset = extraGameMidiInfo.trackOffset + (extraGameMidiInfo.trackIncrement * extra);
numberTracksCompare = outputDecompressed[trackCountOffset];
delete [] outputDecompressed;
}
else if (extraGameMidiInfo.zlbCompressed)
{
compress->SetGame(STUNTRACER64);
int decompressedSize = 0;
int compressedSize = -1;
byte* outputBuffer = Decompress(&ROM[extraGameMidiInfo.compressedFileOffset], romSize - extraGameMidiInfo.compressedFileOffset, decompressedSize, compressedSize);
if (outputBuffer != NULL)
{
int trackCountOffset = extraGameMidiInfo.trackOffset + (extraGameMidiInfo.trackIncrement * extra);
numberTracksCompare = outputBuffer[trackCountOffset];
delete [] outputBuffer;
}
}*/
if (numberTracks == 0x0)
{
numberTracks = CharArrayToShort(&inputMID[0]) / 2;
}
numberInstruments = 1;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
try
{
std::vector<SngNoteInfo> sngNoteList;
int trackRealLength = 0;
std::vector<int> tracksEDEE;
int loopStart = 0;
int loopEnd = 0;
int maxTrackLength = 0;
int highestTrackLength = 0;
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToShort(&inputMID[(x * 2)]);
if (trackDataPointer >= inputSize)
{
numberTracks = x;
break;
}
// Fake track
if ((x > 0) && (inputMID[trackDataPointer-1] != 0xFF))
{
break;
}
unsigned long trackEnd;
/*if (x < (numberTracks - 1))
{
trackEnd = CharArrayToShort(&inputMID[((x + 1) * 2)]);
}
else*/
{
trackEnd = inputSize;
}
int trackLength = FindHighestKonamiLengthTrack(x, inputMID, trackDataPointer, trackEnd);
if (trackLength > highestTrackLength)
highestTrackLength = trackLength;
}
/*if (numberTracks != numberTracksCompare)
{
FILE* temp = fopen("C:\\temp\\a.txt", "a");
fprintf(temp, "%s %08X Specified %02X Real %02X %s\n", &ROM[0x20], extraGameMidiInfo.compressedFileOffset, numberTracksCompare, numberTracks, outFileName);
fclose(temp);
}*/
for (int x = 0; x < numberTracks; x++)
{
unsigned long trackDataPointer = CharArrayToShort(&inputMID[(x * 2)]);
if (trackDataPointer >= inputSize)
{
numberTracks = x;
break;
}
// Fake track
if ((x > 0) && (inputMID[trackDataPointer-1] != 0xFF))
{
break;
}
unsigned long trackEnd;
/*if (x < (numberTracks - 1))
{
trackEnd = CharArrayToShort(&inputMID[((x + 1) * 2)]);
}
else*/
{
trackEnd = inputSize;
}
ParseKonamiTrack(x, numberInstruments, tempoPositions, sngNoteList, inputMID, trackDataPointer, trackEnd, noteUniqueId, writeOutLoops, loopWriteCount, extendTracksToHighest, highestTrackLength);
}
WriteSngList(sngNoteList, tempoPositions, outFileName, separateByInstrument, 0x0030, false, 24);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
void CMidiParse::SSEQToMidi(unsigned char* ROM, int romSize, byte* inputMID, int inputSize, CString outFileName, int& numberInstruments, bool calculateInstrumentCountOnly, bool separateByInstrument, bool writeOutLoops, int loopWriteCount, bool extendTracksToHighest, ExtraGameMidiInfo extraGameMidiInfo, unsigned long numberTracks)
{
numberInstruments = 1;
int noteUniqueId = 0;
std::vector<TimeAndValue> tempoPositions;
try
{
std::vector<SngNoteInfo> sngNoteList;
int trackRealLength = 0;
int loopStart = 0;
int loopEnd = 0;
int maxTrackLength = 0;
int highestTrackLength = 0;
int trackLength = FindHighestSSEQLengthTrack(inputMID, inputSize, numberTracks);
if (trackLength > highestTrackLength)
highestTrackLength = trackLength;
unsigned long division = 0x1E0;
unsigned long offsetData = 0;
for (int track = 0; track < numberTracks; track++)
{
unsigned short extraFlag = CharArrayToShort(&inputMID[offsetData + 0xE]);
unsigned long sizeTrack = CharArrayToLong(&inputMID[offsetData + 0x10]);
division = CharArrayToLong(&inputMID[offsetData + 8]);
if (extraFlag)
{
offsetData += 4;
}
offsetData += 0x14;
ParseSSEQTrack(track, numberInstruments, tempoPositions, sngNoteList, inputMID, offsetData, inputSize, noteUniqueId, writeOutLoops, loopWriteCount, extendTracksToHighest, highestTrackLength);
offsetData += sizeTrack;
}
WriteSngList(sngNoteList, tempoPositions, outFileName, separateByInstrument, division, false, 24);
}
catch (...)
{
MessageBox(NULL, "Error exporting", "Error", NULL);
}
}
BOOL CMidiParse::hiddenExec (PTSTR pCmdLine, CString currentDirectory)
{
STARTUPINFO si;
PROCESS_INFORMATION processInfo;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
ZeroMemory(&processInfo, sizeof(processInfo));
/*return */CreateProcess(0, pCmdLine, 0, 0, FALSE, 0, 0, currentDirectory, &si, &processInfo);
WaitForSingleObject(processInfo.hProcess, 20000);
DWORD exitCode;
if (GetExitCodeProcess(processInfo.hProcess, &exitCode))
{
if (exitCode == STILL_ACTIVE)
{
MessageBox(NULL, "For some reason GZip Failed", "Error", NULL);
TerminateProcess(processInfo.hProcess, exitCode);
return false;
}
}
return true;
}
BOOL CMidiParse::hiddenExec (PTSTR pCmdLine, CString currentDirectory, HANDLE out)
{
::SetCurrentDirectory(currentDirectory);
STARTUPINFO si;
PROCESS_INFORMATION processInfo;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
//si.wShowWindow = SW_HIDE;
si.hStdOutput = out;
//si.hStdInput = out;
//si.hStdError = out;
ZeroMemory(&processInfo, sizeof(processInfo));
if (currentDirectory.ReverseFind('\\') == (currentDirectory.GetLength()-1))
{
currentDirectory = currentDirectory.Mid(0, (currentDirectory.GetLength()-1));
}
/*return */CreateProcess(0, pCmdLine, 0, 0, TRUE, CREATE_DEFAULT_ERROR_MODE, 0, currentDirectory, &si, &processInfo);
WaitForSingleObject(processInfo.hProcess, 20000);
DWORD exitCode;
if (GetExitCodeProcess(processInfo.hProcess, &exitCode))
{
if (exitCode == STILL_ACTIVE)
{
MessageBox(NULL, "For some reason Zip Failed", "Error", NULL);
TerminateProcess(processInfo.hProcess, exitCode);
return false;
}
}
return true;
} | 30.648065 | 751 | 0.625065 | [
"vector"
] |
4febf52e41fcd06e18b7eb72e7f75498ad3c391b | 2,675 | cpp | C++ | awesome/c_cpp/cpp-cheat/cpp/functional.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | 3 | 2021-01-06T03:01:18.000Z | 2022-03-21T03:02:55.000Z | awesome/c_cpp/cpp-cheat/cpp/functional.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | awesome/c_cpp/cpp-cheat/cpp/functional.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | /*
# functional
Convenient simple functions.
They implement `operator()`, which allows you to pass them to
other stdlib functions that take functions as arguments.
*/
#include "common.hpp"
int overload(int i){ return i + 1; }
int overload(int i, int j){ return i + j; }
int default_(int i, int j = 1){ return i + j; }
int main() {
// # function
{
// Disambiguate overload.
// http://stackoverflow.com/questions/12500411/setting-a-stdfunction-variable-to-refer-to-the-stdsin-function
{
std::function<int(int)> f = (int(*)(int))&overload;
assert(f(1) == 2);
std::function<int(int, int)> g = (int(*)(int, int))&overload;
assert(g(1, 2) == 3);
}
// Default vaues without bind.
// TODO possible?
{
// Fails. j seems to contain trash.
//std::function<int(int)> f = (int(*)(int))&default_;
//assert(f(1) == 2);
// Lambda workaround.
std::function<int(int)> f = [](int i){ return default_(i); };
assert(f(1) == 2);
std::function<int(int, int)> g = (int(*)(int, int))&default_;
assert(g(1, 2) == 3);
}
}
/*
# bind2nd
TODO Deprecated?
Tranform a function that takes two arguments into a function that takes only the first.
Useful with stdlib functions that must take functions that take a single argument,
but you want to pass an extra parameter to that function.
*/
{
/*
std::vector<int> v = {2, 0, 1};
assert(std::find_if (
v.begin(),
v.end(),
std::bind2nd([](int i, int param){return i == param + 1;}, 1)
) == v.begin());
*/
}
// # plus
{
assert(std::plus<int>()(1, 2) == 3);
}
#if __cplusplus >= 201103L
/*
# hash
http://www.cplusplus.com/reference/functional/hash/
The stdlib furnishes overloaded hash functions for stdlib containers.
Those functions are implemented as callable classes that implement `()`.
For base types, those hashes are found under the `functional`.
For std::vectors, only `std::vector<bool>` has a template.
For other types, they are found in the same header that defines those types:
ex: hash for std::vectors is under `<vector>`.
Returns a `size_t` result.
*/
{
std::cout << "hash" << std::endl;
std::cout << " 1 = " << std::hash<int>()(1) << std::endl;
std::cout << " string abc = " << std::hash<std::string>()("abc") << std::endl;
}
#endif
}
| 27.57732 | 117 | 0.539439 | [
"vector"
] |
4fec5bd4c750975a513235c4f68ebfde10306ad4 | 938 | cpp | C++ | aws-cpp-sdk-glue/source/model/RunStatementResult.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-glue/source/model/RunStatementResult.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-glue/source/model/RunStatementResult.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/glue/model/RunStatementResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
RunStatementResult::RunStatementResult() :
m_id(0)
{
}
RunStatementResult::RunStatementResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
m_id(0)
{
*this = result;
}
RunStatementResult& RunStatementResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetInteger("Id");
}
return *this;
}
| 21.813953 | 104 | 0.735608 | [
"model"
] |
4fed5d2aed79f4668a9de34e979832814e4531d2 | 5,910 | cc | C++ | test/mnist_keras.cc | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 65 | 2020-12-07T01:15:41.000Z | 2022-03-28T01:17:33.000Z | test/mnist_keras.cc | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 1 | 2021-04-08T13:20:39.000Z | 2021-04-09T00:37:02.000Z | test/mnist_keras.cc | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 7 | 2021-01-07T08:52:39.000Z | 2022-03-08T13:04:37.000Z | #include "../include/ceras.hpp"
#include "../include/utils/range.hpp"
#include "../include/utils/better_assert.hpp"
#include "../include/utils/color.hpp"
#include "../include/keras/layer.hpp"
#include "../include/keras/model.hpp"
#include <fstream>
#include <string>
#include <vector>
#include <cstddef>
#include <cstdint>
#include <iterator>
// image: [u32, u32, u32, u32, uint8, uint8 .... ]
// label: [u32, u32, uint8, uint8 .... ]
std::string const training_image_path{ "./examples/mnist/dataset/mnist/train-images-idx3-ubyte" }; // 60000 images
std::string const training_label_path{ "./examples/mnist/dataset/mnist/train-labels-idx1-ubyte" }; // 60000 labels
std::string const testing_image_path{ "./examples/mnist/dataset/mnist/t10k-images-idx3-ubyte" }; // 10000 images
std::string const testing_label_path{ "./examples/mnist/dataset/mnist/t10k-labels-idx1-ubyte" }; // 10000 labels
std::vector<std::uint8_t> load_binary( std::string const& filename )
{
std::ifstream ifs( filename, std::ios::binary );
better_assert( ifs.good(), "Failed to load data from ", filename );
std::vector<char> buff{ ( std::istreambuf_iterator<char>( ifs ) ), ( std::istreambuf_iterator<char>() ) };
std::vector<std::uint8_t> ans( buff.size() );
std::copy( buff.begin(), buff.end(), reinterpret_cast<char*>( ans.data() ) );
std::cout << "Loaded binary from file " << color::rize( filename, "Red" ) << ", got " << color::rize( buff.size(), "Green" ) << " bytes." << std::endl;
return ans;
}
/*
std::size_t const image_offset = 16 + i * batch_size * 28 * 28;
for ( auto j : range( batch_size * 28 * 28 ) )
input_images[j] = static_cast<float>(training_images[j+image_offset]) / 127.5f - 1.0f;
*/
ceras::tensor<float> process_images( std::vector<std::uint8_t> const& images ) // [uint8, ..., uint8] --> [ dims, 28*28 ]
{
unsigned long const offset = 16;
unsigned long const size = images.size()-offset;
unsigned long const samples = size / (28*28);
auto zeros = ceras::zeros<float>( {samples, 28*28} );
ceras::for_each( zeros.begin(), zeros.end(), images.begin()+offset, []( float& x, std::uint8_t v ) { x = static_cast<float>(v) / 127.5f - 1.0f; } );
return zeros;
}
ceras::tensor<float> process_labels( std::vector<std::uint8_t> const& labels ) // [uint8, ..., uint8] --> [ dims, 10 ]
{
unsigned long const offset = 8;
unsigned long const size = labels.size()-offset;
unsigned long const samples = size;
auto zeros = ceras::zeros<float>( {samples, 10} );
auto _zeros = ceras::view_2d{zeros, samples, 10};
for ( auto idx : ceras::range( samples ) )
{
unsigned long const label = static_cast<unsigned long>(labels[idx+offset]);
_zeros[idx][label] = 1.0f;
}
return zeros;
}
/*
using namespace Keras;
auto input = Input( {28*28,} );
auto layer_1 = Dense<512, activation<"relu">, use_bias<false>>{}( input );
auto layer_2 = Dense<128, activation<"leaky_relu">>{}( layer_1 );
auto layer_3 = Dense<32, activation<"relu">>{}( layer_2 );
auto layer_4 = Dense<10>{}( layer_3 );
auto model = Model{ input, layer_4 };
//auto compiled_model = model.compile<loss<"crossentropy">, optimizer<"sgd", 32, "0.08">>();
auto compiled_model = model.compile<optimizer<"sgd", 32, "0.08">, loss<"crossentropy">>();
auto fake_inputs = ceras::random<float>( {32, 28*28} );
auto fake_outputs = ceras::ones<float>( {32, 10} );
auto error = compiled_model.train_on_batch( fake_inputs, fake_outputs );
std::cout << "Got error :\n" << error << "\n";
*/
int main()
{
ceras::random_generator.seed( 42 );
// prepare dataset
std::vector<std::uint8_t> training_images = load_binary( training_image_path ); // [u32, u32, u32, u32, uint8, uint8, ... ]
auto training_input = process_images( training_images );
std::vector<std::uint8_t> training_labels = load_binary( training_label_path ); // [u32, u32, uint8, uint8, ... ]
auto training_output = process_labels( training_labels );
std::vector<std::uint8_t> testing_images = load_binary( testing_image_path );
auto testing_input = process_images( training_images );
std::vector<std::uint8_t> testing_labels = load_binary( testing_label_path );
auto testing_output = process_labels( training_labels );
// define model
using namespace Keras;
auto input = Input( {28*28} );
auto l_1 = Dense<256, activation<"relu">, use_bias<false>>{}( input );
auto l_2 = Dense<128, activation<"relu">>{}( l_1 );
auto l_3 = Dense<10, activation<"relu">>{}( l_2 );
auto model = Model{ input, l_3 };
// training
//auto compiled_model = model.compile<optimizer<"sgd", 10, "0.1">, loss<"crossentropy">>();
auto compiled_model = model.compile<optimizer<"sgd", 1000, "0.1">, loss<"crossentropy">>();
unsigned long const batch_size = 1000;
unsigned long const epochs = 1;
auto terrors = compiled_model.fit( training_input, training_output, batch_size, epochs);
std::cout << "\nTraining errors:\n";
for ( auto error : terrors ) std::cout << error << " ";
std::cout << "\n";
// prediction
auto prediction = compiled_model.predict( testing_input );
unsigned long const test_cases = *((prediction.shape()).begin());
unsigned long errors = 0;
for ( auto idx : ceras::range( test_cases ) )
{
unsigned long predicted_number = std::max_element( prediction.begin()+10*idx, prediction.begin()+10*idx+10 ) - prediction.begin() - 10*idx;
unsigned long ground_truth_number = std::max_element( testing_output.begin()+10*idx, testing_output.begin()+10*idx+10 ) - testing_output.begin() - 10*idx;
errors = (predicted_number == ground_truth_number) ? errors : errors + 1;
}
float const err = 1.0 * errors / test_cases;
std::cout << "Prediction error on the testing set is " << err << std::endl;
return 0;
}
| 43.455882 | 162 | 0.654992 | [
"shape",
"vector",
"model"
] |
4fedb7a943993a4db2565e658967c465d7fb2cbd | 1,144 | cpp | C++ | FoolsEngine/src/FoolsEngine/Events/MainEventDispacher.cpp | pawel-kaleta/FoolsEngine | a2ebd8cfd26947cbea07bcad29fde69683321c86 | [
"Apache-2.0"
] | null | null | null | FoolsEngine/src/FoolsEngine/Events/MainEventDispacher.cpp | pawel-kaleta/FoolsEngine | a2ebd8cfd26947cbea07bcad29fde69683321c86 | [
"Apache-2.0"
] | null | null | null | FoolsEngine/src/FoolsEngine/Events/MainEventDispacher.cpp | pawel-kaleta/FoolsEngine | a2ebd8cfd26947cbea07bcad29fde69683321c86 | [
"Apache-2.0"
] | null | null | null | #include "FE_pch.h"
#include "FoolsEngine\Events\MainEventDispacher.h"
namespace fe
{
void MainEventDispacher::ReceiveEvent(std::shared_ptr<Event> event)
{
FE_PROFILER_FUNC();
FE_LOG_CORE_TRACE("NEW EVENT: {0}", event->ToString());
m_eventsQueue.push_back(event);
FE_LOG_CORE_TRACE("SAVED EVENT: {0}", m_eventsQueue.back()->ToString());
}
void MainEventDispacher::DispachEvents(LayerStack& layerStack)
{
FE_PROFILER_FUNC();
if (m_eventsQueue.empty())
return;
for (auto event_it = m_eventsQueue.begin(); event_it != m_eventsQueue.end(); event_it++) // auto = std::vector< std::shared_ptr< Event > >::iterator
{
for (auto layer_it = layerStack.begin(); layer_it != layerStack.end(); layer_it++) // auto = std::vector< std::shared_ptr< Layer > >::iterator
{
(*layer_it)->OnEvent(*event_it);
if ((*event_it)->Handled)
break;
}
if (!((*event_it)->Handled))
{
//FE_LOG_CORE_WARN("Unhandled event: {0}", (*event_it)->ToString());
}
}
m_eventsQueue.clear();
FE_CORE_ASSERT(m_eventsQueue.size() == 0, "Events buffer not cleared!");
FE_LOG_CORE_DEBUG("Events dispached!");
}
}
| 26 | 150 | 0.674825 | [
"vector"
] |
4fee8f1ce28f0c3cdd3460917155556b9e73a4ee | 133,212 | cpp | C++ | third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "V8TestInterface.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/PrivateScriptRunner.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/V8AbstractEventListener.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8EventListenerList.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8Iterator.h"
#include "bindings/core/v8/V8Node.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8TestInterface.h"
#include "bindings/core/v8/V8TestInterface2.h"
#include "bindings/core/v8/V8TestInterfaceEmpty.h"
#include "bindings/core/v8/V8Window.h"
#include "bindings/tests/idls/core/TestImplements2.h"
#include "bindings/tests/idls/core/TestImplements3Implementation.h"
#include "bindings/tests/idls/core/TestInterfacePartial.h"
#include "bindings/tests/idls/core/TestInterfacePartial2Implementation.h"
#include "core/dom/Document.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/UseCounter.h"
#include "core/inspector/ConsoleMessage.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/ScriptForbiddenScope.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
WrapperTypeInfo V8TestInterface::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestInterface::domTemplate, V8TestInterface::trace, V8TestInterface::traceWrappers, V8TestInterface::toActiveScriptWrappable, V8TestInterface::visitDOMWrapper, V8TestInterface::preparePrototypeAndInterfaceObject, nullptr, "TestInterface", &V8TestInterfaceEmpty::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Dependent };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestInterfaceImplementation.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TestInterfaceImplementation::s_wrapperTypeInfo = V8TestInterface::wrapperTypeInfo;
namespace TestInterfaceImplementationV8Internal {
static void (*voidMethodPartialOverloadMethodForPartialInterface)(const v8::FunctionCallbackInfo<v8::Value>&) = 0;
static void (*staticVoidMethodPartialOverloadMethodForPartialInterface)(const v8::FunctionCallbackInfo<v8::Value>&) = 0;
static void (*promiseMethodPartialOverloadMethodForPartialInterface)(const v8::FunctionCallbackInfo<v8::Value>&) = 0;
static void (*staticPromiseMethodPartialOverloadMethodForPartialInterface)(const v8::FunctionCallbackInfo<v8::Value>&) = 0;
static void (*partial2VoidMethodMethodForPartialInterface)(const v8::FunctionCallbackInfo<v8::Value>&) = 0;
static void (*partial2StaticVoidMethodMethodForPartialInterface)(const v8::FunctionCallbackInfo<v8::Value>&) = 0;
static void testInterfaceAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->testInterfaceAttribute()), impl);
}
static void testInterfaceAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::V8TestInterface_TestInterfaceAttribute_AttributeGetter);
TestInterfaceImplementationV8Internal::testInterfaceAttributeAttributeGetter(info);
}
static void testInterfaceAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "testInterfaceAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
TestInterfaceImplementation* cppValue = V8TestInterface::toImplWithTypeCheck(info.GetIsolate(), v8Value);
if (!cppValue) {
exceptionState.throwTypeError("The provided value is not of type 'TestInterface'.");
exceptionState.throwIfNeeded();
return;
}
impl->setTestInterfaceAttribute(cppValue);
}
static void testInterfaceAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::V8TestInterface_TestInterfaceAttribute_AttributeSetter);
TestInterfaceImplementationV8Internal::testInterfaceAttributeAttributeSetter(v8Value, info);
}
static void doubleAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValue(info, impl->doubleAttribute());
}
static void doubleAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::doubleAttributeAttributeGetter(info);
}
static void doubleAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "doubleAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
double cppValue = toRestrictedDouble(info.GetIsolate(), v8Value, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setDoubleAttribute(cppValue);
}
static void doubleAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::doubleAttributeAttributeSetter(v8Value, info);
}
static void floatAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValue(info, impl->floatAttribute());
}
static void floatAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::floatAttributeAttributeGetter(info);
}
static void floatAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "floatAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
float cppValue = toRestrictedFloat(info.GetIsolate(), v8Value, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setFloatAttribute(cppValue);
}
static void floatAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::floatAttributeAttributeSetter(v8Value, info);
}
static void unrestrictedDoubleAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValue(info, impl->unrestrictedDoubleAttribute());
}
static void unrestrictedDoubleAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::unrestrictedDoubleAttributeAttributeGetter(info);
}
static void unrestrictedDoubleAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "unrestrictedDoubleAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
double cppValue = toDouble(info.GetIsolate(), v8Value, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setUnrestrictedDoubleAttribute(cppValue);
}
static void unrestrictedDoubleAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::unrestrictedDoubleAttributeAttributeSetter(v8Value, info);
}
static void unrestrictedFloatAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValue(info, impl->unrestrictedFloatAttribute());
}
static void unrestrictedFloatAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::unrestrictedFloatAttributeAttributeGetter(info);
}
static void unrestrictedFloatAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "unrestrictedFloatAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
float cppValue = toFloat(info.GetIsolate(), v8Value, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setUnrestrictedFloatAttribute(cppValue);
}
static void unrestrictedFloatAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::unrestrictedFloatAttributeAttributeSetter(v8Value, info);
}
static void testEnumAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueString(info, impl->testEnumAttribute(), info.GetIsolate());
}
static void testEnumAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::testEnumAttributeAttributeGetter(info);
}
static void testEnumAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "testEnumAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
const char* validValues[] = {
"",
"EnumValue1",
"EnumValue2",
"EnumValue3",
};
if (!isValidEnum(cppValue, validValues, WTF_ARRAY_LENGTH(validValues), "TestEnum", exceptionState)) {
currentExecutionContext(info.GetIsolate())->addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, exceptionState.message()));
return;
}
impl->setTestEnumAttribute(cppValue);
}
static void testEnumAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::testEnumAttributeAttributeSetter(v8Value, info);
}
static void stringOrDoubleAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
StringOrDouble result;
impl->stringOrDoubleAttribute(result);
v8SetReturnValue(info, result);
}
static void stringOrDoubleAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::stringOrDoubleAttributeAttributeGetter(info);
}
static void stringOrDoubleAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "stringOrDoubleAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
StringOrDouble cppValue;
V8StringOrDouble::toImpl(info.GetIsolate(), v8Value, cppValue, UnionTypeConversionMode::NotNullable, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setStringOrDoubleAttribute(cppValue);
}
static void stringOrDoubleAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::stringOrDoubleAttributeAttributeSetter(v8Value, info);
}
static void conditionalLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueInt(info, impl->conditionalLongAttribute());
}
static void conditionalLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeGetter(info);
}
static void conditionalLongAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "conditionalLongAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setConditionalLongAttribute(cppValue);
}
static void conditionalLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeSetter(v8Value, info);
}
static void conditionalReadOnlyLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueInt(info, impl->conditionalReadOnlyLongAttribute());
}
static void conditionalReadOnlyLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::conditionalReadOnlyLongAttributeAttributeGetter(info);
}
static void staticStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueString(info, TestInterfaceImplementation::staticStringAttribute(), info.GetIsolate());
}
static void staticStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticStringAttributeAttributeGetter(info);
}
static void staticStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
TestInterfaceImplementation::setStaticStringAttribute(cppValue);
}
static void staticStringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::staticStringAttributeAttributeSetter(v8Value, info);
}
static void staticReturnDOMWrapperAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValue(info, WTF::getPtr(TestInterfaceImplementation::staticReturnDOMWrapperAttribute()), info.GetIsolate()->GetCurrentContext()->Global());
}
static void staticReturnDOMWrapperAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticReturnDOMWrapperAttributeAttributeGetter(info);
}
static void staticReturnDOMWrapperAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "staticReturnDOMWrapperAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* cppValue = V8TestInterface::toImplWithTypeCheck(info.GetIsolate(), v8Value);
if (!cppValue) {
exceptionState.throwTypeError("The provided value is not of type 'TestInterface'.");
exceptionState.throwIfNeeded();
return;
}
TestInterfaceImplementation::setStaticReturnDOMWrapperAttribute(cppValue);
}
static void staticReturnDOMWrapperAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::staticReturnDOMWrapperAttributeAttributeSetter(v8Value, info);
}
static void staticReadOnlyStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueString(info, TestInterfaceImplementation::staticReadOnlyStringAttribute(), info.GetIsolate());
}
static void staticReadOnlyStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticReadOnlyStringAttributeAttributeGetter(info);
}
static void staticReadOnlyReturnDOMWrapperAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* cppValue(WTF::getPtr(TestInterfaceImplementation::staticReadOnlyReturnDOMWrapperAttribute()));
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue, holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(ScriptState::current(info.GetIsolate()), holder, v8AtomicString(info.GetIsolate(), "staticReadOnlyReturnDOMWrapperAttribute"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void staticReadOnlyReturnDOMWrapperAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticReadOnlyReturnDOMWrapperAttributeAttributeGetter(info);
}
static void staticConditionalReadOnlyLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueInt(info, TestInterfaceImplementation::staticConditionalReadOnlyLongAttribute());
}
static void staticConditionalReadOnlyLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticConditionalReadOnlyLongAttributeAttributeGetter(info);
}
static void legacyInterfaceTypeCheckingAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->legacyInterfaceTypeCheckingAttribute()), impl);
}
static void legacyInterfaceTypeCheckingAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::legacyInterfaceTypeCheckingAttributeAttributeGetter(info);
}
static void legacyInterfaceTypeCheckingAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
TestInterfaceEmpty* cppValue = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), v8Value);
impl->setLegacyInterfaceTypeCheckingAttribute(cppValue);
}
static void legacyInterfaceTypeCheckingAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::legacyInterfaceTypeCheckingAttributeAttributeSetter(v8Value, info);
}
static void alwaysExposedAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueInt(info, impl->alwaysExposedAttribute());
}
static void alwaysExposedAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::alwaysExposedAttributeAttributeGetter(info);
}
static void alwaysExposedAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "alwaysExposedAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setAlwaysExposedAttribute(cppValue);
}
static void alwaysExposedAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::alwaysExposedAttributeAttributeSetter(v8Value, info);
}
static void workerExposedAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueInt(info, impl->workerExposedAttribute());
}
static void workerExposedAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::workerExposedAttributeAttributeGetter(info);
}
static void workerExposedAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "workerExposedAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setWorkerExposedAttribute(cppValue);
}
static void workerExposedAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::workerExposedAttributeAttributeSetter(v8Value, info);
}
static void windowExposedAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueInt(info, impl->windowExposedAttribute());
}
static void windowExposedAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::windowExposedAttributeAttributeGetter(info);
}
static void windowExposedAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "windowExposedAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setWindowExposedAttribute(cppValue);
}
static void windowExposedAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::windowExposedAttributeAttributeSetter(v8Value, info);
}
static void lenientThisAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (!V8TestInterface::hasInstance(info.Holder(), info.GetIsolate()))
return; // Return silently because of [LenientThis].
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValue(info, impl->lenientThisAttribute().v8Value());
}
static void lenientThisAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::lenientThisAttributeAttributeGetter(info);
}
static void lenientThisAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (!V8TestInterface::hasInstance(info.Holder(), info.GetIsolate()))
return; // Return silently because of [LenientThis].
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
ScriptValue cppValue = ScriptValue(ScriptState::current(info.GetIsolate()), v8Value);
impl->setLenientThisAttribute(cppValue);
}
static void lenientThisAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::lenientThisAttributeAttributeSetter(v8Value, info);
}
static void implementsStaticReadOnlyLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueInt(info, TestInterfaceImplementation::implementsStaticReadOnlyLongAttribute());
}
static void implementsStaticReadOnlyLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsStaticReadOnlyLongAttributeAttributeGetter(info);
}
static void implementsStaticStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueString(info, TestInterfaceImplementation::implementsStaticStringAttribute(), info.GetIsolate());
}
static void implementsStaticStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsStaticStringAttributeAttributeGetter(info);
}
static void implementsStaticStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
TestInterfaceImplementation::setImplementsStaticStringAttribute(cppValue);
}
static void implementsStaticStringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implementsStaticStringAttributeAttributeSetter(v8Value, info);
}
static void implementsReadonlyStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueString(info, impl->implementsReadonlyStringAttribute(), info.GetIsolate());
}
static void implementsReadonlyStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsReadonlyStringAttributeAttributeGetter(info);
}
static void implementsStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueString(info, impl->implementsStringAttribute(), info.GetIsolate());
}
static void implementsStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsStringAttributeAttributeGetter(info);
}
static void implementsStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
impl->setImplementsStringAttribute(cppValue);
}
static void implementsStringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implementsStringAttributeAttributeSetter(v8Value, info);
}
static void implementsNodeAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->implementsNodeAttribute()), impl);
}
static void implementsNodeAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsNodeAttributeAttributeGetter(info);
}
static void implementsNodeAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "implementsNodeAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
Node* cppValue = V8Node::toImplWithTypeCheck(info.GetIsolate(), v8Value);
if (!cppValue) {
exceptionState.throwTypeError("The provided value is not of type 'Node'.");
exceptionState.throwIfNeeded();
return;
}
impl->setImplementsNodeAttribute(cppValue);
}
static void implementsNodeAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implementsNodeAttributeAttributeSetter(v8Value, info);
}
static void implementsEventHandlerAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
EventListener* cppValue(WTF::getPtr(impl->implementsEventHandlerAttribute()));
v8SetReturnValue(info, cppValue ? v8::Local<v8::Value>(V8AbstractEventListener::cast(cppValue)->getListenerObject(impl->getExecutionContext())) : v8::Local<v8::Value>(v8::Null(info.GetIsolate())));
}
static void implementsEventHandlerAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsEventHandlerAttributeAttributeGetter(info);
}
static void implementsEventHandlerAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
moveEventListenerToNewWrapper(info.GetIsolate(), holder, impl->implementsEventHandlerAttribute(), v8Value, V8TestInterface::eventListenerCacheIndex);
impl->setImplementsEventHandlerAttribute(V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), v8Value, true, ListenerFindOrCreate));
}
static void implementsEventHandlerAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implementsEventHandlerAttributeAttributeSetter(v8Value, info);
}
static void implementsRuntimeEnabledNodeAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->implementsRuntimeEnabledNodeAttribute()), impl);
}
static void implementsRuntimeEnabledNodeAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeGetter(info);
}
static void implementsRuntimeEnabledNodeAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "implementsRuntimeEnabledNodeAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
Node* cppValue = V8Node::toImplWithTypeCheck(info.GetIsolate(), v8Value);
if (!cppValue) {
exceptionState.throwTypeError("The provided value is not of type 'Node'.");
exceptionState.throwIfNeeded();
return;
}
impl->setImplementsRuntimeEnabledNodeAttribute(cppValue);
}
static void implementsRuntimeEnabledNodeAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeSetter(v8Value, info);
}
static void implements2StaticStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueString(info, TestImplements2::implements2StaticStringAttribute(), info.GetIsolate());
}
static void implements2StaticStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeGetter(info);
}
static void implements2StaticStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
TestImplements2::setImplements2StaticStringAttribute(cppValue);
}
static void implements2StaticStringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeSetter(v8Value, info);
}
static void implements2StringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueString(info, TestImplements2::implements2StringAttribute(*impl), info.GetIsolate());
}
static void implements2StringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeGetter(info);
}
static void implements2StringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
TestImplements2::setImplements2StringAttribute(*impl, cppValue);
}
static void implements2StringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeSetter(v8Value, info);
}
static void implements3StringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueString(info, TestImplements3Implementation::implements3StringAttribute(*impl), info.GetIsolate());
}
static void implements3StringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implements3StringAttributeAttributeGetter(info);
}
static void implements3StringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
TestImplements3Implementation::setImplements3StringAttribute(*impl, cppValue);
}
static void implements3StringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implements3StringAttributeAttributeSetter(v8Value, info);
}
static void implements3StaticStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueString(info, TestImplements3Implementation::implements3StaticStringAttribute(), info.GetIsolate());
}
static void implements3StaticStringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implements3StaticStringAttributeAttributeGetter(info);
}
static void implements3StaticStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
TestImplements3Implementation::setImplements3StaticStringAttribute(cppValue);
}
static void implements3StaticStringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::implements3StaticStringAttributeAttributeSetter(v8Value, info);
}
static void partialLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueInt(info, TestInterfacePartial::partialLongAttribute(*impl));
}
static void partialLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialLongAttributeAttributeGetter(info);
}
static void partialLongAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "partialLongAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
TestInterfacePartial::setPartialLongAttribute(*impl, cppValue);
}
static void partialLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::partialLongAttributeAttributeSetter(v8Value, info);
}
static void partialStaticLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueInt(info, TestInterfacePartial::partialStaticLongAttribute());
}
static void partialStaticLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeGetter(info);
}
static void partialStaticLongAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "partialStaticLongAttribute", "TestInterface", holder, info.GetIsolate());
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
TestInterfacePartial::setPartialStaticLongAttribute(cppValue);
}
static void partialStaticLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeSetter(v8Value, info);
}
static void partialCallWithExecutionContextLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
v8SetReturnValueInt(info, TestInterfacePartial::partialCallWithExecutionContextLongAttribute(executionContext, *impl));
}
static void partialCallWithExecutionContextLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeGetter(info);
}
static void partialCallWithExecutionContextLongAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "partialCallWithExecutionContextLongAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
TestInterfacePartial::setPartialCallWithExecutionContextLongAttribute(executionContext, *impl, cppValue);
}
static void partialCallWithExecutionContextLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeSetter(v8Value, info);
}
static void partialPartialEnumTypeAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueString(info, TestInterfacePartial::partialPartialEnumTypeAttribute(*impl), info.GetIsolate());
}
static void partialPartialEnumTypeAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeGetter(info);
}
static void partialPartialEnumTypeAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "partialPartialEnumTypeAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
const char* validValues[] = {
"foo",
"bar",
};
if (!isValidEnum(cppValue, validValues, WTF_ARRAY_LENGTH(validValues), "PartialEnumType", exceptionState)) {
currentExecutionContext(info.GetIsolate())->addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, exceptionState.message()));
return;
}
TestInterfacePartial::setPartialPartialEnumTypeAttribute(*impl, cppValue);
}
static void partialPartialEnumTypeAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeSetter(v8Value, info);
}
static void stringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
String result;
if (!V8TestInterface::PrivateScript::stringAttributeAttributeGetter(toLocalFrame(toFrameIfNotDetached(info.GetIsolate()->GetCurrentContext())), impl, &result))
return;
v8SetReturnValueString(info, result, info.GetIsolate());
}
static void stringAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::stringAttributeAttributeGetter(info);
}
static void stringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
V8TestInterface::PrivateScript::stringAttributeAttributeSetter(toLocalFrame(toFrameIfNotDetached(info.GetIsolate()->GetCurrentContext())), impl, cppValue);
}
static void stringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::stringAttributeAttributeSetter(v8Value, info);
}
static void partial2LongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
v8SetReturnValueInt(info, TestInterfacePartial2Implementation::partial2LongAttribute(*impl));
}
static void partial2LongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partial2LongAttributeAttributeGetter(info);
}
static void partial2LongAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "partial2LongAttribute", "TestInterface", holder, info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(holder);
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
TestInterfacePartial2Implementation::setPartial2LongAttribute(*impl, cppValue);
}
static void partial2LongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::partial2LongAttributeAttributeSetter(v8Value, info);
}
static void partial2StaticLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValueInt(info, TestInterfacePartial2Implementation::partial2StaticLongAttribute());
}
static void partial2StaticLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partial2StaticLongAttributeAttributeGetter(info);
}
static void partial2StaticLongAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "partial2StaticLongAttribute", "TestInterface", holder, info.GetIsolate());
int cppValue = toInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
TestInterfacePartial2Implementation::setPartial2StaticLongAttribute(cppValue);
}
static void partial2StaticLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TestInterfaceImplementationV8Internal::partial2StaticLongAttributeAttributeSetter(v8Value, info);
}
static void voidMethodTestInterfaceEmptyArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "voidMethodTestInterfaceEmptyArg", "TestInterface", 1, info.Length()), info.GetIsolate());
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
TestInterfaceEmpty* testInterfaceEmptyArg;
{
testInterfaceEmptyArg = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!testInterfaceEmptyArg) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("voidMethodTestInterfaceEmptyArg", "TestInterface", "parameter 1 is not of type 'TestInterfaceEmpty'."));
return;
}
}
impl->voidMethodTestInterfaceEmptyArg(testInterfaceEmptyArg);
}
static void voidMethodTestInterfaceEmptyArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::voidMethodTestInterfaceEmptyArgMethod(info);
}
static void voidMethodDoubleArgFloatArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodDoubleArgFloatArg", "TestInterface", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
setMinimumArityTypeError(exceptionState, 2, info.Length());
exceptionState.throwIfNeeded();
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
double doubleArg;
float floatArg;
{
doubleArg = toRestrictedDouble(info.GetIsolate(), info[0], exceptionState);
if (exceptionState.throwIfNeeded())
return;
floatArg = toRestrictedFloat(info.GetIsolate(), info[1], exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->voidMethodDoubleArgFloatArg(doubleArg, floatArg);
}
static void voidMethodDoubleArgFloatArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::voidMethodDoubleArgFloatArgMethod(info);
}
static void voidMethodUnrestrictedDoubleArgUnrestrictedFloatArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodUnrestrictedDoubleArgUnrestrictedFloatArg", "TestInterface", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
setMinimumArityTypeError(exceptionState, 2, info.Length());
exceptionState.throwIfNeeded();
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
double unrestrictedDoubleArg;
float unrestrictedFloatArg;
{
unrestrictedDoubleArg = toDouble(info.GetIsolate(), info[0], exceptionState);
if (exceptionState.throwIfNeeded())
return;
unrestrictedFloatArg = toFloat(info.GetIsolate(), info[1], exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->voidMethodUnrestrictedDoubleArgUnrestrictedFloatArg(unrestrictedDoubleArg, unrestrictedFloatArg);
}
static void voidMethodUnrestrictedDoubleArgUnrestrictedFloatArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::voidMethodUnrestrictedDoubleArgUnrestrictedFloatArgMethod(info);
}
static void voidMethodTestEnumArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodTestEnumArg", "TestInterface", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
V8StringResource<> testEnumArg;
{
testEnumArg = info[0];
if (!testEnumArg.prepare())
return;
const char* validValues[] = {
"",
"EnumValue1",
"EnumValue2",
"EnumValue3",
};
if (!isValidEnum(testEnumArg, validValues, WTF_ARRAY_LENGTH(validValues), "TestEnum", exceptionState)) {
exceptionState.throwIfNeeded();
return;
}
}
impl->voidMethodTestEnumArg(testEnumArg);
}
static void voidMethodTestEnumArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::voidMethodTestEnumArgMethod(info);
}
static void voidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->voidMethod();
}
static void voidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::voidMethodMethod(info);
}
static void voidMethodMethodForMainWorld(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->voidMethod();
}
static void voidMethodMethodCallbackForMainWorld(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::voidMethodMethodForMainWorld(info);
}
static void alwaysExposedMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->alwaysExposedMethod();
}
static void alwaysExposedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::alwaysExposedMethodMethod(info);
}
static void workerExposedMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->workerExposedMethod();
}
static void workerExposedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::workerExposedMethodMethod(info);
}
static void windowExposedMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->windowExposedMethod();
}
static void windowExposedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::windowExposedMethodMethod(info);
}
static void alwaysExposedStaticMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation::alwaysExposedStaticMethod();
}
static void alwaysExposedStaticMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::alwaysExposedStaticMethodMethod(info);
}
static void workerExposedStaticMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation::workerExposedStaticMethod();
}
static void workerExposedStaticMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::workerExposedStaticMethodMethod(info);
}
static void windowExposedStaticMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation::windowExposedStaticMethod();
}
static void windowExposedStaticMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::windowExposedStaticMethodMethod(info);
}
static void staticReturnDOMWrapperMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValue(info, TestInterfaceImplementation::staticReturnDOMWrapperMethod(), info.GetIsolate()->GetCurrentContext()->Global());
}
static void staticReturnDOMWrapperMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticReturnDOMWrapperMethodMethod(info);
}
static void methodWithExposedAndRuntimeEnabledFlagMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->methodWithExposedAndRuntimeEnabledFlag();
}
static void methodWithExposedAndRuntimeEnabledFlagMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::methodWithExposedAndRuntimeEnabledFlagMethod(info);
}
static void overloadMethodWithExposedAndRuntimeEnabledFlag1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "overloadMethodWithExposedAndRuntimeEnabledFlag", "TestInterface", info.Holder(), info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
int longArg;
{
longArg = toInt32(info.GetIsolate(), info[0], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->overloadMethodWithExposedAndRuntimeEnabledFlag(longArg);
}
static void overloadMethodWithExposedAndRuntimeEnabledFlag2Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
V8StringResource<> string;
{
string = info[0];
if (!string.prepare())
return;
}
impl->overloadMethodWithExposedAndRuntimeEnabledFlag(string);
}
static void overloadMethodWithExposedAndRuntimeEnabledFlag3Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
DOMWindow* window;
{
window = toDOMWindow(info.GetIsolate(), info[0]);
if (!window) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("overloadMethodWithExposedAndRuntimeEnabledFlag", "TestInterface", "parameter 1 is not of type 'Window'."));
return;
}
}
impl->overloadMethodWithExposedAndRuntimeEnabledFlag(window);
}
static void overloadMethodWithExposedAndRuntimeEnabledFlagMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "overloadMethodWithExposedAndRuntimeEnabledFlag", "TestInterface", info.Holder(), info.GetIsolate());
switch (std::min(1, info.Length())) {
case 1:
if (RuntimeEnabledFeatures::featureName2Enabled()) {
if (V8Window::hasInstance(info[0], info.GetIsolate())) {
overloadMethodWithExposedAndRuntimeEnabledFlag3Method(info);
return;
}
}
if (info[0]->IsNumber()) {
overloadMethodWithExposedAndRuntimeEnabledFlag1Method(info);
return;
}
if (RuntimeEnabledFeatures::featureNameEnabled()) {
if (true) {
overloadMethodWithExposedAndRuntimeEnabledFlag2Method(info);
return;
}
}
if (true) {
overloadMethodWithExposedAndRuntimeEnabledFlag1Method(info);
return;
}
break;
default:
break;
}
if (info.Length() < 1) {
exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, info.Length()));
exceptionState.throwIfNeeded();
return;
}
exceptionState.throwTypeError("No function was found that matched the signature provided.");
exceptionState.throwIfNeeded();
return;
}
static void overloadMethodWithExposedAndRuntimeEnabledFlagMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::overloadMethodWithExposedAndRuntimeEnabledFlagMethod(info);
}
static void methodWithExposedHavingRuntimeEnabldFlagMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->methodWithExposedHavingRuntimeEnabldFlag();
}
static void methodWithExposedHavingRuntimeEnabldFlagMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::methodWithExposedHavingRuntimeEnabldFlagMethod(info);
}
static void windowAndServiceWorkerExposedMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->windowAndServiceWorkerExposedMethod();
}
static void windowAndServiceWorkerExposedMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::windowAndServiceWorkerExposedMethodMethod(info);
}
static void voidMethodPartialOverload1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->voidMethodPartialOverload();
}
static void voidMethodPartialOverload2Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodPartialOverload", "TestInterface", info.Holder(), info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
double doubleArg;
{
doubleArg = toRestrictedDouble(info.GetIsolate(), info[0], exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->voidMethodPartialOverload(doubleArg);
}
static void staticVoidMethodPartialOverload1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation::staticVoidMethodPartialOverload();
}
static void promiseMethodPartialOverload1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
v8SetReturnValue(info, impl->promiseMethodPartialOverload().v8Value());
}
static void promiseMethodPartialOverload2Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
DOMWindow* window;
{
window = toDOMWindow(info.GetIsolate(), info[0]);
if (!window) {
v8SetReturnValue(info, ScriptPromise::rejectRaw(ScriptState::current(info.GetIsolate()), V8ThrowException::createTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("promiseMethodPartialOverload", "TestInterface", "parameter 1 is not of type 'Window'."))));
return;
}
}
v8SetReturnValue(info, impl->promiseMethodPartialOverload(window).v8Value());
}
static void staticPromiseMethodPartialOverload1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8SetReturnValue(info, TestInterfaceImplementation::staticPromiseMethodPartialOverload().v8Value());
}
static void legacyInterfaceTypeCheckingMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "legacyInterfaceTypeCheckingMethod", "TestInterface", 1, info.Length()), info.GetIsolate());
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
TestInterfaceEmpty* testInterfaceEmptyArg;
{
testInterfaceEmptyArg = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), info[0]);
}
impl->legacyInterfaceTypeCheckingMethod(testInterfaceEmptyArg);
}
static void legacyInterfaceTypeCheckingMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::legacyInterfaceTypeCheckingMethodMethod(info);
}
static void implementsVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
impl->implementsVoidMethod();
}
static void implementsVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsVoidMethodMethod(info);
}
static void implementsComplexMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "implementsComplexMethod", "TestInterface", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
setMinimumArityTypeError(exceptionState, 2, info.Length());
exceptionState.throwIfNeeded();
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
V8StringResource<> strArg;
TestInterfaceEmpty* testInterfaceEmptyArg;
{
strArg = info[0];
if (!strArg.prepare())
return;
testInterfaceEmptyArg = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), info[1]);
if (!testInterfaceEmptyArg) {
exceptionState.throwTypeError("parameter 2 is not of type 'TestInterfaceEmpty'.");
exceptionState.throwIfNeeded();
return;
}
}
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
TestInterfaceEmpty* result = impl->implementsComplexMethod(executionContext, strArg, testInterfaceEmptyArg, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValue(info, result);
}
static void implementsComplexMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsComplexMethodMethod(info);
}
static void implementsCustomVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
V8TestInterface::implementsCustomVoidMethodMethodCustom(info);
}
static void implementsStaticVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation::implementsStaticVoidMethod();
}
static void implementsStaticVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implementsStaticVoidMethodMethod(info);
}
static void implements2VoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
TestImplements2::implements2VoidMethod(*impl);
}
static void implements2VoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implements2VoidMethodMethod(info);
}
static void implements3VoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
TestImplements3Implementation::implements3VoidMethod(*impl);
}
static void implements3VoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implements3VoidMethodMethod(info);
}
static void implements3StaticVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestImplements3Implementation::implements3StaticVoidMethod();
}
static void implements3StaticVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::implements3StaticVoidMethodMethod(info);
}
static void partialVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
TestInterfacePartial::partialVoidMethod(*impl);
}
static void partialVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialVoidMethodMethod(info);
}
static void partialStaticVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfacePartial::partialStaticVoidMethod();
}
static void partialStaticVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialStaticVoidMethodMethod(info);
}
static void partialVoidMethodLongArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "partialVoidMethodLongArg", "TestInterface", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
int longArg;
{
longArg = toInt32(info.GetIsolate(), info[0], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
TestInterfacePartial::partialVoidMethodLongArg(*impl, longArg);
}
static void partialVoidMethodLongArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialVoidMethodLongArgMethod(info);
}
static void partialCallWithExecutionContextRaisesExceptionVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "partialCallWithExecutionContextRaisesExceptionVoidMethod", "TestInterface", info.Holder(), info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
TestInterfacePartial::partialCallWithExecutionContextRaisesExceptionVoidMethod(executionContext, *impl, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void partialCallWithExecutionContextRaisesExceptionVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialCallWithExecutionContextRaisesExceptionVoidMethodMethod(info);
}
static void partialVoidMethodPartialCallbackTypeArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "partialVoidMethodPartialCallbackTypeArg", "TestInterface", 1, info.Length()), info.GetIsolate());
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
ScriptValue partialCallbackTypeArg;
{
if (!info[0]->IsFunction()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("partialVoidMethodPartialCallbackTypeArg", "TestInterface", "The callback provided as parameter 1 is not a function."));
return;
}
partialCallbackTypeArg = ScriptValue(ScriptState::current(info.GetIsolate()), info[0]);
}
TestInterfacePartial::partialVoidMethodPartialCallbackTypeArg(*impl, partialCallbackTypeArg);
}
static void partialVoidMethodPartialCallbackTypeArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partialVoidMethodPartialCallbackTypeArgMethod(info);
}
static void shortMethodWithShortArgumentImplementedInPrivateScriptMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "shortMethodWithShortArgumentImplementedInPrivateScript", "TestInterface", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
int value;
{
value = toInt16(info.GetIsolate(), info[0], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
int result = 0;
if (!V8TestInterface::PrivateScript::shortMethodWithShortArgumentImplementedInPrivateScriptMethod(toLocalFrame(toFrameIfNotDetached(info.GetIsolate()->GetCurrentContext())), impl, value, &result))
return;
v8SetReturnValueInt(info, result);
}
static void shortMethodWithShortArgumentImplementedInPrivateScriptMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::shortMethodWithShortArgumentImplementedInPrivateScriptMethod(info);
}
static void partial2VoidMethod1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
TestInterfacePartial2Implementation::partial2VoidMethod(*impl);
}
static void partial2StaticVoidMethod1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfacePartial2Implementation::partial2StaticVoidMethod();
}
static void voidMethodPartialOverloadMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodPartialOverload", "TestInterface", info.Holder(), info.GetIsolate());
switch (std::min(1, info.Length())) {
case 0:
if (true) {
voidMethodPartialOverload1Method(info);
return;
}
break;
case 1:
if (info[0]->IsNumber()) {
voidMethodPartialOverload2Method(info);
return;
}
if (true) {
voidMethodPartialOverload2Method(info);
return;
}
break;
}
ASSERT(voidMethodPartialOverloadMethodForPartialInterface);
(voidMethodPartialOverloadMethodForPartialInterface)(info);
}
static void voidMethodPartialOverloadMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::voidMethodPartialOverloadMethod(info);
}
static void staticVoidMethodPartialOverloadMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "staticVoidMethodPartialOverload", "TestInterface", info.Holder(), info.GetIsolate());
switch (std::min(1, info.Length())) {
case 0:
if (true) {
staticVoidMethodPartialOverload1Method(info);
return;
}
break;
case 1:
break;
}
ASSERT(staticVoidMethodPartialOverloadMethodForPartialInterface);
(staticVoidMethodPartialOverloadMethodForPartialInterface)(info);
}
static void staticVoidMethodPartialOverloadMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticVoidMethodPartialOverloadMethod(info);
}
static void promiseMethodPartialOverloadMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "promiseMethodPartialOverload", "TestInterface", info.Holder(), info.GetIsolate());
switch (std::min(1, info.Length())) {
case 0:
if (true) {
promiseMethodPartialOverload1Method(info);
return;
}
break;
case 1:
if (V8Window::hasInstance(info[0], info.GetIsolate())) {
promiseMethodPartialOverload2Method(info);
return;
}
break;
}
ASSERT(promiseMethodPartialOverloadMethodForPartialInterface);
(promiseMethodPartialOverloadMethodForPartialInterface)(info);
}
static void promiseMethodPartialOverloadMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::promiseMethodPartialOverloadMethod(info);
}
static void staticPromiseMethodPartialOverloadMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "staticPromiseMethodPartialOverload", "TestInterface", info.Holder(), info.GetIsolate());
switch (std::min(1, info.Length())) {
case 0:
if (true) {
staticPromiseMethodPartialOverload1Method(info);
return;
}
break;
case 1:
break;
}
ASSERT(staticPromiseMethodPartialOverloadMethodForPartialInterface);
(staticPromiseMethodPartialOverloadMethodForPartialInterface)(info);
}
static void staticPromiseMethodPartialOverloadMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::staticPromiseMethodPartialOverloadMethod(info);
}
static void partial2VoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "partial2VoidMethod", "TestInterface", info.Holder(), info.GetIsolate());
switch (std::min(1, info.Length())) {
case 0:
if (true) {
partial2VoidMethod1Method(info);
return;
}
break;
case 1:
break;
}
ASSERT(partial2VoidMethodMethodForPartialInterface);
(partial2VoidMethodMethodForPartialInterface)(info);
}
static void partial2VoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partial2VoidMethodMethod(info);
}
static void partial2StaticVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "partial2StaticVoidMethod", "TestInterface", info.Holder(), info.GetIsolate());
switch (std::min(1, info.Length())) {
case 0:
if (true) {
partial2StaticVoidMethod1Method(info);
return;
}
break;
case 1:
break;
}
ASSERT(partial2StaticVoidMethodMethodForPartialInterface);
(partial2StaticVoidMethodMethodForPartialInterface)(info);
}
static void partial2StaticVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::partial2StaticVoidMethodMethod(info);
}
static void toJSONMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "toJSON", "TestInterface", info.Holder(), info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ScriptValue result = impl->toJSONForBinding(scriptState, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValue(info, result.v8Value());
}
static void toJSONMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::toJSONMethod(info);
}
static void toStringMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
v8SetReturnValueString(info, impl->toString(), info.GetIsolate());
}
static void toStringMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::toStringMethod(info);
}
static void iteratorMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "iterator", "TestInterface", info.Holder(), info.GetIsolate());
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
Iterator* result = impl->iterator(scriptState, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValue(info, result);
}
static void iteratorMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::iteratorMethod(info);
}
static void indexedPropertyGetter(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
String result = impl->anonymousIndexedGetter(index);
if (result.isNull())
return;
v8SetReturnValueString(info, result, info.GetIsolate());
}
static void indexedPropertyGetterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::indexedPropertyGetter(index, info);
}
static void indexedPropertySetter(uint32_t index, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
V8StringResource<> propertyValue = v8Value;
if (!propertyValue.prepare())
return;
bool result = impl->anonymousIndexedSetter(index, propertyValue);
if (!result)
return;
v8SetReturnValue(info, v8Value);
}
static void indexedPropertySetterCallback(uint32_t index, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestInterfaceImplementationV8Internal::indexedPropertySetter(index, v8Value, info);
}
static void indexedPropertyDeleter(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
DeleteResult result = impl->anonymousIndexedDeleter(index);
if (result != DeleteUnknownProperty)
return v8SetReturnValueBool(info, result == DeleteSuccess);
}
static void indexedPropertyDeleterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& info)
{
TestInterfaceImplementationV8Internal::indexedPropertyDeleter(index, info);
}
static void namedPropertyGetter(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
auto nameString = name.As<v8::String>();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
AtomicString propertyName = toCoreAtomicString(nameString);
String result = impl->anonymousNamedGetter(propertyName);
if (result.isNull())
return;
v8SetReturnValueString(info, result, info.GetIsolate());
}
static void namedPropertyGetterCallback(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
if (!name->IsString())
return;
TestInterfaceImplementationV8Internal::namedPropertyGetter(name, info);
}
static void namedPropertySetter(v8::Local<v8::Name> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
auto nameString = name.As<v8::String>();
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
V8StringResource<> propertyName(nameString);
if (!propertyName.prepare())
return;
V8StringResource<> propertyValue = v8Value;
if (!propertyValue.prepare())
return;
bool result = impl->anonymousNamedSetter(propertyName, propertyValue);
if (!result)
return;
v8SetReturnValue(info, v8Value);
}
static void namedPropertySetterCallback(v8::Local<v8::Name> name, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
if (!name->IsString())
return;
TestInterfaceImplementationV8Internal::namedPropertySetter(name, v8Value, info);
}
static void namedPropertyQuery(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Integer>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
AtomicString propertyName = toCoreAtomicString(name.As<v8::String>());
v8::String::Utf8Value namedProperty(name);
ExceptionState exceptionState(ExceptionState::GetterContext, *namedProperty, "TestInterface", info.Holder(), info.GetIsolate());
bool result = impl->namedPropertyQuery(propertyName, exceptionState);
if (exceptionState.throwIfNeeded())
return;
if (!result)
return;
v8SetReturnValueInt(info, v8::None);
}
static void namedPropertyQueryCallback(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Integer>& info)
{
if (!name->IsString())
return;
TestInterfaceImplementationV8Internal::namedPropertyQuery(name, info);
}
static void namedPropertyDeleter(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Boolean>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
AtomicString propertyName = toCoreAtomicString(name.As<v8::String>());
DeleteResult result = impl->anonymousNamedDeleter(propertyName);
if (result != DeleteUnknownProperty)
return v8SetReturnValueBool(info, result == DeleteSuccess);
}
static void namedPropertyDeleterCallback(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Boolean>& info)
{
if (!name->IsString())
return;
TestInterfaceImplementationV8Internal::namedPropertyDeleter(name, info);
}
static void namedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info)
{
TestInterfaceImplementation* impl = V8TestInterface::toImpl(info.Holder());
Vector<String> names;
ExceptionState exceptionState(ExceptionState::EnumerationContext, "TestInterface", info.Holder(), info.GetIsolate());
impl->namedPropertyEnumerator(names, exceptionState);
if (exceptionState.throwIfNeeded())
return;
v8::Local<v8::Array> v8names = v8::Array::New(info.GetIsolate(), names.size());
for (size_t i = 0; i < names.size(); ++i) {
if (!v8CallBoolean(v8names->CreateDataProperty(info.GetIsolate()->GetCurrentContext(), i, v8String(info.GetIsolate(), names[i]))))
return;
}
v8SetReturnValue(info, v8names);
}
static void namedPropertyEnumeratorCallback(const v8::PropertyCallbackInfo<v8::Array>& info)
{
TestInterfaceImplementationV8Internal::namedPropertyEnumerator(info);
}
} // namespace TestInterfaceImplementationV8Internal
void V8TestInterface::visitDOMWrapper(v8::Isolate* isolate, ScriptWrappable* scriptWrappable, const v8::Persistent<v8::Object>& wrapper)
{
TestInterfaceImplementation* impl = scriptWrappable->toImpl<TestInterfaceImplementation>();
TestInterfaceImplementation* referencedName = impl->referencedName();
if (referencedName) {
DOMWrapperWorld::setWrapperReferencesInAllWorlds(wrapper, referencedName, isolate);
}
}
// Suppress warning: global constructors, because AttributeConfiguration is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const V8DOMConfiguration::AttributeConfiguration V8TestInterfaceAttributes[] = {
{"testInterfaceConstructorAttribute", v8ConstructorAttributeGetter, 0, 0, 0, const_cast<WrapperTypeInfo*>(&V8TestInterface::wrapperTypeInfo), static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"TestInterface", v8ConstructorAttributeGetter, 0, 0, 0, const_cast<WrapperTypeInfo*>(&V8TestInterface::wrapperTypeInfo), static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
{"TestInterface2", v8ConstructorAttributeGetter, 0, 0, 0, const_cast<WrapperTypeInfo*>(&V8TestInterface2::wrapperTypeInfo), static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder},
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
const V8DOMConfiguration::AccessorConfiguration V8TestInterfaceAccessors[] = {
{"testInterfaceAttribute", TestInterfaceImplementationV8Internal::testInterfaceAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::testInterfaceAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"doubleAttribute", TestInterfaceImplementationV8Internal::doubleAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::doubleAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"floatAttribute", TestInterfaceImplementationV8Internal::floatAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::floatAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"unrestrictedDoubleAttribute", TestInterfaceImplementationV8Internal::unrestrictedDoubleAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::unrestrictedDoubleAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"unrestrictedFloatAttribute", TestInterfaceImplementationV8Internal::unrestrictedFloatAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::unrestrictedFloatAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"testEnumAttribute", TestInterfaceImplementationV8Internal::testEnumAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::testEnumAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"stringOrDoubleAttribute", TestInterfaceImplementationV8Internal::stringOrDoubleAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::stringOrDoubleAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"staticStringAttribute", TestInterfaceImplementationV8Internal::staticStringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::staticStringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
{"staticReturnDOMWrapperAttribute", TestInterfaceImplementationV8Internal::staticReturnDOMWrapperAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::staticReturnDOMWrapperAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
{"staticReadOnlyStringAttribute", TestInterfaceImplementationV8Internal::staticReadOnlyStringAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
{"staticReadOnlyReturnDOMWrapperAttribute", TestInterfaceImplementationV8Internal::staticReadOnlyReturnDOMWrapperAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
{"legacyInterfaceTypeCheckingAttribute", TestInterfaceImplementationV8Internal::legacyInterfaceTypeCheckingAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::legacyInterfaceTypeCheckingAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"alwaysExposedAttribute", TestInterfaceImplementationV8Internal::alwaysExposedAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::alwaysExposedAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"lenientThisAttribute", TestInterfaceImplementationV8Internal::lenientThisAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::lenientThisAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::DoNotCheckHolder},
{"implementsStaticReadOnlyLongAttribute", TestInterfaceImplementationV8Internal::implementsStaticReadOnlyLongAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
{"implementsStaticStringAttribute", TestInterfaceImplementationV8Internal::implementsStaticStringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implementsStaticStringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
{"implementsReadonlyStringAttribute", TestInterfaceImplementationV8Internal::implementsReadonlyStringAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"implementsStringAttribute", TestInterfaceImplementationV8Internal::implementsStringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implementsStringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"implementsNodeAttribute", TestInterfaceImplementationV8Internal::implementsNodeAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implementsNodeAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"implementsEventHandlerAttribute", TestInterfaceImplementationV8Internal::implementsEventHandlerAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implementsEventHandlerAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"implements3StringAttribute", TestInterfaceImplementationV8Internal::implements3StringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements3StringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"implements3StaticStringAttribute", TestInterfaceImplementationV8Internal::implements3StaticStringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements3StaticStringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
{"partial2LongAttribute", TestInterfaceImplementationV8Internal::partial2LongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partial2LongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"partial2StaticLongAttribute", TestInterfaceImplementationV8Internal::partial2StaticLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partial2StaticLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder},
};
const V8DOMConfiguration::MethodConfiguration V8TestInterfaceMethods[] = {
{"voidMethodTestInterfaceEmptyArg", TestInterfaceImplementationV8Internal::voidMethodTestInterfaceEmptyArgMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"voidMethodDoubleArgFloatArg", TestInterfaceImplementationV8Internal::voidMethodDoubleArgFloatArgMethodCallback, 0, 2, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"voidMethodUnrestrictedDoubleArgUnrestrictedFloatArg", TestInterfaceImplementationV8Internal::voidMethodUnrestrictedDoubleArgUnrestrictedFloatArgMethodCallback, 0, 2, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"voidMethodTestEnumArg", TestInterfaceImplementationV8Internal::voidMethodTestEnumArgMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"voidMethod", TestInterfaceImplementationV8Internal::voidMethodMethodCallback, TestInterfaceImplementationV8Internal::voidMethodMethodCallbackForMainWorld, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"alwaysExposedMethod", TestInterfaceImplementationV8Internal::alwaysExposedMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"alwaysExposedStaticMethod", TestInterfaceImplementationV8Internal::alwaysExposedStaticMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface},
{"staticReturnDOMWrapperMethod", TestInterfaceImplementationV8Internal::staticReturnDOMWrapperMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface},
{"legacyInterfaceTypeCheckingMethod", TestInterfaceImplementationV8Internal::legacyInterfaceTypeCheckingMethodMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"implementsVoidMethod", TestInterfaceImplementationV8Internal::implementsVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"implementsComplexMethod", TestInterfaceImplementationV8Internal::implementsComplexMethodMethodCallback, 0, 2, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"implementsCustomVoidMethod", TestInterfaceImplementationV8Internal::implementsCustomVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"implementsStaticVoidMethod", TestInterfaceImplementationV8Internal::implementsStaticVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface},
{"implements3VoidMethod", TestInterfaceImplementationV8Internal::implements3VoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"implements3StaticVoidMethod", TestInterfaceImplementationV8Internal::implements3StaticVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface},
{"voidMethodPartialOverload", TestInterfaceImplementationV8Internal::voidMethodPartialOverloadMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"staticVoidMethodPartialOverload", TestInterfaceImplementationV8Internal::staticVoidMethodPartialOverloadMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface},
{"promiseMethodPartialOverload", TestInterfaceImplementationV8Internal::promiseMethodPartialOverloadMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"staticPromiseMethodPartialOverload", TestInterfaceImplementationV8Internal::staticPromiseMethodPartialOverloadMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface},
{"partial2VoidMethod", TestInterfaceImplementationV8Internal::partial2VoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"partial2StaticVoidMethod", TestInterfaceImplementationV8Internal::partial2StaticVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface},
{"toJSON", TestInterfaceImplementationV8Internal::toJSONMethodCallback, 0, 0, static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
{"toString", TestInterfaceImplementationV8Internal::toStringMethodCallback, 0, 0, static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype},
};
void V8TestInterface::installV8TestInterfaceTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interfaceTemplate)
{
// Initialize the interface object's template.
V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterface::wrapperTypeInfo.interfaceName, V8TestInterfaceEmpty::domTemplate(isolate, world), V8TestInterface::internalFieldCount);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Register DOM constants, attributes and operations.
if (RuntimeEnabledFeatures::featureNameEnabled()) {
const V8DOMConfiguration::ConstantConfiguration V8TestInterfaceConstants[] = {
{"UNSIGNED_LONG", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedLong},
{"CONST_JAVASCRIPT", 1, 0, V8DOMConfiguration::ConstantTypeShort},
{"IMPLEMENTS_CONSTANT_1", 1, 0, V8DOMConfiguration::ConstantTypeUnsignedShort},
{"IMPLEMENTS_CONSTANT_2", 2, 0, V8DOMConfiguration::ConstantTypeUnsignedShort},
{"PARTIAL2_UNSIGNED_SHORT", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort},
};
V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, V8TestInterfaceConstants, WTF_ARRAY_LENGTH(V8TestInterfaceConstants));
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::ConstantConfiguration constantPartialUnsignedShortConfiguration = {"PARTIAL_UNSIGNED_SHORT", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort};
V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantPartialUnsignedShortConfiguration);
const V8DOMConfiguration::ConstantConfiguration constantPartialDoubleConfiguration = {"PARTIAL_DOUBLE", 0, 3.14, V8DOMConfiguration::ConstantTypeDouble};
V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantPartialDoubleConfiguration);
}
V8DOMConfiguration::installAttributes(isolate, world, instanceTemplate, prototypeTemplate, V8TestInterfaceAttributes, WTF_ARRAY_LENGTH(V8TestInterfaceAttributes));
V8DOMConfiguration::installAccessors(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceAccessors));
V8DOMConfiguration::installMethods(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceMethods, WTF_ARRAY_LENGTH(V8TestInterfaceMethods));
}
if (RuntimeEnabledFeatures::featureNameEnabled()) {
const V8DOMConfiguration::AccessorConfiguration accessorconditionalReadOnlyLongAttributeConfiguration = \
{"conditionalReadOnlyLongAttribute", TestInterfaceImplementationV8Internal::conditionalReadOnlyLongAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorconditionalReadOnlyLongAttributeConfiguration);
const V8DOMConfiguration::AccessorConfiguration accessorstaticConditionalReadOnlyLongAttributeConfiguration = \
{"staticConditionalReadOnlyLongAttribute", TestInterfaceImplementationV8Internal::staticConditionalReadOnlyLongAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorstaticConditionalReadOnlyLongAttributeConfiguration);
const V8DOMConfiguration::AccessorConfiguration accessorconditionalLongAttributeConfiguration = \
{"conditionalLongAttribute", TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorconditionalLongAttributeConfiguration);
}
if (RuntimeEnabledFeatures::implements2FeatureNameEnabled()) {
const V8DOMConfiguration::AccessorConfiguration accessorimplements2StaticStringAttributeConfiguration = \
{"implements2StaticStringAttribute", TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorimplements2StaticStringAttributeConfiguration);
const V8DOMConfiguration::AccessorConfiguration accessorimplements2StringAttributeConfiguration = \
{"implements2StringAttribute", TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorimplements2StringAttributeConfiguration);
}
if (RuntimeEnabledFeatures::implementsFeatureNameEnabled()) {
const V8DOMConfiguration::AccessorConfiguration accessorimplementsRuntimeEnabledNodeAttributeConfiguration = \
{"implementsRuntimeEnabledNodeAttribute", TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorimplementsRuntimeEnabledNodeAttributeConfiguration);
}
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::AccessorConfiguration accessorpartialPartialEnumTypeAttributeConfiguration = \
{"partialPartialEnumTypeAttribute", TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialPartialEnumTypeAttributeConfiguration);
const V8DOMConfiguration::AccessorConfiguration accessorpartialCallWithExecutionContextLongAttributeConfiguration = \
{"partialCallWithExecutionContextLongAttribute", TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialCallWithExecutionContextLongAttributeConfiguration);
const V8DOMConfiguration::AccessorConfiguration accessorpartialLongAttributeConfiguration = \
{"partialLongAttribute", TestInterfaceImplementationV8Internal::partialLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialLongAttributeConfiguration);
const V8DOMConfiguration::AccessorConfiguration accessorpartialStaticLongAttributeConfiguration = \
{"partialStaticLongAttribute", TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialStaticLongAttributeConfiguration);
const V8DOMConfiguration::AccessorConfiguration accessorstringAttributeConfiguration = \
{"stringAttribute", TestInterfaceImplementationV8Internal::stringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::stringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorstringAttributeConfiguration);
}
// Indexed properties
v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestInterfaceImplementationV8Internal::indexedPropertyGetterCallback, TestInterfaceImplementationV8Internal::indexedPropertySetterCallback, 0, TestInterfaceImplementationV8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestInterfaceImplementation>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kAllCanRead);
instanceTemplate->SetHandler(indexedPropertyHandlerConfig);
// Named properties
v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestInterfaceImplementationV8Internal::namedPropertyGetterCallback, TestInterfaceImplementationV8Internal::namedPropertySetterCallback, TestInterfaceImplementationV8Internal::namedPropertyQueryCallback, TestInterfaceImplementationV8Internal::namedPropertyDeleterCallback, TestInterfaceImplementationV8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kAllCanRead) | int(v8::PropertyHandlerFlags::kNonMasking)));
instanceTemplate->SetHandler(namedPropertyHandlerConfig);
// Iterator (@@iterator)
const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, TestInterfaceImplementationV8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype };
V8DOMConfiguration::installMethod(isolate, world, prototypeTemplate, signature, symbolKeyedIteratorConfiguration);
instanceTemplate->SetCallAsFunctionHandler(V8TestInterface::legacyCallCustom);
if (RuntimeEnabledFeatures::implements2FeatureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration implements2VoidMethodMethodConfiguration = {"implements2VoidMethod", TestInterfaceImplementationV8Internal::implements2VoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, implements2VoidMethodMethodConfiguration);
}
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration partialVoidMethodMethodConfiguration = {"partialVoidMethod", TestInterfaceImplementationV8Internal::partialVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialVoidMethodMethodConfiguration);
}
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration partialStaticVoidMethodMethodConfiguration = {"partialStaticVoidMethod", TestInterfaceImplementationV8Internal::partialStaticVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface};
V8DOMConfiguration::installMethod(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialStaticVoidMethodMethodConfiguration);
}
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration partialVoidMethodLongArgMethodConfiguration = {"partialVoidMethodLongArg", TestInterfaceImplementationV8Internal::partialVoidMethodLongArgMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialVoidMethodLongArgMethodConfiguration);
}
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration partialCallWithExecutionContextRaisesExceptionVoidMethodMethodConfiguration = {"partialCallWithExecutionContextRaisesExceptionVoidMethod", TestInterfaceImplementationV8Internal::partialCallWithExecutionContextRaisesExceptionVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialCallWithExecutionContextRaisesExceptionVoidMethodMethodConfiguration);
}
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration partialVoidMethodPartialCallbackTypeArgMethodConfiguration = {"partialVoidMethodPartialCallbackTypeArg", TestInterfaceImplementationV8Internal::partialVoidMethodPartialCallbackTypeArgMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialVoidMethodPartialCallbackTypeArgMethodConfiguration);
}
if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration shortMethodWithShortArgumentImplementedInPrivateScriptMethodConfiguration = {"shortMethodWithShortArgumentImplementedInPrivateScript", TestInterfaceImplementationV8Internal::shortMethodWithShortArgumentImplementedInPrivateScriptMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, shortMethodWithShortArgumentImplementedInPrivateScriptMethodConfiguration);
}
}
v8::Local<v8::FunctionTemplate> V8TestInterface::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world)
{
return V8DOMConfiguration::domClassTemplate(isolate, world, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), V8TestInterface::installV8TestInterfaceTemplateFunction);
}
bool V8TestInterface::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8TestInterface::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TestInterfaceImplementation* V8TestInterface::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}
void V8TestInterface::preparePrototypeAndInterfaceObject(v8::Local<v8::Context> context, const DOMWrapperWorld& world, v8::Local<v8::Object> prototypeObject, v8::Local<v8::Function> interfaceObject, v8::Local<v8::FunctionTemplate> interfaceTemplate)
{
v8::Isolate* isolate = context->GetIsolate();
ExecutionContext* executionContext = toExecutionContext(context);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
if (executionContext && (executionContext->isWorkerGlobalScope())) {
const V8DOMConfiguration::AccessorConfiguration accessorConfiguration = {"workerExposedAttribute", TestInterfaceImplementationV8Internal::workerExposedAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::workerExposedAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, accessorConfiguration);
}
if (executionContext && (executionContext->isDocument())) {
const V8DOMConfiguration::AccessorConfiguration accessorConfiguration = {"windowExposedAttribute", TestInterfaceImplementationV8Internal::windowExposedAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::windowExposedAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder};
V8DOMConfiguration::installAccessor(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, accessorConfiguration);
}
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
ExecutionContext* executionContext = toExecutionContext(prototypeObject->CreationContext());
ASSERT(executionContext);
if (executionContext && (executionContext->isWorkerGlobalScope())) {
const V8DOMConfiguration::MethodConfiguration workerExposedMethodMethodConfiguration = {"workerExposedMethod", TestInterfaceImplementationV8Internal::workerExposedMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, workerExposedMethodMethodConfiguration);
}
if (executionContext && (executionContext->isDocument())) {
const V8DOMConfiguration::MethodConfiguration windowExposedMethodMethodConfiguration = {"windowExposedMethod", TestInterfaceImplementationV8Internal::windowExposedMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, windowExposedMethodMethodConfiguration);
}
if (executionContext && (executionContext->isWorkerGlobalScope())) {
const V8DOMConfiguration::MethodConfiguration workerExposedStaticMethodMethodConfiguration = {"workerExposedStaticMethod", TestInterfaceImplementationV8Internal::workerExposedStaticMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, workerExposedStaticMethodMethodConfiguration);
}
if (executionContext && (executionContext->isDocument())) {
const V8DOMConfiguration::MethodConfiguration windowExposedStaticMethodMethodConfiguration = {"windowExposedStaticMethod", TestInterfaceImplementationV8Internal::windowExposedStaticMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, windowExposedStaticMethodMethodConfiguration);
}
if (executionContext && (executionContext->isDocument())) {
if (RuntimeEnabledFeatures::featureNameEnabled()) {
const V8DOMConfiguration::MethodConfiguration methodWithExposedAndRuntimeEnabledFlagMethodConfiguration = {"methodWithExposedAndRuntimeEnabledFlag", TestInterfaceImplementationV8Internal::methodWithExposedAndRuntimeEnabledFlagMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, methodWithExposedAndRuntimeEnabledFlagMethodConfiguration);
}
}
if (executionContext && (executionContext->isDocument())) {
const V8DOMConfiguration::MethodConfiguration overloadMethodWithExposedAndRuntimeEnabledFlagMethodConfiguration = {"overloadMethodWithExposedAndRuntimeEnabledFlag", TestInterfaceImplementationV8Internal::overloadMethodWithExposedAndRuntimeEnabledFlagMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, overloadMethodWithExposedAndRuntimeEnabledFlagMethodConfiguration);
}
if (executionContext && ((executionContext->isDocument() && RuntimeEnabledFeatures::featureNameEnabled()) || (executionContext->isWorkerGlobalScope() && RuntimeEnabledFeatures::featureName2Enabled()))) {
const V8DOMConfiguration::MethodConfiguration methodWithExposedHavingRuntimeEnabldFlagMethodConfiguration = {"methodWithExposedHavingRuntimeEnabldFlag", TestInterfaceImplementationV8Internal::methodWithExposedHavingRuntimeEnabldFlagMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, methodWithExposedHavingRuntimeEnabldFlagMethodConfiguration);
}
if (executionContext && (executionContext->isDocument() || executionContext->isServiceWorkerGlobalScope())) {
const V8DOMConfiguration::MethodConfiguration windowAndServiceWorkerExposedMethodMethodConfiguration = {"windowAndServiceWorkerExposedMethod", TestInterfaceImplementationV8Internal::windowAndServiceWorkerExposedMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype};
V8DOMConfiguration::installMethod(isolate, world, v8::Local<v8::Object>(), prototypeObject, interfaceObject, signature, windowAndServiceWorkerExposedMethodMethodConfiguration);
}
}
ActiveScriptWrappable* V8TestInterface::toActiveScriptWrappable(v8::Local<v8::Object> wrapper)
{
return toImpl(wrapper);
}
bool V8TestInterface::PrivateScript::shortMethodWithShortArgumentImplementedInPrivateScriptMethod(LocalFrame* frame, TestInterface* holderImpl, int value, int* result)
{
if (!frame)
return false;
v8::HandleScope handleScope(toIsolate(frame));
ScriptForbiddenScope::AllowUserAgentScript script;
ScriptState* scriptState = ScriptState::forWorld(frame, DOMWrapperWorld::privateScriptIsolatedWorld());
if (!scriptState)
return false;
ScriptState* scriptStateInUserScript = ScriptState::forMainWorld(frame);
if (!scriptStateInUserScript)
return false;
ScriptState::Scope scope(scriptState);
v8::Local<v8::Value> holder = toV8(holderImpl, scriptState->context()->Global(), scriptState->isolate());
if (holder.IsEmpty())
return false;
v8::Local<v8::Value> valueHandle = v8::Integer::New(scriptState->isolate(), value);
v8::Local<v8::Value> argv[] = { valueHandle };
ExceptionState exceptionState(ExceptionState::ExecutionContext, "shortMethodWithShortArgumentImplementedInPrivateScript", "TestInterfaceImplementation", scriptState->context()->Global(), scriptState->isolate());
v8::Local<v8::Value> v8Value = PrivateScriptRunner::runDOMMethod(scriptState, scriptStateInUserScript, "TestInterfaceImplementation", "shortMethodWithShortArgumentImplementedInPrivateScript", holder, 1, argv);
if (v8Value.IsEmpty())
return false;
int cppValue = toInt16(scriptState->isolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return false;
*result = cppValue;
RELEASE_ASSERT(!exceptionState.hadException());
return true;
}
bool V8TestInterface::PrivateScript::stringAttributeAttributeGetter(LocalFrame* frame, TestInterfaceImplementation* holderImpl, String* result)
{
if (!frame)
return false;
v8::HandleScope handleScope(toIsolate(frame));
ScriptForbiddenScope::AllowUserAgentScript script;
ScriptState* scriptState = ScriptState::forWorld(frame, DOMWrapperWorld::privateScriptIsolatedWorld());
if (!scriptState)
return false;
ScriptState* scriptStateInUserScript = ScriptState::forMainWorld(frame);
if (!scriptStateInUserScript)
return false;
ScriptState::Scope scope(scriptState);
v8::Local<v8::Value> holder = toV8(holderImpl, scriptState->context()->Global(), scriptState->isolate());
if (holder.IsEmpty())
return false;
ExceptionState exceptionState(ExceptionState::GetterContext, "stringAttribute", "TestInterfaceImplementation", scriptState->context()->Global(), scriptState->isolate());
v8::Local<v8::Value> v8Value = PrivateScriptRunner::runDOMAttributeGetter(scriptState, scriptStateInUserScript, "TestInterfaceImplementation", "stringAttribute", holder);
if (v8Value.IsEmpty())
return false;
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return false;
RELEASE_ASSERT(!exceptionState.hadException());
*result = cppValue;
return true;
}
bool V8TestInterface::PrivateScript::stringAttributeAttributeSetter(LocalFrame* frame, TestInterfaceImplementation* holderImpl, String cppValue)
{
if (!frame)
return false;
v8::HandleScope handleScope(toIsolate(frame));
ScriptForbiddenScope::AllowUserAgentScript script;
ScriptState* scriptState = ScriptState::forWorld(frame, DOMWrapperWorld::privateScriptIsolatedWorld());
if (!scriptState)
return false;
ScriptState* scriptStateInUserScript = ScriptState::forMainWorld(frame);
if (!scriptStateInUserScript)
return false;
ScriptState::Scope scope(scriptState);
v8::Local<v8::Value> holder = toV8(holderImpl, scriptState->context()->Global(), scriptState->isolate());
if (holder.IsEmpty())
return false;
ExceptionState exceptionState(ExceptionState::SetterContext, "stringAttribute", "TestInterfaceImplementation", scriptState->context()->Global(), scriptState->isolate());
return PrivateScriptRunner::runDOMAttributeSetter(scriptState, scriptStateInUserScript, "TestInterfaceImplementation", "stringAttribute", holder, v8String(scriptState->isolate(), cppValue));
}
InstallTemplateFunction V8TestInterface::installV8TestInterfaceTemplateFunction = (InstallTemplateFunction)&V8TestInterface::installV8TestInterfaceTemplate;
void V8TestInterface::updateWrapperTypeInfo(InstallTemplateFunction installTemplateFunction, PreparePrototypeAndInterfaceObjectFunction preparePrototypeAndInterfaceObjectFunction)
{
V8TestInterface::installV8TestInterfaceTemplateFunction = installTemplateFunction;
if (preparePrototypeAndInterfaceObjectFunction)
V8TestInterface::wrapperTypeInfo.preparePrototypeAndInterfaceObjectFunction = preparePrototypeAndInterfaceObjectFunction;
}
void V8TestInterface::registerVoidMethodPartialOverloadMethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&))
{
TestInterfaceImplementationV8Internal::voidMethodPartialOverloadMethodForPartialInterface = method;
}
void V8TestInterface::registerStaticVoidMethodPartialOverloadMethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&))
{
TestInterfaceImplementationV8Internal::staticVoidMethodPartialOverloadMethodForPartialInterface = method;
}
void V8TestInterface::registerPromiseMethodPartialOverloadMethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&))
{
TestInterfaceImplementationV8Internal::promiseMethodPartialOverloadMethodForPartialInterface = method;
}
void V8TestInterface::registerStaticPromiseMethodPartialOverloadMethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&))
{
TestInterfaceImplementationV8Internal::staticPromiseMethodPartialOverloadMethodForPartialInterface = method;
}
void V8TestInterface::registerPartial2VoidMethodMethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&))
{
TestInterfaceImplementationV8Internal::partial2VoidMethodMethodForPartialInterface = method;
}
void V8TestInterface::registerPartial2StaticVoidMethodMethodForPartialInterface(void (*method)(const v8::FunctionCallbackInfo<v8::Value>&))
{
TestInterfaceImplementationV8Internal::partial2StaticVoidMethodMethodForPartialInterface = method;
}
} // namespace blink
| 56.065657 | 620 | 0.796482 | [
"object",
"vector"
] |
4fef6a9e376d4a5a312aee4687d7ce374cc681af | 3,131 | cc | C++ | examples/impact_invariant_control/impact_aware_time_based_fsm.cc | Brian-Acosta/dairlib | 88da55d6e4378b93a787f3587d08b8a60f2f03f0 | [
"BSD-3-Clause"
] | 32 | 2019-04-15T03:10:26.000Z | 2022-03-28T17:27:03.000Z | examples/impact_invariant_control/impact_aware_time_based_fsm.cc | Brian-Acosta/dairlib | 88da55d6e4378b93a787f3587d08b8a60f2f03f0 | [
"BSD-3-Clause"
] | 157 | 2019-02-21T03:13:57.000Z | 2022-03-09T19:13:59.000Z | examples/impact_invariant_control/impact_aware_time_based_fsm.cc | Brian-Acosta/dairlib | 88da55d6e4378b93a787f3587d08b8a60f2f03f0 | [
"BSD-3-Clause"
] | 22 | 2019-03-02T22:31:42.000Z | 2022-03-10T21:28:50.000Z | #include "examples/impact_invariant_control/impact_aware_time_based_fsm.h"
using std::cout;
using std::endl;
using drake::systems::BasicVector;
using drake::systems::Context;
using Eigen::VectorXd;
using std::string;
namespace dairlib {
using systems::OutputVector;
ImpactTimeBasedFiniteStateMachine::ImpactTimeBasedFiniteStateMachine(
const drake::multibody::MultibodyPlant<double>& plant,
const std::vector<int>& states, const std::vector<double>& state_durations,
double t0, double near_impact_threshold, BLEND_FUNC blend_func)
: TimeBasedFiniteStateMachine(plant, states, state_durations, t0),
states_(states),
state_durations_(state_durations),
t0_(t0),
near_impact_threshold_(near_impact_threshold),
blend_func_(blend_func) {
near_impact_port_ =
this->DeclareVectorOutputPort("next_fsm, t_to_impact",
BasicVector<double>(2),
&ImpactTimeBasedFiniteStateMachine::CalcNearImpact)
.get_index();
// Accumulate the durations to get timestamps
double sum = 0;
DRAKE_DEMAND(states.size() == state_durations.size());
impact_times_.push_back(0.0);
impact_states_.push_back(0);
for (int i = 0; i < states.size(); ++i) {
sum += state_durations[i];
accu_state_durations_.push_back(sum);
impact_times_.push_back(sum);
impact_states_.push_back(states[i]);
}
period_ = sum;
}
double alpha_sigmoid(double t, double tau, double near_impact_threshold) {
double x = (t + near_impact_threshold) / tau;
return exp(x) / (1 + exp(x));
}
double alpha_exp(double t, double tau, double near_impact_threshold) {
return 1 - exp(-(t + near_impact_threshold) / tau);
}
void ImpactTimeBasedFiniteStateMachine::CalcNearImpact(
const Context<double>& context, BasicVector<double>* near_impact) const {
// Read in lcm message time
const OutputVector<double>* robot_output =
(OutputVector<double>*)this->EvalVectorInput(context, state_port_);
auto current_time = static_cast<double>(robot_output->get_timestamp());
double remainder = fmod(current_time, period_);
// Assign the blending function ptr
auto alpha_func = blend_func_ == SIGMOID ? &alpha_sigmoid : &alpha_exp;
VectorXd near_impact_data = VectorXd::Zero(2);
// Get current finite state
if (current_time >= t0_) {
for (int i = 0; i < impact_states_.size(); ++i) {
double blend_window = blend_func_ == SIGMOID
? 1.5 * near_impact_threshold_
: near_impact_threshold_;
if (abs(remainder - impact_times_[i]) < blend_window) {
if (remainder < impact_times_[i]) {
near_impact_data(0) = alpha_func(remainder - impact_times_[i], tau_,
near_impact_threshold_);
} else {
near_impact_data(0) = alpha_func(impact_times_[i] - remainder, tau_,
near_impact_threshold_);
}
near_impact_data(1) = impact_states_[i];
break;
}
}
}
near_impact->get_mutable_value() = near_impact_data;
}
} // namespace dairlib
| 34.406593 | 79 | 0.676461 | [
"vector"
] |
4fefbbf8729db262f334f9e213b0f6b9c9a82651 | 709 | cpp | C++ | ec/typechainid.cpp | vankiaio/vktchainkit | 60aee5a3789e7a2078404f8e8b7ac62ca84ff3e6 | [
"Apache-2.0"
] | 1 | 2019-04-19T08:06:44.000Z | 2019-04-19T08:06:44.000Z | ec/typechainid.cpp | vankiaio/vktchainkit | 60aee5a3789e7a2078404f8e8b7ac62ca84ff3e6 | [
"Apache-2.0"
] | null | null | null | ec/typechainid.cpp | vankiaio/vktchainkit | 60aee5a3789e7a2078404f8e8b7ac62ca84ff3e6 | [
"Apache-2.0"
] | null | null | null | #include "typechainid.h"
#include "../utility/utils.h"
#include <string.h>
TypeChainId::TypeChainId()
{
memset(id, 0, sizeof(id));
}
void *TypeChainId::getBytes()
{
return (void*)id;
}
void TypeChainId::setBytes(unsigned char *bytes)
{
memcpy(id, bytes, 32);
}
const unsigned char *TypeChainId::chainId() const
{
return id;
}
TypeChainId TypeChainId::fromHex(const std::string& strHex)
{
TypeChainId cid;
if (strHex.empty()) {
return cid;
}
//assert(strHex.size() == 64);
std::vector<unsigned char> vec(strHex.begin(), strHex.end());
std::vector<unsigned char> bytes = Utils::convertHexStrToBytes(vec);
cid.setBytes(bytes.data());
return cid;
}
| 17.725 | 72 | 0.648801 | [
"vector"
] |
4ff138f25707cf55fcfa4291fc908e747067b492 | 3,880 | cpp | C++ | test/families/test_normal.cpp | bosky9/c-plus-plus-project | 6ae6b2f9d78dc310540cc8dc91eae8690de72bf1 | [
"MIT"
] | null | null | null | test/families/test_normal.cpp | bosky9/c-plus-plus-project | 6ae6b2f9d78dc310540cc8dc91eae8690de72bf1 | [
"MIT"
] | null | null | null | test/families/test_normal.cpp | bosky9/c-plus-plus-project | 6ae6b2f9d78dc310540cc8dc91eae8690de72bf1 | [
"MIT"
] | null | null | null | /**
* @file test_normal.cpp
* @author Bodini Alessia, Boschi Federico, Cinquetti Ettore
* @date January, 2022
*/
#include "families/normal.hpp"
#include <catch2/catch_test_macros.hpp>
TEST_CASE("Approximating model", "[approximating_model][approximating_model_reg]") {
Eigen::VectorXd v(2);
v << 1, 2;
std::pair<Eigen::MatrixXd, Eigen::MatrixXd> H_mu;
SECTION("Approximating model", "[approximating_model]") {
H_mu = Normal::approximating_model(3, v);
REQUIRE(H_mu.first == Eigen::MatrixXd::Constant(v.size(), v.size(), 3));
REQUIRE(H_mu.second == Eigen::MatrixXd::Zero(v.size(), v.size()));
}
SECTION("Approximating model with regressors", "[approximating_model_reg]") {
H_mu = Normal::approximating_model_reg(3, v);
REQUIRE(H_mu.first == Eigen::MatrixXd::Constant(v.size(), v.size(), 3));
REQUIRE(H_mu.second == Eigen::MatrixXd::Zero(v.size(), v.size()));
}
}
TEST_CASE("Build latent variables", "[build_latent_variables]") {
Normal normal{};
std::vector<lv_to_build> result = normal.build_latent_variables();
REQUIRE(std::get<0>(result.front()) == "Normal scale");
REQUIRE(std::get<1>(result.front())->get_transform_name() == "exp");
REQUIRE(*reinterpret_cast<Normal*>(std::get<2>(result.front())) == Normal{0.0, 3.0});
REQUIRE(std::get<3>(result.front()) == 0.0);
delete std::get<1>(result.front());
delete std::get<2>(result.front());
}
TEST_CASE("Draw variable", "[draw_variable][draw_variable_local]") {
Normal normal{};
Eigen::VectorXd variable;
SECTION("Draw variable", "[draw_variable]") {
variable = normal.draw_variable(0.0, 1.0, 1.0, 1.0, 5);
}
SECTION("Draw variable with local mean and variance", "[draw_variable_local") {
variable = normal.draw_variable_local(2);
}
}
TEST_CASE("Log of the PDF", "[logpdf]") {
Normal normal{2.0, 4.0};
REQUIRE(normal.logpdf(2.0) == -1.3862943611198906);
}
TEST_CASE("Markov blanket", "[markov_blanket]") {
Eigen::VectorXd v = Eigen::VectorXd::Ones(3);
Eigen::VectorXd result = Normal::markov_blanket(v, v, 1.0);
REQUIRE((result - Eigen::Vector3d{-0.91893853, -0.91893853, -0.91893853}).norm() < 0.0000001);
}
TEST_CASE("Setup", "[setup]") {
Normal normal{};
FamilyAttributes attributes = normal.setup();
REQUIRE(attributes.name == "Normal");
REQUIRE(attributes.scale == true);
REQUIRE(attributes.shape == false);
REQUIRE(attributes.skewness == false);
}
TEST_CASE("Negative Log Likelihood", "[neg_loglikelihood]") {
Eigen::VectorXd v = Eigen::VectorXd::Ones(3);
Normal n{};
REQUIRE(n.neg_loglikelihood(v, v, 1.0) == -2.756815599614018);
}
TEST_CASE("PDF", "[pdf]") {
Normal normal{};
REQUIRE(normal.pdf(1.0) == 0.6065306597126334);
}
TEST_CASE("Change parameters", "[vi_change_param][vi_return_param]") {
Normal normal{};
normal.vi_change_param(0, 2.0);
normal.vi_change_param(1, 5.0);
REQUIRE(normal.vi_return_param(0) == 2.0);
REQUIRE(normal.vi_return_param(1) == 5.0);
}
TEST_CASE("Compute score", "[vi_score]") {
Normal normal{};
REQUIRE(normal.vi_score(1.0, 0) == 1);
REQUIRE(normal.vi_score(1.0, 1) == 0);
REQUIRE(normal.vi_score(static_cast<Eigen::VectorXd>(Eigen::Vector2d{1.0, 1.0}), 0) == Eigen::Vector2d{1.0, 1.0});
REQUIRE(normal.vi_score(static_cast<Eigen::VectorXd>(Eigen::Vector2d{1.0, 1.0}), 1) == Eigen::Vector2d{0.0, 0.0});
}
TEST_CASE("Clone function", "[clone]") {
Normal normal{1, 3.5};
std::unique_ptr<Family> normal2 = normal.clone();
REQUIRE(normal2->get_name() == "Normal");
REQUIRE(dynamic_cast<Normal*>(normal2.get())->get_sigma0() == normal.get_sigma0());
REQUIRE(dynamic_cast<Normal*>(normal2.get())->get_mu0() == normal.get_mu0());
REQUIRE(normal2.get()->logpdf(1.8) == normal.logpdf(1.8));
}
| 34.035088 | 118 | 0.648454 | [
"shape",
"vector",
"model"
] |
4ff15016835ca31e16c3ee0b782afcdf43145b9a | 6,404 | hpp | C++ | include/UnityEngine/XR/InputFeatureUsage_1.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/UnityEngine/XR/InputFeatureUsage_1.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/UnityEngine/XR/InputFeatureUsage_1.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.IEquatable`1
#include "System/IEquatable_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin il2cpp-utils forward declares
struct Il2CppObject;
// Completed il2cpp-utils forward declares
// Type namespace: UnityEngine.XR
namespace UnityEngine::XR {
// Forward declaring type: InputFeatureUsage`1<T>
template<typename T>
struct InputFeatureUsage_1;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE_GENERIC_STRUCT(::UnityEngine::XR::InputFeatureUsage_1, "UnityEngine.XR", "InputFeatureUsage`1");
// Type namespace: UnityEngine.XR
namespace UnityEngine::XR {
// WARNING Size may be invalid!
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: UnityEngine.XR.InputFeatureUsage`1
// [TokenAttribute] Offset: FFFFFFFF
template<typename T>
struct InputFeatureUsage_1/*, public ::System::ValueType, public ::System::IEquatable_1<::UnityEngine::XR::InputFeatureUsage_1<T>>*/ {
public:
public:
// [DebuggerBrowsableAttribute] Offset: 0x6C9848
// private System.String <name>k__BackingField
// Size: 0x8
// Offset: 0x0
::StringW name;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
public:
// Creating value type constructor for type: InputFeatureUsage_1
constexpr InputFeatureUsage_1(::StringW name_ = {}) noexcept : name{name_} {}
// Creating interface conversion operator: operator ::System::ValueType
operator ::System::ValueType() noexcept {
return *reinterpret_cast<::System::ValueType*>(this);
}
// Creating interface conversion operator: operator ::System::IEquatable_1<::UnityEngine::XR::InputFeatureUsage_1<T>>
operator ::System::IEquatable_1<::UnityEngine::XR::InputFeatureUsage_1<T>>() noexcept {
return *reinterpret_cast<::System::IEquatable_1<::UnityEngine::XR::InputFeatureUsage_1<T>>*>(this);
}
// Creating conversion operator: operator ::StringW
constexpr operator ::StringW() const noexcept {
return name;
}
// Autogenerated instance field getter
// Get instance field: private System.String <name>k__BackingField
[[deprecated("Use field access instead!")]] ::StringW& dyn_$name$k__BackingField() {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::XR::InputFeatureUsage_1::dyn_$name$k__BackingField");
auto ___internal__instance = *this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "<name>k__BackingField"))->offset;
return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// public System.String get_name()
// Offset: 0xFFFFFFFFFFFFFFFF
::StringW get_name() {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::XR::InputFeatureUsage_1::get_name");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_name", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method);
}
// public System.Void set_name(System.String value)
// Offset: 0xFFFFFFFFFFFFFFFF
void set_name(::StringW value) {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::XR::InputFeatureUsage_1::set_name");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "set_name", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)})));
::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value);
}
// public System.Void .ctor(System.String usageName)
// Offset: 0xFFFFFFFFFFFFFFFF
// ABORTED: conflicts with another method. InputFeatureUsage_1(::StringW usageName)
// public System.Boolean Equals(UnityEngine.XR.InputFeatureUsage`1<T> other)
// Offset: 0xFFFFFFFFFFFFFFFF
bool Equals(::UnityEngine::XR::InputFeatureUsage_1<T> other) {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::XR::InputFeatureUsage_1::Equals");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(*this, classof(::UnityEngine::XR::InputFeatureUsage_1<T>), -1));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, other);
}
// public override System.Boolean Equals(System.Object obj)
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: System.ValueType
// Base method: System.Boolean ValueType::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj) {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::XR::InputFeatureUsage_1::Equals");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(*this, classof(::System::ValueType*), -1));
return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, obj);
}
// public override System.Int32 GetHashCode()
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: System.ValueType
// Base method: System.Int32 ValueType::GetHashCode()
int GetHashCode() {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::XR::InputFeatureUsage_1::GetHashCode");
auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(*this, classof(::System::ValueType*), -1));
return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method);
}
}; // UnityEngine.XR.InputFeatureUsage`1
// Could not write size check! Type: UnityEngine.XR.InputFeatureUsage`1 is generic, or has no fields that are valid for size checks!
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 56.175439 | 202 | 0.725328 | [
"object",
"vector"
] |
4ff342883b102a1f41e84f77ae53f9514884128a | 1,673 | cpp | C++ | src/main.cpp | hilnius/cappella | 555a920330e615793b238d72255274ca7c558467 | [
"MIT"
] | null | null | null | src/main.cpp | hilnius/cappella | 555a920330e615793b238d72255274ca7c558467 | [
"MIT"
] | null | null | null | src/main.cpp | hilnius/cappella | 555a920330e615793b238d72255274ca7c558467 | [
"MIT"
] | null | null | null | #include <iostream>
#include <proxygen/httpserver/HTTPServer.h>
#include "core/MySQLDatabaseDriver.hpp"
#include "core/Router.hpp"
#include "core/RouterHandlerFactory.hpp"
#include "app/UserEntityManager.hpp"
#include "app/PageEntityManager.hpp"
#include "app/User.hpp"
#include "app/Page.hpp"
#include "app/PageController.hpp"
#include "app/UserController.hpp"
using namespace std;
int main(int argc, char* argv[]) {
cout << "Cappella started" << endl;
Router::getInstance()->rest<PageController>("/page");
Router::getInstance()->rest<UserController>("/user");
MySQLDatabaseDriver::getInstance()->connect("127.0.0.1:3306", "root", "");
MySQLDatabaseDriver::getInstance()->use("cappella");
UserEntityManager::getInstance()->load();
PageEntityManager::getInstance()->load();
MySQLDatabaseDriver::kill();
MySQLDatabaseDriver::kill();
// START THE SERVER
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
std::vector<proxygen::HTTPServer::IPConfig> IPs = {
{folly::SocketAddress("localhost", 8001, true), proxygen::HTTPServer::Protocol::HTTP},
};
proxygen::HTTPServerOptions options;
options.threads = sysconf(_SC_NPROCESSORS_ONLN);
options.idleTimeout = std::chrono::milliseconds(60000);
options.shutdownOn = {SIGINT, SIGTERM};
options.handlerFactories = proxygen::RequestHandlerChain()
.addThen<RouterHandlerFactory>()
.build();
proxygen::HTTPServer server(std::move(options));
server.bind(IPs);
// Start HTTPServer mainloop in a separate thread
std::thread t([&] () {
server.start();
});
t.join();
return 0;
}
| 28.355932 | 90 | 0.716079 | [
"vector"
] |
4ff34fc1306eaafc177f8d7f5c23ad040741491b | 7,557 | cpp | C++ | subprojects/ce-login/cli/CliVerifyHsf.cpp | human3rr/ibm-acf | 2d4c0acca4a08b2a5cf92a614d5ef6d7f15b5b5d | [
"Apache-2.0"
] | null | null | null | subprojects/ce-login/cli/CliVerifyHsf.cpp | human3rr/ibm-acf | 2d4c0acca4a08b2a5cf92a614d5ef6d7f15b5b5d | [
"Apache-2.0"
] | null | null | null | subprojects/ce-login/cli/CliVerifyHsf.cpp | human3rr/ibm-acf | 2d4c0acca4a08b2a5cf92a614d5ef6d7f15b5b5d | [
"Apache-2.0"
] | null | null | null |
#include "CeLoginCli.h"
#include "CliUtils.h"
#include <CeLogin.h>
#include <getopt.h>
#include <string.h>
#include <inttypes.h>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace CeLogin;
struct VerifyArguments
{
std::string mHsfFileName;
std::string mPublicKeyFileName;
std::string mPassword;
std::string mSerialNumber;
bool mVerbose;
bool mHelp;
VerifyArguments()
{
mVerbose = false;
mHelp = false;
}
};
enum VerifyOptOptions
{
HsfFileName,
PublicKeyFileName,
Password,
SerialNumber,
Help,
Verbose,
NOptOptions
};
struct option verify_long_options[NOptOptions + 1] = {
{"hsfFile", required_argument, NULL, 'i'},
{"publicKeyFile", required_argument, NULL, 'k'},
{"password", required_argument, NULL, 'p'},
{"serialNumber", required_argument, NULL, 's'},
{"help", no_argument, NULL, 'h'},
{"verbose", no_argument, NULL, 'v'},
{0, 0, 0, 0}};
std::string verify_options_description[NOptOptions] = {
"HsfFile", "PublicKeyFile", "Password",
"SerialNumber"
"Help",
"Verbose"};
void verifyParseArgs(int argc, char** argv, struct VerifyArguments& args)
{
std::string short_options = "";
for (int i = 0; i < NOptOptions; i++)
{
short_options += verify_long_options[i].val;
if (required_argument == verify_long_options[i].has_arg)
{
short_options += ":";
}
}
int c;
int sNumOfRequiredArgumentsFound = 0;
while (1)
{
int option_index = 0;
c = getopt_long(argc, argv, short_options.c_str(), verify_long_options,
&option_index);
if (c == -1)
break;
switch (c)
{
case 'i':
{
sNumOfRequiredArgumentsFound++;
args.mHsfFileName = std::string(optarg);
break;
}
case 'k':
{
sNumOfRequiredArgumentsFound++;
args.mPublicKeyFileName = std::string(optarg);
break;
}
case 'p':
{
sNumOfRequiredArgumentsFound++;
args.mPassword = std::string(optarg);
break;
}
case 's':
{
sNumOfRequiredArgumentsFound++;
args.mSerialNumber = std::string(optarg);
break;
}
case 'h':
{
args.mHelp = true;
break;
}
case 'v':
{
args.mVerbose = true;
break;
}
default:
{
}
}
}
}
void verifyPrintHelp(int argc, char** argv)
{
// Find the longest option
size_t sLongestOpt = 0;
for (unsigned int i = 0; i < NOptOptions; i++)
{
size_t sLength = strlen(verify_long_options[i].name);
sLongestOpt = std::max<size_t>(sLongestOpt, sLength);
}
std::cout << "Usage: " << argv[0] << " " << argv[1] << std::endl;
for (unsigned int i = 0; i < NOptOptions; i++)
{
size_t sLength = strlen(verify_long_options[i].name);
std::cout << "\t-" << (char)verify_long_options[i].val << " --"
<< verify_long_options[i].name;
for (size_t j = 0; j < (sLongestOpt - sLength); j++)
{
std::cout << " ";
}
std::cout << " | " << verify_options_description[i] << std::endl;
}
}
bool verifyValidateArgs(const VerifyArguments& args)
{
bool sIsValidArgs = true;
if (args.mHsfFileName.empty())
{
sIsValidArgs = false;
std::cout << "Error: Missing HsfFileName" << std::endl;
}
if (args.mPublicKeyFileName.empty())
{
sIsValidArgs = false;
std::cout << "Error: Missing Public Key File Path" << std::endl;
}
if (args.mPassword.empty())
{
sIsValidArgs = false;
std::cout << "Error: Missing Password" << std::endl;
}
if (args.mSerialNumber.empty())
{
sIsValidArgs = false;
std::cout << "Error: Missing Serial Number" << std::endl;
}
return sIsValidArgs;
}
CeLogin::CeLoginRc cli::verifyHsf(int argc, char** argv)
{
VerifyArguments sArgs;
verifyParseArgs(argc, argv, sArgs);
CeLogin::CeLoginRc sRc = CeLogin::CeLoginRc::Failure;
if (sArgs.mHelp)
{
verifyPrintHelp(argc, argv);
}
else if (verifyValidateArgs(sArgs))
{
std::vector<uint8_t> sHsf;
if (readBinaryFile(sArgs.mHsfFileName, sHsf))
{
std::vector<uint8_t> sPublicKey;
if (readBinaryFile(sArgs.mPublicKeyFileName, sPublicKey))
{
std::time_t sTime = std::time(NULL);
CeLogin::ServiceAuthority sAuth = CeLogin::ServiceAuth_None;
uint64_t sExpiration;
sRc = CeLogin::getServiceAuthorityV1(
sHsf.data(), sHsf.size(), sArgs.mPassword.data(),
sArgs.mPassword.size(), sTime, sPublicKey.data(),
sPublicKey.size(), sArgs.mSerialNumber.data(),
sArgs.mSerialNumber.size(), sAuth, sExpiration);
if (CeLoginRc::Success == sRc)
{
std::cout << "ACF/password is valid" << std::endl;
}
else if (CeLoginRc::SignatureNotValid == sRc)
{
std::cout << "Signature is not valid" << std::endl;
}
else
{
std::cout << "Error: Component \"" << (int)sRc.mComponent
<< "\" Reason: 0x" << std::hex << (int)sRc.mReason
<< std::endl;
std::cout << "Error: " << sRc << std::endl;
}
switch (sAuth)
{
case CeLogin::ServiceAuth_None:
{
std::cout << "Authorization: None" << std::endl;
break;
}
case CeLogin::ServiceAuth_User:
{
std::cout << "Authorization: User" << std::endl;
break;
}
case CeLogin::ServiceAuth_CE:
{
std::cout << "Authorization: CE" << std::endl;
break;
}
case CeLogin::ServiceAuth_Dev:
{
std::cout << "Authorization: Dev" << std::endl;
break;
}
default:
{
std::cout << "Authorization: Unknown" << std::endl;
break;
}
}
printf("Expiration (UNIX): %llu\n", sExpiration);
}
else
{
std::cout << "ERROR: Unable to read public key file: \""
<< sArgs.mPublicKeyFileName << "\"" << std::endl;
}
}
else
{
std::cout << "ERROR: Unable to read hsf file: \""
<< sArgs.mHsfFileName << "\"" << std::endl;
}
}
else
{
std::cout << "Args failed to validate" << std::endl;
}
return sRc;
}
| 28.303371 | 80 | 0.474792 | [
"vector"
] |
4ff67d7c9d72e1aafaea24652d32ff6c15523669 | 8,280 | cc | C++ | mindspore/ccsrc/backend/kernel_compiler/cpu/eigen/lu_cpu_kernel.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | 1 | 2021-12-27T13:42:29.000Z | 2021-12-27T13:42:29.000Z | mindspore/ccsrc/backend/kernel_compiler/cpu/eigen/lu_cpu_kernel.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/backend/kernel_compiler/cpu/eigen/lu_cpu_kernel.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 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 "backend/kernel_compiler/cpu/eigen/lu_cpu_kernel.h"
#include <vector>
#include <algorithm>
#include <utility>
#include <unordered_map>
#include "utils/ms_utils.h"
namespace mindspore {
namespace kernel {
namespace {
constexpr size_t kLUInputsNum = 1;
constexpr size_t kLUaIndex = 0;
constexpr size_t kLUOutputsNum = 3;
constexpr size_t kLuIndex = 0;
constexpr size_t kPivotsIndex = 1;
constexpr size_t kPermutationIndex = 2;
constexpr size_t kLUDefaultShape = 1;
constexpr size_t kRowIndex = 2;
constexpr size_t kColIndex = 1;
constexpr int kZeroThreshold = INT32_MIN;
} // namespace
template <typename T>
void LUCPUKernel<T>::InitMatrixInfo(const std::vector<size_t> &shape, size_t *row, size_t *col) {
if (shape.empty()) {
MS_LOG_EXCEPTION << kernel_name_ << "shape is invalid.";
}
if (shape.size() == kLUDefaultShape) {
*row = shape.front();
*col = 1;
} else {
*row = shape.at(shape.size() - kRowIndex);
*col = shape.at(shape.size() - kColIndex);
}
return;
}
template <typename T>
void LUCPUKernel<T>::InitKernel(const CNodePtr &kernel_node) {
MS_EXCEPTION_IF_NULL(kernel_node);
kernel_name_ = AnfAlgo::GetCNodeName(kernel_node);
dtype_ = AnfAlgo::GetInputDeviceDataType(kernel_node, 0);
size_t input_num = AnfAlgo::GetInputTensorNum(kernel_node);
CHECK_KERNEL_INPUTS_NUM(input_num, kLUInputsNum, kernel_name_);
size_t output_num = AnfAlgo::GetOutputTensorNum(kernel_node);
CHECK_KERNEL_OUTPUTS_NUM(output_num, kLUOutputsNum, kernel_name_);
auto a_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, kLUaIndex);
InitMatrixInfo(a_shape, &a_row_, &a_col_);
auto lu_shape = AnfAlgo::GetOutputInferShape(kernel_node, kLuIndex);
InitMatrixInfo(lu_shape, &lu_row_, &lu_col_);
auto pivots_shape = AnfAlgo::GetOutputInferShape(kernel_node, kPivotsIndex);
InitMatrixInfo(pivots_shape, &pivots_row_, &pivots_col_);
auto permutation_shape = AnfAlgo::GetOutputInferShape(kernel_node, kPermutationIndex);
InitMatrixInfo(permutation_shape, &permutation_row_, &permutation_col_);
}
template <typename T>
void LUCPUKernel<T>::InitInputOutputSize(const CNodePtr &kernel_node) {
CPUKernel::InitInputOutputSize(kernel_node);
size_t lu_size = lu_col_ * sizeof(T);
(void)workspace_size_list_.emplace_back(lu_size);
(void)workspace_size_list_.emplace_back(lu_size);
}
template <typename T>
T LUCPUKernel<T>::GetPermutatedValue(const T *lu_value, const int *per, size_t i, size_t j) {
const T *pered_lu_value = lu_value + per[i] * lu_col_ + j;
return *pered_lu_value;
}
template <typename T>
bool LUCPUKernel<T>::UpdateMajorPermutation(T *lu_value, int *per, size_t k, size_t rows) {
T max_major_value = static_cast<T>(kZeroThreshold);
int max_major_index = 0;
for (size_t i = k; i < rows; ++i) {
T value = GetPermutatedValue(lu_value, per, i, k);
T abs_value = std::abs(value);
if (abs_value > max_major_value) {
max_major_value = abs_value;
max_major_index = i;
}
}
size_t per_k = per[k];
per[k] = per[max_major_index];
per[max_major_index] = per_k;
return max_major_value != static_cast<T>(kZeroThreshold);
}
template <typename T>
void LUCPUKernel<T>::SetPermutatedValue(T *lu_value, const int *per, size_t i, size_t j, const T &value) {
T *pered_lu_value = lu_value + per[i] * lu_col_ + j;
*pered_lu_value = value;
}
template <typename T>
bool LUCPUKernel<T>::Launch(const std::vector<kernel::AddressPtr> &inputs,
const std::vector<kernel::AddressPtr> &workspace,
const std::vector<kernel::AddressPtr> &outputs) {
// input matrix of (m,n) PA = LU
T *a_value = reinterpret_cast<T *>(inputs[kLUaIndex]->addr);
T *lu_value = reinterpret_cast<T *>(outputs[kLuIndex]->addr);
// pivots permutation value
int *per_value = reinterpret_cast<int *>(outputs[kPivotsIndex]->addr);
// permutation matrix value
int *permutation_value = reinterpret_cast<int *>(outputs[kPermutationIndex]->addr);
T *lu_ori_wk = reinterpret_cast<T *>(workspace[kLuIndex]->addr);
T *lu_trans_wk = reinterpret_cast<T *>(workspace[kPivotsIndex]->addr);
// init pivots
for (size_t i = 0; i < pivots_row_; ++i) {
per_value[i] = i;
}
// 1. memcpy input to output, do full lu inplace.
(void)memcpy_s(lu_value, lu_row_ * lu_col_ * sizeof(T), a_value, a_row_ * a_col_ * sizeof(T));
int s = std::min(a_row_, a_col_);
// 2. do lu decompose inplace
for (int k = 0; k < s; ++k) {
// 2.1 choose major element of current col if return false means current col elements are all zero, just continue.
if (!UpdateMajorPermutation(lu_value, per_value, k, lu_row_)) {
continue;
}
// 2.2 major element x --> (1/x), get inplace origin lu matrix value.
T value = static_cast<T>(1.0 / GetPermutatedValue(lu_value, per_value, k, k));
// 2.3 change major col values
for (size_t i = k + 1; i < lu_row_; ++i) {
T y = static_cast<T>(GetPermutatedValue(lu_value, per_value, i, k) * value);
// set inplace new lu matrix value.
SetPermutatedValue(lu_value, per_value, i, k, y);
}
// 2.4 Gauss elimination core
for (size_t i = k + 1; i < lu_row_; ++i) {
for (size_t j = k + 1; j < lu_col_; ++j) {
T y =
static_cast<T>(GetPermutatedValue(lu_value, per_value, i, j) -
GetPermutatedValue(lu_value, per_value, i, k) * GetPermutatedValue(lu_value, per_value, k, j));
SetPermutatedValue(lu_value, per_value, i, j, y);
}
}
}
// 3. calculate final lu by permutation list
std::unordered_map<int, std::pair<int, bool>> pivots_map;
for (int i = 0; i < static_cast<int>(lu_row_); ++i) {
pivots_map[per_value[i]] = {i, false};
}
int pivots_count = 0;
for (const auto &pivot : pivots_map) {
pivots_count++;
int key = pivot.first;
int index = pivot.second.first;
bool is_visited = pivot.second.second;
if (is_visited || index == (pivots_count - 1)) {
continue;
}
T *lu_ori_row = lu_value + index * lu_col_;
T *lu_trans_row = lu_value + key * lu_col_;
// copy ori data to trans lu
(void)memcpy_s(lu_trans_wk, lu_col_ * sizeof(T), lu_ori_row, lu_col_ * sizeof(T));
// copy new data to ori data ptr
(void)memcpy_s(lu_ori_row, lu_col_ * sizeof(T), lu_trans_row, lu_col_ * sizeof(T));
// update pivot map
pivots_map[key] = {index, true};
// put ori data which stored in workspace to mapped new place
is_visited = pivots_map[index].second;
while (!is_visited) {
key = index;
index = pivots_map[key].first;
is_visited = pivots_map[key].second;
lu_ori_row = lu_value + index * lu_col_;
T *tmp_wk = lu_trans_wk;
lu_trans_wk = lu_ori_wk;
lu_ori_wk = tmp_wk;
// copy new ori data to trans workspace
(void)memcpy_s(lu_trans_wk, lu_col_ * sizeof(T), lu_ori_row, lu_col_ * sizeof(T));
// copy new data to ori data place
(void)memcpy_s(lu_ori_row, lu_col_ * sizeof(T), lu_ori_wk, lu_col_ * sizeof(T));
pivots_map[key] = {index, true};
}
}
// 4. calculate final permutation matrix
// for PA = LU get: base + row * permutation_row_ + col
// for A = PLU get: base + col * permutation_row_ + row
// here, we do A = PLU which is same as scipy.
size_t count = permutation_col_ * permutation_row_ * sizeof(int);
(void)memset_s(reinterpret_cast<void *>(permutation_value), count, 0, count);
for (size_t i = 0; i < pivots_row_; ++i) {
int position = per_value[i];
int *per_addr = permutation_value + position * permutation_row_ + i;
*per_addr = 1;
}
return true;
}
} // namespace kernel
} // namespace mindspore
| 38.333333 | 120 | 0.688406 | [
"shape",
"vector"
] |
4ff7300ab838e452a417b31c1a51513c7c948c89 | 4,754 | cc | C++ | homeworks/1DWaveAbsorbingBC/templates/1dwaveabsorbingbc.cc | kryo4096/NPDECODES | 3498c0e4abec6ba21447849ba2ddc9286c068ea1 | [
"MIT"
] | 15 | 2019-04-29T11:28:56.000Z | 2022-03-22T05:10:58.000Z | homeworks/1DWaveAbsorbingBC/templates/1dwaveabsorbingbc.cc | kryo4096/NPDECODES | 3498c0e4abec6ba21447849ba2ddc9286c068ea1 | [
"MIT"
] | 12 | 2020-02-29T15:05:58.000Z | 2022-02-21T13:51:07.000Z | homeworks/1DWaveAbsorbingBC/templates/1dwaveabsorbingbc.cc | kryo4096/NPDECODES | 3498c0e4abec6ba21447849ba2ddc9286c068ea1 | [
"MIT"
] | 26 | 2020-01-09T15:59:23.000Z | 2022-03-24T16:27:33.000Z | /**
* @file 1dwaveabsorbingbc.cc
* @brief NPDE homework "1DWaveAbsorbingBC" code
* @author Oliver Rietmann
* @date 08.04.2019
* @copyright Developed at ETH Zurich
*/
#include "1dwaveabsorbingbc.h"
#include <Eigen/Core>
#include <Eigen/SparseCore>
#include <Eigen/SparseLU>
#include <cmath>
#include <utility>
#include <vector>
namespace WaveAbsorbingBC1D {
constexpr double PI = 3.14159265358979323846;
// Boundary data on the right-hand side (x = 1)
double g(double t) { return 0 <= t && t <= PI ? std::sin(t) : 0.0; }
/**
* @brief Get the full (--> including both boundary points) Galerkin matrix A
* @param N number of spacial nodes, including x=0, but excluding x=1
* @param c speed of propagation
* @param h (spacial) meshwidth
* @return Full Galerkin matrix A of shape (N+1)x(N+1)
*/
/* SAM_LISTING_BEGIN_7 */
Eigen::SparseMatrix<double> getA_full(unsigned int N, double c, double h) {
std::vector<Eigen::Triplet<double>> triplets;
triplets.reserve(3 * (N + 1) - 2); // that many triplets needed
const double scale = c * c / h;
// store first row separately
triplets.push_back(Eigen::Triplet<double>(0, 0, scale));
triplets.push_back(Eigen::Triplet<double>(0, 1, -scale));
// loop over interior rows
for (unsigned i = 1; i < N; ++i) {
triplets.push_back(Eigen::Triplet<double>(i, i - 1, -scale));
triplets.push_back(Eigen::Triplet<double>(i, i, 2.0 * scale));
triplets.push_back(Eigen::Triplet<double>(i, i + 1, -scale));
}
// store last row separately
triplets.push_back(Eigen::Triplet<double>(N, N - 1, -scale));
triplets.push_back(Eigen::Triplet<double>(N, N, scale));
// Creat (N+1)x(N+1) sparse matrix in CRS format
Eigen::SparseMatrix<double> A(N + 1, N + 1);
A.setFromTriplets(triplets.begin(), triplets.end());
return A;
}
/* SAM_LISTING_END_7 */
/**
* @brief Get the full (--> including both boundary points) Galerkin matrix B
* @param N number of spacial nodes, including x=0, but excluding x=1
* @param c speed of propagation
* @return Full Galerkin matrix B of size (N+1)x(N+1)
*/
/* SAM_LISTING_BEGIN_8 */
Eigen::SparseMatrix<double> getB_full(unsigned int N, double c) {
Eigen::SparseMatrix<double> B(N + 1, N + 1);
// Just a single non-zero entry; we can afford to sete it directly
B.coeffRef(0, 0) = c;
return B;
}
/* SAM_LISTING_END_8 */
/**
* @brief Get the full (--> including both boundary points) Galerkin matrix M
* @param N number of spacial nodes, including x=0, but excluding x=1
* @param h (spacial) meshwidth
* @return Full Galerkin matrix M of size (N+1)x(N+1)
* Note that M is a diagonal matrix!
*/
/* SAM_LISTING_BEGIN_9 */
Eigen::SparseMatrix<double> getM_full(unsigned int N, double h) {
Eigen::SparseMatrix<double> M(N + 1, N + 1);
M.setIdentity(); // Supposed to be efficient
M *= h;
// Modify two entries; efficiency does not matter much
M.coeffRef(0, 0) = h / 2;
M.coeffRef(N, N) = h / 2;
return M;
}
/* SAM_LISTING_END_9 */
/* SAM_LISTING_BEGIN_1 */
Eigen::MatrixXd waveLeapfrogABC(double c, double T, unsigned int N,
unsigned int m) {
// N is also the number of cells of the mesh
double h = 1.0 / N;
// Obtain Galerkin matrices for truncated finite element space
// Note that the functions get*_full return the matrices for the full finite
// element space including the tent function located at x=1. Removing the last
// row and column of that matrix amounts to dropping that basis function.
// However, the efficiency of this block() operation in the case of sparse
// matrices is in doubt, in particular, since the result is assigned to
// another sparse matrix, which foils Eigen's expression template
// optimization. The use of "auto" would be highly advisable here!
Eigen::SparseMatrix<double> A = getA_full(N, c, h).block(0, 0, N, N);
Eigen::SparseMatrix<double> B = getB_full(N, c).block(0, 0, N, N);
Eigen::SparseMatrix<double> M = getM_full(N, h).block(0, 0, N, N);
// Matrix for returning solution
Eigen::MatrixXd R(m + 1, N + 1);
//====================
// Your code goes here
//====================
return R;
}
/* SAM_LISTING_END_1 */
/* SAM_LISTING_BEGIN_2 */
std::pair<Eigen::VectorXd, Eigen::VectorXd> computeEnergies(
const Eigen::MatrixXd &full_solution, double c, double tau) {
int m = full_solution.rows() - 1;
int N = full_solution.cols() - 1;
double h = 1.0 / N;
Eigen::SparseMatrix<double> A = getA_full(N, c, h);
Eigen::SparseMatrix<double> M = getM_full(N, h);
Eigen::VectorXd E_pot(m + 1);
Eigen::VectorXd E_kin(m);
//====================
// Your code goes here
//====================
return std::make_pair(E_pot, E_kin);
}
/* SAM_LISTING_END_2 */
} // namespace WaveAbsorbingBC1D
| 34.70073 | 80 | 0.666597 | [
"mesh",
"shape",
"vector"
] |
4ffc859acf6c0a904dd84fa0e59fe19452cd1601 | 58,507 | cpp | C++ | data/gki_navigation/channel_controller/src/channel_controller.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | data/gki_navigation/channel_controller/src/channel_controller.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | data/gki_navigation/channel_controller/src/channel_controller.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | #include "channel_controller/channel_controller.h"
#include "channel_controller/bresenham.h"
#include <pluginlib/class_list_macros.h>
#include <string>
#include <nav_msgs/Path.h>
#include <angles/angles.h>
#include <visualization_msgs/MarkerArray.h>
#include <kobuki_msgs/Sound.h>
#include <kobuki_msgs/Led.h>
#include <boost/foreach.hpp>
#include <std_msgs/Empty.h>
#include <algorithm>
#define forEach BOOST_FOREACH
namespace channel_controller
{
PLUGINLIB_EXPORT_CLASS(channel_controller::ChannelController, nav_core::BaseLocalPlanner);
ChannelController::ChannelController() : tf_(NULL), costmap_ros_(NULL), current_waypoint_(0), use_laser_(true), use_costmap_(true)
{
}
ChannelController::~ChannelController()
{
}
void ChannelController::initialize(std::string name,
tf::TransformListener* tf, costmap_2d::Costmap2DROS* costmap_ros)
{
tf_ = tf;
costmap_ros_ = costmap_ros;
state_ = CSFollowChannel;
safe_waypoint_state_ = SWSNone;
waiting_for_obstacles_start_time_ = ros::Time(0);
voronoi_.initializeEmpty(costmap_ros_->getCostmap()->getSizeInCellsX(),
costmap_ros_->getCostmap()->getSizeInCellsY(), true);
// Name is probably something like channel_controller::ChannelController
// And our param then should be ChannelController
size_t colon = name.find_last_of(":");
std::string class_name = name.substr(colon + 1);
if(colon == std::string::npos)
class_name = name;
ROS_INFO("Initializing ChannelController from ~/%s", class_name.c_str());
ros::NodeHandle nhPriv("~/" + class_name); // ~ = /move_base, our config should be in /move_base/name
ros::NodeHandle nh;
nhPriv.param("use_laser", use_laser_, true);
nhPriv.param("use_costmap", use_costmap_, true);
nhPriv.param("safe_waypoint_channel_width", safe_waypoint_channel_width_, 0.5);
nhPriv.param("safe_waypoint_channel_width_at_max_tv", safe_waypoint_channel_width_at_max_tv_, 0.5);
nhPriv.param("safe_channel_width", safe_channel_width_, 0.4);
nhPriv.param("channel_score_da", channel_score_da_, 1.0);
nhPriv.param("channel_score_dist", channel_score_dist_, 0.3);
nhPriv.param("max_channel_length", max_channel_length_, 3.0);
nhPriv.param("min_get_to_safe_dist_time", min_get_to_safe_dist_time_, 3.0);
nhPriv.param("max_get_to_safe_dist_time", max_get_to_safe_dist_time_, 10.0);
nhPriv.param("waypoint_reached_dist", waypoint_reached_dist_, 0.3);
nhPriv.param("waypoint_reached_dist_at_max_tv", waypoint_reached_dist_at_max_tv_, 0.3);
nhPriv.param("waypoint_reached_angle", waypoint_reached_angle_, 7.0);
nhPriv.param("goal_reached_dist", goal_reached_dist_, 0.1);
nhPriv.param("goal_reached_angle", goal_reached_angle_, 0.22);
nhPriv.param("min_tv", min_tv_, 0.1);
nhPriv.param("max_tv", max_tv_, 0.6);
nhPriv.param("min_rv", min_rv_, 0.0);
nhPriv.param("max_rv", max_rv_, 0.9);
nhPriv.param("min_inplace_rv", min_inplace_rv_, 0.1);
nhPriv.param("stopped_tv", stopped_tv_, 0.05);
nhPriv.param("stopped_rv", stopped_rv_, 0.1);
nhPriv.param("max_accel_tv", max_accel_tv_, 2.0);
nhPriv.param("max_accel_rv", max_accel_rv_, 1.5);
nhPriv.param("wait_for_obstacles_time", wait_for_obstacles_time_, -1.0);
nhPriv.param("no_progress_hard_clear_time", no_progress_hard_clear_time_, -1.0);
nhPriv.param("vis_max_dist", vis_max_dist_, 1.0);
nhPriv.param("visualize_voronoi", visualize_voronoi_, false);
ROS_INFO("use_laser: %d", use_laser_);
ROS_INFO("use_costmap: %d", use_costmap_);
ROS_INFO("safe_waypoint_channel_width: %f", safe_waypoint_channel_width_);
ROS_INFO("safe_waypoint_channel_width_at_max_tv: %f", safe_waypoint_channel_width_at_max_tv_);
ROS_INFO("safe_channel_width: %f", safe_channel_width_);
ROS_INFO("channel_score_da: %f", channel_score_da_);
ROS_INFO("channel_score_dist: %f", channel_score_dist_);
ROS_INFO("min_get_to_safe_dist_time: %f", min_get_to_safe_dist_time_);
ROS_INFO("max_get_to_safe_dist_time: %f", max_get_to_safe_dist_time_);
ROS_INFO("waypoint_reached_dist: %f", waypoint_reached_dist_);
ROS_INFO("waypoint_reached_dist_at_max_tv: %f", waypoint_reached_dist_at_max_tv_);
ROS_INFO("waypoint_reached_angle: %f", waypoint_reached_angle_);
ROS_INFO("goal_reached_dist: %f", goal_reached_dist_);
ROS_INFO("goal_reached_angle: %f", goal_reached_angle_);
ROS_INFO("min_tv: %f", min_tv_);
ROS_INFO("max_tv: %f", max_tv_);
ROS_INFO("min_rv: %f", min_rv_);
ROS_INFO("max_rv: %f", max_rv_);
ROS_INFO("min_inplace_rv: %f", min_inplace_rv_);
ROS_INFO("stopped_tv: %f", stopped_tv_);
ROS_INFO("stopped_rv: %f", stopped_rv_);
ROS_INFO("max_accel_tv: %f", max_accel_tv_);
ROS_INFO("max_accel_rv: %f", max_accel_rv_);
ROS_INFO("wait_for_obstacles_time: %f", wait_for_obstacles_time_);
ROS_INFO("no_progress_hard_clear_time: %f", no_progress_hard_clear_time_);
ROS_INFO("vis_max_dist: %f", vis_max_dist_);
ROS_INFO("visualize_voronoi: %d", visualize_voronoi_);
pub_markers_ = nhPriv.advertise<visualization_msgs::MarkerArray>("channel_markers", 1);
pub_status_marker_ = nhPriv.advertise<visualization_msgs::Marker>("drive_channel_status", 1);
pub_local_plan_ = nhPriv.advertise<nav_msgs::Path>("local_plan", 1);
pub_sound_ = nh.advertise<kobuki_msgs::Sound>("mobile_base/commands/sound", 1);
pub_led_ = nh.advertise<kobuki_msgs::Led>("mobile_base/commands/led1", 3);
pub_call_clear_ = nh.advertise<std_msgs::Empty>("/call_clear", 1);
sub_odom_ = nh.subscribe("odom", 2, &ChannelController::odometryCallback, this);
sub_laser_ = nh.subscribe("base_scan", 3, &ChannelController::laserCallback, this);
//updateVoronoi();
srand48(time(NULL));
}
bool ChannelController::updateVoronoi()
{
bool voronoi_ok = true;
costmap_ = costmap_ros_->getCostmap();
ROS_ASSERT(costmap_->getSizeInCellsX() == voronoi_.getSizeX());
ROS_ASSERT(costmap_->getSizeInCellsY() == voronoi_.getSizeY());
std::vector<IntPoint> obstacles;
if(use_costmap_) {
for(unsigned int x = 0; x < costmap_->getSizeInCellsX(); x++) {
for(unsigned int y = 0; y < costmap_->getSizeInCellsY(); y++) {
if(costmap_->getCost(x, y) >= costmap_2d::LETHAL_OBSTACLE) { // lethal and unknown
obstacles.push_back(IntPoint(x, y));
}
}
}
}
float validRangesFrac = 0.0;
if(use_laser_) {
double dt = (ros::Time::now() - last_laser_.header.stamp).toSec();
//printf("LASER AGE: %f\n", dt);
if(dt > 0.2) {
ROS_ERROR("%s: Laser too old - age is: %f", __func__, dt);
return false;
}
// get tf from laser to costmap/voronoi frame
tf::StampedTransform transform;
try {
if(!tf_->waitForTransform(costmap_ros_->getGlobalFrameID(),
last_laser_.header.frame_id, last_laser_.header.stamp, ros::Duration(0.1))) {
ROS_ERROR("Current Laser TF not available");
return false;
}
tf_->lookupTransform(costmap_ros_->getGlobalFrameID(),
last_laser_.header.frame_id, last_laser_.header.stamp, transform);
} catch(tf::TransformException & e) {
ROS_ERROR("%s: TF Error: %s", __func__, e.what());
return false;
}
unsigned int validRanges = 0; // to check if we got actual data, i.e. Go drive!
unsigned int endIdx = last_laser_.ranges.size();
endIdx = std::min(endIdx, 1000u); // start/end from index filter params
for(unsigned int i = 80; i < endIdx; i++) {
if(last_laser_.ranges[i] <= last_laser_.range_min || last_laser_.ranges[i] >= last_laser_.range_max)
continue;
validRanges++;
double da = last_laser_.angle_min + last_laser_.angle_increment * i;
tf::Vector3 pt(last_laser_.ranges[i] * cos(da), last_laser_.ranges[i] * sin(da), 0.0);
tf::Vector3 ptCostmap = transform * pt;
unsigned int ix, iy;
if(costmap_->worldToMap(ptCostmap.x(), ptCostmap.y(), ix, iy)) {
obstacles.push_back(IntPoint(ix, iy));
}
}
if(last_laser_.ranges.size() > 0)
validRangesFrac = (double)validRanges/(double)last_laser_.ranges.size();
}
// If there are no obstacles, wait as a precaution (assume there always will be _some_)
// Will stop in actual free space!
if(wait_for_obstacles_time_ > 0.0 && obstacles.empty() && validRangesFrac < 0.2) {
if(waiting_for_obstacles_start_time_ == ros::Time(0)) {
// first time we got in here
waiting_for_obstacles_start_time_ = ros::Time::now();
ROS_WARN("No obstacles in local costmap. Starting to wait for %fs",
wait_for_obstacles_time_);
kobuki_msgs::Sound warn_sound;
warn_sound.value = kobuki_msgs::Sound::ERROR;
//usleep(500*1000);
pub_sound_.publish(warn_sound);
voronoi_ok = false;
} else if(ros::Time::now() - waiting_for_obstacles_start_time_ <=
ros::Duration(wait_for_obstacles_time_)) {
ROS_WARN_THROTTLE(1.0, "No obstacles in local costmap. Waiting %.1fs/%.1fs before going.",
(ros::Time::now() - waiting_for_obstacles_start_time_).toSec(),
wait_for_obstacles_time_);
voronoi_ok = false;
} // else: over the time, but still no obstacles
// keep the start time active until we receive obstacles,
// but continue going anyways as the wait time is over
}
// obstacles found, reset waiting_for_obstacles_start_time_
if(!obstacles.empty())
waiting_for_obstacles_start_time_ = ros::Time(0);
voronoi_.exchangeObstacles(obstacles);
voronoi_.update(true);
//voronoi_.prune(); // FIXME This only does voronoi stuff, not distance related.
if(visualize_voronoi_)
visualizeVoronoi();
return voronoi_ok;
}
void ChannelController::visualizeVoronoi()
{
ROS_ASSERT(costmap_->getSizeInCellsX() == voronoi_.getSizeX());
ROS_ASSERT(costmap_->getSizeInCellsY() == voronoi_.getSizeY());
// nothing to send to no one
if(pub_markers_.getNumSubscribers() == 0)
return;
visualization_msgs::MarkerArray channelMarkers;
visualization_msgs::Marker voronoiMarker;
voronoiMarker.header.frame_id = costmap_ros_->getGlobalFrameID();
voronoiMarker.header.stamp = ros::Time(0);
voronoiMarker.ns = "voronoi";
voronoiMarker.id = 0;
voronoiMarker.type = visualization_msgs::Marker::SPHERE_LIST;
voronoiMarker.action = visualization_msgs::Marker::ADD;
voronoiMarker.pose.orientation.w = 1.0;
voronoiMarker.scale.x = costmap_->getResolution() * sqrt(2.0);
voronoiMarker.scale.y = costmap_->getResolution() * sqrt(2.0);
voronoiMarker.scale.z = costmap_->getResolution() * sqrt(2.0);
voronoiMarker.frame_locked = false;
geometry_msgs::Point cellPoint;
cellPoint.z = - costmap_->getResolution() * sqrt(2.0)/2.0;
std_msgs::ColorRGBA cellColor;
cellColor.a = 1.0;
for(unsigned int x = 0; x < costmap_->getSizeInCellsX(); x++) {
for(unsigned int y = 0; y < costmap_->getSizeInCellsY(); y++) {
float dist = voronoi_.getDistance(x, y);
dist *= costmap_->getResolution(); // now in meters
costmap_->mapToWorld(x, y, cellPoint.x, cellPoint.y);
voronoiMarker.points.push_back(cellPoint);
if(dist == -INFINITY) {
cellColor.r = 1.0;
cellColor.g = 0.0;
cellColor.b = 1.0;
} else if(dist == INFINITY) {
cellColor.r = 0.0;
cellColor.g = 1.0;
cellColor.b = 0.0;
} else {
if(dist > vis_max_dist_) {
cellColor.r = cellColor.g = cellColor.b = 1.0;
} else {
// make those slightly darker then max dist to distinguish
// vis max dist regions
cellColor.r = cellColor.g = cellColor.b = 0.9 * dist / vis_max_dist_;
}
}
voronoiMarker.colors.push_back(cellColor);
}
}
channelMarkers.markers.push_back(voronoiMarker);
pub_markers_.publish(channelMarkers);
}
bool ChannelController::isGoalReached()
{
if(ros::Time::now() - last_odom_.header.stamp > ros::Duration(0.5)) {
ROS_ERROR_THROTTLE(1.0, "isGoalReached:: Last odom is too old: %f - not at goal.",
(ros::Time::now() - last_odom_.header.stamp).toSec());
return false;
}
double cur_tv = last_odom_.twist.twist.linear.x;
double cur_rv = last_odom_.twist.twist.angular.z;
if(current_waypoint_ >= global_plan_.size() &&
fabs(cur_tv) < stopped_tv_ && fabs(cur_rv) < 2.0*min_inplace_rv_) {
ROS_INFO("ChannelController: Goal Reached!");
kobuki_msgs::Sound sound;
sound.value = kobuki_msgs::Sound::CLEANINGEND;
pub_sound_.publish(sound);
return true;
} else {
//ROS_INFO("Not at goal. At wp %d/%zu vel %f %f", current_waypoint_, global_plan_.size(),
// cur_tv, cur_rv);
}
return false;
}
bool ChannelController::setPlan(const std::vector<geometry_msgs::PoseStamped> & plan)
{
// check if the new plan has the same goal
bool sameGoal = false;
if(!global_plan_.empty() && !plan.empty()) {
geometry_msgs::PoseStamped currentGoal = global_plan_.back();
geometry_msgs::PoseStamped newGoal = plan.back();
if(currentGoal.header.frame_id == newGoal.header.frame_id) { // ignore time for fixed frames
tf::Pose currentGoalPose;
tf::Pose newGoalPose;
tf::poseMsgToTF(currentGoal.pose, currentGoalPose);
tf::poseMsgToTF(newGoal.pose, newGoalPose);
tf::Pose relPose = currentGoalPose.inverseTimes(newGoalPose);
if(relPose.getOrigin().length() < 0.05 &&
fabs(tf::getYaw(relPose.getRotation())) < angles::from_degrees(5.0)) {
sameGoal = true;
}
}
}
global_plan_ = plan;
current_waypoint_ = 0;
if(false && sameGoal && state_ == CSGetToSafeWaypointDist) {
ROS_WARN("New plan for same goal - keeping state CSGetToSafeWaypointDist");
state_ = CSGetToSafeWaypointDist;
} else {
state_ = CSFollowChannel;
}
if(!sameGoal) {
last_progress_time_ = ros::Time::now();
}
// localize now to verify this makes sense somehow and return upon that.
return localizeGlobalPlan(current_waypoint_);
}
bool ChannelController::currentWaypointReached() const
{
if(local_plan_.empty())
return true;
tf::Stamped<tf::Pose> robot_pose;
if(!costmap_ros_->getRobotPose(robot_pose))
return false;
tf::Stamped<tf::Pose> currentWaypoint = local_plan_.front();
tf::Pose toWaypoint = robot_pose.inverseTimes(currentWaypoint);
double cur_tv = last_odom_.twist.twist.linear.x;
double distThreshold = waypoint_reached_dist_ + (waypoint_reached_dist_at_max_tv_ - waypoint_reached_dist_) *
straight_up(cur_tv, min_tv_, max_tv_);
double angleThreshold = waypoint_reached_angle_;
if(local_plan_.size() == 1) { // only 1 wp left -> goal wp
distThreshold = goal_reached_dist_;
if((ros::Time::now() - goal_turn_start_time_) < ros::Duration(5.0)) {
angleThreshold = goal_reached_angle_/2.0;
} else {
angleThreshold = goal_reached_angle_;
}
}
if(state_ != CSGoalTurn) {
// Setting state to CSGoalTurn determined that this
// already was true once, from then on we don't care
// (latched goal approach)
// This must not be checked in that case as CSGoalTurn
// only turns to goal, but never approaches again.
if(toWaypoint.getOrigin().length() > distThreshold)
return false;
}
if(fabs(tf::getYaw(toWaypoint.getRotation())) > angleThreshold)
return false;
return true;
}
bool ChannelController::localizeGlobalPlan(unsigned int start_index)
{
// FIXME test this with different frames for map/odom
nav_msgs::Path localPlanMsg;
localPlanMsg.header.stamp = ros::Time(0);
localPlanMsg.header.frame_id = costmap_ros_->getGlobalFrameID();
local_plan_.clear();
if(global_plan_.empty()) {
pub_local_plan_.publish(localPlanMsg);
return false;
}
tf::StampedTransform transform;
// purposely ignoreing the global_plan_.header.stamp here as we assume that the global_plan_
// frame is a fixed frame and the controller's something like odom.
// We thus want the most current transformation into our frame for the global_plan_.
try {
tf_->lookupTransform(costmap_ros_->getGlobalFrameID(),
global_plan_.front().header.frame_id, ros::Time(0), transform);
} catch(tf::TransformException & e) {
ROS_ERROR("%s: TF Error: %s", __func__, e.what());
pub_local_plan_.publish(localPlanMsg);
return false;
}
// we'll assume all frame_id are the same in global plan
for(unsigned int i = start_index; i < global_plan_.size(); i++) {
tf::Pose global_pose;
tf::poseMsgToTF(global_plan_.at(i).pose, global_pose);
tf::Stamped<tf::Pose> local_pose;
local_pose.frame_id_ = costmap_ros_->getGlobalFrameID();
local_pose.stamp_ = transform.stamp_;
local_pose.setData(transform * global_pose);
local_plan_.push_back(local_pose);
if(pub_local_plan_.getNumSubscribers() > 0) {
geometry_msgs::PoseStamped local_pose_msg;
tf::poseStampedTFToMsg(local_pose, local_pose_msg);
localPlanMsg.poses.push_back(local_pose_msg);
}
}
pub_local_plan_.publish(localPlanMsg);
return true;
}
DriveChannel ChannelController::computeChannel(tf::Pose from_pose, tf::Pose to_pose, double clearance_dist) const
{
ROS_ASSERT(costmap_->getSizeInCellsX() == voronoi_.getSizeX());
ROS_ASSERT(costmap_->getSizeInCellsY() == voronoi_.getSizeY());
DriveChannel channel;
channel.from_pose_ = from_pose;
channel.min_dist_ = HUGE_VAL;
int start_x, start_y;
int target_x, target_y;
costmap_->worldToMapNoBounds(from_pose.getOrigin().x(), from_pose.getOrigin().y(),
start_x, start_y);
costmap_->worldToMapNoBounds(to_pose.getOrigin().x(), to_pose.getOrigin().y(),
target_x, target_y);
int trace_x = start_x;
int trace_y = start_y;
for(Bresenham b(start_x, start_y, target_x, target_y); b.hasNext(); b.advance()) {
if(b.cur_x() < 0 || b.cur_y() < 0)
break;
if(b.cur_x() >= (int)voronoi_.getSizeX() || b.cur_y() >= (int)voronoi_.getSizeY())
break;
float dist = voronoi_.getDistance(b.cur_x(), b.cur_y());
dist *= costmap_->getResolution();
if(dist == -INFINITY) // +INFINITY Ok
break;
if(dist < clearance_dist)
break;
if(dist < channel.min_dist_)
channel.min_dist_ = dist;
trace_x = b.cur_x();
trace_y = b.cur_y();
}
double dx = costmap_->getResolution() * (trace_x - start_x);
double dy = costmap_->getResolution() * (trace_y - start_y);
tf::Pose deltaPose = from_pose.inverseTimes(to_pose);
tf::Pose deltaChannelLength(deltaPose.getRotation(),
deltaPose.getOrigin().normalized() * hypot(dx, dy));
channel.to_pose_ = from_pose * deltaChannelLength;
return channel;
}
visualization_msgs::Marker ChannelController::createChannelMarkers(
const std::vector<DriveChannel> & channels, double min_good_dist,
int best_idx) const
{
visualization_msgs::Marker channelMarker;
channelMarker.header.stamp = ros::Time(0);
channelMarker.header.frame_id = costmap_ros_->getGlobalFrameID();
channelMarker.ns = "channels";
channelMarker.id = 2;
channelMarker.type = visualization_msgs::Marker::LINE_LIST;
channelMarker.action = visualization_msgs::Marker::ADD;
channelMarker.pose.orientation.w = 1.0;
channelMarker.scale.x = 0.01;
channelMarker.lifetime = ros::Duration(0);
channelMarker.frame_locked = false;
int index = 0;
forEach(const DriveChannel & channel, channels) {
// rotation of 90 for half of width and the end to show width
double dir = channel.direction();
double min_dist = channel.min_dist_;
if(min_dist > 2.0 * std::max(costmap_->getSizeInMetersX(), costmap_->getSizeInMetersY())) {
min_dist = 2.0 * std::max(costmap_->getSizeInMetersX(), costmap_->getSizeInMetersY());
}
tf::Vector3 half_width(0.0, min_dist, 0.0);
tf::Vector3 half_width_other(0.0, -min_dist, 0.0);
tf::Pose side_offset(tf::createQuaternionFromYaw(0.0), half_width);
tf::Pose side_offset_other(tf::createQuaternionFromYaw(0.0), half_width_other);
tf::Pose channel_dir(tf::createQuaternionFromYaw(dir));
tf::Pose z = tf::Pose(channel.from_pose_.getRotation()) * channel_dir * side_offset;
tf::Pose z2 = tf::Pose(channel.from_pose_.getRotation()) * channel_dir * side_offset_other;
geometry_msgs::Point pt;
pt.x = channel.from_pose_.getOrigin().x();
pt.y = channel.from_pose_.getOrigin().y();
pt.z = 0.0;
channelMarker.points.push_back(pt);
//ROS_INFO_STREAM("X CHANNEL TO " << pt << " LENGTH " << channel.length());
pt.x = channel.to_pose_.getOrigin().x();
pt.y = channel.to_pose_.getOrigin().y();
channelMarker.points.push_back(pt);
if(channel.length() > 0) {
pt.x = channel.to_pose_.getOrigin().x() + z2.getOrigin().x();
pt.y = channel.to_pose_.getOrigin().y() + z2.getOrigin().y();
channelMarker.points.push_back(pt);
pt.x = channel.to_pose_.getOrigin().x() + z.getOrigin().x();
pt.y = channel.to_pose_.getOrigin().y() + z.getOrigin().y();
channelMarker.points.push_back(pt);
}
std_msgs::ColorRGBA col;
col.r = 0.7;
col.g = 0.0;
col.b = 0.0;
col.a = 1.0;
if(channel.length() >= min_good_dist) {
col.r = 0.0;
col.g = 0.7;
col.b = 0.0;
}
if(index == best_idx) {
col.r = 0.0;
col.g = 0.0;
col.b = 1.0;
}
channelMarker.colors.push_back(col);
channelMarker.colors.push_back(col);
if(channel.length() > 0) {
channelMarker.colors.push_back(col);
channelMarker.colors.push_back(col);
}
index++;
}
return channelMarker;
}
visualization_msgs::Marker ChannelController::createPoseMarker(const tf::Pose & pose,
double r, double g, double b,
const std::string & ns, int id) const
{
visualization_msgs::Marker poseMarker;
poseMarker.header.stamp = ros::Time(0);
poseMarker.header.frame_id = costmap_ros_->getGlobalFrameID();
poseMarker.ns = ns;
poseMarker.id = id;
poseMarker.type = visualization_msgs::Marker::SPHERE;
poseMarker.action = visualization_msgs::Marker::ADD;
tf::poseTFToMsg(pose, poseMarker.pose);
poseMarker.scale.x = 0.1;
poseMarker.scale.y = 0.1;
poseMarker.scale.z = 0.1;
poseMarker.color.r = r;
poseMarker.color.g = g;
poseMarker.color.b = b;
poseMarker.color.a = 1.0;
poseMarker.lifetime = ros::Duration(0);
poseMarker.frame_locked = false;
return poseMarker;
}
double ChannelController::straight_up(double x, double a, double b) const
{
// linearly go up from 0 to 1 between a and b
if(x <= a)
return 0.0;
if(x >= b)
return 1.0;
return (x - a)/(b - a);
}
double ChannelController::straight_down(double x, double a, double b) const
{
// linearly go down from 1 to 0 between a and b
if(x <= a)
return 1.0;
if(x >= b)
return 0.0;
return (b - x)/(b - a);
}
void ChannelController::odometryCallback(const nav_msgs::Odometry & odom)
{
last_odom_ = odom;
}
void ChannelController::laserCallback(const sensor_msgs::LaserScan & laser)
{
last_laser_ = laser;
}
void ChannelController::limitTwist(geometry_msgs::Twist & cmd_vel) const
{
// Whats the point of this fn: Basically prevent the impossible
// When we set a tv/rv traj, we still drive on that even if one
// of the values doesn't work
// just that we drive on it slower.
// That's what the result should be. Must make sure that always happens, especially
// when avoiding obstacles/braking
// Very important for collision avoidance.
// FIXME Zerg Hack, this should be done properly
// assuming no max_accel_rv
//
// If tv is small, we are either fast and braking hard
// or we are slow and accelerating
// In both cases, there is no need to limit.
if(fabs(cmd_vel.linear.x) < 2.0 * min_tv_) {
return;
}
double cur_tv = last_odom_.twist.twist.linear.x;
double cur_rv = last_odom_.twist.twist.angular.z;
if(cur_tv * cmd_vel.linear.x < 0) {
if(fabs(cur_tv) < min_tv_) { // special case near zero, no error
cur_tv = 0.0;
} else {
ROS_ERROR_THROTTLE(1.0, "%s: TV changes sign, cur: %f, target: %f - cannot handle this, not limiting!",
__func__, cur_tv, cmd_vel.linear.x);
}
return;
}
// TODO dead reckoning option
//double dt = (ros::Time::now() - last_cmd_vel_time_).toSec(); // estimated dt for commands
double dt = (ros::Time::now() - last_odom_.header.stamp).toSec(); // estimated dt for commands
if(dt < 0) {
ROS_ERROR_THROTTLE(1.0, "%s: Got odometry from the future, dt: %f, setting 0",
__func__, dt);
}
// If we haven't send commands for a while, we'll get an initial "kick"
// with a large dt, this should be OK
double dx_max = max_accel_tv_ * dt;
double dth_max = max_accel_rv_ * dt;
// FIXME later: stopping for obstacle? -> test and increase accel limits or not limit
// if the channel is too short.
double twist_scale = 1.0;
if(fabs(cmd_vel.linear.x - cur_tv) > dx_max) {
twist_scale = dx_max/fabs(cmd_vel.linear.x - cur_tv);
}
//ROS_DEBUG("twist_scale tv: %f ", twist_scale);
if(max_accel_rv_ > 0 && fabs(cmd_vel.angular.z - cur_rv) > dth_max) {
twist_scale = std::min(twist_scale, dth_max/fabs(cmd_vel.angular.z - cur_rv));
}
//ROS_DEBUG("twist_scale after rv: %f ", twist_scale);
// scale both for same trajectory
if(twist_scale < 1.0) {
// braking = we set a lower absolute speed OR we even reverse the speed
if(fabs(cmd_vel.linear.x) < fabs(cur_tv) || (cmd_vel.linear.x * cur_tv) < 0) {
ROS_DEBUG_THROTTLE(1.0, "Not scaling twist to accel limits as we are braking: old tv: %f target tv: %f", cur_tv, cmd_vel.linear.x);
} else {
geometry_msgs::Twist new_cmd_vel = cmd_vel;
new_cmd_vel.linear.x = cur_tv + twist_scale *
(cmd_vel.linear.x - cur_tv);
// We need to get as close to the target traj given by tv/rv as possible
double ideal_scaled_rv = new_cmd_vel.linear.x/cmd_vel.linear.x * cmd_vel.angular.z;
if(max_accel_rv_ <= 0) {
new_cmd_vel.angular.z = ideal_scaled_rv;
} else {
// how close can we get
if(fabs(ideal_scaled_rv - cur_rv) > dth_max) { // can't reach, take largest step
if(ideal_scaled_rv < cur_rv) {
new_cmd_vel.angular.z = cur_rv - dth_max;
} else {
new_cmd_vel.angular.z = cur_rv + dth_max;
}
} else {
new_cmd_vel.angular.z = ideal_scaled_rv;
}
}
//new_cmd_vel.angular.z = cur_rv + twist_scale *
// (cmd_vel.angular.z - cur_rv);
// //twist_scale * cmd_vel.angular.z;
// never scale at/near min vels
// never scale to/near min vels
//// check mins
//// FIXME Not relevant when scaling here?
//// -> we'd have a large delta anyways...
//if(fabs(cmd_vel.linear.x) < stopped_tv_) {
// if(fabs(new_cmd_vel.angular.z) < min_inplace_rv_) {
// new_cmd_vel.angular.z = sign(cmd_vel.angular.z) * min_inplace_rv_;
// }
//} else {
// if(fabs(new_cmd_vel.linear.x) < min_tv_)
// new_cmd_vel.linear.x = sign(cmd_vel.linear.x) * min_tv_;
// if(fabs(new_cmd_vel.angular.z) < min_rv_)
// new_cmd_vel.angular.z = sign(cmd_vel.angular.z) * min_rv_;
//}
/*ROS_DEBUG("%s: dt: %f, dx_max: %f, dth_max: %f", __func__,
dt, dx_max, dth_max);
ROS_DEBUG("%s: cur tv: %f target tv: %f, cur rv: %f, target rv: %f", __func__,
cur_tv, cmd_vel.linear.x, cur_rv, cmd_vel.angular.z);*/
ROS_DEBUG("%s: Scaling cmd vel from %f, %f -> %f %f", __func__,
cmd_vel.linear.x, cmd_vel.angular.z,
new_cmd_vel.linear.x, new_cmd_vel.angular.z);
cmd_vel = new_cmd_vel;
}
}
}
bool ChannelController::computeVelocityForChannel(const DriveChannel & channel, geometry_msgs::Twist & cmd_vel, ScopedVelocityStatus & status) const
{
// TODO make sure that channel length are until free and not until waypoint
// Maybe only if there is no more waypoints near it limit for corner racing
// BUT maybe we just stop quickly???
// goal approach is scaled with speed already
// TODO final speed advise is safty
// 2. think about channel selection as in what do we want/need
// a) for close quarters
// b) for high speed open area (later, also need to check how global plans look there)
// c) dont tune too much towards global plan - dynamic obst are NOT in there and the dist counts
// -- more: think about why channels with dist arent on global plan, can we pause and observe?
// 3. redo speed selection with fast and safe
ROS_ASSERT(!local_plan_.empty());
cmd_vel = geometry_msgs::Twist(); // init to 0
double channel_dir = channel.direction();
double channel_length = channel.length();
double channel_width = 2.0 * channel.min_dist_;
// the channel should have originated at robot_pose
tf::Pose relToWp = channel.from_pose_.inverseTimes(local_plan_.front());
// FIXME later: maybe look ahead if next waypoints are on the same channels: GO!
// channel way different, stop first, then turn in place
double cur_tv = last_odom_.twist.twist.linear.x;
double cur_rv = last_odom_.twist.twist.angular.z;
if(fabs(channel_dir) > angles::from_degrees(45)) {
//double cur_rv = last_odom_.twist.twist.angular.z;
if(fabs(cur_tv) < stopped_tv_) {
// Just turn full. We're stopped and way in the wrong direction
cmd_vel.angular.z = max_rv_ * sign(channel_dir);
status.setChannelTurnToChannel(channel_dir, cur_tv, cur_rv);
} else { // else: stop (0)
status.setChannelStopToTurn(channel_dir, cur_tv, cur_rv);
}
return true;
}
// kinda steer towards channel
cmd_vel.angular.z = sign(channel_dir) * (min_rv_ + (max_rv_ - min_rv_) *
straight_up(fabs(channel_dir), angles::from_degrees(0.0), angles::from_degrees(60.0)));
// FIXME later use width as main scaling? relate to robot?
// TODO align those to max values with time
// speed up if there is space
double channel_length_tv_scale = straight_up(channel_length, 0.3, 2.0);
// go slower forward if we aren't pointing in the right direction
double bad_direction_tv_scale =
straight_down(fabs(channel_dir), angles::from_degrees(10.0), angles::from_degrees(60.0));
// go slower when narrow
tf::Pose zero;
bool in_bounds = true;
double around_dist = getDistanceAtPose(zero, &in_bounds);
double close_to_obstacles_scale = 1;
if (in_bounds)
{
close_to_obstacles_scale = 0.33 + 0.66 * straight_up(around_dist, 0.3, 0.6);
}
double channel_width_tv_scale = straight_up(channel_width,
safe_waypoint_channel_width_, safe_waypoint_channel_width_at_max_tv_);
// for now ignore close to wp unless goal.
double close_to_goal_tv_scale = 1.0;
double close_to_goal_rv_scale = 1.0;
if(local_plan_.size() == 1) { // going for goal
double dist_to_wp = relToWp.getOrigin().length();
double angle_to_wp = atan2(relToWp.getOrigin().y(), relToWp.getOrigin().x());
close_to_goal_tv_scale = straight_up(dist_to_wp,
2.0 * goal_reached_dist_, 5.0 * goal_reached_dist_);
close_to_goal_rv_scale = straight_up(fabs(angle_to_wp),
goal_reached_angle_, 5.0 * goal_reached_angle_);
}
std::string tv_scale_reason = "none";
double tv_scale = bad_direction_tv_scale;
if(tv_scale < 1.0)
tv_scale_reason = "bad_direction";
tv_scale = std::min(tv_scale, channel_length_tv_scale);
if(tv_scale == channel_length_tv_scale)
tv_scale_reason = "channel_length";
tv_scale = std::min(tv_scale, channel_width_tv_scale);
if(tv_scale == channel_width_tv_scale)
tv_scale_reason = "channel_width";
tv_scale = std::min(tv_scale, close_to_obstacles_scale);
if(tv_scale == close_to_goal_tv_scale)
tv_scale_reason = "close_to_obstacles";
tv_scale = std::min(tv_scale, close_to_goal_tv_scale);
if(tv_scale == close_to_goal_tv_scale)
tv_scale_reason = "close_to_goal";
if(tv_scale >= 0.99)
tv_scale_reason = "none";
std::string rv_scale_reason = "none";
double rv_scale = close_to_goal_rv_scale;
if(rv_scale < 1.0)
rv_scale_reason = "close_to_goal";
if(rv_scale >= 0.99)
rv_scale_reason = "none";
// TODO the relationship and scaling for rv/tv should more use
// absolute values matched to the max values
// not just a factor of the max, i.e. high max rv will turn to rapidly
// when tv max isn't that high, i.e. the combination isn't good.
cmd_vel.linear.x = min_tv_ + (max_tv_ - min_tv_) * tv_scale;
cmd_vel.angular.z *= 0.2 + 0.8 * rv_scale;
// Let's make sure we're not below the min values
double tv_min_fact = fabs(cmd_vel.linear.x)/min_tv_;
// If we're too slow ahead is only OK if we're at least turning
// somewhat quickly
if(tv_min_fact < 1.0 && fabs(cmd_vel.angular.z) < angles::from_degrees(10)) {
// scale up so we get at least one higher.
cmd_vel.linear.x /= tv_min_fact;
cmd_vel.angular.z /= tv_min_fact;
}
if(fabs(cmd_vel.linear.x) < stopped_tv_ && fabs(cmd_vel.angular.z) < min_inplace_rv_) {
ROS_DEBUG("%s: tv almost 0 and rv below min_inplace_rv_ -> increasing rv", __func__);
cmd_vel.angular.z = sign(cmd_vel.angular.z) * min_inplace_rv_;
cmd_vel.linear.x = sign(cmd_vel.linear.x) * stopped_tv_; // drive at least stopped tv
}
//limitTwist(cmd_vel);
status.setChannelFollowChannel(channel_dir, cur_tv, cur_rv, tv_scale_reason, rv_scale_reason);
return true;
}
void ChannelController::computeVelocityForSafeChannel(
const DriveChannel & channel,
geometry_msgs::Twist & cmd_vel, ScopedVelocityStatus & status,
bool turn_in) const
{
cmd_vel = geometry_msgs::Twist(); // init to 0
double channel_dir = channel.direction();
bool backwards = false;
// check if channel is behind us - go backwards
if(fabs(channel_dir) > angles::from_degrees(90)) {
backwards = true;
// substract 90 deg to get equivalent forward channel
channel_dir = sign(channel_dir) * (fabs(channel_dir) - angles::from_degrees(90.0));
// switch dir as we're going backwards
channel_dir *= -1.0;
}
if(!turn_in)
channel_dir *= -1.0;
cmd_vel.linear.x = min_tv_;
if(backwards)
cmd_vel.linear.x *= -1.0;
// kinda steer towards channel slowly
cmd_vel.angular.z = sign(channel_dir) * (min_rv_ + 0.1 * (max_rv_ - min_rv_) *
straight_up(fabs(channel_dir), angles::from_degrees(10.0), angles::from_degrees(90.0)));
}
bool ChannelController::handleGoalTurn(geometry_msgs::Twist & cmd_vel,
const tf::Stamped<tf::Pose> & robotPose, double distToTarget,
ScopedVelocityStatus & status)
{
if(state_ != CSGoalTurn) {
if(local_plan_.size() != 1) // either already goal reached or not approach goal wp
return false;
if(distToTarget > goal_reached_dist_) // approaching goal but not near enough yet
return false;
goal_turn_start_time_ = ros::Time::now();
}
state_ = CSGoalTurn; // latch this once we're in here - stay
// we are at the goal point
// as currentWaypointReached didn't trigger: we're not turned to it
tf::Stamped<tf::Pose> currentWaypoint = local_plan_.front();
tf::Pose toWaypoint = robotPose.inverseTimes(currentWaypoint);
double da = angles::normalize_angle(tf::getYaw(toWaypoint.getRotation()));
double curTv = last_odom_.twist.twist.linear.x;
double curRv = last_odom_.twist.twist.angular.z;
if(fabs(curTv) < stopped_tv_) {
cmd_vel.angular.z = sign(da) * (min_inplace_rv_ + (max_rv_ - min_inplace_rv_) *
straight_up(fabs(da), angles::from_degrees(10.0), angles::from_degrees(90.0)));
status.setAtGoalPosTurnToGoal(da, curTv, curRv);
} else { // else: stop (0)
status.setAtGoalPosStopToTurn(da, curTv, curRv);
}
return true;
}
double ChannelController::getDistanceAtPose(const tf::Pose & pose, bool* in_bounds) const
{
// determine current dist
int pose_x, pose_y;
costmap_->worldToMapNoBounds(pose.getOrigin().x(), pose.getOrigin().y(),
pose_x, pose_y);
if(pose_x < 0 || pose_y < 0 ||
pose_x >= (int)voronoi_.getSizeX() || pose_y >= (int)voronoi_.getSizeY()) {
if(in_bounds == NULL) {
// only warn if in_bounds isn't checked externally
ROS_WARN_THROTTLE(1.0, "%s: Pose out of voronoi bounds (%.2f, %.2f) = (%d, %d)", __func__,
pose.getOrigin().x(), pose.getOrigin().y(), pose_x, pose_y);
} else {
*in_bounds = false;
}
return 0.0;
}
if(in_bounds) {
*in_bounds = true;
}
float dist = voronoi_.getDistance(pose_x, pose_y);
dist *= costmap_->getResolution();
return dist;
}
int ChannelController::getToSafeWaypoint(geometry_msgs::Twist & cmd_vel,
const tf::Pose & robotPose, const tf::Pose & relativeTarget,
ScopedVelocityStatus & status)
{
if(state_ != CSGetToSafeWaypointDist) // we're not active
return 0;
ros::Duration activeTime = ros::Time::now() - get_to_safe_waypoint_start_time_;
if(activeTime > ros::Duration(max_get_to_safe_dist_time_))
return -1;
// determine current dist
bool pose_in_bounds;
double dist = getDistanceAtPose(robotPose, &pose_in_bounds);
if(!pose_in_bounds) {
ROS_ERROR("%s: Robot pose not in bounds", __func__); // shouldn't happen
return -1;
}
// stay active if activeTime < min_get_to_safe_dist_time_ or
// we're not at safe waypoint dist
if(dist >= safe_waypoint_channel_width_/2.0 &&
activeTime >= ros::Duration(min_get_to_safe_dist_time_)) {
// out of obst and executed long enough -> we're done
state_ = CSFollowChannel;
return -2;
}
// actual behavior - choose channels.
std::vector<DriveChannel> safe_channels = computeChannels(robotPose, relativeTarget,
safe_channel_width_/2.0);
if(safe_channels.empty()) {
ROS_ERROR_THROTTLE(1.0, "Could find no safe_channels - recovery needed");
return -1;
}
int best_idx = -1;
if(safe_waypoint_state_ == SWSBestChannel)
best_idx = evaluateSafeChannels(safe_channels, false);
else if(safe_waypoint_state_ == SWSBestBackwardsChannelTurnIn ||
safe_waypoint_state_ == SWSBestBackwardsChannelTurnOut)
best_idx = evaluateSafeChannels(safe_channels, true);
if(best_idx < 0) {
ROS_ERROR_THROTTLE(1.0, "Could not find best safe channel");
return -1;
}
visualization_msgs::MarkerArray channelMarkers;
channelMarkers.markers.push_back(createChannelMarkers(safe_channels, 0.0, best_idx));
pub_markers_.publish(channelMarkers);
if(safe_waypoint_state_ == SWSBestChannel ||
safe_waypoint_state_ == SWSBestBackwardsChannelTurnIn)
computeVelocityForSafeChannel(safe_channels[best_idx], cmd_vel, status, true);
else if(safe_waypoint_state_ == SWSBestBackwardsChannelTurnOut)
computeVelocityForSafeChannel(safe_channels[best_idx], cmd_vel, status, false);
status.setGetToSafeWaypoint(dist, activeTime.toSec(), safe_waypoint_state_);
return 1;
}
std::vector<DriveChannel> ChannelController::computeChannels(const tf::Pose & robotPose,
const tf::Pose & relativeTarget, double minDist) const
{
std::vector<DriveChannel> channels;
for(double da = -M_PI; da <= M_PI - angles::from_degrees(5.0); da += angles::from_degrees(5.0)) {
tf::Pose rotDir(tf::createQuaternionFromYaw(da));
// point in da, along up to the whole costmap length
tf::Pose relativeTargetDir(relativeTarget.getRotation(),
relativeTarget.getOrigin().normalized() *
max_channel_length_);
tf::Pose rotTarget = robotPose * rotDir * relativeTargetDir;
DriveChannel channel = computeChannel(robotPose, rotTarget, minDist);
channel.da_ = da;
if(channel.length() > 0)
channels.push_back(channel);
}
return channels;
}
double ChannelController::computeChannelScore(double da, double dist) const
{
// Scoring is based on da and min_dist:
// small da + small dist
// - Score by dist and a bit da (already there keep from obst + steer)
// small da + large dist
// - Score by dist and a bit da (already there keep from obst + steer)
// large da + small dist
// - Score by da (try to get there first)
// large da + large dist
// - Score by da (try to get there first)
// => Make this a smooth transition
double da_score = 0.5 * (cos(fabs(da)) + 1.0); // [0..1] based on cos -> 1.0 for da = 0.0
//// keeping dist_score influence very conservative for now.
//// A 20% wider channel gets a bit more score.
//double dist_score = straight_up(dist, safe_channel_width_/2.0, 1.2 * safe_waypoint_channel_width_/2.0);
double dist_score = straight_up(dist, safe_waypoint_channel_width_/2.0, safe_waypoint_channel_width_at_max_tv_/2.0);
double score = channel_score_da_ * da_score + channel_score_dist_ * dist_score;
return score;
}
int ChannelController::evaluateChannels(const std::vector<DriveChannel> & channels,
double distToTarget) const
{
int best_idx = -1;
double best_score = -1.0;
ROS_DEBUG("dist to target is: %f", distToTarget);
for(unsigned int channel_idx = 0; channel_idx < channels.size(); channel_idx++) {
const DriveChannel & channel = channels.at(channel_idx);
double da = channel.da_;
if(fabs(da) > angles::from_degrees(90.0)) {
continue;
}
double dist = channel.min_dist_;
if(channel.length() >= distToTarget) { // valid
//ROS_INFO("Valid channel found with da %f at %zu", da, channels.size() - 1);
double score = computeChannelScore(da, dist);
if(score > best_score) {
best_score = score;
best_idx = channel_idx;
//ROS_INFO("Better channel found with da %f at %d", best_da, best_idx);
}
}
}
//if(best_idx < 0) {
// ROS_WARN("No valid channel found - trying channels at half distToTarget");
// for(unsigned int channel_idx = 0; channel_idx < channels.size(); channel_idx++) {
// const DriveChannel & channel = channels.at(channel_idx);
// double da = channel.da_;
// double dist = channel.min_dist_;
// if(channel.length() >= 0.5 * distToTarget) { // valid
// double score = computeChannelScore(da, dist);
// if(score > best_score) {
// best_score = score;
// best_idx = channel_idx;
// }
// }
// }
//}
return best_idx;
}
int ChannelController::evaluateSafeChannels(const std::vector<DriveChannel> & channels, bool onlyBackwards) const
{
int best_idx = -1;
double best_score = -1.0;
for(unsigned int channel_idx = 0; channel_idx < channels.size(); channel_idx++) {
const DriveChannel & channel = channels.at(channel_idx);
double dir = channel.direction();
double dist = channel.min_dist_;
double length = channel.length();
if(onlyBackwards) {
if(fabs(dir) < angles::from_degrees(90))
continue;
}
// Scoring is based on dist and length
// Last term is added to decide between equal channels
double score = straight_up(dist, safe_channel_width_/2.0, safe_channel_width_) +
straight_up(length, 0.0, 2.0 * safe_channel_width_) +
0.05 * straight_up(dist, 0.0, 10.0);
if(score > best_score) {
best_score = score;
best_idx = channel_idx;
//ROS_INFO("Better safe channel found with da %f at %d", best_da, best_idx);
}
}
return best_idx;
}
bool ChannelController::computeVelocityCommands(geometry_msgs::Twist & cmd_vel)
{
cmd_vel = geometry_msgs::Twist(); // init to 0
ScopedVelocityStatus velStatus(cmd_vel, pub_status_marker_, pub_sound_, pub_led_, costmap_ros_, costmap_ros_->getGlobalFrameID());
if(ros::Time::now() - last_odom_.header.stamp > ros::Duration(0.5)) {
ROS_ERROR("Last odom is too old: %f - cannot produce commands.",
(ros::Time::now() - last_odom_.header.stamp).toSec());
return false;
}
if(!updateVoronoi()) {
ROS_ERROR_THROTTLE(1.0, "updateVoronoi failed.");
return false;
}
if(!localizeGlobalPlan(current_waypoint_)) {
return false;
}
// FIXME later: we should be able to skip/advance to waypoints furhter in the plan if they are reached.
// No need to follow the plan backwards if we somehow got ahead towards goal - only that counts.
while(!local_plan_.empty() && currentWaypointReached()) {
current_waypoint_++;
last_progress_time_ = ros::Time::now();
if(!localizeGlobalPlan(current_waypoint_)) {
return false;
}
} // FIXME later: more efficient, esp for skipping: wayPOintReache(idx)
if(local_plan_.empty()) {
return true; // FIXME At goal, but move_base wants us to say we did a velocity command always
}
tf::Stamped<tf::Pose> robot_pose;
if(!costmap_ros_->getRobotPose(robot_pose)) {
return false;
}
if(no_progress_hard_clear_time_ > 0 &&
ros::Time::now() - last_progress_time_ > ros::Duration(no_progress_hard_clear_time_)) {
ROS_WARN("No progress for %f s - calling /call_clear.", no_progress_hard_clear_time_);
std_msgs::Empty e;
pub_call_clear_.publish(e);
last_progress_time_ = ros::Time::now(); // prevent this happening all the time, essentially reset
kobuki_msgs::Sound snd;
snd.value = kobuki_msgs::Sound::OFF;
pub_sound_.publish(snd);
return false;
}
// check for local wpt in obstacle: call replanning if that happens
bool local_wpt_in_bounds;
double dist_at_next_wpt = getDistanceAtPose(local_plan_.front(), &local_wpt_in_bounds);
if(local_wpt_in_bounds) { // out of bounds OK - far away - drive there first
if(dist_at_next_wpt <= 0.0) {
ROS_WARN_THROTTLE(1.0, "Next waypoint in obstacle - requesting new plan");
return false;
}
}
visualization_msgs::MarkerArray channelMarkers;
tf::Pose currentTarget = local_plan_.front();
channelMarkers.markers.push_back(createPoseMarker(currentTarget, 1.0, 1.0, 0.0, "current_target"));
tf::Pose relativeTarget = robot_pose.inverseTimes(currentTarget);
double distToTarget = relativeTarget.getOrigin().length();
if(handleGoalTurn(cmd_vel, robot_pose, distToTarget, velStatus)) {
// don't compute a channel, just turn to goal
channelMarkers.markers.push_back(createChannelMarkers(std::vector<DriveChannel>(), 0.0, -1));
pub_markers_.publish(channelMarkers); // pub empty channels
return true;
}
int getting_to_safe_wpt = getToSafeWaypoint(cmd_vel, robot_pose, relativeTarget, velStatus);
if(getting_to_safe_wpt == 1) {
return true;
} else if(getting_to_safe_wpt == -1) {
ROS_ERROR_THROTTLE(1.0, "getToSafeWaypoint failed.");
velStatus.setNoSafeChannel();
return false;
} else if(getting_to_safe_wpt == -2) {
ROS_INFO_THROTTLE(1.0, "getToSafeWaypoint succeeded - querying new global plan.");
return false;
}
// TODO must occur everywhere, where we use this for scaling, etc.
// check locations
// HERE, safe waypoint, scoring
double cur_tv = last_odom_.twist.twist.linear.x;
double min_channel_width = safe_waypoint_channel_width_ +
(safe_waypoint_channel_width_at_max_tv_ - safe_waypoint_channel_width_) *
straight_up(cur_tv, min_tv_, max_tv_);
// TODO need to be more aggressive here, otherwise never channels
// TODO aspect ratio channels?
std::vector<DriveChannel> channels = computeChannels(robot_pose, relativeTarget,
min_channel_width/2.0);
// aspect could be for socring
// Maybe something here: best ideal chans, then go down in what we need - drive those more convervative.
// more convervative can punish width a lot
if(channels.size() == 0)
channels = computeChannels(robot_pose, relativeTarget, safe_waypoint_channel_width_/2.0);
if(channels.size() == 0) {
ROS_WARN("No safe_waypoint_channel_width channels found - switching to CSGetToSafeWaypointDist");
state_ = CSGetToSafeWaypointDist;
double prob = drand48();
if(prob < 0.35)
safe_waypoint_state_ = SWSBestBackwardsChannelTurnIn;
else if(prob < 0.7)
safe_waypoint_state_ = SWSBestBackwardsChannelTurnOut;
else
safe_waypoint_state_ = SWSBestChannel;
get_to_safe_waypoint_start_time_ = ros::Time::now();
// just enable behavior here, next iteration will execute.
return true;
}
int best_idx = evaluateChannels(channels, distToTarget);
channelMarkers.markers.push_back(createChannelMarkers(channels, distToTarget, best_idx));
pub_markers_.publish(channelMarkers);
// no valid channel found -> replan global please
if(best_idx < 0) {
ROS_WARN_THROTTLE(0.5, "No valid channel found.");
velStatus.setNoValidChannel();
return false;
}
ROS_DEBUG("Best channel found with da %.0f deg width: %.1f m",
angles::to_degrees(channels[best_idx].da_),
2.0 * channels[best_idx].min_dist_);
bool foundChannelCmd = computeVelocityForChannel(channels[best_idx], cmd_vel, velStatus);
if(!foundChannelCmd) {
ROS_ERROR("%s: Could not determine channel velocity", __func__);
}
ROS_DEBUG("%sSending cmd vel: %f %f", foundChannelCmd ? "" : "NOT ", cmd_vel.linear.x, cmd_vel.angular.z);
last_cmd_vel_time_ = ros::Time::now();
return foundChannelCmd;
}
ChannelController::ScopedVelocityStatus::ScopedVelocityStatus(geometry_msgs::Twist & cmdVel,
ros::Publisher & pubMarkers, ros::Publisher & pubSound, ros::Publisher & pubLED,
const costmap_2d::Costmap2DROS* costmap, std::string map_frame_id) :
cmd_vel(cmdVel), pub_markers(pubMarkers), pub_sound(pubSound), pub_led(pubLED), costmap(costmap), map_frame_id(map_frame_id)
{
status << std::setprecision(2) << std::fixed;
state = CSNone;
}
ChannelController::ScopedVelocityStatus::~ScopedVelocityStatus()
{
publishStatus();
}
void ChannelController::ScopedVelocityStatus::setAtGoalPosStopToTurn(double angle_to_goal, double cur_tv, double cur_rv)
{
status << "At Goal Pos" << std::endl <<
"-> Stop to turn" << std::endl <<
"Angle: " << angles::to_degrees(angle_to_goal) << " deg" << std::endl <<
"Cur TV: " << cur_tv << " Cur RV: " << angles::to_degrees(cur_rv) << " deg/s" << std::endl;
state = CSGoalTurn;
}
void ChannelController::ScopedVelocityStatus::setAtGoalPosTurnToGoal(double angle_to_goal, double cur_tv, double cur_rv)
{
status << "At Goal Pos" << std::endl <<
"-> Turn to goal" << std::endl <<
"Angle: " << angles::to_degrees(angle_to_goal) << std::endl <<
"Cur TV: " << cur_tv << " Cur RV: " << angles::to_degrees(cur_rv) << " deg/s" << std::endl;
state = CSGoalTurn;
}
void ChannelController::ScopedVelocityStatus::setChannelStopToTurn(double rel_channel_dir, double cur_tv, double cur_rv)
{
status << "Follow Channel" << std::endl <<
"-> Stop to turn" << std::endl <<
"Angle: " << angles::to_degrees(rel_channel_dir) << std::endl <<
"Cur TV: " << cur_tv << " Cur RV: " << angles::to_degrees(cur_rv) << " deg/s" << std::endl;
state = CSFollowChannel;
}
void ChannelController::ScopedVelocityStatus::setChannelTurnToChannel(double rel_channel_dir, double cur_tv, double cur_rv)
{
status << "Follow Channel" << std::endl <<
"-> Turn to channel" << std::endl <<
"Angle: " << angles::to_degrees(rel_channel_dir) << std::endl <<
"Cur TV: " << cur_tv << " Cur RV: " << angles::to_degrees(cur_rv) << " deg/s" << std::endl;
state = CSFollowChannel;
}
void ChannelController::ScopedVelocityStatus::setChannelFollowChannel(double rel_channel_dir,
double cur_tv, double cur_rv,
const std::string & tv_scale, const std::string & rv_scale)
{
status << "Follow Channel" << std::endl <<
"Angle: " << angles::to_degrees(rel_channel_dir) << std::endl <<
"Cur TV: " << cur_tv << " Cur RV: " << angles::to_degrees(cur_rv) << " deg/s" << std::endl <<
"TV limited: " << tv_scale << std::endl <<
"RV limited: " << rv_scale << std::endl;
state = CSFollowChannel;
}
void ChannelController::ScopedVelocityStatus::setNoValidChannel()
{
status << "No valid channel" << std::endl;
state = CSNone;
}
void ChannelController::ScopedVelocityStatus::setNoSafeChannel()
{
status << "No safe channel" << std::endl;
state = CSNone;
}
void ChannelController::ScopedVelocityStatus::setGetToSafeWaypoint(double cur_dist, double active_time, enum SafeWaypointState safe_waypoint_st)
{
status << "Get To Safe WPT" << std::endl;
switch(safe_waypoint_st) {
case SWSBestChannel:
status << "-> Best Channel" << std::endl;
break;
case SWSBestBackwardsChannelTurnIn:
status << "-> Best Backwards In" << std::endl;
break;
case SWSBestBackwardsChannelTurnOut:
status << "-> Best Backwards Out" << std::endl;
break;
default:
status << "-> ERROR undefined: " << safe_waypoint_st << std::endl;
break;
}
status << "Cur Safe Dist: " << cur_dist << std::endl <<
"Active for: " << active_time << " s" << std::endl;
state = CSGetToSafeWaypointDist;
safe_waypoint_state = safe_waypoint_st;
}
void ChannelController::ScopedVelocityStatus::publishStatus()
{
status << "TV: " << cmd_vel.linear.x << " m/s" << std::endl <<
"RV: " << angles::to_degrees(cmd_vel.angular.z) << " deg/s" << std::endl;
visualization_msgs::Marker statusMarker;
statusMarker.header.stamp = ros::Time(0);
statusMarker.header.frame_id = map_frame_id;
statusMarker.ns = "status";
statusMarker.id = 0;
statusMarker.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
statusMarker.action = visualization_msgs::Marker::ADD;
statusMarker.text = status.str();
statusMarker.scale.z = 0.25;
//ROS_INFO("Status: %s", status.str().c_str());
// put status marker near robot
tf::Stamped<tf::Pose> robot_pose;
if(!costmap->getRobotPose(robot_pose)) {
statusMarker.pose.orientation.w = 1.0;
} else {
tf::poseTFToMsg(robot_pose, statusMarker.pose);
}
statusMarker.pose.position.x += 1.0;
statusMarker.pose.position.z += 1.0;
statusMarker.color.r = 1.0;
statusMarker.color.g = 1.0;
statusMarker.color.b = 0.0;
statusMarker.color.a = 1.0;
statusMarker.lifetime = ros::Duration(0);
statusMarker.frame_locked = false;
pub_markers.publish(statusMarker);
kobuki_msgs::Led led;
if(cmd_vel.linear.x == 0 && cmd_vel.angular.z == 0) { // for some reason we're stopping
led.value = kobuki_msgs::Led::BLACK;
} else if(state == CSFollowChannel) {
led.value = kobuki_msgs::Led::GREEN;
} else if(state == CSGoalTurn) {
led.value = kobuki_msgs::Led::ORANGE;
} else if(state == CSGetToSafeWaypointDist) {
led.value = kobuki_msgs::Led::RED;
}
pub_led.publish(led);
static ros::Time last_sound_time = ros::Time(0);
if(ros::Time::now() - last_sound_time > ros::Duration(1.0)) {
kobuki_msgs::Sound sound;
sound.value = 0;
if(state == CSGetToSafeWaypointDist) {
sound.value = kobuki_msgs::Sound::RECHARGE;
} else if(state == CSGoalTurn) {
sound.value = kobuki_msgs::Sound::BUTTON;
}
if(sound.value > 0) {
pub_sound.publish(sound);
last_sound_time = ros::Time::now();
}
}
}
}
| 40.68637 | 148 | 0.644692 | [
"vector",
"transform"
] |
8b01887c9d53fc741cba537c3385987e2a541b54 | 3,386 | cxx | C++ | Modules/Numerics/FEM/test/itkFEMElement2DC0QuadraticTriangleStressTest.cxx | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | 3 | 2018-10-01T20:46:17.000Z | 2019-12-17T19:39:50.000Z | Modules/Numerics/FEM/test/itkFEMElement2DC0QuadraticTriangleStressTest.cxx | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | null | null | null | Modules/Numerics/FEM/test/itkFEMElement2DC0QuadraticTriangleStressTest.cxx | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | 4 | 2018-05-17T16:34:54.000Z | 2020-09-24T02:12:40.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkFEMSolver.h"
#include "itkFEMSpatialObjectReader.h"
#include "itkFEMSpatialObjectWriter.h"
int itkFEMElement2DC0QuadraticTriangleStressTest(int argc, char *argv[])
{
if(argc < 1)
{
std::cerr << "Missing Spatial Object Filename" << std::endl;
return EXIT_FAILURE;
}
//Need to register default FEM object types,
//and setup SpatialReader to recognize FEM types
//which is all currently done as a HACK in
//the initializaiton of the itk::FEMFactoryBase::GetFactory()
itk::FEMFactoryBase::GetFactory()->RegisterDefaultTypes();
typedef itk::fem::Solver<2> Solver2DType;
Solver2DType::Pointer solver = Solver2DType::New();
typedef itk::FEMSpatialObjectReader<2> FEMSpatialObjectReaderType;
typedef FEMSpatialObjectReaderType::Pointer FEMSpatialObjectReaderPointer;
FEMSpatialObjectReaderPointer SpatialReader = FEMSpatialObjectReaderType::New();
SpatialReader->SetFileName( argv[1] );
SpatialReader->Update();
FEMSpatialObjectReaderType::ScenePointer myScene = SpatialReader->GetScene();
if( !myScene )
{
std::cout << "No Scene : [FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << " [PASSED]" << std::endl;
// Testing the fe mesh validity
typedef itk::FEMObjectSpatialObject<2> FEMObjectSpatialObjectType;
FEMObjectSpatialObjectType::ChildrenListType* children = SpatialReader->GetGroup()->GetChildren();
if( strcmp( (*(children->begin() ) )->GetTypeName(), "FEMObjectSpatialObject") )
{
std::cout << " [FAILED]" << std::endl;
return EXIT_FAILURE;
}
FEMObjectSpatialObjectType::Pointer femSO =
dynamic_cast<FEMObjectSpatialObjectType *>( (*(children->begin() ) ).GetPointer() );
if (!femSO)
{
std::cout << " dynamic_cast [FAILED]" << std::endl;
return EXIT_FAILURE;
}
delete children;
femSO->GetFEMObject()->FinalizeMesh();
solver->SetInput( femSO->GetFEMObject() );
solver->Update();
// to write the deformed mesh
FEMObjectSpatialObjectType::Pointer femSODef = FEMObjectSpatialObjectType::New();
femSODef->SetFEMObject(solver->GetOutput() );
typedef itk::FEMSpatialObjectWriter<2> FEMSpatialObjectWriterType;
typedef FEMSpatialObjectWriterType::Pointer FEMSpatialObjectWriterPointer;
FEMSpatialObjectWriterPointer SpatialWriter = FEMSpatialObjectWriterType::New();
SpatialWriter->SetInput(femSODef);
SpatialWriter->SetFileName( argv[2] );
SpatialWriter->Update();
std::cout << "Test PASSED!" << std::endl;
return EXIT_SUCCESS;
}
| 36.408602 | 101 | 0.671589 | [
"mesh",
"object"
] |
8b0479e77205921d4f78f0b243a1b373e9e88078 | 26,129 | cpp | C++ | src/test/xraytests/condensingtransaction_tests.cpp | xraychain/XrayChain-v.020 | 4fdb5b10e6dde6d3b1dbda3f18b77ec47f81947e | [
"MIT"
] | 1 | 2022-03-16T18:15:38.000Z | 2022-03-16T18:15:38.000Z | src/test/xraytests/condensingtransaction_tests.cpp | xraychain/XrayChain-v.020 | 4fdb5b10e6dde6d3b1dbda3f18b77ec47f81947e | [
"MIT"
] | null | null | null | src/test/xraytests/condensingtransaction_tests.cpp | xraychain/XrayChain-v.020 | 4fdb5b10e6dde6d3b1dbda3f18b77ec47f81947e | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include <xraytests/test_utils.h>
const std::vector<valtype> code = {
/*
contract Sender1 {
address sender2;
address sender3;
function Sender1() {
}
function setSenders(address senderx, address sendery) public{
sender2 = senderx;
sender3 = sendery;
}
function share() public payable{
if(msg.sender != address(sender3)){
sender2.call.value(msg.value/2)(bytes4(sha3("share()")));
}
}
function sendAll() public payable{
sender2.call.value(this.balance)(bytes4(sha3("keep()")));
}
function keep() public payable{
}
function() payable { } //always payable
}
*/
valtype(ParseHex("606060405234610000575b5b5b6103bf8061001b6000396000f30060606040523615610060576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680635579818d14610069578063a8d5fd65146100bb578063e14f680f146100c5578063e4d06d82146100cf575b6100675b5b565b005b34610000576100b9600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506100d9565b005b6100c3610160565b005b6100cd61029d565b005b6100d7610390565b005b81600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b5050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561029a57600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166002348115610000570460405180807f7368617265282900000000000000000000000000000000000000000000000000815250600701905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886185025a03f19350505050505b5b565b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff163160405180807f6b65657028290000000000000000000000000000000000000000000000000000815250600601905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886185025a03f19350505050505b565b5b5600a165627a7a7230582094424c92e68d8ea77caec662d2895cc9086f115ed7baa3f7e508b4d8d011161f0029")),
/*
contract Sender2{
address sender1;
address sender3;
function Sender2() {
}
function setSenders(address senderx, address sendery) public{
sender1 = senderx;
sender3 = sendery;
}
function share() public payable{
sender3.call.value(msg.value/2)(bytes4(sha3("share()")));
}
function keep() public payable{
}
function withdrawAll() public{
sender3.call(bytes4(sha3("withdraw()")));
msg.sender.send(this.balance);
}
function() payable { } //always payable
}
*/
valtype(ParseHex("606060405234610000575b5b5b6103a38061001b6000396000f30060606040523615610060576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680635579818d14610069578063853828b6146100bb578063a8d5fd65146100ca578063e4d06d82146100d4575b6100675b5b565b005b34610000576100b9600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506100de565b005b34610000576100c8610165565b005b6100d261028f565b005b6100dc610374565b005b81600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b5050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660405180807f7769746864726177282900000000000000000000000000000000000000000000815250600a01905060405180910390207c010000000000000000000000000000000000000000000000000000000090046040518163ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018090506000604051808303816000876161da5a03f192505050503373ffffffffffffffffffffffffffffffffffffffff166108fc3073ffffffffffffffffffffffffffffffffffffffff16319081150290604051809050600060405180830381858888f19350505050505b565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166002348115610000570460405180807f7368617265282900000000000000000000000000000000000000000000000000815250600701905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886185025a03f19350505050505b565b5b5600a165627a7a723058206dd48a1be1f30e54f5105f13673a3fff6be78a63bb148924dd62a145b43694440029")),
/*
contract Sender3 {
address sender1;
address sender2;
function Sender3() {
}
function setSenders(address senderx, address sendery) public{
sender1 = senderx;
sender2 = sendery;
}
function share() public payable{
sender1.call.value(msg.value/2)(bytes4(sha3("share()")));
sender2.call.value(msg.value/4)(bytes4(sha3("keep()")));
}
function withdraw() public{
msg.sender.send(this.balance);
}
function() payable { } //always payable
}
*/
valtype(ParseHex("606060405234610000575b5b5b6103968061001b6000396000f30060606040523615610055576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680633ccfd60b1461005e5780635579818d1461006d578063a8d5fd65146100bf575b61005c5b5b565b005b346100005761006b6100c9565b005b34610000576100bd600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190505061011c565b005b6100c76101a3565b005b3373ffffffffffffffffffffffffffffffffffffffff166108fc3073ffffffffffffffffffffffffffffffffffffffff16319081150290604051809050600060405180830381858888f19350505050505b565b81600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b5050565b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166002348115610000570460405180807f7368617265282900000000000000000000000000000000000000000000000000815250600701905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886185025a03f1935050505050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166004348115610000570460405180807f6b65657028290000000000000000000000000000000000000000000000000000815250600601905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886185025a03f19350505050505b5600a165627a7a723058208fddda1b1d980244617e9e88336ac5c0d3e1a836d77985d899cd6d96058106260029")),
/*call Sender1 setSender*/
valtype(ParseHex("5579818d00000000000000000000000000a64bc3531cd43517a1eee783245effd6770f48000000000000000000000000ca1d76da7e66c5db9459f098e7e6a09381eef2b5")),
/*call Sender2 setSender*/
valtype(ParseHex("5579818d00000000000000000000000047b725b087f9ef7802b4fef599cfeb08a451e46f000000000000000000000000ca1d76da7e66c5db9459f098e7e6a09381eef2b5")),
/*call Sender3 setSender*/
valtype(ParseHex("5579818d00000000000000000000000047b725b087f9ef7802b4fef599cfeb08a451e46f00000000000000000000000000a64bc3531cd43517a1eee783245effd6770f48")),
/*share*/
valtype(ParseHex("a8d5fd65")),
/*keep*/
valtype(ParseHex("e4d06d82")),
/*sendAll*/
valtype(ParseHex("e14f680f")),
/*withdrawAll*/
valtype(ParseHex("853828b6")),
/*
contract Test1 {
address Sender1 = 0x47b725b087f9ef7802b4fef599cfeb08a451e46f;
address Sender2 = 0x00a64bc3531cd43517a1eee783245effd6770f48;
address Sender3 = 0xca1d76da7e66c5db9459f098e7e6a09381eef2b5;
function transfer() {
Sender1.send(this.balance/3);
Sender2.send(this.balance/2);
Sender3.send(this.balance);
}
function() payable { }
}
*/
valtype(ParseHex("60606040527347b725b087f9ef7802b4fef599cfeb08a451e46f600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055507300a64bc3531cd43517a1eee783245effd6770f48600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555073ca1d76da7e66c5db9459f098e7e6a09381eef2b5600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034610000575b6101ee806101186000396000f3006060604052361561003f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638a4068dd14610048575b6100465b5b565b005b3461000057610055610057565b005b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc60033073ffffffffffffffffffffffffffffffffffffffff1631811561000057049081150290604051809050600060405180830381858888f1935050505050600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc60023073ffffffffffffffffffffffffffffffffffffffff1631811561000057049081150290604051809050600060405180830381858888f1935050505050600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc3073ffffffffffffffffffffffffffffffffffffffff16319081150290604051809050600060405180830381858888f19350505050505b5600a165627a7a72305820a16c66241bc68fd2da2088dfbf7847f57fda4273502d7b817499d4bb32d41f1b0029")),
/*transfer*/
valtype(ParseHex("8a4068dd")),
/*
contract Test11{
function() payable { }
}
*/
valtype(ParseHex("6060604052346000575b60398060166000396000f30060606040525b600b5b5b565b0000a165627a7a7230582089f5187aa25f85528a07c69078180c9616660442c881510ebc3534a29011b49e0029")),
/*
contract Test12{
address addr = 0xcf8c04c7c0a68f7483ce660df9e3056d05347d5c;
function transfer() payable {
addr.call.value(this.balance/2)(bytes4(sha3("00")));
}
function() payable { }
}
*/
valtype(ParseHex("606060405273cf8c04c7c0a68f7483ce660df9e3056d05347d5c600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550341561006157fe5b5b61017d806100716000396000f3006060604052361561003f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638a4068dd14610048575b6100465b5b565b005b610050610052565b005b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660023073ffffffffffffffffffffffffffffffffffffffff16318115156100ae57fe5b0460405180807f3030000000000000000000000000000000000000000000000000000000000000815250600201905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886187965a03f19350505050505b5600a165627a7a723058207f49346fdf78e94fe907fa5c0cc37c1bc5e86a5f91ef2811fe70e302cab979ee0029")),
/*
contract Test13{
address addr = 0xef1bada115ec9dcc117ca8d395f649fee774498c;
function transfer() payable {
addr.call.value(this.balance/2)(bytes4(sha3("transfer()")));
}
function() payable { }
}
*/
valtype(ParseHex("606060405273ef1bada115ec9dcc117ca8d395f649fee774498c600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550341561006157fe5b5b61017d806100716000396000f3006060604052361561003f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638a4068dd14610048575b6100465b5b565b005b610050610052565b005b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660023073ffffffffffffffffffffffffffffffffffffffff16318115156100ae57fe5b0460405180807f7472616e73666572282900000000000000000000000000000000000000000000815250600a01905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886187965a03f19350505050505b5600a165627a7a72305820b568c0caeeeb3a6af971f764ca36556567fb91dd3f5beac33dbe0a18d7902dc80029")),
/*
contract Test14{
address addr = 0xbf280ab611c4866bf3d4721d834633e5e615f6c7;
function transfer() payable {
addr.call.value(this.balance/2)(bytes4(sha3("transfer()")));
}
function() payable { }
}
*/
valtype(ParseHex("606060405273bf280ab611c4866bf3d4721d834633e5e615f6c7600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550341561006157fe5b5b61017d806100716000396000f3006060604052361561003f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638a4068dd14610048575b6100465b5b565b005b610050610052565b005b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660023073ffffffffffffffffffffffffffffffffffffffff16318115156100ae57fe5b0460405180807f7472616e73666572282900000000000000000000000000000000000000000000815250600a01905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886187965a03f19350505050505b5600a165627a7a72305820daeb96d07fc42ad749f5f2c00724a6b1818986262e8aa37572c35ef7fb1260c60029")),
/*
contract Test15{
address addr = 0xefc304b02e965bf2fc34654a9b6c35e587aebb55;
function transfer() payable {
addr.call.value(this.balance/2)(bytes4(sha3("transfer()")));
}
function() payable { }
}
*/
valtype(ParseHex("606060405273efc304b02e965bf2fc34654a9b6c35e587aebb55600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550341561006157fe5b5b61017d806100716000396000f3006060604052361561003f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638a4068dd14610048575b6100465b5b565b005b610050610052565b005b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660023073ffffffffffffffffffffffffffffffffffffffff16318115156100ae57fe5b0460405180807f7472616e73666572282900000000000000000000000000000000000000000000815250600a01905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886187965a03f19350505050505b5600a165627a7a723058203289bd2de8b19d77e8d408d2a3f9bf60d53dda62c2aa77dec4e6d982c7aca30b0029")),
/*
contract SuicideTest{
address addr = 0x47b725b087f9ef7802b4fef599cfeb08a451e46f;
function SuicideTest() payable {}
function sui() payable {
suicide(addr);
}
function() payable { }
}
*/
valtype(ParseHex("60606040527347b725b087f9ef7802b4fef599cfeb08a451e46f600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b5b5b60b68061006a6000396000f30060606040523615603d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063c421249a146045575b60435b5b565b005b604b604d565b005b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b5600a165627a7a72305820e3bd6e50ab35c5105478fab7852d2307ea9c3adefc32ae8da2ec3e72dd791aed0029")),
/*sui*/
valtype(ParseHex("c421249a")),
/*
contract Test{
address addr = 0x47b725b087f9ef7802b4fef599cfeb08a451e46f;
function transfer() payable {
addr.call.value(this.balance/2)(bytes4(sha3("transfer()")));
}
function Test() payable{}
function() payable {}
}
*/
valtype(ParseHex("60606040527347b725b087f9ef7802b4fef599cfeb08a451e46f600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b5b5b61017a8061006b6000396000f3006060604052361561003f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638a4068dd14610048575b6100465b5b565b005b610050610052565b005b600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660023073ffffffffffffffffffffffffffffffffffffffff16318115610000570460405180807f7472616e73666572282900000000000000000000000000000000000000000000815250600a01905060405180910390207c01000000000000000000000000000000000000000000000000000000009004906040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180905060006040518083038185886185025a03f19350505050505b5600a165627a7a72305820709abc77d99f7e829396b41fcf78a6d4444b9f9734ea765177bd11cbd7357e960029"))
};
const dev::h256 hash = dev::h256(ParseHex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
void checkRes(ByteCodeExecResult& res, std::vector<dev::Address>& addresses, std::vector<dev::u256>& balances, size_t sizeTxs){
std::unordered_map<dev::Address, Vin> vins = globalState->vins();
BOOST_CHECK(res.valueTransfers.size() == sizeTxs);
for(size_t i = 0; i < addresses.size(); i++){
BOOST_CHECK(globalState->balance(addresses[i]) == balances[i]);
if(balances[i] > 0){
BOOST_CHECK(vins.count(addresses[i]));
BOOST_CHECK(vins[addresses[i]].value = balances[i]);
} else {
BOOST_CHECK(!vins.count(addresses[i]));
}
}
}
void checkTx(CTransaction& tx, size_t sizeVin, size_t sizeVout, std::vector<CAmount> values){
BOOST_CHECK(tx.vin.size() == sizeVin);
BOOST_CHECK(tx.vout.size() == sizeVout);
for(size_t i = 0; i < tx.vout.size(); i++){
BOOST_CHECK(tx.vout[i].nValue == values[i]);
}
}
BOOST_FIXTURE_TEST_SUITE(condensingtransaction_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(condensingtransactionbehavior_tests){
initState();
dev::h256 hashTemp(hash);
std::vector<XrayTransaction> txs;
std::vector<dev::Address> addresses;
for(size_t i = 0; i < 3; i++){
txs.push_back(createXrayTransaction(code[i], 0, dev::u256(500000), dev::u256(1), hashTemp, dev::Address(), i));
addresses.push_back(createXrayAddress(hashTemp, i));
++hashTemp;
}
auto result = executeBC(txs);
std::vector<dev::u256> balances = {0,0,0};
checkRes(result.second, addresses, balances, 0);
txs.clear();
for(size_t i = 0; i < 3; i++){
txs.push_back(createXrayTransaction(code[i + 3], 0, dev::u256(500000), dev::u256(1), hashTemp, addresses[i]));
}
result = executeBC(txs);
balances = {0,0,0};
checkRes(result.second, addresses, balances, 0);
txs.clear();
txs.push_back(createXrayTransaction(code[6], 8000, dev::u256(500000), dev::u256(1), hashTemp, addresses[0]));
result = executeBC(txs);
balances = {5000,2500,500};
checkRes(result.second, addresses, balances, 1);
checkTx(result.second.valueTransfers[0], 1, 3, {2500,5000,500});
txs.clear();
txs.push_back(createXrayTransaction(code[7], 2000, dev::u256(500000), dev::u256(1), hashTemp, addresses[0]));
txs.push_back(createXrayTransaction(code[8], 2000, dev::u256(500000), dev::u256(1), hashTemp, addresses[0]));
result = executeBC(txs);
balances = {0,11500,500};
checkRes(result.second, addresses, balances, 2);
checkTx(result.second.valueTransfers[0], 2, 1, {7000});
checkTx(result.second.valueTransfers[1], 3, 1, {11500});
txs.clear();
txs.push_back(createXrayTransaction(code[6], 2000, dev::u256(30000), dev::u256(1), hashTemp, addresses[1]));
txs.push_back(createXrayTransaction(code[9], 0, dev::u256(500000), dev::u256(1), hashTemp, addresses[1]));
result = executeBC(txs);
balances = {0,0,0};
checkRes(result.second, addresses, balances, 2);
checkTx(result.second.valueTransfers[0], 1, 1, {2000});
checkTx(result.second.valueTransfers[1], 2, 1, {12000});
}
BOOST_AUTO_TEST_CASE(condensingtransactionbreadthways_tests){
initState();
dev::h256 hashTemp(hash);
std::vector<dev::Address> addresses;
std::vector<XrayTransaction> txs;
for(size_t i = 0; i < 3; i++){
txs.push_back(createXrayTransaction(code[i], 0, dev::u256(500000), dev::u256(1), hashTemp, dev::Address(), i));
addresses.push_back(createXrayAddress(hashTemp, i));
++hashTemp;
}
txs.push_back(createXrayTransaction(code[10], 0, dev::u256(500000), dev::u256(1), hashTemp, dev::Address(), 4));
addresses.push_back(createXrayAddress(hashTemp, 4));
auto result = executeBC(txs);
txs.clear();
txs.push_back(createXrayTransaction(code[0], 15000, dev::u256(500000), dev::u256(1), hashTemp, addresses[3]));
txs.push_back(createXrayTransaction(code[11], 0, dev::u256(500000), dev::u256(1), hashTemp, addresses[3]));
result = executeBC(txs);
std::vector<dev::u256> balances = {5000,5000,5000,0};
checkRes(result.second, addresses, balances, 2);
checkTx(result.second.valueTransfers[0], 1, 1, {15000});
checkTx(result.second.valueTransfers[1], 1, 3, {5000,5000,5000});
}
BOOST_AUTO_TEST_CASE(condensingtransactiondeep_tests){
initState();
dev::h256 hashTemp(hash);
std::vector<dev::Address> addresses;
std::vector<XrayTransaction> txs;
for(size_t i = 12; i < 17; i++){
txs.push_back(createXrayTransaction(code[i], 0, dev::u256(500000), dev::u256(1), hashTemp, dev::Address(), i));
addresses.push_back(createXrayAddress(hashTemp, i));
++hashTemp;
}
auto result = executeBC(txs);
txs.clear();
txs.push_back(createXrayTransaction(code[11], 20000, dev::u256(500000), dev::u256(1), hashTemp, addresses[4]));
result = executeBC(txs);
std::vector<dev::u256> balances = {1250,1250,2500,5000,10000};
checkRes(result.second, addresses, balances, 1);
checkTx(result.second.valueTransfers[0], 1, 5, {10000,2500,1250,1250,5000});
}
BOOST_AUTO_TEST_CASE(condensingtransactionsuicide_tests){
initState();
dev::h256 hashTemp(hash);
std::vector<dev::Address> addresses;
std::vector<XrayTransaction> txs;
txs.push_back(createXrayTransaction(code[12], 0, dev::u256(500000), dev::u256(1), hashTemp, dev::Address(), 0));
addresses.push_back(createXrayAddress(hashTemp, 0));
txs.push_back(createXrayTransaction(code[17], 0, dev::u256(500000), dev::u256(1), ++hashTemp, dev::Address(), 1));
txs.push_back(createXrayTransaction(valtype(), 13000, dev::u256(500000), dev::u256(1), hashTemp, createXrayAddress(hashTemp, 1), 1));
addresses.push_back(createXrayAddress(hashTemp, 1));
auto result = executeBC(txs);
txs.clear();
txs.push_back(createXrayTransaction(code[18], 0, dev::u256(500000), dev::u256(1), hashTemp, addresses[1]));
result = executeBC(txs);
std::vector<dev::u256> balances = {13000,0};
checkRes(result.second, addresses, balances, 1);
checkTx(result.second.valueTransfers[0], 1, 1, {13000});
}
BOOST_AUTO_TEST_CASE(condensingtransactionpaytopubkeyhash_tests){
initState();
dev::h256 hashTemp(hash);
std::vector<dev::Address> addresses;
std::vector<XrayTransaction> txs;
txs.push_back(createXrayTransaction(code[19], 0, dev::u256(500000), dev::u256(1), hashTemp, dev::Address(), 13));
txs.push_back(createXrayTransaction(valtype(), 13000, dev::u256(500000), dev::u256(1), hashTemp, createXrayAddress(hashTemp, 13), 13));
addresses.push_back(createXrayAddress(hashTemp, 13));
auto result = executeBC(txs);
txs.clear();
txs.push_back(createXrayTransaction(code[11], 0, dev::u256(500000), dev::u256(1), hashTemp, addresses[0]));
result = executeBC(txs);
std::vector<dev::u256> balances = {6500,6500};
checkRes(result.second, addresses, balances, 1);
checkTx(result.second.valueTransfers[0], 1, 2, {6500,6500});
BOOST_CHECK(result.second.valueTransfers[0].vout[0].scriptPubKey.IsPayToPubkeyHash());
BOOST_CHECK(result.second.valueTransfers[0].vout[1].scriptPubKey.HasOpCall());
}
BOOST_AUTO_TEST_SUITE_END()
| 75.517341 | 1,998 | 0.805886 | [
"vector"
] |
8b06a98b5a1c709fdd62fb9a133b638617c264c3 | 17,936 | cpp | C++ | Source/Core/FontEngineDefault/FreeTypeInterface.cpp | jonesmz/RmlUi | 4791d7abc72e99a7a4d96daf7d5f89d0fa2067d3 | [
"MIT"
] | null | null | null | Source/Core/FontEngineDefault/FreeTypeInterface.cpp | jonesmz/RmlUi | 4791d7abc72e99a7a4d96daf7d5f89d0fa2067d3 | [
"MIT"
] | null | null | null | Source/Core/FontEngineDefault/FreeTypeInterface.cpp | jonesmz/RmlUi | 4791d7abc72e99a7a4d96daf7d5f89d0fa2067d3 | [
"MIT"
] | null | null | null | /*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* 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 "FreeTypeInterface.h"
#include "../../../Include/RmlUi/Core/Log.h"
#include <string.h>
#include <limits.h>
#include <ft2build.h>
#include FT_FREETYPE_H
namespace Rml {
static FT_Library ft_library = nullptr;
static bool BuildGlyph(FT_Face ft_face, Character character, FontGlyphMap& glyphs, float bitmap_scaling_factor);
static void BuildGlyphMap(FT_Face ft_face, int size, FontGlyphMap& glyphs, float bitmap_scaling_factor, bool load_default_glyphs);
static void GenerateMetrics(FT_Face ft_face, FontMetrics& metrics, float bitmap_scaling_factor);
static bool SetFontSize(FT_Face ft_face, int font_size, float& out_bitmap_scaling_factor);
static void BitmapDownscale(byte* bitmap_new, int new_width, int new_height, const byte* bitmap_source, int width, int height, int pitch,
ColorFormat color_format);
bool FreeType::Initialise()
{
RMLUI_ASSERT(!ft_library);
FT_Error result = FT_Init_FreeType(&ft_library);
if (result != 0)
{
Log::Message(Log::LT_ERROR, "Failed to initialise FreeType, error %d.", result);
Shutdown();
return false;
}
return true;
}
void FreeType::Shutdown()
{
if (ft_library != nullptr)
{
FT_Done_FreeType(ft_library);
ft_library = nullptr;
}
}
// Loads a FreeType face from memory.
FontFaceHandleFreetype FreeType::LoadFace(const byte* data, int data_length, const String& source)
{
RMLUI_ASSERT(ft_library);
FT_Face face = nullptr;
int error = FT_New_Memory_Face(ft_library, (const FT_Byte*)data, data_length, 0, &face);
if (error != 0)
{
Log::Message(Log::LT_ERROR, "FreeType error %d while loading face from %s.", error, source.c_str());
return 0;
}
// Initialise the character mapping on the face.
if (face->charmap == nullptr)
{
FT_Select_Charmap(face, FT_ENCODING_APPLE_ROMAN);
if (face->charmap == nullptr)
{
Log::Message(Log::LT_ERROR, "Font face (from %s) does not contain a Unicode or Apple Roman character map.", source.c_str());
FT_Done_Face(face);
return 0;
}
}
return (FontFaceHandleFreetype)face;
}
bool FreeType::ReleaseFace(FontFaceHandleFreetype in_face)
{
FT_Face face = (FT_Face)in_face;
FT_Error error = FT_Done_Face(face);
return (error == 0);
}
void FreeType::GetFaceStyle(FontFaceHandleFreetype in_face, String& font_family, Style::FontStyle& style, Style::FontWeight& weight)
{
FT_Face face = (FT_Face)in_face;
font_family = face->family_name;
style = face->style_flags & FT_STYLE_FLAG_ITALIC ? Style::FontStyle::Italic : Style::FontStyle::Normal;
weight = face->style_flags & FT_STYLE_FLAG_BOLD ? Style::FontWeight::Bold : Style::FontWeight::Normal;
}
// Initialises the handle so it is able to render text.
bool FreeType::InitialiseFaceHandle(FontFaceHandleFreetype face, int font_size, FontGlyphMap& glyphs, FontMetrics& metrics, bool load_default_glyphs)
{
FT_Face ft_face = (FT_Face)face;
metrics.size = font_size;
float bitmap_scaling_factor = 1.0f;
if (!SetFontSize(ft_face, font_size, bitmap_scaling_factor))
return false;
// Construct the initial list of glyphs.
BuildGlyphMap(ft_face, font_size, glyphs, bitmap_scaling_factor, load_default_glyphs);
// Generate the metrics for the handle.
GenerateMetrics(ft_face, metrics, bitmap_scaling_factor);
return true;
}
bool FreeType::AppendGlyph(FontFaceHandleFreetype face, int font_size, Character character, FontGlyphMap& glyphs)
{
FT_Face ft_face = (FT_Face)face;
RMLUI_ASSERT(glyphs.find(character) == glyphs.end());
RMLUI_ASSERT(ft_face);
// Set face size again in case it was used at another size in another font face handle.
float bitmap_scaling_factor = 1.0f;
if (!SetFontSize(ft_face, font_size, bitmap_scaling_factor))
return false;
if (!BuildGlyph(ft_face, character, glyphs, bitmap_scaling_factor))
return false;
return true;
}
int FreeType::GetKerning(FontFaceHandleFreetype face, int font_size, Character lhs, Character rhs)
{
FT_Face ft_face = (FT_Face)face;
RMLUI_ASSERT(FT_HAS_KERNING(ft_face));
// Set face size again in case it was used at another size in another font face handle.
// Font size value of zero assumes it is already set.
if (font_size > 0)
{
float bitmap_scaling_factor = 1.0f;
if (!SetFontSize(ft_face, font_size, bitmap_scaling_factor) || bitmap_scaling_factor != 1.0f)
return 0;
}
FT_Vector ft_kerning;
FT_Error ft_error = FT_Get_Kerning(
ft_face,
FT_Get_Char_Index(ft_face, (FT_ULong)lhs),
FT_Get_Char_Index(ft_face, (FT_ULong)rhs),
FT_KERNING_DEFAULT,
&ft_kerning
);
if (ft_error)
return 0;
int kerning = ft_kerning.x >> 6;
return kerning;
}
bool FreeType::HasKerning(FontFaceHandleFreetype face)
{
FT_Face ft_face = (FT_Face)face;
return FT_HAS_KERNING(ft_face);
}
static void BuildGlyphMap(FT_Face ft_face, int size, FontGlyphMap& glyphs, const float bitmap_scaling_factor, const bool load_default_glyphs)
{
if (load_default_glyphs)
{
glyphs.reserve(128);
// Add the ASCII characters now. Other characters are added later as needed.
FT_ULong code_min = 32;
FT_ULong code_max = 126;
for (FT_ULong character_code = code_min; character_code <= code_max; ++character_code)
BuildGlyph(ft_face, (Character)character_code, glyphs, bitmap_scaling_factor);
}
// Add a replacement character for rendering unknown characters.
Character replacement_character = Character::Replacement;
auto it = glyphs.find(replacement_character);
if (it == glyphs.end())
{
FontGlyph glyph;
glyph.dimensions = { size / 3, (size * 2) / 3 };
glyph.bitmap_dimensions = glyph.dimensions;
glyph.advance = glyph.dimensions.x + 2;
glyph.bearing = { 1, glyph.dimensions.y };
glyph.bitmap_owned_data.reset(new byte[glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y]);
glyph.bitmap_data = glyph.bitmap_owned_data.get();
for (int y = 0; y < glyph.bitmap_dimensions.y; y++)
{
for (int x = 0; x < glyph.bitmap_dimensions.x; x++)
{
constexpr int stroke = 1;
int i = y * glyph.bitmap_dimensions.x + x;
bool near_edge = (x < stroke || x >= glyph.bitmap_dimensions.x - stroke || y < stroke || y >= glyph.bitmap_dimensions.y - stroke);
glyph.bitmap_owned_data[i] = (near_edge ? 0xdd : 0);
}
}
glyphs[replacement_character] = std::move(glyph);
}
}
static bool BuildGlyph(FT_Face ft_face, const Character character, FontGlyphMap& glyphs, const float bitmap_scaling_factor)
{
FT_UInt index = FT_Get_Char_Index(ft_face, (FT_ULong)character);
if (index == 0)
return false;
FT_Error error = FT_Load_Glyph(ft_face, index, FT_LOAD_COLOR);
if (error != 0)
{
Log::Message(Log::LT_WARNING, "Unable to load glyph for character '%u' on the font face '%s %s'; error code: %d.", (unsigned int)character, ft_face->family_name, ft_face->style_name, error);
return false;
}
error = FT_Render_Glyph(ft_face->glyph, FT_RENDER_MODE_NORMAL);
if (error != 0)
{
Log::Message(Log::LT_WARNING, "Unable to render glyph for character '%u' on the font face '%s %s'; error code: %d.", (unsigned int)character, ft_face->family_name, ft_face->style_name, error);
return false;
}
auto result = glyphs.emplace(character, FontGlyph{});
if (!result.second)
{
Log::Message(Log::LT_WARNING, "Glyph character '%u' is already loaded in the font face '%s %s'.", (unsigned int)character, ft_face->family_name, ft_face->style_name);
return false;
}
FontGlyph& glyph = result.first->second;
FT_GlyphSlot ft_glyph = ft_face->glyph;
// Set the glyph's dimensions.
glyph.dimensions.x = ft_glyph->metrics.width >> 6;
glyph.dimensions.y = ft_glyph->metrics.height >> 6;
// Set the glyph's bearing.
glyph.bearing.x = ft_glyph->metrics.horiBearingX >> 6;
glyph.bearing.y = ft_glyph->metrics.horiBearingY >> 6;
// Set the glyph's advance.
glyph.advance = ft_glyph->metrics.horiAdvance >> 6;
// Set the glyph's bitmap dimensions.
glyph.bitmap_dimensions.x = ft_glyph->bitmap.width;
glyph.bitmap_dimensions.y = ft_glyph->bitmap.rows;
// Determine new metrics if we need to scale the bitmap received from FreeType. Only allow bitmap downscaling.
const bool scale_bitmap = (bitmap_scaling_factor < 1.f);
if (scale_bitmap)
{
glyph.dimensions = Vector2i(Vector2f(glyph.dimensions) * bitmap_scaling_factor);
glyph.bearing = Vector2i(Vector2f(glyph.bearing) * bitmap_scaling_factor);
glyph.advance = int(float(glyph.advance) * bitmap_scaling_factor);
glyph.bitmap_dimensions = Vector2i(Vector2f(glyph.bitmap_dimensions) * bitmap_scaling_factor);
}
// Copy the glyph's bitmap data from the FreeType glyph handle to our glyph handle.
if (glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y != 0)
{
// Check if the pixel mode is supported.
if (ft_glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO && ft_glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY &&
ft_glyph->bitmap.pixel_mode != FT_PIXEL_MODE_BGRA)
{
Log::Message(Log::LT_WARNING, "Unable to render glyph on the font face '%s %s': unsupported pixel mode (%d).",
ft_glyph->face->family_name, ft_glyph->face->style_name, ft_glyph->bitmap.pixel_mode);
}
else if (ft_glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO && scale_bitmap)
{
Log::Message(Log::LT_WARNING, "Unable to render glyph on the font face '%s %s': bitmap scaling unsupported in mono pixel mode.",
ft_glyph->face->family_name, ft_glyph->face->style_name);
}
else
{
const int num_bytes_per_pixel = (ft_glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 1);
glyph.color_format = (ft_glyph->bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? ColorFormat::RGBA8 : ColorFormat::A8);
glyph.bitmap_owned_data.reset(new byte[glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y * num_bytes_per_pixel]);
glyph.bitmap_data = glyph.bitmap_owned_data.get();
byte* destination_bitmap = glyph.bitmap_owned_data.get();
const byte* source_bitmap = ft_glyph->bitmap.buffer;
// Copy the bitmap data into the newly-allocated space on our glyph.
switch (ft_glyph->bitmap.pixel_mode)
{
case FT_PIXEL_MODE_MONO:
{
// Unpack 1-bit data into 8-bit.
for (int i = 0; i < glyph.bitmap_dimensions.y; ++i)
{
int mask = 0x80;
const byte* source_byte = source_bitmap;
for (int j = 0; j < glyph.bitmap_dimensions.x; ++j)
{
if ((*source_byte & mask) == mask)
destination_bitmap[j] = 255;
else
destination_bitmap[j] = 0;
mask >>= 1;
if (mask <= 0)
{
mask = 0x80;
++source_byte;
}
}
destination_bitmap += glyph.bitmap_dimensions.x;
source_bitmap += ft_glyph->bitmap.pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_BGRA:
{
if (scale_bitmap)
{
// Resize the glyph data to the new dimensions.
BitmapDownscale(destination_bitmap, glyph.bitmap_dimensions.x, glyph.bitmap_dimensions.y, source_bitmap,
(int)ft_glyph->bitmap.width, (int)ft_glyph->bitmap.rows, ft_glyph->bitmap.pitch, glyph.color_format);
}
else
{
// Copy the glyph data directly.
const int num_bytes_per_line = glyph.bitmap_dimensions.x * num_bytes_per_pixel;
for (int i = 0; i < glyph.bitmap_dimensions.y; ++i)
{
memcpy(destination_bitmap, source_bitmap, num_bytes_per_line);
destination_bitmap += num_bytes_per_line;
source_bitmap += ft_glyph->bitmap.pitch;
}
}
if (glyph.color_format == ColorFormat::RGBA8)
{
// Swizzle channels (BGRA -> RGBA) and un-premultiply alpha.
destination_bitmap = glyph.bitmap_owned_data.get();
for (int k = 0; k < glyph.bitmap_dimensions.x * glyph.bitmap_dimensions.y * num_bytes_per_pixel; k += 4)
{
byte b = destination_bitmap[k];
byte g = destination_bitmap[k + 1];
byte r = destination_bitmap[k + 2];
const byte alpha = destination_bitmap[k + 3];
RMLUI_ASSERTMSG(b <= alpha && g <= alpha && r <= alpha, "Assumption of glyph data being premultiplied is broken.");
if (alpha > 0 && alpha < 255)
{
b = byte((b * 255) / alpha);
g = byte((g * 255) / alpha);
r = byte((r * 255) / alpha);
}
destination_bitmap[k] = r;
destination_bitmap[k + 1] = g;
destination_bitmap[k + 2] = b;
destination_bitmap[k + 3] = alpha;
}
}
}
break;
}
}
}
return true;
}
static void GenerateMetrics(FT_Face ft_face, FontMetrics& metrics, float bitmap_scaling_factor)
{
metrics.line_height = ft_face->size->metrics.height >> 6;
metrics.baseline = metrics.line_height - (ft_face->size->metrics.ascender >> 6);
metrics.underline_position = FT_MulFix(ft_face->underline_position, ft_face->size->metrics.y_scale) * bitmap_scaling_factor / float(1 << 6);
metrics.underline_thickness = FT_MulFix(ft_face->underline_thickness, ft_face->size->metrics.y_scale) * bitmap_scaling_factor / float(1 << 6);
metrics.underline_thickness = Math::Max(metrics.underline_thickness, 1.0f);
// Determine the x-height of this font face.
FT_UInt index = FT_Get_Char_Index(ft_face, 'x');
if (index != 0 && FT_Load_Glyph(ft_face, index, 0) == 0)
metrics.x_height = ft_face->glyph->metrics.height >> 6;
else
metrics.x_height = metrics.line_height / 2;
if (bitmap_scaling_factor != 1.f)
{
metrics.line_height = int(float(metrics.line_height) * bitmap_scaling_factor);
metrics.baseline = int(float(metrics.baseline) * bitmap_scaling_factor);
metrics.x_height = int(float(metrics.x_height) * bitmap_scaling_factor);
}
}
static bool SetFontSize(FT_Face ft_face, int font_size, float& out_bitmap_scaling_factor)
{
RMLUI_ASSERT(out_bitmap_scaling_factor == 1.f);
FT_Error error = 0;
// Set the character size on the font face.
error = FT_Set_Char_Size(ft_face, 0, font_size << 6, 0, 0);
// If setting char size fails, try to select a bitmap strike instead when available.
if (error != 0 && FT_HAS_FIXED_SIZES(ft_face))
{
constexpr int a_big_number = INT_MAX / 2;
int heuristic_min = INT_MAX;
int index_min = -1;
// Select the bitmap strike with the smallest size *above* font_size, or else the largest size.
for (int i = 0; i < ft_face->num_fixed_sizes; i++)
{
const int size_diff = ft_face->available_sizes[i].height - font_size;
const int heuristic = (size_diff < 0 ? a_big_number - size_diff : size_diff);
if (heuristic < heuristic_min)
{
index_min = i;
heuristic_min = heuristic;
}
}
if (index_min >= 0)
{
out_bitmap_scaling_factor = float(font_size) / ft_face->available_sizes[index_min].height;
// Add some tolerance to the scaling factor to avoid unnecessary scaling. Only allow downscaling.
constexpr float bitmap_scaling_factor_threshold = 0.95f;
if (out_bitmap_scaling_factor >= bitmap_scaling_factor_threshold)
out_bitmap_scaling_factor = 1.f;
error = FT_Select_Size(ft_face, index_min);
}
}
if (error != 0)
{
Log::Message(Log::LT_ERROR, "Unable to set the character size '%d' on the font face '%s %s'.", font_size, ft_face->family_name,
ft_face->style_name);
return false;
}
return true;
}
static void BitmapDownscale(byte* bitmap_new, const int new_width, const int new_height, const byte* bitmap_source, const int width, const int height,
const int pitch, const ColorFormat color_format)
{
// Average filter for downscaling bitmap images, based on https://stackoverflow.com/a/9571580
constexpr int max_num_channels = 4;
const int num_channels = (color_format == ColorFormat::RGBA8 ? 4 : 1);
const float xscale = float(new_width) / width;
const float yscale = float(new_height) / height;
const float sumscale = xscale * yscale;
float yend = 0.0f;
for (int f = 0; f < new_height; f++) // y on output
{
const float ystart = yend;
yend = (f + 1) * (1.f / yscale);
if (yend >= height)
yend = height - 0.001f;
float xend = 0.0;
for (int g = 0; g < new_width; g++) // x on output
{
float xstart = xend;
xend = (g + 1) * (1.f / xscale);
if (xend >= width)
xend = width - 0.001f;
float sum[max_num_channels] = {};
for (int y = (int)ystart; y <= (int)yend; ++y)
{
float yportion = 1.0f;
if (y == (int)ystart)
yportion -= ystart - y;
if (y == (int)yend)
yportion -= y + 1 - yend;
for (int x = (int)xstart; x <= (int)xend; ++x)
{
float xportion = 1.0f;
if (x == (int)xstart)
xportion -= xstart - x;
if (x == (int)xend)
xportion -= x + 1 - xend;
for (int i = 0; i < num_channels; i++)
sum[i] += bitmap_source[y * pitch + x * num_channels + i] * yportion * xportion;
}
}
for (int i = 0; i < num_channels; i++)
bitmap_new[(f * new_width + g) * num_channels + i] = (byte)Math::Min(sum[i] * sumscale, 255.f);
}
}
}
} // namespace Rml
| 33.276438 | 194 | 0.709021 | [
"render"
] |
8b091dcd4ae42a4f2be303a25e1192617c818a95 | 45,186 | cpp | C++ | be/src/olap/column_file/column_reader.cpp | gitter-badger/incubator-doris | c877b4301331811c8fea4ef21f77bbf5a284f954 | [
"Apache-2.0"
] | null | null | null | be/src/olap/column_file/column_reader.cpp | gitter-badger/incubator-doris | c877b4301331811c8fea4ef21f77bbf5a284f954 | [
"Apache-2.0"
] | 2 | 2018-11-02T09:04:26.000Z | 2018-11-05T09:04:40.000Z | be/src/olap/column_file/column_reader.cpp | doris-ci/incubator-doris | acb332833a5bbd11232746af3a4576d801adbbf3 | [
"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 <cstring>
#include "olap/column_file/bit_field_reader.h"
#include "olap/column_file/column_reader.h"
#include "olap/column_file/file_stream.h"
#include "olap/olap_define.h"
namespace doris {
namespace column_file {
IntegerColumnReader::IntegerColumnReader(uint32_t column_unique_id):
_eof(false),
_column_unique_id(column_unique_id),
_data_reader(NULL) {
}
IntegerColumnReader::~IntegerColumnReader() {
SAFE_DELETE(_data_reader);
}
OLAPStatus IntegerColumnReader::init(
std::map<StreamName, ReadOnlyFileStream*>* streams, bool is_sign) {
if (NULL == streams) {
OLAP_LOG_WARNING("input streams is NULL");
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
// Get data stream according to column id and type
ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DATA,
streams);
if (data_stream == NULL) {
OLAP_LOG_WARNING("specified stream is NULL");
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_data_reader = new(std::nothrow) RunLengthIntegerReader(data_stream, is_sign);
if (NULL == _data_reader) {
OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader");
return OLAP_ERR_MALLOC_ERROR;
}
// reset eof flag when init, to support reinit
return OLAP_SUCCESS;
}
OLAPStatus IntegerColumnReader::seek(PositionProvider* position) {
return _data_reader->seek(position);
}
OLAPStatus IntegerColumnReader::skip(uint64_t row_count) {
return _data_reader->skip(row_count);
}
OLAPStatus IntegerColumnReader::next(int64_t* value) {
return _data_reader->next(value);
}
StringColumnDirectReader::StringColumnDirectReader(
uint32_t column_unique_id,
uint32_t dictionary_size) :
_eof(false),
_column_unique_id(column_unique_id),
_values(NULL),
_data_stream(NULL),
_length_reader(NULL) {
}
StringColumnDirectReader::~StringColumnDirectReader() {
SAFE_DELETE(_length_reader);
}
OLAPStatus StringColumnDirectReader::init(
std::map<StreamName, ReadOnlyFileStream*>* streams,
int size, MemPool* mem_pool) {
if (NULL == streams) {
OLAP_LOG_WARNING("input streams is NULL");
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
// Get data stream according to column id and type
_data_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DATA,
streams);
if (NULL == _data_stream) {
OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_values = reinterpret_cast<StringSlice*>(mem_pool->allocate(size * sizeof(StringSlice)));
ReadOnlyFileStream* length_stream = extract_stream(_column_unique_id,
StreamInfoMessage::LENGTH,
streams);
if (NULL == length_stream) {
OLAP_LOG_WARNING("specifiedstream not found. [unique_id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_length_reader = new(std::nothrow) RunLengthIntegerReader(length_stream, false);
if (NULL == _length_reader) {
OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader");
return OLAP_ERR_MALLOC_ERROR;
}
return OLAP_SUCCESS;
}
OLAPStatus StringColumnDirectReader::seek(PositionProvider* position) {
OLAPStatus res = _data_stream->seek(position);
// All strings in segment may be empty, so the data stream is EOF and
// and length stream is not EOF.
if (OLAP_SUCCESS == res || OLAP_ERR_COLUMN_STREAM_EOF == res) {
res = _length_reader->seek(position);
}
return res;
}
OLAPStatus StringColumnDirectReader::skip(uint64_t row_count) {
OLAPStatus res = OLAP_SUCCESS;
int64_t skip_length = 0;
int64_t tmp_length = 0;
for (size_t i = 0; i < row_count; ++i) {
res = _length_reader->next(&tmp_length);
if (OLAP_SUCCESS != res) {
return res;
}
skip_length += tmp_length;
}
if (OLAP_SUCCESS == res) {
// TODO: skip function of instream is implemented, but not tested
return _data_stream->skip(skip_length);
}
return res;
}
// Return string field of current row_count
OLAPStatus StringColumnDirectReader::next(char* buffer, uint32_t* length) {
int64_t read_length = 0;
OLAPStatus res = _length_reader->next(&read_length);
*length = read_length;
while (OLAP_SUCCESS == res && read_length > 0) {
uint64_t buf_size = read_length;
res = _data_stream->read(buffer, &buf_size);
read_length -= buf_size;
buffer += buf_size;
}
*length -= read_length;
return res;
}
OLAPStatus StringColumnDirectReader::next_vector(
ColumnVector* column_vector,
uint32_t size,
MemPool* mem_pool,
int64_t* read_bytes) {
/*
* MemPool here is not the same as MemPool in init function
* 1. MemPool is created by VectorizedRowBatch,
* and reset when load row batch
* 2. MemPool in init function is created by SegmentReader,
* and free by SegmentReader deconstructor.
*/
OLAPStatus res = OLAP_SUCCESS;
int64_t length = 0;
int64_t string_buffer_size = 0;
column_vector->set_col_data(_values);
if (column_vector->no_nulls()) {
for (int i = 0; i < size; ++i) {
res = _length_reader->next(&length);
if (OLAP_SUCCESS != res) {
return res;
}
_values[i].size = length;
string_buffer_size += length;
}
char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(string_buffer_size));
for (int i = 0; i < size; ++i) {
_values[i].data = string_buffer;
length = _values[i].size;
while (length > 0) {
uint64_t buf_size = length;
res = _data_stream->read(string_buffer, &buf_size);
if (res != OLAP_SUCCESS) {
return res;
}
length -= buf_size;
string_buffer += buf_size;
}
}
} else {
bool* is_null = column_vector->is_null();
for (int i = 0; i < size; ++i) {
if (!is_null[i]) {
res = _length_reader->next(&length);
if (OLAP_SUCCESS != res) {
return res;
}
_values[i].size = length;
string_buffer_size += length;
} else {
_values[i].size = 0;
}
}
char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(string_buffer_size));
for (int i = 0; i < size; ++i) {
if (!is_null[i]) {
length = _values[i].size;
_values[i].data = string_buffer;
while (length > 0) {
uint64_t buf_size = length;
res = _data_stream->read(string_buffer, &buf_size);
if (res != OLAP_SUCCESS) {
return res;
}
length -= buf_size;
string_buffer += buf_size;
}
} else {
_values[i].data = nullptr;
_values[i].size = 0;
}
}
}
*read_bytes += string_buffer_size;
return res;
}
StringColumnDictionaryReader::StringColumnDictionaryReader(
uint32_t column_unique_id,
uint32_t dictionary_size) :
_eof(false),
_dictionary_size(dictionary_size),
_column_unique_id(column_unique_id),
_values(NULL),
//_dictionary_size(0),
//_offset_dictionary(NULL),
//_dictionary_data_buffer(NULL),
_read_buffer(NULL),
_data_reader(NULL) {
}
StringColumnDictionaryReader::~StringColumnDictionaryReader() {
//SAFE_DELETE_ARRAY(_offset_dictionary);
//SAFE_DELETE(_dictionary_data_buffer);
SAFE_DELETE(_data_reader);
SAFE_DELETE_ARRAY(_read_buffer);
}
/*
// TODO.改为先解析成字典,不过看起来也不会太快,因为这里会全部解析完,而放在后边解析可能能省点资源
// 后边再测,先保留代码
OLAPStatus StringColumnDictionaryReader::init(std::map<StreamName, ReadOnlyFileStream *> *streams,
UniqueIdEncodingMap* encodings,
RuntimeProfile* profile) {
ReadOnlyFileStream* dictionary_data_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DICTIONARY_DATA,
streams);
if (NULL == dictionary_data_stream) {
OLAP_LOG_WARNING("dictionary data stream not found. [unique id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
if (dictionary_data_stream->stream_length() > 0) {
_dictionary_data_buffer = ByteBuffer::create(
dictionary_data_stream->estimate_uncompressed_length());
size_t offset = 0;
size_t length = 0;
// TODO. stream 还需要修改,使之真正能够方便的读取
while (0 != (length = dictionary_data_stream->available())) {
dictionary_data_stream->read(_dictionary_data_buffer->array() + offset, &length);
offset += length;
}
} else {
_dictionary_data_buffer = NULL;
}
UniqueIdEncodingMap::iterator it = encodings->find(_column_unique_id);
if (it == encodings->end()) {
OLAP_LOG_WARNING("encoding not found. [unique id = %u]", _column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
uint64_t dictionary_size = (*it).second.dictionary_size();
// 建立字典偏移列表
ReadOnlyFileStream* dictionary_length_stream = extract_stream(_column_unique_id,
StreamInfoMessage::LENGTH,
streams);
if (NULL == dictionary_length_stream) {
OLAP_LOG_WARNING("dictionary length stream not found. [unique id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
RunLengthIntegerReader* dictionary_length_reader =
new (std::nothrow) RunLengthIntegerReader(dictionary_length_stream, true);
uint64_t offset = 0;
// 如果上次分配的空间足够多,这次可以不分配
if (dictionary_size + 1 > _dictionary_size || NULL == _offset_dictionary) {
SAFE_DELETE_ARRAY(_offset_dictionary);
_dictionary_size = dictionary_size + 1;
_offset_dictionary = new (std::nothrow) uint64_t[_dictionary_size];
if (NULL == _offset_dictionary) {
OLAP_LOG_WARNING("fail to allocate dictionary buffer");
return OLAP_ERR_MALLOC_ERROR;
}
}
// 应该只有dictionary_size 项,最后一个单位保存一个“不存在的”位置,
// 也就是最后一个字符串的终止位置,这样做是为了支持偏移计算的算法不用处理边界
int64_t value = 0;
OLAPStatus res = OLAP_SUCCESS;
size_t dictionary_entry = 0;
for (; dictionary_entry < dictionary_size; ++dictionary_entry) {
_offset_dictionary[dictionary_entry] = offset;
res = dictionary_length_reader->next(&value);
// 理论上应该足够读,读出eof也是不对的。
if (OLAP_SUCCESS != res && OLAP_ERR_DATA_EOF != res) {
OLAP_LOG_WARNING("build offset dictionary failed. [res = %d]", res);
return res;
}
offset += value;
}
_offset_dictionary[dictionary_entry] = offset;
// 建立数据流读取器
ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DATA,
streams);
if (NULL == data_stream) {
OLAP_LOG_WARNING("data stream not found. [unique id = %u]", _column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_data_reader = new (std::nothrow) RunLengthIntegerReader(data_stream, true);
if (NULL == _data_reader) {
OLAP_LOG_WARNING("fail to malloc data reader");
return OLAP_ERR_MALLOC_ERROR;
}
return OLAP_SUCCESS;
}
*/
OLAPStatus StringColumnDictionaryReader::init(
std::map<StreamName, ReadOnlyFileStream*>* streams,
int size, MemPool* mem_pool) {
ReadOnlyFileStream* dictionary_data_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DICTIONARY_DATA,
streams);
if (NULL == dictionary_data_stream) {
OLAP_LOG_WARNING("dictionary data stream not found. [unique id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
ReadOnlyFileStream* dictionary_length_stream = extract_stream(_column_unique_id,
StreamInfoMessage::LENGTH,
streams);
if (NULL == dictionary_length_stream) {
OLAP_LOG_WARNING("dictionary length stream not found. [unique id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
RunLengthIntegerReader* dictionary_length_reader =
new(std::nothrow) RunLengthIntegerReader(dictionary_length_stream, false);
OLAPStatus res = OLAP_SUCCESS;
/*
uint64_t offset = 0;
int64_t value = 0;
size_t length_remain = 0;
size_t length_to_read = 0;
size_t read_buffer_size = 1024;
ByteBuffer* read_buffer = ByteBuffer::create(read_buffer_size);
if (NULL == read_buffer) {
OLAP_LOG_WARNING("fail to malloc ByteBuffer");
return OLAP_ERR_MALLOC_ERROR;
}
for (size_t dictionary_entry = 0; dictionary_entry < dictionary_size; ++dictionary_entry) {
res = dictionary_length_reader->next(&value);
// 理论上应该足够读,读出eof也是不对的。
if (OLAP_SUCCESS != res && OLAP_ERR_DATA_EOF != res) {
OLAP_LOG_WARNING("build offset dictionary failed. [res = %d]", res);
return res;
}
// 其实为offset,长度为value的string
length_remain = value;
std::string dictionary_item;
while (length_remain != 0) {
length_to_read = std::min(length_remain, read_buffer_size);
res = dictionary_data_stream->read(read_buffer->array(), &length_to_read);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("read dictionary content failed");
return res;
}
dictionary_item.append(read_buffer->array(), length_to_read);
length_remain -= length_to_read;
}
_dictionary.push_back(dictionary_item);
offset += value;
}
*/
_values = reinterpret_cast<StringSlice*>(mem_pool->allocate(size * sizeof(StringSlice)));
int64_t read_buffer_size = 1024;
char* _read_buffer = new(std::nothrow) char[read_buffer_size];
if (NULL == _read_buffer) {
OLAP_LOG_WARNING("fail to malloc read buffer. [size = %lu]", read_buffer_size);
return OLAP_ERR_MALLOC_ERROR;
}
int64_t length = 0;
uint64_t read_length = 0;
std::string dictionary_item;
for (size_t dictionary_entry = 0; dictionary_entry < _dictionary_size; ++dictionary_entry) {
res = dictionary_length_reader->next(&length);
// 理论上应该足够读,读出eof也是不对的。
if (OLAP_SUCCESS != res || length < 0) {
OLAP_LOG_WARNING("build offset dictionary failed. [res = %d]", res);
return res;
}
if (length > read_buffer_size) {
SAFE_DELETE_ARRAY(_read_buffer);
read_buffer_size = length;
if (NULL == (_read_buffer = new(std::nothrow) char[read_buffer_size])) {
OLAP_LOG_WARNING("fail to malloc read buffer. [size = %lu]", read_buffer_size);
return OLAP_ERR_MALLOC_ERROR;
}
}
read_length = length;
dictionary_data_stream->read(_read_buffer, &read_length);
if (static_cast<int64_t>(read_length) != length) {
OLAP_LOG_WARNING("read stream fail.");
return OLAP_ERR_COLUMN_READ_STREAM;
}
dictionary_item.assign(_read_buffer, length);
_dictionary.push_back(dictionary_item);
}
// 建立数据流读取器
ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DATA,
streams);
if (NULL == data_stream) {
OLAP_LOG_WARNING("data stream not found. [unique id = %u]", _column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_data_reader = new(std::nothrow) RunLengthIntegerReader(data_stream, false);
if (NULL == _data_reader) {
OLAP_LOG_WARNING("fail to malloc data reader");
return OLAP_ERR_MALLOC_ERROR;
}
SAFE_DELETE_ARRAY(_read_buffer);
SAFE_DELETE(dictionary_length_reader);
return OLAP_SUCCESS;
}
OLAPStatus StringColumnDictionaryReader::seek(PositionProvider* position) {
return _data_reader->seek(position);
}
OLAPStatus StringColumnDictionaryReader::skip(uint64_t row_count) {
return _data_reader->skip(row_count);
}
OLAPStatus StringColumnDictionaryReader::next(char* buffer, uint32_t* length) {
int64_t value;
OLAPStatus res = _data_reader->next(&value);
// 错误或是EOF
if (OLAP_SUCCESS != res) {
if (OLAP_ERR_DATA_EOF == res) {
_eof = true;
}
return res;
}
if (value >= static_cast<int64_t>(_dictionary.size())) {
OLAP_LOG_WARNING("value may indicated an invalid dictionary entry. "
"[value = %lu, dictionary_size = %lu]",
value, _dictionary.size());
return OLAP_ERR_BUFFER_OVERFLOW;
}
memcpy(buffer, _dictionary[value].c_str(), _dictionary[value].size());
*length = _dictionary[value].size();
return OLAP_SUCCESS;
}
OLAPStatus StringColumnDictionaryReader::next_vector(
ColumnVector* column_vector,
uint32_t size,
MemPool* mem_pool,
int64_t* read_bytes) {
int64_t index[size];
int64_t buffer_size = 0;
OLAPStatus res = OLAP_SUCCESS;
column_vector->set_col_data(_values);
if (column_vector->no_nulls()) {
for (int i = 0; i < size; ++i) {
res = _data_reader->next(&index[i]);
if (OLAP_SUCCESS != res) {
return res;
}
if (index[i] >= static_cast<int64_t>(_dictionary.size())) {
OLAP_LOG_WARNING("value may indicated an invalid dictionary entry. "
"[index = %lu, dictionary_size = %lu]",
index[i], _dictionary.size());
return OLAP_ERR_BUFFER_OVERFLOW;
}
_values[i].size = _dictionary[index[i]].size();
buffer_size += _values[i].size;
}
char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(buffer_size));
for (int i = 0; i < size; ++i) {
memory_copy(string_buffer,
_dictionary[index[i]].c_str(),
_values[i].size);
_values[i].data = string_buffer;
string_buffer += _values[i].size;
}
} else {
bool* is_null = column_vector->is_null();
for (int i = 0; i < size; ++i) {
if (!is_null[i]) {
res = _data_reader->next(&index[i]);
if (OLAP_SUCCESS != res) {
return res;
}
if (index[i] >= static_cast<int64_t>(_dictionary.size())) {
OLAP_LOG_WARNING("value may indicated an invalid dictionary entry. "
"[index = %lu, dictionary_size = %lu]",
index[i], _dictionary.size());
return OLAP_ERR_BUFFER_OVERFLOW;
}
_values[i].size = _dictionary[index[i]].size();
buffer_size += _values[i].size;
}
}
char* string_buffer = reinterpret_cast<char*>(mem_pool->allocate(buffer_size));
for (int i = 0; i < size; ++i) {
if (!is_null[i]) {
memory_copy(string_buffer,
_dictionary[index[i]].c_str(),
_values[i].size);
_values[i].data = string_buffer;
string_buffer += _values[i].size;
}
}
}
*read_bytes += buffer_size;
return res;
}
ColumnReader::ColumnReader(uint32_t column_id, uint32_t column_unique_id) :
_value_present(false),
_is_null(NULL),
_column_id(column_id),
_column_unique_id(column_unique_id),
_present_reader(NULL) {
}
ColumnReader* ColumnReader::create(uint32_t column_id,
const std::vector<FieldInfo>& columns,
const UniqueIdToColumnIdMap& included,
UniqueIdToColumnIdMap& segment_included,
const UniqueIdEncodingMap& encodings) {
if (column_id >= columns.size()) {
OLAP_LOG_WARNING("invalid column_id, column_id=%u, columns_size=%lu",
column_id, columns.size());
return NULL;
}
const FieldInfo& field_info = columns[column_id];
ColumnReader* reader = NULL;
uint32_t column_unique_id = field_info.unique_id;
if (0 == included.count(column_unique_id)) {
return NULL;
}
if (0 == segment_included.count(column_unique_id)) {
if (field_info.has_default_value) {
if (0 == strcasecmp("NULL", field_info.default_value.c_str())
&& field_info.is_allow_null) {
return new(std::nothrow) NullValueReader(column_id, column_unique_id);
} else {
return new(std::nothrow) DefaultValueReader(column_id, column_unique_id,
field_info.default_value, field_info.type, field_info.length);
}
} else if (field_info.is_allow_null) {
LOG(WARNING) << "create NullValueReader: " << field_info.name;
return new(std::nothrow) NullValueReader(column_id, column_unique_id);
} else {
OLAP_LOG_WARNING("not null field has no default value");
return NULL;
}
}
uint32_t dictionary_size = 0;
ColumnEncodingMessage::Kind encode_kind = ColumnEncodingMessage::DIRECT;
UniqueIdEncodingMap::const_iterator it = encodings.find(column_unique_id);
if (it != encodings.end()) {
encode_kind = (*it).second.kind();
dictionary_size = (*it).second.dictionary_size();
}
switch (field_info.type) {
case OLAP_FIELD_TYPE_TINYINT:
case OLAP_FIELD_TYPE_UNSIGNED_TINYINT: {
reader = new(std::nothrow) TinyColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_SMALLINT: {
reader = new(std::nothrow) IntegerColumnReaderWrapper<int16_t, true>(
column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_UNSIGNED_SMALLINT: {
reader = new(std::nothrow) IntegerColumnReaderWrapper<uint16_t, false>(
column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_INT: {
reader = new(std::nothrow) IntegerColumnReaderWrapper<int32_t, true>(
column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_UNSIGNED_INT: {
reader = new(std::nothrow) IntegerColumnReaderWrapper<uint32_t, false>(
column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_BIGINT: {
reader = new(std::nothrow) IntegerColumnReaderWrapper<int64_t, true>(
column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_UNSIGNED_BIGINT: {
reader = new(std::nothrow) IntegerColumnReaderWrapper<uint64_t, false>(
column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_FLOAT: {
reader = new(std::nothrow) FloatColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_DOUBLE: {
reader = new(std::nothrow) DoubleColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_DISCRETE_DOUBLE: {
reader = new(std::nothrow) DiscreteDoubleColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_CHAR: {
if (ColumnEncodingMessage::DIRECT == encode_kind) {
reader = new(std::nothrow) FixLengthStringColumnReader<StringColumnDirectReader>(
column_id, column_unique_id, field_info.length, dictionary_size);
} else if (ColumnEncodingMessage::DICTIONARY == encode_kind) {
reader = new(std::nothrow) FixLengthStringColumnReader<StringColumnDictionaryReader>(
column_id, column_unique_id, field_info.length, dictionary_size);
} else {
OLAP_LOG_WARNING("known encoding format. data may be generated by higher version,"
"try updating olapengine binary to solve this problem");
// TODO. define a new return code
return NULL;
}
break;
}
case OLAP_FIELD_TYPE_DATETIME: {
reader = new(std::nothrow) DateTimeColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_DATE: {
reader = new(std::nothrow) DateColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_DECIMAL: {
reader = new(std::nothrow) DecimalColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_LARGEINT: {
reader = new(std::nothrow) LargeIntColumnReader(column_id, column_unique_id);
break;
}
case OLAP_FIELD_TYPE_VARCHAR:
case OLAP_FIELD_TYPE_HLL: {
if (ColumnEncodingMessage::DIRECT == encode_kind) {
reader = new(std::nothrow) VarStringColumnReader<StringColumnDirectReader>(
column_id, column_unique_id, field_info.length, dictionary_size);
} else if (ColumnEncodingMessage::DICTIONARY == encode_kind) {
reader = new(std::nothrow) VarStringColumnReader<StringColumnDictionaryReader>(
column_id, column_unique_id, field_info.length, dictionary_size);
} else {
OLAP_LOG_WARNING("known encoding format. data may be generated by higher version, "
"try updating olapengine binary to solve this problem");
// TODO. define a new return code
return NULL;
}
break;
}
case OLAP_FIELD_TYPE_STRUCT:
case OLAP_FIELD_TYPE_LIST:
case OLAP_FIELD_TYPE_MAP:
default: {
LOG(WARNING) << "unspported filed type. [field=" << field_info.name
<< " type=" << field_info.type << "]";
break;
}
}
if (NULL != reader) {
std::vector<uint32_t>::const_iterator it;
for (it = field_info.sub_columns.begin(); it != field_info.sub_columns.end(); ++it) {
ColumnReader* sub_reader = create((*it), columns, included,
segment_included, encodings);
if (NULL == sub_reader) {
OLAP_LOG_WARNING("fail to create sub column reader.");
SAFE_DELETE(reader);
return NULL;
}
reader->_sub_readers.push_back(sub_reader);
}
}
return reader;
}
ColumnReader::~ColumnReader() {
SAFE_DELETE(_present_reader);
}
OLAPStatus ColumnReader::init(
std::map<StreamName, ReadOnlyFileStream*>* streams,
int size, MemPool* mem_pool,
OlapReaderStatistics* stats) {
if (NULL == streams) {
OLAP_LOG_WARNING("null parameters given.");
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
_stats = stats;
// 从map中找到需要的流,ColumnReader的数据应该由一条PRESENT流和一条ROW_INDEX流组成
ReadOnlyFileStream* present_stream = extract_stream(_column_unique_id,
StreamInfoMessage::PRESENT,
streams);
_is_null = reinterpret_cast<bool*>(mem_pool->allocate(size));
memset(_is_null, 0, size);
if (NULL == present_stream) {
_present_reader = NULL;
_value_present = false;
} else {
OLAP_LOG_DEBUG("create null present_stream for column_id: %d", _column_unique_id);
_present_reader = new(std::nothrow) BitFieldReader(present_stream);
if (NULL == _present_reader) {
OLAP_LOG_WARNING("malloc present reader failed.");
return OLAP_ERR_MALLOC_ERROR;
}
if (OLAP_SUCCESS != _present_reader->init()) {
OLAP_LOG_WARNING("fail to init present reader.");
return OLAP_ERR_INIT_FAILED;
}
_value_present = true;
}
return OLAP_SUCCESS;
}
OLAPStatus ColumnReader::seek(PositionProvider* position) {
if (NULL != _present_reader) {
return _present_reader->seek(position);
}
return OLAP_SUCCESS;
}
OLAPStatus ColumnReader::skip(uint64_t row_count) {
return OLAP_SUCCESS;
}
OLAPStatus ColumnReader::next_vector(
ColumnVector* column_vector,
uint32_t size,
MemPool* mem_pool) {
OLAPStatus res = OLAP_SUCCESS;
column_vector->set_is_null(_is_null);
if (NULL != _present_reader) {
column_vector->set_no_nulls(false);
for (uint32_t i = 0; i < size; ++i) {
bool value = false;
res = _present_reader->next((char*)&value);
if (OLAP_SUCCESS != res) {
break;
}
_is_null[i] = value;
}
_stats->bytes_read += size;
} else {
column_vector->set_no_nulls(true);
}
return res;
}
uint64_t ColumnReader::_count_none_nulls(uint64_t rows) {
if (_present_reader != NULL) {
OLAPStatus res = OLAP_SUCCESS;
uint64_t result = 0;
for (uint64_t counter = 0; counter < rows; ++counter) {
res = _present_reader->next(reinterpret_cast<char*>(&_value_present));
if (OLAP_SUCCESS == res && (false == _value_present)) {
result += 1;
} else {
break;
}
}
return result;
} else {
return rows;
}
}
TinyColumnReader::TinyColumnReader(uint32_t column_id, uint32_t column_unique_id) :
ColumnReader(column_id, column_unique_id),
_eof(false),
_values(NULL),
_data_reader(NULL) {}
TinyColumnReader::~TinyColumnReader() {
SAFE_DELETE(_data_reader);
}
OLAPStatus TinyColumnReader::init(
std::map<StreamName, ReadOnlyFileStream*>* streams,
int size, MemPool* mem_pool,
OlapReaderStatistics* stats) {
if (NULL == streams) {
OLAP_LOG_WARNING("input streams is NULL");
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
ColumnReader::init(streams, size, mem_pool, stats);
ReadOnlyFileStream* data_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DATA,
streams);
if (NULL == data_stream) {
OLAP_LOG_WARNING("specified stream not exist");
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_values = reinterpret_cast<char*>(mem_pool->allocate(size));
_data_reader = new(std::nothrow) RunLengthByteReader(data_stream);
if (NULL == _data_reader) {
OLAP_LOG_WARNING("malloc data reader failed");
return OLAP_ERR_MALLOC_ERROR;
}
return OLAP_SUCCESS;
}
OLAPStatus TinyColumnReader::seek(PositionProvider* positions) {
OLAPStatus res;
if (NULL == _present_reader) {
res = _data_reader->seek(positions);
if (OLAP_SUCCESS != res) {
return res;
}
} else {
res = ColumnReader::seek(positions);
if (OLAP_SUCCESS != res) {
return res;
}
res = _data_reader->seek(positions);
if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) {
OLAP_LOG_WARNING("fail to seek tinyint stream. [res=%d]", res);
return res;
}
}
return OLAP_SUCCESS;
}
OLAPStatus TinyColumnReader::skip(uint64_t row_count) {
// count_none_nulls 其实就是columnReader的跳过函数。
return _data_reader->skip(_count_none_nulls(row_count));
}
OLAPStatus TinyColumnReader::next_vector(
ColumnVector* column_vector,
uint32_t size,
MemPool* mem_pool) {
OLAPStatus res = ColumnReader::next_vector(column_vector, size, mem_pool);
if (OLAP_SUCCESS != res) {
if (OLAP_ERR_DATA_EOF == res) {
_eof = true;
}
return res;
}
bool* is_null = column_vector->is_null();
column_vector->set_col_data(_values);
if (column_vector->no_nulls()) {
for (uint32_t i = 0; i < size; ++i) {
res = _data_reader->next(_values + i);
if (OLAP_SUCCESS != res) {
break;
}
}
} else {
for (uint32_t i = 0; i < size; ++i) {
if (!is_null[i]) {
res = _data_reader->next(_values + i);
if (OLAP_SUCCESS != res) {
break;
}
}
}
}
_stats->bytes_read += size;
if (OLAP_ERR_DATA_EOF == res) {
_eof = true;
}
return res;
}
DecimalColumnReader::DecimalColumnReader(uint32_t column_id, uint32_t column_unique_id) :
ColumnReader(column_id, column_unique_id),
_eof(false),
_values(NULL),
_int_reader(NULL),
_frac_reader(NULL) {
}
DecimalColumnReader::~DecimalColumnReader() {
SAFE_DELETE(_int_reader);
SAFE_DELETE(_frac_reader);
}
OLAPStatus DecimalColumnReader::init(
std::map<StreamName, ReadOnlyFileStream*>* streams,
int size, MemPool* mem_pool,
OlapReaderStatistics* stats) {
if (NULL == streams) {
OLAP_LOG_WARNING("input streams is NULL");
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
// reset stream and reader
ColumnReader::init(streams, size, mem_pool, stats);
_values = reinterpret_cast<decimal12_t*>(mem_pool->allocate(size * sizeof(decimal12_t)));
// 从map中找到需要的流,StringColumnReader的数据应该由一条DATA流和一条LENGTH流组成
ReadOnlyFileStream* int_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DATA,
streams);
if (NULL == int_stream) {
OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
ReadOnlyFileStream* frac_stream = extract_stream(_column_unique_id,
StreamInfoMessage::SECONDARY,
streams);
if (NULL == frac_stream) {
OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_int_reader = new(std::nothrow) RunLengthIntegerReader(int_stream, true);
if (NULL == _int_reader) {
OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader");
return OLAP_ERR_MALLOC_ERROR;
}
_frac_reader = new(std::nothrow) RunLengthIntegerReader(frac_stream, true);
if (NULL == _frac_reader) {
OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader");
return OLAP_ERR_MALLOC_ERROR;
}
return OLAP_SUCCESS;
}
OLAPStatus DecimalColumnReader::seek(PositionProvider* positions) {
OLAPStatus res;
if (NULL == _present_reader) {
res = _int_reader->seek(positions);
if (OLAP_SUCCESS != res) {
return res;
}
res = _frac_reader->seek(positions);
if (OLAP_SUCCESS != res) {
return res;
}
} else {
//all field in the segment can be NULL, so the data stream is EOF
res = ColumnReader::seek(positions);
if (OLAP_SUCCESS != res) {
return res;
}
res = _int_reader->seek(positions);
if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) {
OLAP_LOG_WARNING("fail to seek int stream of decimal. [res=%d]", res);
return res;
}
res = _frac_reader->seek(positions);
if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) {
OLAP_LOG_WARNING("fail to seek frac stream of decimal. [res=%d]", res);
return res;
}
}
return OLAP_SUCCESS;
}
OLAPStatus DecimalColumnReader::skip(uint64_t row_count) {
OLAPStatus res = _int_reader->skip(row_count);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to create int part reader");
return res;
}
res = _frac_reader->skip(row_count);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to create frac part reader");
return res;
}
return OLAP_SUCCESS;
}
OLAPStatus DecimalColumnReader::next_vector(
ColumnVector* column_vector,
uint32_t size,
MemPool* mem_pool) {
OLAPStatus res = ColumnReader::next_vector(column_vector, size, mem_pool);
if (OLAP_SUCCESS != res) {
if (OLAP_ERR_DATA_EOF == res) {
_eof = true;
}
return res;
}
bool* is_null = column_vector->is_null();
column_vector->set_col_data(_values);
if (column_vector->no_nulls()) {
for (uint32_t i = 0; i < size; ++i) {
int64_t value = 0;
OLAPStatus res = _int_reader->next(&value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal int part");
break;
}
_values[i].integer = value;
res = _frac_reader->next(&value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal frac part");
break;
}
_values[i].fraction = value;
}
} else {
for (uint32_t i = 0; i < size; ++i) {
int64_t value = 0;
if (!is_null[i]) {
OLAPStatus res = _int_reader->next(&value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal int part");
break;
}
_values[i].integer = value;
res = _frac_reader->next(&value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal frac part");
break;
}
_values[i].fraction = value;
}
}
}
_stats->bytes_read += sizeof(decimal12_t) * size;
return res;
}
LargeIntColumnReader::LargeIntColumnReader(uint32_t column_id, uint32_t column_unique_id) :
ColumnReader(column_id, column_unique_id),
_eof(false),
_values(NULL),
_high_reader(NULL),
_low_reader(NULL) {}
LargeIntColumnReader::~LargeIntColumnReader() {
SAFE_DELETE(_high_reader);
SAFE_DELETE(_low_reader);
}
OLAPStatus LargeIntColumnReader::init(
std::map<StreamName, ReadOnlyFileStream*>* streams,
int size, MemPool* mem_pool,
OlapReaderStatistics* stats) {
if (NULL == streams) {
OLAP_LOG_WARNING("input streams is NULL");
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
// reset stream and reader
ColumnReader::init(streams, size, mem_pool, stats);
_values = reinterpret_cast<int128_t*>(
mem_pool->try_allocate_aligned(size * sizeof(int128_t), alignof(int128_t)));
// 从map中找到需要的流,LargeIntColumnReader的数据应该由一条DATA流组成
ReadOnlyFileStream* high_stream = extract_stream(_column_unique_id,
StreamInfoMessage::DATA,
streams);
if (NULL == high_stream) {
OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
ReadOnlyFileStream* low_stream = extract_stream(_column_unique_id,
StreamInfoMessage::SECONDARY,
streams);
if (NULL == low_stream) {
OLAP_LOG_WARNING("specified stream not found. [unique_id = %u]",
_column_unique_id);
return OLAP_ERR_COLUMN_STREAM_NOT_EXIST;
}
_high_reader = new(std::nothrow) RunLengthIntegerReader(high_stream, true);
if (NULL == _high_reader) {
OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader.");
return OLAP_ERR_MALLOC_ERROR;
}
_low_reader = new(std::nothrow) RunLengthIntegerReader(low_stream, true);
if (NULL == _low_reader) {
OLAP_LOG_WARNING("fail to malloc RunLengthIntegerReader.");
return OLAP_ERR_MALLOC_ERROR;
}
return OLAP_SUCCESS;
}
OLAPStatus LargeIntColumnReader::seek(PositionProvider* positions) {
OLAPStatus res;
if (NULL == _present_reader) {
res = _high_reader->seek(positions);
if (OLAP_SUCCESS != res) {
return res;
}
res = _low_reader->seek(positions);
if (OLAP_SUCCESS != res) {
return res;
}
} else {
//all field in the segment can be NULL, so the data stream is EOF
res = ColumnReader::seek(positions);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to seek null stream of largeint");
return res;
}
res = _high_reader->seek(positions);
if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) {
OLAP_LOG_WARNING("fail to seek high int stream of largeint. [res=%d]", res);
return res;
}
res = _low_reader->seek(positions);
if (OLAP_SUCCESS != res && OLAP_ERR_COLUMN_STREAM_EOF != res) {
OLAP_LOG_WARNING("fail to seek low int stream of largeint. [res=%d]", res);
return res;
}
}
return OLAP_SUCCESS;
}
OLAPStatus LargeIntColumnReader::skip(uint64_t row_count) {
OLAPStatus res = _high_reader->skip(row_count);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to skip large int high part. [res=%d]", res);
return res;
}
res = _low_reader->skip(row_count);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to skip large int low part reader. [res=%d]", res);
return res;
}
return OLAP_SUCCESS;
}
OLAPStatus LargeIntColumnReader::next_vector(
ColumnVector* column_vector,
uint32_t size,
MemPool* mem_pool) {
OLAPStatus res = ColumnReader::next_vector(column_vector, size, mem_pool);
if (OLAP_SUCCESS != res) {
if (OLAP_ERR_DATA_EOF == res) {
_eof = true;
}
return res;
}
bool* is_null = column_vector->is_null();
column_vector->set_col_data(_values);
if (column_vector->no_nulls()) {
for (uint32_t i = 0; i < size; ++i) {
int64_t* value = NULL;
value = (int64_t*)(_values + i);
res = _high_reader->next(value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal int part");
break;
}
res = _low_reader->next(++value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal frac part");
break;
}
}
} else {
for (uint32_t i = 0; i < size; ++i) {
int64_t* value = NULL;
if (!is_null[i]) {
value = (int64_t*)(_values + i);
res = _high_reader->next(value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal int part");
break;
}
res = _low_reader->next(++value);
if (OLAP_SUCCESS != res) {
OLAP_LOG_WARNING("fail to read decimal frac part");
break;
}
}
}
}
_stats->bytes_read += 16 * size;
return res;
}
} // namespace column_file
} // namespace doris
| 33.225 | 98 | 0.600783 | [
"vector"
] |
8b0acb47106260464907076a04953bbf609c006a | 10,651 | cpp | C++ | KernelSDK/src/kernel/KernelExec/cDevTestToggle.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 38 | 2018-09-24T09:37:41.000Z | 2022-02-21T04:16:43.000Z | KernelSDK/src/kernel/KernelExec/cDevTestToggle.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 1 | 2018-10-02T17:57:44.000Z | 2018-10-07T06:55:44.000Z | KernelSDK/src/kernel/KernelExec/cDevTestToggle.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 6 | 2018-10-02T17:12:38.000Z | 2021-01-27T10:01:30.000Z | // Copyright 2018 Grass Valley, A Belden Brand
// 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 "stdafx.h"
#include "LogCategories.h"
#include "cFile.h"
using namespace vfs;
namespace
{
const Char* const kDevTestRegistryKey = L"Software\\vfs\\_DevTest"; //!< \brief When running a T version we get our toggles from the registry
const Char* const kDevTestFileName = L"Toggles.sys"; //!< \brief When running an S version we get our toggles from a file
bool kTrueBool = true; //!< \brief When using file toggles, they all point to this boolean
//{{{
class cDevTestToggleManager
{
public:
//{{{
cDevTestToggleManager()
: mInitialised(false), mRegTogglesAvailable(false), mForceTogglesOn(false), mForceTogglesOff(false), mFileTogglesAvailable(false)
{
}
//}}}
//{{{
bool isAvailable()
{
if (!mInitialised)
initialise();
return (mRegTogglesAvailable || mFileTogglesAvailable);
}
//}}}
//{{{
bool* getBoolForToggle(bool* toggle, String variableName, String description)
{
cLockGuard lg(&mLock); // take the lock while constructing a toggle (std::map not thread safe!)
tTogglesMap::const_iterator it = mToggles.find(variableName);
if (it != mToggles.end())
toggle = it->second.first;
else
{
if (mRegTogglesAvailable)
{
mToggleStorage.push_back(false);
toggle = &mToggleStorage.back();
mToggles[variableName] = std::make_pair(toggle, description);
createRegistryToggle(variableName, description);
*toggle = getRegistryToggleValue(variableName);
}
}
return toggle; // return the bool*
}
//}}}
//{{{
void updateAll()
{
if (!mInitialised)
initialise();
if (mRegTogglesAvailable)
{
cLockGuard lg(&mLock); // take the lock while updating toggles (std::map not thread safe!)
// Check the state of ForceOn or ForceOff
checkRegistryTogglesForced();
// Update all toggles from the registry
for (tTogglesMap::iterator it = mToggles.begin(); it != mToggles.end(); ++it)
{
const String& variableName = it->first;
bool* toggleState = it->second.first;
*toggleState = getRegistryToggleValue(variableName);
}
}
}
//}}}
//{{{
size_t logAll()
{
cLockGuard lg(&mLock); // take the lock while checking toggles (std::map not thread safe!)
typedef std::set<std::pair<String, String> > tTogglesSet;
tTogglesSet togglesEnabled;
tTogglesSet togglesDisabled;
// Group toggles into Enabled and Disabled
for (tTogglesMap::iterator it = mToggles.begin(); it != mToggles.end(); ++it)
{
const String& variableName = it->first;
bool* toggleState = it->second.first;
const String& description = it->second.second;
if (*toggleState)
togglesEnabled.insert(tTogglesSet::value_type(variableName, description));
else
togglesDisabled.insert(tTogglesSet::value_type(variableName, description));
}
// Only log if we actually have toggles enabled
if (mRegTogglesAvailable && (!togglesEnabled.empty() || !togglesDisabled.empty()))
{
cLogIndentGuard Indent(kCtgFeatureToggles, L"");
if (mForceTogglesOn)
QMSG((0, L"DevTest Toggles set to ForceOn"));
else if (mForceTogglesOff)
QMSG((0, L"DevTest Toggles set to ForceOff"));
if (!togglesEnabled.empty())
{
cLogIndentGuard IndentEnabled(0, L"DevTest Toggles enabled:");
for (tTogglesSet::const_iterator it = togglesEnabled.begin(); it != togglesEnabled.end(); ++it)
QMSG((0, L"%-20s - %s", it->first.c_str(), it->second.c_str()));
}
if (!togglesDisabled.empty())
{
cLogIndentGuard IndentDisabled(0, L"DevTest Toggles disabled:");
for (tTogglesSet::const_iterator it = togglesDisabled.begin(); it != togglesDisabled.end(); ++it)
QMSG((0, L"%-20s - %s", it->first.c_str(), it->second.c_str()));
}
}
return togglesEnabled.size();
}
//}}}
private:
//{{{
void initialise()
{
cLockGuard lg(&mLock); // take the lock while reading from the registry
if (mInitialised)
return;
mInitialised = true;
// Get the path of the current executable
String path;
{
std::vector<Char> filename(MAX_PATH);
DWORD filenameSize = GetModuleFileName(NULL, &filename.at(0), (DWORD) filename.size());
if (filenameSize == 0 || filenameSize == filename.size())
return;
path = String(&filename.at(0), filenameSize);
path = path.substr(0, path.rfind(L"\\") + 1);
if (path.size() < 2)
return;
}
// Get the software version to decide if we are registry- (T builds) or file- (S builds) based
const Char versionLetter = iSystemInfo::singleton().getProductVersionLetter();
const String version = iSystemInfo::singleton().getProductVersion();
if (versionLetter == L'D' || versionLetter == L'T') // D/T builds have registry toggles
{
mRegHelp = createRegistryHelp();
if (mRegHelp->isKeyCreated(kDevTestRegistryKey))
{
try
{
// Check we have permission to write to the registry
mRegHelp->setItemString(kDevTestRegistryKey, L"!", L"!");
mRegHelp->deleteItem(kDevTestRegistryKey, L"!");
mRegTogglesAvailable = true;
}
catch (cRecoverable&)
{
QSOS((L"Error attempting to write to \"%s\". DevTest toggles will not function. Check registry permissions", kDevTestRegistryKey));
}
// Check the state of ForceOn or ForceOff
if (mRegTogglesAvailable)
checkRegistryTogglesForced();
}
}
if (versionLetter == L'S') // S builds have file based toggles
{
// Read the encrypted contents of the file
cMemory::Ptr encryptedContents;
try
{
encryptedContents = cFile(path + kDevTestFileName, fFileAccess_Read, 0).read();
}
catch (cNotFound)
{
}
if (encryptedContents.isNull() || encryptedContents->getSize() == 0)
return;
// Decrypt the contents into a vector of strings
std::vector<String> contents;
const char* bytes = encryptedContents->getConstBytes();
String line;
for (size_t i = 0; i < encryptedContents->getSize(); i++)
{
char byte = ~bytes[i];
if (byte == '\0')
{
contents.push_back(line);
line.clear();
}
else
line += byte;
}
if (!line.empty())
contents.push_back(line);
// The first parameter must match the version of software
if (!contents.empty() && !contents[0].empty() && version.substr(0, contents[0].size()) == contents[0])
{
mFileTogglesAvailable = true;
// The remaining parameters are the toggles to enable
for (std::vector<String>::const_iterator it = contents.begin() + 1; it != contents.end(); ++it)
{
mToggles.insert(std::make_pair(*it, std::make_pair(&kTrueBool, String())));
}
}
}
}
//}}}
//{{{
void createRegistryToggle(const String& variableName, const String& description)
{
if (!mRegHelp->isItemCreated(kDevTestRegistryKey, variableName))
mRegHelp->setItemNumber(kDevTestRegistryKey, variableName, 0);
mRegHelp->setItemString(kDevTestRegistryKey, variableName + L"-Desc", description);
}
//}}}
//{{{
void checkRegistryTogglesForced()
{
try
{
String defaultValue = mRegHelp->getItemString(kDevTestRegistryKey, L"");
mForceTogglesOn = (defaultValue == L"ForceOn");
mForceTogglesOff = (defaultValue == L"ForceOff");
}
catch (cRecoverable&)
{
}
}
//}}}
//{{{
bool getRegistryToggleValue(const String& variableName)
{
if (mForceTogglesOn)
return true;
if (mForceTogglesOff)
return false;
try
{
return (mRegHelp->getItemNumber(kDevTestRegistryKey, variableName) != 0);
}
catch (cRecoverable&)
{
return false;
}
}
//}}}
bool mInitialised; //!< \brief Have we loaded our registry settings yet?
bool mRegTogglesAvailable; //!< \brief Are registry toggles available? Does the registry key exist?
bool mFileTogglesAvailable; //!< \brief Are file toggles available? Does "Toggles.sys" exist?
typedef std::map<String, std::pair<bool*, String> > tTogglesMap;
cLock mLock; //!< \brief Lock needs to be held for initialisation and updating of cDevTestToggle instances
tTogglesMap mToggles; //!< \brief Map from feature toggle Name to (Value, Description) pair
bool mForceTogglesOn; //!< \brief Have all toggles been forced on?
bool mForceTogglesOff; //!< \brief Have all toggles been forced off?
std::deque<bool> mToggleStorage; //!< \brief The actual storage for the toggles
iRegistryHelp::Ptr mRegHelp;
};
//}}}
//! \brief The only cDevTestToggleManager in existence
cDevTestToggleManager gDevTestToggleManager;
}
//{{{
cDevTestToggle::cDevTestToggle(const char* const variableName, const Char* const description)
: mToggleState(&mBoolStorage), mBoolStorage(false)
{
if (gDevTestToggleManager.isAvailable())
mToggleState = gDevTestToggleManager.getBoolForToggle(mToggleState, widen(variableName), description);
}
//}}}
//{{{
size_t cDevTestToggle::logAll()
{
if (gDevTestToggleManager.isAvailable())
return gDevTestToggleManager.logAll();
return 0;
}
//}}}
//{{{
void cDevTestToggle::updateAll()
{
gDevTestToggleManager.updateAll();
}
//}}}
| 32.37386 | 143 | 0.610835 | [
"vector"
] |
8b0c2f7d4b2b07565a6de976fffdeb076557b161 | 33,542 | hpp | C++ | dart/dynamics/MetaSkeleton.hpp | malasiot/dart-vsim-octomap | d7afcacdcdcf7da688fb61caf1761b1309888ffe | [
"BSD-2-Clause"
] | null | null | null | dart/dynamics/MetaSkeleton.hpp | malasiot/dart-vsim-octomap | d7afcacdcdcf7da688fb61caf1761b1309888ffe | [
"BSD-2-Clause"
] | null | null | null | dart/dynamics/MetaSkeleton.hpp | malasiot/dart-vsim-octomap | d7afcacdcdcf7da688fb61caf1761b1309888ffe | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2011-2017, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_DYNAMICS_METASKELETON_HPP_
#define DART_DYNAMICS_METASKELETON_HPP_
#include <vector>
#include <string>
#include <Eigen/Dense>
#include "dart/common/Signal.hpp"
#include "dart/common/Subject.hpp"
#include "dart/math/Geometry.hpp"
#include "dart/dynamics/Frame.hpp"
#include "dart/dynamics/InvalidIndex.hpp"
namespace dart {
namespace dynamics {
class BodyNode;
class SoftBodyNode;
class PointMass;
class Joint;
class DegreeOfFreedom;
class Marker;
/// MetaSkeleton is a pure abstract base class that provides a common interface
/// for obtaining data (such as Jacobians and Mass Matrices) from groups of
/// BodyNodes.
class MetaSkeleton : public common::Subject
{
public:
using NameChangedSignal
= common::Signal<void(std::shared_ptr<const MetaSkeleton> _skeleton,
const std::string& _oldName,
const std::string& _newName)>;
MetaSkeleton(const MetaSkeleton&) = delete;
/// Default destructor
virtual ~MetaSkeleton() = default;
//----------------------------------------------------------------------------
/// \{ \name Name
//----------------------------------------------------------------------------
/// Set the name of this MetaSkeleton
virtual const std::string& setName(const std::string& _name) = 0;
/// Get the name of this MetaSkeleton
virtual const std::string& getName() const = 0;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Structural Properties
//----------------------------------------------------------------------------
/// Get number of body nodes
virtual std::size_t getNumBodyNodes() const = 0;
/// Get BodyNode whose index is _idx
virtual BodyNode* getBodyNode(std::size_t _idx) = 0;
/// Get const BodyNode whose index is _idx
virtual const BodyNode* getBodyNode(std::size_t _idx) const = 0;
/// Returns the BodyNode of given name.
///
/// \param[in] name The BodyNode name that want to search.
/// \return The body node of given name.
virtual BodyNode* getBodyNode(const std::string& name) = 0;
/// Returns the BodyNode of given name.
///
/// \param[in] name The BodyNode name that want to search.
/// \return The body node of given name.
virtual const BodyNode* getBodyNode(const std::string& name) const = 0;
/// Get all the BodyNodes that are held by this MetaSkeleton
virtual const std::vector<BodyNode*>& getBodyNodes() = 0;
/// Get all the BodyNodes that are held by this MetaSkeleton
virtual const std::vector<const BodyNode*>& getBodyNodes() const = 0;
/// Returns all the BodyNodes of given name.
/// \param[in] name The BodyNode name that want to search.
/// \return The list of BodyNodes of given name.
virtual std::vector<BodyNode*> getBodyNodes(const std::string& name) = 0;
/// Returns all the BodyNodes of given name.
/// \param[in] name The BodyNode name that want to search.
/// \return The list of BodyNodes of given name.
virtual std::vector<const BodyNode*> getBodyNodes(
const std::string& name) const = 0;
/// Get the index of a specific BodyNode within this ReferentialSkeleton.
/// Returns INVALID_INDEX if it is not held in this ReferentialSkeleton.
/// When _warning is true, a warning message will be printed if the BodyNode
/// is not in the MetaSkeleton.
virtual std::size_t getIndexOf(const BodyNode* _bn, bool _warning=true) const = 0;
/// Get number of Joints
virtual std::size_t getNumJoints() const = 0;
/// Get Joint whose index is _idx
virtual Joint* getJoint(std::size_t _idx) = 0;
/// Get const Joint whose index is _idx
virtual const Joint* getJoint(std::size_t _idx) const = 0;
/// Returns the Joint of given name.
/// \param[in] name The joint name that want to search.
/// \return The joint of given name.
virtual Joint* getJoint(const std::string& name) = 0;
/// Returns the joint of given name.
/// \param[in] name The joint name that want to search.
/// \return The joint of given name.
virtual const Joint* getJoint(const std::string& name) const = 0;
/// Returns all the joints that are held by this MetaSkeleton.
virtual std::vector<Joint*> getJoints() = 0;
/// Returns all the joints that are held by this MetaSkeleton.
virtual std::vector<const Joint*> getJoints() const = 0;
/// Returns all the Joint of given name.
///
/// This MetaSkeleton can contain multiple Joints with the same name when
/// this MetaSkeleton contains Joints from multiple Skeletons.
///
/// \param[in] name The joint name that want to search.
/// \return The list of joints of given name.
virtual std::vector<Joint*> getJoints(const std::string& name) = 0;
/// Returns all the Joint of given name.
///
/// This MetaSkeleton can contain multiple Joints with the same name when
/// this MetaSkeleton contains Joints from multiple Skeletons.
///
/// \param[in] name The joint name that want to search.
/// \return The list of joints of given name.
virtual std::vector<const Joint*> getJoints(
const std::string& name) const = 0;
/// Get the index of a specific Joint within this ReferentialSkeleton. Returns
/// INVALID_INDEX if it is not held in this ReferentialSkeleton.
/// When _warning is true, a warning message will be printed if the Joint is
/// not in the MetaSkeleton.
virtual std::size_t getIndexOf(const Joint* _joint, bool _warning=true) const = 0;
/// Return the number of degrees of freedom in this skeleton
virtual std::size_t getNumDofs() const = 0;
/// Get degree of freedom (aka generalized coordinate) whose index is _idx
virtual DegreeOfFreedom* getDof(std::size_t _idx) = 0;
/// Get degree of freedom (aka generalized coordinate) whose index is _idx
virtual const DegreeOfFreedom* getDof(std::size_t _idx) const = 0;
/// Get the vector of DegreesOfFreedom for this MetaSkeleton
virtual const std::vector<DegreeOfFreedom*>& getDofs() = 0;
/// Get a vector of const DegreesOfFreedom for this MetaSkeleton
virtual std::vector<const DegreeOfFreedom*> getDofs() const = 0;
/// Get the index of a specific DegreeOfFreedom within this
/// ReferentialSkeleton. Returns INVALID_INDEX if it is not held in this
/// ReferentialSkeleton. When _warning is true, a warning message will be
/// printed if the DegreeOfFreedom is not in the MetaSkeleton.
virtual std::size_t getIndexOf(const DegreeOfFreedom* _dof,
bool _warning=true) const = 0;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Command
//----------------------------------------------------------------------------
/// Set a single command
void setCommand(std::size_t _index, double _command);
/// Get a single command
double getCommand(std::size_t _index) const;
/// Set commands for all generalized coordinates
void setCommands(const Eigen::VectorXd& _commands);
/// Set commands for a subset of the generalized coordinates
void setCommands(const std::vector<std::size_t>& _indices,
const Eigen::VectorXd& _commands);
/// Get commands for all generalized coordinates
Eigen::VectorXd getCommands() const;
/// Get commands for a subset of the generalized coordinates
Eigen::VectorXd getCommands(const std::vector<std::size_t>& _indices) const;
/// Set all commands to zero
void resetCommands();
/// \}
//----------------------------------------------------------------------------
/// \{ \name Position
//----------------------------------------------------------------------------
/// Set the position of a single generalized coordinate
void setPosition(std::size_t index, double _position);
/// Get the position of a single generalized coordinate
double getPosition(std::size_t _index) const;
/// Set the positions for all generalized coordinates
void setPositions(const Eigen::VectorXd& _positions);
/// Set the positions for a subset of the generalized coordinates
void setPositions(const std::vector<std::size_t>& _indices,
const Eigen::VectorXd& _positions);
/// Get the positions for all generalized coordinates
Eigen::VectorXd getPositions() const;
/// Get the positions for a subset of the generalized coordinates
Eigen::VectorXd getPositions(const std::vector<std::size_t>& _indices) const;
/// Set all positions to zero
void resetPositions();
/// Set the lower limit of a generalized coordinate's position
void setPositionLowerLimit(std::size_t _index, double _position);
/// Set the lower limits for all generalized coordinates
void setPositionLowerLimits(const Eigen::VectorXd& positions);
/// Set the lower limits for a subset of the generalized coordinates
void setPositionLowerLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& positions);
/// Get the lower limit of a generalized coordinate's position
double getPositionLowerLimit(std::size_t _index) const;
/// Get the lower limits for all generalized coordinates
Eigen::VectorXd getPositionLowerLimits() const;
/// Get the lower limits for a subset of the generalized coordinates
Eigen::VectorXd getPositionLowerLimits(
const std::vector<std::size_t>& indices) const;
/// Set the upper limit of a generalized coordainte's position
void setPositionUpperLimit(std::size_t _index, double _position);
/// Set the upper limits for all generalized coordinates
void setPositionUpperLimits(const Eigen::VectorXd& positions);
/// Set the upper limits for a subset of the generalized coordinates
void setPositionUpperLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& positions);
/// Get the upper limit of a generalized coordinate's position
double getPositionUpperLimit(std::size_t _index) const;
/// Get the upper limits for all generalized coordinates
Eigen::VectorXd getPositionUpperLimits() const;
/// Get the upper limits for a subset of the generalized coordinates
Eigen::VectorXd getPositionUpperLimits(
const std::vector<std::size_t>& indices) const;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Velocity
//----------------------------------------------------------------------------
/// Set the velocity of a single generalized coordinate
void setVelocity(std::size_t _index, double _velocity);
/// Get the velocity of a single generalized coordinate
double getVelocity(std::size_t _index) const;
/// Set the velocities of all generalized coordinates
void setVelocities(const Eigen::VectorXd& _velocities);
/// Set the velocities of a subset of the generalized coordinates
void setVelocities(const std::vector<std::size_t>& _indices,
const Eigen::VectorXd& _velocities);
/// Get the velocities for all generalized coordinates
Eigen::VectorXd getVelocities() const;
/// Get the velocities for a subset of the generalized coordinates
Eigen::VectorXd getVelocities(const std::vector<std::size_t>& _indices) const;
/// Set all velocities to zero
void resetVelocities();
/// Set the lower limit of a generalized coordinate's velocity
void setVelocityLowerLimit(std::size_t _index, double _velocity);
/// Set the lower limits for all generalized coordinates's velocity
void setVelocityLowerLimits(const Eigen::VectorXd& velocities);
/// Set the lower limits for a subset of the generalized coordinates's
/// velocity
void setVelocityLowerLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& velocities);
/// Get the lower limit of a generalized coordinate's velocity
double getVelocityLowerLimit(std::size_t _index);
/// Get the lower limits for all generalized coordinates's velocity
Eigen::VectorXd getVelocityLowerLimits() const;
/// Get the lower limits for a subset of the generalized coordinates's
/// velocity
Eigen::VectorXd getVelocityLowerLimits(
const std::vector<std::size_t>& indices) const;
/// Set the upper limit of a generalized coordinate's velocity
void setVelocityUpperLimit(std::size_t _index, double _velocity);
/// Set the upper limits for all generalized coordinates's velocity
void setVelocityUpperLimits(const Eigen::VectorXd& velocities);
/// Set the upper limits for a subset of the generalized coordinates's
/// velocity
void setVelocityUpperLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& velocities);
/// Get the upper limit of a generalized coordinate's velocity
double getVelocityUpperLimit(std::size_t _index);
/// Get the upper limits for all generalized coordinates's velocity
Eigen::VectorXd getVelocityUpperLimits() const;
/// Get the upper limits for a subset of the generalized coordinates's
/// velocity
Eigen::VectorXd getVelocityUpperLimits(
const std::vector<std::size_t>& indices) const;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Acceleration
//----------------------------------------------------------------------------
/// Set the acceleration of a single generalized coordinate
void setAcceleration(std::size_t _index, double _acceleration);
/// Get the acceleration of a single generalized coordinate
double getAcceleration(std::size_t _index) const;
/// Set the accelerations of all generalized coordinates
void setAccelerations(const Eigen::VectorXd& _accelerations);
/// Set the accelerations of a subset of the generalized coordinates
void setAccelerations(const std::vector<std::size_t>& _indices,
const Eigen::VectorXd& _accelerations);
/// Get the accelerations for all generalized coordinates
Eigen::VectorXd getAccelerations() const;
/// Get the accelerations for a subset of the generalized coordinates
Eigen::VectorXd getAccelerations(const std::vector<std::size_t>& _indices) const;
/// Set all accelerations to zero
void resetAccelerations();
/// Set the lower limit of a generalized coordinate's acceleration
void setAccelerationLowerLimit(std::size_t _index, double _acceleration);
/// Set the lower limits for all generalized coordinates's acceleration
void setAccelerationLowerLimits(const Eigen::VectorXd& accelerations);
/// Set the lower limits for a subset of the generalized coordinates's
/// acceleration
void setAccelerationLowerLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& accelerations);
/// Get the lower limit of a generalized coordinate's acceleration
double getAccelerationLowerLimit(std::size_t _index) const;
/// Get the lower limits for all generalized coordinates's acceleration
Eigen::VectorXd getAccelerationLowerLimits() const;
/// Get the lower limits for a subset of the generalized coordinates's
/// acceleration
Eigen::VectorXd getAccelerationLowerLimits(
const std::vector<std::size_t>& indices) const;
/// Set the upper limit of a generalized coordinate's acceleration
void setAccelerationUpperLimit(std::size_t _index, double _acceleration);
/// Set the upper limits for all generalized coordinates's acceleration
void setAccelerationUpperLimits(const Eigen::VectorXd& accelerations);
/// Set the upper limits for a subset of the generalized coordinates's
/// acceleration
void setAccelerationUpperLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& accelerations);
/// Get the upper limit of a generalized coordinate's acceleration
double getAccelerationUpperLimit(std::size_t _index) const;
/// Get the upper limits for all generalized coordinates's acceleration
Eigen::VectorXd getAccelerationUpperLimits() const;
/// Get the upper limits for a subset of the generalized coordinates's
/// acceleration
Eigen::VectorXd getAccelerationUpperLimits(
const std::vector<std::size_t>& indices) const;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Force
//----------------------------------------------------------------------------
/// Set the force of a single generalized coordinate
void setForce(std::size_t _index, double _force);
/// Get the force of a single generalized coordinate
double getForce(std::size_t _index) const;
/// Set the forces of all generalized coordinates
void setForces(const Eigen::VectorXd& _forces);
/// Set the forces of a subset of the generalized coordinates
void setForces(const std::vector<std::size_t>& _index,
const Eigen::VectorXd& _forces);
/// Get the forces for all generalized coordinates
Eigen::VectorXd getForces() const;
/// Get the forces for a subset of the generalized coordinates
Eigen::VectorXd getForces(const std::vector<std::size_t>& _indices) const;
/// Set all forces of the generalized coordinates to zero
void resetGeneralizedForces();
/// Set the lower limit of a generalized coordinate's force
void setForceLowerLimit(std::size_t _index, double _force);
/// Set the lower limits for all generalized coordinates's force
void setForceLowerLimits(const Eigen::VectorXd& forces);
/// Set the lower limits for a subset of the generalized coordinates's force
void setForceLowerLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& forces);
/// Get the lower limit of a generalized coordinate's force
double getForceLowerLimit(std::size_t _index) const;
/// Get the lower limits for all generalized coordinates's force
Eigen::VectorXd getForceLowerLimits() const;
/// Get the lower limits for a subset of the generalized coordinates's force
Eigen::VectorXd getForceLowerLimits(
const std::vector<std::size_t>& indices) const;
/// Set the upper limit of a generalized coordinate's force
void setForceUpperLimit(std::size_t _index, double _force);
/// Set the upperlimits for all generalized coordinates's force
void setForceUpperLimits(const Eigen::VectorXd& forces);
/// Set the upper limits for a subset of the generalized coordinates's force
void setForceUpperLimits(const std::vector<std::size_t>& indices,
const Eigen::VectorXd& forces);
/// Get the upper limit of a generalized coordinate's force
double getForceUpperLimit(std::size_t _index) const;
/// Get the upper limits for all generalized coordinates's force
Eigen::VectorXd getForceUpperLimits() const;
/// Get the upper limits for a subset of the generalized coordinates's force
Eigen::VectorXd getForceUpperLimits(
const std::vector<std::size_t>& indices) const;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Velocity Change
//----------------------------------------------------------------------------
/// Get the velocity changes for all the generalized coordinates
Eigen::VectorXd getVelocityChanges() const;
//----------------------------------------------------------------------------
/// \{ \name Constraint Impulse
//----------------------------------------------------------------------------
/// Set the constraint impulses for the generalized coordinates
void setJointConstraintImpulses(const Eigen::VectorXd& _impulses);
/// Get the constraint impulses for the generalized coordinates
Eigen::VectorXd getJointConstraintImpulses() const;
//----------------------------------------------------------------------------
/// \{ \name Jacobians
//----------------------------------------------------------------------------
/// Get the spatial Jacobian targeting the origin of a BodyNode. The Jacobian
/// is expressed in the Frame of the BodyNode.
virtual math::Jacobian getJacobian(const JacobianNode* _node) const = 0;
/// Get the spatial Jacobian targeting the origin of a BodyNode. You can
/// specify a coordinate Frame to express the Jabocian in.
virtual math::Jacobian getJacobian(
const JacobianNode* _node,
const Frame* _inCoordinatesOf) const = 0;
/// Get the spatial Jacobian targeting an offset in a BodyNode. The _offset is
/// expected in coordinates of the BodyNode Frame. The Jacobian is expressed
/// in the Frame of the BodyNode.
virtual math::Jacobian getJacobian(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset) const = 0;
/// Get the spatial Jacobian targeting an offset in a BodyNode. The _offset is
/// expected in coordinates of the BodyNode Frame. You can specify a
/// coordinate Frame to express the Jabocian in.
virtual math::Jacobian getJacobian(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset,
const Frame* _inCoordinatesOf) const = 0;
/// Get the spatial Jacobian targeting the origin of a BodyNode. The Jacobian
/// is expressed in the World Frame.
virtual math::Jacobian getWorldJacobian(const JacobianNode* _node) const = 0;
/// Get the spatial Jacobian targeting an offset in a BodyNode. The _offset is
/// expected in coordinates of the BodyNode Frame. The Jacobian is expressed
/// in the World Frame.
virtual math::Jacobian getWorldJacobian(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset) const = 0;
/// Get the linear Jacobian targeting the origin of a BodyNode. You can
/// specify a coordinate Frame to express the Jabocian in.
virtual math::LinearJacobian getLinearJacobian(
const JacobianNode* _node,
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the linear Jacobian targeting an offset in a BodyNode. The _offset is
/// expected in coordinates of the BodyNode Frame. You can specify a
/// coordinate Frame to express the Jabocian in.
virtual math::LinearJacobian getLinearJacobian(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset,
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the angular Jacobian of a BodyNode. You can specify a coordinate Frame
/// to express the Jabocian in.
virtual math::AngularJacobian getAngularJacobian(
const JacobianNode* _node,
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the spatial Jacobian time derivative targeting the origin of a
/// BodyNode. The Jacobian is expressed in the Frame of the BodyNode.
virtual math::Jacobian getJacobianSpatialDeriv(
const JacobianNode* _node) const = 0;
/// Get the spatial Jacobian time derivative targeting the origin of a
/// BodyNode. You can specify a coordinate Frame to express the Jabocian in.
virtual math::Jacobian getJacobianSpatialDeriv(
const JacobianNode* _node,
const Frame* _inCoordinatesOf) const = 0;
/// Get the spatial Jacobian time derivative targeting an offset in a
/// BodyNode. The _offset is expected in coordinates of the BodyNode Frame.
/// The Jacobian is expressed in the Frame of the BodyNode.
virtual math::Jacobian getJacobianSpatialDeriv(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset) const = 0;
/// Get the spatial Jacobian time derivative targeting an offset in a
/// BodyNode. The _offset is expected in coordinates of the BodyNode Frame.
/// You can specify a coordinate Frame to express the Jabocian in.
virtual math::Jacobian getJacobianSpatialDeriv(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset,
const Frame* _inCoordinatesOf) const = 0;
/// Get the spatial Jacobian time derivative targeting the origin of a
/// BodyNode. The Jacobian is expressed in the World Frame.
virtual math::Jacobian getJacobianClassicDeriv(
const JacobianNode* _node) const = 0;
/// Get the spatial Jacobian time derivative targeting the origin a
/// BodyNode. The _offset is expected in coordinates of the BodyNode Frame.
/// You can specify a coordinate Frame to express the Jabocian in.
virtual math::Jacobian getJacobianClassicDeriv(
const JacobianNode* _node,
const Frame* _inCoordinatesOf) const = 0;
/// Get the spatial Jacobian time derivative targeting an offset in a
/// BodyNode. The _offset is expected in coordinates of the BodyNode Frame.
/// You can specify a coordinate Frame to express the Jabocian in.
virtual math::Jacobian getJacobianClassicDeriv(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset,
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the linear Jacobian (classical) time derivative targeting the origin
/// of a BodyNode. The _offset is expected in coordinates of the BodyNode
/// Frame. You can specify a coordinate Frame to express the Jabocian in.
virtual math::LinearJacobian getLinearJacobianDeriv(
const JacobianNode* _node,
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the linear Jacobian (classical) time derivative targeting an offset in
/// a BodyNode. The _offset is expected in coordinates of the BodyNode Frame.
/// You can specify a coordinate Frame to express the Jabocian in.
virtual math::LinearJacobian getLinearJacobianDeriv(
const JacobianNode* _node,
const Eigen::Vector3d& _localOffset,
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the angular Jacobian time derivative of a BodyNode. You can specify a
/// coordinate Frame to express the Jabocian in.
virtual math::AngularJacobian getAngularJacobianDeriv(
const JacobianNode* _node,
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Equations of Motion
//----------------------------------------------------------------------------
/// Get the total mass of all BodyNodes in this MetaSkeleton. Note that
/// for the ReferentialSkeleton extension of MetaSkeleton, this will be an
/// O(n) operation, while the Skeleton extension will be O(1).
virtual double getMass() const = 0;
/// Get the Mass Matrix of the MetaSkeleton
virtual const Eigen::MatrixXd& getMassMatrix() const = 0;
/// Get augmented mass matrix of the skeleton. This matrix is used in
/// ConstraintDynamics to compute constraint forces. The matrix is
/// M + h*D + h*h*K where D is diagonal joint damping coefficient matrix, K is
/// diagonal joint stiffness matrix, and h is simulation time step.
virtual const Eigen::MatrixXd& getAugMassMatrix() const = 0;
/// Get inverse of Mass Matrix of the MetaSkeleton.
virtual const Eigen::MatrixXd& getInvMassMatrix() const = 0;
/// Get inverse of augmented Mass Matrix of the MetaSkeleton.
virtual const Eigen::MatrixXd& getInvAugMassMatrix() const = 0;
/// Get Coriolis force vector of the MetaSkeleton's BodyNodes.
virtual const Eigen::VectorXd& getCoriolisForces() const = 0;
/// Get gravity force vector of the MetaSkeleton.
virtual const Eigen::VectorXd& getGravityForces() const = 0;
/// Get combined vector of Coriolis force and gravity force of the MetaSkeleton.
virtual const Eigen::VectorXd& getCoriolisAndGravityForces() const = 0;
/// Get external force vector of the MetaSkeleton.
virtual const Eigen::VectorXd& getExternalForces() const = 0;
/// Get constraint force vector.
virtual const Eigen::VectorXd& getConstraintForces() const = 0;
/// Clear the external forces of the BodyNodes in this MetaSkeleton
virtual void clearExternalForces() = 0;
/// Clear the internal forces of the BodyNodes in this MetaSkeleton
virtual void clearInternalForces() = 0;
/// Compute and return Lagrangian of this MetaSkeleton
double computeLagrangian() const;
/// Get the kinetic energy of this MetaSkeleton
DART_DEPRECATED(6.1)
double getKineticEnergy() const;
/// Get the kinetic energy of this MetaSkeleton
virtual double computeKineticEnergy() const = 0;
/// Get the potential energy of this MetaSkeleton
DART_DEPRECATED(6.1)
double getPotentialEnergy() const;
/// Get the potential energy of this MetaSkeleton
virtual double computePotentialEnergy() const = 0;
/// Clear collision flags of the BodyNodes in this MetaSkeleton
DART_DEPRECATED(6.0)
virtual void clearCollidingBodies() = 0;
/// \}
//----------------------------------------------------------------------------
/// \{ \name Center of Mass Jacobian
//----------------------------------------------------------------------------
/// Get the MetaSkeleton's COM with respect to any Frame (default is World
/// Frame)
virtual Eigen::Vector3d getCOM(
const Frame* _withRespectTo = Frame::World()) const = 0;
/// Get the Skeleton's COM spatial velocity in terms of any Frame (default is
/// World Frame)
virtual Eigen::Vector6d getCOMSpatialVelocity(
const Frame* _relativeTo = Frame::World(),
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the Skeleton's COM linear velocity in terms of any Frame (default is
/// World Frame)
virtual Eigen::Vector3d getCOMLinearVelocity(
const Frame* _relativeTo = Frame::World(),
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the Skeleton's COM spatial acceleration in terms of any Frame (default
/// is World Frame)
virtual Eigen::Vector6d getCOMSpatialAcceleration(
const Frame* _relativeTo = Frame::World(),
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the MetaSkeleton's COM linear acceleration in terms of any Frame
/// (default is World Frame)
virtual Eigen::Vector3d getCOMLinearAcceleration(
const Frame* _relativeTo = Frame::World(),
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the MetaSkeleton's COM Jacobian in terms of any Frame (default is
/// World Frame)
virtual math::Jacobian getCOMJacobian(
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the MetaSkeleton's COM Linear Jacobian in terms of any Frame (default is
/// World Frame)
virtual math::LinearJacobian getCOMLinearJacobian(
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the Skeleton's COM Jacobian spatial time derivative in terms of any
/// Frame (default is World Frame).
///
/// NOTE: Since this is a spatial time derivative, it is only meant to be used
/// with spatial acceleration vectors. If you are using classical linear
/// vectors, then use getCOMLinearJacobianDeriv() instead.
virtual math::Jacobian getCOMJacobianSpatialDeriv(
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// Get the Skeleton's COM Linear Jacobian time derivative in terms of any
/// Frame (default is World Frame).
///
/// NOTE: Since this is a classical time derivative, it is only meant to be
/// used with classical acceleration vectors. If you are using spatial
/// vectors, then use getCOMJacobianSpatialDeriv() instead.
virtual math::LinearJacobian getCOMLinearJacobianDeriv(
const Frame* _inCoordinatesOf = Frame::World()) const = 0;
/// \}
protected:
/// Default constructor
MetaSkeleton();
//--------------------------------------------------------------------------
// Signals
//--------------------------------------------------------------------------
NameChangedSignal mNameChangedSignal;
public:
//--------------------------------------------------------------------------
// Slot registers
//--------------------------------------------------------------------------
common::SlotRegister<NameChangedSignal> onNameChanged;
};
} // namespace dynamics
} // namespace dart
#endif // DART_DYNAMICS_METASKELETON_HPP_
| 41.05508 | 84 | 0.677091 | [
"geometry",
"vector"
] |
8b0cd26df2b523728a320f715f6f972d0fa5498d | 8,461 | cxx | C++ | Filters/OpenTURNS/vtkOTScatterPlotMatrix.cxx | cclauss/VTK | f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d | [
"BSD-3-Clause"
] | 1,755 | 2015-01-03T06:55:00.000Z | 2022-03-29T05:23:26.000Z | Filters/OpenTURNS/vtkOTScatterPlotMatrix.cxx | cclauss/VTK | f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d | [
"BSD-3-Clause"
] | 29 | 2015-04-23T20:58:30.000Z | 2022-03-02T16:16:42.000Z | Filters/OpenTURNS/vtkOTScatterPlotMatrix.cxx | cclauss/VTK | f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d | [
"BSD-3-Clause"
] | 1,044 | 2015-01-05T22:48:27.000Z | 2022-03-31T02:38:26.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkOTScatterPlotMatrix.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOTScatterPlotMatrix.h"
#include "vtkAxis.h"
#include "vtkBrush.h"
#include "vtkChart.h"
#include "vtkChartXY.h"
#include "vtkColor.h"
#include "vtkColorTransferFunction.h"
#include "vtkCompositeDataIterator.h"
#include "vtkExecutive.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkNew.h"
#include "vtkOTDensityMap.h"
#include "vtkObjectFactory.h"
#include "vtkPen.h"
#include "vtkPlotHistogram2D.h"
#include "vtkPlotPoints.h"
#include "vtkTable.h"
#include "vtkTextProperty.h"
#include <vector>
// Static density values for now
static const int nDensityValues = 3;
static const double densityValues[3] = { 0.1, 0.5, 0.9 };
// An internal class to store density map settings
class vtkOTScatterPlotMatrix::DensityMapSettings
{
public:
DensityMapSettings()
{
this->PlotPen->SetColor(0, 0, 0, 255);
this->ShowDensityMap = false;
this->DensityLineSize = 2;
for (int i = 0; i < nDensityValues; i++)
{
this->DensityMapValues.push_back(densityValues[i]);
double r, g, b;
vtkMath::HSVToRGB(densityValues[i], 1, 0.75, &r, &g, &b);
this->DensityMapColorMap.insert(
std::make_pair(densityValues[i], vtkColor4ub(r * 255, g * 255, b * 255)));
}
}
~DensityMapSettings() = default;
vtkNew<vtkPen> PlotPen;
bool ShowDensityMap;
float DensityLineSize;
std::vector<double> DensityMapValues;
std::map<double, vtkColor4ub> DensityMapColorMap;
};
vtkStandardNewMacro(vtkOTScatterPlotMatrix);
vtkOTScatterPlotMatrix::vtkOTScatterPlotMatrix()
{
this->DensityMapsSettings[vtkScatterPlotMatrix::SCATTERPLOT] =
new vtkOTScatterPlotMatrix::DensityMapSettings;
this->DensityMapsSettings[vtkScatterPlotMatrix::ACTIVEPLOT] = new DensityMapSettings();
}
vtkOTScatterPlotMatrix::~vtkOTScatterPlotMatrix()
{
delete this->DensityMapsSettings[vtkScatterPlotMatrix::SCATTERPLOT];
delete this->DensityMapsSettings[vtkScatterPlotMatrix::ACTIVEPLOT];
}
//------------------------------------------------------------------------------
void vtkOTScatterPlotMatrix::AddSupplementaryPlot(
vtkChart* chart, int plotType, vtkStdString row, vtkStdString column, int plotCorner)
{
vtkChartXY* xy = vtkChartXY::SafeDownCast(chart);
if (plotType != NOPLOT && plotType != HISTOGRAM &&
this->DensityMapsSettings[plotType]->ShowDensityMap && !this->Animating)
{
DensityMapCacheMap::iterator it = this->DensityMapCache.find(std::make_pair(row, column));
vtkOTDensityMap* density;
if (it != this->DensityMapCache.end())
{
density = it->second;
}
else
{
vtkSmartPointer<vtkOTDensityMap> densityPt = vtkSmartPointer<vtkOTDensityMap>::New();
this->DensityMapCache[std::make_pair(row, column)] = densityPt;
density = densityPt;
}
// Compute density map
density->SetInputData(this->Input);
density->SetNumberOfContours(3);
density->SetValue(0, 0.1);
density->SetValue(1, 0.5);
density->SetValue(2, 0.9);
density->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_ROWS, row);
density->SetInputArrayToProcess(1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_ROWS, column);
density->Update();
// Iterate over multiblock output to drow the density maps
vtkMultiBlockDataSet* mb = vtkMultiBlockDataSet::SafeDownCast(density->GetOutput());
vtkCompositeDataIterator* iter = mb->NewIterator();
for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())
{
vtkTable* densityLineTable = vtkTable::SafeDownCast(iter->GetCurrentDataObject());
if (densityLineTable)
{
vtkPlot* densityPlot = chart->AddPlot(vtkChart::LINE);
if (xy)
{
xy->AutoAxesOff();
xy->SetPlotCorner(densityPlot, plotCorner);
xy->RaisePlot(densityPlot);
}
densityPlot->SetInputData(densityLineTable, densityLineTable->GetColumnName(1), row);
double densityVal = iter->GetCurrentMetaData()->Get(vtkOTDensityMap::DENSITY());
vtkPen* plotPen = vtkPen::New();
plotPen->DeepCopy(this->DensityMapsSettings[plotType]->PlotPen);
plotPen->SetColor(this->DensityMapsSettings[plotType]->DensityMapColorMap[densityVal]);
densityPlot->SetPen(plotPen);
plotPen->Delete();
vtkPlotPoints* plotPoints = vtkPlotPoints::SafeDownCast(densityPlot);
plotPoints->SetWidth(this->DensityMapsSettings[plotType]->DensityLineSize);
}
}
iter->Delete();
// Draw the density map image as well
vtkImageData* image = vtkImageData::SafeDownCast(density->GetExecutive()->GetOutputData(1));
if (image)
{
vtkNew<vtkPlotHistogram2D> histo;
histo->SetInputData(image);
if (this->TransferFunction.Get() == nullptr)
{
double* range = image->GetScalarRange();
vtkNew<vtkColorTransferFunction> stc;
stc->SetColorSpaceToDiverging();
stc->AddRGBPoint(range[0], 59. / 255., 76. / 255., 192. / 255.);
stc->AddRGBPoint(0.5 * (range[0] + range[1]), 221. / 255., 221. / 255., 221. / 255.);
stc->AddRGBPoint(range[1], 180. / 255., 4. / 255., 38. / 255.);
stc->Build();
histo->SetTransferFunction(stc);
}
else
{
histo->SetTransferFunction(this->TransferFunction);
}
histo->Update();
chart->AddPlot(histo);
if (xy)
{
xy->LowerPlot(histo); // push the plot in background
}
}
else
{
vtkWarningMacro("Density image is not found.");
}
}
}
//------------------------------------------------------------------------------
void vtkOTScatterPlotMatrix::SetDensityMapVisibility(int plotType, bool visible)
{
if (plotType != NOPLOT && plotType != HISTOGRAM &&
this->DensityMapsSettings[plotType]->ShowDensityMap != visible)
{
this->DensityMapsSettings[plotType]->ShowDensityMap = visible;
this->Modified();
if (plotType == ACTIVEPLOT)
{
this->ActivePlotValid = false;
}
}
}
//------------------------------------------------------------------------------
void vtkOTScatterPlotMatrix::SetDensityLineSize(int plotType, float size)
{
if (plotType != NOPLOT && plotType != HISTOGRAM &&
this->DensityMapsSettings[plotType]->DensityLineSize != size)
{
this->DensityMapsSettings[plotType]->DensityLineSize = size;
this->Modified();
if (plotType == ACTIVEPLOT)
{
this->ActivePlotValid = false;
}
}
}
//------------------------------------------------------------------------------
void vtkOTScatterPlotMatrix::SetDensityMapColor(
int plotType, unsigned int densityLineIndex, const vtkColor4ub& color)
{
if (plotType != NOPLOT && plotType != HISTOGRAM &&
densityLineIndex < this->DensityMapsSettings[plotType]->DensityMapValues.size())
{
double density = this->DensityMapsSettings[plotType]->DensityMapValues[densityLineIndex];
if (this->DensityMapsSettings[plotType]->DensityMapColorMap[density] != color)
{
this->DensityMapsSettings[plotType]->DensityMapColorMap[density] = color;
this->Modified();
if (plotType == ACTIVEPLOT)
{
this->ActivePlotValid = false;
}
}
}
}
//------------------------------------------------------------------------------
void vtkOTScatterPlotMatrix::PrintSelf(ostream& os, vtkIndent indent)
{
Superclass::PrintSelf(os, indent);
}
//------------------------------------------------------------------------------
vtkScalarsToColors* vtkOTScatterPlotMatrix::GetTransferFunction()
{
return this->TransferFunction;
}
//------------------------------------------------------------------------------
void vtkOTScatterPlotMatrix::SetTransferFunction(vtkScalarsToColors* stc)
{
if (this->TransferFunction.Get() != stc)
{
this->TransferFunction = stc;
this->Modified();
}
}
| 33.575397 | 96 | 0.632904 | [
"vector"
] |
8b0ee9dd5806614f1f3f23c9851c048878654e0d | 2,469 | cpp | C++ | src/IceRay/main/interface/python/core/geometry/transform/affine.cpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | 2 | 2020-09-04T12:27:15.000Z | 2022-01-17T14:49:40.000Z | src/IceRay/main/interface/python/core/geometry/transform/affine.cpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | null | null | null | src/IceRay/main/interface/python/core/geometry/transform/affine.cpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | 1 | 2020-09-04T12:27:52.000Z | 2020-09-04T12:27:52.000Z |
#include "./transform.hpp"
#include "IceRay/geometry/transform/affine.hpp"
typedef GS_DDMRM::S_IceRay::S_geometry::S_transform::GC_affine GTs_affine;
bool GFs_doTranslate( GTs_affine & P_affine, GTs_coord3D const& P_move )
{
GTs_affine3D I_transform;
::math::linear::affine::id( I_transform );
I_transform.vector() = P_move;
GTs_affine3D I_2world;
::math::linear::affine::compose( I_2world, I_transform, P_affine.F_2world() );
P_affine.F_2world( I_2world );
return true;
}
bool GFs_doScale0( GTs_affine &P_affine, GTs_coord3D const& P_scale )
{
GTs_affine3D I_transform;
::math::linear::affine::id( I_transform );
I_transform.matrix()[0][0] = P_scale[0];
I_transform.matrix()[1][1] = P_scale[1];
I_transform.matrix()[2][2] = P_scale[2];
GTs_affine3D I_2world;
::math::linear::affine::compose( I_2world, I_transform, P_affine.F_2world() );
P_affine.F_2world( I_2world );
return true;
}
bool GFs_doScaleX( GTs_affine & P_affine, GTs_coord3D const& P_pivot, GTs_coord3D const& P_scale )
{
using namespace ::math::linear::vector;
GFs_doTranslate( P_affine, -P_pivot );
GFs_doScale0( P_affine, P_scale );
GFs_doTranslate( P_affine, P_pivot );
return true;
}
bool GFs_doRotate( GTs_affine * P_affine, GTs_coord3D const& P_pivot, GTs_coord3D const& P_direction, GTs_scalar const& P_angle )
{
GTs_affine::T_affine I_rotate; ::math::linear::affine::rotate( I_rotate, P_pivot, P_direction, P_angle );
GTs_affine::T_affine I_2world; ::math::linear::affine::compose( I_2world, I_rotate, P_affine->F_2world() );
P_affine->F_2world( I_2world );
return true;
}
bool GFs_doSkewX( GTs_affine * P_affine, GTs_coord3D const& P_pivot, GTs_coord3D const& P_angle )
{
return true;
}
void expose_IceRay_geometry_transform_affine()
{
//MAKE_SUBMODULE( IceRay );
MAKE_SUBMODULE( core );
MAKE_SUBMODULE( geometry );
boost::python::class_< GTs_affine, boost::python::bases<GTs__base> >( "GeometryTransformAffine" )
.def( boost::python::init<>() )
.def( boost::python::init<GTs__base *>() )
.def( boost::python::init<GTs__base *, GTs_affine3D>() )
.def( boost::python::init<GTs__base *, GTs_matrix3D, GTs_coord3D>() )
.def("translate", &GFs_doTranslate )
.def("scale", &GFs_doScaleX )
.def("rotate", &GFs_doRotate )
.def("skew", &GFs_doSkewX )
;
}
| 30.109756 | 130 | 0.674362 | [
"geometry",
"vector",
"transform"
] |
8b162fa69e84200a517a624b0a72f287162924ee | 23,724 | cpp | C++ | Snake/mainwindow.cpp | jclehner18/QT_Snake_Game | 26eccac5eba0234a4c286a9f72d6e042bcdc353a | [
"Apache-2.0"
] | null | null | null | Snake/mainwindow.cpp | jclehner18/QT_Snake_Game | 26eccac5eba0234a4c286a9f72d6e042bcdc353a | [
"Apache-2.0"
] | null | null | null | Snake/mainwindow.cpp | jclehner18/QT_Snake_Game | 26eccac5eba0234a4c286a9f72d6e042bcdc353a | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
//Special credit to Alex Menilli who voiced Death sound
//Credit to Nik Pensyl for producing all sounds and Recording of Munch Sound
//Credit to: https://freemidi.org/download3-26214-all-of-me--john-legend for Midi files of music generated.
QSound music("../game_music.wav");
QSound munch("../Munch.wav");
QSound dead("../Death.wav");
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow) {
ui->setupUi(this);
setFixedSize(width(), height());
start_width = width();
start_height = height();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(painting()));
food.push_back(6);
food.push_back(7);
getHighScore();
scales.load("../snake_Background.png");
head_up.load("../Snake_Head_Up.png");
head_left.load("../Snake_Head_Left.png");
head_right.load("../Snake_Head_Right.png");
head_down.load("../Snake_Head_Down.png");
head2_up.load("../Snake_Head2_Up.png");
head2_left.load("../Snake_Head2_Left.png");
head2_right.load("../Snake_Head2_Right.png");
head2_down.load("../Snake_Head2_Down.png");
music.setLoops(0);
munch.setLoops(0);
dead.setLoops(0);
}
void MainWindow::getHighScore() {
fstream infile;
infile.open("../snek_HighScore.txt", ios_base::in);
string high;
getline(infile, high);
try {
highscore = stoi(high);
} catch (exception &err) {
highscore = 0;
}
infile.close();
}
void MainWindow::setHighScore() {
fstream ofile;
ofile.open("../snek_HighScore.txt", ios_base::out);
ofile<<highscore;
ofile.close();
}
void MainWindow::paintEvent(QPaintEvent *e) {
QPainter p(this);
if(start) {
p.setBrush(Qt::black);
p.drawRect(0, 0, width(), height());
p.setPen(QPen(QColor(0, 70, 0), 5));
p.drawLine(25, 100, 25, game_height-25);
p.drawLine(25, game_height-25, game_width-25, game_height-25);
p.drawLine(game_width-25, 100, game_width-25, game_height-25);
p.drawLine(25, 100, game_width-25, 100);
p.setPen(QPen(QColor(0, 70, 0), 2));
p.setBrush(Qt::red);
p.drawEllipse(food[0]*50+30, food[1]*50+105, 40, 40);
if(begin==1) {
_sleep(1000);
begin++;
music.play();
} else {
begin++;
}
if(music.isFinished()) {
music.play();
}
snek1 = move(snek1, snek1_direction_current);
snek1_direction_current = snek1_direction_new;
QFont font("Courier", 35, QFont::DemiBold);
p.setPen(Qt::white);
QFontMetrics fm(font);
p.setFont(font);
QString Player_score = "Player 1: " + QString::fromStdString(to_string(snek1.size()));
p.drawText(20, 50, Player_score);
for(int i =0; i<snek1.size(); i++) {
p.setBrush(Qt::green);
if(i!=0) {
p.drawImage(snek1[i][0]*50+25, snek1[i][1]*50+100, scales);
} else {
if(snek1_direction_current==0) {
p.drawImage(snek1[i][0]*50+25, snek1[i][1]*50+75, head_up);
} else if(snek1_direction_current==1) {
p.drawImage(snek1[i][0]*50, snek1[i][1]*50+100, head_left);
} else if(snek1_direction_current==2) {
p.drawImage(snek1[i][0]*50+25, snek1[i][1]*50+100, head_down);
} else{
p.drawImage(snek1[i][0]*50+25, snek1[i][1]*50+100, head_right);
}
}
}
if(players==2) {
snek2 = move(snek2, snek2_direction_current);
snek2_direction_current = snek2_direction_new;
Player_score = "Player 2: " + QString::fromStdString(to_string(snek2.size()));
p.setPen(Qt::white);
p.drawText(520, 50, Player_score);
for(int i =0; i<snek2.size(); i++) {
p.setBrush(Qt::blue);
if(i!=0) {
p.drawImage(snek2[i][0]*50+25, snek2[i][1]*50+100, scales);
} else {
if(snek2_direction_current==0) {
p.drawImage(snek2[i][0]*50+25, snek2[i][1]*50+75, head2_up);
} else if(snek2_direction_current==1) {
p.drawImage(snek2[i][0]*50, snek2[i][1]*50+100, head2_left);
} else if(snek2_direction_current==2) {
p.drawImage(snek2[i][0]*50+25, snek2[i][1]*50+100, head2_down);
} else{
p.drawImage(snek2[i][0]*50+25, snek2[i][1]*50+100, head2_right);
}
}
}
check1PlayerWin();
} else {
check1PlayerWin();
}
} else {
p.setBrush(QColor(0, 200, 235));
p.drawRect(0, 0, width(), height());
}
}
void MainWindow::check1PlayerWin() {
if(snek1[0][0]==-1 || snek1[0][0]==15 || snek1[0][1]==-1 || snek1[0][1]==15) {
game_over = true;
start = false;
if(players==2) {
winner = 2;
check2PlayerWin();
if(winner==1) {
winner = 0;
}
}
} else if(players==2) {
for(int j = 0; j<snek2.size(); j++) {
if(snek1[0][1]==snek2[j][1] && snek1[0][0]==snek2[j][0]) {
game_over = true;
start = false;
winner =2;
check2PlayerWin();
if(winner==1) {
winner = 0;
}
}
}
}
if(players==2 && winner==-1){
check2PlayerWin();
}
if(game_over) {
GameOver();
}
}
void MainWindow::check2PlayerWin() {
if(snek2[0][0]==-1 || snek2[0][0]==15 || snek2[0][1]==-1 || snek2[0][1]==15) {
game_over = true;
start = false;
winner = 1;
} else {
for(int j = 0; j<snek1.size(); j++) {
if(snek2[0][1]==snek1[j][1] && snek2[0][0]==snek1[j][0]) {
game_over = true;
start = false;
winner =1;
}
}
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::painting() {
repaint();
if(!game_over && start) {
timer->start(speed);
}
}
void MainWindow::newFood() {
bool clear = false;
srand(time(NULL));
if(munch.isFinished()) {
munch.play();
} else {
munch.play();
}
do {
clear = true;
food[0] = rand()%15;
food[1] = rand()%15;
for(int j = 0; j<snek1.size(); j++) {
if(snek1[j][0]==food[0] && snek1[j][1]==food[1]) {
clear = false;
break;
}
}
if(players==2 && clear) {
for(int j = 0; j<snek2.size(); j++) {
if(snek2[j][0]==food[0] && snek2[j][1]==food[1]) {
clear = false;
break;
}
}
}
} while(!clear);
}
void MainWindow::on_Beginbut_clicked() {
if(players!=0 && diffictulty!=0) {
start = true;
ui->Easybut->hide();
ui->Gamerbut->hide();
ui->Beginbut->hide();
ui->Instructbut->hide();
ui->Mediumbut->hide();
ui->Player1but->hide();
ui->Player2but->hide();
ui->ctrInv->hide();
ui->sneklab->hide();
ui->playerlab->hide();
ui->difflab->hide();
vector<int> coords;
coords.push_back(5);
coords.push_back(7);
snek1_direction_current = 0;
snek2_direction_current = 2;
snek1_direction_new = 0;
snek2_direction_new = 2;
food[0] = 7;
food[1] = 7;
snek1.clear();
snek2.clear();
snek1.push_back(coords);
coords[0] = 8;
snek2.push_back(coords);
setFixedSize(game_width, game_height);
timer->start(speed);
} else {
QMessageBox msg;
msg.setText("Make sure you have chosen an option from both sections.");
msg.exec();
}
}
vector<vector<int>> MainWindow::move(vector<vector<int>> snek, int direct) {
for(int i =snek.size()-1; i>=0; i--) {
if(i==0) {
if(i+1==snek.size()) {
switch(direct) {
case 0: {
if(snek[0][1]-1==food[1] && snek[0][0]==food[0]) {
snek.push_back(snek[i]);
newFood();
}
break;
}
case 1: {
if(snek[0][0]-1==food[0] && snek[0][1]==food[1]) {
snek.push_back(snek[i]);
newFood();
}
break;
}
case 2: {
if(snek[0][1]+1==food[1] && snek[0][0]==food[0]) {
snek.push_back(snek[i]);
newFood();
}
break;
}
case 3: {
if(snek[0][0]+1==food[0] && snek[0][1]==food[1]) {
snek.push_back(snek[i]);
newFood();
munch.play();
}
break;
}
}
}
switch(direct) {
case 0: {
snek[0][1] = snek[0][1]-1;
break;
}
case 1: {
snek[0][0] = snek[0][0]-1;
break;
}
case 2: {
snek[0][1] = snek[0][1]+1;
break;
}
case 3: {
snek[0][0] = snek[0][0]+1;
break;
}
}
} else {
if(i+1==snek.size()) {
switch(direct) {
case 0: {
if(snek[0][1]-1==food[1] && snek[0][0]==food[0]) {
snek.push_back(snek[i]);
newFood();
}
break;
}
case 1: {
if(snek[0][0]-1==food[0] && snek[0][1]==food[1]) {
snek.push_back(snek[i]);
newFood();
}
break;
}
case 2: {
if(snek[0][1]+1==food[1] && snek[0][0]==food[0]) {
snek.push_back(snek[i]);
newFood();
}
break;
}
case 3: {
if(snek[0][0]+1==food[0] && snek[0][1]==food[1]) {
snek.push_back(snek[i]);
newFood();
}
break;
}
}
}
snek[i]=snek[i-1];
switch(direct) {
case 0: {
if(snek[0][1]-1==snek[i][1] && snek[0][0]==snek[i][0]) {
start = false;
game_over = true;
GameOver();
}
break;
}
case 1: {
if(snek[0][0]-1==snek[i][0] && snek[0][1]==snek[i][1]) {
start = false;
game_over = true;
GameOver();
}
break;
}
case 2: {
if(snek[0][1]+1==snek[i][1] && snek[0][0]==snek[i][0]) {
start = false;
game_over = true;
GameOver();
}
break;
}
case 3: {
if(snek[0][0]+1==snek[i][0] && snek[0][1]==snek[i][1]) {
start = false;
game_over = true;
GameOver();
}
break;
}
}
}
}
return snek;
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
int key = event->key();
qDebug()<<"Test";
if(!inverted) {
switch(key) {
case Qt::Key_Left: {
if(snek1_direction_current==0 || snek1_direction_current==2) {
snek1_direction_new = 1;
}
break;
}
case Qt::Key_Right: {
if(snek1_direction_current==0 || snek1_direction_current==2) {
snek1_direction_new = 3;
}
break;
}
case Qt::Key_Up: {
if(snek1_direction_current==1 || snek1_direction_current==3) {
snek1_direction_new = 0;
}
break;
}
case Qt::Key_Down: {
if(snek1_direction_current==1 || snek1_direction_current==3) {
snek1_direction_new = 2;
}
break;
}
}
switch(key) {
case Qt::Key_A: {
if(snek2_direction_current==0 || snek2_direction_current==2) {
snek2_direction_new = 1;
}
break;
}
case Qt::Key_D: {
if(snek2_direction_current==0 || snek2_direction_current==2) {
snek2_direction_new = 3;
}
break;
}
case Qt::Key_W: {
if(snek2_direction_current==1 || snek2_direction_current==3) {
snek2_direction_new = 0;
}
break;
}
case Qt::Key_S: {
if(snek2_direction_current==1 || snek2_direction_current==3) {
snek2_direction_new = 2;
}
break;
}
}
} else {
switch(key) {
case Qt::Key_Right: {
if(snek1_direction_current==0 || snek1_direction_current==2) {
snek1_direction_new = 1;
}
break;
}
case Qt::Key_Left: {
if(snek1_direction_current==0 || snek1_direction_current==2) {
snek1_direction_new = 3;
}
break;
}
case Qt::Key_Down: {
if(snek1_direction_current==1 || snek1_direction_current==3) {
snek1_direction_new = 0;
}
break;
}
case Qt::Key_Up: {
if(snek1_direction_current==1 || snek1_direction_current==3) {
snek1_direction_new = 2;
}
break;
}
}
switch(key) {
case Qt::Key_D: {
if(snek2_direction_current==0 || snek2_direction_current==2) {
snek2_direction_new = 1;
}
break;
}
case Qt::Key_A: {
if(snek2_direction_current==0 || snek2_direction_current==2) {
snek2_direction_new = 3;
}
break;
}
case Qt::Key_S: {
if(snek2_direction_current==1 || snek2_direction_current==3) {
snek2_direction_new = 0;
}
break;
}
case Qt::Key_W: {
if(snek2_direction_current==1 || snek2_direction_current==3) {
snek2_direction_new = 2;
}
break;
}
}
}
}
void MainWindow::on_Gamerbut_toggled(bool checked) {
diffictulty = 3;
speed = 70;
}
void MainWindow::on_Mediumbut_toggled(bool checked) {
diffictulty = 2;
speed = 90;
}
void MainWindow::on_Easybut_toggled(bool checked) {
diffictulty = 1;
speed = 100;
}
void MainWindow::on_Player1but_toggled(bool checked) {
players = 1;
}
void MainWindow::on_Player2but_toggled(bool checked) {
players = 2;
}
void MainWindow::GameOver() {
if(game_over) {
music.stop();
if(dead.isFinished()) {
dead.play();
} else {
dead.play();
}
QMessageBox msgBox;
QString GameText;
if(players==2) {
if(winner==0) {
if(snek1.size()==snek2.size()) {
int size = snek1.size();
GameText = "Thanks for playing. It was a tie. Both player's scores were : "+ QString::fromStdString(to_string(size)+". ") + "The high score is: " + QString::fromStdString(to_string(highscore) + ". ") + "Would you like to play agian?";
if(size>highscore) {
GameText = "Thanks for playing. You guys beat the high score but tied each other. Both player's scores were : "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
highscore = size;
setHighScore();
} else if(size==highscore) {
GameText = "Thanks for playing. You guys tied the high Score and with each other. Both player's scores were : "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
}
} else if(snek1.size()>snek2.size()) {
int size = snek1.size();
GameText = "Thanks for playing. Player 1 wins!!! Player's 1 score was: "+ QString::fromStdString(to_string(size)+". ") + "The high score is: " + QString::fromStdString(to_string(highscore) + ". ") + "Would you like to play agian?";
if(size>highscore) {
GameText = "Thanks for playing. Player 1 wins and beat the high score!!! Player's 1 score was: "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
highscore = size;
setHighScore();
} else if(size==highscore) {
GameText = "Thanks for playing. Player 1 wins and tied the high score!!! Player's 1 scores were : "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
}
} else {
int size = snek2.size();
GameText = "Thanks for playing. Player 2 wins!!! Player's 2 score was: "+ QString::fromStdString(to_string(size)+". ") + "The high score is: " + QString::fromStdString(to_string(highscore) + ". ") + "Would you like to play agian?";
if(size>highscore) {
GameText = "Thanks for playing. Player 2 wins and beat the high score!!! Player's 2 score was: "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
highscore = size;
setHighScore();
} else if(size==highscore) {
GameText = "Thanks for playing. Player 2 wins and tied the high score!!! Player's 2 scores were : "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
}
}
} else if(winner==1) {
int size = snek1.size();
GameText = "Thanks for playing. Player 1 wins!!! Player's 1 score was: "+ QString::fromStdString(to_string(size)+". ") + "The high score is: " + QString::fromStdString(to_string(highscore) + ". ") + "Would you like to play agian?";
if(size>highscore) {
GameText = "Thanks for playing. Player 1 wins and beat the high score!!! Player's 1 score was: "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
highscore = size;
setHighScore();
} else if(size==highscore) {
GameText = "Thanks for playing. Player 1 wins and tied the high score!!! Player's 1 scores were : "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
}
} else {
int size = snek2.size();
GameText = "Thanks for playing. Player 2 wins!!! Player's 2 score was: "+ QString::fromStdString(to_string(size)+". ") + "The high score is: " + QString::fromStdString(to_string(highscore) + ". ") + "Would you like to play agian?";
if(size>highscore) {
GameText = "Thanks for playing. Player 2 wins and beat the high score!!! Player's 2 score was: "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
highscore = size;
setHighScore();
} else if(size==highscore) {
GameText = "Thanks for playing. Player 2 wins and tied the high score!!! Player's 2 scores were : "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
}
}
} else {
int size = snek1.size();
GameText = "Thanks for playing. Your score was: "+ QString::fromStdString(to_string(size) +". ") + "The high score is: " + QString::fromStdString(to_string(highscore) + ". ") + "Would you like to play agian?";
if(size>highscore) {
GameText = "Thanks for playing. You beat the high score which is now: "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
highscore = size;
setHighScore();
} else if(size==highscore) {
GameText = "Thanks for playing. You tied the high score!!! Your score was: "+ QString::fromStdString(to_string(size)+". ") + "Would you like to play agian?";
}
}
msgBox.setText(GameText);
QAbstractButton *yes = msgBox.addButton(tr("Yes"), QMessageBox::YesRole);
QAbstractButton *no = msgBox.addButton(tr("No"), QMessageBox::YesRole);
msgBox.exec();
if(msgBox.clickedButton()==yes) {
start = false;
setFixedSize(start_width, start_height);
ui->Easybut->show();
ui->Gamerbut->show();
ui->Beginbut->show();
ui->Mediumbut->show();
ui->Player1but->show();
ui->Player2but->show();
ui->Instructbut->show();
ui->sneklab->show();
ui->playerlab->show();
ui->ctrInv->show();
ui->difflab->show();
begin = 0;
winner = -1;
} else {
qApp->exit(0);
}
game_over = false;
}
}
void MainWindow::on_Instructbut_clicked() {
QMessageBox msgBox;
QString instructions = "Welcome to snek(our version of the snake game).\n\n The object of the game is to grow your snake as big as possible by eating the fruit(red circles). Music will start to play and your snake will start moving at a consistent speed, based on the difficulty chosen. \n\nPlayer 1 will always be the green snake and use the arrow keys to turn in the associated direction. \n\nIf two players is selected then a blue snake will appear as well as a green snake head. The green snake will be player 1 and use the arrow keys while player 2 will use the \"WASD\" keys to move around the grid in attempt to grow and survive.\n\n And most importantly ENJOY :).";
msgBox.setText(instructions);
msgBox.exec();
}
void MainWindow::on_ctrInv_toggled(bool checked) {
if(!checked) {
inverted = false;
} else {
inverted = true;
}
}
| 36.164634 | 677 | 0.470199 | [
"object",
"vector"
] |
8b1848769c600fb0247ace5ccadaa5bebb398745 | 76,166 | cpp | C++ | src/par_msquares.cpp | jvo203/FITSWebQL | 59a98bc1916ce5b5d88ec1ee1986009f47a76e8b | [
"MIT"
] | 1 | 2022-03-09T07:21:48.000Z | 2022-03-09T07:21:48.000Z | src/par_msquares.cpp | jvo203/FITSWebQL | 59a98bc1916ce5b5d88ec1ee1986009f47a76e8b | [
"MIT"
] | 1 | 2020-06-04T08:12:36.000Z | 2020-06-08T06:20:06.000Z | src/par_msquares.cpp | jvo203/FITSWebQL | 59a98bc1916ce5b5d88ec1ee1986009f47a76e8b | [
"MIT"
] | null | null | null | #include "par_msquares.hpp"
#ifndef PAR_MSQUARES_IMPLEMENTATION
#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include <string.h>
typedef struct {
PAR_MSQUARES_T* values;
size_t count;
size_t capacity;
} par__uint16list;
typedef struct {
float* points;
int npoints;
PAR_MSQUARES_T* triangles;
int ntriangles;
int dim;
uint32_t color;
int nconntriangles;
PAR_MSQUARES_T* conntri;
par__uint16list* tjunctions;
} par_msquares__mesh;
struct par_msquares_meshlist_s {
int nmeshes;
par_msquares__mesh** meshes;
};
static int** par_msquares_binary_point_table = 0;
static int** par_msquares_binary_triangle_table = 0;
static int* par_msquares_quaternary_triangle_table[64][4];
static int* par_msquares_quaternary_boundary_table[64][4];
static par_msquares_meshlist* par_msquares__merge(par_msquares_meshlist** lists,
int count, int snap);
static void par_init_tables()
{
char const* BINARY_TABLE =
"0"
"1017"
"1123"
"2023370"
"1756"
"2015560"
"2123756"
"3023035056"
"1345"
"4013034045057"
"2124451"
"3024045057"
"2734467"
"3013034046"
"3124146167"
"2024460";
char const* binary_token = BINARY_TABLE;
par_msquares_binary_point_table = PAR_CALLOC(int*, 16);
par_msquares_binary_triangle_table = PAR_CALLOC(int*, 16);
for (int i = 0; i < 16; i++) {
int ntris = *binary_token - '0';
binary_token++;
par_msquares_binary_triangle_table[i] =
PAR_CALLOC(int, (ntris + 1) * 3);
int* sqrtris = par_msquares_binary_triangle_table[i];
sqrtris[0] = ntris;
int mask = 0;
int* sqrpts = par_msquares_binary_point_table[i] = PAR_CALLOC(int, 7);
sqrpts[0] = 0;
for (int j = 0; j < ntris * 3; j++, binary_token++) {
int midp = *binary_token - '0';
int bit = 1 << midp;
if (!(mask & bit)) {
mask |= bit;
sqrpts[++sqrpts[0]] = midp;
}
sqrtris[j + 1] = midp;
}
}
char const* QUATERNARY_TABLE =
"2024046000"
"3346360301112300"
"3346360301112300"
"3346360301112300"
"3560502523013450"
"2015056212414500"
"4018087785756212313828348450"
"4018087785756212313828348450"
"3560502523013450"
"4018087785756212313828348450"
"2015056212414500"
"4018087785756212313828348450"
"3560502523013450"
"4018087785756212313828348450"
"4018087785756212313828348450"
"2015056212414500"
"3702724745001756"
"2018087212313828348452785756"
"4013034045057112301756"
"4013034045057112301756"
"2023037027347460"
"1701312414616700"
"2018087212313847857568348450"
"2018087212313847857568348450"
"4018087123138028348452785756"
"1701467161262363513450"
"2018087412313883484502785756"
"2018087212313828348452785756"
"4018087123138028348452785756"
"1701467161262363513450"
"2018087212313828348452785756"
"2018087412313883484502785756"
"3702724745001756"
"4013034045057112301756"
"2018087212313828348452785756"
"4013034045057112301756"
"4018087123138028348452785756"
"2018087412313883484502785756"
"1701467161262363513450"
"2018087212313828348452785756"
"2023037027347460"
"2018087212313847857568348450"
"1701312414616700"
"2018087212313847857568348450"
"4018087123138028348452785756"
"2018087212313828348452785756"
"1701467161262363513450"
"2018087412313883484502785756"
"3702724745001756"
"4013034045057112301756"
"4013034045057112301756"
"2018087212313828348452785756"
"4018087123138028348452785756"
"2018087412313883484502785756"
"2018087212313828348452785756"
"1701467161262363513450"
"4018087123138028348452785756"
"2018087212313828348452785756"
"2018087412313883484502785756"
"1701467161262363513450"
"2023037027347460"
"2018087212313847857568348450"
"2018087212313847857568348450"
"1701312414616700";
char const* quaternary_token = QUATERNARY_TABLE;
int* quaternary_values = PAR_CALLOC(int, strlen(QUATERNARY_TABLE));
int* vals = quaternary_values;
for (int i = 0; i < 64; i++) {
int ntris = *quaternary_token++ - '0';
*vals = ntris;
par_msquares_quaternary_triangle_table[i][0] = vals++;
for (int j = 0; j < ntris * 3; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
ntris = *quaternary_token++ - '0';
*vals = ntris;
par_msquares_quaternary_triangle_table[i][1] = vals++;
for (int j = 0; j < ntris * 3; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
ntris = *quaternary_token++ - '0';
*vals = ntris;
par_msquares_quaternary_triangle_table[i][2] = vals++;
for (int j = 0; j < ntris * 3; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
ntris = *quaternary_token++ - '0';
*vals = ntris;
par_msquares_quaternary_triangle_table[i][3] = vals++;
for (int j = 0; j < ntris * 3; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
}
assert(vals == quaternary_values + strlen(QUATERNARY_TABLE));
char const* QUATERNARY_EDGES =
"0000"
"11313100113131001131310013501530"
"115151002188523881258830218852388125883013501530"
"218852388125883011515100218852388125883013501530"
"218852388125883021885238812588301151510015700175"
"2188723881258832788521357131017521357131017513701730"
"11717100218872388127883021887238812788302388702588327885"
"1172713515302188725881027885218872388125883278852388702588327885"
"11727135153021887238812588327885218872588102788515700175"
"213571310175218872388125883278852135713101752388702588327885"
"21887258810278851172713515302188723881258832788513701730"
"21887238812788301171710021887238812788302388702588327885"
"21887238812588327885117271351530218872588102788515700175"
"213571310175213571310175218872388125883278852388702588327885"
"2188725881027885218872388125883278851172713515302388702588327885"
"21887238812588327885218872588102788511727135153013701730"
"2188723881278830218872388127883011717100";
quaternary_token = QUATERNARY_EDGES;
quaternary_values = PAR_CALLOC(int, strlen(QUATERNARY_EDGES));
vals = quaternary_values;
for (int i = 0; i < 64; i++) {
int nedges = *quaternary_token++ - '0';
*vals = nedges;
par_msquares_quaternary_boundary_table[i][0] = vals++;
for (int j = 0; j < nedges * 2; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
nedges = *quaternary_token++ - '0';
*vals = nedges;
par_msquares_quaternary_boundary_table[i][1] = vals++;
for (int j = 0; j < nedges * 2; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
nedges = *quaternary_token++ - '0';
*vals = nedges;
par_msquares_quaternary_boundary_table[i][2] = vals++;
for (int j = 0; j < nedges * 2; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
nedges = *quaternary_token++ - '0';
*vals = nedges;
par_msquares_quaternary_boundary_table[i][3] = vals++;
for (int j = 0; j < nedges * 2; j++) {
int pt = *quaternary_token++ - '0';
assert(pt >= 0 && pt < 9);
*vals++ = pt;
}
}
assert(vals == quaternary_values + strlen(QUATERNARY_EDGES));
}
typedef struct {
float const* data;
float threshold;
float lower_bound;
float upper_bound;
int width;
int height;
} par_gray_context;
static int gray_inside(int location, void* contextptr)
{
par_gray_context* context = (par_gray_context*) contextptr;
return context->data[location] > context->threshold;
}
static int gray_multi_inside(int location, void* contextptr)
{
par_gray_context* context = (par_gray_context*) contextptr;
float val = context->data[location];
float upper = context->upper_bound;
float lower = context->lower_bound;
return val >= lower && val < upper;
}
static float gray_height(float x, float y, void* contextptr)
{
par_gray_context* context = (par_gray_context*) contextptr;
int i = PAR_CLAMP(context->width * x, 0, context->width - 1);
int j = PAR_CLAMP(context->height * y, 0, context->height - 1);
return context->data[i + j * context->width];
}
typedef struct {
par_byte const* data;
par_byte color[4];
int bpp;
int width;
int height;
} par_color_context;
static int color_inside(int location, void* contextptr)
{
par_color_context* context = (par_color_context*) contextptr;
par_byte const* data = context->data + location * context->bpp;
for (int i = 0; i < context->bpp; i++) {
if (data[i] != context->color[i]) {
return 0;
}
}
return 1;
}
static float color_height(float x, float y, void* contextptr)
{
par_color_context* context = (par_color_context*) contextptr;
assert(context->bpp == 4);
int i = PAR_CLAMP(context->width * x, 0, context->width - 1);
int j = PAR_CLAMP(context->height * y, 0, context->height - 1);
int k = i + j * context->width;
return context->data[k * 4 + 3] / 255.0;
}
par_msquares_meshlist* par_msquares_color(par_byte const* data, int width,
int height, int cellsize, uint32_t color, int bpp, int flags)
{
par_color_context context;
context.bpp = bpp;
if (flags & PAR_MSQUARES_SWIZZLE) {
context.color[0] = (color >> 0) & 0xff;
context.color[1] = (color >> 8) & 0xff;
context.color[2] = (color >> 16) & 0xff;
context.color[3] = (color >> 24) & 0xff;
} else {
context.color[0] = (color >> 16) & 0xff;
context.color[1] = (color >> 8) & 0xff;
context.color[2] = (color >> 0) & 0xff;
context.color[3] = (color >> 24) & 0xff;
}
context.data = data;
context.width = width;
context.height = height;
return par_msquares_function(
width, height, cellsize, flags, &context, color_inside, color_height);
}
par_msquares_meshlist* par_msquares_grayscale(float const* data, int width,
int height, int cellsize, float threshold, int flags)
{
par_gray_context context;
context.width = width;
context.height = height;
context.data = data;
context.threshold = threshold;
return par_msquares_function(
width, height, cellsize, flags, &context, gray_inside, gray_height);
}
par_msquares_meshlist* par_msquares_grayscale_multi(float const* data,
int width, int height, int cellsize, float const* thresholds,
int nthresholds, int flags)
{
par_msquares_meshlist* mlists[2];
mlists[0] = PAR_CALLOC(par_msquares_meshlist, 1);
int connect = flags & PAR_MSQUARES_CONNECT;
int snap = flags & PAR_MSQUARES_SNAP;
int heights = flags & PAR_MSQUARES_HEIGHTS;
if (!heights) {
snap = connect = 0;
}
flags &= ~PAR_MSQUARES_INVERT;
flags &= ~PAR_MSQUARES_DUAL;
flags &= ~PAR_MSQUARES_CONNECT;
flags &= ~PAR_MSQUARES_SNAP;
par_gray_context context;
context.width = width;
context.height = height;
context.data = data;
context.lower_bound = -FLT_MAX;
for (int i = 0; i <= nthresholds; i++) {
int mergeconf = i > 0 ? connect : 0;
if (i == nthresholds) {
context.upper_bound = FLT_MAX;
mergeconf |= snap;
} else {
context.upper_bound = thresholds[i];
}
mlists[1] = par_msquares_function(width, height, cellsize, flags,
&context, gray_multi_inside, gray_height);
mlists[0] = par_msquares__merge(mlists, 2, mergeconf);
context.lower_bound = context.upper_bound;
flags |= connect;
}
return mlists[0];
}
par_msquares_mesh const* par_msquares_get_mesh(
par_msquares_meshlist* mlist, int mindex)
{
assert(mlist && mindex < mlist->nmeshes);
return (par_msquares_mesh const*) mlist->meshes[mindex];
}
int par_msquares_get_count(par_msquares_meshlist* mlist)
{
assert(mlist);
return mlist->nmeshes;
}
void par_msquares_free(par_msquares_meshlist* mlist)
{
if (!mlist) {
return;
}
par_msquares__mesh** meshes = mlist->meshes;
for (int i = 0; i < mlist->nmeshes; i++) {
free(meshes[i]->points);
free(meshes[i]->triangles);
free(meshes[i]);
}
free(meshes);
free(mlist);
}
// Combine multiple meshlists by moving mesh pointers, and optionally applying
// a snap operation that assigns a single Z value across all verts in each
// mesh. The Z value determined by the mesh's position in the final mesh list.
static par_msquares_meshlist* par_msquares__merge(par_msquares_meshlist** lists,
int count, int snap)
{
par_msquares_meshlist* merged = PAR_CALLOC(par_msquares_meshlist, 1);
merged->nmeshes = 0;
for (int i = 0; i < count; i++) {
merged->nmeshes += lists[i]->nmeshes;
}
merged->meshes = PAR_CALLOC(par_msquares__mesh*, merged->nmeshes);
par_msquares__mesh** pmesh = merged->meshes;
for (int i = 0; i < count; i++) {
par_msquares_meshlist* meshlist = lists[i];
for (int j = 0; j < meshlist->nmeshes; j++) {
*pmesh++ = meshlist->meshes[j];
}
free(meshlist);
}
if (!snap) {
return merged;
}
pmesh = merged->meshes;
float zmin = FLT_MAX;
float zmax = -zmin;
for (int i = 0; i < merged->nmeshes; i++, pmesh++) {
float* pzed = (*pmesh)->points + 2;
for (int j = 0; j < (*pmesh)->npoints; j++, pzed += 3) {
zmin = PAR_MIN(*pzed, zmin);
zmax = PAR_MAX(*pzed, zmax);
}
}
float zextent = zmax - zmin;
pmesh = merged->meshes;
for (int i = 0; i < merged->nmeshes; i++, pmesh++) {
float* pzed = (*pmesh)->points + 2;
float zed = zmin + zextent * i / (merged->nmeshes - 1);
for (int j = 0; j < (*pmesh)->npoints; j++, pzed += 3) {
*pzed = zed;
}
}
if (!(snap & PAR_MSQUARES_CONNECT)) {
return merged;
}
for (int i = 1; i < merged->nmeshes; i++) {
par_msquares__mesh* mesh = merged->meshes[i];
// Find all extrusion points. This is tightly coupled to the
// tessellation code, which generates two "connector" triangles for each
// extruded edge. The first two verts of the second triangle are the
// verts that need to be displaced.
char* markers = PAR_CALLOC(char, mesh->npoints);
int tri = mesh->ntriangles - mesh->nconntriangles;
while (tri < mesh->ntriangles) {
markers[mesh->triangles[tri * 3 + 3]] = 1;
markers[mesh->triangles[tri * 3 + 4]] = 1;
tri += 2;
}
// Displace all extrusion points down to the previous level.
float zed = zmin + zextent * (i - 1) / (merged->nmeshes - 1);
float* pzed = mesh->points + 2;
for (int j = 0; j < mesh->npoints; j++, pzed += 3) {
if (markers[j]) {
*pzed = zed;
}
}
free(markers);
}
return merged;
}
static void par_remove_unreferenced_verts(par_msquares__mesh* mesh)
{
if (mesh->npoints == 0) {
return;
}
char* markers = PAR_CALLOC(char, mesh->npoints);
PAR_MSQUARES_T const* ptris = mesh->triangles;
int newnpts = 0;
for (int i = 0; i < mesh->ntriangles * 3; i++, ptris++) {
if (!markers[*ptris]) {
newnpts++;
markers[*ptris] = 1;
}
}
float* newpts = PAR_CALLOC(float, newnpts * mesh->dim);
PAR_MSQUARES_T* mapping = PAR_CALLOC(PAR_MSQUARES_T, mesh->npoints);
float const* ppts = mesh->points;
float* pnewpts = newpts;
int j = 0;
if (mesh->dim == 3) {
for (int i = 0; i < mesh->npoints; i++, ppts += 3) {
if (markers[i]) {
*pnewpts++ = ppts[0];
*pnewpts++ = ppts[1];
*pnewpts++ = ppts[2];
mapping[i] = j++;
}
}
} else {
for (int i = 0; i < mesh->npoints; i++, ppts += 2) {
if (markers[i]) {
*pnewpts++ = ppts[0];
*pnewpts++ = ppts[1];
mapping[i] = j++;
}
}
}
free(mesh->points);
free(markers);
mesh->points = newpts;
mesh->npoints = newnpts;
for (int i = 0; i < mesh->ntriangles * 3; i++) {
mesh->triangles[i] = mapping[mesh->triangles[i]];
}
free(mapping);
}
par_msquares_meshlist* par_msquares_function(int width, int height,
int cellsize, int flags, void* context, par_msquares_inside_fn insidefn,
par_msquares_height_fn heightfn)
{
assert(width > 0 && width % cellsize == 0);
assert(height > 0 && height % cellsize == 0);
if (flags & PAR_MSQUARES_DUAL) {
int connect = flags & PAR_MSQUARES_CONNECT;
int snap = flags & PAR_MSQUARES_SNAP;
int heights = flags & PAR_MSQUARES_HEIGHTS;
if (!heights) {
snap = connect = 0;
}
flags ^= PAR_MSQUARES_INVERT;
flags &= ~PAR_MSQUARES_DUAL;
flags &= ~PAR_MSQUARES_CONNECT;
par_msquares_meshlist* m[2];
m[0] = par_msquares_function(width, height, cellsize, flags,
context, insidefn, heightfn);
flags ^= PAR_MSQUARES_INVERT;
if (connect) {
flags |= PAR_MSQUARES_CONNECT;
}
m[1] = par_msquares_function(width, height, cellsize, flags,
context, insidefn, heightfn);
return par_msquares__merge(m, 2, snap | connect);
}
int invert = flags & PAR_MSQUARES_INVERT;
// Create the two code tables if we haven't already. These are tables of
// fixed constants, so it's embarassing that we use dynamic memory
// allocation for them. However it's easy and it's one-time-only.
if (!par_msquares_binary_point_table) {
par_init_tables();
}
// Allocate the meshlist and the first mesh.
par_msquares_meshlist* mlist = PAR_CALLOC(par_msquares_meshlist, 1);
mlist->nmeshes = 1;
mlist->meshes = PAR_CALLOC(par_msquares__mesh*, 1);
mlist->meshes[0] = PAR_CALLOC(par_msquares__mesh, 1);
par_msquares__mesh* mesh = mlist->meshes[0];
mesh->dim = (flags & PAR_MSQUARES_HEIGHTS) ? 3 : 2;
int ncols = width / cellsize;
int nrows = height / cellsize;
// Worst case is four triangles and six verts per cell, so allocate that
// much.
int maxtris = ncols * nrows * 4;
int maxpts = ncols * nrows * 6;
int maxedges = ncols * nrows * 2;
// However, if we include extrusion triangles for boundary edges,
// we need space for another 4 triangles and 4 points per cell.
PAR_MSQUARES_T* conntris = 0;
int nconntris = 0;
PAR_MSQUARES_T* edgemap = 0;
if (flags & PAR_MSQUARES_CONNECT) {
conntris = PAR_CALLOC(PAR_MSQUARES_T, maxedges * 6);
maxtris += maxedges * 2;
maxpts += maxedges * 2;
edgemap = PAR_CALLOC(PAR_MSQUARES_T, maxpts);
for (int i = 0; i < maxpts; i++) {
edgemap[i] = 0xffff;
}
}
PAR_MSQUARES_T* tris = PAR_CALLOC(PAR_MSQUARES_T, maxtris * 3);
int ntris = 0;
float* pts = PAR_CALLOC(float, maxpts * mesh->dim);
int npts = 0;
// The "verts" x/y/z arrays are the 4 corners and 4 midpoints around the
// square, in counter-clockwise order. The origin of "triangle space" is at
// the lower-left, although we expect the image data to be in raster order
// (starts at top-left).
float vertsx[8], vertsy[8];
float normalization = 1.0f / PAR_MAX(width, height);
float normalized_cellsize = cellsize * normalization;
int maxrow = (height - 1) * width;
PAR_MSQUARES_T* ptris = tris;
PAR_MSQUARES_T* pconntris = conntris;
float* ppts = pts;
uint8_t* prevrowmasks = PAR_CALLOC(uint8_t, ncols);
int* prevrowinds = PAR_CALLOC(int, ncols * 3);
// If simplification is enabled, we need to track all 'F' cells and their
// repsective triangle indices.
uint8_t* simplification_codes = 0;
PAR_MSQUARES_T* simplification_tris = 0;
uint8_t* simplification_ntris = 0;
if (flags & PAR_MSQUARES_SIMPLIFY) {
simplification_codes = PAR_CALLOC(uint8_t, nrows * ncols);
simplification_tris = PAR_CALLOC(PAR_MSQUARES_T, nrows * ncols);
simplification_ntris = PAR_CALLOC(uint8_t, nrows * ncols);
}
// Do the march!
for (int row = 0; row < nrows; row++) {
vertsx[0] = vertsx[6] = vertsx[7] = 0;
vertsx[1] = vertsx[5] = 0.5 * normalized_cellsize;
vertsx[2] = vertsx[3] = vertsx[4] = normalized_cellsize;
vertsy[0] = vertsy[1] = vertsy[2] = normalized_cellsize * (row + 1);
vertsy[4] = vertsy[5] = vertsy[6] = normalized_cellsize * row;
vertsy[3] = vertsy[7] = normalized_cellsize * (row + 0.5);
int northi = row * cellsize * width;
int southi = PAR_MIN(northi + cellsize * width, maxrow);
int northwest = invert ^ insidefn(northi, context);
int southwest = invert ^ insidefn(southi, context);
int previnds[8] = {0};
uint8_t prevmask = 0;
for (int col = 0; col < ncols; col++) {
northi += cellsize;
southi += cellsize;
if (col == ncols - 1) {
northi--;
southi--;
}
int northeast = invert ^ insidefn(northi, context);
int southeast = invert ^ insidefn(southi, context);
int code = southwest | (southeast << 1) | (northwest << 2) |
(northeast << 3);
int const* pointspec = par_msquares_binary_point_table[code];
int ptspeclength = *pointspec++;
int currinds[8] = {0};
uint8_t mask = 0;
uint8_t prevrowmask = prevrowmasks[col];
while (ptspeclength--) {
int midp = *pointspec++;
int bit = 1 << midp;
mask |= bit;
// The following six conditionals perform welding to reduce the
// number of vertices. The first three perform welding with the
// cell to the west; the latter three perform welding with the
// cell to the north.
if (bit == 1 && (prevmask & 4)) {
currinds[midp] = previnds[2];
continue;
}
if (bit == 128 && (prevmask & 8)) {
currinds[midp] = previnds[3];
continue;
}
if (bit == 64 && (prevmask & 16)) {
currinds[midp] = previnds[4];
continue;
}
if (bit == 16 && (prevrowmask & 4)) {
currinds[midp] = prevrowinds[col * 3 + 2];
continue;
}
if (bit == 32 && (prevrowmask & 2)) {
currinds[midp] = prevrowinds[col * 3 + 1];
continue;
}
if (bit == 64 && (prevrowmask & 1)) {
currinds[midp] = prevrowinds[col * 3 + 0];
continue;
}
ppts[0] = vertsx[midp];
ppts[1] = vertsy[midp];
// Adjust the midpoints to a more exact crossing point.
if (midp == 1) {
int begin = southi - cellsize / 2;
int previous = 0;
for (int i = 0; i < cellsize; i++) {
int offset = begin + i / 2 * ((i % 2) ? -1 : 1);
int inside = insidefn(offset, context);
if (i > 0 && inside != previous) {
ppts[0] = normalization *
(col * cellsize + offset - southi + cellsize);
break;
}
previous = inside;
}
} else if (midp == 5) {
int begin = northi - cellsize / 2;
int previous = 0;
for (int i = 0; i < cellsize; i++) {
int offset = begin + i / 2 * ((i % 2) ? -1 : 1);
int inside = insidefn(offset, context);
if (i > 0 && inside != previous) {
ppts[0] = normalization *
(col * cellsize + offset - northi + cellsize);
break;
}
previous = inside;
}
} else if (midp == 3) {
int begin = northi + width * cellsize / 2;
int previous = 0;
for (int i = 0; i < cellsize; i++) {
int offset = begin +
width * (i / 2 * ((i % 2) ? -1 : 1));
int inside = insidefn(offset, context);
if (i > 0 && inside != previous) {
ppts[1] = normalization *
(row * cellsize +
(offset - northi) / (float) width);
break;
}
previous = inside;
}
} else if (midp == 7) {
int begin = northi + width * cellsize / 2 - cellsize;
int previous = 0;
for (int i = 0; i < cellsize; i++) {
int offset = begin +
width * (i / 2 * ((i % 2) ? -1 : 1));
int inside = insidefn(offset, context);
if (i > 0 && inside != previous) {
ppts[1] = normalization *
(row * cellsize +
(offset - northi - cellsize) / (float) width);
break;
}
previous = inside;
}
}
if (mesh->dim == 3) {
if (width > height) {
ppts[2] = heightfn(ppts[0], ppts[1] * width / height,
context);
} else {
ppts[2] = heightfn(ppts[0] * height / width, ppts[1],
context);
}
}
ppts += mesh->dim;
currinds[midp] = npts++;
}
int const* trianglespec = par_msquares_binary_triangle_table[code];
int trispeclength = *trianglespec++;
if (flags & PAR_MSQUARES_SIMPLIFY) {
simplification_codes[ncols * row + col] = code;
simplification_tris[ncols * row + col] = ntris;
simplification_ntris[ncols * row + col] = trispeclength;
}
// Add triangles.
while (trispeclength--) {
int a = *trianglespec++;
int b = *trianglespec++;
int c = *trianglespec++;
*ptris++ = currinds[c];
*ptris++ = currinds[b];
*ptris++ = currinds[a];
ntris++;
}
// Create two extrusion triangles for each boundary edge.
if (flags & PAR_MSQUARES_CONNECT) {
trianglespec = par_msquares_binary_triangle_table[code];
trispeclength = *trianglespec++;
while (trispeclength--) {
int a = *trianglespec++;
int b = *trianglespec++;
int c = *trianglespec++;
int i = currinds[a];
int j = currinds[b];
int k = currinds[c];
int u = 0, v = 0, w = 0;
if ((a % 2) && (b % 2)) {
u = v = 1;
} else if ((a % 2) && (c % 2)) {
u = w = 1;
} else if ((b % 2) && (c % 2)) {
v = w = 1;
} else {
continue;
}
if (u && edgemap[i] == 0xffff) {
for (int d = 0; d < mesh->dim; d++) {
*ppts++ = pts[i * mesh->dim + d];
}
edgemap[i] = npts++;
}
if (v && edgemap[j] == 0xffff) {
for (int d = 0; d < mesh->dim; d++) {
*ppts++ = pts[j * mesh->dim + d];
}
edgemap[j] = npts++;
}
if (w && edgemap[k] == 0xffff) {
for (int d = 0; d < mesh->dim; d++) {
*ppts++ = pts[k * mesh->dim + d];
}
edgemap[k] = npts++;
}
if ((a % 2) && (b % 2)) {
*pconntris++ = i;
*pconntris++ = j;
*pconntris++ = edgemap[j];
*pconntris++ = edgemap[j];
*pconntris++ = edgemap[i];
*pconntris++ = i;
} else if ((a % 2) && (c % 2)) {
*pconntris++ = edgemap[k];
*pconntris++ = k;
*pconntris++ = i;
*pconntris++ = edgemap[i];
*pconntris++ = edgemap[k];
*pconntris++ = i;
} else if ((b % 2) && (c % 2)) {
*pconntris++ = j;
*pconntris++ = k;
*pconntris++ = edgemap[k];
*pconntris++ = edgemap[k];
*pconntris++ = edgemap[j];
*pconntris++ = j;
}
nconntris += 2;
}
}
// Prepare for the next cell.
prevrowmasks[col] = mask;
prevrowinds[col * 3 + 0] = currinds[0];
prevrowinds[col * 3 + 1] = currinds[1];
prevrowinds[col * 3 + 2] = currinds[2];
prevmask = mask;
northwest = northeast;
southwest = southeast;
for (int i = 0; i < 8; i++) {
previnds[i] = currinds[i];
vertsx[i] += normalized_cellsize;
}
}
}
free(edgemap);
free(prevrowmasks);
free(prevrowinds);
// Perform quick-n-dirty simplification by iterating two rows at a time.
// In no way does this create the simplest possible mesh, but at least it's
// fast and easy.
if (flags & PAR_MSQUARES_SIMPLIFY) {
int in_run = 0, start_run;
// First figure out how many triangles we can eliminate.
int neliminated_triangles = 0;
for (int row = 0; row < nrows - 1; row += 2) {
for (int col = 0; col < ncols; col++) {
int a = simplification_codes[ncols * row + col] == 0xf;
int b = simplification_codes[ncols * row + col + ncols] == 0xf;
if (a && b) {
if (!in_run) {
in_run = 1;
start_run = col;
}
continue;
}
if (in_run) {
in_run = 0;
int run_width = col - start_run;
neliminated_triangles += run_width * 4 - 2;
}
}
if (in_run) {
in_run = 0;
int run_width = ncols - start_run;
neliminated_triangles += run_width * 4 - 2;
}
}
// Build a new index array cell-by-cell. If any given cell is 'F' and
// its neighbor to the south is also 'F', then it's part of a run.
int nnewtris = ntris + nconntris - neliminated_triangles;
PAR_MSQUARES_T* newtris = PAR_CALLOC(PAR_MSQUARES_T, nnewtris * 3);
PAR_MSQUARES_T* pnewtris = newtris;
in_run = 0;
for (int row = 0; row < nrows - 1; row += 2) {
for (int col = 0; col < ncols; col++) {
int cell = ncols * row + col;
int south = cell + ncols;
int a = simplification_codes[cell] == 0xf;
int b = simplification_codes[south] == 0xf;
if (a && b) {
if (!in_run) {
in_run = 1;
start_run = col;
}
continue;
}
if (in_run) {
in_run = 0;
int nw_cell = ncols * row + start_run;
int ne_cell = ncols * row + col - 1;
int sw_cell = nw_cell + ncols;
int se_cell = ne_cell + ncols;
int nw_tri = simplification_tris[nw_cell];
int ne_tri = simplification_tris[ne_cell];
int sw_tri = simplification_tris[sw_cell];
int se_tri = simplification_tris[se_cell];
int nw_corner = nw_tri * 3 + 4;
int ne_corner = ne_tri * 3 + 0;
int sw_corner = sw_tri * 3 + 2;
int se_corner = se_tri * 3 + 1;
*pnewtris++ = tris[se_corner];
*pnewtris++ = tris[sw_corner];
*pnewtris++ = tris[nw_corner];
*pnewtris++ = tris[nw_corner];
*pnewtris++ = tris[ne_corner];
*pnewtris++ = tris[se_corner];
}
int ncelltris = simplification_ntris[cell];
int celltri = simplification_tris[cell];
for (int t = 0; t < ncelltris; t++, celltri++) {
*pnewtris++ = tris[celltri * 3];
*pnewtris++ = tris[celltri * 3 + 1];
*pnewtris++ = tris[celltri * 3 + 2];
}
ncelltris = simplification_ntris[south];
celltri = simplification_tris[south];
for (int t = 0; t < ncelltris; t++, celltri++) {
*pnewtris++ = tris[celltri * 3];
*pnewtris++ = tris[celltri * 3 + 1];
*pnewtris++ = tris[celltri * 3 + 2];
}
}
if (in_run) {
in_run = 0;
int nw_cell = ncols * row + start_run;
int ne_cell = ncols * row + ncols - 1;
int sw_cell = nw_cell + ncols;
int se_cell = ne_cell + ncols;
int nw_tri = simplification_tris[nw_cell];
int ne_tri = simplification_tris[ne_cell];
int sw_tri = simplification_tris[sw_cell];
int se_tri = simplification_tris[se_cell];
int nw_corner = nw_tri * 3 + 4;
int ne_corner = ne_tri * 3 + 0;
int sw_corner = sw_tri * 3 + 2;
int se_corner = se_tri * 3 + 1;
*pnewtris++ = tris[se_corner];
*pnewtris++ = tris[sw_corner];
*pnewtris++ = tris[nw_corner];
*pnewtris++ = tris[nw_corner];
*pnewtris++ = tris[ne_corner];
*pnewtris++ = tris[se_corner];
}
}
ptris = pnewtris;
ntris -= neliminated_triangles;
free(tris);
tris = newtris;
free(simplification_codes);
free(simplification_tris);
free(simplification_ntris);
// Remove unreferenced points.
char* markers = PAR_CALLOC(char, npts);
ptris = tris;
int newnpts = 0;
for (int i = 0; i < ntris * 3; i++, ptris++) {
if (!markers[*ptris]) {
newnpts++;
markers[*ptris] = 1;
}
}
for (int i = 0; i < nconntris * 3; i++) {
if (!markers[conntris[i]]) {
newnpts++;
markers[conntris[i]] = 1;
}
}
float* newpts = PAR_CALLOC(float, newnpts * mesh->dim);
PAR_MSQUARES_T* mapping = PAR_CALLOC(PAR_MSQUARES_T, npts);
ppts = pts;
float* pnewpts = newpts;
int j = 0;
if (mesh->dim == 3) {
for (int i = 0; i < npts; i++, ppts += 3) {
if (markers[i]) {
*pnewpts++ = ppts[0];
*pnewpts++ = ppts[1];
*pnewpts++ = ppts[2];
mapping[i] = j++;
}
}
} else {
for (int i = 0; i < npts; i++, ppts += 2) {
if (markers[i]) {
*pnewpts++ = ppts[0];
*pnewpts++ = ppts[1];
mapping[i] = j++;
}
}
}
free(pts);
free(markers);
pts = newpts;
npts = newnpts;
for (int i = 0; i < ntris * 3; i++) {
tris[i] = mapping[tris[i]];
}
for (int i = 0; i < nconntris * 3; i++) {
conntris[i] = mapping[conntris[i]];
}
free(mapping);
}
// Append all extrusion triangles to the main triangle array.
// We need them to be last so that they form a contiguous sequence.
pconntris = conntris;
for (int i = 0; i < nconntris; i++) {
*ptris++ = *pconntris++;
*ptris++ = *pconntris++;
*ptris++ = *pconntris++;
ntris++;
}
free(conntris);
// Final cleanup and return.
assert(npts <= maxpts);
assert(ntris <= maxtris);
mesh->npoints = npts;
mesh->points = pts;
mesh->ntriangles = ntris;
mesh->triangles = tris;
mesh->nconntriangles = nconntris;
return mlist;
}
typedef struct {
PAR_MSQUARES_T outera;
PAR_MSQUARES_T outerb;
PAR_MSQUARES_T innera;
PAR_MSQUARES_T innerb;
char i;
char j;
par_msquares__mesh* mesh;
int mesh_index;
} par_connector;
static par_connector* par_conn_find(par_connector* conns, int nconns,
char i, char j)
{
for (int c = 0; c < nconns; c++) {
if (conns[c].i == i && conns[c].j == j) {
return conns + c;
}
}
return 0;
}
static int par_msquares_cmp(const void *a, const void *b)
{
uint32_t arg1 = *((uint32_t const*) a);
uint32_t arg2 = *((uint32_t const*) b);
if (arg1 < arg2) return -1;
if (arg1 > arg2) return 1;
return 0;
}
typedef int (*par_msquares_code_fn)(int, int, int, int, void*);
static int par_msquares_multi_code(int sw, int se, int ne, int nw)
{
int code[4];
int ncols = 0;
code[0] = ncols++;
if (se == sw) {
code[1] = code[0];
} else {
code[1] = ncols++;
}
if (ne == se) {
code[2] = code[1];
} else if (ne == sw) {
code[2] = code[0];
} else {
code[2] = ncols++;
}
if (nw == ne) {
code[3] = code[2];
} else if (nw == se) {
code[3] = code[1];
} else if (nw == sw) {
code[3] = code[0];
} else {
code[3] = ncols++;
}
return code[0] | (code[1] << 2) | (code[2] << 4) | (code[3] << 6);
}
static uint32_t par_msquares_argb(par_byte const* pdata, int bpp)
{
uint32_t color = 0;
if (bpp == 4) {
color |= pdata[2];
color |= pdata[1] << 8;
color |= pdata[0] << 16;
color |= pdata[3] << 24;
return color;
}
for (int j = 0; j < bpp; j++) {
color <<= 8;
color |= pdata[j];
}
return color;
}
// Merge connective triangles into the primary triangle list.
static void par_msquares__finalize(par_msquares_meshlist* mlist)
{
if (mlist->nmeshes < 2 || mlist->meshes[1]->nconntriangles == 0) {
return;
}
for (int m = 1; m < mlist->nmeshes; m++) {
par_msquares__mesh* mesh = mlist->meshes[m];
int ntris = mesh->ntriangles + mesh->nconntriangles;
PAR_MSQUARES_T* triangles = PAR_CALLOC(PAR_MSQUARES_T, ntris * 3);
PAR_MSQUARES_T* dst = triangles;
PAR_MSQUARES_T const* src = mesh->triangles;
for (int t = 0; t < mesh->ntriangles; t++) {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
}
src = mesh->conntri;
for (int t = 0; t < mesh->nconntriangles; t++) {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
}
free(mesh->triangles);
free(mesh->conntri);
mesh->triangles = triangles;
mesh->ntriangles = ntris;
mesh->conntri = 0;
mesh->nconntriangles = 0;
}
}
static par__uint16list* par__uint16list_create()
{
par__uint16list* list = PAR_CALLOC(par__uint16list, 1);
list->count = 0;
list->capacity = 32;
list->values = PAR_CALLOC(PAR_MSQUARES_T, list->capacity);
return list;
}
static void par__uint16list_add3(par__uint16list* list,
PAR_MSQUARES_T a, PAR_MSQUARES_T b, PAR_MSQUARES_T c)
{
if (list->count + 3 > list->capacity) {
list->capacity *= 2;
list->values = PAR_REALLOC(PAR_MSQUARES_T, list->values, list->capacity);
}
list->values[list->count++] = a;
list->values[list->count++] = b;
list->values[list->count++] = c;
}
static void par__uint16list_free(par__uint16list* list)
{
if (list) {
PAR_FREE(list->values);
PAR_FREE(list);
}
}
static void par_msquares__repair_tjunctions(par_msquares_meshlist* mlist)
{
for (int m = 0; m < mlist->nmeshes; m++) {
par_msquares__mesh* mesh = mlist->meshes[m];
par__uint16list* tjunctions = mesh->tjunctions;
int njunctions = (int) tjunctions->count / 3;
if (njunctions == 0) {
continue;
}
int ntriangles = mesh->ntriangles + njunctions;
mesh->triangles = PAR_REALLOC(PAR_MSQUARES_T, mesh->triangles,
ntriangles * 3);
PAR_MSQUARES_T const* jun = tjunctions->values;
PAR_MSQUARES_T* new_triangles = mesh->triangles + mesh->ntriangles * 3;
int ncreated = 0;
for (int j = 0; j < njunctions; j++, jun += 3) {
PAR_MSQUARES_T* tri = mesh->triangles;
int t;
for (t = 0; t < mesh->ntriangles; t++, tri += 3) {
int i = -1;
if (tri[0] == jun[0] && tri[1] == jun[1]) {
i = 0;
} else if (tri[1] == jun[0] && tri[2] == jun[1]) {
i = 1;
} else if (tri[2] == jun[0] && tri[0] == jun[1]) {
i = 2;
} else {
continue;
}
new_triangles[0] = tri[(i + 0) % 3];
new_triangles[1] = jun[2];
new_triangles[2] = tri[(i + 2) % 3];
tri[(i + 0) % 3] = jun[2];
new_triangles += 3;
ncreated++;
break;
}
// TODO: Need to investigate the "msquares_multi_diagram.obj" test.
assert(t != mesh->ntriangles &&
"Error with T-Junction repair; please disable the CLEAN flag.");
}
mesh->ntriangles += ncreated;
}
}
par_msquares_meshlist* par_msquares_color_multi(par_byte const* data, int width,
int height, int cellsize, int bpp, int flags)
{
if (!par_msquares_binary_point_table) {
par_init_tables();
}
const int ncols = width / cellsize;
const int nrows = height / cellsize;
const int maxrow = (height - 1) * width;
const int ncells = ncols * nrows;
const int dim = (flags & PAR_MSQUARES_HEIGHTS) ? 3 : 2;
const int west_to_east[9] = { 2, -1, -1, -1, -1, -1, 4, 3, -1 };
const int north_to_south[9] = { -1, -1, -1, -1, 2, 1, 0, -1, -1 };
assert(!(flags & PAR_MSQUARES_HEIGHTS) || bpp == 4);
assert(bpp > 0 && bpp <= 4 && "Bytes per pixel must be 1, 2, 3, or 4.");
assert(!(flags & PAR_MSQUARES_CLEAN) || !(flags & PAR_MSQUARES_SIMPLIFY));
assert(!(flags & PAR_MSQUARES_SNAP) &&
"SNAP is not supported with color_multi");
assert(!(flags & PAR_MSQUARES_INVERT) &&
"INVERT is not supported with color_multi");
assert(!(flags & PAR_MSQUARES_DUAL) &&
"DUAL is not supported with color_multi");
// Find all unique colors and ensure there are no more than 256 colors.
uint32_t colors[256];
int ncolors = 0;
par_byte const* pdata = data;
for (int i = 0; i < width * height; i++, pdata += bpp) {
uint32_t color = par_msquares_argb(pdata, bpp);
if (0 == bsearch(&color, colors, ncolors, 4, par_msquares_cmp)) {
assert(ncolors < 256);
colors[ncolors++] = color;
qsort(colors, ncolors, sizeof(uint32_t), par_msquares_cmp);
}
}
// Convert the color image to grayscale using the mapping table.
par_byte* pixels = PAR_CALLOC(par_byte, width * height);
pdata = data;
for (int i = 0; i < width * height; i++, pdata += bpp) {
uint32_t color = par_msquares_argb(pdata, bpp);
void* result = bsearch(&color, colors, ncolors, 4, par_msquares_cmp);
pixels[i] = (uint32_t*) result - &colors[0];
}
// Allocate 1 mesh for each color.
par_msquares_meshlist* mlist = PAR_CALLOC(par_msquares_meshlist, 1);
mlist->nmeshes = ncolors;
mlist->meshes = PAR_CALLOC(par_msquares__mesh*, ncolors);
par_msquares__mesh* mesh;
int maxtris_per_cell = 6;
int maxpts_per_cell = 9;
if (flags & PAR_MSQUARES_CONNECT) {
maxpts_per_cell += 6;
}
for (int i = 0; i < ncolors; i++) {
mesh = mlist->meshes[i] = PAR_CALLOC(par_msquares__mesh, 1);
mesh->color = colors[i];
mesh->points = PAR_CALLOC(float, ncells * maxpts_per_cell * dim);
mesh->triangles = PAR_CALLOC(PAR_MSQUARES_T, ncells * maxtris_per_cell * 3);
mesh->dim = dim;
mesh->tjunctions = par__uint16list_create();
if (flags & PAR_MSQUARES_CONNECT) {
mesh->conntri = PAR_CALLOC(PAR_MSQUARES_T, ncells * 8 * 3);
}
}
// The "verts" x/y/z arrays are the 4 corners and 4 midpoints around the
// square, in counter-clockwise order, starting at the lower-left. The
// ninth vert is the center point.
float vertsx[9], vertsy[9];
float normalization = 1.0f / PAR_MAX(width, height);
float normalized_cellsize = cellsize * normalization;
uint8_t cella[256];
uint8_t cellb[256];
uint8_t* currcell = cella;
uint8_t* prevcell = cellb;
PAR_MSQUARES_T inds0[256 * 9];
PAR_MSQUARES_T inds1[256 * 9];
PAR_MSQUARES_T* currinds = inds0;
PAR_MSQUARES_T* previnds = inds1;
PAR_MSQUARES_T* rowindsa = PAR_CALLOC(PAR_MSQUARES_T, ncols * 3 * 256);
uint8_t* rowcellsa = PAR_CALLOC(uint8_t, ncols * 256);
PAR_MSQUARES_T* rowindsb = PAR_CALLOC(PAR_MSQUARES_T, ncols * 3 * 256);
uint8_t* rowcellsb = PAR_CALLOC(uint8_t, ncols * 256);
PAR_MSQUARES_T* prevrowinds = rowindsa;
PAR_MSQUARES_T* currrowinds = rowindsb;
uint8_t* prevrowcells = rowcellsa;
uint8_t* currrowcells = rowcellsb;
uint32_t* simplification_words = 0;
if (flags & PAR_MSQUARES_SIMPLIFY) {
simplification_words = PAR_CALLOC(uint32_t, 2 * nrows * ncols);
}
// Do the march!
for (int row = 0; row < nrows; row++) {
vertsx[0] = vertsx[6] = vertsx[7] = 0;
vertsx[1] = vertsx[5] = vertsx[8] = 0.5 * normalized_cellsize;
vertsx[2] = vertsx[3] = vertsx[4] = normalized_cellsize;
vertsy[0] = vertsy[1] = vertsy[2] = normalized_cellsize * (row + 1);
vertsy[4] = vertsy[5] = vertsy[6] = normalized_cellsize * row;
vertsy[3] = vertsy[7] = vertsy[8] = normalized_cellsize * (row + 0.5);
int northi = row * cellsize * width;
int southi = PAR_MIN(northi + cellsize * width, maxrow);
int nwval = pixels[northi];
int swval = pixels[southi];
memset(currrowcells, 0, ncols * 256);
for (int col = 0; col < ncols; col++) {
northi += cellsize;
southi += cellsize;
if (col == ncols - 1) {
northi--;
southi--;
}
// Obtain 8-bit code and grab the four corresponding triangle lists.
int neval = pixels[northi];
int seval = pixels[southi];
int code = par_msquares_multi_code(swval, seval, neval, nwval) >> 2;
int const* trispecs[4] = {
par_msquares_quaternary_triangle_table[code][0],
par_msquares_quaternary_triangle_table[code][1],
par_msquares_quaternary_triangle_table[code][2],
par_msquares_quaternary_triangle_table[code][3]
};
int ntris[4] = {
*trispecs[0]++,
*trispecs[1]++,
*trispecs[2]++,
*trispecs[3]++
};
int const* edgespecs[4] = {
par_msquares_quaternary_boundary_table[code][0],
par_msquares_quaternary_boundary_table[code][1],
par_msquares_quaternary_boundary_table[code][2],
par_msquares_quaternary_boundary_table[code][3]
};
int nedges[4] = {
*edgespecs[0]++,
*edgespecs[1]++,
*edgespecs[2]++,
*edgespecs[3]++
};
int vals[4] = { swval, seval, neval, nwval };
// Gather topology information.
par_connector edges[16];
int ncedges = 0;
for (int c = 0; c < 4; c++) {
int color = vals[c];
par_msquares__mesh* mesh = mlist->meshes[color];
par_connector edge;
for (int e = 0; e < nedges[c]; e++) {
char previndex = edgespecs[c][e * 2];
char currindex = edgespecs[c][e * 2 + 1];
edge.i = previndex;
edge.j = currindex;
edge.mesh_index = color;
edge.mesh = mesh;
edges[ncedges++] = edge;
}
}
assert(ncedges < 16);
// Push triangles and points into the four affected meshes.
for (int m = 0; m < ncolors; m++) {
currcell[m] = 0;
}
uint32_t colors = 0;
uint32_t counts = 0;
PAR_MSQUARES_T* conntris_start[4];
for (int c = 0; c < 4; c++) {
int color = vals[c];
colors |= color << (8 * c);
counts |= ntris[c] << (8 * c);
par_msquares__mesh* mesh = mlist->meshes[color];
float height = (mesh->color >> 24) / 255.0;
conntris_start[c] = mesh->conntri + mesh->nconntriangles * 3;
int usedpts[9] = {0};
PAR_MSQUARES_T* pcurrinds = currinds + 9 * color;
PAR_MSQUARES_T const* pprevinds = previnds + 9 * color;
PAR_MSQUARES_T const* pprevrowinds =
prevrowinds + ncols * 3 * color + col * 3;
uint8_t prevrowcell = prevrowcells[color * ncols + col];
float* pdst = mesh->points + mesh->npoints * mesh->dim;
int previndex, prevflag;
for (int t = 0; t < ntris[c] * 3; t++) {
PAR_MSQUARES_T index = trispecs[c][t];
if (usedpts[index]) {
continue;
}
usedpts[index] = 1;
if (index < 8) {
currcell[color] |= 1 << index;
}
// Vertical welding.
previndex = north_to_south[index];
prevflag = (previndex > -1) ? (1 << previndex) : 0;
if (row > 0 && (prevrowcell & prevflag)) {
pcurrinds[index] = pprevrowinds[previndex];
continue;
}
// Horizontal welding.
previndex = west_to_east[index];
prevflag = (previndex > -1) ? (1 << previndex) : 0;
if (col > 0 && (prevcell[color] & prevflag)) {
pcurrinds[index] = pprevinds[previndex];
continue;
}
// Insert brand new point.
float* vertex = pdst;
*pdst++ = vertsx[index];
*pdst++ = 1 - vertsy[index];
if (mesh->dim == 3) {
*pdst++ = height;
}
pcurrinds[index] = mesh->npoints++;
// If this is a midpoint, nudge it to the intersection.
if (index == 1) {
int begin = southi - cellsize;
for (int i = 1; i < cellsize + 1; i++) {
int val = pixels[begin + i];
if (val != pixels[begin]) {
vertex[0] = vertsx[0] + normalized_cellsize *
(float) i / cellsize;
break;
}
}
} else if (index == 3) {
int begin = northi;
for (int i = 1; i < cellsize + 1; i++) {
int val = pixels[begin + i * width];
if (val != pixels[begin]) {
vertex[1] = (1 - vertsy[4]) -
normalized_cellsize * (float) i / cellsize;
break;
}
}
}
}
// Look for T junctions and note them for later repairs.
uint8_t prc = prevrowcell;
if (usedpts[4] && !usedpts[5] && usedpts[6] && (prc & 2)) {
// Above cell had a middle vert, current cell straddles it.
par__uint16list_add3(mesh->tjunctions,
pcurrinds[4], pcurrinds[6], pprevrowinds[1]);
} else if ((prc & 1) && !(prc & 2) && (prc & 4) && usedpts[5]) {
// Current cell has a middle vert, above cell straddles it.
par__uint16list_add3(mesh->tjunctions,
pprevrowinds[0], pprevrowinds[2], pcurrinds[5]);
}
uint8_t pcc = col > 0 ? prevcell[color] : 0;
if (usedpts[0] && !usedpts[7] && usedpts[6] && (pcc & 8)) {
// Left cell had a middle vert, current cell straddles it.
par__uint16list_add3(mesh->tjunctions,
pcurrinds[6], pcurrinds[0], pprevinds[3]);
}
if ((pcc & 4) && !(pcc & 8) && (pcc & 16) && usedpts[7]) {
// Current cell has a middle vert, left cell straddles it.
par__uint16list_add3(mesh->tjunctions,
pprevinds[2], pprevinds[4], pcurrinds[7]);
}
// Stamp out the cell's triangle indices for this color.
PAR_MSQUARES_T* tdst = mesh->triangles + mesh->ntriangles * 3;
mesh->ntriangles += ntris[c];
for (int t = 0; t < ntris[c] * 3; t++) {
PAR_MSQUARES_T index = trispecs[c][t];
*tdst++ = pcurrinds[index];
}
// Add extrusion points and connective triangles if requested.
if (!(flags & PAR_MSQUARES_CONNECT)) {
continue;
}
for (int e = 0; e < nedges[c]; e++) {
int previndex = edgespecs[c][e * 2];
int currindex = edgespecs[c][e * 2 + 1];
par_connector* thisedge = par_conn_find(edges,
ncedges, previndex, currindex);
thisedge->innera = pcurrinds[previndex];
thisedge->innerb = pcurrinds[currindex];
thisedge->outera = mesh->npoints;
thisedge->outerb = mesh->npoints + 1;
par_connector* oppedge = par_conn_find(edges,
ncedges, currindex, previndex);
if (oppedge->mesh_index > color) continue;
*pdst++ = vertsx[previndex];
*pdst++ = 1 - vertsy[previndex];
if (mesh->dim == 3) {
*pdst++ = height;
}
mesh->npoints++;
*pdst++ = vertsx[currindex];
*pdst++ = 1 - vertsy[currindex];
if (mesh->dim == 3) {
*pdst++ = height;
}
mesh->npoints++;
PAR_MSQUARES_T i0 = mesh->npoints - 1;
PAR_MSQUARES_T i1 = mesh->npoints - 2;
PAR_MSQUARES_T i2 = pcurrinds[previndex];
PAR_MSQUARES_T i3 = pcurrinds[currindex];
PAR_MSQUARES_T* ptr = mesh->conntri +
mesh->nconntriangles * 3;
*ptr++ = i2; *ptr++ = i1; *ptr++ = i0;
*ptr++ = i0; *ptr++ = i3; *ptr++ = i2;
mesh->nconntriangles += 2;
}
}
// Adjust the positions of the extrusion verts.
if (flags & PAR_MSQUARES_CONNECT) {
for (int c = 0; c < 4; c++) {
int color = vals[c];
PAR_MSQUARES_T* pconninds = conntris_start[c];
par_msquares__mesh* mesh = mlist->meshes[color];
for (int e = 0; e < nedges[c]; e++) {
int previndex = edgespecs[c][e * 2];
int currindex = edgespecs[c][e * 2 + 1];
PAR_MSQUARES_T i1 = pconninds[1];
PAR_MSQUARES_T i0 = pconninds[2];
par_connector const* oppedge = par_conn_find(edges,
ncedges, currindex, previndex);
if (oppedge->mesh_index > color) continue;
int d = mesh->dim;
float* dst = mesh->points;
float const* src = oppedge->mesh->points;
dst[i0 * d + 0] = src[oppedge->innera * d + 0];
dst[i0 * d + 1] = src[oppedge->innera * d + 1];
dst[i1 * d + 0] = src[oppedge->innerb * d + 0];
dst[i1 * d + 1] = src[oppedge->innerb * d + 1];
if (d == 3) {
dst[i0 * d + 2] = src[oppedge->innera * d + 2];
dst[i1 * d + 2] = src[oppedge->innerb * d + 2];
}
pconninds += 6;
}
}
}
// Stash the bottom indices for each mesh in this cell to enable
// vertical as-you-go welding.
uint8_t* pcurrrowcells = currrowcells;
PAR_MSQUARES_T* pcurrrowinds = currrowinds;
PAR_MSQUARES_T const* pcurrinds = currinds;
for (int color = 0; color < ncolors; color++) {
pcurrrowcells[col] = currcell[color];
pcurrrowcells += ncols;
pcurrrowinds[col * 3 + 0] = pcurrinds[0];
pcurrrowinds[col * 3 + 1] = pcurrinds[1];
pcurrrowinds[col * 3 + 2] = pcurrinds[2];
pcurrrowinds += ncols * 3;
pcurrinds += 9;
}
// Stash some information later used by simplification.
if (flags & PAR_MSQUARES_SIMPLIFY) {
int cell = col + row * ncols;
simplification_words[cell * 2] = colors;
simplification_words[cell * 2 + 1] = counts;
}
// Advance the cursor.
nwval = neval;
swval = seval;
for (int i = 0; i < 9; i++) {
vertsx[i] += normalized_cellsize;
}
PAR_SWAP(uint8_t*, prevcell, currcell);
PAR_SWAP(PAR_MSQUARES_T*, previnds, currinds);
}
PAR_SWAP(uint8_t*, prevrowcells, currrowcells);
PAR_SWAP(PAR_MSQUARES_T*, prevrowinds, currrowinds);
}
free(prevrowinds);
free(prevrowcells);
free(pixels);
if (flags & PAR_MSQUARES_CLEAN) {
par_msquares__repair_tjunctions(mlist);
}
for (int m = 0; m < mlist->nmeshes; m++) {
par_msquares__mesh* mesh = mlist->meshes[m];
par__uint16list_free(mesh->tjunctions);
}
if (!(flags & PAR_MSQUARES_SIMPLIFY)) {
par_msquares__finalize(mlist);
return mlist;
}
uint8_t* simplification_blocks = PAR_CALLOC(uint8_t, nrows * ncols);
uint32_t* simplification_tris = PAR_CALLOC(uint32_t, nrows * ncols);
uint8_t* simplification_ntris = PAR_CALLOC(uint8_t, nrows * ncols);
// Perform quick-n-dirty simplification by iterating two rows at a time.
// In no way does this create the simplest possible mesh, but at least it's
// fast and easy.
for (uint32_t color = 0; color < (uint32_t) ncolors; color++) {
par_msquares__mesh* mesh = mlist->meshes[color];
// Populate the per-mesh info grids.
int ntris = 0;
for (int row = 0; row < nrows; row++) {
for (int col = 0; col < ncols; col++) {
int cell = ncols * row + col;
uint32_t colors = simplification_words[cell * 2];
uint32_t counts = simplification_words[cell * 2 + 1];
int ncelltris = 0;
int ncorners = 0;
if ((colors & 0xff) == color) {
ncelltris = counts & 0xff;
ncorners++;
}
if (((colors >> 8) & 0xff) == color) {
ncelltris += (counts >> 8) & 0xff;
ncorners++;
}
if (((colors >> 16) & 0xff) == color) {
ncelltris += (counts >> 16) & 0xff;
ncorners++;
}
if (((colors >> 24) & 0xff) == color) {
ncelltris += (counts >> 24) & 0xff;
ncorners++;
}
simplification_ntris[cell] = ncelltris;
simplification_tris[cell] = ntris;
simplification_blocks[cell] = ncorners == 4;
ntris += ncelltris;
}
}
// First figure out how many triangles we can eliminate.
int in_run = 0, start_run;
int neliminated_triangles = 0;
for (int row = 0; row < nrows - 1; row += 2) {
for (int col = 0; col < ncols; col++) {
int cell = ncols * row + col;
int a = simplification_blocks[cell];
int b = simplification_blocks[cell + ncols];
if (a && b) {
if (!in_run) {
in_run = 1;
start_run = col;
}
continue;
}
if (in_run) {
in_run = 0;
int run_width = col - start_run;
neliminated_triangles += run_width * 4 - 2;
}
}
if (in_run) {
in_run = 0;
int run_width = ncols - start_run;
neliminated_triangles += run_width * 4 - 2;
}
}
if (neliminated_triangles == 0) {
continue;
}
// Build a new index array cell-by-cell. If any given cell is 'F' and
// its neighbor to the south is also 'F', then it's part of a run.
int nnewtris = mesh->ntriangles - neliminated_triangles;
PAR_MSQUARES_T* newtris = PAR_CALLOC(PAR_MSQUARES_T, nnewtris * 3);
PAR_MSQUARES_T* pnewtris = newtris;
in_run = 0;
PAR_MSQUARES_T* tris = mesh->triangles;
for (int row = 0; row < nrows - 1; row += 2) {
for (int col = 0; col < ncols; col++) {
int cell = ncols * row + col;
int south = cell + ncols;
int a = simplification_blocks[cell];
int b = simplification_blocks[south];
if (a && b) {
if (!in_run) {
in_run = 1;
start_run = col;
}
continue;
}
if (in_run) {
in_run = 0;
int nw_cell = ncols * row + start_run;
int ne_cell = ncols * row + col - 1;
int sw_cell = nw_cell + ncols;
int se_cell = ne_cell + ncols;
int nw_tri = simplification_tris[nw_cell];
int ne_tri = simplification_tris[ne_cell];
int sw_tri = simplification_tris[sw_cell];
int se_tri = simplification_tris[se_cell];
int nw_corner = nw_tri * 3 + 5;
int ne_corner = ne_tri * 3 + 2;
int sw_corner = sw_tri * 3 + 0;
int se_corner = se_tri * 3 + 1;
*pnewtris++ = tris[nw_corner];
*pnewtris++ = tris[sw_corner];
*pnewtris++ = tris[se_corner];
*pnewtris++ = tris[se_corner];
*pnewtris++ = tris[ne_corner];
*pnewtris++ = tris[nw_corner];
}
int ncelltris = simplification_ntris[cell];
int celltri = simplification_tris[cell];
for (int t = 0; t < ncelltris; t++, celltri++) {
*pnewtris++ = tris[celltri * 3];
*pnewtris++ = tris[celltri * 3 + 1];
*pnewtris++ = tris[celltri * 3 + 2];
}
ncelltris = simplification_ntris[south];
celltri = simplification_tris[south];
for (int t = 0; t < ncelltris; t++, celltri++) {
*pnewtris++ = tris[celltri * 3];
*pnewtris++ = tris[celltri * 3 + 1];
*pnewtris++ = tris[celltri * 3 + 2];
}
}
if (in_run) {
in_run = 0;
int nw_cell = ncols * row + start_run;
int ne_cell = ncols * row + ncols - 1;
int sw_cell = nw_cell + ncols;
int se_cell = ne_cell + ncols;
int nw_tri = simplification_tris[nw_cell];
int ne_tri = simplification_tris[ne_cell];
int sw_tri = simplification_tris[sw_cell];
int se_tri = simplification_tris[se_cell];
int nw_corner = nw_tri * 3 + 5;
int ne_corner = ne_tri * 3 + 2;
int sw_corner = sw_tri * 3 + 0;
int se_corner = se_tri * 3 + 1;
*pnewtris++ = tris[nw_corner];
*pnewtris++ = tris[sw_corner];
*pnewtris++ = tris[se_corner];
*pnewtris++ = tris[se_corner];
*pnewtris++ = tris[ne_corner];
*pnewtris++ = tris[nw_corner];
}
}
mesh->ntriangles -= neliminated_triangles;
free(mesh->triangles);
mesh->triangles = newtris;
}
free(simplification_blocks);
free(simplification_ntris);
free(simplification_tris);
free(simplification_words);
par_msquares__finalize(mlist);
for (int i = 0; i < mlist->nmeshes; i++) {
par_remove_unreferenced_verts(mlist->meshes[i]);
}
return mlist;
}
void par_msquares_free_boundary(par_msquares_boundary* polygon)
{
free(polygon->points);
free(polygon->chains);
free(polygon->lengths);
free(polygon);
}
typedef struct par__hedge_s {
uint32_t key;
struct par__hvert_s* endvert;
struct par__hedge_s* opposite;
struct par__hedge_s* next;
struct par__hedge_s* prev;
} par__hedge;
typedef struct par__hvert_s {
par__hedge* incoming;
} par__hvert;
typedef struct {
par_msquares_mesh const* mesh;
par__hvert* verts;
par__hedge* edges;
par__hedge** sorted_edges;
} par__hemesh;
static int par__hedge_cmp(const void *arg0, const void *arg1)
{
par__hedge* he0 = *((par__hedge**) arg0);
par__hedge* he1 = *((par__hedge**) arg1);
if (he0->key < he1->key) return -1;
if (he0->key > he1->key) return 1;
return 0;
}
static par__hedge* par__hedge_find(par__hemesh* hemesh, uint32_t key)
{
par__hedge target = {0};
target.key = key;
par__hedge* ptarget = ⌖
int nedges = hemesh->mesh->ntriangles * 3;
par__hedge** result = (par__hedge**) bsearch(&ptarget, hemesh->sorted_edges,
nedges, sizeof(par__hedge*), par__hedge_cmp);
return result ? *result : 0;
}
static uint32_t par__hedge_key(par__hvert* a, par__hvert* b, par__hvert* s)
{
uint32_t ai = a - s;
uint32_t bi = b - s;
return (ai << 16) | bi;
}
par_msquares_boundary* par_msquares_extract_boundary(
par_msquares_mesh const* mesh)
{
par_msquares_boundary* result = PAR_CALLOC(par_msquares_boundary, 1);
par__hemesh hemesh = {0};
hemesh.mesh = mesh;
int nedges = mesh->ntriangles * 3;
// Populate all fields of verts and edges, except opposite.
hemesh.edges = PAR_CALLOC(par__hedge, nedges);
par__hvert* hverts = hemesh.verts = PAR_CALLOC(par__hvert, mesh->npoints);
par__hedge* edge = hemesh.edges;
PAR_MSQUARES_T const* tri = mesh->triangles;
for (int n = 0; n < mesh->ntriangles; n++, edge += 3, tri += 3) {
edge[0].endvert = hverts + tri[1];
edge[1].endvert = hverts + tri[2];
edge[2].endvert = hverts + tri[0];
hverts[tri[1]].incoming = edge + 0;
hverts[tri[2]].incoming = edge + 1;
hverts[tri[0]].incoming = edge + 2;
edge[0].next = edge + 1;
edge[1].next = edge + 2;
edge[2].next = edge + 0;
edge[0].prev = edge + 2;
edge[1].prev = edge + 0;
edge[2].prev = edge + 1;
edge[0].key = par__hedge_key(edge[2].endvert, edge[0].endvert, hverts);
edge[1].key = par__hedge_key(edge[0].endvert, edge[1].endvert, hverts);
edge[2].key = par__hedge_key(edge[1].endvert, edge[2].endvert, hverts);
}
// Sort the edges according to their key.
hemesh.sorted_edges = PAR_CALLOC(par__hedge*, mesh->ntriangles * 3);
for (int n = 0; n < nedges; n++) {
hemesh.sorted_edges[n] = hemesh.edges + n;
}
qsort(hemesh.sorted_edges, nedges, sizeof(par__hedge*), par__hedge_cmp);
// Populate the "opposite" field in each edge.
for (int n = 0; n < nedges; n++) {
par__hedge* edge = hemesh.edges + n;
par__hedge* prev = edge->prev;
par__hvert* start = edge->endvert;
par__hvert* end = prev->endvert;
uint32_t key = par__hedge_key(start, end, hverts);
edge->opposite = par__hedge_find(&hemesh, key);
}
// Re-use the sorted_edges array, filling it with boundary edges only.
// Also create a mapping table to consolidate all boundary verts.
int nborders = 0;
for (int n = 0; n < nedges; n++) {
par__hedge* edge = hemesh.edges + n;
if (!edge->opposite) {
hemesh.sorted_edges[nborders++] = edge;
}
}
// Allocate for the worst case (all separate triangles).
// We'll adjust the lengths later.
result->nchains = nborders / 3;
result->npoints = nborders + result->nchains;
result->points = PAR_CALLOC(float, 2 * result->npoints);
result->chains = PAR_CALLOC(float*, result->nchains);
result->lengths = PAR_CALLOC(PAR_MSQUARES_T, result->nchains);
// Iterate over each polyline.
edge = hemesh.sorted_edges[0];
int pt = 0;
int nwritten = 0;
int nchains = 0;
while (1) {
float* points = result->points;
par__hedge* orig = edge;
PAR_MSQUARES_T index = edge->prev->endvert - hverts;
result->chains[nchains] = points + pt;
result->lengths[nchains]++;
points[pt++] = mesh->points[index * mesh->dim];
points[pt++] = mesh->points[index * mesh->dim + 1];
while (1) {
index = edge->endvert - hverts;
edge->key = 0;
nwritten++;
result->lengths[nchains]++;
points[pt++] = mesh->points[index * mesh->dim];
points[pt++] = mesh->points[index * mesh->dim + 1];
par__hedge* next = edge->next;
while (next != edge) {
if (!next->opposite) {
break;
}
next = next->opposite->next;
}
edge = next;
if (edge == orig) {
break;
}
}
nchains++;
if (nwritten >= nborders) {
break;
}
for (int i = 0; i < nborders; i++) {
edge = hemesh.sorted_edges[i];
if (edge->key) {
break;
}
}
}
result->npoints = pt / 2;
result->nchains = nchains;
free(hemesh.verts);
free(hemesh.edges);
free(hemesh.sorted_edges);
return result;
}
#endif // PAR_MSQUARES_IMPLEMENTATION
// par_msquares is distributed under the MIT license:
//
// Copyright (c) 2019 Philip Rideout
//
// 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.
| 37.837059 | 84 | 0.509151 | [
"mesh"
] |
8b18af512fa916d5e4b6dfdc3473d63963d972dd | 301,642 | cpp | C++ | src/linalg/linalg_internal_cpu/Kron_internal.cpp | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 11 | 2020-04-14T15:45:42.000Z | 2022-03-31T14:37:03.000Z | src/linalg/linalg_internal_cpu/Kron_internal.cpp | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 38 | 2019-08-02T15:15:51.000Z | 2022-03-04T19:07:02.000Z | src/linalg/linalg_internal_cpu/Kron_internal.cpp | j9263178/Cytnx | cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b | [
"Apache-2.0"
] | 7 | 2019-07-17T07:50:55.000Z | 2021-07-03T06:44:52.000Z | #include "linalg/linalg_internal_cpu/Kron_internal.hpp"
#include "utils/utils_internal_interface.hpp"
#include "utils/complex_arithmetic.hpp"
//#include "lapack_wrapper.hpp"
#ifdef UNI_OMP
#include <omp.h>
#endif
namespace cytnx{
namespace linalg_internal{
/// Kron
void Kron_internal_cdtcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdtcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdtd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdtf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdtu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdtu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdtu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cdtb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex128 *_Lin = (cytnx_complex128*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_complex128(_Rin[tmp2],0);
}
}
//----------------------------------------
void Kron_internal_cftcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cftcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cftd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cftf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cftu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cftu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cfti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cfti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cfti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cftu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_cftb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_complex64 *_Lin = (cytnx_complex64*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_complex64(_Rin[tmp2],0);
}
}
//-------------------------
void Kron_internal_dtcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dtcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dtd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dtf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dtu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dtu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dtu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_dtb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_double *_Lin = (cytnx_double*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*double(_Rin[tmp2]);
}
}
//-------------------------------
void Kron_internal_ftcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_ftcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_ftd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_ftf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_ftu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_ftu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_fti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_fti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_fti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_ftu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_ftb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_float *_Lin = (cytnx_float*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*float(_Rin[tmp2]);
}
}
//----------------------------------------
void Kron_internal_i64tcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64tcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64td(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64tf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64ti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64tu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64ti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64tu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64ti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64tu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i64tb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int64 *_Lin = (cytnx_int64*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_int64(_Rin[tmp2]);
}
}
//-----------------------------------
void Kron_internal_u64tcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64tcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64td(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64tf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64ti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64tu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64ti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64tu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64ti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64tu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u64tb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint64 *_Lin = (cytnx_uint64*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_uint64(_Rin[tmp2]);
}
}
//-------------------------------------
void Kron_internal_i32tcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32tcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32td(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32tf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32ti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32tu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32ti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32tu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32ti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32tu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i32tb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_int32 *_Lin = (cytnx_int32*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_int32(_Rin[tmp2]);
}
}
//----------------------------------------
void Kron_internal_u32tcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32tcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32td(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32tf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32ti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32tu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32ti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32tu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint32 *_out = (cytnx_uint32*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32ti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint32 *_out = (cytnx_uint32*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32tu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint32 *_out = (cytnx_uint32*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u32tb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint32 *_out = (cytnx_uint32*)out->Mem;
cytnx_uint32 *_Lin = (cytnx_uint32*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_uint32(_Rin[tmp2]);
}
}
//----------------------------------------
void Kron_internal_i16tcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16tcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16td(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16tf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16ti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16tu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16ti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16tu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint32 *_out = (cytnx_uint32*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16ti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int16 *_out = (cytnx_int16*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16tu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int16 *_out = (cytnx_int16*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_i16tb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int16 *_out = (cytnx_int16*)out->Mem;
cytnx_int16 *_Lin = (cytnx_int16*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_int16(_Rin[tmp2]);
}
}
//----------------------------------------
void Kron_internal_u16tcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16tcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16td(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16tf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16ti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16tu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16ti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16tu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint32 *_out = (cytnx_uint32*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16ti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int16 *_out = (cytnx_int16*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16tu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint16 *_out = (cytnx_uint16*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
void Kron_internal_u16tb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint16 *_out = (cytnx_uint16*)out->Mem;
cytnx_uint16 *_Lin = (cytnx_uint16*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*cytnx_uint16(_Rin[tmp2]);
}
}
//----------------------------------------
void Kron_internal_btcd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex128 *_out = (cytnx_complex128*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_complex128 *_Rin = (cytnx_complex128*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_complex128(_Lin[tmp],0)*_Rin[tmp2];
}
}
void Kron_internal_btcf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_complex64 *_out = (cytnx_complex64*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_complex64 *_Rin = (cytnx_complex64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_complex64(_Lin[tmp],0)*_Rin[tmp2];
}
}
void Kron_internal_btd(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_double *_out = (cytnx_double*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_double *_Rin = (cytnx_double*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_double(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_btf(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_float *_out = (cytnx_float*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_float *_Rin = (cytnx_float*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_float(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_bti64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int64 *_out = (cytnx_int64*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_int64 *_Rin = (cytnx_int64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_int64(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_btu64(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint64 *_out = (cytnx_uint64*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_uint64 *_Rin = (cytnx_uint64*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_uint64(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_bti32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int32 *_out = (cytnx_int32*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_int32 *_Rin = (cytnx_int32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_int32(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_btu32(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint32 *_out = (cytnx_uint32*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_uint32 *_Rin = (cytnx_uint32*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_uint32(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_bti16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_int16 *_out = (cytnx_int16*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_int16 *_Rin = (cytnx_int16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_int16(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_btu16(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_uint16 *_out = (cytnx_uint16*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_uint16 *_Rin = (cytnx_uint16*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = cytnx_uint16(_Lin[tmp])*_Rin[tmp2];
}
}
void Kron_internal_btb(boost::intrusive_ptr<Storage_base> & out, const boost::intrusive_ptr<Storage_base> & Lin, const boost::intrusive_ptr<Storage_base> & Rin, const std::vector<cytnx_uint64> &shape1, const std::vector<cytnx_uint64> &shape2){
cytnx_bool *_out = (cytnx_bool*)out->Mem;
cytnx_bool *_Lin = (cytnx_bool*)Lin->Mem;
cytnx_bool *_Rin = (cytnx_bool*)Rin->Mem;
cytnx_error_msg(shape1.size()!=shape2.size(),"[ERROR][Internal Kron] T1 rank != T2 rank %s","\n");
cytnx_uint64 TotalElem = shape1[0]*shape2[0];
std::vector<cytnx_uint64> new_shape_acc(shape1.size());
std::vector<cytnx_uint64> shape1_acc(shape1.size());
std::vector<cytnx_uint64> shape2_acc(shape1.size());
new_shape_acc.back() = 1;
shape1_acc.back() = 1;
shape2_acc.back() = 1;
for(unsigned long long i=1;i<new_shape_acc.size();i++){
new_shape_acc[new_shape_acc.size()-1-i] = new_shape_acc[new_shape_acc.size()-i]*shape1[new_shape_acc.size()-i]*shape2[new_shape_acc.size()-i];
TotalElem*=shape1[i]*shape2[i];
shape1_acc[shape1_acc.size()-1-i] = shape1_acc[shape1_acc.size()-i]*shape1[shape1_acc.size()-i];
shape2_acc[shape2_acc.size()-1-i] = shape2_acc[shape2_acc.size()-i]*shape2[shape2_acc.size()-i];
}
#ifdef UNI_OMP
#pragma omp parallel for schedule(dynamic)
#endif
for(unsigned long long i=0;i<TotalElem;i++){
std::vector<cytnx_uint64> idd;
cytnx_uint64 tmp = i;
cytnx_uint64 tmp2;
for(unsigned long long j=0;j<new_shape_acc.size();j++)
{
idd.push_back(tmp/new_shape_acc[j]);
tmp= tmp%new_shape_acc[j];
}
//using idd to calculate add of Lin and Rin
tmp = tmp2 = 0;
for(unsigned long long j=0;j<new_shape_acc.size();j++){
tmp += cytnx_uint64(idd[j]/shape2[j])*shape1_acc[j];
tmp2 += cytnx_uint64(idd[j]%shape2[j])*shape2_acc[j];
}
_out[i] = _Lin[tmp]*_Rin[tmp2];
}
}
}//namespace linalg_internal
}//namespace cytnx
| 52.532567 | 255 | 0.522507 | [
"vector"
] |
8b19d78af99f7c3f10c041034249497361cc83e4 | 1,845 | cpp | C++ | src/ObjectUtils/SymbolsFile.cpp | dpallotti/orbitprofiler | 11af85c0c9f5e7feb2916bb5e22977b59a792d64 | [
"BSD-2-Clause"
] | 1 | 2021-12-26T06:43:40.000Z | 2021-12-26T06:43:40.000Z | src/ObjectUtils/SymbolsFile.cpp | dpallotti/orbitprofiler | 11af85c0c9f5e7feb2916bb5e22977b59a792d64 | [
"BSD-2-Clause"
] | null | null | null | src/ObjectUtils/SymbolsFile.cpp | dpallotti/orbitprofiler | 11af85c0c9f5e7feb2916bb5e22977b59a792d64 | [
"BSD-2-Clause"
] | 1 | 2021-03-10T15:21:19.000Z | 2021-03-10T15:21:19.000Z | // Copyright (c) 2021 The Orbit 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 "ObjectUtils/SymbolsFile.h"
#include <absl/strings/str_format.h>
#include <filesystem>
#include <memory>
#include <string>
#include "ObjectUtils/ObjectFile.h"
#include "ObjectUtils/PdbFile.h"
#include "OrbitBase/File.h"
#include "OrbitBase/Result.h"
namespace orbit_object_utils {
ErrorMessageOr<std::unique_ptr<SymbolsFile>> CreateSymbolsFile(
const std::filesystem::path& file_path) {
std::string error_message{
absl::StrFormat("Unable to create symbols file from \"%s\".", file_path.string())};
OUTCOME_TRY(auto file_exists, orbit_base::FileExists(file_path));
if (!file_exists) {
error_message.append("\n* File does not exist.");
return ErrorMessage{error_message};
}
ErrorMessageOr<std::unique_ptr<ObjectFile>> object_file_or_error = CreateObjectFile(file_path);
if (object_file_or_error.has_value()) {
if (object_file_or_error.value()->HasDebugSymbols()) {
return std::move(object_file_or_error.value());
}
error_message.append("\n* File does not contain symbols.");
return ErrorMessage{error_message};
}
error_message.append(absl::StrFormat("\n* File cannot be read as an object file, error: %s",
object_file_or_error.error().message()));
ErrorMessageOr<std::unique_ptr<PdbFile>> pdb_file_or_error = CreatePdbFile(file_path);
if (pdb_file_or_error.has_value()) return std::move(pdb_file_or_error.value());
error_message.append(absl::StrFormat("\n* File cannot be read as a pdb file, error: %s",
pdb_file_or_error.error().message()));
return ErrorMessage{error_message};
}
} // namespace orbit_object_utils | 34.166667 | 97 | 0.710027 | [
"object"
] |
8b1b79875fd486033e751291367670ebfb0d7c73 | 4,218 | cpp | C++ | Examples/Examples/BusinessObject.cpp | BartoszKlonowski/CxVector | e0222e31daef8bb506f9407030de68adaf1345c7 | [
"MIT"
] | 4 | 2021-04-18T14:29:54.000Z | 2021-07-06T18:18:47.000Z | Examples/Examples/BusinessObject.cpp | BartoszKlonowski/CxVector | e0222e31daef8bb506f9407030de68adaf1345c7 | [
"MIT"
] | 8 | 2021-02-17T00:01:38.000Z | 2021-03-12T19:27:32.000Z | Examples/Examples/BusinessObject.cpp | BartoszKlonowski/SharpVector | e0222e31daef8bb506f9407030de68adaf1345c7 | [
"MIT"
] | null | null | null | // Copyright (c) Cx Code - Bartosz Klonowski.
// Licensed under the MIT License.
#include "../ErrorCodes.hpp"
#include "../../Source/Vector.hpp"
#include <string>
namespace Examples
{
class Part
{
public:
std::string partName;
int partID;
Part( std::string partName, int partID ) : partName{ partName }, partID{ partID }
{
}
std::string ToString()
{
return std::string( "ID: " ).append( std::to_string( partID ) ).append( " Name: " ).append( partName );
}
bool operator==( const Part& other ) const
{
return partID == other.partID;
}
};
class BusinessObjectExample
{
public:
ErrorCodes Run()
{
// Create a list of parts.
Cx::Vector<Part> parts;
// Add parts to the list.
parts.push_back( Part( "crank arm", 1234 ) );
parts.push_back( Part( "chain ring", 1334 ) );
parts.push_back( Part( "regular seat", 1434 ) );
parts.push_back( Part( "banana seat", 1444 ) );
parts.push_back( Part( "cassette", 1534 ) );
parts.push_back( Part( "shift lever", 1634 ) );
// Write out the parts in the list. This will call the overridden ToString method in the Part class.
parts.ForEach( []( Part p )
{
std::cout << p.ToString() << std::endl;
} );
// Check the list for part #1734. This calls the IEquatable.Equals method of the Part class, which checks the PartId for equality.
std::cout << "\nContains(\"1734\"): {" << parts.Contains( Part( "", 1734 ) ) << "}" << std::endl;
// Insert a new item at position 2.
std::cout << "\nInsert(2, \"1834\")" << std::endl;
parts.insert( parts.cbegin() + 2, Part( "brake lever", 1834 ) );
parts.ForEach( []( Part p )
{
std::cout << p.ToString() << std::endl;
} );
std::cout << "\nParts[3]: {" << parts[3].ToString() << "{" << std::endl;
std::cout << "\nRemove(\"1534\")" << std::endl;
// This will remove part 1534 even though the PartName is different, because the Equals method only checks PartId for equality.
parts.Remove( Part( "cogs", 1534 ) );
parts.ForEach( []( Part p )
{
std::cout << p.ToString() << std::endl;
} );
std::cout << "\nRemoveAt(3)" << std::endl;
// This will remove the part at index 3.
parts.RemoveAt( 3 );
parts.ForEach( []( Part p )
{
std::cout << p.ToString() << std::endl;
} );
/*
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1534 Name: cassette
ID: 1634 Name: shift lever
Contains("1734"): False
Insert(2, "1834")
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1534 Name: cassette
ID: 1634 Name: shift lever
Parts[3]: ID: 1434 Name: regular seat
Remove("1534")
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1634 Name: shift lever
RemoveAt(3)
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1444 Name: banana seat
ID: 1634 Name: shift lever
*/
return ErrorCodes::Success;
}
};
}
| 32.446154 | 143 | 0.461593 | [
"vector"
] |
8b1bba7f036cb0d2580a30f75b42c08ede8d5bab | 812 | cpp | C++ | 570A - Elections/17709407_31MS_2200K.cpp | cloudzfy/codeforces | d409574c1a4218419aa6e9ddc02fddb7b83455d8 | [
"MIT"
] | 1 | 2016-04-30T02:57:49.000Z | 2016-04-30T02:57:49.000Z | 570A - Elections/17709407_31MS_2200K.cpp | cloudzfy/codeforces | d409574c1a4218419aa6e9ddc02fddb7b83455d8 | [
"MIT"
] | null | null | null | 570A - Elections/17709407_31MS_2200K.cpp | cloudzfy/codeforces | d409574c1a4218419aa6e9ddc02fddb7b83455d8 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cstring>
#include <algorithm>
#include <map>
#include <stack>
using namespace std;
int main(int argc, const char * argv[]) {
int n, m, a;
cin>>n>>m;
vector<int> count(n, 0);
for (int i = 0; i < m; i++) {
int maxVotes = INT_MIN, idx = -1;
for (int j = 0; j < n; j++) {
cin>>a;
if (a > maxVotes) {
maxVotes = a;
idx = j;
}
}
count[idx]++;
}
int maxVotes = INT_MIN, idx = -1;
for (int i = 0; i < n; i++) {
if (count[i] > maxVotes) {
maxVotes = count[i];
idx = i;
}
}
cout<<idx + 1<<endl;
return 0;
} | 21.945946 | 41 | 0.471675 | [
"vector"
] |
8b1d05d252de9f3236ff31dd6571ac582ee42abf | 46,118 | cpp | C++ | llvm/lib/CodeGen/MachineFunction.cpp | nihaals/llvm-project | 3e45bb9829231b3fd185447a62c9505ba68a74e2 | [
"Apache-2.0"
] | null | null | null | llvm/lib/CodeGen/MachineFunction.cpp | nihaals/llvm-project | 3e45bb9829231b3fd185447a62c9505ba68a74e2 | [
"Apache-2.0"
] | null | null | null | llvm/lib/CodeGen/MachineFunction.cpp | nihaals/llvm-project | 3e45bb9829231b3fd185447a62c9505ba68a74e2 | [
"Apache-2.0"
] | null | null | null | //===- MachineFunction.cpp ------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Collect native machine code information for a function. This allows
// target-specific information about the generated code to be stored with each
// function.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/CodeGen/WasmEHFuncInfo.h"
#include "llvm/CodeGen/WinEHFuncInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSlotTracker.h"
#include "llvm/IR/Value.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DOTGraphTraits.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "codegen"
static cl::opt<unsigned> AlignAllFunctions(
"align-all-functions",
cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
"means align on 16B boundaries)."),
cl::init(0), cl::Hidden);
static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
using P = MachineFunctionProperties::Property;
switch(Prop) {
case P::FailedISel: return "FailedISel";
case P::IsSSA: return "IsSSA";
case P::Legalized: return "Legalized";
case P::NoPHIs: return "NoPHIs";
case P::NoVRegs: return "NoVRegs";
case P::RegBankSelected: return "RegBankSelected";
case P::Selected: return "Selected";
case P::TracksLiveness: return "TracksLiveness";
case P::TiedOpsRewritten: return "TiedOpsRewritten";
}
llvm_unreachable("Invalid machine function property");
}
// Pin the vtable to this file.
void MachineFunction::Delegate::anchor() {}
void MachineFunctionProperties::print(raw_ostream &OS) const {
const char *Separator = "";
for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
if (!Properties[I])
continue;
OS << Separator << getPropertyName(static_cast<Property>(I));
Separator = ", ";
}
}
//===----------------------------------------------------------------------===//
// MachineFunction implementation
//===----------------------------------------------------------------------===//
// Out-of-line virtual method.
MachineFunctionInfo::~MachineFunctionInfo() = default;
void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
MBB->getParent()->DeleteMachineBasicBlock(MBB);
}
static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
const Function &F) {
if (F.hasFnAttribute(Attribute::StackAlignment))
return F.getFnStackAlignment();
return STI->getFrameLowering()->getStackAlign().value();
}
MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
const TargetSubtargetInfo &STI,
unsigned FunctionNum, MachineModuleInfo &mmi)
: F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
FunctionNumber = FunctionNum;
init();
}
void MachineFunction::handleInsertion(MachineInstr &MI) {
if (TheDelegate)
TheDelegate->MF_HandleInsertion(MI);
}
void MachineFunction::handleRemoval(MachineInstr &MI) {
if (TheDelegate)
TheDelegate->MF_HandleRemoval(MI);
}
void MachineFunction::init() {
// Assume the function starts in SSA form with correct liveness.
Properties.set(MachineFunctionProperties::Property::IsSSA);
Properties.set(MachineFunctionProperties::Property::TracksLiveness);
if (STI->getRegisterInfo())
RegInfo = new (Allocator) MachineRegisterInfo(this);
else
RegInfo = nullptr;
MFInfo = nullptr;
// We can realign the stack if the target supports it and the user hasn't
// explicitly asked us not to.
bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
!F.hasFnAttribute("no-realign-stack");
FrameInfo = new (Allocator) MachineFrameInfo(
getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
/*ForcedRealign=*/CanRealignSP &&
F.hasFnAttribute(Attribute::StackAlignment));
if (F.hasFnAttribute(Attribute::StackAlignment))
FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
// FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
// FIXME: Use Function::hasOptSize().
if (!F.hasFnAttribute(Attribute::OptimizeForSize))
Alignment = std::max(Alignment,
STI->getTargetLowering()->getPrefFunctionAlignment());
if (AlignAllFunctions)
Alignment = Align(1ULL << AlignAllFunctions);
JumpTableInfo = nullptr;
if (isFuncletEHPersonality(classifyEHPersonality(
F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
WinEHInfo = new (Allocator) WinEHFuncInfo();
}
if (isScopedEHPersonality(classifyEHPersonality(
F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
WasmEHInfo = new (Allocator) WasmEHFuncInfo();
}
assert(Target.isCompatibleDataLayout(getDataLayout()) &&
"Can't create a MachineFunction using a Module with a "
"Target-incompatible DataLayout attached\n");
PSVManager =
std::make_unique<PseudoSourceValueManager>(*(getSubtarget().
getInstrInfo()));
}
MachineFunction::~MachineFunction() {
clear();
}
void MachineFunction::clear() {
Properties.reset();
// Don't call destructors on MachineInstr and MachineOperand. All of their
// memory comes from the BumpPtrAllocator which is about to be purged.
//
// Do call MachineBasicBlock destructors, it contains std::vectors.
for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
I->Insts.clearAndLeakNodesUnsafely();
MBBNumbering.clear();
InstructionRecycler.clear(Allocator);
OperandRecycler.clear(Allocator);
BasicBlockRecycler.clear(Allocator);
CodeViewAnnotations.clear();
VariableDbgInfos.clear();
if (RegInfo) {
RegInfo->~MachineRegisterInfo();
Allocator.Deallocate(RegInfo);
}
if (MFInfo) {
MFInfo->~MachineFunctionInfo();
Allocator.Deallocate(MFInfo);
}
FrameInfo->~MachineFrameInfo();
Allocator.Deallocate(FrameInfo);
ConstantPool->~MachineConstantPool();
Allocator.Deallocate(ConstantPool);
if (JumpTableInfo) {
JumpTableInfo->~MachineJumpTableInfo();
Allocator.Deallocate(JumpTableInfo);
}
if (WinEHInfo) {
WinEHInfo->~WinEHFuncInfo();
Allocator.Deallocate(WinEHInfo);
}
if (WasmEHInfo) {
WasmEHInfo->~WasmEHFuncInfo();
Allocator.Deallocate(WasmEHInfo);
}
}
const DataLayout &MachineFunction::getDataLayout() const {
return F.getParent()->getDataLayout();
}
/// Get the JumpTableInfo for this function.
/// If it does not already exist, allocate one.
MachineJumpTableInfo *MachineFunction::
getOrCreateJumpTableInfo(unsigned EntryKind) {
if (JumpTableInfo) return JumpTableInfo;
JumpTableInfo = new (Allocator)
MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
return JumpTableInfo;
}
DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
return F.getDenormalMode(FPType);
}
/// Should we be emitting segmented stack stuff for the function
bool MachineFunction::shouldSplitStack() const {
return getFunction().hasFnAttribute("split-stack");
}
LLVM_NODISCARD unsigned
MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
FrameInstructions.push_back(Inst);
return FrameInstructions.size() - 1;
}
/// This discards all of the MachineBasicBlock numbers and recomputes them.
/// This guarantees that the MBB numbers are sequential, dense, and match the
/// ordering of the blocks within the function. If a specific MachineBasicBlock
/// is specified, only that block and those after it are renumbered.
void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
if (empty()) { MBBNumbering.clear(); return; }
MachineFunction::iterator MBBI, E = end();
if (MBB == nullptr)
MBBI = begin();
else
MBBI = MBB->getIterator();
// Figure out the block number this should have.
unsigned BlockNo = 0;
if (MBBI != begin())
BlockNo = std::prev(MBBI)->getNumber() + 1;
for (; MBBI != E; ++MBBI, ++BlockNo) {
if (MBBI->getNumber() != (int)BlockNo) {
// Remove use of the old number.
if (MBBI->getNumber() != -1) {
assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
"MBB number mismatch!");
MBBNumbering[MBBI->getNumber()] = nullptr;
}
// If BlockNo is already taken, set that block's number to -1.
if (MBBNumbering[BlockNo])
MBBNumbering[BlockNo]->setNumber(-1);
MBBNumbering[BlockNo] = &*MBBI;
MBBI->setNumber(BlockNo);
}
}
// Okay, all the blocks are renumbered. If we have compactified the block
// numbering, shrink MBBNumbering now.
assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
MBBNumbering.resize(BlockNo);
}
/// This method iterates over the basic blocks and assigns their IsBeginSection
/// and IsEndSection fields. This must be called after MBB layout is finalized
/// and the SectionID's are assigned to MBBs.
void MachineFunction::assignBeginEndSections() {
front().setIsBeginSection();
auto CurrentSectionID = front().getSectionID();
for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
if (MBBI->getSectionID() == CurrentSectionID)
continue;
MBBI->setIsBeginSection();
std::prev(MBBI)->setIsEndSection();
CurrentSectionID = MBBI->getSectionID();
}
back().setIsEndSection();
}
/// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
const DebugLoc &DL,
bool NoImplicit) {
return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
MachineInstr(*this, MCID, DL, NoImplicit);
}
/// Create a new MachineInstr which is a copy of the 'Orig' instruction,
/// identical in all ways except the instruction has no parent, prev, or next.
MachineInstr *
MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
MachineInstr(*this, *Orig);
}
MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
MachineInstr *FirstClone = nullptr;
MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
while (true) {
MachineInstr *Cloned = CloneMachineInstr(&*I);
MBB.insert(InsertBefore, Cloned);
if (FirstClone == nullptr) {
FirstClone = Cloned;
} else {
Cloned->bundleWithPred();
}
if (!I->isBundledWithSucc())
break;
++I;
}
// Copy over call site info to the cloned instruction if needed. If Orig is in
// a bundle, copyCallSiteInfo takes care of finding the call instruction in
// the bundle.
if (Orig.shouldUpdateCallSiteInfo())
copyCallSiteInfo(&Orig, FirstClone);
return *FirstClone;
}
/// Delete the given MachineInstr.
///
/// This function also serves as the MachineInstr destructor - the real
/// ~MachineInstr() destructor must be empty.
void
MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
// Verify that a call site info is at valid state. This assertion should
// be triggered during the implementation of support for the
// call site info of a new architecture. If the assertion is triggered,
// back trace will tell where to insert a call to updateCallSiteInfo().
assert((!MI->isCandidateForCallSiteEntry() ||
CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
"Call site info was not updated!");
// Strip it for parts. The operand array and the MI object itself are
// independently recyclable.
if (MI->Operands)
deallocateOperandArray(MI->CapOperands, MI->Operands);
// Don't call ~MachineInstr() which must be trivial anyway because
// ~MachineFunction drops whole lists of MachineInstrs wihout calling their
// destructors.
InstructionRecycler.Deallocate(Allocator, MI);
}
/// Allocate a new MachineBasicBlock. Use this instead of
/// `new MachineBasicBlock'.
MachineBasicBlock *
MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
MachineBasicBlock(*this, bb);
}
/// Delete the given MachineBasicBlock.
void
MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
assert(MBB->getParent() == this && "MBB parent mismatch!");
// Clean up any references to MBB in jump tables before deleting it.
if (JumpTableInfo)
JumpTableInfo->RemoveMBBFromJumpTables(MBB);
MBB->~MachineBasicBlock();
BasicBlockRecycler.Deallocate(Allocator, MBB);
}
MachineMemOperand *MachineFunction::getMachineMemOperand(
MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
SyncScope::ID SSID, AtomicOrdering Ordering,
AtomicOrdering FailureOrdering) {
return new (Allocator)
MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
SSID, Ordering, FailureOrdering);
}
MachineMemOperand *MachineFunction::getMachineMemOperand(
MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
SyncScope::ID SSID, AtomicOrdering Ordering,
AtomicOrdering FailureOrdering) {
return new (Allocator)
MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
Ordering, FailureOrdering);
}
MachineMemOperand *MachineFunction::getMachineMemOperand(
const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
return new (Allocator)
MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
AAMDNodes(), nullptr, MMO->getSyncScopeID(),
MMO->getSuccessOrdering(), MMO->getFailureOrdering());
}
MachineMemOperand *MachineFunction::getMachineMemOperand(
const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
return new (Allocator)
MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
AAMDNodes(), nullptr, MMO->getSyncScopeID(),
MMO->getSuccessOrdering(), MMO->getFailureOrdering());
}
MachineMemOperand *
MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
int64_t Offset, LLT Ty) {
const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
// If there is no pointer value, the offset isn't tracked so we need to adjust
// the base alignment.
Align Alignment = PtrInfo.V.isNull()
? commonAlignment(MMO->getBaseAlign(), Offset)
: MMO->getBaseAlign();
// Do not preserve ranges, since we don't necessarily know what the high bits
// are anymore.
return new (Allocator) MachineMemOperand(
PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
MMO->getSuccessOrdering(), MMO->getFailureOrdering());
}
MachineMemOperand *
MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
const AAMDNodes &AAInfo) {
MachinePointerInfo MPI = MMO->getValue() ?
MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
return new (Allocator) MachineMemOperand(
MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
MMO->getFailureOrdering());
}
MachineMemOperand *
MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
MachineMemOperand::Flags Flags) {
return new (Allocator) MachineMemOperand(
MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
MMO->getSuccessOrdering(), MMO->getFailureOrdering());
}
MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) {
return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
PostInstrSymbol, HeapAllocMarker);
}
const char *MachineFunction::createExternalSymbolName(StringRef Name) {
char *Dest = Allocator.Allocate<char>(Name.size() + 1);
llvm::copy(Name, Dest);
Dest[Name.size()] = 0;
return Dest;
}
uint32_t *MachineFunction::allocateRegMask() {
unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
memset(Mask, 0, Size * sizeof(Mask[0]));
return Mask;
}
ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
int* AllocMask = Allocator.Allocate<int>(Mask.size());
copy(Mask, AllocMask);
return {AllocMask, Mask.size()};
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void MachineFunction::dump() const {
print(dbgs());
}
#endif
StringRef MachineFunction::getName() const {
return getFunction().getName();
}
void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
OS << "# Machine code for function " << getName() << ": ";
getProperties().print(OS);
OS << '\n';
// Print Frame Information
FrameInfo->print(*this, OS);
// Print JumpTable Information
if (JumpTableInfo)
JumpTableInfo->print(OS);
// Print Constant Pool
ConstantPool->print(OS);
const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
if (RegInfo && !RegInfo->livein_empty()) {
OS << "Function Live Ins: ";
for (MachineRegisterInfo::livein_iterator
I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
OS << printReg(I->first, TRI);
if (I->second)
OS << " in " << printReg(I->second, TRI);
if (std::next(I) != E)
OS << ", ";
}
OS << '\n';
}
ModuleSlotTracker MST(getFunction().getParent());
MST.incorporateFunction(getFunction());
for (const auto &BB : *this) {
OS << '\n';
// If we print the whole function, print it at its most verbose level.
BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
}
OS << "\n# End machine code for function " << getName() << ".\n\n";
}
/// True if this function needs frame moves for debug or exceptions.
bool MachineFunction::needsFrameMoves() const {
return getMMI().hasDebugInfo() ||
getTarget().Options.ForceDwarfFrameSection ||
F.needsUnwindTableEntry();
}
namespace llvm {
template<>
struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
static std::string getGraphName(const MachineFunction *F) {
return ("CFG for '" + F->getName() + "' function").str();
}
std::string getNodeLabel(const MachineBasicBlock *Node,
const MachineFunction *Graph) {
std::string OutStr;
{
raw_string_ostream OSS(OutStr);
if (isSimple()) {
OSS << printMBBReference(*Node);
if (const BasicBlock *BB = Node->getBasicBlock())
OSS << ": " << BB->getName();
} else
Node->print(OSS);
}
if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
// Process string output to make it nicer...
for (unsigned i = 0; i != OutStr.length(); ++i)
if (OutStr[i] == '\n') { // Left justify
OutStr[i] = '\\';
OutStr.insert(OutStr.begin()+i+1, 'l');
}
return OutStr;
}
};
} // end namespace llvm
void MachineFunction::viewCFG() const
{
#ifndef NDEBUG
ViewGraph(this, "mf" + getName());
#else
errs() << "MachineFunction::viewCFG is only available in debug builds on "
<< "systems with Graphviz or gv!\n";
#endif // NDEBUG
}
void MachineFunction::viewCFGOnly() const
{
#ifndef NDEBUG
ViewGraph(this, "mf" + getName(), true);
#else
errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
<< "systems with Graphviz or gv!\n";
#endif // NDEBUG
}
/// Add the specified physical register as a live-in value and
/// create a corresponding virtual register for it.
Register MachineFunction::addLiveIn(MCRegister PReg,
const TargetRegisterClass *RC) {
MachineRegisterInfo &MRI = getRegInfo();
Register VReg = MRI.getLiveInVirtReg(PReg);
if (VReg) {
const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
(void)VRegRC;
// A physical register can be added several times.
// Between two calls, the register class of the related virtual register
// may have been constrained to match some operation constraints.
// In that case, check that the current register class includes the
// physical register and is a sub class of the specified RC.
assert((VRegRC == RC || (VRegRC->contains(PReg) &&
RC->hasSubClassEq(VRegRC))) &&
"Register class mismatch!");
return VReg;
}
VReg = MRI.createVirtualRegister(RC);
MRI.addLiveIn(PReg, VReg);
return VReg;
}
/// Return the MCSymbol for the specified non-empty jump table.
/// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
/// normal 'L' label is returned.
MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
bool isLinkerPrivate) const {
const DataLayout &DL = getDataLayout();
assert(JumpTableInfo && "No jump tables");
assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
: DL.getPrivateGlobalPrefix();
SmallString<60> Name;
raw_svector_ostream(Name)
<< Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
return Ctx.getOrCreateSymbol(Name);
}
/// Return a function-local symbol to represent the PIC base.
MCSymbol *MachineFunction::getPICBaseSymbol() const {
const DataLayout &DL = getDataLayout();
return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
Twine(getFunctionNumber()) + "$pb");
}
/// \name Exception Handling
/// \{
LandingPadInfo &
MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
unsigned N = LandingPads.size();
for (unsigned i = 0; i < N; ++i) {
LandingPadInfo &LP = LandingPads[i];
if (LP.LandingPadBlock == LandingPad)
return LP;
}
LandingPads.push_back(LandingPadInfo(LandingPad));
return LandingPads[N];
}
void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
MCSymbol *BeginLabel, MCSymbol *EndLabel) {
LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
LP.BeginLabels.push_back(BeginLabel);
LP.EndLabels.push_back(EndLabel);
}
MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
LP.LandingPadLabel = LandingPadLabel;
const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
if (const auto *PF =
dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
getMMI().addPersonality(PF);
if (LPI->isCleanup())
addCleanup(LandingPad);
// FIXME: New EH - Add the clauses in reverse order. This isn't 100%
// correct, but we need to do it this way because of how the DWARF EH
// emitter processes the clauses.
for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
Value *Val = LPI->getClause(I - 1);
if (LPI->isCatch(I - 1)) {
addCatchTypeInfo(LandingPad,
dyn_cast<GlobalValue>(Val->stripPointerCasts()));
} else {
// Add filters in a list.
auto *CVal = cast<Constant>(Val);
SmallVector<const GlobalValue *, 4> FilterList;
for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
II != IE; ++II)
FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
addFilterTypeInfo(LandingPad, FilterList);
}
}
} else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
}
} else {
assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
}
return LandingPadLabel;
}
void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
ArrayRef<const GlobalValue *> TyInfo) {
LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
for (unsigned N = TyInfo.size(); N; --N)
LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
}
void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
ArrayRef<const GlobalValue *> TyInfo) {
LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
std::vector<unsigned> IdsInFilter(TyInfo.size());
for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
}
void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
bool TidyIfNoBeginLabels) {
for (unsigned i = 0; i != LandingPads.size(); ) {
LandingPadInfo &LandingPad = LandingPads[i];
if (LandingPad.LandingPadLabel &&
!LandingPad.LandingPadLabel->isDefined() &&
(!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
LandingPad.LandingPadLabel = nullptr;
// Special case: we *should* emit LPs with null LP MBB. This indicates
// "nounwind" case.
if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
LandingPads.erase(LandingPads.begin() + i);
continue;
}
if (TidyIfNoBeginLabels) {
for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
MCSymbol *EndLabel = LandingPad.EndLabels[j];
if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
(EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
continue;
LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
--j;
--e;
}
// Remove landing pads with no try-ranges.
if (LandingPads[i].BeginLabels.empty()) {
LandingPads.erase(LandingPads.begin() + i);
continue;
}
}
// If there is no landing pad, ensure that the list of typeids is empty.
// If the only typeid is a cleanup, this is the same as having no typeids.
if (!LandingPad.LandingPadBlock ||
(LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
LandingPad.TypeIds.clear();
++i;
}
}
void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
LP.TypeIds.push_back(0);
}
void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
const Function *Filter,
const BlockAddress *RecoverBA) {
LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
SEHHandler Handler;
Handler.FilterOrFinally = Filter;
Handler.RecoverBA = RecoverBA;
LP.SEHHandlers.push_back(Handler);
}
void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
const Function *Cleanup) {
LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
SEHHandler Handler;
Handler.FilterOrFinally = Cleanup;
Handler.RecoverBA = nullptr;
LP.SEHHandlers.push_back(Handler);
}
void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
ArrayRef<unsigned> Sites) {
LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
}
unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
if (TypeInfos[i] == TI) return i + 1;
TypeInfos.push_back(TI);
return TypeInfos.size();
}
int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
// If the new filter coincides with the tail of an existing filter, then
// re-use the existing filter. Folding filters more than this requires
// re-ordering filters and/or their elements - probably not worth it.
for (unsigned i : FilterEnds) {
unsigned j = TyIds.size();
while (i && j)
if (FilterIds[--i] != TyIds[--j])
goto try_next;
if (!j)
// The new filter coincides with range [i, end) of the existing filter.
return -(1 + i);
try_next:;
}
// Add the new filter.
int FilterID = -(1 + FilterIds.size());
FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
llvm::append_range(FilterIds, TyIds);
FilterEnds.push_back(FilterIds.size());
FilterIds.push_back(0); // terminator
return FilterID;
}
MachineFunction::CallSiteInfoMap::iterator
MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
assert(MI->isCandidateForCallSiteEntry() &&
"Call site info refers only to call (MI) candidates");
if (!Target.Options.EmitCallSiteInfo)
return CallSitesInfo.end();
return CallSitesInfo.find(MI);
}
/// Return the call machine instruction or find a call within bundle.
static const MachineInstr *getCallInstr(const MachineInstr *MI) {
if (!MI->isBundle())
return MI;
for (auto &BMI : make_range(getBundleStart(MI->getIterator()),
getBundleEnd(MI->getIterator())))
if (BMI.isCandidateForCallSiteEntry())
return &BMI;
llvm_unreachable("Unexpected bundle without a call site candidate");
}
void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
assert(MI->shouldUpdateCallSiteInfo() &&
"Call site info refers only to call (MI) candidates or "
"candidates inside bundles");
const MachineInstr *CallMI = getCallInstr(MI);
CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
if (CSIt == CallSitesInfo.end())
return;
CallSitesInfo.erase(CSIt);
}
void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
const MachineInstr *New) {
assert(Old->shouldUpdateCallSiteInfo() &&
"Call site info refers only to call (MI) candidates or "
"candidates inside bundles");
if (!New->isCandidateForCallSiteEntry())
return eraseCallSiteInfo(Old);
const MachineInstr *OldCallMI = getCallInstr(Old);
CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
if (CSIt == CallSitesInfo.end())
return;
CallSiteInfo CSInfo = CSIt->second;
CallSitesInfo[New] = CSInfo;
}
void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
const MachineInstr *New) {
assert(Old->shouldUpdateCallSiteInfo() &&
"Call site info refers only to call (MI) candidates or "
"candidates inside bundles");
if (!New->isCandidateForCallSiteEntry())
return eraseCallSiteInfo(Old);
const MachineInstr *OldCallMI = getCallInstr(Old);
CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
if (CSIt == CallSitesInfo.end())
return;
CallSiteInfo CSInfo = std::move(CSIt->second);
CallSitesInfo.erase(CSIt);
CallSitesInfo[New] = CSInfo;
}
void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
DebugInstrNumberingCount = Num;
}
void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
DebugInstrOperandPair B,
unsigned Subreg) {
// Catch any accidental self-loops.
assert(A.first != B.first);
auto Result = DebugValueSubstitutions.insert({A, {B, Subreg}});
(void)Result;
assert(Result.second && "Substitution for an already substituted value?");
}
void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
MachineInstr &New,
unsigned MaxOperand) {
// If the Old instruction wasn't tracked at all, there is no work to do.
unsigned OldInstrNum = Old.peekDebugInstrNum();
if (!OldInstrNum)
return;
// Iterate over all operands looking for defs to create substitutions for.
// Avoid creating new instr numbers unless we create a new substitution.
// While this has no functional effect, it risks confusing someone reading
// MIR output.
// Examine all the operands, or the first N specified by the caller.
MaxOperand = std::min(MaxOperand, Old.getNumOperands());
for (unsigned int I = 0; I < Old.getNumOperands(); ++I) {
const auto &OldMO = Old.getOperand(I);
auto &NewMO = New.getOperand(I);
(void)NewMO;
if (!OldMO.isReg() || !OldMO.isDef())
continue;
assert(NewMO.isDef());
unsigned NewInstrNum = New.getDebugInstrNum();
makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
std::make_pair(NewInstrNum, I));
}
}
/// \}
//===----------------------------------------------------------------------===//
// MachineJumpTableInfo implementation
//===----------------------------------------------------------------------===//
/// Return the size of each entry in the jump table.
unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
// The size of a jump table entry is 4 bytes unless the entry is just the
// address of a block, in which case it is the pointer size.
switch (getEntryKind()) {
case MachineJumpTableInfo::EK_BlockAddress:
return TD.getPointerSize();
case MachineJumpTableInfo::EK_GPRel64BlockAddress:
return 8;
case MachineJumpTableInfo::EK_GPRel32BlockAddress:
case MachineJumpTableInfo::EK_LabelDifference32:
case MachineJumpTableInfo::EK_Custom32:
return 4;
case MachineJumpTableInfo::EK_Inline:
return 0;
}
llvm_unreachable("Unknown jump table encoding!");
}
/// Return the alignment of each entry in the jump table.
unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
// The alignment of a jump table entry is the alignment of int32 unless the
// entry is just the address of a block, in which case it is the pointer
// alignment.
switch (getEntryKind()) {
case MachineJumpTableInfo::EK_BlockAddress:
return TD.getPointerABIAlignment(0).value();
case MachineJumpTableInfo::EK_GPRel64BlockAddress:
return TD.getABIIntegerTypeAlignment(64).value();
case MachineJumpTableInfo::EK_GPRel32BlockAddress:
case MachineJumpTableInfo::EK_LabelDifference32:
case MachineJumpTableInfo::EK_Custom32:
return TD.getABIIntegerTypeAlignment(32).value();
case MachineJumpTableInfo::EK_Inline:
return 1;
}
llvm_unreachable("Unknown jump table encoding!");
}
/// Create a new jump table entry in the jump table info.
unsigned MachineJumpTableInfo::createJumpTableIndex(
const std::vector<MachineBasicBlock*> &DestBBs) {
assert(!DestBBs.empty() && "Cannot create an empty jump table!");
JumpTables.push_back(MachineJumpTableEntry(DestBBs));
return JumpTables.size()-1;
}
/// If Old is the target of any jump tables, update the jump tables to branch
/// to New instead.
bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
MachineBasicBlock *New) {
assert(Old != New && "Not making a change?");
bool MadeChange = false;
for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
ReplaceMBBInJumpTable(i, Old, New);
return MadeChange;
}
/// If MBB is present in any jump tables, remove it.
bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
bool MadeChange = false;
for (MachineJumpTableEntry &JTE : JumpTables) {
auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
MadeChange |= (removeBeginItr != JTE.MBBs.end());
JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
}
return MadeChange;
}
/// If Old is a target of the jump tables, update the jump table to branch to
/// New instead.
bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
MachineBasicBlock *Old,
MachineBasicBlock *New) {
assert(Old != New && "Not making a change?");
bool MadeChange = false;
MachineJumpTableEntry &JTE = JumpTables[Idx];
for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
if (JTE.MBBs[j] == Old) {
JTE.MBBs[j] = New;
MadeChange = true;
}
return MadeChange;
}
void MachineJumpTableInfo::print(raw_ostream &OS) const {
if (JumpTables.empty()) return;
OS << "Jump Tables:\n";
for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
OS << printJumpTableEntryReference(i) << ':';
for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
if (i != e)
OS << '\n';
}
OS << '\n';
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
#endif
Printable llvm::printJumpTableEntryReference(unsigned Idx) {
return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
}
//===----------------------------------------------------------------------===//
// MachineConstantPool implementation
//===----------------------------------------------------------------------===//
void MachineConstantPoolValue::anchor() {}
unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
return DL.getTypeAllocSize(Ty);
}
unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
if (isMachineConstantPoolEntry())
return Val.MachineCPVal->getSizeInBytes(DL);
return DL.getTypeAllocSize(Val.ConstVal->getType());
}
bool MachineConstantPoolEntry::needsRelocation() const {
if (isMachineConstantPoolEntry())
return true;
return Val.ConstVal->needsDynamicRelocation();
}
SectionKind
MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
if (needsRelocation())
return SectionKind::getReadOnlyWithRel();
switch (getSizeInBytes(*DL)) {
case 4:
return SectionKind::getMergeableConst4();
case 8:
return SectionKind::getMergeableConst8();
case 16:
return SectionKind::getMergeableConst16();
case 32:
return SectionKind::getMergeableConst32();
default:
return SectionKind::getReadOnly();
}
}
MachineConstantPool::~MachineConstantPool() {
// A constant may be a member of both Constants and MachineCPVsSharingEntries,
// so keep track of which we've deleted to avoid double deletions.
DenseSet<MachineConstantPoolValue*> Deleted;
for (unsigned i = 0, e = Constants.size(); i != e; ++i)
if (Constants[i].isMachineConstantPoolEntry()) {
Deleted.insert(Constants[i].Val.MachineCPVal);
delete Constants[i].Val.MachineCPVal;
}
for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
if (Deleted.count(CPV) == 0)
delete CPV;
}
}
/// Test whether the given two constants can be allocated the same constant pool
/// entry.
static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
const DataLayout &DL) {
// Handle the trivial case quickly.
if (A == B) return true;
// If they have the same type but weren't the same constant, quickly
// reject them.
if (A->getType() == B->getType()) return false;
// We can't handle structs or arrays.
if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
return false;
// For now, only support constants with the same size.
uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
return false;
Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
// Try constant folding a bitcast of both instructions to an integer. If we
// get two identical ConstantInt's, then we are good to share them. We use
// the constant folding APIs to do this so that we get the benefit of
// DataLayout.
if (isa<PointerType>(A->getType()))
A = ConstantFoldCastOperand(Instruction::PtrToInt,
const_cast<Constant *>(A), IntTy, DL);
else if (A->getType() != IntTy)
A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
IntTy, DL);
if (isa<PointerType>(B->getType()))
B = ConstantFoldCastOperand(Instruction::PtrToInt,
const_cast<Constant *>(B), IntTy, DL);
else if (B->getType() != IntTy)
B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
IntTy, DL);
return A == B;
}
/// Create a new entry in the constant pool or return an existing one.
/// User must specify the log2 of the minimum required alignment for the object.
unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
Align Alignment) {
if (Alignment > PoolAlignment) PoolAlignment = Alignment;
// Check to see if we already have this constant.
//
// FIXME, this could be made much more efficient for large constant pools.
for (unsigned i = 0, e = Constants.size(); i != e; ++i)
if (!Constants[i].isMachineConstantPoolEntry() &&
CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
if (Constants[i].getAlign() < Alignment)
Constants[i].Alignment = Alignment;
return i;
}
Constants.push_back(MachineConstantPoolEntry(C, Alignment));
return Constants.size()-1;
}
unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
Align Alignment) {
if (Alignment > PoolAlignment) PoolAlignment = Alignment;
// Check to see if we already have this constant.
//
// FIXME, this could be made much more efficient for large constant pools.
int Idx = V->getExistingMachineCPValue(this, Alignment);
if (Idx != -1) {
MachineCPVsSharingEntries.insert(V);
return (unsigned)Idx;
}
Constants.push_back(MachineConstantPoolEntry(V, Alignment));
return Constants.size()-1;
}
void MachineConstantPool::print(raw_ostream &OS) const {
if (Constants.empty()) return;
OS << "Constant Pool:\n";
for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
OS << " cp#" << i << ": ";
if (Constants[i].isMachineConstantPoolEntry())
Constants[i].Val.MachineCPVal->print(OS);
else
Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
OS << ", align=" << Constants[i].getAlign().value();
OS << "\n";
}
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
#endif
| 36.057858 | 85 | 0.668134 | [
"object",
"vector"
] |
8b1d584fda677fe4ef66b897ff42489f38bc7c86 | 7,018 | cc | C++ | Cpp_Drop_In_Another_Thread/main.cc | c86j224s/snippet | 47072085e91fd3a7e584f159ba9989550871a9e5 | [
"Apache-2.0"
] | null | null | null | Cpp_Drop_In_Another_Thread/main.cc | c86j224s/snippet | 47072085e91fd3a7e584f159ba9989550871a9e5 | [
"Apache-2.0"
] | null | null | null | Cpp_Drop_In_Another_Thread/main.cc | c86j224s/snippet | 47072085e91fd3a7e584f159ba9989550871a9e5 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <map>
#include <unordered_map>
#include <variant>
#include <optional>
#include <string>
#include <mutex>
#include <chrono>
#include <numeric>
#include <functional>
#include <atomic>
#include <memory>
#include <thread>
struct Obj {
char m_mem[512 * 1024 * 1024] = { 0, };
int m_i = 0;
Obj(int i) : m_i(i) {}
~Obj() {}
int I() const { return m_i; }
};
struct SparseObj {
std::unordered_map<int, std::vector<int>> m_mem;
int m_i = 0;
SparseObj(int i) : m_i(i) {
for (auto i = 0; i < 1'000'000; i++) {
m_mem.emplace(i, std::vector<int> {i, });
}
}
~SparseObj() {}
int I() const { return m_i; }
};
template<typename T>
class DropQueue {
std::mutex m_mtx;
std::vector<T> m_ptrs;
std::atomic<bool> m_dirty = false;
public:
DropQueue() {
m_ptrs.reserve(100'000);
}
~DropQueue() {}
void Push(T&& ptr) {
std::lock_guard<std::mutex> lg{ m_mtx };
m_ptrs.emplace_back(std::forward<T>(ptr));
m_dirty = true;
}
void Consume() {
if (!m_dirty) return;
std::lock_guard<std::mutex> lg{ m_mtx };
m_ptrs.clear();
m_dirty = false;
}
bool Empty() {
return !m_dirty;
}
};
double check_duration(std::function<void(void)> f, bool should_print) {
auto start = std::chrono::steady_clock::now();
f();
std::chrono::duration<double> dur = std::chrono::steady_clock::now() - start;
if (should_print)
std::cout << "execution duration : " << dur.count() << " secs" << std::endl;
return dur.count();
}
template<typename T>
double check_duration2(std::function<void(std::unique_ptr<T>)> f, bool should_print, std::unique_ptr<T> arg) {
auto start = std::chrono::steady_clock::now();
f(std::move(arg));
std::chrono::duration<double> dur = std::chrono::steady_clock::now() - start;
if (should_print)
std::cout << "execution duration : " << dur.count() << " secs" << std::endl;
return dur.count();
}
template<typename T, int N>
void check_main() {
check_duration([] {
auto result = 0;
for (auto i = 0; i < N; i++) {
auto obj = std::make_unique<T>(i);
result += obj->I();
}
std::cout << result << std::endl;
}, true);
check_duration([] {
auto result = 0;
for (auto i = 0; i < N; i++) {
auto obj = std::make_unique<T>(i);
result += obj->I();
std::thread([](std::unique_ptr<T> p) {}, std::move(obj)).detach();
}
std::cout << result << std::endl;
}, true);
check_duration([] {
auto result = 0;
auto drop_queue = std::make_shared<DropQueue<std::unique_ptr<T>>>();
auto fin = false;
std::thread t([&fin, drop_queue]() mutable {
while (!fin || !drop_queue->Empty()) {
drop_queue->Consume();
std::this_thread::yield();
}
});
for (auto i = 0; i < N; i++) {
auto obj = std::make_unique<T>(i);
result += obj->I();
drop_queue->Push(std::move(obj));
}
std::cout << result << std::endl;
fin = true;
t.join();
}, true);
}
template<typename T, int N>
void check_main2() {
{
std::vector<double> durs;
auto result = 0;
for (auto i = 0; i < N; i++) {
auto obj = std::make_unique<T>(i);
auto dur = check_duration2<T>([&result](auto obj) mutable {
result += obj->I();
}, false, std::move(obj));
durs.emplace_back(dur);
}
std::cout << result << std::endl;
std::cout << "execution duration : " << std::accumulate(durs.begin(), durs.end(), 0.0) / durs.size() << " secs" << std::endl;
}
{
std::vector<double> durs;
auto result = 0;
for (auto i = 0; i < N; i++) {
auto obj = std::make_unique<T>(i);
auto dur = check_duration2<T>([&result](auto obj) mutable {
result += obj->I();
std::thread([](std::unique_ptr<T> p) {}, std::move(obj)).detach();
}, false, std::move(obj));
durs.emplace_back(dur);
}
std::cout << result << std::endl;
std::cout << "execution duration : " << std::accumulate(durs.begin(), durs.end(), 0.0) / durs.size() << " secs" << std::endl;
}
{
std::vector<double> durs;
auto result = 0;
auto drop_queue = std::make_shared<DropQueue<std::unique_ptr<T>>>();
auto fin = false;
std::thread t([&fin, drop_queue]() mutable {
while (!fin || !drop_queue->Empty()) {
drop_queue->Consume();
std::this_thread::yield();
}
});
for (auto i = 0; i < N; i++) {
auto obj = std::make_unique<T>(i);
auto dur = check_duration2<T>([drop_queue, result](auto obj) mutable {
result += obj->I();
drop_queue->Push(std::move(obj));
}, false, std::move(obj));
durs.emplace_back(dur);
}
fin = true;
t.join();
std::cout << result << std::endl;
std::cout << "execution duration : " << std::accumulate(durs.begin(), durs.end(), 0.0) / durs.size() << " secs" << std::endl;
}
}
int main(int argc, char** argv)
{
std::cout << "========== check method 1 ==========" << std::endl;
std::cout << "=== 1 ===" << std::endl;
check_main<Obj, 1>();
check_main<SparseObj, 1>();
std::cout << "=== 10 ===" << std::endl;
check_main<Obj, 10>();
check_main<SparseObj, 10>();
std::cout << "=== 20 ===" << std::endl;
check_main<Obj, 20>();
check_main<SparseObj, 20>();
/*
std::cout << "=== 50 ===" << std::endl;
check_main<Obj, 50>();
check_main<SparseObj, 50>();
std::cout << "=== 100 ===" << std::endl;
check_main<Obj, 100>();
check_main<SparseObj, 100>();
*/
std::cout << "========== check method 2 ==========" << std::endl;
std::cout << "=== 1 ===" << std::endl;
check_main2<Obj, 1>();
check_main2<SparseObj, 1>();
std::cout << "=== 10 ===" << std::endl;
check_main2<Obj, 10>();
check_main2<SparseObj, 10>();
std::cout << "=== 20 ===" << std::endl;
check_main2<Obj, 20>();
check_main2<SparseObj, 20>();
/*
std::cout << "=== 50 ===" << std::endl;
check_main2<Obj, 50>();
check_main2<SparseObj, 50>();
std::cout << "=== 100 ===" << std::endl;
check_main2<Obj, 100>();
check_main2<SparseObj, 100>();
*/
return 0;
}
| 24.886525 | 134 | 0.479054 | [
"vector"
] |
8b1de2a0dd55c43cc6c9b1456c34bb2bf4784a38 | 27,103 | cpp | C++ | src/mongo/util/heap_profiler.cpp | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | 12 | 2020-04-27T21:31:57.000Z | 2020-12-13T13:25:06.000Z | src/mongo/util/heap_profiler.cpp | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | null | null | null | src/mongo/util/heap_profiler.cpp | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | 4 | 2021-03-27T14:40:25.000Z | 2022-03-19T20:52:41.000Z | /**
* Copyright (C) 2016 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault
#include "mongo/platform/basic.h"
#include "mongo/base/init.h"
#include "mongo/base/static_assert.h"
#include "mongo/config.h"
#include "mongo/db/commands/server_status.h"
#include "mongo/db/server_parameters.h"
#include "mongo/util/log.h"
#include "mongo/util/stacktrace.h"
#include <gperftools/malloc_hook.h>
#include <third_party/murmurhash3/MurmurHash3.h>
// for dlfcn.h and backtrace
#if defined(_POSIX_VERSION) && defined(MONGO_CONFIG_HAVE_EXECINFO_BACKTRACE)
#include <dlfcn.h>
#include <execinfo.h>
//
// Sampling heap profiler
//
// Intercepts allocate and free calls to track approximate number of live allocated bytes
// associated with each allocating stack trace at each point in time.
//
// Hooks into tcmalloc via the MallocHook interface, but has no dependency
// on any allocator internals; could be used with any allocator via similar
// hooks, or via shims.
//
// Adds no space overhead to each allocated object - allocated objects
// and associated stack traces are recorded in separate pre-allocated
// fixed-size hash tables. Size of the separate hash tables is configurable
// but something on the order of tens of MB should suffice for most purposes.
//
// Performance overhead is small because it only samples a fraction of the allocations.
//
// Samples allocate calls every so many bytes allocated.
// * a stack trace is obtained, and entered in a stack hash table if it's a new stack trace
// * the number of active bytes charged to that stack trace is increased
// * the allocated object, stack trace, and number of bytes is recorded in an object hash table
// For each free call if the freed object is in the object hash table.
// * the number of active bytes charged to the allocating stack trace is decreased
// * the object is removed from the object hash table
//
// Enable at startup time (only) with
// mongod --setParameter heapProfilingEnabled=true
//
// If enabled, adds a heapProfile section to serverStatus as follows:
//
// heapProfile: {
// stats: {
// // internal stats related to heap profiling process (collisions, number of stacks, etc.)
// }
// stacks: {
// stack_n_: { // one for each stack _n_
// activeBytes: ..., // number of active bytes allocated by this stack
// stack: [ // the stack itself
// "frame0",
// "frame1",
// ...
// ]
// }
// }
//
// Each new stack encountered is also logged to mongod log with a message like
// .... stack_n_: {0: "frame0", 1: "frame1", ...}
//
// Can be used in one of two ways:
//
// Via FTDC - strings are not captured by FTDC, so the information
// recorded in FTDC for each sample is essentially of the form
// {stack_n_: activeBytes} for each stack _n_. The timeseries tool
// will present one graph per stack, identified by the label stack_n_,
// showing active bytes that were allocated by that stack at each
// point in time. The mappings from stack_n_ to the actual stack can
// be found in mongod log.
//
// Via serverStatus - the serverStatus section described above
// contains complete information, including the stack trace. It can
// be obtained and examined manually, and can be further processed by
// tools.
//
// We will need about 1 active ObjInfo for every sampleIntervalBytes live bytes,
// so max active memory we can handle is sampleIntervalBytes * kMaxObjInfos.
// With the current defaults of
// kMaxObjInfos = 1024 * 1024
// sampleIntervalBytes = 256 * 1024
// the following information is computed and logged on startup (see HeapProfiler()):
// maxActiveMemory 262144 MB
// objTableSize 72 MB
// stackTableSize 16.6321MB
// So the defaults allow handling very large memories at a reasonable sampling interval
// and acceptable size overhead for the hash tables.
//
namespace mongo {
namespace {
//
// Simple hash table maps Key->Value.
// All storage is pre-allocated at creation.
// Access functions take a hash specifying a bucket as the first parameter to avoid re-computing
// hash unnecessarily; caller must ensure that hash is correctly computed from the appropriate Key.
// Key must implement operator== to support find().
// Key and Value must both support assignment to allow copying key and value into table on insert.
//
// Concurrency rules:
// Reads (find(), isBucketEmpty(), forEach()) MAY be called concurrently with each other.
// Writes (insert(), remove()) may NOT be called concurrently with each other.
// Concurrency of reads and writes is as follows:
// find() may NOT be called concurrently with any write.
// isBucketEmpty() MAY be called concurrently with any write.
// forEach()
// MAY be called concurrently with insert() but NOT remove()
// does not provide snapshot semantics wrt set of entries traversed
// caller must ensure safety wrt concurrent modification of Value of existing entry
//
using Hash = uint32_t;
template <class Key, class Value>
class HashTable {
MONGO_DISALLOW_COPYING(HashTable);
private:
struct Entry {
Key key{};
Value value{};
std::atomic<Entry*> next{nullptr}; // NOLINT
std::atomic<bool> valid{false}; // NOLINT
Entry() {}
};
const size_t maxEntries; // we allocate storage for this many entries on creation
std::atomic_size_t numEntries; // number of entries currently in use NOLINT
size_t numBuckets; // number of buckets, computed as numEntries * loadFactor
// pre-allocate buckets and entries
std::unique_ptr<std::atomic<Entry*>[]> buckets; // NOLINT
std::unique_ptr<Entry[]> entries;
std::atomic_size_t nextEntry; // first entry that's never been used NOLINT
Entry* freeEntry; // linked list of entries returned to us by removeEntry
public:
HashTable(size_t maxEntries, int loadFactor)
: maxEntries(maxEntries),
numEntries(0),
numBuckets(maxEntries * loadFactor),
buckets(new std::atomic<Entry*>[numBuckets]()), // NOLINT
entries(new Entry[maxEntries]()),
nextEntry(0),
freeEntry(nullptr) {}
// Allocate a new entry in the specified hash bucket.
// Stores a copy of the specified Key and Value.
// Returns a pointer to the newly allocated Value, or nullptr if out of space.
Value* insert(Hash hash, const Key& key, const Value& value) {
hash %= numBuckets;
Entry* entry = nullptr;
if (freeEntry) {
entry = freeEntry;
freeEntry = freeEntry->next;
} else if (nextEntry < maxEntries) {
entry = &entries[nextEntry++];
}
if (entry) {
entry->next = buckets[hash].load();
buckets[hash] = entry;
entry->key = key;
entry->value = value;
entry->valid = true; // signal that the entry is well-formed and may be traversed
numEntries++;
return &entry->value;
} else {
return nullptr;
}
}
// Find the entry containing Key in the specified hash bucket.
// Returns a pointer to the corresponding Value object, or nullptr if not found.
Value* find(Hash hash, const Key& key) {
hash %= numBuckets;
for (Entry* entry = buckets[hash]; entry; entry = entry->next)
if (entry->key == key)
return &entry->value;
return nullptr;
}
// Remove an entry specified by key.
void remove(Hash hash, const Key& key) {
hash %= numBuckets;
for (auto nextp = &buckets[hash]; *nextp; nextp = &((*nextp).load()->next)) {
Entry* entry = *nextp;
if (entry->key == key) {
*nextp = entry->next.load();
entry->valid = false; // first signal entry is invalid as it may get reused
entry->next = freeEntry;
freeEntry = entry;
numEntries--;
break;
}
}
}
// Traverse the array of pre-allocated entries, calling f(key, value) on each valid entry.
// This may be called concurrently with insert() but not remove()
// atomic entry.valid ensures that it will see only well-formed entries
// nextEntry is atomic to guard against torn reads as nextEntry is updated
// Note however it is not guaranteed to provide snapshot semantics wrt the set of entries,
// and caller must ensure safety wrt concurrent updates to the Value of an entry
template <typename F>
void forEach(F f) {
for (size_t i = 0; i < nextEntry; i++) {
Entry& entry = entries[i];
if (entry.valid) // only traverse well-formed entries
f(entry.key, entry.value);
}
}
// Determines whether the specified hash bucket is empty. May be called concurrently with
// insert() and remove(). Concurrent visibility on other threads is guaranteed because
// buckets[hash] is atomic.
bool isEmptyBucket(Hash hash) {
hash %= numBuckets;
return buckets[hash] == nullptr;
}
// Number of entries.
size_t size() {
return numEntries;
}
// Highwater mark of number of entries used, for reporting stats.
size_t maxSizeSeen() {
return nextEntry;
}
// Returns total allocated size of the hash table, for reporting stats.
size_t memorySizeBytes() {
return numBuckets * sizeof(buckets[0]) + maxEntries * sizeof(entries[0]);
}
};
class HeapProfiler {
private:
// 0: sampling internally disabled
// 1: sample every allocation - byte accurate but slow and big
// >1: sample ever sampleIntervalBytes bytes allocated - less accurate but fast and small
std::atomic_size_t sampleIntervalBytes; // NOLINT
stdx::mutex hashtable_mutex; // guards updates to both object and stack hash tables
stdx::mutex stackinfo_mutex; // guards against races updating the StackInfo bson representation
// cumulative bytes allocated - determines when samples are taken
std::atomic_size_t bytesAllocated{0}; // NOLINT
// estimated currently active bytes - sum of activeBytes for all stacks
size_t totalActiveBytes = 0;
//
// Hash table of stacks
//
using FrameInfo = void*; // per-frame information is just the IP
static const int kMaxStackInfos = 20000; // max number of unique call sites we handle
static const int kStackHashTableLoadFactor = 2; // keep loading <50%
static const int kMaxFramesPerStack = 100; // max depth of stack
// stack HashTable Key
struct Stack {
int numFrames = 0;
std::array<FrameInfo, kMaxFramesPerStack> frames;
Stack() {}
bool operator==(const Stack& that) {
return this->numFrames == that.numFrames &&
std::equal(frames.begin(), frames.begin() + numFrames, that.frames.begin());
}
Hash hash() {
Hash hash;
MONGO_STATIC_ASSERT_MSG(sizeof(frames) == sizeof(FrameInfo) * kMaxFramesPerStack,
"frames array is not dense");
MurmurHash3_x86_32(frames.data(), numFrames * sizeof(FrameInfo), 0, &hash);
return hash;
}
};
// Stack HashTable Value.
struct StackInfo {
int stackNum = 0; // used for stack short name
BSONObj stackObj{}; // symbolized representation
size_t activeBytes = 0; // number of live allocated bytes charged to this stack
explicit StackInfo(int stackNum) : stackNum(stackNum) {}
StackInfo() {}
};
// The stack HashTable itself.
HashTable<Stack, StackInfo> stackHashTable{kMaxStackInfos, kStackHashTableLoadFactor};
// frames to skip at top and bottom of backtrace when reporting stacks
int skipStartFrames = 0;
int skipEndFrames = 0;
//
// Hash table of allocated objects.
//
static const int kMaxObjInfos = 1024 * 1024; // maximum tracked allocations
static const int kObjHashTableLoadFactor = 4; // keep hash table loading <25%
// Obj HashTable Key.
struct Obj {
const void* objPtr = nullptr;
explicit Obj(const void* objPtr) : objPtr(objPtr) {}
Obj() {}
bool operator==(const Obj& that) {
return this->objPtr == that.objPtr;
}
Hash hash() {
Hash hash = 0;
MurmurHash3_x86_32(&objPtr, sizeof(objPtr), 0, &hash);
return hash;
}
};
// Obj HashTable Value.
struct ObjInfo {
size_t accountedLen = 0;
StackInfo* stackInfo = nullptr;
ObjInfo(size_t accountedLen, StackInfo* stackInfo)
: accountedLen(accountedLen), stackInfo(stackInfo) {}
ObjInfo() {}
};
// The obj HashTable itself.
HashTable<Obj, ObjInfo> objHashTable{kMaxObjInfos, kObjHashTableLoadFactor};
// If we encounter an error that doesn't allow us to proceed, for
// example out of space for new hash table entries, we internally
// disable profiling and then log an error message.
void disable(const char* msg) {
sampleIntervalBytes = 0;
log() << msg;
}
//
// Record an allocation.
//
void _alloc(const void* objPtr, size_t objLen) {
// still profiling?
if (sampleIntervalBytes == 0)
return;
// Sample every sampleIntervalBytes bytes of allocation.
// We charge each sampled stack with the amount of memory allocated since the last sample
// this could grossly overcharge any given stack sample, but on average over a large
// number of samples will be correct.
size_t lastSample = bytesAllocated.fetch_add(objLen);
size_t currentSample = lastSample + objLen;
size_t accountedLen = sampleIntervalBytes *
(currentSample / sampleIntervalBytes - lastSample / sampleIntervalBytes);
if (accountedLen == 0)
return;
// Get backtrace.
Stack tempStack;
tempStack.numFrames = backtrace(tempStack.frames.data(), kMaxFramesPerStack);
// Compute backtrace hash.
Hash stackHash = tempStack.hash();
// Now acquire lock.
stdx::lock_guard<stdx::mutex> lk(hashtable_mutex);
// Look up stack in stackHashTable.
StackInfo* stackInfo = stackHashTable.find(stackHash, tempStack);
// If new stack, store in stackHashTable.
if (!stackInfo) {
StackInfo newStackInfo(stackHashTable.size() /*stackNum*/);
stackInfo = stackHashTable.insert(stackHash, tempStack, newStackInfo);
if (!stackInfo) {
disable("too many stacks; disabling heap profiling");
return;
}
}
// Count the bytes.
totalActiveBytes += accountedLen;
stackInfo->activeBytes += accountedLen;
// Enter obj in objHashTable.
Obj obj(objPtr);
ObjInfo objInfo(accountedLen, stackInfo);
if (!objHashTable.insert(obj.hash(), obj, objInfo)) {
disable("too many live objects; disabling heap profiling");
return;
}
}
//
// Record a freed object.
//
void _free(const void* objPtr) {
// still profiling?
if (sampleIntervalBytes == 0)
return;
// Compute hash, quick return before locking if bucket is empty (common case).
// This is crucial for performance because we need to check the hash table on every _free.
// Visibility of the bucket entry if the _alloc was done on a different thread is
// guaranteed because isEmptyBucket consults an atomic pointer.
Obj obj(objPtr);
Hash objHash = obj.hash();
if (objHashTable.isEmptyBucket(objHash))
return;
// Now acquire lock.
stdx::lock_guard<stdx::mutex> lk(hashtable_mutex);
// Remove the object from the hash bucket if present.
ObjInfo* objInfo = objHashTable.find(objHash, obj);
if (objInfo) {
totalActiveBytes -= objInfo->accountedLen;
objInfo->stackInfo->activeBytes -= objInfo->accountedLen;
objHashTable.remove(objHash, obj);
}
}
//
// Generate bson representation of stack.
//
void generateStackIfNeeded(Stack& stack, StackInfo& stackInfo) {
if (!stackInfo.stackObj.isEmpty())
return;
BSONArrayBuilder builder;
for (int j = skipStartFrames; j < stack.numFrames - skipEndFrames; j++) {
Dl_info dli;
StringData frameString;
char* demangled = nullptr;
if (dladdr(stack.frames[j], &dli)) {
if (dli.dli_sname) {
int status;
demangled = abi::__cxa_demangle(dli.dli_sname, 0, 0, &status);
if (demangled) {
// strip off function parameters as they are very verbose and not useful
char* p = strchr(demangled, '(');
if (p)
frameString = StringData(demangled, p - demangled);
else
frameString = demangled;
} else {
frameString = dli.dli_sname;
}
}
}
if (frameString.empty()) {
std::ostringstream s;
s << stack.frames[j];
frameString = s.str();
}
builder.append(frameString);
if (demangled)
free(demangled);
}
stackInfo.stackObj = builder.obj();
log() << "heapProfile stack" << stackInfo.stackNum << ": " << stackInfo.stackObj;
}
//
// Generate serverStatus section.
//
bool logGeneralStats = true; // first time only
// In order to reduce load on ftdc we track the stacks we deem important enough to emit
// once a stack is deemed "important" it remains important from that point on.
// "Important" is a sticky quality to improve the stability of the set of stacks we emit,
// and we always emit them in stackNum order, greatly improving ftdc compression efficiency.
std::set<StackInfo*, bool (*)(StackInfo*, StackInfo*)> importantStacks{
[](StackInfo* a, StackInfo* b) -> bool { return a->stackNum < b->stackNum; }};
int numImportantSamples = 0; // samples currently included in importantStacks
const int kMaxImportantSamples = 4 * 3600; // reset every 4 hours at default 1 sample / sec
void _generateServerStatusSection(BSONObjBuilder& builder) {
// compute and log some informational stats first time through
if (logGeneralStats) {
const size_t maxActiveMemory = sampleIntervalBytes * kMaxObjInfos;
const size_t objTableSize = objHashTable.memorySizeBytes();
const size_t stackTableSize = stackHashTable.memorySizeBytes();
const double MB = 1024 * 1024;
log() << "sampleIntervalBytes " << sampleIntervalBytesParameter << "; "
<< "maxActiveMemory " << maxActiveMemory / MB << " MB; "
<< "objTableSize " << objTableSize / MB << " MB; "
<< "stackTableSize " << stackTableSize / MB << " MB";
// print a stack trace to log somap for post-facto symbolization
log() << "following stack trace is for heap profiler informational purposes";
printStackTrace();
logGeneralStats = false;
}
// Stats subsection.
BSONObjBuilder statsBuilder(builder.subobjStart("stats"));
statsBuilder.appendNumber("totalActiveBytes", totalActiveBytes);
statsBuilder.appendNumber("bytesAllocated", bytesAllocated);
statsBuilder.appendNumber("numStacks", stackHashTable.size());
statsBuilder.appendNumber("currentObjEntries", objHashTable.size());
statsBuilder.appendNumber("maxObjEntriesUsed", objHashTable.maxSizeSeen());
statsBuilder.doneFast();
// Guard against races updating the StackInfo bson representation.
stdx::lock_guard<stdx::mutex> lk(stackinfo_mutex);
// Traverse stackHashTable accumulating potential stacks to emit.
// We do this traversal without locking hashtable_mutex because we need to use the heap.
// forEach guarantees this is safe wrt to insert(), and we never call remove().
// We use stackinfo_mutex to ensure safety wrt concurrent updates to the StackInfo objects.
// We can get skew between entries, which is ok.
std::vector<StackInfo*> stackInfos;
stackHashTable.forEach([&](Stack& stack, StackInfo& stackInfo) {
if (stackInfo.activeBytes) {
generateStackIfNeeded(stack, stackInfo);
stackInfos.push_back(&stackInfo);
}
});
// Sort the stacks and find enough stacks to account for at least 99% of the active bytes
// deem any stack that has ever met this criterion as "important".
auto sortByActiveBytes = [](StackInfo* a, StackInfo* b) -> bool {
return a->activeBytes > b->activeBytes;
};
std::stable_sort(stackInfos.begin(), stackInfos.end(), sortByActiveBytes);
size_t threshold = totalActiveBytes * 0.99;
size_t cumulative = 0;
for (auto it = stackInfos.begin(); it != stackInfos.end(); ++it) {
StackInfo* stackInfo = *it;
importantStacks.insert(stackInfo);
cumulative += stackInfo->activeBytes;
if (cumulative > threshold)
break;
}
// Build the stacks subsection by emitting the "important" stacks.
BSONObjBuilder stacksBuilder(builder.subobjStart("stacks"));
for (auto it = importantStacks.begin(); it != importantStacks.end(); ++it) {
StackInfo* stackInfo = *it;
std::ostringstream shortName;
shortName << "stack" << stackInfo->stackNum;
BSONObjBuilder stackBuilder(stacksBuilder.subobjStart(shortName.str()));
stackBuilder.appendNumber("activeBytes", stackInfo->activeBytes);
stackBuilder.append("stack", stackInfo->stackObj);
}
stacksBuilder.doneFast();
// importantStacks grows monotonically, so it can accumulate unneeded stacks,
// so we clear it periodically.
if (++numImportantSamples >= kMaxImportantSamples) {
log() << "clearing importantStacks";
importantStacks.clear();
numImportantSamples = 0;
}
}
//
// Static hooks to give to the allocator.
//
static void alloc(const void* obj, size_t objLen) {
heapProfiler->_alloc(obj, objLen);
}
static void free(const void* obj) {
heapProfiler->_free(obj);
}
public:
static HeapProfiler* heapProfiler;
static bool enabledParameter;
static long long sampleIntervalBytesParameter;
HeapProfiler() {
// Set sample interval from the parameter.
sampleIntervalBytes = sampleIntervalBytesParameter;
// This is our only allocator dependency - ifdef and change as
// appropriate for other allocators, using hooks or shims.
// For tcmalloc we skip two frames that are internal to the allocator
// so that the top frame is the public tc_* function.
skipStartFrames = 2;
skipEndFrames = 0;
MallocHook::AddNewHook(alloc);
MallocHook::AddDeleteHook(free);
}
static void generateServerStatusSection(BSONObjBuilder& builder) {
if (heapProfiler)
heapProfiler->_generateServerStatusSection(builder);
}
};
//
// serverStatus section
//
class HeapProfilerServerStatusSection final : public ServerStatusSection {
public:
HeapProfilerServerStatusSection() : ServerStatusSection("heapProfile") {}
bool includeByDefault() const override {
return HeapProfiler::enabledParameter;
}
BSONObj generateSection(OperationContext* txn,
const BSONElement& configElement) const override {
BSONObjBuilder builder;
HeapProfiler::generateServerStatusSection(builder);
return builder.obj();
}
} heapProfilerServerStatusSection;
//
// startup
//
HeapProfiler* HeapProfiler::heapProfiler;
bool HeapProfiler::enabledParameter = false;
long long HeapProfiler::sampleIntervalBytesParameter = 256 * 1024;
ExportedServerParameter<bool, ServerParameterType::kStartupOnly> heapProfilingEnabledParameter(
ServerParameterSet::getGlobal(), "heapProfilingEnabled", &HeapProfiler::enabledParameter);
ExportedServerParameter<long long, ServerParameterType::kStartupOnly>
heapProfilingSampleIntervalBytes(ServerParameterSet::getGlobal(),
"heapProfilingSampleIntervalBytes",
&HeapProfiler::sampleIntervalBytesParameter);
MONGO_INITIALIZER_GENERAL(StartHeapProfiling, ("EndStartupOptionHandling"), ("default"))
(InitializerContext* context) {
if (HeapProfiler::enabledParameter)
HeapProfiler::heapProfiler = new HeapProfiler();
return Status::OK();
}
} // namespace
} // namespace mongo
#endif // MONGO_HAVE_HEAP_PROFILER
| 39.451237 | 100 | 0.64063 | [
"object",
"vector"
] |
8b2353a659110392e5eea6a6b0963b7be19416f5 | 719 | cpp | C++ | src/top.chenqwwq/leetcode/topic/dp/_983/minimum-cost-for-tickets.cpp | chenqwwq/_leetcode | a8055c53c9a68cedb1b57a56f98e83709448e4cb | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/leetcode/topic/dp/_983/minimum-cost-for-tickets.cpp | chenqwwq/_leetcode | a8055c53c9a68cedb1b57a56f98e83709448e4cb | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/leetcode/topic/dp/_983/minimum-cost-for-tickets.cpp | chenqwwq/_leetcode | a8055c53c9a68cedb1b57a56f98e83709448e4cb | [
"Apache-2.0"
] | null | null | null | //
// Created by 陈炳鑫 on 2022/3/27.
//
#include "stdc++.h"
#include "common.h"
using namespace std;
class Solution {
const int INF = 0x3f3f3f3f;
public:
int mincostTickets(vector<int> &v, vector<int> &c) {
auto n = v.size();
vector<int> d{1, 7, 30}, dp(n + 1, INF);
dp[0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= 2; ++j) {
int cur = i - 1;
while (cur >= 0 && v[i - 1] - v[cur] < d[j]) cur--;
dp[i] = min(dp[i], c[j] + dp[cur + 1]);
}
}
return dp[n];
}
};
int main() {
vector<int> v1{1, 4, 6, 7, 8, 20}, v2{2, 7, 15};
(new Solution)->mincostTickets(v1, v2);
}
| 21.787879 | 67 | 0.435327 | [
"vector"
] |
8b2382e4a741905b143530c7223a555dce69210c | 4,371 | hpp | C++ | include/Oculus/Platform/Notifications.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/Oculus/Platform/Notifications.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/Oculus/Platform/Notifications.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Oculus::Platform
namespace Oculus::Platform {
// Forward declaring type: Request`1<T>
template<typename T>
class Request_1;
// Forward declaring type: Request
class Request;
}
// Forward declaring namespace: Oculus::Platform::Models
namespace Oculus::Platform::Models {
// Forward declaring type: RoomInviteNotificationList
class RoomInviteNotificationList;
}
// Completed forward declares
// Type namespace: Oculus.Platform
namespace Oculus::Platform {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Oculus.Platform.Notifications
// [TokenAttribute] Offset: FFFFFFFF
class Notifications : public ::Il2CppObject {
public:
// Creating value type constructor for type: Notifications
Notifications() noexcept {}
// static public Oculus.Platform.Request`1<Oculus.Platform.Models.RoomInviteNotificationList> GetRoomInviteNotifications()
// Offset: 0x23B1EC8
static Oculus::Platform::Request_1<Oculus::Platform::Models::RoomInviteNotificationList*>* GetRoomInviteNotifications();
// static public Oculus.Platform.Request MarkAsRead(System.UInt64 notificationID)
// Offset: 0x23B1FD4
static Oculus::Platform::Request* MarkAsRead(uint64_t notificationID);
// static public Oculus.Platform.Request`1<Oculus.Platform.Models.RoomInviteNotificationList> GetNextRoomInviteNotificationListPage(Oculus.Platform.Models.RoomInviteNotificationList list)
// Offset: 0x23B2114
static Oculus::Platform::Request_1<Oculus::Platform::Models::RoomInviteNotificationList*>* GetNextRoomInviteNotificationListPage(Oculus::Platform::Models::RoomInviteNotificationList* list);
}; // Oculus.Platform.Notifications
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::Notifications*, "Oculus.Platform", "Notifications");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Oculus::Platform::Notifications::GetRoomInviteNotifications
// Il2CppName: GetRoomInviteNotifications
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Oculus::Platform::Request_1<Oculus::Platform::Models::RoomInviteNotificationList*>* (*)()>(&Oculus::Platform::Notifications::GetRoomInviteNotifications)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::Notifications*), "GetRoomInviteNotifications", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Oculus::Platform::Notifications::MarkAsRead
// Il2CppName: MarkAsRead
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Oculus::Platform::Request* (*)(uint64_t)>(&Oculus::Platform::Notifications::MarkAsRead)> {
static const MethodInfo* get() {
static auto* notificationID = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::Notifications*), "MarkAsRead", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{notificationID});
}
};
// Writing MetadataGetter for method: Oculus::Platform::Notifications::GetNextRoomInviteNotificationListPage
// Il2CppName: GetNextRoomInviteNotificationListPage
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Oculus::Platform::Request_1<Oculus::Platform::Models::RoomInviteNotificationList*>* (*)(Oculus::Platform::Models::RoomInviteNotificationList*)>(&Oculus::Platform::Notifications::GetNextRoomInviteNotificationListPage)> {
static const MethodInfo* get() {
static auto* list = &::il2cpp_utils::GetClassFromName("Oculus.Platform.Models", "RoomInviteNotificationList")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::Notifications*), "GetNextRoomInviteNotificationListPage", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{list});
}
};
| 58.28 | 289 | 0.75429 | [
"vector"
] |
8b2ce063cda84cca077bd22747b0aac4c94cc1c4 | 661 | cpp | C++ | src/flexui/Render/TreePainter.cpp | franciscod/flexui | 9af2c32a8ac3fe7127a9dd6927abe8b1945237c4 | [
"MIT"
] | null | null | null | src/flexui/Render/TreePainter.cpp | franciscod/flexui | 9af2c32a8ac3fe7127a9dd6927abe8b1945237c4 | [
"MIT"
] | null | null | null | src/flexui/Render/TreePainter.cpp | franciscod/flexui | 9af2c32a8ac3fe7127a9dd6927abe8b1945237c4 | [
"MIT"
] | null | null | null | #include "flexui/Render/TreePainter.hpp"
#include "flexui/Render/Painter.hpp"
#include "flexui/Element.hpp"
#include "flexui/Surface.hpp"
namespace flexui {
TreePainter::TreePainter(Surface* surface)
: TreeProcessor(surface)
{
m_Painter = new Painter(surface->getTextureProvider());
}
TreePainter::~TreePainter()
{
delete m_Painter;
}
void TreePainter::process()
{
m_Painter->reset();
rec(m_Surface->getRoot());
}
Painter* TreePainter::getPainter() const
{
return m_Painter;
}
// this will be removed
void TreePainter::rec(Element* el)
{
el->paintContent(m_Painter);
for (Element* e : el->getChildrens())
rec(e);
}
}
| 16.121951 | 57 | 0.694402 | [
"render"
] |
8b363cbd9bb6509811fe9324e2497e3f298b3de7 | 4,359 | hxx | C++ | Modules/Filtering/GPUThresholding/include/itkGPUBinaryThresholdImageFilter.hxx | ferdymercury/ITK | b0a86ded2edd698a6f4a3e58a9db23523a7eb871 | [
"Apache-2.0"
] | 2 | 2021-02-01T17:24:16.000Z | 2021-02-02T02:18:46.000Z | Modules/Filtering/GPUThresholding/include/itkGPUBinaryThresholdImageFilter.hxx | ferdymercury/ITK | b0a86ded2edd698a6f4a3e58a9db23523a7eb871 | [
"Apache-2.0"
] | 4 | 2019-02-08T21:13:11.000Z | 2019-02-18T20:57:34.000Z | Modules/Filtering/GPUThresholding/include/itkGPUBinaryThresholdImageFilter.hxx | ferdymercury/ITK | b0a86ded2edd698a6f4a3e58a9db23523a7eb871 | [
"Apache-2.0"
] | 4 | 2015-02-07T05:09:14.000Z | 2019-10-08T09:17:30.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 itkGPUBinaryThresholdImageFilter_hxx
#define itkGPUBinaryThresholdImageFilter_hxx
namespace itk
{
/**
* Constructor
*/
template <typename TInputImage, typename TOutputImage>
GPUBinaryThresholdImageFilter<TInputImage, TOutputImage>::GPUBinaryThresholdImageFilter()
{
std::ostringstream defines;
if (TInputImage::ImageDimension > 3)
{
itkExceptionMacro("GPUBinaryThresholdImageFilter supports 1/2/3D image.");
}
std::vector<std::string> validTypes;
validTypes.emplace_back("unsigned char");
validTypes.emplace_back("unsigned short");
validTypes.emplace_back("char");
validTypes.emplace_back("int");
validTypes.emplace_back("unsigned int");
validTypes.emplace_back("float");
validTypes.emplace_back("double");
defines << "#define DIM_" << TInputImage::ImageDimension << "\n";
std::string validTypeName;
bool isValid = GetValidTypename(typeid(typename TInputImage::PixelType), validTypes, validTypeName);
if (isValid)
{
defines << "#define InPixelType " << validTypeName << "\n";
defines << "#define OutPixelType " << validTypeName << "\n";
#ifdef __APPLE__
// This is to work around a bug in the OpenCL compiler on Mac OS 10.6 and 10.7 with NVidia drivers
// where the compiler was not handling unsigned char arguments correctly.
// be sure to define the kernel arguments as InArgType and OutArgType in the kernel source
// Using unsigned short instead of unsigned char in the kernel definition
// is a known workaround to this problem.
if (validTypeName == "unsigned char")
{
defines << "#define InArgType unsigned short\n";
defines << "#define OutArgType unsigned short\n";
}
else
{
defines << "#define InArgType " << validTypeName << "\n";
defines << "#define OutArgType " << validTypeName << "\n";
}
#else
defines << "#define InArgType " << validTypeName << "\n";
defines << "#define OutArgType " << validTypeName << "\n";
#endif
}
else
{
std::ostringstream excpMsg;
excpMsg << "GPUBinaryThresholdImageFilter supports";
unsigned int sz = validTypes.size();
for (unsigned int ii = 0; ii < sz; ++ii)
{
if (ii < sz - 1)
{
excpMsg << " " << validTypes[ii] << ",";
}
else
{
excpMsg << " and " << validTypes[ii] << " input and output images.";
}
}
itkExceptionMacro(<< excpMsg.str().c_str());
}
const char * GPUSource = GPUBinaryThresholdImageFilter::GetOpenCLSource();
// load and build program
this->m_GPUKernelManager->LoadProgramFromString(GPUSource, defines.str().c_str());
// create kernel
this->m_UnaryFunctorImageFilterGPUKernelHandle = this->m_GPUKernelManager->CreateKernel("BinaryThresholdFilter");
}
template <typename TInputImage, typename TOutputImage>
void
GPUBinaryThresholdImageFilter<TInputImage, TOutputImage>::GPUGenerateData()
{
// set up the functor values
typename InputPixelObjectType::Pointer lowerThreshold = this->GetLowerThresholdInput();
typename InputPixelObjectType::Pointer upperThreshold = this->GetUpperThresholdInput();
if (lowerThreshold->Get() > upperThreshold->Get())
{
itkExceptionMacro(<< "Lower threshold cannot be greater than upper threshold.");
}
// Setup up the functor
this->GetFunctor().SetLowerThreshold(lowerThreshold->Get());
this->GetFunctor().SetUpperThreshold(upperThreshold->Get());
this->GetFunctor().SetInsideValue(this->GetInsideValue());
this->GetFunctor().SetOutsideValue(this->GetOutsideValue());
GPUSuperclass::GPUGenerateData();
}
} // end of namespace itk
#endif
| 33.790698 | 115 | 0.678367 | [
"vector",
"3d"
] |
8b3e8d08d2c1dcefeee3ac3a09f37ba60f30779b | 26,102 | cpp | C++ | execs/CM-Overlapping-AGM-SNAP/lib/snap/util.cpp | zhanghuijun-hello/A-framework-for-evaluating-community-mining-algorithms.- | 41ba38513b0b62d7837979de9de68abb475f9db2 | [
"MIT"
] | 1 | 2019-06-13T20:18:51.000Z | 2019-06-13T20:18:51.000Z | execs/CM-Overlapping-AGM-SNAP/lib/snap/util.cpp | zhanghuijun-hello/A-framework-for-evaluating-community-mining-algorithms.- | 41ba38513b0b62d7837979de9de68abb475f9db2 | [
"MIT"
] | null | null | null | execs/CM-Overlapping-AGM-SNAP/lib/snap/util.cpp | zhanghuijun-hello/A-framework-for-evaluating-community-mining-algorithms.- | 41ba38513b0b62d7837979de9de68abb475f9db2 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////
// Graph Utilities
void TGUtil::GetCdf(const TIntPrV& PdfV, TIntPrV& CdfV) {
CdfV = PdfV;
for (int i = 1; i < CdfV.Len(); i++) {
CdfV[i].Val2 = CdfV[i-1].Val2 + CdfV[i].Val2; }
}
void TGUtil::GetCdf(const TFltPrV& PdfV, TFltPrV& CdfV) {
CdfV = PdfV;
for (int i = 1; i < CdfV.Len(); i++) {
CdfV[i].Val2 = CdfV[i-1].Val2 + CdfV[i].Val2; }
}
void TGUtil::GetCdf(const TIntFltKdV& PdfV, TIntFltKdV& CdfV) {
CdfV = PdfV;
for (int i = 1; i < CdfV.Len(); i++) {
CdfV[i].Dat = CdfV[i-1].Dat + CdfV[i].Dat; }
}
TIntPrV TGUtil::GetCdf(const TIntPrV& PdfV) {
TIntPrV CdfV;
GetCdf(PdfV, CdfV);
return CdfV;
}
TFltPrV TGUtil::GetCdf(const TFltPrV& PdfV) {
TFltPrV CdfV;
GetCdf(PdfV, CdfV);
return CdfV;
}
void TGUtil::GetCCdf(const TIntPrV& PdfV, TIntPrV& CCdfV) {
CCdfV = PdfV;
for (int i = CCdfV.Len()-2; i >= 0; i--) {
CCdfV[i].Val2 = CCdfV[i+1].Val2 + CCdfV[i].Val2; }
}
void TGUtil::GetCCdf(const TFltPrV& PdfV, TFltPrV& CCdfV) {
CCdfV = PdfV;
for (int i = CCdfV.Len()-2; i >= 0; i--) {
CCdfV[i].Val2 = CCdfV[i+1].Val2 + CCdfV[i].Val2; }
}
void TGUtil::GetCCdf(const TIntFltKdV& PdfV, TIntFltKdV& CCdfV) {
CCdfV = PdfV;
for (int i = CCdfV.Len()-2; i >= 0; i--) {
CCdfV[i].Dat = CCdfV[i+1].Dat + CCdfV[i].Dat; }
}
TIntPrV TGUtil::GetCCdf(const TIntPrV& PdfV) {
TIntPrV CCdfV;
GetCCdf(PdfV, CCdfV);
return CCdfV;
}
TFltPrV TGUtil::GetCCdf(const TFltPrV& PdfV) {
TFltPrV CCdfV;
GetCCdf(PdfV, CCdfV);
return CCdfV;
}
void TGUtil::GetPdf(const TIntPrV& CdfV, TIntPrV& PdfV) {
PdfV = CdfV;
for (int i = PdfV.Len()-1; i > 0; i--) {
PdfV[i].Val2 = PdfV[i].Val2 - PdfV[i-1].Val2; }
}
void TGUtil::GetPdf(const TFltPrV& CdfV, TFltPrV& PdfV) {
PdfV = CdfV;
for (int i = PdfV.Len()-1; i > 0; i--) {
PdfV[i].Val2 = PdfV[i].Val2 - PdfV[i-1].Val2; }
}
void TGUtil::GetPdf(const TIntFltKdV& CdfV, TIntFltKdV& PdfV) {
PdfV = CdfV;
for (int i = PdfV.Len()-1; i > 0; i--) {
PdfV[i].Dat = PdfV[i].Dat - PdfV[i-1].Dat; }
}
void TGUtil::Normalize(TFltPrV& PdfV) {
double Sum = 0.0;
for (int i = 0; i < PdfV.Len(); i++) {
Sum += PdfV[i].Val2; }
if (Sum <= 0.0) { return; }
for (int i = 0; i < PdfV.Len(); i++) {
PdfV[i].Val2 /= Sum; }
}
void TGUtil::Normalize(TIntFltKdV& PdfV) {
double Sum = 0.0;
for (int i = 0; i < PdfV.Len(); i++) {
Sum += PdfV[i].Dat; }
if (Sum <= 0.0) { return; }
for (int i = 0; i < PdfV.Len(); i++) {
PdfV[i].Dat /= Sum; }
}
void TGUtil::MakeExpBins(const TFltPrV& XYValV, TFltPrV& ExpXYValV, const double& BinFactor, const double& MinYVal) {
TGnuPlot::MakeExpBins(XYValV, ExpXYValV, BinFactor, MinYVal);
}
void TGUtil::MakeExpBins(const TFltKdV& XYValV, TFltKdV& ExpXYValV, const double& BinFactor, const double& MinYVal) {
TGnuPlot::MakeExpBins(XYValV, ExpXYValV, BinFactor, MinYVal);
}
void TGUtil::MakeExpBins(const TFltV& YValV, TFltV& ExpYValV, const double& BinFactor) {
ExpYValV.Clr(true);
int prevI=0;
for (int i = 0; i < YValV.Len(); ) {
ExpYValV.Add(YValV[i]);
i = int(i*BinFactor);
if (i==prevI) { i++; }
prevI = i;
}
}
void TGUtil::MakeExpBins(const TIntV& YValV, TIntV& ExpYValV, const double& BinFactor) {
ExpYValV.Clr(true);
int prevI=0;
for (int i = 0; i < YValV.Len(); ) {
ExpYValV.Add(YValV[i]);
i = int(i*BinFactor);
if (i==prevI) { i++; }
prevI = i;
}
}
/////////////////////////////////////////////////
// String helper functions and utilities
// get <TagNm>TagVal</TagNm>
TChA& TStrUtil::GetXmlTagVal(TXmlLx& XmlLx, const TChA& TagNm) {
static TChA TagVal;
EAssertR(XmlLx.GetSym() == xsySTag, TagNm);
EAssertR(TagNm == XmlLx.TagNm.CStr(), TagNm);
const TXmlLxSym NextSym = XmlLx.GetSym();
TagVal = XmlLx.TxtChA;
if (NextSym == xsyStr) {
EAssertR(XmlLx.GetSym() == xsyETag, TagNm);
} else {
EAssertR(NextSym == xsyETag, TagNm); // empty tag
//printf(" token: %s empty! %s\n", XmlLx.TagNm.CStr(), XmlLx.GetFPosStr().CStr());
}
EAssertR(XmlLx.TagNm == TagNm, TagNm);
return TagVal;
}
// get <TagNm>TagVal</TagNm>
void TStrUtil::GetXmlTagNmVal(TXmlLx& XmlLx, TChA& TagNm, TChA& TagVal) {
EAssertR(XmlLx.GetSym() == xsySTag, TagNm);
TagNm = XmlLx.TagNm;
const TXmlLxSym NextSym = XmlLx.GetSym();
TagVal = XmlLx.TxtChA;
if (NextSym == xsyStr) {
EAssertR(XmlLx.GetSym() == xsyETag, TagNm);
} else {
EAssertR(NextSym == xsyETag, TagNm); // empty tag
//printf(" token: %s empty! %s\n", XmlLx.TagNm.CStr(), XmlLx.GetFPosStr().CStr());
}
}
// get <TagNm>*</TagNm> (can be many tags inbetween
bool TStrUtil::GetXmlTagNmVal2(TXmlLx& XmlLx, TChA& TagNm, TChA& TagVal, const bool& TakeTagNms) {
if (XmlLx.GetSym() != xsySTag) {
return false; }
TagVal.Clr();
TagNm = XmlLx.TagNm;
//const TXmlLxSym NextSym = XmlLx.GetSym();
while (XmlLx.Sym != xsyETag || XmlLx.TagNm != TagNm.CStr()) {
if (TakeTagNms) {
TagVal += XmlLx.TxtChA; }
else if (XmlLx.Sym == xsyStr) {
TagVal += XmlLx.TxtChA; }
XmlLx.GetSym();
}
return true;
//if (NextSym == xsyStr) {
// EAssertR(XmlLx.GetSym() == xsyETag, TagNm);
//} else {
// EAssertR(NextSym == xsyETag, TagNm); // empty tag
// printf(" token: %s empty! %s\n", XmlLx.TagNm.CStr(), XmlLx.GetFPosStr().CStr());
//}
}
// http://www.ijs.si/fdfd/blah.html --> www.ijs.si
TChA TStrUtil::GetDomNm(const TChA& UrlChA) {
int EndSlash = UrlChA.SearchCh('/', 7)-1; // skip starting http://
if (EndSlash > 0) {
const int BegSlash = UrlChA.SearchChBack('/', EndSlash);
if (BegSlash > 0) { return UrlChA.GetSubStr(BegSlash+1, EndSlash).ToLc(); }
else { return UrlChA.GetSubStr(0, UrlChA.SearchCh('/', 0)-1).ToLc(); }
} else {
if (UrlChA.IsPrefix("http://")) { return UrlChA.GetSubStr(7, UrlChA.Len()-1).ToLc(); }
EndSlash = UrlChA.SearchCh('/', 0);
if (EndSlash > 0) { return UrlChA.GetSubStr(0, EndSlash-1).ToLc(); }
else { return TChA(UrlChA).ToLc(); }
}
}
// get domain name and also strip starting www.
TChA TStrUtil::GetDomNm2(const TChA& UrlChA) {
TChA Dom = GetDomNm(UrlChA);
if (Dom.IsPrefix("www.")) { return Dom.GetSubStr(4, TInt::Mx); }
else { return Dom; }
}
int GetNthOccurence(const TChA& Url, const int& Count, const char Ch='/') {
const char *c = Url.CStr();
int cnt = 0;
while (*c && cnt != Count) {
if (*c == Ch) { cnt++; }
c++;
}
return int(c-Url.CStr()-1);
}
// get website (GetDomNm2 or blog url)
TChA TStrUtil::GetWebsiteNm(const TChA& PostUrlStr) {
TChA DomNm = TStrUtil::GetDomNm2(PostUrlStr);
// http://blog.myspace.com/index.cfm?fuseaction=blog.view&friendid=141560&blogid=420009539
if (DomNm == "blog.myspace.com") {
return PostUrlStr.GetSubStr(7, GetNthOccurence(PostUrlStr, 2, '&')-1);
}
// For these websites take the domain name and 1st directory: http://blogs.msdn.com/squasta
// http://blogs.msdn.com/squasta/archive/2008/08/11/annonces-microsoft-au-black-hat-2008.aspx
// http://ameblo.jp/baptism/entry-10126216277.html
// http://xfruits.com/fcuignet/?id=8793&clic=249862689&url=http%3a%2f%2fnews.google.com%2fnews%2furl%3fsa%3dt%26ct%3dfr%2f9-0%26fd%3dr%26url%3dhttp%3a%2f%2fwww.investir-en-tunisie.net%2fnews%2farticle.php%253fid%253d5026%26cid%3d1241943065%26ei%3doy6gslh9jzycxahkjfxucw%26usg%3dafqjcnen_bczqldodsyga6zps2axphxl3q
// http://scienceblogs.com/grrlscientist/2008/08/reader_comments.php
// http://blogs.sun.com/geertjan/entry/wicket_in_action_undoubtedly_the
// http://blog.wired.com/gadgets/2008/08/apple-sells-60.html
// http://weblogs.asp.net/mehfuzh/archive/2008/08/11/linqextender-1-4-enhanced-object-tracking.aspx
// http://blogs.technet.com/plitpromicrosoftcom/archive/2008/08/11/nowa-karta-sim.aspx
// http://blogs.guardian.co.uk/greenslade/2008/08/murdoch_aims_to_boost_subscrib.html
// http://blogs.clarin.com/quimeykiltru/2008/8/11/mentira-mentira-creo
// http://blogs.sun.com/geertjan/entry/wicket_in_action_undoubtedly_the
// http://blog.wired.com/gadgets/2008/08/apple-sells-60.html
// http://weblogs.asp.net/mehfuzh/archive/2008/08/11/linqextender-1-4-enhanced-object-tracking.aspx
// http://blogs.technet.com/plitpromicrosoftcom/archive/2008/08/11/nowa-karta-sim.aspx
// http://blogs.guardian.co.uk/greenslade/2008/08/murdoch_aims_to_boost_subscrib.html
// http://blogs.clarin.com/quimeykiltru/2008/8/11/mentira-mentira-creo
// http://blogs.zdnet.com/hardware/?p=2391
// http://blogs.citypages.com/sports/2008/08/ufc_87_seek_and.php
// http://voices.washingtonpost.com/achenblog/2008/08/no_medal_for_bush.html
// http://blog.tv2.dk/ole.mork/entry254689.html
// http://blogs.menomoneefallsnow.com/in_the_race/archive/2008/08/11/sometimes-it-s-about-how-you-play-the-game.asp
// http://weblogs.baltimoresun.com/entertainment/midnight_sun/blog/2008/08/heidis_bad_break_with_dubai_pa.html
// http://eonline.com/uberblog/b23076_youtubular_from_rickrolled_barackrolled.html?sid=rss_topstories&utm_source=eo
if (DomNm=="blogs.msdn.com" || DomNm=="ameblo.jp" || DomNm=="xfruits.com" || DomNm=="scienceblogs.com" || DomNm=="blogs.sun.com"
|| DomNm=="blog.wired.com" || DomNm=="weblogs.asp.net" || DomNm=="blogs.technet.com" || DomNm=="blogs.guardian.co"
|| DomNm=="blogs.clarin.com" || DomNm=="blogs.sun.com" || DomNm=="blog.wired.com" || DomNm=="weblogs.asp.net"
|| DomNm=="blogs.technet.com" || DomNm=="blogs.guardian.com" || DomNm=="blogs.clarin.com" || DomNm=="blogs.zdnet.com"
|| DomNm=="blogs.citypages.com" || DomNm=="voices.washingtonpost.com" || DomNm=="blog.tv2.dk"
|| DomNm=="blogs.menomoneefallsnow.com" || DomNm=="weblogs.baltimoresun.com" || DomNm=="eonline.com") {
return PostUrlStr.GetSubStr(7, GetNthOccurence(PostUrlStr, 4)-1);
}
// http://digg.com/submit?phase=2&url=http://socialitelife.celebuzz.com/archive/2008/07/31/and_then_a_hero_came_along.php&title=and
// http://digg.com/general_sciences/mental_images_are_like_pictures_slide_show
if (DomNm == "digg.com") {
if (PostUrlStr.IsPrefix("http://digg.com/submit?")) {
const int Url = PostUrlStr.SearchStr(";url=");
if (Url != -1) {
return GetWebsiteNm(PostUrlStr.GetSubStr(Url+5, PostUrlStr.SearchCh('&', Url+5))); }
} else {
return PostUrlStr.GetSubStr(7, GetNthOccurence(PostUrlStr, 4)-1); }
}
// For these websites take the domain name and 2 directories: http://bbc.co.uk/blogs/thereporters/
// http://bbc.co.uk/blogs/thereporters/markdevenport/2008/08/back_to_porridge.html
// http://nydailynews.com/blogs/subwaysquawkers/2008/08/anaheim-is-no-magic-kingdom-fo.html
// http://newsbusters.org/blogs/p-j-gladnick/2008/08/11/sf-chronicle-writer-predicts-global-warming-shellfish-invas
// http://nydailynews.com/blogs/subwaysquawkers/2008/08/anaheim-is-no-magic-kingdom-fo.html
if (PostUrlStr.IsPrefix("http://nydailynews.com/blogs/") || PostUrlStr.IsPrefix("http://bbc.co.uk/blogs/")
|| PostUrlStr.IsPrefix("http://nydailynews.com/blogs/") || PostUrlStr.IsPrefix("http://newsbusters.org/blogs/")) {
return PostUrlStr.GetSubStr(7, GetNthOccurence(PostUrlStr, 5)-1);
}
// http://feeds.feedburner.com/~r/adesblog/ ~3/361711640
if (DomNm=="feeds.feedburner.com") {
return PostUrlStr.GetSubStr(7, GetNthOccurence(PostUrlStr, 5)-1);
}
// http://groups.google.com/group/news.admin.net-abuse.sightings/browse_thread/thread/8452c47949453216/f07daa509b90295c?show_docid=f07daa509b90295c
if (DomNm=="groups.google.com") {
return PostUrlStr.GetSubStr(7, GetNthOccurence(PostUrlStr, 5)-1);
}
// http://news.google.com/news/url?sa=t&ct=us/20-0&fd=r&url=http://www.theobserver.ca/articledisplay.aspx%3fe%3d1151495&cid=0&ei=yswgsjpndpbi8atc9knacw&usg=afqjcnhrbg-nc9z6ymtqfkear3_npwqqxa
if (DomNm=="news.google.com") { // redirect
const int UrlPos = PostUrlStr.SearchStr("&url=");
if (UrlPos != -1) {
return GetWebsiteNm(PostUrlStr.GetSubStr(UrlPos+5, PostUrlStr.SearchCh('&', UrlPos+5))); }
}
// http://bloggrevyen.no/go/110340/http://blog.christergulbrandsen.com/2008/08/11/is-nationalism-the-only-way-to-de
if (DomNm == "bloggrevyen.no") { // redirect
const int Http2 = PostUrlStr.SearchStr("/http://");
if (Http2!=-1) {
return GetWebsiteNm(PostUrlStr.GetSubStr(Http2+1, PostUrlStr.Len()-1)); }
}
//http://us.rd.yahoo.com/dailynews/rss/search/urgent+care/sig=11phgb4tu/*http%3a//www.newswise.com/articles/view/543340/?sc=rsmn
//http://ca.rd.yahoo.com/dailynews/rss/topstories/*http://ca.news.yahoo.com/s/reuters/080801/n_top_news/news_afgha
if (DomNm.IsSuffix(".rd.yahoo.com")) {
const int Http2 = PostUrlStr.SearchStr("/*");
if (Http2!=-1) {
return GetWebsiteNm(PostUrlStr.GetSubStr(Http2+9, PostUrlStr.Len()-1)); }
}
return DomNm;
}
/// Quick URL nomalization: Remove ending /, /index.html, etc. and strip starting www.
bool TStrUtil::GetNormalizedUrl(const TChA& UrlIn, const TChA& BaseUrl, TChA& UrlOut) {
UrlOut = UrlIn;
if (StripEnd(UrlIn, "/", UrlOut)) {}
else if (StripEnd(UrlIn, "/index.html", UrlOut)) {}
else if (StripEnd(UrlIn, "/index.htm", UrlOut)) {}
else if (StripEnd(UrlIn, "/index.php", UrlOut)) {}
if (! (UrlOut.IsPrefix("http://") || UrlOut.IsPrefix("ftp://"))) {
// if UrlIn is relative url, try combine it with BaseUrl
if (UrlIn.Empty() || ! (BaseUrl.IsPrefix("http://") || BaseUrl.IsPrefix("ftp://"))) {
//printf("** Bad URL: base:'%s' url:'%s'\n", BaseUrl.CStr(), UrlIn.CStr());
return false; }
TChA Out;
if (! GetNormalizedUrl(BaseUrl, TChA(), Out)) { return false; }
if (UrlIn[0] != '/') { Out.AddCh('/'); }
Out += UrlOut;
UrlOut = Out;
}
// http://www. --> http://
if (UrlOut.IsPrefix("http://www.")) {
UrlOut = TChA("http://") + UrlOut.GetSubStr(11, TInt::Mx);
}
UrlOut.ToLc();
return true;
}
bool TStrUtil::StripEnd(const TChA& Str, const TChA& SearchStr, TChA& NewStr) {
const int StrLen = Str.Len();
const int SearchStrLen = SearchStr.Len();
if (StrLen < SearchStrLen) { return false; }
for (int i = 0; i < SearchStrLen; i++) {
if (Str[StrLen-i-1] != SearchStr[SearchStrLen-i-1]) { return false; }
}
NewStr = Str.GetSubStr(0, StrLen-SearchStrLen-1);
return true;
}
TChA TStrUtil::GetShorStr(const TChA& LongStr, const int MaxLen) {
if (LongStr.Len() < MaxLen) { return LongStr; }
TChA Str = LongStr.GetSubStr(0, MaxLen-1);
Str += "...";
return Str;
}
// space separated sequence of words, remove all punctuations, etc.
TChA TStrUtil::GetCleanWrdStr(const TChA& ChA) {
char *b = (char *) ChA.CStr();
while (*b && ! TCh::IsAlNum(*b)) { b++; }
if (*b == 0) { return TChA(); }
TChA OutChA(ChA.Len());
char *e = b, tmp;
while (*e) {
b = e;
while (*e && (TCh::IsAlNum(*e) || ((*e=='\'' || *e=='-') && TCh::IsAlNum(*(e+1))))) { e++; }
if (b < e) {
tmp = *e; *e=0;
OutChA += b; OutChA.AddCh(' ');
*e = tmp;
}
while (*e && ! TCh::IsAlNum(*e)) { e++; }
if (! *e) { break; }
}
OutChA.DelLastCh(); OutChA.ToLc();
return OutChA;
}
// space seprated sequence of words (includes all non-blank characters, i.e., punctuations)
TChA TStrUtil::GetCleanStr(const TChA& ChA) {
char *b = (char *) ChA.CStr();
while (*b && ! TCh::IsAlNum(*b)) { b++; }
if (*b == 0) { return TChA(); }
TChA OutChA(ChA.Len());
char *e = b;
bool ws=false;
while (*e) {
while (*e && TCh::IsWs(*e)) { e++; ws=true; }
if (! *e) { break; }
if (ws) { OutChA.AddCh(' '); ws=false; }
OutChA.AddCh(*e);
e++;
}
//OutChA.ToLc();
return OutChA;
}
int TStrUtil::CountWords(const TChA& ChA) {
return CountWords(ChA.CStr());
}
int TStrUtil::CountWords(const char* CStr) {
int WrdCnt = 1;
for (const char *c = CStr; *c; c++) {
if (TCh::IsWs(*c)) { WrdCnt++; }
}
return WrdCnt;
}
int TStrUtil::CountWords(const TChA& ChA, const TStrHash<TInt>& StopWordH) {
TChA Tmp;
TVec<char *> WrdV;
SplitWords(Tmp, WrdV);
int SWordCnt = 0;
for (int w = 0; w < WrdV.Len(); w++) {
if (StopWordH.IsKey(WrdV[w])) { SWordCnt++; }
}
return WrdV.Len() - SWordCnt;
}
int TStrUtil::SplitWords(TChA& ChA, TVec<char *>& WrdV, const bool& SplitOnWs) {
WrdV.Clr(false);
WrdV.Add(ChA.CStr());
for (char *c = (char *) ChA.CStr(); *c; c++) {
if ((SplitOnWs && *c == ' ') || (! SplitOnWs && ! TCh::IsAlNum(*c))) {
*c = 0;
if (! WrdV.Empty() && strlen(WrdV.Last()) == 0) { WrdV.DelLast(); }
WrdV.Add(c+1);
}
}
return WrdV.Len();
}
int TStrUtil::SplitOnCh(TChA& ChA, TVec<char *>& WrdV, const char& Ch, const bool& SkipEmpty) {
WrdV.Clr(false);
WrdV.Add(ChA.CStr());
for (char *c = (char *) ChA.CStr(); *c; c++) {
if (*c == Ch) {
*c = 0;
if (SkipEmpty && ! WrdV.Empty() && strlen(WrdV.Last()) == 0) { WrdV.DelLast(); }
WrdV.Add(c+1);
}
}
if (SkipEmpty && ! WrdV.Empty() && strlen(WrdV.Last()) == 0) { WrdV.DelLast(); }
return WrdV.Len();
}
int TStrUtil::SplitLines(TChA& ChA, TVec<char *>& LineV, const bool& SkipEmpty) {
LineV.Clr(false);
LineV.Add(ChA.CStr());
bool IsChs=false;
for (char *c = (char *) ChA.CStr(); *c; c++) {
if (*c == '\n') {
if (c > ChA.CStr() && *(c-1)=='\r') { *(c-1)=0; } // \r\n
*c=0;
if (SkipEmpty) {
if (IsChs) { LineV.Add(c+1); }
} else {
LineV.Add(c+1);
}
IsChs=false;
} else {
IsChs=true;
}
}
return LineV.Len();
}
int TStrUtil::SplitSentences(TChA& ChA, TVec<char *>& SentenceV) {
SentenceV.Clr();
const char *B = ChA.CStr();
const char *E = B+ChA.Len();
char *c = (char *) B;
while (*c && TCh::IsWs(*c)) { c++; }
if (*c) { SentenceV.Add(c); } else { return 0; }
for (; c < E; c++) {
if (c<E && (*c == '.' || *c == '!' || *c == '?') && ! TCh::IsAlNum(*(c+1))) { // end of sentence
if (c<E && *(c+1)=='"') { *c='"'; c++; } // blah." --> blah"
if (c>=E) { continue; }
*c=0; c++;
char *e = c-1;
while (e>B && *e!='"' && ! TCh::IsAlNum(*e)) { *e=0; e--; } // skip trailing non-alpha-num chars
while (c<E && ! (TCh::IsAlNum(*c) || (*c=='"' && TCh::IsAlNum(*(c+1))))) { c++; } // sentence starts with AlNum or "AlNum
if (c<E) { SentenceV.Add(c); }
}
}
return SentenceV.Len();
}
void TStrUtil::RemoveHtmlTags(const TChA& HtmlStr, TChA& TextStr) {
TextStr.Clr();
char *StrB, *StrE;
// use full page html: skip till <body>
//PageHtmlStr = "<script fdsfs> fsdfsd </script> jure";
/*if (UseFullHtml) {
StrB = PageHtmlStr.CStr();
StrE = StrB+PageHtmlStr.Len();
char * NewB = strstr(StrB, "<body>");
if (NewB != NULL) { StrB = NewB+6; }
char * NewE = strstr(StrB, "body>");
if (NewE != NULL) {
while (true) {
char *E=strstr(NewE+4, "body>");
if (E == NULL) { break; } NewE = E; }
StrE = NewE;
}
} else { // only extracted post html*/
StrB = (char *) HtmlStr.CStr();
StrE = (char *) StrB+HtmlStr.Len(); //}
for (char *e = StrB; e < StrE; ) {
char* b = e;
while (e<StrE && *e != '<') { e++; }
// copy text
char tmp=*e; *e = 0;
TextStr+= b; TextStr.AddCh(' '); *e = tmp;
if (e >= StrE) { return; }
// if start of a comment: skip
if (e[1]=='!' && e[2]=='-' && e[3]=='-') { // comment
e += 3;
while(e<StrE && !(*(e-2)=='-' && *(e-1)=='-' && *e=='>')) { e++; }
e++; continue;
}
// if "<script" then skip
if (e[1]=='s' && e[2]=='c' && e[3]=='r' && e[4]=='i' && e[5]=='p' && e[6]=='t') {
e += 5;
while(e<StrE && !(*(e-6)=='s' && *(e-5)=='c' && *(e-4)=='r' && *(e-3)=='i' && *(e-2)=='p' && *(e-1)=='t' && *e=='>')) { e++; }
e++; continue;
}
// skip to end of tag
while (e < StrE && *e != '>') { e++; }
if (e>=StrE) { return; }
e++;
}
}
bool TStrUtil::IsLatinStr(const TChA& Str, const double& MinAlFrac) {
int AlNumCnt=0, ChCnt=0;
for (const char *c = Str.CStr(); *c; c++) {
if (TCh::IsWs(*c)) { continue; }
if (*c > 0 && TCh::IsAlNum(*c)) { AlNumCnt++; }
ChCnt++;
}
if (double(AlNumCnt)/double(ChCnt) > MinAlFrac) { return true; }
return false;
}
void TStrUtil::GetWIdV(const TStrHash<TInt>& StrH, const char *CStr, TIntV& WIdV) {
const int NotWId = -1;
TChA ChA(CStr);
TVec<char *> WrdV;
TInt WId;
TStrUtil::SplitWords(ChA, WrdV);
WIdV.Clr(false);
for (int w = 0; w < WrdV.Len(); w++) {
if (StrH.IsKeyGetDat(WrdV[w], WId)) { WIdV.Add(WId); }
else { WIdV.Add(NotWId); }
}
}
// and words to StrH and get a vector of word ids
void TStrUtil::GetAddWIdV(TStrHash<TInt>& StrH, const char *CStr, TIntV& WIdV) {
TChA ChA(CStr);
TVec<char *> WrdV;
TInt WId;
TStrUtil::SplitWords(ChA, WrdV);
WIdV.Clr(false);
for (int w = 0; w < WrdV.Len(); w++) {
WIdV.Add(StrH.AddDatId(WrdV[w]));
}
}
// Parse time in various formats:
// 10:16, 16 Sep 2004
// 10:20, 2004 Sep 16
// 2005-07-07 20:30:35
// 23:24:07, 2005-07-10
// 9 July 2005 14:38
// 21:16, July 9, 2005
// 06:02, 10 July 2005
bool TStrUtil::GetTmFromStr(const char* TmStr, TSecTm& Tm) {
static TStrV MonthV1, MonthV2;
if (MonthV1.Empty()) {
TStr("january|february|march|april|may|june|july|august|september|october|november|december").SplitOnAllCh('|', MonthV1);
TStr("jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec").SplitOnAllCh('|', MonthV2);
}
TChA Tmp(TmStr);
Tmp.ToLc();
TVec<char *> WrdV;
const char* End = Tmp.CStr()+Tmp.Len();
int Col = -1, Cols=0;
for (char *b = Tmp.CStr(); b <End; ) {
WrdV.Add(b);
while (*b && ! (*b==' ' || *b=='-' || *b==':' || *b==',')) { b++; }
if (*b==':') { if(Col==-1) { Col=WrdV.Len(); } Cols++; }
*b=0; b++;
while (*b && (*b==' ' || *b=='-' || *b==':' || *b==',')) { b++; }
}
if (Cols == 2) {
if (Col+1 >= WrdV.Len()) { return false; }
WrdV.Del(Col+1);
}
if (Col<1) { return false; }
const int Hr = atoi(WrdV[Col-1]);
const int Min = atoi(WrdV[Col]);
WrdV.Del(Col); WrdV.Del(Col-1);
if (WrdV.Len() != 3) { return false; }
int y=0,m=1,d=2, Mon=-1;
if (TCh::IsAlpha(WrdV[0][0])) {
y=2; m=0; d=1;
} else if (TCh::IsAlpha(WrdV[1][0])) {
y=2; m=1; d=0;
} else if (TCh::IsAlpha(WrdV[2][0])) {
y=0; m=2; d=1;
} else {
y=0; m=1; d=2;
Mon = atoi(WrdV[m]);
}
int Day = atoi(WrdV[d]);
if (Mon <= 0) { Mon = MonthV1.SearchForw(WrdV[m])+1; }
if (Mon <= 0) { Mon = MonthV2.SearchForw(WrdV[m])+1; }
if (Mon == 0) { return false; }
int Year = atoi(WrdV[y]);
if (Day > Year) { ::Swap(Day, Year); }
//printf("%d-%02d-%02d %02d:%02d\n", Year, Mon, Day, Hr, Min);
Tm = TSecTm(Year, Mon, Day, Hr, Min, 0);
return true;
}
// Standardize first and lastnames into <last_name>_<first name innitial>
TStr TStrUtil::GetStdName(TStr AuthorName) {
TStr StdName;
AuthorName.ToLc();
AuthorName.ChangeChAll('\n', ' ');
AuthorName.ChangeChAll('.', ' ');
// if there is a number in the name, remove it and everything after it
int i, pos = 0;
while (pos<AuthorName.Len() && (AuthorName[pos]!='#' && !TCh::IsNum(AuthorName[pos]))) {
pos++; }
if (pos < AuthorName.Len()) {
AuthorName = AuthorName.GetSubStr(0, pos-1).ToTrunc(); }
if (AuthorName.Empty()) { return TStr::GetNullStr(); }
// replace everything after '('
int b = AuthorName.SearchCh('(');
if (b != -1) {
AuthorName = AuthorName.GetSubStr(0, b-1).ToTrunc(); }
// skip if contains ')'
if (AuthorName .SearchCh(')')!=-1) { return TStr::GetNullStr(); }
// skip if it is not a name
if (AuthorName .SearchStr("figures")!=-1 || AuthorName .SearchStr("macros")!=-1
|| AuthorName .SearchStr("univ")!=-1 || AuthorName .SearchStr("institute")!=-1) {
return TStr::GetNullStr();
}
// remove all non-letters (latex tags, ...)
TChA NewName;
for (i = 0; i < AuthorName.Len(); i++) {
const char Ch = AuthorName[i];
if (TCh::IsAlpha(Ch) || TCh::IsWs(Ch) || Ch=='-') { NewName += Ch; }
}
StdName = NewName; StdName.ToTrunc();
TStrV AuthNmV; StdName.SplitOnWs(AuthNmV);
// too short -- not a name
if (! AuthNmV.Empty() && AuthNmV.Last() == "jr") AuthNmV.DelLast();
if (AuthNmV.Len() < 2) return TStr::GetNullStr();
const TStr LastNm = AuthNmV.Last();
if (! TCh::IsAlpha(LastNm[0]) || LastNm.Len() == 1) return TStr::GetNullStr();
IAssert(isalpha(AuthNmV[0][0]));
return TStr::Fmt("%s_%c", LastNm.CStr(), AuthNmV[0][0]);
}
void TStrUtil::GetStdNameV(TStr AuthorNames, TStrV& StdNameV) {
AuthorNames.ChangeChAll('\n', ' ');
AuthorNames.ToLc();
// split into author names
TStrV AuthV, TmpV, Tmp2V;
// split on 'and'
AuthorNames.SplitOnStr(" and ", TmpV);
int i;
for (i = 0; i < TmpV.Len(); i++) {
TmpV[i].SplitOnAllCh(',', Tmp2V); AuthV.AddV(Tmp2V); }
// split on '&'
TmpV = AuthV; AuthV.Clr();
for (i = 0; i < TmpV.Len(); i++) {
TmpV[i].SplitOnAllCh('&', Tmp2V); AuthV.AddV(Tmp2V); }
// split on ','
TmpV = AuthV; AuthV.Clr();
for (i = 0; i < TmpV.Len(); i++) {
TmpV[i].SplitOnAllCh(',', Tmp2V); AuthV.AddV(Tmp2V); }
// split on ';'
TmpV = AuthV; AuthV.Clr();
for (i = 0; i < TmpV.Len(); i++) {
TmpV[i].SplitOnAllCh(';', Tmp2V); AuthV.AddV(Tmp2V); }
// standardize names
StdNameV.Clr();
//printf("\n*** %s\n", AuthorNames.CStr());
for (i = 0; i < AuthV.Len(); i++) {
TStr StdName = GetStdName(AuthV[i]);
if (! StdName.Empty()) {
//printf("\t%s ==> %s\n", AuthV[i].CStr(), StdName.CStr());
StdNameV.Add(StdName);
}
}
}
| 37.449067 | 315 | 0.587503 | [
"object",
"vector"
] |
8b3eda36eb0e77b681de960d8c3e63593a5045b0 | 12,001 | cpp | C++ | aws-cpp-sdk-ec2/source/model/ScheduledInstance.cpp | bswhite1/aws-sdk-cpp | a050168cf8f7f6ea920d52894eaad186953cb27b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/source/model/ScheduledInstance.cpp | bswhite1/aws-sdk-cpp | a050168cf8f7f6ea920d52894eaad186953cb27b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/source/model/ScheduledInstance.cpp | bswhite1/aws-sdk-cpp | a050168cf8f7f6ea920d52894eaad186953cb27b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/ec2/model/ScheduledInstance.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
ScheduledInstance::ScheduledInstance() :
m_availabilityZoneHasBeenSet(false),
m_createDateHasBeenSet(false),
m_hourlyPriceHasBeenSet(false),
m_instanceCount(0),
m_instanceCountHasBeenSet(false),
m_instanceTypeHasBeenSet(false),
m_networkPlatformHasBeenSet(false),
m_nextSlotStartTimeHasBeenSet(false),
m_platformHasBeenSet(false),
m_previousSlotEndTimeHasBeenSet(false),
m_recurrenceHasBeenSet(false),
m_scheduledInstanceIdHasBeenSet(false),
m_slotDurationInHours(0),
m_slotDurationInHoursHasBeenSet(false),
m_termEndDateHasBeenSet(false),
m_termStartDateHasBeenSet(false),
m_totalScheduledInstanceHours(0),
m_totalScheduledInstanceHoursHasBeenSet(false)
{
}
ScheduledInstance::ScheduledInstance(const XmlNode& xmlNode) :
m_availabilityZoneHasBeenSet(false),
m_createDateHasBeenSet(false),
m_hourlyPriceHasBeenSet(false),
m_instanceCount(0),
m_instanceCountHasBeenSet(false),
m_instanceTypeHasBeenSet(false),
m_networkPlatformHasBeenSet(false),
m_nextSlotStartTimeHasBeenSet(false),
m_platformHasBeenSet(false),
m_previousSlotEndTimeHasBeenSet(false),
m_recurrenceHasBeenSet(false),
m_scheduledInstanceIdHasBeenSet(false),
m_slotDurationInHours(0),
m_slotDurationInHoursHasBeenSet(false),
m_termEndDateHasBeenSet(false),
m_termStartDateHasBeenSet(false),
m_totalScheduledInstanceHours(0),
m_totalScheduledInstanceHoursHasBeenSet(false)
{
*this = xmlNode;
}
ScheduledInstance& ScheduledInstance::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode availabilityZoneNode = resultNode.FirstChild("availabilityZone");
if(!availabilityZoneNode.IsNull())
{
m_availabilityZone = availabilityZoneNode.GetText();
m_availabilityZoneHasBeenSet = true;
}
XmlNode createDateNode = resultNode.FirstChild("createDate");
if(!createDateNode.IsNull())
{
m_createDate = DateTime(StringUtils::Trim(createDateNode.GetText().c_str()).c_str(), DateFormat::ISO_8601);
m_createDateHasBeenSet = true;
}
XmlNode hourlyPriceNode = resultNode.FirstChild("hourlyPrice");
if(!hourlyPriceNode.IsNull())
{
m_hourlyPrice = hourlyPriceNode.GetText();
m_hourlyPriceHasBeenSet = true;
}
XmlNode instanceCountNode = resultNode.FirstChild("instanceCount");
if(!instanceCountNode.IsNull())
{
m_instanceCount = StringUtils::ConvertToInt32(StringUtils::Trim(instanceCountNode.GetText().c_str()).c_str());
m_instanceCountHasBeenSet = true;
}
XmlNode instanceTypeNode = resultNode.FirstChild("instanceType");
if(!instanceTypeNode.IsNull())
{
m_instanceType = instanceTypeNode.GetText();
m_instanceTypeHasBeenSet = true;
}
XmlNode networkPlatformNode = resultNode.FirstChild("networkPlatform");
if(!networkPlatformNode.IsNull())
{
m_networkPlatform = networkPlatformNode.GetText();
m_networkPlatformHasBeenSet = true;
}
XmlNode nextSlotStartTimeNode = resultNode.FirstChild("nextSlotStartTime");
if(!nextSlotStartTimeNode.IsNull())
{
m_nextSlotStartTime = DateTime(StringUtils::Trim(nextSlotStartTimeNode.GetText().c_str()).c_str(), DateFormat::ISO_8601);
m_nextSlotStartTimeHasBeenSet = true;
}
XmlNode platformNode = resultNode.FirstChild("platform");
if(!platformNode.IsNull())
{
m_platform = platformNode.GetText();
m_platformHasBeenSet = true;
}
XmlNode previousSlotEndTimeNode = resultNode.FirstChild("previousSlotEndTime");
if(!previousSlotEndTimeNode.IsNull())
{
m_previousSlotEndTime = DateTime(StringUtils::Trim(previousSlotEndTimeNode.GetText().c_str()).c_str(), DateFormat::ISO_8601);
m_previousSlotEndTimeHasBeenSet = true;
}
XmlNode recurrenceNode = resultNode.FirstChild("recurrence");
if(!recurrenceNode.IsNull())
{
m_recurrence = recurrenceNode;
m_recurrenceHasBeenSet = true;
}
XmlNode scheduledInstanceIdNode = resultNode.FirstChild("scheduledInstanceId");
if(!scheduledInstanceIdNode.IsNull())
{
m_scheduledInstanceId = scheduledInstanceIdNode.GetText();
m_scheduledInstanceIdHasBeenSet = true;
}
XmlNode slotDurationInHoursNode = resultNode.FirstChild("slotDurationInHours");
if(!slotDurationInHoursNode.IsNull())
{
m_slotDurationInHours = StringUtils::ConvertToInt32(StringUtils::Trim(slotDurationInHoursNode.GetText().c_str()).c_str());
m_slotDurationInHoursHasBeenSet = true;
}
XmlNode termEndDateNode = resultNode.FirstChild("termEndDate");
if(!termEndDateNode.IsNull())
{
m_termEndDate = DateTime(StringUtils::Trim(termEndDateNode.GetText().c_str()).c_str(), DateFormat::ISO_8601);
m_termEndDateHasBeenSet = true;
}
XmlNode termStartDateNode = resultNode.FirstChild("termStartDate");
if(!termStartDateNode.IsNull())
{
m_termStartDate = DateTime(StringUtils::Trim(termStartDateNode.GetText().c_str()).c_str(), DateFormat::ISO_8601);
m_termStartDateHasBeenSet = true;
}
XmlNode totalScheduledInstanceHoursNode = resultNode.FirstChild("totalScheduledInstanceHours");
if(!totalScheduledInstanceHoursNode.IsNull())
{
m_totalScheduledInstanceHours = StringUtils::ConvertToInt32(StringUtils::Trim(totalScheduledInstanceHoursNode.GetText().c_str()).c_str());
m_totalScheduledInstanceHoursHasBeenSet = true;
}
}
return *this;
}
void ScheduledInstance::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_availabilityZoneHasBeenSet)
{
oStream << location << index << locationValue << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
if(m_createDateHasBeenSet)
{
oStream << location << index << locationValue << ".CreateDate=" << StringUtils::URLEncode(m_createDate.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_hourlyPriceHasBeenSet)
{
oStream << location << index << locationValue << ".HourlyPrice=" << StringUtils::URLEncode(m_hourlyPrice.c_str()) << "&";
}
if(m_instanceCountHasBeenSet)
{
oStream << location << index << locationValue << ".InstanceCount=" << m_instanceCount << "&";
}
if(m_instanceTypeHasBeenSet)
{
oStream << location << index << locationValue << ".InstanceType=" << StringUtils::URLEncode(m_instanceType.c_str()) << "&";
}
if(m_networkPlatformHasBeenSet)
{
oStream << location << index << locationValue << ".NetworkPlatform=" << StringUtils::URLEncode(m_networkPlatform.c_str()) << "&";
}
if(m_nextSlotStartTimeHasBeenSet)
{
oStream << location << index << locationValue << ".NextSlotStartTime=" << StringUtils::URLEncode(m_nextSlotStartTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_platformHasBeenSet)
{
oStream << location << index << locationValue << ".Platform=" << StringUtils::URLEncode(m_platform.c_str()) << "&";
}
if(m_previousSlotEndTimeHasBeenSet)
{
oStream << location << index << locationValue << ".PreviousSlotEndTime=" << StringUtils::URLEncode(m_previousSlotEndTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_recurrenceHasBeenSet)
{
Aws::StringStream recurrenceLocationAndMemberSs;
recurrenceLocationAndMemberSs << location << index << locationValue << ".Recurrence";
m_recurrence.OutputToStream(oStream, recurrenceLocationAndMemberSs.str().c_str());
}
if(m_scheduledInstanceIdHasBeenSet)
{
oStream << location << index << locationValue << ".ScheduledInstanceId=" << StringUtils::URLEncode(m_scheduledInstanceId.c_str()) << "&";
}
if(m_slotDurationInHoursHasBeenSet)
{
oStream << location << index << locationValue << ".SlotDurationInHours=" << m_slotDurationInHours << "&";
}
if(m_termEndDateHasBeenSet)
{
oStream << location << index << locationValue << ".TermEndDate=" << StringUtils::URLEncode(m_termEndDate.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_termStartDateHasBeenSet)
{
oStream << location << index << locationValue << ".TermStartDate=" << StringUtils::URLEncode(m_termStartDate.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_totalScheduledInstanceHoursHasBeenSet)
{
oStream << location << index << locationValue << ".TotalScheduledInstanceHours=" << m_totalScheduledInstanceHours << "&";
}
}
void ScheduledInstance::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_availabilityZoneHasBeenSet)
{
oStream << location << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
if(m_createDateHasBeenSet)
{
oStream << location << ".CreateDate=" << StringUtils::URLEncode(m_createDate.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_hourlyPriceHasBeenSet)
{
oStream << location << ".HourlyPrice=" << StringUtils::URLEncode(m_hourlyPrice.c_str()) << "&";
}
if(m_instanceCountHasBeenSet)
{
oStream << location << ".InstanceCount=" << m_instanceCount << "&";
}
if(m_instanceTypeHasBeenSet)
{
oStream << location << ".InstanceType=" << StringUtils::URLEncode(m_instanceType.c_str()) << "&";
}
if(m_networkPlatformHasBeenSet)
{
oStream << location << ".NetworkPlatform=" << StringUtils::URLEncode(m_networkPlatform.c_str()) << "&";
}
if(m_nextSlotStartTimeHasBeenSet)
{
oStream << location << ".NextSlotStartTime=" << StringUtils::URLEncode(m_nextSlotStartTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_platformHasBeenSet)
{
oStream << location << ".Platform=" << StringUtils::URLEncode(m_platform.c_str()) << "&";
}
if(m_previousSlotEndTimeHasBeenSet)
{
oStream << location << ".PreviousSlotEndTime=" << StringUtils::URLEncode(m_previousSlotEndTime.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_recurrenceHasBeenSet)
{
Aws::String recurrenceLocationAndMember(location);
recurrenceLocationAndMember += ".Recurrence";
m_recurrence.OutputToStream(oStream, recurrenceLocationAndMember.c_str());
}
if(m_scheduledInstanceIdHasBeenSet)
{
oStream << location << ".ScheduledInstanceId=" << StringUtils::URLEncode(m_scheduledInstanceId.c_str()) << "&";
}
if(m_slotDurationInHoursHasBeenSet)
{
oStream << location << ".SlotDurationInHours=" << m_slotDurationInHours << "&";
}
if(m_termEndDateHasBeenSet)
{
oStream << location << ".TermEndDate=" << StringUtils::URLEncode(m_termEndDate.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_termStartDateHasBeenSet)
{
oStream << location << ".TermStartDate=" << StringUtils::URLEncode(m_termStartDate.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_totalScheduledInstanceHoursHasBeenSet)
{
oStream << location << ".TotalScheduledInstanceHours=" << m_totalScheduledInstanceHours << "&";
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
| 36.477204 | 177 | 0.715274 | [
"model"
] |
8b40010a4be4e21f9bc7f92b17c8a4a8b7faa69b | 54,277 | cpp | C++ | dev/Code/Tools/Woodpecker/Woodpecker/LUA/LUAEditorFindDialog.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 8 | 2019-10-07T16:33:47.000Z | 2020-12-07T03:59:58.000Z | dev/Code/Tools/Woodpecker/Woodpecker/LUA/LUAEditorFindDialog.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | null | null | null | dev/Code/Tools/Woodpecker/Woodpecker/LUA/LUAEditorFindDialog.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "stdafx.h"
#include <AzCore/Script/ScriptAsset.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzCore/Component/TickBus.h>
#include "LUAEditorFindDialog.hxx"
#include "LUAEditorMainWindow.hxx"
#include "LUAEditorContextMessages.h"
#include "LUAEditorBlockState.h"
#include <Woodpecker/LUA/ui_LUAEditorFindDialog.h>
namespace LUAEditorInternal
{
// this stuff goes in the user preferences rather than the global stuff:
class FindSavedState
: public AZ::UserSettings
{
public:
AZ_RTTI(FindSavedState, "{2B880623-63A9-4B39-B8B9-47609590D7D2}", AZ::UserSettings);
AZ_CLASS_ALLOCATOR(FindSavedState, AZ::SystemAllocator, 0);
FindSavedState()
{
m_lastSearchInFilesMode = 0;
m_findWrap = true;
}
int m_lastSearchInFilesMode;
bool m_findWrap;
static void Reflect(AZ::ReflectContext* reflection)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection);
if (serializeContext)
{
serializeContext->Class<FindSavedState>()
->Field("m_lastSearchInFilesMode", &FindSavedState::m_lastSearchInFilesMode)
->Field("m_findWrap", &FindSavedState::m_findWrap);
}
}
};
}
namespace LUAEditor
{
extern AZ::Uuid ContextID;
//////////////////////////////////////////////////////////////////////////
//find dialog
// QDialog(/*parent*/) strip the parent from QDialog and this window will no longer be forced on top all the time
LUAEditorFindDialog::LUAEditorFindDialog(QWidget* parent)
: QDialog(parent)
{
pLUAEditorMainWindow = qobject_cast<LUAEditorMainWindow*>(parent);
AZ_Assert(pLUAEditorMainWindow, "Parent Widget is NULL or not the LUAEditorMainWindow!");
m_bAnyDocumentsOpen = false;
LUAViewMessages::Bus::Handler::BusConnect();
m_bWasFindInAll = false;
m_gui = azcreate(Ui::LUAEditorFindDialog, ());
m_gui->setupUi(this);
this->setFixedSize(this->size());
m_gui->searchDownRadioButton->setChecked(true);
m_gui->searchAndReplaceGroupBox->setChecked(false);
m_gui->regularExpressionCheckBox->setChecked(false);
auto pState = AZ::UserSettings::CreateFind<LUAEditorInternal::FindSavedState>(AZ_CRC("FindInCurrent", 0xba0962af), AZ::UserSettings::CT_LOCAL);
m_gui->wrapCheckBox->setChecked((pState ? pState->m_findWrap : true));
connect(m_gui->wrapCheckBox, &QCheckBox::stateChanged, this, [this](int newState)
{
auto pState = AZ::UserSettings::CreateFind<LUAEditorInternal::FindSavedState>(AZ_CRC("FindInCurrent", 0xba0962af), AZ::UserSettings::CT_LOCAL);
pState->m_findWrap = (newState == Qt::Checked);
});
m_bFoundFirst = false;
m_bLastForward = m_gui->searchDownRadioButton->isChecked();
m_bLastWrap = m_gui->wrapCheckBox->isChecked();
//stored dialog state for find/replace
m_bCaseSensitiveIsChecked = false;
m_bWholeWordIsChecked = false;
m_bRegExIsChecked = false;
//find in files stuff
m_bCancelFindSignal = false;
m_bFindThreadRunning = false;
//replace in files stuff
m_bCancelReplaceSignal = false;
m_bReplaceThreadRunning = false;
connect(m_gui->searchWhereComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnSearchWhereChanged(int)));
connect(this, SIGNAL(triggerFindInFilesNext(int)), this, SLOT(FindInFilesNext(int)), Qt::QueuedConnection);
connect(this, SIGNAL(triggerReplaceInFilesNext()), this, SLOT(ReplaceInFilesNext()), Qt::QueuedConnection);
connect(this, SIGNAL(triggerFindNextInView(LUAViewWidget::FindOperation*, LUAViewWidget*, QListWidget*)), this, SLOT(FindNextInView(LUAViewWidget::FindOperation*, LUAViewWidget*, QListWidget*)), Qt::QueuedConnection);
QString stylesheet(R"(QLabel[LUAEditorFindDialogLabel="true"],QGroupBox,QCheckBox,QRadioButton,QPushButton
{
font-size: 12px;
};
QLabel[IdleLabel="true"]
{
font-size:18px;
}
)");
setStyleSheet(stylesheet);
}
LUAViewWidget* LUAEditorFindDialog::GetViewFromParent()
{
LUAViewWidget* pLUAViewWidget = pLUAEditorMainWindow->GetCurrentView();
return pLUAViewWidget;
}
LUAEditorFindDialog::~LUAEditorFindDialog()
{
LUAViewMessages::Bus::Handler::BusDisconnect();
azdestroy(m_gui);
}
void LUAEditorFindDialog::SetAnyDocumentsOpen(bool value)
{
m_bAnyDocumentsOpen = value;
m_gui->searchWhereComboBox->clear();
if (m_bAnyDocumentsOpen)
{
m_gui->searchWhereComboBox->addItem(tr("Current File"));
m_gui->searchWhereComboBox->addItem(tr("All Open Files"));
m_gui->searchWhereComboBox->setCurrentIndex(0);
// TODO: Enable when asset database is in used
//m_gui->searchWhereComboBox->addItem(tr("All LUA Assets"));
// since at least one document is open take this opportunity
// to copy any selected text block to the string to find in the dialog
LUAViewWidget* pLUAViewWidget = GetViewFromParent();
if (pLUAViewWidget)
{
if (pLUAViewWidget->HasSelectedText())
{
QString qstr = pLUAViewWidget->GetSelectedText();
m_gui->txtFind->setText(qstr);
}
}
}
else
{
// TODO: Enable when asset database is in used
//m_gui->searchWhereComboBox->addItem(tr("All LUA Assets"));
m_gui->searchWhereComboBox->setCurrentIndex(0);
}
m_gui->txtFind->setFocus();
m_gui->txtFind->selectAll();
}
// make the "find next" button match the file scope from the pull-down menu
void LUAEditorFindDialog::OnSearchWhereChanged(int index)
{
if (m_bAnyDocumentsOpen)
{
switch (index)
{
case 0:
m_gui->findNextButton->setEnabled(true);
break;
case 1:
case 2:
m_gui->findNextButton->setEnabled(false);
break;
}
}
m_gui->findNextButton->setDefault(m_gui->findNextButton->isEnabled());
m_gui->findAllButton->setDefault(!m_gui->findNextButton->isEnabled());
m_gui->findNextButton->setAutoDefault(m_gui->findNextButton->isEnabled());
m_gui->findAllButton->setAutoDefault(!m_gui->findNextButton->isEnabled());
}
void LUAEditorFindDialog::SaveState()
{
if (m_bAnyDocumentsOpen)
{
auto pState = AZ::UserSettings::CreateFind<LUAEditorInternal::FindSavedState>(m_bWasFindInAll ? AZ_CRC("LUAFindInAny", 0x9b85f4f9) : AZ_CRC("FindInCurrent", 0xba0962af), AZ::UserSettings::CT_LOCAL);
pState->m_lastSearchInFilesMode = m_gui->searchWhereComboBox->currentIndex();
}
}
void LUAEditorFindDialog::SetToFindInAllOpen(bool findInAny)
{
m_bWasFindInAll = findInAny;
// restore prior global mode:
if (m_bAnyDocumentsOpen)
{
auto pState = AZ::UserSettings::Find<LUAEditorInternal::FindSavedState>(findInAny ? AZ_CRC("LUAFindInAny", 0x9b85f4f9) : AZ_CRC("FindInCurrent", 0xba0962af), AZ::UserSettings::CT_LOCAL);
if (pState)
{
m_gui->searchWhereComboBox->setCurrentIndex(pState->m_lastSearchInFilesMode); // theres three options!
m_gui->findNextButton->setEnabled(m_gui->searchWhereComboBox->currentIndex() == 0);
}
else
{
// TODO: When the asset database is in use, this test may want to default to AllLUAAssets instead
m_gui->searchWhereComboBox->setCurrentIndex(findInAny ? AllOpenDocs : CurrentDoc);
m_gui->findNextButton->setEnabled(m_gui->searchWhereComboBox->currentIndex() == 0);
}
}
else
{
m_gui->searchWhereComboBox->setCurrentIndex(CurrentDoc); // theres only one option, no files are open
m_gui->findNextButton->setEnabled(false);
}
m_gui->findNextButton->setDefault(m_gui->findNextButton->isEnabled());
m_gui->findAllButton->setDefault(!m_gui->findNextButton->isEnabled());
m_gui->findNextButton->setAutoDefault(m_gui->findNextButton->isEnabled());
m_gui->findAllButton->setAutoDefault(!m_gui->findNextButton->isEnabled());
if (m_bWasFindInAll)
{
this->setWindowTitle("Find in files...");
}
else
{
this->setWindowTitle("Find...");
}
}
void LUAEditorFindDialog::ResetSearch()
{
m_bFoundFirst = false;
}
// currently used to mark a wrap point for multiple-view searching
void LUAEditorFindDialog::SetNewSearchStarting(bool bOverride, bool bSearchForwards)
{
if (bOverride && bSearchForwards)
{
m_gui->searchDownRadioButton->setChecked(true);
}
else if (bOverride)
{
m_gui->searchUpRadioButton->setChecked(true);
}
m_WrapWidget = GetViewFromParent();
if (m_WrapWidget)
{
m_WrapWidget->GetCursorPosition(m_WrapLine, m_WrapIndex);
}
}
void LUAEditorFindDialog::OnFindNext()
{
if (m_bFindThreadRunning)
{
m_bCancelFindSignal = true;
}
LUAViewWidget* pLUAViewWidget = pLUAEditorMainWindow->GetCurrentView();
if (!pLUAViewWidget)
{
return;
}
if (!m_gui->txtFind->text().isEmpty())
{
if (m_lastSearchText != m_gui->txtFind->text() || m_bLastWrap != m_gui->wrapCheckBox->isChecked())
{
m_bFoundFirst = false;
}
//if we switched from finding forward to backward after finding a first
//the the cursor will be in front of the last find, so the first finding backward
//will re-find the current find (the one we are already found). This is unintuitive
//to the user so instead we find backward to move the cursor to the beginning
//of the current selection then call find next to actually find the next previous
//occurrence as the user intended
//whats strange is this only happens for find backward, find forward seems
//to be smart enough to take this into account already.... so on do another find next
//if searching up
if (m_bFoundFirst &&
m_bLastForward != m_gui->searchDownRadioButton->isChecked())
{
m_findOperation = pLUAViewWidget->FindFirst(m_gui->txtFind->text(),
m_gui->regularExpressionCheckBox->isChecked(),
m_gui->caseSensitiveCheckBox->isChecked(),
m_gui->wholeWordsCheckBox->isChecked(),
m_gui->wrapCheckBox->isChecked(),
m_gui->searchDownRadioButton->isChecked());
if (!m_gui->searchDownRadioButton->isChecked())
{
pLUAViewWidget->FindNext(m_findOperation);
}
}
else if (m_bFoundFirst)
{
pLUAViewWidget->FindNext(m_findOperation);
}
else
{
// if moving backwards move the last result's cursor back one character
// because it's placed at the end of the word and searching back from
// the end of the word simply returns the word again
if (!m_gui->searchDownRadioButton->isChecked())
{
pLUAViewWidget->MoveCursor(-1);
}
m_findOperation = pLUAViewWidget->FindFirst(m_gui->txtFind->text(),
m_gui->regularExpressionCheckBox->isChecked(),
m_gui->caseSensitiveCheckBox->isChecked(),
m_gui->wholeWordsCheckBox->isChecked(),
m_gui->wrapCheckBox->isChecked(),
m_gui->searchDownRadioButton->isChecked());
}
m_lastSearchText = m_gui->txtFind->text();
m_bLastForward = m_gui->searchDownRadioButton->isChecked();
m_bLastWrap = m_gui->wrapCheckBox->isChecked();
}
else
{
QMessageBox::warning(this, "Error!", "You may not search for an empty string!");
}
if (!m_findOperation)
{
QMessageBox::warning(this, "Search failed!", tr("Could not find \"%1\" within/further this context.").arg(m_gui->txtFind->text()));
}
}
void LUAEditorFindDialog::FindInView(LUAViewWidget* pLUAViewWidget, QListWidget* pCurrentFindListView)
{
pCurrentFindListView;
if (!pLUAViewWidget)
{
return;
}
pLUAViewWidget->SetCursorPosition(0, 0);
auto findOperation = pLUAViewWidget->FindFirst(m_gui->txtFind->text(),
m_gui->regularExpressionCheckBox->isChecked(),
m_gui->caseSensitiveCheckBox->isChecked(),
m_gui->wholeWordsCheckBox->isChecked(),
false,
m_gui->searchDownRadioButton->isChecked());
if (findOperation)
{
emit triggerFindNextInView(&findOperation, pLUAViewWidget, pCurrentFindListView);
}
}
void LUAEditorFindDialog::FindNextInView(LUAViewWidget::FindOperation* operation, LUAViewWidget* pLUAViewWidget, QListWidget* pCurrentFindListView)
{
pLUAViewWidget;
pCurrentFindListView;
int line = 0;
int index = 0;
pLUAViewWidget->GetCursorPosition(line, index);
QString itemText;
QString lineTxt;
lineTxt.setNum(line + 1); //files are 1 based
AZStd::string assetFileName(pLUAViewWidget->m_Info.m_assetName + ".lua");
itemText = assetFileName.c_str();
itemText += "(";
itemText += lineTxt;
itemText += "): ";
itemText += pLUAViewWidget->GetLineText(line).trimmed();
QListWidgetItem* pItem = new QListWidgetItem(pCurrentFindListView);
pItem->setText(itemText);
//char buf[64];
//pLUAViewWidget->m_Info.m_assetId.ToString(buf,AZ_ARRAY_SIZE(buf),true,true);
pItem->setData(Qt::UserRole + 1, QVariant(/*buf*/ pLUAViewWidget->m_Info.m_assetId.c_str()));
AZStd::string assetFileName2(pLUAViewWidget->m_Info.m_assetName + ".lua");
pItem->setData(Qt::UserRole + 2, QVariant(assetFileName2.c_str()));
pItem->setData(Qt::UserRole + 3, QVariant(line));
pItem->setData(Qt::UserRole + 4, QVariant(index));
pItem->setData(Qt::UserRole + 5, QVariant(m_gui->txtFind->text().length()));
pCurrentFindListView->addItem(pItem);
pLUAViewWidget->FindNext(*operation);
if (operation && !m_bCancelFindSignal)
{
emit triggerFindNextInView(operation, pLUAViewWidget, pCurrentFindListView);
}
else
{
BusyOff();
}
}
void LUAEditorFindDialog::OnFindAll()
{
if (m_bReplaceThreadRunning)
{
QMessageBox::warning(this, "Error!", "You may not run Find ALL while a Replace All is running!");
return;
}
m_resultList.clear();
m_bCancelFindSignal = false;
m_bFindThreadRunning = true;
int widgetIndex = 0;
if (m_gui->m_find1RadioButton->isChecked())
{
widgetIndex = 0;
}
else if (m_gui->m_find2RadioButton->isChecked())
{
widgetIndex = 1;
}
else if (m_gui->m_find3RadioButton->isChecked())
{
widgetIndex = 2;
}
else if (m_gui->m_find4RadioButton->isChecked())
{
widgetIndex = 3;
}
pLUAEditorMainWindow->SetCurrentFindListWidget(widgetIndex);
auto resultsWidget = pLUAEditorMainWindow->GetFindResultsWidget(widgetIndex);
resultsWidget->Clear();
pLUAEditorMainWindow->ResetSearchClicks();
if (!m_gui->txtFind->text().isEmpty())
{
int theMode = m_gui->searchWhereComboBox->currentIndex();
if (!m_bAnyDocumentsOpen)
{
// TODO: Enable when the asset database is used.
//theMode = AllLUAAssets;
}
else
{
theMode = AllOpenDocs;
}
BusyOn();
m_lastSearchWhere = theMode;
if (theMode == CurrentDoc)
{
FindInFilesSetUp(theMode, resultsWidget);
emit triggerFindInFilesNext(theMode);
}
else if (theMode == AllOpenDocs)
{
FindInFilesSetUp(theMode, resultsWidget);
emit triggerFindInFilesNext(theMode);
}
else if (theMode == AllLUAAssets)
{
FindInFilesSetUp(theMode, resultsWidget);
emit triggerFindInFilesNext(theMode);
}
}
else
{
QMessageBox::warning(this, "Error!", "You may not search for an empty string!");
}
}
void LUAEditorFindDialog::FindInFilesSetUp(int theMode, FindResults* resultsWidget)
{
m_FIFData.m_TotalMatchesFound = 0;
m_FIFData.m_OpenView = pLUAEditorMainWindow->GetAllViews();
if (theMode == CurrentDoc)
{
m_FIFData.m_openViewIter = m_FIFData.m_OpenView.begin();
while (*m_FIFData.m_openViewIter != pLUAEditorMainWindow->GetCurrentView() && m_FIFData.m_openViewIter != m_FIFData.m_OpenView.end())
{
++m_FIFData.m_openViewIter;
}
}
else
{
m_FIFData.m_openViewIter = m_FIFData.m_OpenView.begin();
}
m_FIFData.m_resultsWidget = resultsWidget;
//get a list of all the lua assets info
m_dFindAllLUAAssetsInfo.clear();
if (theMode == AllLUAAssets)
{
AZ_Assert(false, "Fix assets!");
//AZ::u32 platformFeatureFlags = PLATFORM_FEATURE_FLAGS_ALL;
//EBUS_EVENT_RESULT(platformFeatureFlags, EditorFramework::EditorAssetCatalogMessages::Bus, GetCurrentPlatformFeatureFlags);
//EBUS_EVENT(EditorFramework::EditorAssetCatalogMessages::Bus, FindEditorAssetsByType, m_dFindAllLUAAssetsInfo, AZ::ScriptAsset::StaticAssetType(), platformFeatureFlags);
}
m_SearchText = m_gui->txtFind->text();
m_FIFData.m_dOpenView.clear();
m_FIFData.m_bWholeWordIsChecked = m_gui->wholeWordsCheckBox->isChecked();
m_FIFData.m_bRegExIsChecked = m_gui->regularExpressionCheckBox->isChecked();
m_FIFData.m_bCaseSensitiveIsChecked = m_gui->caseSensitiveCheckBox->isChecked();
if (m_FIFData.m_bWholeWordIsChecked)
{
if (!m_SearchText.startsWith("\b", Qt::CaseInsensitive) &&
!m_SearchText.endsWith("\b", Qt::CaseInsensitive))
{
m_FIFData.m_SearchText = "\\b";
m_FIFData.m_SearchText += m_SearchText;
m_FIFData.m_SearchText += "\\b";
}
}
else
{
m_FIFData.m_SearchText = m_SearchText;
}
m_FIFData.m_assetInfoIter = m_dFindAllLUAAssetsInfo.begin();
}
void LUAEditorFindDialog::FindInFilesNext(int theMode)
{
// one at a time parse the open documents and store their name strings away
if ((!m_bCancelFindSignal) && m_FIFData.m_openViewIter != m_FIFData.m_OpenView.end())
{
// this block mimics the original FindInView() call, localized to the FIF callback scheme
bool syncResult = pLUAEditorMainWindow->SyncDocumentToContext((*m_FIFData.m_openViewIter)->m_Info.m_assetId);
if (syncResult)
{
// successful sync between the QScintilla document and the raw buffer version that we need
const char* buffer = nullptr;
AZStd::size_t actualSize = 0;
EBUS_EVENT(Context_DocumentManagement::Bus, GetDocumentData, (*m_FIFData.m_openViewIter)->m_Info.m_assetId, &buffer, actualSize);
/************************************************************************/
/* Open files are similar but not identical to closed file processing */
/************************************************************************/
char* pBuf = (char*)azmalloc(actualSize + 1);
char* pCur = pBuf;
pCur[actualSize] = '\0';
memcpy(pCur, buffer, actualSize);
AZStd::vector<char*> dLines;
AZStd::string assetName = (*m_FIFData.m_openViewIter)->m_Info.m_assetName + ".lua";
while ((AZ::IO::Streamer::SizeType)(pCur - pBuf) <= actualSize)
{
dLines.push_back(pCur);
while (*pCur != '\n' && (AZ::IO::Streamer::SizeType)(pCur - pBuf) <= actualSize)
{
pCur++;
}
if ((AZ::IO::Streamer::SizeType)(pCur - pBuf) <= actualSize)
{
*pCur = '\0';
pCur++;
}
}
for (int line = 0; line < dLines.size(); ++line)
{
ResultEntry entry;
entry.m_lineText = dLines[line];
QRegExp regex(m_FIFData.m_SearchText, m_FIFData.m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
int index = 0;
if (m_FIFData.m_bRegExIsChecked || m_FIFData.m_bWholeWordIsChecked)
{
index = entry.m_lineText.indexOf(regex, index);
}
else
{
index = entry.m_lineText.indexOf(m_FIFData.m_SearchText, index, m_FIFData.m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
}
if (index > -1)
{
const auto& docInfo = (*m_FIFData.m_openViewIter)->m_Info;
++m_FIFData.m_TotalMatchesFound;
QString qAssetName = assetName.c_str();
if (m_resultList.find(qAssetName) == m_resultList.end())
{
m_resultList[qAssetName].m_assetId = docInfo.m_assetId;
}
entry.m_lineNumber = line;
entry.m_lineText = entry.m_lineText.trimmed();
while (index > -1)
{
if (m_FIFData.m_bRegExIsChecked || m_FIFData.m_bWholeWordIsChecked)
{
entry.m_matches.push_back(AZStd::make_pair(index, regex.matchedLength()));
}
else
{
entry.m_matches.push_back(AZStd::make_pair(index, m_FIFData.m_SearchText.length()));
}
index++;
if (m_FIFData.m_bRegExIsChecked || m_FIFData.m_bWholeWordIsChecked)
{
index = entry.m_lineText.indexOf(regex, index);
}
else
{
index = entry.m_lineText.indexOf(m_FIFData.m_SearchText, index, m_FIFData.m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
}
}
m_resultList[qAssetName].m_entries.push_back(entry);
}
}
azfree(pBuf);
}
/************************************************************************/
/* */
/************************************************************************/
if (theMode == CurrentDoc)
{
m_FIFData.m_dOpenView.push_back((*m_FIFData.m_openViewIter)->m_Info.m_assetName + ".lua");
m_FIFData.m_openViewIter = m_FIFData.m_OpenView.end();
}
else
{
++m_FIFData.m_openViewIter;
if (m_FIFData.m_openViewIter == m_FIFData.m_OpenView.end())
{
for (AZStd::vector<LUAViewWidget*>::iterator openViewIter = m_FIFData.m_OpenView.begin();
openViewIter != m_FIFData.m_OpenView.end(); ++openViewIter)
{
m_FIFData.m_dOpenView.push_back((*openViewIter)->m_Info.m_assetName + ".lua");
}
}
}
emit triggerFindInFilesNext(theMode);
return;
}
if ((!m_bCancelFindSignal) && m_FIFData.m_assetInfoIter != m_dFindAllLUAAssetsInfo.end())
{
// from the previously prepared list of strings of names of open files, is THIS asset open?
bool bIsOpen = false;
for (AZStd::vector<AZStd::string>::iterator iter = m_FIFData.m_dOpenView.begin();
!bIsOpen && iter != m_FIFData.m_dOpenView.end(); ++iter)
{
AZ_Assert(false, "check under!");
//if (*iter == m_FIFData.m_assetInfoIter->m_physicalPath)
if (*iter == *m_FIFData.m_assetInfoIter)
{
bIsOpen = true;
break;
}
}
if (!bIsOpen)
{
/* AZ::IO::Stream* pStream = AZ::IO::g_streamer->RegisterStream(m_FIFData.m_assetInfoIter->m_StreamName.c_str());
if (!pStream)
{
AZ_TracePrintf("LUA", "FindInFilesNext (%s) NULL stream\n",m_FIFData.m_assetInfoIter->m_StreamName);
}
else
{
AZ::IO::Streamer::SizeType fileSize = pStream->Size();
char* buf = (char*)dhmalloc(fileSize+1);
buf[fileSize]='\0';
size_t offset=0;
while(size_t bytesRead = AZ::IO::g_streamer->Read(pStream,offset,fileSize-offset,buf+offset))
{
offset += bytesRead;
if(offset == fileSize)
break;
}
AZ::IO::g_streamer->UnRegisterStream(pStream);
char* pCur = buf;
AZStd::vector<char*> dLines;
while((AZ::IO::Streamer::SizeType)(pCur - buf) <= fileSize)
{
dLines.push_back(pCur);
while(*pCur != '\n' && (AZ::IO::Streamer::SizeType)(pCur - buf) <= fileSize)
pCur++;
if((AZ::IO::Streamer::SizeType)(pCur - buf) <= fileSize)
{
*pCur = '\0';
pCur++;
}
}
for(int line=0; line<dLines.size(); ++line)
{
ResultEntry entry;
entry.m_lineText = dLines[line];
QRegExp regex(m_FIFData.m_SearchText, m_FIFData.m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
int index = 0;
if(m_FIFData.m_bRegExIsChecked || m_FIFData.m_bWholeWordIsChecked)
index = entry.m_lineText.indexOf(regex, index);
else
index = entry.m_lineText.indexOf(m_FIFData.m_SearchText, index, m_FIFData.m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
if(index > -1)
{
++m_FIFData.m_TotalMatchesFound;
QString qAssetName = assetName.c_str();
if (m_resultList.find(qAssetName) == m_resultList.end())
{
m_resultList[qAssetName].m_assetId = AZ::Data::AssetId::CreateNull();
}
entry.m_lineNumber = line;
entry.m_lineText = entry.m_lineText.trimmed();
while (index > -1)
{
if (m_FIFData.m_bRegExIsChecked || m_FIFData.m_bWholeWordIsChecked)
{
entry.m_matches.push_back(AZStd::make_pair(index, regex.matchedLength()));
}
else
{
entry.m_matches.push_back(AZStd::make_pair(index, m_FIFData.m_SearchText.length()));
}
index++;
if (m_FIFData.m_bRegExIsChecked || m_FIFData.m_bWholeWordIsChecked)
index = entry.m_lineText.indexOf(regex, index);
else
index = entry.m_lineText.indexOf(m_FIFData.m_SearchText, index, m_FIFData.m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
}
m_resultList[qAssetName].m_entries.push_back(entry);
}
}
dhfree(buf);
}
*/
}
++m_FIFData.m_assetInfoIter;
emit triggerFindInFilesNext(theMode);
return;
}
if (!m_resultList.empty() || m_bCancelFindSignal)
{
if (!m_bCancelFindSignal)
{
PostProcessOn();
EBUS_QUEUE_FUNCTION(AZ::SystemTickBus, &LUAEditorFindDialog::ProcessFindItems, this);
}
else
{
BusyOff();
}
m_bFindThreadRunning = false;
AZ_TracePrintf("LUA", "Find In Files Matches Found = %d\n", m_FIFData.m_TotalMatchesFound);
}
else
{
m_bFindThreadRunning = false;
BusyOff();
}
}
void LUAEditorFindDialog::ProcessFindItems()
{
auto doc = m_FIFData.m_resultsWidget->Document();
auto setFoldLevel = [&doc](int lineNum, int foldLevel, int depth)
{
QTBlockState blockState;
auto block = doc->findBlockByNumber(lineNum);
AZ_Assert(block.isValid(), "should only be setting fold level on a just added line");
blockState.m_qtBlockState = block.userState();
blockState.m_blockState.m_uninitialized = 0;
blockState.m_blockState.m_folded = 0;
blockState.m_blockState.m_foldLevel = foldLevel;
blockState.m_blockState.m_syntaxHighlighterState = depth;
block.setUserState(blockState.m_qtBlockState);
};
int currentLine = 0;
m_FIFData.m_resultsWidget->Clear();
QString hits;
if (m_FIFData.m_TotalMatchesFound == 1)
{
hits.append("hit");
}
else
{
hits.append("hits");
}
QString files;
if (m_resultList.size() == 1)
{
files.append("file");
}
else
{
files.append("files");
}
QString header("Find \"%1\" (%2 %4 in %3 %5)");
header = header.arg(m_FIFData.m_SearchText).arg(m_FIFData.m_TotalMatchesFound).arg(m_resultList.size()).arg(hits).arg(files);
m_FIFData.m_resultsWidget->AppendPlainText(header);
setFoldLevel(currentLine, 0, 0);
for (auto iter = m_resultList.begin(); iter != m_resultList.end(); ++iter)
{
++currentLine;
if (iter->m_entries.size() == 1)
{
hits = "hit";
}
else
{
hits = "hits";
}
QString text("\t\"%1\" (%2 %3)");
text = text.arg(iter.key()).arg(iter->m_entries.size()).arg(hits);
m_FIFData.m_resultsWidget->AppendPlainText(text);
setFoldLevel(currentLine, 1, 1);
for (auto& entry : iter->m_entries)
{
++currentLine;
text = "\t\t\tLine %1: %2";
text = text.arg(entry.m_lineNumber).arg(entry.m_lineText);
m_FIFData.m_resultsWidget->AppendPlainText(text);
AZ_Assert(!entry.m_matches.empty(), "shouldn't be an entry at all if there wasn't at least one match");
setFoldLevel(currentLine, 1, 2);
auto block = doc->findBlockByNumber(currentLine);
AZ_Assert(block.isValid(), "should only be setting data on a just added line");
auto resultsWidget = m_FIFData.m_resultsWidget;
auto assignAssetId = [resultsWidget](const AZStd::string& assetName, const AZStd::string& assetId) {resultsWidget->AssignAssetId(assetName, assetId); };
block.setUserData(aznew FindResultsBlockInfo {iter->m_assetId, iter.key().toUtf8().data(), entry.m_lineNumber,
entry.m_matches[0].first, assignAssetId});
}
setFoldLevel(currentLine, 0, 2);
}
m_FIFData.m_resultsWidget->FinishedAddingText(m_FIFData.m_SearchText, m_FIFData.m_bRegExIsChecked,
m_FIFData.m_bWholeWordIsChecked, m_FIFData.m_bCaseSensitiveIsChecked);
BusyOff();
int findWindow = 0;
if (m_gui->m_find1RadioButton->isChecked())
{
findWindow = 0;
}
else if (m_gui->m_find2RadioButton->isChecked())
{
findWindow = 1;
}
else if (m_gui->m_find3RadioButton->isChecked())
{
findWindow = 2;
}
else if (m_gui->m_find4RadioButton->isChecked())
{
findWindow = 3;
}
//get the find tab and let see it
QTabWidget* pLuaFindTabWidget = pLUAEditorMainWindow->GetFindTabWidget();
AZ_Assert(pLuaFindTabWidget, "LUAEditorMainWindow cant find the FindTabWidget!");
pLuaFindTabWidget->show();
pLuaFindTabWidget->raise();
pLuaFindTabWidget->activateWindow();
pLuaFindTabWidget->setFocus();
pLUAEditorMainWindow->OnOpenFindView(findWindow);
m_resultList.clear();
}
void LUAEditorFindDialog::OnCancel()
{
m_bCancelFindSignal = true;
m_bCancelReplaceSignal = true;
//this->close();
}
void LUAEditorFindDialog::OnReplace()
{
if (m_bFindThreadRunning)
{
m_bCancelFindSignal = true;
}
LUAViewWidget* pLUAViewWidget = GetViewFromParent();
if (!pLUAViewWidget)
{
return;
}
if (pLUAViewWidget->HasSelectedText())
{
if (pLUAViewWidget->m_Info.m_bSourceControl_BusyRequestingEdit ||
pLUAViewWidget->m_Info.m_bSourceControl_BusyGettingStats ||
pLUAViewWidget->m_Info.m_bSourceControl_Ready == false)
{
EBUS_QUEUE_FUNCTION(AZ::SystemTickBus, &LUAEditorFindDialog::OnReplace, this);
}
else if (!pLUAViewWidget->m_Info.m_bSourceControl_CanWrite &&
pLUAViewWidget->m_Info.m_bSourceControl_CanCheckOut)
{
// check it out for edit
EBUS_EVENT(Context_DocumentManagement::Bus,
DocumentCheckOutRequested,
pLUAViewWidget->m_Info.m_assetId);
EBUS_QUEUE_FUNCTION(AZ::SystemTickBus, &LUAEditorFindDialog::OnReplace, this);
}
else if (!pLUAViewWidget->m_Info.m_bSourceControl_CanWrite)
{
QMessageBox::warning(this, "Error!", "Can not check out file for replace!");
}
else
{
pLUAViewWidget->ReplaceSelectedText(m_gui->txtReplaceWith->text());
int startLine = 0;
int startIndex = 0;
pLUAViewWidget->GetCursorPosition(startLine, startIndex);
pLUAViewWidget->SetCursorPosition(startLine, startIndex + 1);
OnFindNext();
}
}
else
{
OnFindNext();
}
}
void LUAEditorFindDialog::ReplaceInFilesSetUp()
{
BusyOn();
m_bReplaceThreadRunning = true;
m_bCancelReplaceSignal = false;
//get a list of all the lua assets info
m_RIFData.m_dReplaceProcessList.clear();
m_RIFData.m_dReplaceAllLUAAssetsInfo.clear();
AZ_Assert(false, "Fix assets!");
//AZ::u32 platformFeatureFlags = PLATFORM_FEATURE_FLAGS_ALL;
//EBUS_EVENT_RESULT(platformFeatureFlags, EditorFramework::EditorAssetCatalogMessages::Bus, GetCurrentPlatformFeatureFlags);
//EBUS_EVENT(EditorFramework::EditorAssetCatalogMessages::Bus, FindEditorAssetsByType, m_RIFData.m_dReplaceAllLUAAssetsInfo, AZ::ScriptAsset::StaticAssetType(), platformFeatureFlags);
m_RIFData.m_OpenView = pLUAEditorMainWindow->GetAllViews();
m_SearchText = m_gui->txtFind->text();
m_RIFData.m_dOpenView.clear();
for (auto iter = m_RIFData.m_OpenView.begin(); iter != m_RIFData.m_OpenView.end(); ++iter)
{
m_RIFData.m_dOpenView.push_back((*iter)->m_Info.m_assetName + ".lua");
}
m_RIFData.m_bWholeWordIsChecked = m_gui->wholeWordsCheckBox->isChecked();
m_RIFData.m_bRegExIsChecked = m_gui->regularExpressionCheckBox->isChecked();
m_RIFData.m_bCaseSensitiveIsChecked = m_gui->caseSensitiveCheckBox->isChecked();
if (m_RIFData.m_bWholeWordIsChecked)
{
if (!m_SearchText.startsWith("\b", Qt::CaseInsensitive) &&
!m_SearchText.endsWith("\b", Qt::CaseInsensitive))
{
m_RIFData.m_SearchText = "\\b";
m_RIFData.m_SearchText += m_SearchText;
m_RIFData.m_SearchText += "\\b";
}
}
else
{
m_RIFData.m_SearchText = m_SearchText;
}
m_RIFData.m_assetInfoIter = m_RIFData.m_dReplaceAllLUAAssetsInfo.begin();
}
void LUAEditorFindDialog::ReplaceInFilesNext()
{
if (m_bCancelReplaceSignal)
{
BusyOff();
m_bReplaceThreadRunning = false;
m_bCancelReplaceSignal = false;
return; // return with no timer set to call back ends this run
}
if (m_RIFData.m_assetInfoIter != m_RIFData.m_dReplaceAllLUAAssetsInfo.end())
{
//for each asset name, if the asset is not open already, open it search it and close it
{
bool bIsOpen = false;
for (AZStd::vector<AZStd::string>::iterator openViewIter = m_RIFData.m_dOpenView.begin();
openViewIter != m_RIFData.m_dOpenView.end(); ++openViewIter)
{
// is this the right check?
if (*openViewIter == *m_RIFData.m_assetInfoIter)
//if (*openViewIter == m_RIFData.m_assetInfoIter->m_physicalPath)
{
bIsOpen = true;
break;
}
}
if (!bIsOpen)
{
/*
AZ::IO::Stream* pStream = AZ::IO::g_streamer->RegisterStream(m_RIFData.m_assetInfoIter->m_StreamName.c_str());
if (!pStream)
{
AZ_TracePrintf("LUA", "ReplaceInFilesNext (%s) NULL stream\n",m_FIFData.m_assetInfoIter->m_StreamName);
}
else
{
size_t fileSize = pStream->Size();
char* buf = (char*)dhmalloc(fileSize+1);
buf[fileSize]=NULL;
size_t offset=0;
while(size_t bytesRead = AZ::IO::g_streamer->Read(pStream,offset,fileSize-offset,buf+offset))
{
offset += bytesRead;
if(offset == fileSize)
break;
}
AZ::IO::g_streamer->UnRegisterStream(pStream);
char* pCur = buf;
AZStd::vector<char*> dLines;
while((AZ::IO::Streamer::SizeType)(pCur - buf) <= fileSize)
{
dLines.push_back(pCur);
while(*pCur != '\n' && (AZ::IO::Streamer::SizeType)(pCur - buf) <= fileSize)
pCur++;
if((AZ::IO::Streamer::SizeType)(pCur - buf) <= fileSize)
{
*pCur = NULL;
pCur++;
}
}
for(AZStd::size_t line=0; line<dLines.size(); ++line)
{
QString str(dLines[line]);
QRegExp regex(m_RIFData.m_SearchText, m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
int index = 0;
if(m_bRegExIsChecked || m_bWholeWordIsChecked)
index = str.indexOf(regex, index);
else
index = str.indexOf(m_RIFData.m_SearchText, index, m_bCaseSensitiveIsChecked ? Qt::CaseSensitive : Qt::CaseInsensitive);
if(index > -1)
{
m_RIFData.m_dReplaceProcessList.push_back(assetName.c_str());
line = dLines.size();
}
}
delete buf;
}
*/
}
}
++m_RIFData.m_assetInfoIter;
// are we done with the search and dispatch?
if (m_RIFData.m_assetInfoIter == m_RIFData.m_dReplaceAllLUAAssetsInfo.end())
{
if (!m_RIFData.m_dReplaceProcessList.empty())
{
PostReplaceOn();
QTimer::singleShot(0, this, SLOT(ProcessReplaceItems()));
}
else
{
m_bReplaceThreadRunning = false;
m_bCancelReplaceSignal = false;
BusyOff();
}
return;
}
QTimer::singleShot(1, this, SLOT(ReplaceInFilesNext()));
}
}
void LUAEditorFindDialog::ProcessReplaceItems()
{
if (m_bCancelReplaceSignal)
{
BusyOff();
m_bReplaceThreadRunning = false;
m_bCancelReplaceSignal = false;
return; // return with no timer set to call back ends this run
}
if (!m_RIFData.m_dReplaceProcessList.empty())
{
AZStd::string assetName = AZStd::move(m_RIFData.m_dReplaceProcessList.back());
m_RIFData.m_dReplaceProcessList.pop_back();
m_RIFData.m_waitingForOpenToComplete.insert(assetName);
//split physical path into the components saved by the database
AZStd::string projectRoot, databaseRoot, databasePath, databaseFile, fileExtension;
if (!AzFramework::StringFunc::AssetDatabasePath::Split(assetName.c_str(), &projectRoot, &databaseRoot, &databasePath, &databaseFile, &fileExtension))
{
AZ_Warning("LUAEditorFindDialog", false, AZStd::string::format("<span severity=\"err\">Path is invalid: '%s'</span>", assetName.c_str()).c_str());
return;
}
//find it in the database
//AZStd::vector<EditorFramework::EditorAsset> dAssetInfo;
//EBUS_EVENT(EditorFramework::EditorAssetCatalogMessages::Bus, FindEditorAssetsByName, dAssetInfo, databaseRoot.c_str(), databasePath.c_str(), databaseFile.c_str(), fileExtension.c_str());
//if (dAssetInfo.empty())
// return;
//request it be opened
//EBUS_EVENT_ID( LUAEditor::ContextID,
//EditorFramework::AssetManagementMessages::Bus,
// AssetOpenRequested,
// dAssetInfo[0].m_databaseAsset.m_assetId,
// AZ::ScriptAsset::StaticAssetType());
QTimer::singleShot(0, this, SLOT(ProcessReplaceItems()));
}
else
{
// getting here means we've dispatched all the requests to open the files.
if ((m_PendingReplaceInViewOperations.empty()) && (m_RIFData.m_waitingForOpenToComplete.empty()))
{
BusyOff();
m_bReplaceThreadRunning = false;
m_bCancelReplaceSignal = false;
}
}
}
void LUAEditorFindDialog::OnDataLoadedAndSet(const DocumentInfo& info, LUAViewWidget* pLUAViewWidget)
{
auto searcher = m_RIFData.m_waitingForOpenToComplete.find(info.m_assetName);
if (searcher != m_RIFData.m_waitingForOpenToComplete.end())
{
m_RIFData.m_waitingForOpenToComplete.erase(searcher);
bool wasEmpty = m_PendingReplaceInViewOperations.empty();
m_PendingReplaceInViewOperations.push_back(pLUAViewWidget);
// only start iterating the first time:
if (wasEmpty)
{
QTimer::singleShot(0, this, SLOT(OnReplaceInViewIterate()));
}
}
}
void LUAEditorFindDialog::OnReplaceInViewIterate()
{
if ((m_PendingReplaceInViewOperations.empty()) && (m_RIFData.m_waitingForOpenToComplete.empty()))
{
BusyOff();
m_bCancelReplaceSignal = false;
m_bReplaceThreadRunning = false;
return;
}
LUAViewWidget* pWidget = m_PendingReplaceInViewOperations.back();
int result = ReplaceInView(pWidget);
if (m_bCancelReplaceSignal)
{
BusyOff();
m_bReplaceThreadRunning = false;
m_bCancelReplaceSignal = false;
return;
}
// any result besides -2 means we're done with this item:
if (result != -2)
{
m_PendingReplaceInViewOperations.pop_back();
}
if (!m_PendingReplaceInViewOperations.empty())
{
QTimer::singleShot(0, this, SLOT(OnReplaceInViewIterate()));
}
if ((m_PendingReplaceInViewOperations.empty()) && (m_RIFData.m_waitingForOpenToComplete.empty()))
{
BusyOff();
m_bCancelReplaceSignal = false;
m_bReplaceThreadRunning = false;
return;
}
}
int LUAEditorFindDialog::ReplaceInView(LUAViewWidget* pLUAViewWidget)
{
if (m_bCancelReplaceSignal)
{
BusyOff();
m_bReplaceThreadRunning = false;
m_bCancelReplaceSignal = false;
return 0;
}
if (pLUAViewWidget->m_Info.m_bSourceControl_BusyRequestingEdit ||
pLUAViewWidget->m_Info.m_bSourceControl_BusyGettingStats ||
pLUAViewWidget->m_Info.m_bSourceControl_Ready == false)
{
return -2;
}
else if (!pLUAViewWidget->m_Info.m_bSourceControl_CanWrite &&
pLUAViewWidget->m_Info.m_bSourceControl_CanCheckOut)
{
// check it out for edit
EBUS_EVENT(Context_DocumentManagement::Bus,
DocumentCheckOutRequested,
pLUAViewWidget->m_Info.m_assetId);
return -2;
}
else if (!pLUAViewWidget->m_Info.m_bSourceControl_CanWrite)
{
QMessageBox::warning(this, "Can not check out file!", (pLUAViewWidget->m_Info.m_assetName + ".lua").c_str());
return -1;
}
int count = 0;
pLUAViewWidget->SetCursorPosition(0, 0);
if (pLUAViewWidget->FindFirst(m_gui->txtFind->text(),
m_gui->regularExpressionCheckBox->isChecked(),
m_gui->caseSensitiveCheckBox->isChecked(),
m_gui->wholeWordsCheckBox->isChecked(),
m_gui->wrapCheckBox->isChecked(),
m_gui->searchDownRadioButton->isChecked()))
{
pLUAViewWidget->ReplaceSelectedText(m_gui->txtReplaceWith->text());
count++;
while (pLUAViewWidget->FindFirst(m_gui->txtFind->text(),
m_gui->regularExpressionCheckBox->isChecked(),
m_gui->caseSensitiveCheckBox->isChecked(),
m_gui->wholeWordsCheckBox->isChecked(),
m_gui->wrapCheckBox->isChecked(),
m_gui->searchDownRadioButton->isChecked()))
{
pLUAViewWidget->ReplaceSelectedText(m_gui->txtReplaceWith->text());
int startLine = 0;
int startIndex = 0;
pLUAViewWidget->GetCursorPosition(startLine, startIndex);
pLUAViewWidget->SetCursorPosition(startLine, startIndex + 1);
count++;
}
}
return count;
}
void LUAEditorFindDialog::OnReplaceAll()
{
if (m_bFindThreadRunning)
{
QMessageBox::warning(this, "Error!", "You may not run Replace ALL while a Find All is running!");
return;
}
if (!m_gui->txtFind->text().isEmpty())
{
int theMode = m_gui->searchWhereComboBox->currentIndex();
if (!m_bAnyDocumentsOpen)
{
theMode = AllLUAAssets;
}
m_lastSearchWhere = theMode;
if (theMode == CurrentDoc)
{
BusyOn();
m_PendingReplaceInViewOperations.push_back(pLUAEditorMainWindow->GetCurrentView());
QTimer::singleShot(0, this, SLOT(OnReplaceInViewIterate()));
}
else if (theMode == AllOpenDocs || theMode == AllLUAAssets)
{
BusyOn();
AZStd::vector<LUAViewWidget*> dOpenView = pLUAEditorMainWindow->GetAllViews();
for (AZStd::vector<LUAViewWidget*>::iterator openViewIter = dOpenView.begin(); openViewIter != dOpenView.end(); ++openViewIter)
{
m_PendingReplaceInViewOperations.push_back(*openViewIter);
}
QTimer::singleShot(0, this, SLOT(OnReplaceInViewIterate()));
if (theMode == AllLUAAssets)
{
ReplaceInFilesSetUp();
emit triggerReplaceInFilesNext();
}
}
}
else
{
QMessageBox::warning(this, "Error!", "You may not replace an empty string!");
}
}
void LUAEditorFindDialog::BusyOn()
{
m_gui->cancelButton->setEnabled(true);
m_gui->busyLabel->setText("Working");
}
void LUAEditorFindDialog::BusyOff()
{
m_gui->cancelButton->setEnabled(false);
m_gui->busyLabel->setText("Idle");
}
void LUAEditorFindDialog::PostProcessOn()
{
m_gui->cancelButton->setEnabled(false);
m_gui->busyLabel->setText("List Prep");
}
void LUAEditorFindDialog::PostReplaceOn()
{
BusyOff();
m_bReplaceThreadRunning = false;
m_gui->cancelButton->setEnabled(true);
m_gui->busyLabel->setText("Replacing");
}
void LUAEditorFindDialog::showEvent(QShowEvent* event)
{
raise();
QDialog::showEvent(event);
}
void LUAEditorFindDialog::Reflect(AZ::ReflectContext* reflection)
{
LUAEditorInternal::FindSavedState::Reflect(reflection);
}
}//namespace LUAEditor
#include <Woodpecker/LUA/LUAEditorFindDialog.moc> | 39.020129 | 225 | 0.540597 | [
"vector"
] |
8b42d9914a46c8a1d6d923cf85c52cab58909a78 | 33,780 | cc | C++ | src/parsing/scanner-character-streams.cc | Durian2022/v8 | 2d02f1eadc087e4e48eecbfdf3731bb5a13876f3 | [
"BSD-3-Clause"
] | null | null | null | src/parsing/scanner-character-streams.cc | Durian2022/v8 | 2d02f1eadc087e4e48eecbfdf3731bb5a13876f3 | [
"BSD-3-Clause"
] | null | null | null | src/parsing/scanner-character-streams.cc | Durian2022/v8 | 2d02f1eadc087e4e48eecbfdf3731bb5a13876f3 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/parsing/scanner-character-streams.h"
#include <memory>
#include <vector>
#include "include/v8.h"
#include "src/common/globals.h"
#include "src/handles/handles.h"
#include "src/logging/runtime-call-stats-scope.h"
#include "src/objects/objects-inl.h"
#include "src/parsing/scanner.h"
#include "src/strings/unicode-inl.h"
namespace v8 {
namespace internal {
class V8_NODISCARD ScopedExternalStringLock {
public:
explicit ScopedExternalStringLock(ExternalString string) {
DCHECK(!string.is_null());
if (string.IsExternalOneByteString()) {
resource_ = ExternalOneByteString::cast(string).resource();
} else {
DCHECK(string.IsExternalTwoByteString());
resource_ = ExternalTwoByteString::cast(string).resource();
}
DCHECK(resource_);
resource_->Lock();
}
// Copying a lock increases the locking depth.
ScopedExternalStringLock(const ScopedExternalStringLock& other) V8_NOEXCEPT
: resource_(other.resource_) {
resource_->Lock();
}
~ScopedExternalStringLock() { resource_->Unlock(); }
private:
// Not nullptr.
const v8::String::ExternalStringResourceBase* resource_;
};
namespace {
const unibrow::uchar kUtf8Bom = 0xFEFF;
} // namespace
template <typename Char>
struct Range {
const Char* start;
const Char* end;
size_t length() { return static_cast<size_t>(end - start); }
bool unaligned_start() const {
return reinterpret_cast<intptr_t>(start) % sizeof(Char) == 1;
}
};
// A Char stream backed by an on-heap SeqOneByteString or SeqTwoByteString.
template <typename Char>
class OnHeapStream {
public:
using String = typename CharTraits<Char>::String;
OnHeapStream(Handle<String> string, size_t start_offset, size_t end)
: string_(string), start_offset_(start_offset), length_(end) {}
OnHeapStream(const OnHeapStream&) V8_NOEXCEPT : start_offset_(0), length_(0) {
UNREACHABLE();
}
// The no_gc argument is only here because of the templated way this class
// is used along with other implementations that require V8 heap access.
Range<Char> GetDataAt(size_t pos, RuntimeCallStats* stats,
DisallowGarbageCollection* no_gc) {
return {&string_->GetChars(*no_gc)[start_offset_ + std::min(length_, pos)],
&string_->GetChars(*no_gc)[start_offset_ + length_]};
}
static const bool kCanBeCloned = false;
static const bool kCanAccessHeap = true;
private:
Handle<String> string_;
const size_t start_offset_;
const size_t length_;
};
// A Char stream backed by an off-heap ExternalOneByteString or
// ExternalTwoByteString.
template <typename Char>
class ExternalStringStream {
using ExternalString = typename CharTraits<Char>::ExternalString;
public:
ExternalStringStream(ExternalString string, size_t start_offset,
size_t length)
: lock_(string),
data_(string.GetChars() + start_offset),
length_(length) {}
ExternalStringStream(const ExternalStringStream& other) V8_NOEXCEPT
: lock_(other.lock_),
data_(other.data_),
length_(other.length_) {}
// The no_gc argument is only here because of the templated way this class
// is used along with other implementations that require V8 heap access.
Range<Char> GetDataAt(size_t pos, RuntimeCallStats* stats,
DisallowGarbageCollection* no_gc = nullptr) {
return {&data_[std::min(length_, pos)], &data_[length_]};
}
static const bool kCanBeCloned = true;
static const bool kCanAccessHeap = false;
private:
ScopedExternalStringLock lock_;
const Char* const data_;
const size_t length_;
};
// A Char stream backed by a C array. Testing only.
template <typename Char>
class TestingStream {
public:
TestingStream(const Char* data, size_t length)
: data_(data), length_(length) {}
// The no_gc argument is only here because of the templated way this class
// is used along with other implementations that require V8 heap access.
Range<Char> GetDataAt(size_t pos, RuntimeCallStats* stats,
DisallowGarbageCollection* no_gc = nullptr) {
return {&data_[std::min(length_, pos)], &data_[length_]};
}
static const bool kCanBeCloned = true;
static const bool kCanAccessHeap = false;
private:
const Char* const data_;
const size_t length_;
};
// A Char stream backed by multiple source-stream provided off-heap chunks.
template <typename Char>
class ChunkedStream {
public:
explicit ChunkedStream(ScriptCompiler::ExternalSourceStream* source)
: source_(source) {}
ChunkedStream(const ChunkedStream&) V8_NOEXCEPT {
// TODO(rmcilroy): Implement cloning for chunked streams.
UNREACHABLE();
}
// The no_gc argument is only here because of the templated way this class
// is used along with other implementations that require V8 heap access.
Range<Char> GetDataAt(size_t pos, RuntimeCallStats* stats,
DisallowGarbageCollection* no_gc = nullptr) {
Chunk chunk = FindChunk(pos, stats);
size_t buffer_end = chunk.length;
size_t buffer_pos = std::min(buffer_end, pos - chunk.position);
return {&chunk.data[buffer_pos], &chunk.data[buffer_end]};
}
~ChunkedStream() {
for (Chunk& chunk : chunks_) delete[] chunk.data;
}
static const bool kCanBeCloned = false;
static const bool kCanAccessHeap = false;
private:
struct Chunk {
Chunk(const Char* const data, size_t position, size_t length)
: data(data), position(position), length(length) {}
const Char* const data;
// The logical position of data.
const size_t position;
const size_t length;
size_t end_position() const { return position + length; }
};
Chunk FindChunk(size_t position, RuntimeCallStats* stats) {
while (V8_UNLIKELY(chunks_.empty())) FetchChunk(size_t{0}, stats);
// Walk forwards while the position is in front of the current chunk.
while (position >= chunks_.back().end_position() &&
chunks_.back().length > 0) {
FetchChunk(chunks_.back().end_position(), stats);
}
// Walk backwards.
for (auto reverse_it = chunks_.rbegin(); reverse_it != chunks_.rend();
++reverse_it) {
if (reverse_it->position <= position) return *reverse_it;
}
UNREACHABLE();
}
virtual void ProcessChunk(const uint8_t* data, size_t position,
size_t length) {
// Incoming data has to be aligned to Char size.
DCHECK_EQ(0, length % sizeof(Char));
chunks_.emplace_back(reinterpret_cast<const Char*>(data), position,
length / sizeof(Char));
}
void FetchChunk(size_t position, RuntimeCallStats* stats) {
const uint8_t* data = nullptr;
size_t length;
{
RCS_SCOPE(stats, RuntimeCallCounterId::kGetMoreDataCallback);
length = source_->GetMoreData(&data);
}
ProcessChunk(data, position, length);
}
ScriptCompiler::ExternalSourceStream* source_;
protected:
std::vector<struct Chunk> chunks_;
};
// Provides a buffered utf-16 view on the bytes from the underlying ByteStream.
// Chars are buffered if either the underlying stream isn't utf-16 or the
// underlying utf-16 stream might move (is on-heap).
template <template <typename T> class ByteStream>
class BufferedCharacterStream : public Utf16CharacterStream {
public:
template <class... TArgs>
BufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) {
buffer_pos_ = pos;
}
bool can_be_cloned() const final {
return ByteStream<uint16_t>::kCanBeCloned;
}
std::unique_ptr<Utf16CharacterStream> Clone() const override {
CHECK(can_be_cloned());
return std::unique_ptr<Utf16CharacterStream>(
new BufferedCharacterStream<ByteStream>(*this));
}
protected:
bool ReadBlock() final {
size_t position = pos();
buffer_pos_ = position;
buffer_start_ = &buffer_[0];
buffer_cursor_ = buffer_start_;
DisallowGarbageCollection no_gc;
Range<uint8_t> range =
byte_stream_.GetDataAt(position, runtime_call_stats(), &no_gc);
if (range.length() == 0) {
buffer_end_ = buffer_start_;
return false;
}
size_t length = std::min({kBufferSize, range.length()});
i::CopyChars(buffer_, range.start, length);
buffer_end_ = &buffer_[length];
return true;
}
bool can_access_heap() const final {
return ByteStream<uint8_t>::kCanAccessHeap;
}
private:
BufferedCharacterStream(const BufferedCharacterStream<ByteStream>& other)
: byte_stream_(other.byte_stream_) {}
static const size_t kBufferSize = 512;
uc16 buffer_[kBufferSize];
ByteStream<uint8_t> byte_stream_;
};
// Provides a unbuffered utf-16 view on the bytes from the underlying
// ByteStream.
template <template <typename T> class ByteStream>
class UnbufferedCharacterStream : public Utf16CharacterStream {
public:
template <class... TArgs>
UnbufferedCharacterStream(size_t pos, TArgs... args) : byte_stream_(args...) {
buffer_pos_ = pos;
}
bool can_access_heap() const final {
return ByteStream<uint16_t>::kCanAccessHeap;
}
bool can_be_cloned() const final {
return ByteStream<uint16_t>::kCanBeCloned;
}
std::unique_ptr<Utf16CharacterStream> Clone() const override {
return std::unique_ptr<Utf16CharacterStream>(
new UnbufferedCharacterStream<ByteStream>(*this));
}
protected:
bool ReadBlock() final {
size_t position = pos();
buffer_pos_ = position;
DisallowGarbageCollection no_gc;
Range<uint16_t> range =
byte_stream_.GetDataAt(position, runtime_call_stats(), &no_gc);
buffer_start_ = range.start;
buffer_end_ = range.end;
buffer_cursor_ = buffer_start_;
if (range.length() == 0) return false;
DCHECK(!range.unaligned_start());
DCHECK_LE(buffer_start_, buffer_end_);
return true;
}
UnbufferedCharacterStream(const UnbufferedCharacterStream<ByteStream>& other)
: byte_stream_(other.byte_stream_) {}
ByteStream<uint16_t> byte_stream_;
};
// Provides a unbuffered utf-16 view on the bytes from the underlying
// ByteStream.
class RelocatingCharacterStream final
: public UnbufferedCharacterStream<OnHeapStream> {
public:
template <class... TArgs>
RelocatingCharacterStream(Isolate* isolate, size_t pos, TArgs... args)
: UnbufferedCharacterStream<OnHeapStream>(pos, args...),
isolate_(isolate) {
isolate->heap()->AddGCEpilogueCallback(UpdateBufferPointersCallback,
v8::kGCTypeAll, this);
}
private:
~RelocatingCharacterStream() final {
isolate_->heap()->RemoveGCEpilogueCallback(UpdateBufferPointersCallback,
this);
}
static void UpdateBufferPointersCallback(v8::Isolate* v8_isolate,
v8::GCType type,
v8::GCCallbackFlags flags,
void* stream) {
reinterpret_cast<RelocatingCharacterStream*>(stream)
->UpdateBufferPointers();
}
void UpdateBufferPointers() {
DisallowGarbageCollection no_gc;
Range<uint16_t> range =
byte_stream_.GetDataAt(buffer_pos_, runtime_call_stats(), &no_gc);
if (range.start != buffer_start_) {
buffer_cursor_ = (buffer_cursor_ - buffer_start_) + range.start;
buffer_start_ = range.start;
buffer_end_ = range.end;
}
}
Isolate* isolate_;
};
// ----------------------------------------------------------------------------
// BufferedUtf16CharacterStreams
//
// A buffered character stream based on a random access character
// source (ReadBlock can be called with pos() pointing to any position,
// even positions before the current).
//
// TODO(verwaest): Remove together with Utf8 external streaming streams.
class BufferedUtf16CharacterStream : public Utf16CharacterStream {
public:
BufferedUtf16CharacterStream();
protected:
static const size_t kBufferSize = 512;
bool ReadBlock() final;
// FillBuffer should read up to kBufferSize characters at position and store
// them into buffer_[0..]. It returns the number of characters stored.
virtual size_t FillBuffer(size_t position) = 0;
// Fixed sized buffer that this class reads from.
// The base class' buffer_start_ should always point to buffer_.
uc16 buffer_[kBufferSize];
};
BufferedUtf16CharacterStream::BufferedUtf16CharacterStream()
: Utf16CharacterStream(buffer_, buffer_, buffer_, 0) {}
bool BufferedUtf16CharacterStream::ReadBlock() {
DCHECK_EQ(buffer_start_, buffer_);
size_t position = pos();
buffer_pos_ = position;
buffer_cursor_ = buffer_;
buffer_end_ = buffer_ + FillBuffer(position);
DCHECK_EQ(pos(), position);
DCHECK_LE(buffer_end_, buffer_start_ + kBufferSize);
return buffer_cursor_ < buffer_end_;
}
// ----------------------------------------------------------------------------
// Windows1252CharacterStream - chunked streaming of windows-1252 data.
//
// Similar to BufferedCharacterStream, but does the translation of
// windows-1252 that are incompatible with their latin-1 equivalents.
namespace {
static const uc16 kWindows1252ToUC16[256] = {
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, // 00-07
0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, // 08-0F
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, // 10-17
0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, // 18-1F
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, // 20-27
0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, // 28-2F
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, // 30-37
0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, // 38-3F
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, // 40-47
0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, // 48-4F
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, // 50-57
0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, // 58-5F
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, // 60-67
0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, // 68-6F
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, // 70-77
0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F, // 78-7F
0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, // 80-87
0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, // 88-8F
0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, // 90-97
0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, // 98-9F
0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, // A0-A7
0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, // A8-AF
0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, // B0-B7
0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, // B8-BF
0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, // C0-C7
0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, // C8-CF
0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, // D0-D7
0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, // D8-DF
0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, // E0-E7
0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, // E8-EF
0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, // F0-F7
0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF // F8-FF
};
} // namespace
class Windows1252CharacterStream final : public Utf16CharacterStream {
public:
Windows1252CharacterStream(
size_t pos, ScriptCompiler::ExternalSourceStream* source_stream)
: byte_stream_(source_stream) {
buffer_pos_ = pos;
}
bool can_be_cloned() const final {
return ChunkedStream<uint16_t>::kCanBeCloned;
}
std::unique_ptr<Utf16CharacterStream> Clone() const override {
CHECK(can_be_cloned());
return std::unique_ptr<Utf16CharacterStream>(
new Windows1252CharacterStream(*this));
}
protected:
bool ReadBlock() final {
size_t position = pos();
buffer_pos_ = position;
buffer_start_ = &buffer_[0];
buffer_cursor_ = buffer_start_;
DisallowGarbageCollection no_gc;
Range<uint8_t> range =
byte_stream_.GetDataAt(position, runtime_call_stats(), &no_gc);
if (range.length() == 0) {
buffer_end_ = buffer_start_;
return false;
}
size_t length = std::min({kBufferSize, range.length()});
std::transform(range.start, range.start + length, &buffer_[0],
[](uint8_t c) { return kWindows1252ToUC16[c]; });
buffer_end_ = &buffer_[length];
return true;
}
bool can_access_heap() const final {
return ChunkedStream<uint8_t>::kCanAccessHeap;
}
private:
Windows1252CharacterStream(const Windows1252CharacterStream& other)
V8_NOEXCEPT : byte_stream_(other.byte_stream_) {}
static const size_t kBufferSize = 512;
uc16 buffer_[kBufferSize];
ChunkedStream<uint8_t> byte_stream_;
};
// ----------------------------------------------------------------------------
// Utf8ExternalStreamingStream - chunked streaming of Utf-8 data.
//
// This implementation is fairly complex, since data arrives in chunks which
// may 'cut' arbitrarily into utf-8 characters. Also, seeking to a given
// character position is tricky because the byte position cannot be derived
// from the character position.
//
// TODO(verwaest): Decode utf8 chunks into utf16 chunks on the blink side
// instead so we don't need to buffer.
class Utf8ExternalStreamingStream final : public BufferedUtf16CharacterStream {
public:
Utf8ExternalStreamingStream(
ScriptCompiler::ExternalSourceStream* source_stream)
: current_({0, {0, 0, 0, unibrow::Utf8::State::kAccept}}),
source_stream_(source_stream) {}
~Utf8ExternalStreamingStream() final {
for (const Chunk& chunk : chunks_) delete[] chunk.data;
}
bool can_access_heap() const final { return false; }
bool can_be_cloned() const final { return false; }
std::unique_ptr<Utf16CharacterStream> Clone() const override {
UNREACHABLE();
}
protected:
size_t FillBuffer(size_t position) final;
private:
// A position within the data stream. It stores:
// - The 'physical' position (# of bytes in the stream),
// - the 'logical' position (# of ucs-2 characters, also within the stream),
// - a possibly incomplete utf-8 char at the current 'physical' position.
struct StreamPosition {
size_t bytes;
size_t chars;
uint32_t incomplete_char;
unibrow::Utf8::State state;
};
// Position contains a StreamPosition and the index of the chunk the position
// points into. (The chunk_no could be derived from pos, but that'd be
// an expensive search through all chunks.)
struct Position {
size_t chunk_no;
StreamPosition pos;
};
// A chunk in the list of chunks, containing:
// - The chunk data (data pointer and length), and
// - the position at the first byte of the chunk.
struct Chunk {
const uint8_t* data;
size_t length;
StreamPosition start;
};
// Within the current chunk, skip forward from current_ towards position.
bool SkipToPosition(size_t position);
// Within the current chunk, fill the buffer_ (while it has capacity).
void FillBufferFromCurrentChunk();
// Fetch a new chunk (assuming current_ is at the end of the current data).
bool FetchChunk();
// Search through the chunks and set current_ to point to the given position.
// (This call is potentially expensive.)
void SearchPosition(size_t position);
std::vector<Chunk> chunks_;
Position current_;
ScriptCompiler::ExternalSourceStream* source_stream_;
};
bool Utf8ExternalStreamingStream::SkipToPosition(size_t position) {
DCHECK_LE(current_.pos.chars, position); // We can only skip forward.
// Already there? Then return immediately.
if (current_.pos.chars == position) return true;
const Chunk& chunk = chunks_[current_.chunk_no];
DCHECK(current_.pos.bytes >= chunk.start.bytes);
unibrow::Utf8::State state = chunk.start.state;
uint32_t incomplete_char = chunk.start.incomplete_char;
size_t it = current_.pos.bytes - chunk.start.bytes;
const uint8_t* cursor = &chunk.data[it];
const uint8_t* end = &chunk.data[chunk.length];
size_t chars = current_.pos.chars;
if (V8_UNLIKELY(current_.pos.bytes < 3 && chars == 0)) {
while (cursor < end) {
unibrow::uchar t =
unibrow::Utf8::ValueOfIncremental(&cursor, &state, &incomplete_char);
if (t == unibrow::Utf8::kIncomplete) continue;
if (t != kUtf8Bom) {
chars++;
if (t > unibrow::Utf16::kMaxNonSurrogateCharCode) chars++;
}
break;
}
}
while (cursor < end && chars < position) {
unibrow::uchar t =
unibrow::Utf8::ValueOfIncremental(&cursor, &state, &incomplete_char);
if (t != unibrow::Utf8::kIncomplete) {
chars++;
if (t > unibrow::Utf16::kMaxNonSurrogateCharCode) chars++;
}
}
current_.pos.bytes = chunk.start.bytes + (cursor - chunk.data);
current_.pos.chars = chars;
current_.pos.incomplete_char = incomplete_char;
current_.pos.state = state;
current_.chunk_no += (cursor == end);
return current_.pos.chars == position;
}
void Utf8ExternalStreamingStream::FillBufferFromCurrentChunk() {
DCHECK_LT(current_.chunk_no, chunks_.size());
DCHECK_EQ(buffer_start_, buffer_cursor_);
DCHECK_LT(buffer_end_ + 1, buffer_start_ + kBufferSize);
const Chunk& chunk = chunks_[current_.chunk_no];
// The buffer_ is writable, but buffer_*_ members are const. So we get a
// non-const pointer into buffer that points to the same char as buffer_end_.
uint16_t* output_cursor = buffer_ + (buffer_end_ - buffer_start_);
DCHECK_EQ(output_cursor, buffer_end_);
unibrow::Utf8::State state = current_.pos.state;
uint32_t incomplete_char = current_.pos.incomplete_char;
// If the current chunk is the last (empty) chunk we'll have to process
// any left-over, partial characters.
if (chunk.length == 0) {
unibrow::uchar t = unibrow::Utf8::ValueOfIncrementalFinish(&state);
if (t != unibrow::Utf8::kBufferEmpty) {
DCHECK_EQ(t, unibrow::Utf8::kBadChar);
*output_cursor = static_cast<uc16>(t);
buffer_end_++;
current_.pos.chars++;
current_.pos.incomplete_char = 0;
current_.pos.state = state;
}
return;
}
size_t it = current_.pos.bytes - chunk.start.bytes;
const uint8_t* cursor = chunk.data + it;
const uint8_t* end = chunk.data + chunk.length;
// Deal with possible BOM.
if (V8_UNLIKELY(current_.pos.bytes < 3 && current_.pos.chars == 0)) {
while (cursor < end) {
unibrow::uchar t =
unibrow::Utf8::ValueOfIncremental(&cursor, &state, &incomplete_char);
if (V8_LIKELY(t < kUtf8Bom)) {
*(output_cursor++) = static_cast<uc16>(t); // The most frequent case.
} else if (t == unibrow::Utf8::kIncomplete) {
continue;
} else if (t == kUtf8Bom) {
// BOM detected at beginning of the stream. Don't copy it.
} else if (t <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
*(output_cursor++) = static_cast<uc16>(t);
} else {
*(output_cursor++) = unibrow::Utf16::LeadSurrogate(t);
*(output_cursor++) = unibrow::Utf16::TrailSurrogate(t);
}
break;
}
}
const uint16_t* max_buffer_end = buffer_start_ + kBufferSize;
while (cursor < end && output_cursor + 1 < max_buffer_end) {
unibrow::uchar t =
unibrow::Utf8::ValueOfIncremental(&cursor, &state, &incomplete_char);
if (V8_LIKELY(t <= unibrow::Utf16::kMaxNonSurrogateCharCode)) {
*(output_cursor++) = static_cast<uc16>(t); // The most frequent case.
} else if (t == unibrow::Utf8::kIncomplete) {
continue;
} else {
*(output_cursor++) = unibrow::Utf16::LeadSurrogate(t);
*(output_cursor++) = unibrow::Utf16::TrailSurrogate(t);
}
// Fast path for ascii sequences.
size_t remaining = end - cursor;
size_t max_buffer = max_buffer_end - output_cursor;
int max_length = static_cast<int>(std::min(remaining, max_buffer));
DCHECK_EQ(state, unibrow::Utf8::State::kAccept);
int ascii_length = NonAsciiStart(cursor, max_length);
CopyChars(output_cursor, cursor, ascii_length);
cursor += ascii_length;
output_cursor += ascii_length;
}
current_.pos.bytes = chunk.start.bytes + (cursor - chunk.data);
current_.pos.chars += (output_cursor - buffer_end_);
current_.pos.incomplete_char = incomplete_char;
current_.pos.state = state;
current_.chunk_no += (cursor == end);
buffer_end_ = output_cursor;
}
bool Utf8ExternalStreamingStream::FetchChunk() {
RCS_SCOPE(runtime_call_stats(), RuntimeCallCounterId::kGetMoreDataCallback);
DCHECK_EQ(current_.chunk_no, chunks_.size());
DCHECK(chunks_.empty() || chunks_.back().length != 0);
const uint8_t* chunk = nullptr;
size_t length = source_stream_->GetMoreData(&chunk);
chunks_.push_back({chunk, length, current_.pos});
return length > 0;
}
void Utf8ExternalStreamingStream::SearchPosition(size_t position) {
// If current_ already points to the right position, we're done.
//
// This is expected to be the common case, since we typically call
// FillBuffer right after the current buffer.
if (current_.pos.chars == position) return;
// No chunks. Fetch at least one, so we can assume !chunks_.empty() below.
if (chunks_.empty()) {
DCHECK_EQ(current_.chunk_no, 0u);
DCHECK_EQ(current_.pos.bytes, 0u);
DCHECK_EQ(current_.pos.chars, 0u);
FetchChunk();
}
// Search for the last chunk whose start position is less or equal to
// position.
size_t chunk_no = chunks_.size() - 1;
while (chunk_no > 0 && chunks_[chunk_no].start.chars > position) {
chunk_no--;
}
// Did we find the terminating (zero-length) chunk? Then we're seeking
// behind the end of the data, and position does not exist.
// Set current_ to point to the terminating chunk.
if (chunks_[chunk_no].length == 0) {
current_ = {chunk_no, chunks_[chunk_no].start};
return;
}
// Did we find the non-last chunk? Then our position must be within chunk_no.
if (chunk_no + 1 < chunks_.size()) {
// Fancy-pants optimization for ASCII chunks within a utf-8 stream.
// (Many web sites declare utf-8 encoding, but use only (or almost only) the
// ASCII subset for their JavaScript sources. We can exploit this, by
// checking whether the # bytes in a chunk are equal to the # chars, and if
// so avoid the expensive SkipToPosition.)
bool ascii_only_chunk =
chunks_[chunk_no].start.incomplete_char == 0 &&
(chunks_[chunk_no + 1].start.bytes - chunks_[chunk_no].start.bytes) ==
(chunks_[chunk_no + 1].start.chars - chunks_[chunk_no].start.chars);
if (ascii_only_chunk) {
size_t skip = position - chunks_[chunk_no].start.chars;
current_ = {chunk_no,
{chunks_[chunk_no].start.bytes + skip,
chunks_[chunk_no].start.chars + skip, 0,
unibrow::Utf8::State::kAccept}};
} else {
current_ = {chunk_no, chunks_[chunk_no].start};
SkipToPosition(position);
}
// Since position was within the chunk, SkipToPosition should have found
// something.
DCHECK_EQ(position, current_.pos.chars);
return;
}
// What's left: We're in the last, non-terminating chunk. Our position
// may be in the chunk, but it may also be in 'future' chunks, which we'll
// have to obtain.
DCHECK_EQ(chunk_no, chunks_.size() - 1);
current_ = {chunk_no, chunks_[chunk_no].start};
bool have_more_data = true;
bool found = SkipToPosition(position);
while (have_more_data && !found) {
DCHECK_EQ(current_.chunk_no, chunks_.size());
have_more_data = FetchChunk();
found = have_more_data && SkipToPosition(position);
}
// We'll return with a postion != the desired position only if we're out
// of data. In that case, we'll point to the terminating chunk.
DCHECK_EQ(found, current_.pos.chars == position);
DCHECK_EQ(have_more_data, chunks_.back().length != 0);
DCHECK_IMPLIES(!found, !have_more_data);
DCHECK_IMPLIES(!found, current_.chunk_no == chunks_.size() - 1);
}
size_t Utf8ExternalStreamingStream::FillBuffer(size_t position) {
buffer_cursor_ = buffer_;
buffer_end_ = buffer_;
SearchPosition(position);
bool out_of_data = current_.chunk_no != chunks_.size() &&
chunks_[current_.chunk_no].length == 0 &&
current_.pos.incomplete_char == 0;
if (out_of_data) return 0;
// Fill the buffer, until we have at least one char (or are out of data).
// (The embedder might give us 1-byte blocks within a utf-8 char, so we
// can't guarantee progress with one chunk. Thus we iterate.)
while (!out_of_data && buffer_cursor_ == buffer_end_) {
// At end of current data, but there might be more? Then fetch it.
if (current_.chunk_no == chunks_.size()) {
out_of_data = !FetchChunk();
}
FillBufferFromCurrentChunk();
}
DCHECK_EQ(current_.pos.chars - position,
static_cast<size_t>(buffer_end_ - buffer_cursor_));
return buffer_end_ - buffer_cursor_;
}
// ----------------------------------------------------------------------------
// ScannerStream: Create stream instances.
Utf16CharacterStream* ScannerStream::For(Isolate* isolate,
Handle<String> data) {
return ScannerStream::For(isolate, data, 0, data->length());
}
Utf16CharacterStream* ScannerStream::For(Isolate* isolate, Handle<String> data,
int start_pos, int end_pos) {
DCHECK_GE(start_pos, 0);
DCHECK_LE(start_pos, end_pos);
DCHECK_LE(end_pos, data->length());
size_t start_offset = 0;
if (data->IsSlicedString()) {
SlicedString string = SlicedString::cast(*data);
start_offset = string.offset();
String parent = string.parent();
if (parent.IsThinString()) parent = ThinString::cast(parent).actual();
data = handle(parent, isolate);
} else {
data = String::Flatten(isolate, data);
}
if (data->IsExternalOneByteString()) {
return new BufferedCharacterStream<ExternalStringStream>(
static_cast<size_t>(start_pos), ExternalOneByteString::cast(*data),
start_offset, static_cast<size_t>(end_pos));
} else if (data->IsExternalTwoByteString()) {
return new UnbufferedCharacterStream<ExternalStringStream>(
static_cast<size_t>(start_pos), ExternalTwoByteString::cast(*data),
start_offset, static_cast<size_t>(end_pos));
} else if (data->IsSeqOneByteString()) {
return new BufferedCharacterStream<OnHeapStream>(
static_cast<size_t>(start_pos), Handle<SeqOneByteString>::cast(data),
start_offset, static_cast<size_t>(end_pos));
} else if (data->IsSeqTwoByteString()) {
return new RelocatingCharacterStream(
isolate, static_cast<size_t>(start_pos),
Handle<SeqTwoByteString>::cast(data), start_offset,
static_cast<size_t>(end_pos));
} else {
UNREACHABLE();
}
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const char* data) {
return ScannerStream::ForTesting(data, strlen(data));
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const char* data, size_t length) {
if (data == nullptr) {
DCHECK_EQ(length, 0);
// We don't want to pass in a null pointer into the the character stream,
// because then the one-past-the-end pointer is undefined, so instead pass
// through this static array.
static const char non_null_empty_string[1] = {0};
data = non_null_empty_string;
}
return std::unique_ptr<Utf16CharacterStream>(
new BufferedCharacterStream<TestingStream>(
0, reinterpret_cast<const uint8_t*>(data), length));
}
std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
const uint16_t* data, size_t length) {
if (data == nullptr) {
DCHECK_EQ(length, 0);
// We don't want to pass in a null pointer into the the character stream,
// because then the one-past-the-end pointer is undefined, so instead pass
// through this static array.
static const uint16_t non_null_empty_uint16_t_string[1] = {0};
data = non_null_empty_uint16_t_string;
}
return std::unique_ptr<Utf16CharacterStream>(
new UnbufferedCharacterStream<TestingStream>(0, data, length));
}
Utf16CharacterStream* ScannerStream::For(
ScriptCompiler::ExternalSourceStream* source_stream,
v8::ScriptCompiler::StreamedSource::Encoding encoding) {
switch (encoding) {
case v8::ScriptCompiler::StreamedSource::TWO_BYTE:
return new UnbufferedCharacterStream<ChunkedStream>(
static_cast<size_t>(0), source_stream);
case v8::ScriptCompiler::StreamedSource::ONE_BYTE:
return new BufferedCharacterStream<ChunkedStream>(static_cast<size_t>(0),
source_stream);
case v8::ScriptCompiler::StreamedSource::WINDOWS_1252:
return new Windows1252CharacterStream(static_cast<size_t>(0),
source_stream);
case v8::ScriptCompiler::StreamedSource::UTF8:
return new Utf8ExternalStreamingStream(source_stream);
}
UNREACHABLE();
}
} // namespace internal
} // namespace v8
| 35.821845 | 80 | 0.684725 | [
"vector",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.