hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 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 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4b3e15649008fff3ff878c272fb4d0dc5fe8314f | 1,134 | cpp | C++ | heap_sort.cpp | MDarshan123/Algorithms-1 | c077ef399f4fea59f683c0338e56d1a87a79a466 | [
"MIT"
] | 33 | 2019-10-20T03:07:31.000Z | 2021-12-05T06:50:12.000Z | heap_sort.cpp | MDarshan123/Algorithms-1 | c077ef399f4fea59f683c0338e56d1a87a79a466 | [
"MIT"
] | 51 | 2019-10-09T18:09:53.000Z | 2021-07-06T08:28:39.000Z | heap_sort.cpp | MDarshan123/Algorithms-1 | c077ef399f4fea59f683c0338e56d1a87a79a466 | [
"MIT"
] | 117 | 2019-10-09T18:10:58.000Z | 2022-02-22T14:22:47.000Z | # Python program for implementation of heap Sort
# To heapify subtree rooted at index i.
# n is size of heap
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and arr[i] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# Driver code to test above
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
# This code is contributed by Mohit Kumra
| 23.625 | 51 | 0.603175 | MDarshan123 |
4b40cb282bccefe5f63fcfea11d1405e9c6c359e | 16,227 | cc | C++ | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/src/contrib/random/sgx_random_engine.cc | mengkai94/training_results_v0.6 | 43dc3e250f8da47b5f8833197d74cb8cf1004fc9 | [
"Apache-2.0"
] | 64 | 2021-05-02T14:42:34.000Z | 2021-05-06T01:35:03.000Z | src/contrib/random/sgx_random_engine.cc | clhne/tvm | d59320c764bd09474775e1b292f3c05c27743d24 | [
"Apache-2.0"
] | 23 | 2019-07-29T05:21:52.000Z | 2020-08-31T18:51:42.000Z | src/contrib/random/sgx_random_engine.cc | clhne/tvm | d59320c764bd09474775e1b292f3c05c27743d24 | [
"Apache-2.0"
] | 51 | 2019-07-12T05:10:25.000Z | 2021-07-28T16:19:06.000Z | /*!
* Copyright (c) 2018 by Contributors
* \file random/sgx_random_engine.h
* \brief SGX trusted random engine
*/
#include <dmlc/logging.h>
#include <sgx_trts.h>
#include <algorithm>
#include <cmath>
#include "../../runtime/sgx/common.h"
namespace tvm {
namespace contrib {
/*!
* \brief An interface for generating [tensors of] random numbers.
*/
class RandomEngine {
public:
/*!
* \brief Creates a RandomEngine, suggesting the use of a provided seed.
*/
explicit RandomEngine(unsigned seed) {
LOG(WARNING) << "SGX RandomEngine does not support seeding.";
}
/*!
* \brief Seeds the underlying RNG, if possible.
*/
inline void Seed(unsigned seed) {
LOG(WARNING) << "SGX RandomEngine does not support seeding.";
}
/*!
* \return the seed associated with the underlying RNG.
*/
inline unsigned GetSeed() const {
LOG(WARNING) << "SGX RandomEngine does not support seeding.";
return 0;
}
/*!
* \return a random integer sampled from the RNG.
*/
inline unsigned GetRandInt() {
int rand_int;
TVM_SGX_CHECKED_CALL(
sgx_read_rand(reinterpret_cast<unsigned char*>(&rand_int), sizeof(int)));
return rand_int;
}
/*!
* \return a random integer sampled from Unif(low, high).
*/
inline float GetUniform(float low, float high) {
float max_int = static_cast<float>(std::numeric_limits<unsigned>::max());
float unif01 = GetRandInt() / max_int;
return low + unif01 * (high - low);
}
/*!
* \return a random value sampled from Normal(loc, scale**2).
*/
inline float GetNormal(float loc, float scale) {
float sign = GetUniform(-1, 1);
float sample = GetStandardNormalOneside();
return loc + (sign > 0 ? scale : -scale) * sample;
}
/*!
* \brief Fills a tensor with values drawn from Unif(low, high)
*/
void SampleUniform(DLTensor* data, float low, float high) {
CHECK_GT(high, low) << "high must be bigger than low";
CHECK(data->strides == nullptr);
DLDataType dtype = data->dtype;
int64_t size = 1;
for (int i = 0; i < data->ndim; ++i) {
size *= data->shape[i];
}
CHECK(dtype.code == kDLFloat && dtype.bits == 32 && dtype.lanes == 1);
std::generate_n(static_cast<float*>(data->data), size, [&] () {
float max_int = static_cast<float>(std::numeric_limits<unsigned>::max());
float unif01 = GetRandInt() / max_int;
return low + unif01 * (high - low);
});
}
/*!
* \brief Fills a tensor with values drawn from Normal(loc, scale)
*/
void SampleNormal(DLTensor* data, float loc, float scale) {
CHECK_GT(scale, 0) << "scale must be positive";
CHECK(data->strides == nullptr);
DLDataType dtype = data->dtype;
int64_t size = 1;
for (int i = 0; i < data->ndim; ++i) {
size *= data->shape[i];
}
CHECK(dtype.code == kDLFloat && dtype.bits == 32 && dtype.lanes == 1);
std::generate_n(static_cast<float*>(data->data), size, [&] () {
return GetNormal(loc, scale);
});
}
private:
/*!
* \return a random value sampled from Normal(0, 1) such that the
* sampled value is greater than tail
*/
inline float GetStandardNormalTail(float tail) {
while (true) {
float u1 = GetUniform(0, 1);
float u2 = GetUniform(0, 1);
float x = - log(u1) / tail;
float y = - log(u2);
if (2 * y < x * x) {
return x + tail;
}
}
}
/*!
* \return a random positive value sampled from Normal(0, 1).
*/
inline float GetStandardNormalOneside() {
while (true) {
unsigned i = GetRandInt() & 255;
float x = GetUniform(0, ZIG_NORM_X[i]);
if (x < ZIG_NORM_X[i+1]) {
return x;
}
if (i == 0) {
return GetStandardNormalTail(ZIG_NORM_X[1]);
}
float y = GetUniform(ZIG_NORM_F[i], ZIG_NORM_F[i+1]);
if (y < exp(-0.5 * x * x)) {
return x;
}
}
}
/*!
* Tables for normal distribution which is sampled using the ziggurat algorithm.
*/
static constexpr float ZIG_NORM_X[257] =
{3.910757959537090045, 3.654152885361008796, 3.449278298560964462, 3.320244733839166074,
3.224575052047029100, 3.147889289517149969, 3.083526132001233044, 3.027837791768635434,
2.978603279880844834, 2.934366867207854224, 2.894121053612348060, 2.857138730872132548,
2.822877396825325125, 2.790921174000785765, 2.760944005278822555, 2.732685359042827056,
2.705933656121858100, 2.680514643284522158, 2.656283037575502437, 2.633116393630324570,
2.610910518487548515, 2.589575986706995181, 2.569035452680536569, 2.549221550323460761,
2.530075232158516929, 2.511544441625342294, 2.493583041269680667, 2.476149939669143318,
2.459208374333311298, 2.442725318198956774, 2.426670984935725972, 2.411018413899685520,
2.395743119780480601, 2.380822795170626005, 2.366237056715818632, 2.351967227377659952,
2.337996148795031370, 2.324308018869623016, 2.310888250599850036, 2.297723348901329565,
2.284800802722946056, 2.272108990226823888, 2.259637095172217780, 2.247375032945807760,
2.235313384928327984, 2.223443340090905718, 2.211756642882544366, 2.200245546609647995,
2.188902771624720689, 2.177721467738641614, 2.166695180352645966, 2.155817819875063268,
2.145083634046203613, 2.134487182844320152, 2.124023315687815661, 2.113687150684933957,
2.103474055713146829, 2.093379631137050279, 2.083399693996551783, 2.073530263516978778,
2.063767547809956415, 2.054107931648864849, 2.044547965215732788, 2.035084353727808715,
2.025713947862032960, 2.016433734904371722, 2.007240830558684852, 1.998132471356564244,
1.989106007615571325, 1.980158896898598364, 1.971288697931769640, 1.962493064942461896,
1.953769742382734043, 1.945116560006753925, 1.936531428273758904, 1.928012334050718257,
1.919557336591228847, 1.911164563769282232, 1.902832208548446369, 1.894558525668710081,
1.886341828534776388, 1.878180486290977669, 1.870072921069236838, 1.862017605397632281,
1.854013059758148119, 1.846057850283119750, 1.838150586580728607, 1.830289919680666566,
1.822474540091783224, 1.814703175964167636, 1.806974591348693426, 1.799287584547580199,
1.791640986550010028, 1.784033659547276329, 1.776464495522344977, 1.768932414909077933,
1.761436365316706665, 1.753975320315455111, 1.746548278279492994, 1.739154261283669012,
1.731792314050707216, 1.724461502945775715, 1.717160915015540690, 1.709889657069006086,
1.702646854797613907, 1.695431651932238548, 1.688243209434858727, 1.681080704722823338,
1.673943330923760353, 1.666830296159286684, 1.659740822855789499, 1.652674147080648526,
1.645629517902360339, 1.638606196773111146, 1.631603456932422036, 1.624620582830568427,
1.617656869570534228, 1.610711622367333673, 1.603784156023583041, 1.596873794420261339,
1.589979870021648534, 1.583101723393471438, 1.576238702733332886, 1.569390163412534456,
1.562555467528439657, 1.555733983466554893, 1.548925085471535512, 1.542128153226347553,
1.535342571438843118, 1.528567729435024614, 1.521803020758293101, 1.515047842773992404,
1.508301596278571965, 1.501563685112706548, 1.494833515777718391, 1.488110497054654369,
1.481394039625375747, 1.474683555695025516, 1.467978458615230908, 1.461278162507407830,
1.454582081885523293, 1.447889631277669675, 1.441200224845798017, 1.434513276002946425,
1.427828197027290358, 1.421144398672323117, 1.414461289772464658, 1.407778276843371534,
1.401094763676202559, 1.394410150925071257, 1.387723835686884621, 1.381035211072741964,
1.374343665770030531, 1.367648583594317957, 1.360949343030101844, 1.354245316759430606,
1.347535871177359290, 1.340820365893152122, 1.334098153216083604, 1.327368577624624679,
1.320630975217730096, 1.313884673146868964, 1.307128989027353860, 1.300363230327433728,
1.293586693733517645, 1.286798664489786415, 1.279998415710333237, 1.273185207661843732,
1.266358287014688333, 1.259516886060144225, 1.252660221891297887, 1.245787495544997903,
1.238897891102027415, 1.231990574742445110, 1.225064693752808020, 1.218119375481726552,
1.211153726239911244, 1.204166830140560140, 1.197157747875585931, 1.190125515422801650,
1.183069142678760732, 1.175987612011489825, 1.168879876726833800, 1.161744859441574240,
1.154581450355851802, 1.147388505416733873, 1.140164844363995789, 1.132909248648336975,
1.125620459211294389, 1.118297174115062909, 1.110938046009249502, 1.103541679420268151,
1.096106627847603487, 1.088631390649514197, 1.081114409698889389, 1.073554065787871714,
1.065948674757506653, 1.058296483326006454, 1.050595664586207123, 1.042844313139370538,
1.035040439828605274, 1.027181966030751292, 1.019266717460529215, 1.011292417434978441,
1.003256679539591412, 0.995156999629943084, 0.986990747093846266, 0.978755155288937750,
0.970447311058864615, 0.962064143217605250, 0.953602409875572654, 0.945058684462571130,
0.936429340280896860, 0.927710533396234771, 0.918898183643734989, 0.909987953490768997,
0.900975224455174528, 0.891855070726792376, 0.882622229578910122, 0.873271068082494550,
0.863795545546826915, 0.854189171001560554, 0.844444954902423661, 0.834555354079518752,
0.824512208745288633, 0.814306670128064347, 0.803929116982664893, 0.793369058833152785,
0.782615023299588763, 0.771654424216739354, 0.760473406422083165, 0.749056662009581653,
0.737387211425838629, 0.725446140901303549, 0.713212285182022732, 0.700661841097584448,
0.687767892786257717, 0.674499822827436479, 0.660822574234205984, 0.646695714884388928,
0.632072236375024632, 0.616896989996235545, 0.601104617743940417, 0.584616766093722262,
0.567338257040473026, 0.549151702313026790, 0.529909720646495108, 0.509423329585933393,
0.487443966121754335, 0.463634336771763245, 0.437518402186662658, 0.408389134588000746,
0.375121332850465727, 0.335737519180459465, 0.286174591747260509, 0.215241895913273806,
0.000000000000000000};
static constexpr float ZIG_NORM_F[257] =
{0.000477467764586655, 0.001260285930498598, 0.002609072746106363, 0.004037972593371872,
0.005522403299264754, 0.007050875471392110, 0.008616582769422917, 0.010214971439731100,
0.011842757857943104, 0.013497450601780807, 0.015177088307982072, 0.016880083152595839,
0.018605121275783350, 0.020351096230109354, 0.022117062707379922, 0.023902203305873237,
0.025705804008632656, 0.027527235669693315, 0.029365939758230111, 0.031221417192023690,
0.033093219458688698, 0.034980941461833073, 0.036884215688691151, 0.038802707404656918,
0.040736110656078753, 0.042684144916619378, 0.044646552251446536, 0.046623094902089664,
0.048613553216035145, 0.050617723861121788, 0.052635418276973649, 0.054666461325077916,
0.056710690106399467, 0.058767952921137984, 0.060838108349751806, 0.062921024437977854,
0.065016577971470438, 0.067124653828023989, 0.069245144397250269, 0.071377949059141965,
0.073522973714240991, 0.075680130359194964, 0.077849336702372207, 0.080030515814947509,
0.082223595813495684, 0.084428509570654661, 0.086645194450867782, 0.088873592068594229,
0.091113648066700734, 0.093365311913026619, 0.095628536713353335, 0.097903279039215627,
0.100189498769172020, 0.102487158942306270, 0.104796225622867056, 0.107116667775072880,
0.109448457147210021, 0.111791568164245583, 0.114145977828255210, 0.116511665626037014,
0.118888613443345698, 0.121276805485235437, 0.123676228202051403, 0.126086870220650349,
0.128508722280473636, 0.130941777174128166, 0.133386029692162844, 0.135841476571757352,
0.138308116449064322, 0.140785949814968309, 0.143274978974047118, 0.145775208006537926,
0.148286642733128721, 0.150809290682410169, 0.153343161060837674, 0.155888264725064563,
0.158444614156520225, 0.161012223438117663, 0.163591108232982951, 0.166181285765110071,
0.168782774801850333, 0.171395595638155623, 0.174019770082499359, 0.176655321444406654,
0.179302274523530397, 0.181960655600216487, 0.184630492427504539, 0.187311814224516926,
0.190004651671193070, 0.192709036904328807, 0.195425003514885592, 0.198152586546538112,
0.200891822495431333, 0.203642749311121501, 0.206405406398679298, 0.209179834621935651,
0.211966076307852941, 0.214764175252008499, 0.217574176725178370, 0.220396127481011589,
0.223230075764789593, 0.226076071323264877, 0.228934165415577484, 0.231804410825248525,
0.234686861873252689, 0.237581574432173676, 0.240488605941449107, 0.243408015423711988,
0.246339863502238771, 0.249284212419516704, 0.252241126056943765, 0.255210669955677150,
0.258192911338648023, 0.261187919133763713, 0.264195763998317568, 0.267216518344631837,
0.270250256366959984, 0.273297054069675804, 0.276356989296781264, 0.279430141762765316,
0.282516593084849388, 0.285616426816658109, 0.288729728483353931, 0.291856585618280984,
0.294997087801162572, 0.298151326697901342, 0.301319396102034120, 0.304501391977896274,
0.307697412505553769, 0.310907558127563710, 0.314131931597630143, 0.317370638031222396,
0.320623784958230129, 0.323891482377732021, 0.327173842814958593, 0.330470981380537099,
0.333783015832108509, 0.337110066638412809, 0.340452257045945450, 0.343809713148291340,
0.347182563958251478, 0.350570941482881204, 0.353974980801569250, 0.357394820147290515,
0.360830600991175754, 0.364282468130549597, 0.367750569780596226, 0.371235057669821344,
0.374736087139491414, 0.378253817247238111, 0.381788410875031348, 0.385340034841733958,
0.388908860020464597, 0.392495061461010764, 0.396098818517547080, 0.399720314981931668,
0.403359739222868885, 0.407017284331247953, 0.410693148271983222, 0.414387534042706784,
0.418100649839684591, 0.421832709231353298, 0.425583931339900579, 0.429354541031341519,
0.433144769114574058, 0.436954852549929273, 0.440785034667769915, 0.444635565397727750,
0.448506701509214067, 0.452398706863882505, 0.456311852680773566, 0.460246417814923481,
0.464202689050278838, 0.468180961407822172, 0.472181538469883255, 0.476204732721683788,
0.480250865911249714, 0.484320269428911598, 0.488413284707712059, 0.492530263646148658,
0.496671569054796314, 0.500837575128482149, 0.505028667945828791, 0.509245245998136142,
0.513487720749743026, 0.517756517232200619, 0.522052074674794864, 0.526374847174186700,
0.530725304406193921, 0.535103932383019565, 0.539511234259544614, 0.543947731192649941,
0.548413963257921133, 0.552910490428519918, 0.557437893621486324, 0.561996775817277916,
0.566587763258951771, 0.571211506738074970, 0.575868682975210544, 0.580559996103683473,
0.585286179266300333, 0.590047996335791969, 0.594846243770991268, 0.599681752622167719,
0.604555390700549533, 0.609468064928895381, 0.614420723892076803, 0.619414360609039205,
0.624450015550274240, 0.629528779928128279, 0.634651799290960050, 0.639820277456438991,
0.645035480824251883, 0.650298743114294586, 0.655611470583224665, 0.660975147780241357,
0.666391343912380640, 0.671861719900766374, 0.677388036222513090, 0.682972161648791376,
0.688616083008527058, 0.694321916130032579, 0.700091918140490099, 0.705928501336797409,
0.711834248882358467, 0.717811932634901395, 0.723864533472881599, 0.729995264565802437,
0.736207598131266683, 0.742505296344636245, 0.748892447223726720, 0.755373506511754500,
0.761953346841546475, 0.768637315803334831, 0.775431304986138326, 0.782341832659861902,
0.789376143571198563, 0.796542330428254619, 0.803849483176389490, 0.811307874318219935,
0.818929191609414797, 0.826726833952094231, 0.834716292992930375, 0.842915653118441077,
0.851346258465123684, 0.860033621203008636, 0.869008688043793165, 0.878309655816146839,
0.887984660763399880, 0.898095921906304051, 0.908726440060562912, 0.919991505048360247,
0.932060075968990209, 0.945198953453078028, 0.959879091812415930, 0.977101701282731328,
1.000000000000000000};
};
constexpr float RandomEngine::ZIG_NORM_X[];
constexpr float RandomEngine::ZIG_NORM_F[];
} // namespace contrib
} // namespace tvm
| 55.762887 | 92 | 0.762125 | mengkai94 |
4b425e1bcfaab4ff82c705397313c550c4eecbdd | 4,120 | cxx | C++ | Modules/Filtering/ImageGradient/test/itkGradientImageFilterTest2.cxx | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2021-11-29T14:41:43.000Z | 2021-11-29T14:41:43.000Z | Modules/Filtering/ImageGradient/test/itkGradientImageFilterTest2.cxx | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2017-08-18T19:28:52.000Z | 2017-08-18T19:28:52.000Z | Modules/Filtering/ImageGradient/test/itkGradientImageFilterTest2.cxx | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2017-08-18T19:07:39.000Z | 2017-08-18T19:07:39.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 <iostream>
#include "itkVectorImage.h"
#include "itkGradientImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
namespace
{
template <typename TInputImage>
int DoIt( const std::string &infname,
const std::string &outfname )
{
using InputImageType = TInputImage;
const unsigned int ImageDimension = InputImageType::ImageDimension;
using InputPixelType = typename InputImageType::PixelType;
using ReaderType = itk::ImageFileReader<InputImageType>;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( infname );
using FilterType = itk::GradientImageFilter<InputImageType >;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
using OutputImageType = typename FilterType::OutputImageType;
using WriterType = itk::ImageFileWriter<OutputImageType>;
typename WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( outfname );
writer->SetNumberOfStreamDivisions( 5 );
writer->Update();
std::cout << filter;
using VectorImageType = itk::VectorImage<InputPixelType, ImageDimension>;
using VectorFilterType = itk::GradientImageFilter<InputImageType, float, float, VectorImageType>;
typename VectorFilterType::Pointer vectorFilter = VectorFilterType::New();
vectorFilter->SetInput( reader->GetOutput() );
vectorFilter->Update();
filter->UpdateLargestPossibleRegion();
itk::ImageRegionConstIterator<OutputImageType> iter( filter->GetOutput(),
filter->GetOutput()->GetBufferedRegion() );
itk::ImageRegionConstIterator<VectorImageType> viter( vectorFilter->GetOutput(),
vectorFilter->GetOutput()->GetBufferedRegion() );
// Check the filter output
bool diff = false;
while( !iter.IsAtEnd() )
{
for( unsigned int i = 0; i < ImageDimension; ++i )
{
if ( ! itk::Math::FloatAlmostEqual( iter.Get()[i], viter.Get()[i] ) )
{
diff = true;
}
}
++viter;
++iter;
}
if ( diff )
{
std::cerr << "VectorImage output does not match covariant!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
}
int itkGradientImageFilterTest2(int argc, char * argv[] )
{
if ( argc < 3 )
{
std::cerr << "Missing arguments" << std::endl;
std::cerr << "Usage: " << argv[0] << " Inputimage OutputImage" << std::endl;
return EXIT_FAILURE;
}
const std::string infname = argv[1];
const std::string outfname = argv[2];
itk::ImageIOBase::Pointer iobase =
itk::ImageIOFactory::CreateImageIO( infname.c_str(), itk::ImageIOFactory::ReadMode);
if ( iobase.IsNull() )
{
itkGenericExceptionMacro( "Unable to determine ImageIO reader for \"" << infname << "\"" );
}
using TestImageType = itk::Image<short,3>;
using FilterType = itk::GradientImageFilter<TestImageType >;
FilterType::Pointer filter = FilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( filter, GradientImageFilter, ImageToImageFilter );
const unsigned int dimension = iobase->GetNumberOfDimensions();
if ( dimension == 2 )
return DoIt< itk::Image<float, 2> >( infname, outfname );
else if ( dimension == 3 )
return DoIt< itk::Image<float, 3> >( infname, outfname );
return EXIT_FAILURE;
}
| 30.518519 | 99 | 0.674029 | floryst |
4b42a06a27f4d72f91b1a18e9c18eb11801c3a31 | 24,236 | cpp | C++ | tests/args-test.cpp | mbits-libs/libargs | 72f5f2b87ae39f26638a585fa4ad0b96b4152ae6 | [
"MIT"
] | null | null | null | tests/args-test.cpp | mbits-libs/libargs | 72f5f2b87ae39f26638a585fa4ad0b96b4152ae6 | [
"MIT"
] | 2 | 2020-09-25T10:07:38.000Z | 2020-10-11T16:01:17.000Z | tests/args-test.cpp | mbits-libs/libargs | 72f5f2b87ae39f26638a585fa4ad0b96b4152ae6 | [
"MIT"
] | null | null | null | #include <args/parser.hpp>
#include <iostream>
#include <string_view>
using namespace std::literals;
struct test {
const char* title;
int (*callback)();
int expected{0};
std::string_view output{};
};
std::vector<test> g_tests;
template <typename Test>
struct registrar {
registrar() {
::g_tests.push_back(
{Test::get_name(), Test::run, Test::expected(), Test::output()});
}
};
#define TEST_BASE(name, EXPECTED, OUTPUT) \
struct test_##name { \
static const char* get_name() noexcept { return #name; } \
static int run(); \
static int expected() noexcept { return (EXPECTED); } \
static std::string_view output() noexcept { return OUTPUT; } \
}; \
registrar<test_##name> reg_##name; \
int test_##name ::run()
#define TEST(name) TEST_BASE(name, 0, {})
#define TEST_FAIL(name) TEST_BASE(name, 1, {})
#define TEST_OUT(name, OUTPUT) TEST_BASE(name, 0, OUTPUT)
#define TEST_FAIL_OUT(name, OUTPUT) TEST_BASE(name, 1, OUTPUT)
int main(int argc, char* argv[]) {
if (argc == 1) {
for (auto const& test : g_tests) {
printf("%d:%s:", test.expected, test.title);
if (!test.output.empty())
printf("%.*s", static_cast<int>(test.output.size()),
test.output.data());
putc('\n', stdout);
}
return 0;
}
auto const int_test = atoi(argv[1]);
if (int_test < 0) return 100;
auto const test = static_cast<size_t>(int_test);
return g_tests[test].callback();
}
template <typename... CString, typename Mod>
int every_test_ever(Mod mod, CString... args) {
std::string arg_opt;
std::string arg_req;
bool starts_as_false{false};
bool starts_as_true{true};
std::vector<std::string> multi_opt;
std::vector<std::string> multi_req;
std::string positional;
char arg0[] = "args-help-test";
char* __args[] = {arg0, (const_cast<char*>(args))..., nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(arg_opt, "o", "opt").meta("VAR").help("a help for arg_opt").opt();
p.arg(arg_req, "r", "req").help("a help for arg_req");
p.set<std::true_type>(starts_as_false, "on", "1")
.help("a help for on")
.opt();
p.set<std::false_type>(starts_as_true, "off", "0")
.help("a help for off")
.opt();
p.arg(multi_opt, "first").help("zero or more").opt();
p.arg(multi_req, "second").meta("VAL").help("one or more");
p.arg(positional).meta("INPUT").help("a help for positional").opt();
mod(p);
p.parse();
return 0;
}
void noop(const args::parser&) {}
void modify(args::parser& parser) {
parser.program("another");
if (parser.program() != "another") {
fprintf(stderr, "Program not changed: %s\n", parser.program().c_str());
std::exit(1);
}
parser.usage("[OPTIONS]");
if (parser.usage() != "[OPTIONS]") {
fprintf(stderr, "Usage not changed: %s\n", parser.usage().c_str());
std::exit(1);
}
}
void enable_answers(args::parser& parser) {
parser.use_answer_file();
}
void enable_answers_dollar(args::parser& parser) {
parser.use_answer_file('$');
}
template <typename T, typename U>
void EQ_impl(T&& lhs, U&& rhs, const char* lhs_name, const char* rhs_name) {
if (lhs == rhs) return;
std::cerr << "Expected equality of these values:\n " << std::boolalpha
<< lhs_name << "\n Which is: " << lhs << "\n " << rhs_name
<< "\n Which is: " << rhs << "\n";
std::exit(1);
}
#define EQ(lhs, rhs) EQ_impl(lhs, rhs, #lhs, #rhs)
TEST(gen_usage) {
return every_test_ever(
[](args::parser& parser) {
std::string shrt;
const std::string_view expected_help =
"args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first "
"ARG "
"...] --second VAL [--second VAL ...] [INPUT]";
parser.printer_append_usage(shrt);
EQ(expected_help, shrt);
},
"-r", "x", "--second", "somsink");
}
TEST(gen_usage_no_help) {
return every_test_ever(
[](args::parser& parser) {
std::string shrt;
const std::string_view expected_no_help =
"args-help-test [-o VAR] -r ARG [--on] [--off] [--first ARG "
"...] "
"--second VAL [--second VAL ...] [INPUT]";
parser.provide_help(false);
parser.printer_append_usage(shrt);
EQ(expected_no_help, shrt);
},
"-r", "x", "--second", "somsink");
}
TEST_OUT(
short_help_argument,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\n\nprogram description\n\npositional arguments:\n INPUT a help for positional\n\noptional arguments:\n -h, --help show this help message and exit\n -o, --opt VAR a help for arg_opt\n -r, --req ARG a help for arg_req\n --on, -1 a help for on\n --off, -0 a help for off\n --first ARG zero or more\n --second VAL one or more\n)"sv) {
return every_test_ever(noop, "-h");
}
TEST_OUT(
long_help_argument,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\n\nprogram description\n\npositional arguments:\n INPUT a help for positional\n\noptional arguments:\n -h, --help show this help message and exit\n -o, --opt VAR a help for arg_opt\n -r, --req ARG a help for arg_req\n --on, -1 a help for on\n --off, -0 a help for off\n --first ARG zero or more\n --second VAL one or more\n)"sv) {
return every_test_ever(noop, "--help");
}
TEST(help_mod) {
return every_test_ever(modify, "-h");
}
TEST_FAIL_OUT(
no_req,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument -r is required\n)"sv) {
return every_test_ever(noop);
}
TEST_FAIL(no_req_mod) {
return every_test_ever(modify);
}
// TODO: used to be test_fail; regeresion or code behind fixed?
TEST(full) {
return every_test_ever(noop, "-oVALUE", "-r", "SEPARATE", "--req",
"ANOTHER ONE", "--on", "-10", "--off", "--second",
"somsink", "POSITIONAL");
}
TEST_FAIL_OUT(
missing_arg_short,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument -r: expected one argument\n)"sv) {
return every_test_ever(noop, "-r");
}
TEST_FAIL_OUT(
missing_arg,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument --req: expected one argument\n)"sv) {
return every_test_ever(noop, "--req");
}
TEST_FAIL_OUT(
missing_positional,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT] POSITIONAL [POSITIONAL ...]\nargs-help-test: error: argument POSITIONAL is required\n)"sv) {
std::vector<std::string> one_plus;
return every_test_ever(
[&](args::parser& p) {
p.arg(one_plus)
.meta("POSITIONAL")
.help("this parameter must be given at least once");
},
"-r", "x", "--second", "somsink");
}
TEST_FAIL_OUT(
unknown,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: unrecognized argument: --flag\n)"sv) {
return every_test_ever(noop, "--flag");
}
TEST_FAIL_OUT(
unknown_short,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: unrecognized argument: -f\n)"sv) {
return every_test_ever(noop, "-f");
}
TEST_FAIL_OUT(
unknown_positional,
R"(usage: args-help-test [-h]\nargs-help-test: error: unrecognized argument: POSITIONAL\n)"sv) {
#ifdef _WIN32
char arg0[] = R"(C:\Program Files\Program Name\args-help-test.exe)";
#else
char arg0[] = "/usr/bin/args-help-test";
#endif
char arg1[] = "POSITIONAL";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse();
return 0;
}
TEST(console_width) {
const auto isatty = args::detail::is_terminal(stdout);
const auto width = args::detail::terminal_width(stdout);
return isatty ? (width ? 0 : 1) : (width ? 1 : 0);
}
TEST_OUT(
width_forced,
R"(usage: args-help-test [-h] [INPUT]\n\nThis is a very long description of the\nprogram, which should span multiple\nlines in narrow consoles. This will be\ntested with forcing a console width in\nthe parse() method.\n\npositional arguments:\n INPUT This is a very long\n description of the INPUT\n param, which should span\n multiple lines in narrow\n consoles. This will be\n tested with forcing a\n console width in the\n parse() method. Also,\n here's a long word:\n supercalifragilisticexpiali\n docious\n\noptional arguments:\n -h, --help show this help message and\n exit\n)"sv) {
std::string positional;
char arg0[] = "args-help-test";
char arg1[] = "-h";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
auto prog_descr =
"This is a very long description of the program, "
"which should span multiple lines in narrow consoles. "
"This will be tested with forcing a console width in "
"the parse() method."s;
auto long_descr =
"This is a very long description of the INPUT param, "
"which should span multiple lines in narrow consoles. "
"This will be tested with forcing a console width in "
"the parse() method. Also, here's a long word: "
"supercalifragilisticexpialidocious"s;
::args::null_translator tr;
::args::parser p{std::move(prog_descr), ::args::from_main(argc, __args),
&tr};
p.arg(positional).meta("INPUT").help(std::move(long_descr)).opt();
p.parse(::args::parser::exclusive_parser, 40);
return 0;
}
TEST_FAIL(not_an_int) {
int value;
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER").opt();
p.parse();
return 0;
}
TEST_FAIL(out_of_range) {
int value;
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] =
"123456789012345678901234567890123456789012345678901234567890";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER").opt();
p.parse();
return 0;
}
TEST(optional_int_1) {
std::optional<int> value;
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER");
p.parse();
constexpr auto has_value = true;
constexpr auto the_value = 12345;
EQ(has_value, !!value);
EQ(the_value, *value);
return 0;
}
TEST(optional_int_2) {
std::optional<int> value;
char arg0[] = "args-help-test";
char* __args[] = {arg0, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(value, "num").meta("NUMBER");
p.parse();
constexpr auto no_value = false;
EQ(no_value, !!value);
return 0;
}
TEST(subcmd_long) {
char arg0[] = "args-help-test";
char arg1[] = "--num";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse(::args::parser::allow_subcommands);
return 0;
}
TEST(subcmd_short) {
char arg0[] = "args-help-test";
char arg1[] = "-n";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse(::args::parser::allow_subcommands);
return 0;
}
TEST(subcmd_positional) {
char arg0[] = "args-help-test";
char arg1[] = "a_path";
char arg2[] = "12345";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.parse(::args::parser::allow_subcommands);
return 0;
}
TEST(custom_simple_1) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([] {}, "path");
p.parse();
return 0;
}
TEST(custom_simple_1_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([] { std::exit(0); }, "path");
p.parse();
return 1;
}
TEST(custom_simple_2) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](::args::parser&) {}, "path");
p.parse();
return 0;
}
TEST(custom_simple_2_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](::args::parser&) { std::exit(0); }, "path");
p.parse();
return 1;
}
TEST(custom_string_1) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](std::string const&) {}, "path");
p.parse();
return 0;
}
TEST(custom_string_1_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([=](std::string const& arg) { std::exit(arg != arg2); }, "path");
p.parse();
return 1;
}
TEST(custom_string_2) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([](::args::parser&, std::string const&) {}, "path");
p.parse();
return 0;
}
TEST(custom_string_2_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([=](::args::parser&,
std::string const& arg) { std::exit(arg != arg2); },
"path");
p.parse();
return 1;
}
TEST(custom_string_view_1_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom([=](std::string_view arg) { std::exit(arg != arg2); }, "path");
p.parse();
return 1;
}
TEST(custom_string_view_2_exit) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.custom(
[=](::args::parser&, std::string_view arg) { std::exit(arg != arg2); },
"path");
p.parse();
return 1;
}
TEST(empty_args) {
char* __args[] = {nullptr};
auto const args = ::args::from_main(0, __args);
constexpr auto expected_prog_name = ""sv;
constexpr auto expected_args = 0u;
EQ(expected_prog_name, args.progname);
EQ(expected_args, args.args.size());
return 0;
}
TEST(additional_ctors) {
char arg0[] = "args-help-test";
char arg1[] = "--path";
char arg2[] = "value";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
args::null_translator tr;
args::parser p1{""s, arg0, {argc - 1, __args + 1}, &tr};
args::parser p2{""s, args::arglist{argc, __args}, &tr};
return 0;
}
enum class thing { none, one, two };
ENUM_TRAITS_BEGIN(thing)
ENUM_TRAITS_NAME(one)
ENUM_TRAITS_NAME(two)
ENUM_TRAITS_END(thing)
TEST(enum_arg_one) {
char arg0[] = "args-help-test";
char arg1[] = "--thing";
char arg2[] = "one";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
thing which{thing::none};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(which, "thing");
p.parse();
return !(which == thing::one);
}
TEST(enum_arg_two) {
char arg0[] = "args-help-test";
char arg1[] = "--thing";
char arg2[] = "two";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
thing which{thing::none};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(which, "thing");
p.parse();
return !(which == thing::two);
}
TEST_FAIL_OUT(
enum_arg_three,
R"(usage: args-help-test [-h] --thing ARG\nargs-help-test: error: argument --thing: value three is not recognized\nknown values for --thing: one, two\n)"sv) {
char arg0[] = "args-help-test";
char arg1[] = "--thing";
char arg2[] = "three";
char* __args[] = {arg0, arg1, arg2, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
thing which{thing::none};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(which, "thing");
p.parse();
return !(which == thing::none);
}
TEST(long_param_eq) {
return every_test_ever(noop, "-r", "x", "--second=somsink");
}
TEST_FAIL_OUT(
long_param_eq_error,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument --off: value was not expected\n)"sv) {
return every_test_ever(noop, "-r", "x", "--second", "somsink", "--off=on");
}
TEST_OUT(utf_8,
"usage: args-help-test [-h] --\xC3\xA7-arg \xC3\xB1 --c-arg n\\n"
"\\n"
"program description\\n"
"\\n"
"optional arguments:\\n"
" -h, --help show this help message and exit\\n"
" --\xC3\xA7-arg \xC3\xB1 |<----\\n"
" --c-arg n |<----\\n"sv) {
char arg0[] = "args-help-test";
char arg1[] = "--help";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
std::string argument{};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(argument, "\xC3\xA7-arg").meta("\xC3\xB1").help("|<----");
p.arg(argument, "c-arg").meta("n").help("|<----");
p.parse();
return 1;
}
TEST_FAIL_OUT(
no_answer_file_support,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...]\nargs-help-test: error: unrecognized argument: @minimal-args\n)"sv) {
std::string arg_opt;
std::string arg_req;
bool starts_as_false{false};
bool starts_as_true{true};
std::vector<std::string> multi_opt;
std::vector<std::string> multi_req;
char arg0[] = "args-help-test";
char arg1[] = "@minimal-args";
char* __args[] = {arg0, arg1, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.arg(arg_opt, "o", "opt").meta("VAR").help("a help for arg_opt").opt();
p.arg(arg_req, "r", "req").help("a help for arg_req");
p.set<std::true_type>(starts_as_false, "on", "1")
.help("a help for on")
.opt();
p.set<std::false_type>(starts_as_true, "off", "0")
.help("a help for off")
.opt();
p.arg(multi_opt, "first").help("zero or more").opt();
p.arg(multi_req, "second").meta("VAL").help("one or more");
p.parse();
return 0;
}
TEST(answer_file) {
return every_test_ever(enable_answers, "@minimal-args");
}
TEST_FAIL_OUT(
answer_file_not_found,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: cannot open no-such-file\n)"sv) {
return every_test_ever(enable_answers, "@no-such-file");
}
TEST(answer_file_before) {
char arg0[] = "args-help-test";
char arg1[] = "@minimal-args";
char arg2[] = "-r";
char arg3[] = "y";
char* __args[] = {arg0, arg1, arg2, arg3, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
std::string r{}, s{};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.use_answer_file();
p.arg(r, "r", "req").help("a help for arg_req");
p.arg(s, "second").meta("VAL").help("one or more");
p.parse();
return !(r == "y");
}
TEST(answer_file_after) {
char arg0[] = "args-help-test";
char arg1[] = "-r";
char arg2[] = "y";
char arg3[] = "@minimal-args";
char* __args[] = {arg0, arg1, arg2, arg3, nullptr};
int argc = static_cast<int>(std::size(__args)) - 1;
std::string r{}, s{};
::args::null_translator tr;
::args::parser p{"program description", ::args::from_main(argc, __args),
&tr};
p.use_answer_file();
p.arg(r, "r", "req").help("a help for arg_req");
p.arg(s, "second").meta("VAL").help("one or more");
p.parse();
return !(r == "x");
}
TEST(answer_file_alt) {
return every_test_ever(enable_answers_dollar, "$minimal-args");
}
TEST_FAIL_OUT(
answer_file_unexpected,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: argument --off: value was not expected\n)"sv) {
return every_test_ever(enable_answers, "@unexpected-arg-value");
}
TEST_FAIL_OUT(
answer_file_unknown,
R"(usage: args-help-test [-h] [-o VAR] -r ARG [--on] [--off] [--first ARG ...] --second VAL [--second VAL ...] [INPUT]\nargs-help-test: error: unrecognized argument: --unexpected\n)"sv) {
return every_test_ever(enable_answers, "@unknown-arg");
}
| 31.151671 | 718 | 0.609589 | mbits-libs |
4b42cf206f3e1c9b44048a47981ebfdd2d78de10 | 6,505 | cpp | C++ | C++CodeSnippets/HLD [LOJ-1348].cpp | Maruf-Tuhin/Online_Judge | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | 1 | 2019-03-31T05:47:30.000Z | 2019-03-31T05:47:30.000Z | C++CodeSnippets/HLD [LOJ-1348].cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | C++CodeSnippets/HLD [LOJ-1348].cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | /**
* @author : Maruf Tuhin
* @College : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define mem(a, b) memset(a, b, sizeof(a))
#define inf 1e9
#define eps 1e-9
#define mod 1000000007
#define NN 50010
#define read(a) scanf("%lld", &a)
#define root 0
#define LN 16
vector<ll> adj[NN];
ll baseArray[NN], ptr, value[NN];
ll chainNo, chainInd[NN], chainHead[NN], posInBase[NN];
ll depth[NN], par[NN][LN], subsize[NN];
ll seg[NN * 4];
void make_tree(ll node, ll low, ll high) {
if (low == high) {
seg[node] = baseArray[low];
return;
}
ll left = node << 1;
ll right = left | 1;
ll mid = (low + high) >> 1;
make_tree(left, low, mid);
make_tree(right, mid + 1, high);
seg[node] = seg[left] + seg[right];
return;
}
void update_tree(ll node, ll low, ll high, ll ind, ll val) {
if (low == ind && low == high) {
seg[node] = val;
return;
}
ll left = node << 1;
ll right = left | 1;
ll mid = (low + high) >> 1;
if (ind <= mid)
update_tree(left, low, mid, ind, val);
else
update_tree(right, mid + 1, high, ind, val);
seg[node] = seg[left] + seg[right];
return;
}
ll query_tree(ll node, ll low, ll high, ll rlow, ll rhigh) {
if (low >= rlow && high <= rhigh) {
return seg[node];
}
ll left = node << 1;
ll right = left | 1;
ll mid = (low + high) >> 1;
if (rhigh <= mid)
return query_tree(left, low, mid, rlow, rhigh);
else if (rlow > mid)
return query_tree(right, mid + 1, high, rlow, rhigh);
else {
ll L = query_tree(left, low, mid, rlow, mid);
ll R = query_tree(right, mid + 1, high, mid + 1, rhigh);
return L + R;
}
}
ll query_up(ll u, ll v) { // v is an ancestor of u
ll uchain, vchain = chainInd[v], ans = 0;
// uchain and vchain are chain numbers of u and v
while (1) {
uchain = chainInd[u];
if (uchain == vchain) {
ans += query_tree(1, 1, ptr - 1, posInBase[v], posInBase[u]);
break;
}
ans += query_tree(1, 1, ptr - 1, posInBase[chainHead[uchain]],
posInBase[u]);
u = chainHead[uchain]; // move u to u's chainHead
u = par[u][0]; // Then move to its parent, that means we changed
// chains
}
return ans;
}
ll LCA(ll u, ll v) {
if (depth[u] < depth[v])
swap(u, v);
ll diff = depth[u] - depth[v];
for (ll i = 0; i < LN; i++)
if ((diff >> i) & 1)
u = par[u][i];
if (u == v)
return u;
for (ll i = LN - 1; i >= 0; i--)
if (par[u][i] != par[v][i]) {
u = par[u][i];
v = par[v][i];
}
return par[u][0];
}
ll query(ll u, ll v) {
ll lca = LCA(u, v);
ll ans = query_up(u, lca); // One part of path
ll ans2 = query_up(v, lca); // another part of path
return ans + ans2 - query_up(lca, lca); // take the maximum of both paths
}
void change(ll u, ll val) {
update_tree(1, 1, ptr - 1, posInBase[u], val);
}
void HLD(ll curNode, ll prev) {
if (chainHead[chainNo] == -1) {
chainHead[chainNo] = curNode; // Assign chain head
}
chainInd[curNode] = chainNo;
posInBase[curNode] = ptr; // Position of this node in baseArray which we
// will use in Segtree
baseArray[ptr++] = value[curNode];
ll sc = -1, ncost;
// Loop to find special child
for (ll i = 0; i < adj[curNode].size(); i++)
if (adj[curNode][i] != prev) {
if (sc == -1 || subsize[sc] < subsize[adj[curNode][i]]) {
sc = adj[curNode][i];
}
}
if (sc != -1) {
// Expand the chain
HLD(sc, curNode);
}
for (ll i = 0; i < adj[curNode].size(); i++)
if (adj[curNode][i] != prev) {
if (sc != adj[curNode][i]) {
// New chains at each normal node
chainNo++;
HLD(adj[curNode][i], curNode);
}
}
}
void dfs(ll cur, ll prev, ll _depth = 0) {
par[cur][0] = prev;
depth[cur] = _depth;
subsize[cur] = 1;
for (ll i = 0; i < adj[cur].size(); i++)
if (adj[cur][i] != prev) {
dfs(adj[cur][i], cur, _depth + 1);
subsize[cur] += subsize[adj[cur][i]];
}
}
int main() {
#ifdef redback
freopen("C:\\Users\\Maruf\\Desktop\\in.txt", "r", stdin);
#endif
ll tc, t = 1;
scanf("%lld ", &tc);
while (tc--) {
ptr = 1;
ll n;
scanf("%lld", &n);
// Cleaning step, new test case
for (ll i = 0; i <= n; i++) {
adj[i].clear();
chainHead[i] = -1;
for (ll j = 0; j < LN; j++) par[i][j] = -1;
}
for (ll i = 0; i < n; i++) {
read(value[i]);
}
for (ll i = 1; i < n; i++) {
ll u, v, c;
scanf("%lld %lld", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
chainNo = 0;
dfs(root, -1); // We set up subsize, depth and parent for each node
HLD(root, -1); // We decomposed the tree and created baseArray
make_tree(
1, 1,
ptr -
1); // We use baseArray and construct the needed segment tree
// Below Dynamic programming code is for LCA.
for (ll lev = 1; lev <= LN - 1; lev++) {
for (ll i = 0; i < n; i++) {
if (par[i][lev - 1] != -1)
par[i][lev] = par[par[i][lev - 1]][lev - 1];
}
}
ll q;
scanf("%lld", &q);
printf("Case %lld:\n", t++);
while (q--) {
ll tp;
scanf("%lld", &tp);
ll a, b;
scanf("%lld %lld", &a, &b);
if (tp == 0) {
ll ans = query(a, b);
printf("%lld\n", ans);
} else {
change(a, b);
}
}
}
return 0;
}
| 26.443089 | 79 | 0.465796 | Maruf-Tuhin |
4b43788c40830200684afa37f82a146623c14339 | 5,748 | cpp | C++ | lib/analyzer/expressions/typeclass.cpp | reaver-project/vapor | 17ddb5c60b483bd17a288319bfd3e8a43656859e | [
"Zlib"
] | 4 | 2017-07-22T23:12:36.000Z | 2022-01-13T23:57:06.000Z | lib/analyzer/expressions/typeclass.cpp | reaver-project/vapor | 17ddb5c60b483bd17a288319bfd3e8a43656859e | [
"Zlib"
] | 36 | 2016-11-26T17:46:16.000Z | 2019-05-21T16:27:13.000Z | lib/analyzer/expressions/typeclass.cpp | reaver-project/vapor | 17ddb5c60b483bd17a288319bfd3e8a43656859e | [
"Zlib"
] | 3 | 2016-10-01T21:04:32.000Z | 2021-03-20T06:57:53.000Z | /**
* Vapor Compiler Licence
*
* Copyright © 2017-2019 Michał "Griwes" Dominiak
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation is required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
**/
#include "vapor/analyzer/expressions/typeclass.h"
#include "vapor/analyzer/expressions/overload_set.h"
#include "vapor/analyzer/semantic/symbol.h"
#include "vapor/analyzer/semantic/typeclass.h"
#include "vapor/analyzer/statements/function.h"
#include "vapor/parser/expr.h"
#include "vapor/parser/typeclass.h"
#include "expressions/typeclass.pb.h"
namespace reaver::vapor::analyzer
{
inline namespace _v1
{
std::unique_ptr<typeclass_expression> preanalyze_typeclass_literal(precontext & ctx,
const parser::typeclass_literal & parse,
scope * lex_scope)
{
return std::make_unique<typeclass_expression>(
make_node(parse), make_typeclass(ctx, parse, lex_scope));
}
typeclass_expression::typeclass_expression(ast_node parse, std::unique_ptr<typeclass> tc)
: _typeclass{ std::move(tc) }
{
_set_ast_info(parse);
}
typeclass_expression::~typeclass_expression() = default;
void typeclass_expression::print(std::ostream & os, print_context ctx) const
{
os << styles::def << ctx << styles::rule_name << "typeclass-literal";
print_address_range(os, this);
os << '\n';
auto tc_ctx = ctx.make_branch(false);
os << styles::def << tc_ctx << styles::subrule_name << "defined typeclass:\n";
_typeclass->print(os, tc_ctx.make_branch(true), true);
auto params_ctx = ctx.make_branch(_typeclass->get_member_function_decls().empty());
os << styles::def << params_ctx << styles::subrule_name << "parameters:\n";
std::size_t idx = 0;
for (auto && param : _typeclass->get_parameter_expressions())
{
param->print(os, params_ctx.make_branch(++idx == _typeclass->get_parameter_expressions().size()));
}
if (_typeclass->get_member_function_decls().size())
{
auto decl_ctx = ctx.make_branch(true);
os << styles::def << decl_ctx << styles::subrule_name << "member function declarations:\n";
std::size_t idx = 0;
for (auto && member : _typeclass->get_member_function_decls())
{
member->print(
os, decl_ctx.make_branch(++idx == _typeclass->get_member_function_decls().size()));
}
}
}
void typeclass_expression::_set_name(std::u32string name)
{
_typeclass->set_name(std::move(name));
}
future<> typeclass_expression::_analyze(analysis_context & ctx)
{
return when_all(
fmap(_typeclass->get_parameters(), [&](auto && param) { return param->analyze(ctx); }))
.then([&] {
auto param_types = fmap(_typeclass->get_parameters(), [](auto && param) {
auto ret = param->get_type();
assert(ret->is_meta());
return ret;
});
_set_type(ctx.get_typeclass_type(param_types));
})
.then([&] {
return when_all(fmap(_typeclass->get_member_function_decls(),
[&](auto && decl) { return decl->analyze(ctx); }));
})
.then([&] {
// analyze possible unresolved types in function signatures
return when_all(fmap(_typeclass->get_scope()->symbols_in_order(), [&](symbol * symb) {
auto && oset = symb->get_expression()->as<overload_set_expression>();
if (oset)
{
return when_all(fmap(oset->get_overloads(), [&](function * fn) {
return fn->return_type_expression()->analyze(ctx).then([fn, &ctx] {
return when_all(fmap(
fn->parameters(), [&](auto && param) { return param->analyze(ctx); }));
});
}));
}
return make_ready_future();
}));
});
}
std::unique_ptr<expression> typeclass_expression::_clone_expr(replacements & repl) const
{
assert(0);
}
future<expression *> typeclass_expression::_simplify_expr(recursive_context ctx)
{
return when_all(fmap(_typeclass->get_member_function_decls(), [&](auto && decl) {
return decl->simplify(ctx);
})).then([&](auto &&) -> expression * { return this; });
}
statement_ir typeclass_expression::_codegen_ir(ir_generation_context & ctx) const
{
assert(0);
}
constant_init_ir typeclass_expression::_constinit_ir(ir_generation_context &) const
{
assert(0);
}
std::unique_ptr<google::protobuf::Message> typeclass_expression::_generate_interface() const
{
return _typeclass->generate_interface();
}
}
}
| 37.324675 | 110 | 0.60421 | reaver-project |
4b438c9f87d7bc33cfe4d9a966bba4f1e2767a67 | 3,036 | cpp | C++ | sp/src/game/client/dbr/hud_hull.cpp | URAKOLOUY5/source-sdk-2013 | d6e2d4b6d3e93b1224e6b4aa378d05309eee20bc | [
"Unlicense"
] | 2 | 2022-02-18T18:16:37.000Z | 2022-02-23T21:21:37.000Z | sp/src/game/client/dbr/hud_hull.cpp | URAKOLOUY5/u5-maps | d6e2d4b6d3e93b1224e6b4aa378d05309eee20bc | [
"Unlicense"
] | null | null | null | sp/src/game/client/dbr/hud_hull.cpp | URAKOLOUY5/u5-maps | d6e2d4b6d3e93b1224e6b4aa378d05309eee20bc | [
"Unlicense"
] | null | null | null | #include "cbase.h"
#include "hud.h"
#include "hud_macros.h"
#include "c_baseplayer.h"
#include "hud_hull.h"
#include "iclientmode.h"
#include "vgui/ISurface.h"
using namespace vgui;
#include "tier0/memdbgon.h"
#ifndef DBR
DECLARE_HUDELEMENT (CHudHull);
#endif
# define HULL_INIT 80
//------------------------------------------------------------------------
// Purpose: Constructor
//------------------------------------------------------------------------
CHudHull:: CHudHull (const char * pElementName) :
CHudElement (pElementName), BaseClass (NULL, "HudHull")
{
vgui:: Panel * pParent = g_pClientMode-> GetViewport ();
SetParent (pParent);
SetHiddenBits (HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT);
}
//------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------
void CHudHull:: Init()
{
Reset();
}
//------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------
void CHudHull:: Reset (void)
{
m_flHull = HULL_INIT;
m_nHullLow = -1;
SetBgColor (Color (0,0,0,0));
}
//------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------
void CHudHull:: OnThink (void)
{
float newHull = 0;
C_BasePlayer * local = C_BasePlayer:: GetLocalPlayer ();
if (!local)
return;
// Never below zero
newHull = max(local->GetHealth(), 0);
// DevMsg("Sheild at is at: %f\n",newShield);
// Only update the fade if we've changed health
if (newHull == m_flHull)
return;
m_flHull = newHull;
}
//------------------------------------------------------------------------
// Purpose: draws the power bar
//------------------------------------------------------------------------
void CHudHull::Paint()
{
// Get bar chunks
int chunkCount = m_flBarWidth / (m_flBarChunkWidth + m_flBarChunkGap);
int enabledChunks = (int)((float)chunkCount * (m_flHull / 100.0f) + 0.5f );
// Draw the suit power bar
surface()->DrawSetColor (m_HullColor);
int xpos = m_flBarInsetX, ypos = m_flBarInsetY;
for (int i = 0; i < enabledChunks; i++)
{
surface()->DrawFilledRect(xpos, ypos, xpos + m_flBarChunkWidth, ypos + m_flBarHeight);
xpos += (m_flBarChunkWidth + m_flBarChunkGap);
}
// Draw the exhausted portion of the bar.
surface()->DrawSetColor(Color(m_HullColor [0], m_HullColor [1], m_HullColor [2], m_iHullDisabledAlpha));
for (int i = enabledChunks; i < chunkCount; i++)
{
surface()->DrawFilledRect(xpos, ypos, xpos + m_flBarChunkWidth, ypos + m_flBarHeight);
xpos += (m_flBarChunkWidth + m_flBarChunkGap);
}
// Draw our name
surface()->DrawSetTextFont(m_hTextFont);
surface()->DrawSetTextColor(m_HullColor);
surface()->DrawSetTextPos(text_xpos, text_ypos);
//wchar_t *tempString = vgui::localize()->Find("#Valve_Hud_AUX_POWER");
surface()->DrawPrintText(L"HULL", wcslen(L"HULL"));
} | 26.172414 | 105 | 0.525033 | URAKOLOUY5 |
4b45421dcb8c6a9168ef3b3b2d44ed2d2dbd917b | 19,308 | cxx | C++ | Rendering/VR/vtkVRRenderWindow.cxx | jpouderoux/VTK | 1af22bcce698e121b6c8064ea724636621d1bf7e | [
"BSD-3-Clause"
] | 1 | 2021-11-23T02:09:28.000Z | 2021-11-23T02:09:28.000Z | Rendering/VR/vtkVRRenderWindow.cxx | zist8888/VTK | 74ae7be4aa33c94b0535ebbdaf7d27573d7c7614 | [
"BSD-3-Clause"
] | null | null | null | Rendering/VR/vtkVRRenderWindow.cxx | zist8888/VTK | 74ae7be4aa33c94b0535ebbdaf7d27573d7c7614 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkVRRenderWindow.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 "vtkVRRenderWindow.h"
#include "vtkMatrix4x4.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLState.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkRendererCollection.h"
#include "vtkTransform.h"
#include "vtkVRCamera.h"
#include "vtkVRModel.h"
#include "vtkVRRenderer.h"
#include <cstring>
#include <memory>
// include what we need for the helper window
#ifdef WIN32
#include "vtkWin32OpenGLRenderWindow.h"
#endif
#ifdef VTK_USE_X
#include "vtkXOpenGLRenderWindow.h"
#endif
#ifdef VTK_USE_COCOA
#include "vtkCocoaRenderWindow.h"
#endif
#if !defined(_WIN32) || defined(__CYGWIN__)
#define stricmp strcasecmp
#endif
//------------------------------------------------------------------------------
vtkVRRenderWindow::vtkVRRenderWindow()
{
this->StereoCapableWindow = 1;
this->StereoRender = 1;
this->UseOffScreenBuffers = true;
this->Size[0] = 640;
this->Size[1] = 720;
this->Position[0] = 100;
this->Position[1] = 100;
this->HelperWindow = vtkOpenGLRenderWindow::SafeDownCast(vtkRenderWindow::New());
if (!this->HelperWindow)
{
vtkErrorMacro(<< "Failed to create render window");
}
}
//------------------------------------------------------------------------------
vtkVRRenderWindow::~vtkVRRenderWindow()
{
this->Finalize();
vtkRenderer* ren;
vtkCollectionSimpleIterator rit;
this->Renderers->InitTraversal(rit);
while ((ren = this->Renderers->GetNextRenderer(rit)))
{
ren->SetRenderWindow(nullptr);
}
if (this->HelperWindow)
{
this->HelperWindow->Delete();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ContextId: " << this->HelperWindow->GetGenericContext() << "\n";
os << indent << "Window Id: " << this->HelperWindow->GetGenericWindowId() << "\n";
os << indent << "Initialized: " << this->Initialized << "\n";
os << indent << "PhysicalViewDirection: (" << this->PhysicalViewDirection[0] << ", "
<< this->PhysicalViewDirection[1] << ", " << this->PhysicalViewDirection[2] << ")\n";
os << indent << "PhysicalViewUp: (" << this->PhysicalViewUp[0] << ", " << this->PhysicalViewUp[1]
<< ", " << this->PhysicalViewUp[2] << ")\n";
os << indent << "PhysicalTranslation: (" << this->PhysicalTranslation[0] << ", "
<< this->PhysicalTranslation[1] << ", " << this->PhysicalTranslation[2] << ")\n";
os << indent << "PhysicalScale: " << this->PhysicalScale << "\n";
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::ReleaseGraphicsResources(vtkWindow* renWin)
{
this->Superclass::ReleaseGraphicsResources(renWin);
for (FramebufferDesc& fbo : this->FramebufferDescs)
{
glDeleteFramebuffers(1, &fbo.ResolveFramebufferId);
}
for (auto& model : this->DeviceHandleToDeviceDataMap)
{
if (model.second.Model)
{
model.second.Model->ReleaseGraphicsResources(renWin);
}
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetHelperWindow(vtkOpenGLRenderWindow* win)
{
if (this->HelperWindow == win)
{
return;
}
if (this->HelperWindow)
{
this->ReleaseGraphicsResources(this);
this->HelperWindow->Delete();
}
this->HelperWindow = win;
if (win)
{
win->Register(this);
}
this->Modified();
}
void vtkVRRenderWindow::AddDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
this->DeviceHandleToDeviceDataMap[handle] = {};
}
}
void vtkVRRenderWindow::AddDeviceHandle(uint32_t handle, vtkEventDataDevice device)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
this->DeviceHandleToDeviceDataMap[handle] = {};
found = this->DeviceHandleToDeviceDataMap.find(handle);
}
found->second.Device = device;
}
void vtkVRRenderWindow::SetModelForDeviceHandle(uint32_t handle, vtkVRModel* model)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
this->DeviceHandleToDeviceDataMap[handle] = {};
found = this->DeviceHandleToDeviceDataMap.find(handle);
}
found->second.Model = model;
}
vtkVRModel* vtkVRRenderWindow::GetModelForDevice(vtkEventDataDevice idx)
{
auto handle = this->GetDeviceHandleForDevice(idx);
return this->GetModelForDeviceHandle(handle);
}
vtkVRModel* vtkVRRenderWindow::GetModelForDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
return nullptr;
}
return found->second.Model;
}
vtkMatrix4x4* vtkVRRenderWindow::GetDeviceToPhysicalMatrixForDevice(vtkEventDataDevice idx)
{
auto handle = this->GetDeviceHandleForDevice(idx);
return this->GetDeviceToPhysicalMatrixForDeviceHandle(handle);
}
vtkMatrix4x4* vtkVRRenderWindow::GetDeviceToPhysicalMatrixForDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
return nullptr;
}
return found->second.Pose;
}
uint32_t vtkVRRenderWindow::GetDeviceHandleForDevice(vtkEventDataDevice idx, uint32_t index)
{
for (auto& deviceData : this->DeviceHandleToDeviceDataMap)
{
if (deviceData.second.Device == idx && deviceData.second.Index == index)
{
return deviceData.first;
}
}
return InvalidDeviceIndex;
}
uint32_t vtkVRRenderWindow::GetNumberOfDeviceHandlesForDevice(vtkEventDataDevice dev)
{
uint32_t count = 0;
for (auto& deviceData : this->DeviceHandleToDeviceDataMap)
{
if (deviceData.second.Device == dev)
{
count++;
}
}
return count;
}
// default implementation just uses the vtkEventDataDevice
vtkEventDataDevice vtkVRRenderWindow::GetDeviceForDeviceHandle(uint32_t handle)
{
auto found = this->DeviceHandleToDeviceDataMap.find(handle);
if (found == this->DeviceHandleToDeviceDataMap.end())
{
return vtkEventDataDevice::Unknown;
}
return found->second.Device;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::InitializeViewFromCamera(vtkCamera* srccam)
{
vtkRenderer* ren = vtkRenderer::SafeDownCast(this->GetRenderers()->GetItemAsObject(0));
if (!ren)
{
vtkErrorMacro("The renderer must be set prior to calling InitializeViewFromCamera");
return;
}
vtkVRCamera* cam = vtkVRCamera::SafeDownCast(ren->GetActiveCamera());
if (!cam)
{
vtkErrorMacro(
"The renderer's active camera must be set prior to calling InitializeViewFromCamera");
return;
}
// make sure the view up is reasonable based on the view up
// that was set in PV
double distance = sin(vtkMath::RadiansFromDegrees(srccam->GetViewAngle()) / 2.0) *
srccam->GetDistance() / sin(vtkMath::RadiansFromDegrees(cam->GetViewAngle()) / 2.0);
double* oldVup = srccam->GetViewUp();
int maxIdx = fabs(oldVup[0]) > fabs(oldVup[1]) ? (fabs(oldVup[0]) > fabs(oldVup[2]) ? 0 : 2)
: (fabs(oldVup[1]) > fabs(oldVup[2]) ? 1 : 2);
cam->SetViewUp((maxIdx == 0 ? (oldVup[0] > 0 ? 1 : -1) : 0.0),
(maxIdx == 1 ? (oldVup[1] > 0 ? 1 : -1) : 0.0), (maxIdx == 2 ? (oldVup[2] > 0 ? 1 : -1) : 0.0));
this->SetPhysicalViewUp((maxIdx == 0 ? (oldVup[0] > 0 ? 1 : -1) : 0.0),
(maxIdx == 1 ? (oldVup[1] > 0 ? 1 : -1) : 0.0), (maxIdx == 2 ? (oldVup[2] > 0 ? 1 : -1) : 0.0));
double* oldFP = srccam->GetFocalPoint();
double* cvup = cam->GetViewUp();
cam->SetFocalPoint(oldFP);
this->SetPhysicalTranslation(
cvup[0] * distance - oldFP[0], cvup[1] * distance - oldFP[1], cvup[2] * distance - oldFP[2]);
this->SetPhysicalScale(distance);
double* oldDOP = srccam->GetDirectionOfProjection();
int dopMaxIdx = fabs(oldDOP[0]) > fabs(oldDOP[1]) ? (fabs(oldDOP[0]) > fabs(oldDOP[2]) ? 0 : 2)
: (fabs(oldDOP[1]) > fabs(oldDOP[2]) ? 1 : 2);
this->SetPhysicalViewDirection((dopMaxIdx == 0 ? (oldDOP[0] > 0 ? 1 : -1) : 0.0),
(dopMaxIdx == 1 ? (oldDOP[1] > 0 ? 1 : -1) : 0.0),
(dopMaxIdx == 2 ? (oldDOP[2] > 0 ? 1 : -1) : 0.0));
double* idop = this->GetPhysicalViewDirection();
cam->SetPosition(
-idop[0] * distance + oldFP[0], -idop[1] * distance + oldFP[1], -idop[2] * distance + oldFP[2]);
ren->ResetCameraClippingRange();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::MakeCurrent()
{
if (this->HelperWindow)
{
this->HelperWindow->MakeCurrent();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::ReleaseCurrent()
{
if (this->HelperWindow)
{
this->HelperWindow->ReleaseCurrent();
}
}
//------------------------------------------------------------------------------
vtkOpenGLState* vtkVRRenderWindow::GetState()
{
if (this->HelperWindow)
{
return this->HelperWindow->GetState();
}
return this->Superclass::GetState();
}
//------------------------------------------------------------------------------
bool vtkVRRenderWindow::IsCurrent()
{
return this->HelperWindow ? this->HelperWindow->IsCurrent() : false;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::AddRenderer(vtkRenderer* ren)
{
if (ren && !vtkVRRenderer::SafeDownCast(ren))
{
vtkErrorMacro("vtkVRRenderWindow::AddRenderer: Failed to add renderer of type "
<< ren->GetClassName() << ": A subclass of vtkVRRenderer is expected");
return;
}
this->Superclass::AddRenderer(ren);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Start()
{
// if the renderer has not been initialized, do so now
if (this->HelperWindow && !this->Initialized)
{
this->Initialize();
}
this->Superclass::Start();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Initialize()
{
if (this->Initialized)
{
return;
}
this->GetSizeFromAPI();
this->HelperWindow->SetDisplayId(this->GetGenericDisplayId());
this->HelperWindow->SetShowWindow(false);
this->HelperWindow->Initialize();
this->MakeCurrent();
this->OpenGLInit();
// some classes override the ivar in a getter :-(
this->MaximumHardwareLineWidth = this->HelperWindow->GetMaximumHardwareLineWidth();
glDepthRange(0., 1.);
this->SetWindowName(this->GetWindowTitleFromAPI().c_str());
this->CreateFramebuffers();
this->Initialized = true;
vtkDebugMacro(<< "End of VRRenderWindow Initialization");
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Finalize()
{
this->ReleaseGraphicsResources(this);
this->DeviceHandleToDeviceDataMap.clear();
if (this->HelperWindow && this->HelperWindow->GetGenericContext())
{
this->HelperWindow->Finalize();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::Render()
{
this->MakeCurrent();
this->GetState()->ResetGLViewportState();
this->Superclass::Render();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::RenderFramebuffer(FramebufferDesc& framebufferDesc)
{
this->GetState()->PushDrawFramebufferBinding();
this->GetState()->vtkglBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebufferDesc.ResolveFramebufferId);
glBlitFramebuffer(0, 0, this->Size[0], this->Size[1], 0, 0, this->Size[0], this->Size[1],
GL_COLOR_BUFFER_BIT, GL_LINEAR);
if (framebufferDesc.ResolveDepthTextureId != 0)
{
glBlitFramebuffer(0, 0, this->Size[0], this->Size[1], 0, 0, this->Size[0], this->Size[1],
GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
this->GetState()->PopDrawFramebufferBinding();
}
//------------------------------------------------------------------------------
bool vtkVRRenderWindow::GetDeviceToWorldMatrixForDevice(
vtkEventDataDevice device, vtkMatrix4x4* deviceToWorldMatrix)
{
vtkMatrix4x4* deviceToPhysicalMatrix = this->GetDeviceToPhysicalMatrixForDevice(device);
if (deviceToPhysicalMatrix)
{
// we use deviceToWorldMatrix here to temporarily store physicalToWorld
// to avoid having to use a temp matrix. We use a new pointer just to
// keep the code easier to read.
vtkMatrix4x4* physicalToWorldMatrix = deviceToWorldMatrix;
this->GetPhysicalToWorldMatrix(physicalToWorldMatrix);
vtkMatrix4x4::Multiply4x4(physicalToWorldMatrix, deviceToPhysicalMatrix, deviceToWorldMatrix);
return true;
}
return false;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewDirection(double x, double y, double z)
{
if (this->PhysicalViewDirection[0] != x || this->PhysicalViewDirection[1] != y ||
this->PhysicalViewDirection[2] != z)
{
this->PhysicalViewDirection[0] = x;
this->PhysicalViewDirection[1] = y;
this->PhysicalViewDirection[2] = z;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewDirection(double dir[3])
{
this->SetPhysicalViewDirection(dir[0], dir[1], dir[2]);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewUp(double x, double y, double z)
{
if (this->PhysicalViewUp[0] != x || this->PhysicalViewUp[1] != y || this->PhysicalViewUp[2] != z)
{
this->PhysicalViewUp[0] = x;
this->PhysicalViewUp[1] = y;
this->PhysicalViewUp[2] = z;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalViewUp(double dir[3])
{
this->SetPhysicalViewUp(dir[0], dir[1], dir[2]);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalTranslation(double x, double y, double z)
{
if (this->PhysicalTranslation[0] != x || this->PhysicalTranslation[1] != y ||
this->PhysicalTranslation[2] != z)
{
this->PhysicalTranslation[0] = x;
this->PhysicalTranslation[1] = y;
this->PhysicalTranslation[2] = z;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalTranslation(double trans[3])
{
this->SetPhysicalTranslation(trans[0], trans[1], trans[2]);
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalScale(double scale)
{
if (this->PhysicalScale != scale)
{
this->PhysicalScale = scale;
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetPhysicalToWorldMatrix(vtkMatrix4x4* matrix)
{
if (!matrix)
{
return;
}
vtkNew<vtkMatrix4x4> currentPhysicalToWorldMatrix;
this->GetPhysicalToWorldMatrix(currentPhysicalToWorldMatrix);
bool matrixDifferent = false;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (fabs(matrix->GetElement(i, j) - currentPhysicalToWorldMatrix->GetElement(i, j)) >= 1e-3)
{
matrixDifferent = true;
break;
}
}
}
if (!matrixDifferent)
{
return;
}
vtkNew<vtkTransform> hmdToWorldTransform;
hmdToWorldTransform->SetMatrix(matrix);
double translation[3] = { 0.0 };
hmdToWorldTransform->GetPosition(translation);
this->PhysicalTranslation[0] = (-1.0) * translation[0];
this->PhysicalTranslation[1] = (-1.0) * translation[1];
this->PhysicalTranslation[2] = (-1.0) * translation[2];
double scale[3] = { 0.0 };
hmdToWorldTransform->GetScale(scale);
this->PhysicalScale = scale[0];
this->PhysicalViewUp[0] = matrix->GetElement(0, 1);
this->PhysicalViewUp[1] = matrix->GetElement(1, 1);
this->PhysicalViewUp[2] = matrix->GetElement(2, 1);
vtkMath::Normalize(this->PhysicalViewUp);
this->PhysicalViewDirection[0] = (-1.0) * matrix->GetElement(0, 2);
this->PhysicalViewDirection[1] = (-1.0) * matrix->GetElement(1, 2);
this->PhysicalViewDirection[2] = (-1.0) * matrix->GetElement(2, 2);
vtkMath::Normalize(this->PhysicalViewDirection);
this->InvokeEvent(vtkVRRenderWindow::PhysicalToWorldMatrixModified);
this->Modified();
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::GetPhysicalToWorldMatrix(vtkMatrix4x4* physicalToWorldMatrix)
{
if (!physicalToWorldMatrix)
{
return;
}
physicalToWorldMatrix->Identity();
// construct physical to non-scaled world axes (scaling is applied later)
double physicalZ_NonscaledWorld[3] = { -this->PhysicalViewDirection[0],
-this->PhysicalViewDirection[1], -this->PhysicalViewDirection[2] };
double* physicalY_NonscaledWorld = this->PhysicalViewUp;
double physicalX_NonscaledWorld[3] = { 0.0 };
vtkMath::Cross(physicalY_NonscaledWorld, physicalZ_NonscaledWorld, physicalX_NonscaledWorld);
for (int row = 0; row < 3; ++row)
{
physicalToWorldMatrix->SetElement(row, 0, physicalX_NonscaledWorld[row] * this->PhysicalScale);
physicalToWorldMatrix->SetElement(row, 1, physicalY_NonscaledWorld[row] * this->PhysicalScale);
physicalToWorldMatrix->SetElement(row, 2, physicalZ_NonscaledWorld[row] * this->PhysicalScale);
physicalToWorldMatrix->SetElement(row, 3, -this->PhysicalTranslation[row]);
}
}
//------------------------------------------------------------------------------
int* vtkVRRenderWindow::GetScreenSize()
{
if (this->GetSizeFromAPI())
{
this->ScreenSize[0] = this->Size[0];
this->ScreenSize[1] = this->Size[1];
}
return this->ScreenSize;
}
//------------------------------------------------------------------------------
void vtkVRRenderWindow::SetSize(int width, int height)
{
if ((this->Size[0] != width) || (this->Size[1] != height))
{
this->Superclass::SetSize(width, height);
if (this->Interactor)
{
this->Interactor->SetSize(width, height);
}
}
}
| 31.497553 | 100 | 0.610317 | jpouderoux |
4b456dc0150daf1a1979db5991fec39e2c70fefe | 732 | cpp | C++ | Ticker.cpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 26 | 2015-04-22T05:25:25.000Z | 2020-11-15T11:07:56.000Z | Ticker.cpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 2 | 2015-01-05T10:41:27.000Z | 2015-01-06T20:46:11.000Z | Ticker.cpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 5 | 2016-08-02T11:13:57.000Z | 2018-10-26T11:19:27.000Z | #include "Ticker.hpp"
BEGIN_INANITY
Ticker::Ticker() :
lastTick(-1),
pauseTick(-1)
{
tickCoef = 1.0f / Time::GetTicksPerSecond();
}
void Ticker::Pause()
{
// if already paused, do nothing
if(pauseTick >= 0)
return;
// remember pause time
pauseTick = Time::GetTick();
}
float Ticker::Tick()
{
// get current time
Time::Tick currentTick = Time::GetTick();
// calculate amount of ticks from last tick
Time::Tick ticks = 0;
if(lastTick >= 0)
{
if(pauseTick >= 0)
ticks = pauseTick - lastTick;
else
ticks = currentTick - lastTick;
}
// if was paused, resume
if(pauseTick >= 0)
pauseTick = -1;
// remember current tick as last tick
lastTick = currentTick;
return ticks * tickCoef;
}
END_INANITY
| 15.25 | 45 | 0.659836 | quyse |
4b4571a1dcce05248083a5fc2bc7cf8acfc8de44 | 1,851 | cpp | C++ | Code/Libraries/Rodin/src/BTNodes/rodinbtnodeuseresource.cpp | lihop/Eldritch | bb38ff8ad59e4c1f11b1430ef482e60f7618a280 | [
"Zlib"
] | 4 | 2019-09-15T20:00:23.000Z | 2021-08-27T23:32:53.000Z | Code/Libraries/Rodin/src/BTNodes/rodinbtnodeuseresource.cpp | lihop/Eldritch | bb38ff8ad59e4c1f11b1430ef482e60f7618a280 | [
"Zlib"
] | null | null | null | Code/Libraries/Rodin/src/BTNodes/rodinbtnodeuseresource.cpp | lihop/Eldritch | bb38ff8ad59e4c1f11b1430ef482e60f7618a280 | [
"Zlib"
] | 1 | 2021-03-27T11:27:03.000Z | 2021-03-27T11:27:03.000Z | #include "core.h"
#include "rodinbtnodeuseresource.h"
#include "configmanager.h"
#include "Components/wbcomprodinresourcemap.h"
#include "Components/wbcomprodinbehaviortree.h"
#include "wbentity.h"
RodinBTNodeUseResource::RodinBTNodeUseResource()
: m_Resource()
, m_ForceClaim( false )
{
}
RodinBTNodeUseResource::~RodinBTNodeUseResource()
{
}
void RodinBTNodeUseResource::InitializeFromDefinition( const SimpleString& DefinitionName )
{
RodinBTNodeDecorator::InitializeFromDefinition( DefinitionName );
MAKEHASH( DefinitionName );
STATICHASH( Resource );
m_Resource = ConfigManager::GetHash( sResource, HashedString::NullString, sDefinitionName );
STATICHASH( ForceClaim );
m_ForceClaim = ConfigManager::GetBool( sForceClaim, false, sDefinitionName );
}
/*virtual*/ RodinBTNode::ETickStatus RodinBTNodeUseResource::Tick( const float DeltaTime )
{
WBCompRodinResourceMap* const pResourceMap = GET_WBCOMP( GetEntity(), RodinResourceMap );
ASSERT( pResourceMap );
if( m_ChildStatus != ETS_None )
{
// We're just continuing from being woken.
return RodinBTNodeDecorator::Tick( DeltaTime );
}
if( pResourceMap->ClaimResource( this, m_Resource, m_ForceClaim ) )
{
// We got the resource, we're all good (or we're just continuing from being woken).
return RodinBTNodeDecorator::Tick( DeltaTime );
}
else
{
// We couldn't get the resource.
return ETS_Fail;
}
}
/*virtual*/ void RodinBTNodeUseResource::OnFinish()
{
RodinBTNodeDecorator::OnFinish();
WBCompRodinResourceMap* const pResourceMap = GET_WBCOMP( GetEntity(), RodinResourceMap );
ASSERT( pResourceMap );
pResourceMap->ReleaseResource( this, m_Resource );
}
/*virtual*/ bool RodinBTNodeUseResource::OnResourceStolen( const HashedString& Resource )
{
Unused( Resource );
ASSERT( Resource == m_Resource );
m_BehaviorTree->Stop( this );
return false;
} | 26.070423 | 93 | 0.763911 | lihop |
4b45b2aa280d0a1054559f1185dd10551b0220e2 | 331 | cpp | C++ | src/power.cpp | Glowman554/FoxOS-kernel | 06c9f820dee8769b23cf6ba4d5df9cb9324a14d7 | [
"MIT"
] | 13 | 2021-02-19T16:54:18.000Z | 2022-01-06T18:02:20.000Z | src/power.cpp | Glowman554/FoxOS-kernel | 06c9f820dee8769b23cf6ba4d5df9cb9324a14d7 | [
"MIT"
] | 1 | 2021-08-21T16:55:38.000Z | 2021-08-24T10:34:32.000Z | src/power.cpp | Glowman554/FoxOS-kernel | 06c9f820dee8769b23cf6ba4d5df9cb9324a14d7 | [
"MIT"
] | 4 | 2021-08-20T15:28:01.000Z | 2022-03-22T19:02:56.000Z | #include <power.h>
#include <pci/acpi.h>
#include <interrupts/panic.h>
#include <stivale2.h>
//#do_reboot-doc: Reboot FoxOS
void do_reboot() {
uint8_t good = 0x02;
while (good & 0x02) {
good = inb(0x64);
}
outb(0x64, 0xfe);
asm("hlt");
interrupts::Panic p = interrupts::Panic((char*) "Reboot failed!");
p.do_it(NULL);
} | 18.388889 | 67 | 0.655589 | Glowman554 |
4b49ad3749602235aac24ea6c174b33d47f545f6 | 45,547 | cc | C++ | Calibration/EcalCalibAlgos/src/ElectronCalibrationUniv.cc | malbouis/cmssw | 16173a30d3f0c9ecc5419c474bb4d272c58b65c8 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Calibration/EcalCalibAlgos/src/ElectronCalibrationUniv.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Calibration/EcalCalibAlgos/src/ElectronCalibrationUniv.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z |
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "Calibration/Tools/interface/calibXMLwriter.h"
#include "Calibration/Tools/interface/CalibrationCluster.h"
#include "Calibration/Tools/interface/HouseholderDecomposition.h"
#include "Calibration/Tools/interface/MinL3Algorithm.h"
#include "Calibration/EcalCalibAlgos/interface/ElectronCalibrationUniv.h"
#include "FWCore/Utilities/interface/isFinite.h"
#include "TF1.h"
#include "TRandom.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>
ElectronCalibrationUniv::ElectronCalibrationUniv(const edm::ParameterSet& iConfig)
: ebRecHitLabel_(iConfig.getParameter<edm::InputTag>("ebRecHitsLabel")),
eeRecHitLabel_(iConfig.getParameter<edm::InputTag>("eeRecHitsLabel")),
electronLabel_(iConfig.getParameter<edm::InputTag>("electronLabel")),
rootfile_(iConfig.getParameter<std::string>("rootfile")),
calibAlgo_(iConfig.getParameter<std::string>("CALIBRATION_ALGO")),
miscalibfile_(iConfig.getParameter<std::string>("miscalibfile")),
miscalibfileEndCap_(iConfig.getParameter<std::string>("miscalibfileEndCap")),
keventweight_(iConfig.getParameter<int>("keventweight")),
elePt_(iConfig.getParameter<double>("ElePt")),
maxeta_(iConfig.getParameter<int>("maxeta")),
mineta_(iConfig.getParameter<int>("mineta")),
maxphi_(iConfig.getParameter<int>("maxphi")),
minphi_(iConfig.getParameter<int>("minphi")),
cut1_(iConfig.getParameter<double>("cut1")),
cut2_(iConfig.getParameter<double>("cut2")),
cut3_(iConfig.getParameter<double>("cut3")),
numevent_(iConfig.getParameter<int>("numevent")),
cutEPCalo1_(iConfig.getParameter<double>("cutEPCaloMin")),
cutEPCalo2_(iConfig.getParameter<double>("cutEPCaloMax")),
cutEPin1_(iConfig.getParameter<double>("cutEPinMin")),
cutEPin2_(iConfig.getParameter<double>("cutEPinMax")),
cutCalo1_(iConfig.getParameter<double>("cutCaloMin")),
cutCalo2_(iConfig.getParameter<double>("cutCaloMax")),
cutESeed_(iConfig.getParameter<double>("cutESeed")),
clusterSize_(iConfig.getParameter<int>("Clustersize")),
elecclass_(iConfig.getParameter<int>("elecclass")),
ebRecHitToken_(consumes<EBRecHitCollection>(ebRecHitLabel_)),
eeRecHitToken_(consumes<EERecHitCollection>(eeRecHitLabel_)),
gsfElectronToken_(consumes<reco::GsfElectronCollection>(electronLabel_)),
topologyToken_(esConsumes<edm::Transition::BeginRun>()) {}
ElectronCalibrationUniv::~ElectronCalibrationUniv() {}
//========================================================================
void ElectronCalibrationUniv::beginJob() {
//========================================================================
f = new TFile(rootfile_.c_str(), "RECREATE");
f->cd();
EventsAfterCuts = new TH1F("EventsAfterCuts", "Events After Cuts", 30, 0, 30);
// Book histograms
e9 = new TH1F("e9", "E9 energy", 300, 0., 150.);
e25 = new TH1F("e25", "E25 energy", 300, 0., 150.);
scE = new TH1F("scE", "SC energy", 300, 0., 150.);
trP = new TH1F("trP", "Trk momentum", 300, 0., 150.);
EoP = new TH1F("EoP", "EoP", 600, 0., 3.);
EoP_all = new TH1F("EoP_all", "EoP_all", 600, 0., 3.);
calibs = new TH1F("calib", "Calibration constants", 800, 0.5, 2.);
calibsEndCapMinus = new TH1F("calibEndCapMinus", "Calibration constants EE-", 800, 0.5, 2.);
calibsEndCapPlus = new TH1F("calibEndCapPlus", "Calibration constants EE+", 800, 0.5, 2.);
e25OverScE = new TH1F("e25OverscE", "E25 / SC energy", 400, 0., 2.);
E25oP = new TH1F("E25oP", "E25 / P", 750, 0., 1.5);
Map = new TH2F("Map", "Nb Events in Crystal", 173, -86, 86, 362, 0, 361);
e9Overe25 = new TH1F("e9Overe25", "E9 / E25", 400, 0., 2.);
Map3Dcalib = new TH2F("3Dcalib", "3Dcalib", 173, -86, 86, 362, 0, 361);
Map3DcalibEndCapMinus = new TH2F("3DcalibEndCapMinus", "3Dcalib EE-", 100, 0, 100, 100, 0, 100);
Map3DcalibEndCapPlus = new TH2F("3DcalibEndCapPlus", "3Dcalib EE+", 100, 0, 100, 100, 0, 100);
MapCor1 = new TH2F("MapCor1", "Correlation E25/Pcalo versus E25/Pin", 100, 0., 5., 100, 0., 5.);
MapCor2 = new TH2F("MapCor2", "Correlation E25/Pcalo versus E/P", 100, 0., 5., 100, 0., 5.);
MapCor3 = new TH2F("MapCor3", "Correlation E25/Pcalo versus Pout/Pin", 100, 0., 5., 100, 0., 5.);
MapCor4 = new TH2F("MapCor4", "Correlation E25/Pcalo versus E25/highestP", 100, 0., 5., 100, 0., 5.);
MapCor5 = new TH2F("MapCor5", "Correlation E25/Pcalo versus Pcalo/Pout", 100, 0., 5., 100, 0., 5.);
MapCor6 = new TH2F("MapCor6", "Correlation Pout/Pin versus E25/Pin", 100, 0., 5., 100, 0., 5.);
MapCor7 = new TH2F("MapCor7", "Correlation Pout/Pin versus Pcalo/Pout", 100, 0., 5., 100, 0., 5.);
MapCor8 = new TH2F("MapCor8", "Correlation E25/Pin versus Pcalo/Pout", 100, 0., 5., 100, 0., 5.);
MapCor9 = new TH2F("MapCor9", "Correlation E25/Pcalo versus Eseed/Pout", 100, 0., 5., 100, 0., 5.);
MapCor10 = new TH2F("MapCor10", "Correlation Eseed/Pout versus Pout/Pin", 100, 0., 5., 100, 0., 5.);
MapCor11 = new TH2F("MapCor11", "Correlation Eseed/Pout versus E25/Pin", 100, 0., 5., 100, 0., 5.);
// MapCorCalib = new TH2F ("MapCorCalib", "Correlation Miscalibration versus Calibration constants", 500, 0.5,1.5, 500, 0.5, 1.5);
E25oPvsEta = new TH2F("E25oPvsEta", "E/P vs Eta", 173, -86, 86, 600, 0.7, 1.3);
E25oPvsEtaEndCapMinus = new TH2F("E25oPvsEtaEndCapMinus", "E/P vs R EE-", 100, 0, 100, 600, 0.7, 1.3);
E25oPvsEtaEndCapPlus = new TH2F("E25oPvsEtaEndCapPlus", "E/P vs R EE+", 100, 0, 100, 600, 0.7, 1.3);
PinMinPout = new TH1F("PinMinPout", "(Pin - Pout)/Pin", 600, -2.0, 2.0);
calibinter = new TH1F("calibinter", "internal calibration constants", 800, 0.5, 2.);
PinOverPout = new TH1F("PinOverPout", "pinOverpout", 600, 0., 3.);
eSeedOverPout = new TH1F("eSeedOverPout", "eSeedOverpout ", 600, 0., 3.);
// MisCalibs = new TH1F("MisCalibs","Miscalibration constants",800,0.5,2.);
// RatioCalibs = new TH1F("RatioCalibs","Ratio in Calibration Constants", 800, 0.5, 2.0);
// DiffCalibs = new TH1F("DiffCalibs", "Difference in Calibration constants", 800, -1.0,1.0);
calibinterEndCapMinus = new TH1F("calibinterEndCapMinus", "internal calibration constants", 800, 0.5, 2.);
calibinterEndCapPlus = new TH1F("calibinterEndCapPlus", "internal calibration constants", 800, 0.5, 2.);
// MisCalibsEndCapMinus = new TH1F("MisCalibsEndCapMinus","Miscalibration constants",800,0.5,2.);
// MisCalibsEndCapPlus = new TH1F("MisCalibsEndCapPlus","Miscalibration constants",800,0.5,2.);
// RatioCalibsEndCapMinus = new TH1F("RatioCalibsEndCapMinus","Ratio in Calibration Constants", 800, 0.5, 2.0);
// RatioCalibsEndCapPlus = new TH1F("RatioCalibsEndCapPlus","Ratio in Calibration Constants", 800, 0.5, 2.0);
// DiffCalibsEndCapMinus = new TH1F("DiffCalibsEndCapMinus", "Difference in Calibration constants", 800, -1.0,1.0);
// DiffCalibsEndCapPlus = new TH1F("DiffCalibsEndCapPlus", "Difference in Calibration constants", 800, -1.0,1.0);
Error1 = new TH1F("Error1", "DeltaP/Pin", 800, -1.0, 1.0);
Error2 = new TH1F("Error2", "DeltaP/Pout", 800, -1.0, 1.0);
Error3 = new TH1F("Error3", "DeltaP/Pcalo", 800, -1.0, 1.0);
eSeedOverPout2 = new TH1F("eSeedOverPout2", "eSeedOverpout (No Supercluster)", 600, 0., 4.);
hadOverEm = new TH1F("hadOverEm", "Had/EM distribution", 600, -2., 2.);
// Book histograms
Map3DcalibNoCuts = new TH2F("3DcalibNoCuts", "3Dcalib (Before Cuts)", 173, -86, 86, 362, 0, 361);
e9NoCuts = new TH1F("e9NoCuts", "E9 energy (Before Cuts)", 300, 0., 150.);
e25NoCuts = new TH1F("e25NoCuts", "E25 energy (Before Cuts)", 300, 0., 150.);
scENoCuts = new TH1F("scENoCuts", "SC energy (Before Cuts)", 300, 0., 150.);
trPNoCuts = new TH1F("trPNoCuts", "Trk momentum (Before Cuts)", 300, 0., 150.);
EoPNoCuts = new TH1F("EoPNoCuts", "EoP (Before Cuts)", 600, 0., 3.);
calibsNoCuts = new TH1F("calibNoCuts", "Calibration constants (Before Cuts)", 800, 0., 2.);
e25OverScENoCuts = new TH1F("e25OverscENoCuts", "E25 / SC energy (Before Cuts)", 400, 0., 2.);
E25oPNoCuts = new TH1F("E25oPNoCuts", "E25 / P (Before Cuts)", 750, 0., 1.5);
MapEndCapMinus = new TH2F("MapEndCapMinus", "Nb Events in Crystal (EndCap)", 100, 0, 100, 100, 0, 100);
MapEndCapPlus = new TH2F("MapEndCapPlus", "Nb Events in Crystal (EndCap)", 100, 0, 100, 100, 0, 100);
e9Overe25NoCuts = new TH1F("e9Overe25NoCuts", "E9 / E25 (Before Cuts)", 400, 0., 2.);
PinOverPoutNoCuts = new TH1F("PinOverPoutNoCuts", "pinOverpout (Before Cuts)", 600, 0., 3.);
eSeedOverPoutNoCuts = new TH1F(" eSeedOverPoutNoCuts", "eSeedOverpout (Before Cuts) ", 600, 0., 4.);
PinMinPoutNoCuts = new TH1F("PinMinPoutNoCuts", "(Pin - Pout)/Pin (Before Cuts)", 600, -2.0, 2.0);
// RatioCalibsNoCuts = new TH1F("RatioCalibsNoCuts","Ratio in Calibration Constants (Before Cuts)", 800, 0.5, 2.0);
// DiffCalibsNoCuts = new TH1F("DiffCalibsNoCuts", "Difference in Calibration constants (Before Cuts)", 800, -1.0,1.0);
calibinterNoCuts = new TH1F("calibinterNoCuts", "internal calibration constants", 2000, 0.5, 2.);
MapCor1NoCuts =
new TH2F("MapCor1NoCuts", "Correlation E25/PatCalo versus E25/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor2NoCuts =
new TH2F("MapCor2NoCuts", "Correlation E25/PatCalo versus E/P (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor3NoCuts =
new TH2F("MapCor3NoCuts", "Correlation E25/PatCalo versus Pout/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor4NoCuts =
new TH2F("MapCor4NoCuts", "Correlation E25/PatCalo versus E25/highestP (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor5NoCuts =
new TH2F("MapCor5NoCuts", "Correlation E25/Pcalo versus Pcalo/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor6NoCuts =
new TH2F("MapCor6NoCuts", "Correlation Pout/Pin versus E25/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor7NoCuts =
new TH2F("MapCor7NoCuts", "Correlation Pout/Pin versus Pcalo/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor8NoCuts =
new TH2F("MapCor8NoCuts", "Correlation E25/Pin versus Pcalo/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor9NoCuts =
new TH2F("MapCor9NoCuts", "Correlation E25/Pcalo versus Eseed/Pout (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor10NoCuts =
new TH2F("MapCor10NoCuts", "Correlation Eseed/Pout versus Pout/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
MapCor11NoCuts =
new TH2F("MapCor11NoCuts", "Correlation Eseed/Pout versus E25/Pin (Before Cuts)", 100, 0., 5., 100, 0., 5.);
// MapCorCalibEndCapMinus = new TH2F ("MapCorCalibEndCapMinus", "Correlation Miscalibration versus Calibration constants (EndCap)", 500, 0.5,1.5, 500, 0.5, 1.5);
// MapCorCalibEndCapPlus = new TH2F ("MapCorCalibEndCapPlus", "Correlation Miscalibration versus Calibration constants (EndCap)", 500, 0.5,1.5, 500, 0.5, 1.5);
Error1NoCuts = new TH1F("Eror1NoCuts", "DeltaP/Pin (Before Cuts)", 800, -1.0, 1.0);
Error2NoCuts = new TH1F("Error2NoCuts", "DeltaP/Pout (Before Cuts)", 800, -1.0, 1.0);
Error3NoCuts = new TH1F("Error3NoCuts", "DeltaP/Pcalo (Before Cuts)", 800, -1.0, 1.0);
eSeedOverPout2NoCuts = new TH1F("eSeedOverPout2NoCuts", "eSeedOverpout (No Supercluster, Before Cuts)", 600, 0., 4.);
hadOverEmNoCuts = new TH1F("hadOverEmNoCuts", "Had/EM distribution (Before Cuts)", 600, -2., 2.);
//Book histograms after ESeed cut
MapCor1ESeed =
new TH2F("MapCor1ESeed", "Correlation E25/Pcalo versus E25/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor2ESeed =
new TH2F("MapCor2ESeed", "Correlation E25/Pcalo versus E/P (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor3ESeed = new TH2F(
"MapCor3ESeed", "Correlation E25/Pcalo versus Pout/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor4ESeed = new TH2F(
"MapCor4ESeed", "Correlation E25/Pcalo versus E25/highestP (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor5ESeed = new TH2F(
"MapCor5ESeed", "Correlation E25/Pcalo versus Pcalo/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor6ESeed =
new TH2F("MapCor6ESeed", "Correlation Pout/Pin versus E25/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor7ESeed = new TH2F(
"MapCor7ESeed", "Correlation Pout/Pin versus Pcalo/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor8ESeed = new TH2F(
"MapCor8ESeed", "Correlation E25/Pin versus Pcalo/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor9ESeed = new TH2F(
"MapCor9ESeed", "Correlation E25/Pcalo versus Eseed/Pout (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor10ESeed = new TH2F(
"MapCor10ESeed", "Correlation Eseed/Pout versus Pout/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
MapCor11ESeed = new TH2F(
"MapCor11ESeed", "Correlation Eseed/Pout versus E25/Pin (after Eseed/Pout cut)", 100, 0., 5., 100, 0., 5.);
eSeedOverPout2ESeed =
new TH1F("eSeedOverPout2ESeed", "eSeedOverpout (No Supercluster, after Eseed/Pout cut)", 600, 0., 4.);
hadOverEmESeed = new TH1F("hadOverEmESeed", "Had/EM distribution (after Eseed/Pout cut)", 600, -2., 2.);
//Book histograms without any cut
GeneralMap = new TH2F("GeneralMap", "Map without any cuts", 173, -86, 86, 362, 0, 361);
GeneralMapEndCapMinus = new TH2F("GeneralMapEndCapMinus", "Map without any cuts", 100, 0, 100, 100, 0, 100);
GeneralMapEndCapPlus = new TH2F("GeneralMapEndCapPlus", "Map without any cuts", 100, 0, 100, 100, 0, 100);
GeneralMapBeforePt = new TH2F("GeneralMapBeforePt", "Map without any cuts", 173, -86, 86, 362, 0, 361);
GeneralMapEndCapMinusBeforePt =
new TH2F("GeneralMapEndCapMinusBeforePt", "Map without any cuts", 100, 0, 100, 100, 0, 100);
GeneralMapEndCapPlusBeforePt =
new TH2F("GeneralMapEndCapPlusBeforePt", "Map without any cuts", 100, 0, 100, 100, 0, 100);
calibClusterSize = clusterSize_;
etaMin = int(mineta_);
etaMax = int(maxeta_);
phiMin = int(minphi_);
phiMax = int(maxphi_);
if (calibAlgo_ == "L3") {
MyL3Algo1 = new MinL3Algorithm(keventweight_, calibClusterSize, etaMin, etaMax, phiMin, phiMax);
} else {
if (calibAlgo_ == "L3Univ") {
UnivL3 = new MinL3AlgoUniv<DetId>(keventweight_);
} else {
if (calibAlgo_ == "HH" || calibAlgo_ == "HHReg") {
MyHH = new HouseholderDecomposition(calibClusterSize, etaMin, etaMax, phiMin, phiMax);
} else {
std::cout << " Name of Algorithm is not recognize " << calibAlgo_
<< " Should be either L3, HH or HHReg. Abort! " << std::endl;
}
}
}
read_events = 0;
}
//========================================================================
void ElectronCalibrationUniv::beginRun(edm::Run const&, edm::EventSetup const& iSetup) {
//========================================================================
//To Deal with Geometry:
theCaloTopology_ = &iSetup.getData(topologyToken_);
}
//========================================================================
void ElectronCalibrationUniv::endRun(edm::Run const&, edm::EventSetup const& iSetup) {}
//========================================================================
//========================================================================
void ElectronCalibrationUniv::endJob() {
//========================================================================
f->cd();
time_t start, end;
time_t cpu_time_used;
start = time(nullptr);
//In order to do only one loop to use properly looper properties, ask only for 1 iterations!
int nIterations = 10;
if (calibAlgo_ == "L3") {
solution = MyL3Algo1->iterate(EventMatrix, MaxCCeta, MaxCCphi, EnergyVector, nIterations);
} else {
if (calibAlgo_ == "L3Univ") {
//Univsolution= UnivL3->getSolution();
// std::cout<<" Should derive solution "<<EnergyVector.size()<<std::endl;
Univsolution = UnivL3->iterate(EventMatrix, UnivEventIds, EnergyVector, nIterations);
//std::cout<<" solution size "<<Univsolution.size()<<std::endl;
} else {
if (calibAlgo_ == "HH") {
solution = MyHH->iterate(EventMatrix, MaxCCeta, MaxCCphi, EnergyVector, 1, false);
} else {
if (calibAlgo_ == "HHReg") {
solution = MyHH->runRegional(EventMatrix, MaxCCeta, MaxCCphi, EnergyVector, 2);
} else {
std::cout << " Calibration not run due to problem in Algo Choice..." << std::endl;
return;
}
}
}
}
end = time(nullptr);
cpu_time_used = end - start;
// std::cout<<"222 solution size "<<Univsolution.size()<<std::endl;
calibXMLwriter write_calibrations;
// FILE* MisCalib;
// //char* calibfile="miscalibfile";
// MisCalib = fopen(miscalibfile_.c_str(),"r");
// int fileStatus=0;
// int eta=-1;
// int phi=-1;
// float coeff=-1;
std::map<EBDetId, float> OldCoeff;
// while(fileStatus != EOF) {
// fileStatus = fscanf(MisCalib,"%d %d %f\n", &eta,&phi,&coeff);
// if(eta!=-1&&phi!=-1&& coeff!=-1){
// // std::cout<<" We have read correctly the coefficient " << coeff << " corresponding to eta "<<eta<<" and phi "<<phi<<std::endl;
// OldCoeff.insert(std::make_pair(EBDetId(eta,phi,EBDetId::ETAPHIMODE),coeff ));
// }
// }
// fclose(MisCalib);
// FILE* MisCalibEndCap;
// //char* calibfile="miscalibfile";
// MisCalibEndCap = fopen(miscalibfileEndCap_.c_str(),"r");
// int fileStatus2=0;
// int X=-1;
// int Y=-1;
// float coeff2=-1;
std::map<EEDetId, float> OldCoeffEndCap;
// while(fileStatus2 != EOF) {
// fileStatus2 = fscanf(MisCalibEndCap,"%d %d %f\n", &X,&Y,&coeff2);
// if(X!=-1&&Y!=-1&& coeff2!=-1){
// // std::cout<<" We have read correctly the coefficient " << coeff << " corresponding to eta "<<eta<<" and phi "<<phi<<std::endl;
// if(TestEEvalidDetId(X,Y,1)){
// OldCoeffEndCap.insert(std::make_pair(EEDetId(X,Y,1,EEDetId::XYMODE),coeff2 ));
// }
// }
// }
// fclose(MisCalibEndCap);
std::map<DetId, float>::const_iterator itmap;
for (itmap = Univsolution.begin(); itmap != Univsolution.end(); itmap++) {
const DetId Id(itmap->first);
if (Id.subdetId() == 1) {
const EBDetId IChannelDetId(itmap->first);
if (IChannelDetId.ieta() < mineta_) {
continue;
}
if (IChannelDetId.ieta() > maxeta_) {
continue;
}
if (IChannelDetId.iphi() < minphi_) {
continue;
}
if (IChannelDetId.iphi() > maxphi_) {
continue;
}
// float Compare=1;
// std::map<EBDetId,float>::iterator iter = OldCoeff.find(itmap->first);
// if( iter != OldCoeff.end() )Compare = iter->second;
Map3Dcalib->Fill(IChannelDetId.ieta(), IChannelDetId.iphi(), itmap->second);
calibs->Fill(itmap->second);
//DiffCalibs->Fill(newCalibs[icry]-miscalib[IChannelDetId.ieta()-1][IChannelDetId.iphi()-21]);
//RatioCalibs->Fill(newCalibs[icry]/miscalib[IChannelDetId.ieta()-1][IChannelDetId.iphi()-21]);
if (IChannelDetId.ieta() < mineta_ + 2) {
continue;
}
if (IChannelDetId.ieta() > maxeta_ - 2) {
continue;
}
if (IChannelDetId.iphi() < minphi_ + 2) {
continue;
}
if (IChannelDetId.iphi() > maxphi_ - 2) {
continue;
}
write_calibrations.writeLine(IChannelDetId, itmap->second);
calibinter->Fill(itmap->second);
// MapCorCalib->Fill(itmap->second,Compare);
// DiffCalibs->Fill(itmap->second-Compare);
// RatioCalibs->Fill(itmap->second*Compare);
} else {
const EEDetId IChannelDetId(itmap->first);
// if (IChannelDetId.ix()<0 ){continue;}
// if (IChannelDetId.ix()>100 ){continue;}
// if (IChannelDetId.iy()<0 ){continue;}
// if (IChannelDetId.iy()>100 ){continue;}
// std::map<EEDetId,float>::iterator iter = OldCoeffEndCap.find(itmap->first);
// float Compare=1;
// if( iter != OldCoeffEndCap.end() )Compare = iter->second;
if (IChannelDetId.zside() < 0) {
Map3DcalibEndCapMinus->Fill(IChannelDetId.ix(), IChannelDetId.iy(), itmap->second);
calibsEndCapMinus->Fill(itmap->second);
calibinterEndCapMinus->Fill(itmap->second);
// DiffCalibsEndCapMinus->Fill(itmap->second-Compare);
// RatioCalibsEndCapMinus->Fill(itmap->second*Compare);
// MapCorCalibEndCapMinus->Fill(itmap->second,Compare);
} else {
Map3DcalibEndCapPlus->Fill(IChannelDetId.ix(), IChannelDetId.iy(), itmap->second);
calibsEndCapPlus->Fill(itmap->second);
calibinterEndCapPlus->Fill(itmap->second);
// DiffCalibsEndCapPlus->Fill(itmap->second-Compare);
// RatioCalibsEndCapPlus->Fill(itmap->second*Compare);
// MapCorCalibEndCapPlus->Fill(itmap->second,Compare);
}
write_calibrations.writeLine(IChannelDetId, itmap->second);
}
}
EventsAfterCuts->Write();
// Book histograms
e25->Write();
e9->Write();
scE->Write();
trP->Write();
EoP->Write();
EoP_all->Write();
calibs->Write();
calibsEndCapMinus->Write();
calibsEndCapPlus->Write();
e9Overe25->Write();
e25OverScE->Write();
Map->Write();
E25oP->Write();
PinOverPout->Write();
eSeedOverPout->Write();
// MisCalibs->Write();
// RatioCalibs->Write();
// DiffCalibs->Write();
// RatioCalibsNoCuts->Write();
// DiffCalibsNoCuts->Write();
// MisCalibsEndCapMinus->Write();
// MisCalibsEndCapPlus->Write();
// RatioCalibsEndCapMinus->Write();
// RatioCalibsEndCapPlus->Write();
// DiffCalibsEndCapMinus->Write();
// DiffCalibsEndCapPlus->Write();
e25NoCuts->Write();
e9NoCuts->Write();
scENoCuts->Write();
trPNoCuts->Write();
EoPNoCuts->Write();
calibsNoCuts->Write();
e9Overe25NoCuts->Write();
e25OverScENoCuts->Write();
MapEndCapMinus->Write();
MapEndCapPlus->Write();
E25oPNoCuts->Write();
Map3Dcalib->Write();
Map3DcalibEndCapMinus->Write();
Map3DcalibEndCapPlus->Write();
Map3DcalibNoCuts->Write();
calibinter->Write();
calibinterEndCapMinus->Write();
calibinterEndCapPlus->Write();
calibinterNoCuts->Write();
PinOverPoutNoCuts->Write();
eSeedOverPoutNoCuts->Write();
GeneralMap->Write();
GeneralMapEndCapMinus->Write();
GeneralMapEndCapPlus->Write();
GeneralMapBeforePt->Write();
GeneralMapEndCapMinusBeforePt->Write();
GeneralMapEndCapPlusBeforePt->Write();
MapCor1->Write();
MapCor2->Write();
MapCor3->Write();
MapCor4->Write();
MapCor5->Write();
MapCor6->Write();
MapCor7->Write();
MapCor8->Write();
MapCor9->Write();
MapCor10->Write();
MapCor11->Write();
// MapCorCalib->Write();
MapCor1NoCuts->Write();
MapCor2NoCuts->Write();
MapCor3NoCuts->Write();
MapCor4NoCuts->Write();
MapCor5NoCuts->Write();
MapCor6NoCuts->Write();
MapCor7NoCuts->Write();
MapCor8NoCuts->Write();
MapCor9NoCuts->Write();
MapCor10NoCuts->Write();
MapCor11NoCuts->Write();
// MapCorCalibEndCapMinus->Write();
// MapCorCalibEndCapPlus->Write();
MapCor1ESeed->Write();
MapCor2ESeed->Write();
MapCor3ESeed->Write();
MapCor4ESeed->Write();
MapCor5ESeed->Write();
MapCor6ESeed->Write();
MapCor7ESeed->Write();
MapCor8ESeed->Write();
MapCor9ESeed->Write();
MapCor10ESeed->Write();
MapCor11ESeed->Write();
E25oPvsEta->Write();
E25oPvsEtaEndCapMinus->Write();
E25oPvsEtaEndCapPlus->Write();
PinMinPout->Write();
PinMinPoutNoCuts->Write();
Error1->Write();
Error2->Write();
Error3->Write();
Error1NoCuts->Write();
Error2NoCuts->Write();
Error3NoCuts->Write();
eSeedOverPout2->Write();
eSeedOverPout2NoCuts->Write();
eSeedOverPout2ESeed->Write();
hadOverEm->Write();
hadOverEmNoCuts->Write();
hadOverEmESeed->Write();
f->Write();
f->Close();
// if(MyL3Algo1)delete MyL3Algo1;
// if(UnivL3)delete UnivL3;
// if(MyHH)delete MyHH;
// delete f;
//////////////////////// FINAL STATISTICS ////////////////////
std::cout << " " << std::endl;
std::cout << "************* STATISTICS **************" << std::endl;
std::cout << " Events Studied " << read_events << std::endl;
std::cout << "Timing info:" << std::endl;
std::cout << "CPU time usage -- calibrating: " << cpu_time_used << " sec." << std::endl;
/////////////////////////////////////////////////////////////////////////////
}
DetId ElectronCalibrationUniv::findMaxHit(const std::vector<DetId>& v1,
const EBRecHitCollection* EBhits,
const EERecHitCollection* EEhits) {
//=================================================================================
double currEnergy = 0.;
DetId maxHit;
for (std::vector<DetId>::const_iterator idsIt = v1.begin(); idsIt != v1.end(); ++idsIt) {
if (idsIt->subdetId() == 1) {
EBRecHitCollection::const_iterator itrechit;
itrechit = EBhits->find(*idsIt);
if (itrechit == EBhits->end()) {
std::cout << "ElectronCalibration::findMaxHit: rechit not found! " << (EBDetId)(*idsIt) << std::endl;
continue;
}
if (itrechit->energy() > currEnergy) {
currEnergy = itrechit->energy();
maxHit = *idsIt;
}
} else {
EERecHitCollection::const_iterator itrechit;
itrechit = EEhits->find(*idsIt);
if (itrechit == EEhits->end()) {
std::cout << "ElectronCalibration::findMaxHit: rechit not found! idsIt = " << (EEDetId)(*idsIt) << std::endl;
continue;
}
if (itrechit->energy() > currEnergy) {
currEnergy = itrechit->energy();
maxHit = *idsIt;
}
}
}
return maxHit;
}
bool ElectronCalibrationUniv::TestEEvalidDetId(int crystal_ix, int crystal_iy, int iz) {
bool valid = false;
if (crystal_ix < 1 || crystal_ix > 100 || crystal_iy < 1 || crystal_iy > 100 || abs(iz) != 1) {
return valid;
}
if ((crystal_ix >= 1 && crystal_ix <= 3 && (crystal_iy <= 40 || crystal_iy > 60)) ||
(crystal_ix >= 4 && crystal_ix <= 5 && (crystal_iy <= 35 || crystal_iy > 65)) ||
(crystal_ix >= 6 && crystal_ix <= 8 && (crystal_iy <= 25 || crystal_iy > 75)) ||
(crystal_ix >= 9 && crystal_ix <= 13 && (crystal_iy <= 20 || crystal_iy > 80)) ||
(crystal_ix >= 14 && crystal_ix <= 15 && (crystal_iy <= 15 || crystal_iy > 85)) ||
(crystal_ix >= 16 && crystal_ix <= 20 && (crystal_iy <= 13 || crystal_iy > 87)) ||
(crystal_ix >= 21 && crystal_ix <= 25 && (crystal_iy <= 8 || crystal_iy > 92)) ||
(crystal_ix >= 26 && crystal_ix <= 35 && (crystal_iy <= 5 || crystal_iy > 95)) ||
(crystal_ix >= 36 && crystal_ix <= 39 && (crystal_iy <= 3 || crystal_iy > 97)) ||
(crystal_ix >= 98 && crystal_ix <= 100 && (crystal_iy <= 40 || crystal_iy > 60)) ||
(crystal_ix >= 96 && crystal_ix <= 97 && (crystal_iy <= 35 || crystal_iy > 65)) ||
(crystal_ix >= 93 && crystal_ix <= 95 && (crystal_iy <= 25 || crystal_iy > 75)) ||
(crystal_ix >= 88 && crystal_ix <= 92 && (crystal_iy <= 20 || crystal_iy > 80)) ||
(crystal_ix >= 86 && crystal_ix <= 87 && (crystal_iy <= 15 || crystal_iy > 85)) ||
(crystal_ix >= 81 && crystal_ix <= 85 && (crystal_iy <= 13 || crystal_iy > 87)) ||
(crystal_ix >= 76 && crystal_ix <= 80 && (crystal_iy <= 8 || crystal_iy > 92)) ||
(crystal_ix >= 66 && crystal_ix <= 75 && (crystal_iy <= 5 || crystal_iy > 95)) ||
(crystal_ix >= 62 && crystal_ix <= 65 && (crystal_iy <= 3 || crystal_iy > 97)) ||
((crystal_ix == 40 || crystal_ix == 61) &&
((crystal_iy >= 46 && crystal_iy <= 55) || crystal_iy <= 3 || crystal_iy > 97)) ||
((crystal_ix == 41 || crystal_ix == 60) && crystal_iy >= 44 && crystal_iy <= 57) ||
((crystal_ix == 42 || crystal_ix == 59) && crystal_iy >= 43 && crystal_iy <= 58) ||
((crystal_ix == 43 || crystal_ix == 58) && crystal_iy >= 42 && crystal_iy <= 59) ||
((crystal_ix == 44 || crystal_ix == 45 || crystal_ix == 57 || crystal_ix == 56) && crystal_iy >= 41 &&
crystal_iy <= 60) ||
(crystal_ix >= 46 && crystal_ix <= 55 && crystal_iy >= 40 && crystal_iy <= 61)) {
return valid;
}
valid = true;
return valid;
}
//=================================================================================
void ElectronCalibrationUniv::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
//=================================================================================
using namespace edm;
// Get EBRecHits
edm::Handle<EBRecHitCollection> EBphits;
iEvent.getByToken(ebRecHitToken_, EBphits);
if (!EBphits.isValid()) {
std::cerr << "Error! can't get the product EBRecHitCollection: " << std::endl;
}
const EBRecHitCollection* EBhits = EBphits.product(); // get a ptr to the product
// Get EERecHits
edm::Handle<EERecHitCollection> EEphits;
iEvent.getByToken(eeRecHitToken_, EEphits);
if (!EEphits.isValid()) {
std::cerr << "Error! can't get the product EERecHitCollection: " << std::endl;
}
const EERecHitCollection* EEhits = EEphits.product(); // get a ptr to the product
// Get pixelElectrons
edm::Handle<reco::GsfElectronCollection> pElectrons;
iEvent.getByToken(gsfElectronToken_, pElectrons);
if (!pElectrons.isValid()) {
std::cerr << "Error! can't get the product ElectronCollection: " << std::endl;
}
const reco::GsfElectronCollection* electronCollection = pElectrons.product();
read_events++;
if (read_events % 1000 == 0)
std::cout << "read_events = " << read_events << std::endl;
EventsAfterCuts->Fill(1);
if (!EBhits || !EEhits)
return;
EventsAfterCuts->Fill(2);
if (EBhits->empty() && EEhits->empty())
return;
EventsAfterCuts->Fill(3);
if (!electronCollection)
return;
EventsAfterCuts->Fill(4);
if (electronCollection->empty())
return;
// ////////////////Need to recalibrate the events (copy code from EcalRecHitRecalib):
////////////////////////////////////////////////////////////////////////////////////////
/// START HERE....
///////////////////////////////////////////////////////////////////////////////////////
reco::GsfElectronCollection::const_iterator eleIt = electronCollection->begin();
reco::GsfElectron highPtElectron;
float highestElePt = 0.;
bool found = false;
for (eleIt = electronCollection->begin(); eleIt != electronCollection->end(); eleIt++) {
if (fabs(eleIt->eta()) > 2.4)
continue;
// if(eleIt->eta()<0.0) continue;
if (eleIt->pt() > highestElePt) {
highestElePt = eleIt->pt();
highPtElectron = *eleIt;
found = true;
// std::cout<<" eleIt->pt( "<<eleIt->pt()<<" eleIt->eta() "<<eleIt->eta()<<std::endl;
}
}
EventsAfterCuts->Fill(5);
if (!found)
return;
const reco::SuperCluster& sc = *(highPtElectron.superCluster());
// if(fabs(sc.eta())>1.479){std::cout<<" SC not in Barrel "<<sc.eta()<<std::endl;;}
// const std::vector<DetId> & v1 = sc.getHitsByDetId();
std::vector<DetId> v1;
//Loop to fill the vector of DetIds
for (std::vector<std::pair<DetId, float> >::const_iterator idsIt = sc.hitsAndFractions().begin();
idsIt != sc.hitsAndFractions().end();
++idsIt) {
v1.push_back(idsIt->first);
}
DetId maxHitId;
maxHitId = findMaxHit(v1, (EBhits), (EEhits));
//maxHitId = findMaxHit(v1,EBhits,EEhits);
EventsAfterCuts->Fill(6);
if (maxHitId.null()) {
std::cout << " Null " << std::endl;
return;
}
int maxCC_Eta = 0;
int maxCC_Phi = 0;
int Zside = 0;
if (maxHitId.subdetId() != 1) {
maxCC_Eta = ((EEDetId)maxHitId).ix();
maxCC_Phi = ((EEDetId)maxHitId).iy();
Zside = ((EEDetId)maxHitId).zside();
// std::cout<<" ++++++++ Zside "<<Zside<<std::endl;
} else {
maxCC_Eta = ((EBDetId)maxHitId).ieta();
maxCC_Phi = ((EBDetId)maxHitId).iphi();
}
// if(maxCC_Eta>maxeta_ ) ;
// if(maxCC_Eta<mineta_ ) ;
// number of events per crystal is set
// eventcrystal[maxCC_Eta][maxCC_Phi]+=1;
// if(eventcrystal[maxCC_Eta][maxCC_Phi] > numevent_) ;
// fill cluster energy
std::vector<float> energy;
float energy3x3 = 0.;
float energy5x5 = 0.;
//Should be moved to cfg file!
int ClusterSize = clusterSize_;
const CaloSubdetectorTopology* topology = theCaloTopology_->getSubdetectorTopology(DetId::Ecal, maxHitId.subdetId());
std::vector<DetId> NxNaroundMax = topology->getWindow(maxHitId, ClusterSize, ClusterSize);
//ToCompute 3x3
std::vector<DetId> S9aroundMax = topology->getWindow(maxHitId, 3, 3);
EventsAfterCuts->Fill(7);
if ((int)NxNaroundMax.size() != ClusterSize * ClusterSize)
return;
EventsAfterCuts->Fill(8);
if (S9aroundMax.size() != 9)
return;
// std::cout<<" ******** New Event "<<std::endl;
EventsAfterCuts->Fill(9);
for (int icry = 0; icry < ClusterSize * ClusterSize; icry++) {
if (NxNaroundMax[icry].subdetId() == EcalBarrel) {
EBRecHitCollection::const_iterator itrechit;
itrechit = EBhits->find(NxNaroundMax[icry]);
if (itrechit == EBhits->end()) {
// std::cout << "EB DetId not in e25" << std::endl;
energy.push_back(0.);
energy5x5 += 0.;
continue;
}
if (edm::isNotFinite(itrechit->energy())) {
std::cout << " nan energy " << std::endl;
return;
}
energy.push_back(itrechit->energy());
energy5x5 += itrechit->energy();
//Summing in 3x3 to cut later on:
for (int tt = 0; tt < 9; tt++) {
if (NxNaroundMax[icry] == S9aroundMax[tt])
energy3x3 += itrechit->energy();
}
} else {
EERecHitCollection::const_iterator itrechit;
itrechit = EEhits->find(NxNaroundMax[icry]);
if (itrechit == EEhits->end()) {
// std::cout << "EE DetId not in e25" << std::endl;
// std::cout<<" ******** putting 0 "<<std::endl;
energy.push_back(0.);
energy5x5 += 0.;
continue;
}
if (edm::isNotFinite(itrechit->energy())) {
std::cout << " nan energy " << std::endl;
return;
}
energy.push_back(itrechit->energy());
energy5x5 += itrechit->energy();
//Summing in 3x3 to cut later on:
for (int tt = 0; tt < 9; tt++) {
if (NxNaroundMax[icry] == S9aroundMax[tt])
energy3x3 += itrechit->energy();
}
}
}
// if((read_events-50)%10000 ==0)cout << "++++++++++++ENERGY 5x5 " << energy5x5 << std::endl;
EventsAfterCuts->Fill(10);
// std::cout<<" ******** NxNaroundMax.size() "<<NxNaroundMax.size()<<std::endl;
// std::cout<<" ******** energy.size() "<<energy.size()<<std::endl;
if ((int)energy.size() != ClusterSize * ClusterSize)
return;
if (maxHitId.subdetId() == EcalBarrel) {
GeneralMapBeforePt->Fill(maxCC_Eta, maxCC_Phi);
} else {
if (Zside < 0) {
GeneralMapEndCapMinusBeforePt->Fill(maxCC_Eta, maxCC_Phi);
} else {
GeneralMapEndCapPlusBeforePt->Fill(maxCC_Eta, maxCC_Phi);
}
}
EventsAfterCuts->Fill(11);
if (highestElePt < elePt_)
return;
if (maxHitId.subdetId() == EcalBarrel) {
GeneralMap->Fill(maxCC_Eta, maxCC_Phi);
} else {
if (Zside < 0) {
GeneralMapEndCapMinus->Fill(maxCC_Eta, maxCC_Phi);
} else {
GeneralMapEndCapPlus->Fill(maxCC_Eta, maxCC_Phi);
}
}
EventsAfterCuts->Fill(12);
if (highPtElectron.classification() != elecclass_ && elecclass_ != -1)
return;
float Ptrack_in =
sqrt(pow(highPtElectron.trackMomentumAtVtx().X(), 2) + pow(highPtElectron.trackMomentumAtVtx().Y(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Z(), 2));
float UncorrectedPatCalo =
sqrt(pow(highPtElectron.trackMomentumAtCalo().X(), 2) + pow(highPtElectron.trackMomentumAtCalo().Y(), 2) +
pow(highPtElectron.trackMomentumAtCalo().Z(), 2));
float Ptrack_out =
sqrt(pow(highPtElectron.trackMomentumOut().X(), 2) + pow(highPtElectron.trackMomentumOut().Y(), 2) +
pow(highPtElectron.trackMomentumOut().Z(), 2));
e9NoCuts->Fill(energy3x3);
e25NoCuts->Fill(energy5x5);
e9Overe25NoCuts->Fill(energy3x3 / energy5x5);
scENoCuts->Fill(sc.energy());
trPNoCuts->Fill(UncorrectedPatCalo);
EoPNoCuts->Fill(highPtElectron.eSuperClusterOverP());
e25OverScENoCuts->Fill(energy5x5 / sc.energy());
E25oPNoCuts->Fill(energy5x5 / UncorrectedPatCalo);
PinOverPoutNoCuts->Fill(
sqrt(pow(highPtElectron.trackMomentumAtVtx().X(), 2) + pow(highPtElectron.trackMomentumAtVtx().Y(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Z(), 2)) /
sqrt(pow(highPtElectron.trackMomentumOut().X(), 2) + pow(highPtElectron.trackMomentumOut().Y(), 2) +
pow(highPtElectron.trackMomentumOut().Z(), 2)));
eSeedOverPoutNoCuts->Fill(highPtElectron.eSuperClusterOverP());
MapCor1NoCuts->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / Ptrack_in);
MapCor2NoCuts->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSuperClusterOverP());
MapCor3NoCuts->Fill(energy5x5 / UncorrectedPatCalo, Ptrack_out / Ptrack_in);
MapCor4NoCuts->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / highPtElectron.p());
MapCor5NoCuts->Fill(energy5x5 / UncorrectedPatCalo, UncorrectedPatCalo / Ptrack_out);
MapCor6NoCuts->Fill(Ptrack_out / Ptrack_in, energy5x5 / Ptrack_in);
MapCor7NoCuts->Fill(Ptrack_out / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor8NoCuts->Fill(energy5x5 / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor9NoCuts->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSeedClusterOverPout());
MapCor10NoCuts->Fill(highPtElectron.eSeedClusterOverPout(), Ptrack_out / Ptrack_in);
MapCor11NoCuts->Fill(highPtElectron.eSeedClusterOverPout(), energy5x5 / Ptrack_in);
PinMinPoutNoCuts->Fill((Ptrack_in - Ptrack_out) / Ptrack_in);
Error1NoCuts->Fill(highPtElectron.trackMomentumError() / Ptrack_in);
Error2NoCuts->Fill(highPtElectron.trackMomentumError() / Ptrack_out);
Error3NoCuts->Fill(highPtElectron.trackMomentumError() / UncorrectedPatCalo);
eSeedOverPout2NoCuts->Fill(highPtElectron.eSeedClusterOverPout());
hadOverEmNoCuts->Fill(highPtElectron.hadronicOverEm());
//Cuts!
if ((energy3x3 / energy5x5) < cut1_)
return;
if ((Ptrack_out / Ptrack_in) < cut2_ || (Ptrack_out / Ptrack_in) > cut3_)
return;
if ((energy5x5 / Ptrack_in) < cutEPin1_ || (energy5x5 / Ptrack_in) > cutEPin2_)
return;
// if(!highPtElectron.ecalDriven())return;
// if(!highPtElectron.passingCutBasedPreselection())return;
// // Apply Pietro cuts:
// EventsAfterCuts->Fill(13);
// //Module 1
// if(maxHitId.subdetId() == EcalBarrel){
// //Module 1
// if(maxCC_Eta <= 25){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.4 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// //Module 2
// if( maxCC_Eta > 25&& maxCC_Eta <= 45){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.25 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// //Module 3
// if( maxCC_Eta > 45&& maxCC_Eta <= 65){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }else{
// if( maxCC_Eta > 65&& maxCC_Eta <= 85){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }else{
// return;
// }
// }
// }
// }
// }else{
// //EndCapMinus Side:
// //EndCapPlus Side:
// int iR = sqrt((maxCC_Eta-50)*(maxCC_Eta-50) + (maxCC_Phi-50)*(maxCC_Phi-50));
// if( iR >= 22&& iR < 27){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// if( iR >= 27&& iR < 32){
// if(highPtElectron.eSuperClusterOverP()>1.1 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.25 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// if( iR >= 32&& iR < 37){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.2)return ;
// }else{
// if( iR >= 37&& iR < 42){
// if(highPtElectron.eSuperClusterOverP()>1.1 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }else{
// if( iR >= 42){
// if(highPtElectron.eSuperClusterOverP()>1.05 || highPtElectron.eSuperClusterOverP()<0.95)return ;
// if(highPtElectron.eSeedClusterOverPout()>1.15 || highPtElectron.eSeedClusterOverPout()<0.90)return ;
// if((Ptrack_in- Ptrack_out) / Ptrack_in <-0.05 || (Ptrack_in- Ptrack_out) / Ptrack_in >0.15)return ;
// }
// }
// }
// }
// }
// }
if (maxHitId.subdetId() == EcalBarrel) {
E25oPvsEta->Fill(maxCC_Eta, energy5x5 / UncorrectedPatCalo);
} else {
float Radius = sqrt((maxCC_Eta) * (maxCC_Eta) + (maxCC_Phi) * (maxCC_Phi));
if (Zside < 0) {
E25oPvsEtaEndCapMinus->Fill(Radius, energy5x5 / UncorrectedPatCalo);
} else {
E25oPvsEtaEndCapPlus->Fill(Radius, energy5x5 / UncorrectedPatCalo);
}
}
e9->Fill(energy3x3);
e25->Fill(energy5x5);
e9Overe25->Fill(energy3x3 / energy5x5);
scE->Fill(sc.energy());
trP->Fill(UncorrectedPatCalo);
EoP->Fill(highPtElectron.eSuperClusterOverP());
e25OverScE->Fill(energy5x5 / sc.energy());
E25oP->Fill(energy5x5 / UncorrectedPatCalo);
if (maxHitId.subdetId() == EcalBarrel) {
Map->Fill(maxCC_Eta, maxCC_Phi);
} else {
if (Zside < 0) {
MapEndCapMinus->Fill(maxCC_Eta, maxCC_Phi);
} else {
MapEndCapPlus->Fill(maxCC_Eta, maxCC_Phi);
}
}
PinOverPout->Fill(sqrt(pow(highPtElectron.trackMomentumAtVtx().X(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Y(), 2) +
pow(highPtElectron.trackMomentumAtVtx().Z(), 2)) /
sqrt(pow(highPtElectron.trackMomentumOut().X(), 2) + pow(highPtElectron.trackMomentumOut().Y(), 2) +
pow(highPtElectron.trackMomentumOut().Z(), 2)));
eSeedOverPout->Fill(highPtElectron.eSuperClusterOverP());
MapCor1->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / Ptrack_in);
MapCor2->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSuperClusterOverP());
MapCor3->Fill(energy5x5 / UncorrectedPatCalo, Ptrack_out / Ptrack_in);
MapCor4->Fill(energy5x5 / UncorrectedPatCalo, energy5x5 / highPtElectron.p());
MapCor5->Fill(energy5x5 / UncorrectedPatCalo, UncorrectedPatCalo / Ptrack_out);
MapCor6->Fill(Ptrack_out / Ptrack_in, energy5x5 / Ptrack_in);
MapCor7->Fill(Ptrack_out / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor8->Fill(energy5x5 / Ptrack_in, UncorrectedPatCalo / Ptrack_out);
MapCor9->Fill(energy5x5 / UncorrectedPatCalo, highPtElectron.eSeedClusterOverPout());
MapCor10->Fill(highPtElectron.eSeedClusterOverPout(), Ptrack_out / Ptrack_in);
MapCor11->Fill(highPtElectron.eSeedClusterOverPout(), energy5x5 / Ptrack_in);
PinMinPout->Fill((Ptrack_in - Ptrack_out) / Ptrack_in);
Error1->Fill(highPtElectron.trackMomentumError() / Ptrack_in);
Error2->Fill(highPtElectron.trackMomentumError() / Ptrack_out);
Error3->Fill(highPtElectron.trackMomentumError() / UncorrectedPatCalo);
eSeedOverPout2->Fill(highPtElectron.eSeedClusterOverPout());
hadOverEm->Fill(highPtElectron.hadronicOverEm());
UnivEventIds.push_back(NxNaroundMax);
EventMatrix.push_back(energy);
EnergyVector.push_back(UncorrectedPatCalo);
EventsAfterCuts->Fill(14);
if (!highPtElectron.ecalDrivenSeed())
EventsAfterCuts->Fill(15);
return;
}
DEFINE_FWK_MODULE(ElectronCalibrationUniv);
| 44.091965 | 166 | 0.629855 | malbouis |
4b4a53a88a31216c53148baa1ab0b86d8d60022f | 14,142 | cpp | C++ | src/client/client/Command_Client_Engine.cpp | Kuga23/Projet-M2 | 85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433 | [
"MIT"
] | null | null | null | src/client/client/Command_Client_Engine.cpp | Kuga23/Projet-M2 | 85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433 | [
"MIT"
] | null | null | null | src/client/client/Command_Client_Engine.cpp | Kuga23/Projet-M2 | 85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433 | [
"MIT"
] | null | null | null | #include <iostream>
#include <functional>
#include <unistd.h>
#include "Command_Client_Engine.h"
#include "state.h"
#include "render.h"
#include "engine.h"
using namespace client;
using namespace render;
using namespace engine;
using namespace state;
using namespace std;
Command_Client_Engine::Command_Client_Engine() {
}
Command_Client_Engine::~Command_Client_Engine(){
}
void Command_Client_Engine::execute() {
cout << "TEST ENGINE" << endl;
Engine engine;
engine.getState().setMode("engine");
engine.getState().initPlayers();
engine.getState().initCharacters();
engine.getState().initMapCell();
cout << " INIT DONE" << endl;
sf::RenderWindow window(sf::VideoMode(32 * 26 + 500, 32 * 24), "Zorglub");
StateLayer stateLayer(engine.getState(), window);
stateLayer.initTextureArea(engine.getState());
StateLayer *ptr_stateLayer = &stateLayer;
engine.getState().registerObserver(ptr_stateLayer);
bool booting = true;
bool firstround = true;
bool secondroun = false;
bool thirdround = false;
bool fourround = false;
bool fiveround = false;
bool sixround = false;
int p1X;
int p1Y;
int p2X;
int p2Y;
int priority;
// hard code health bc its loong either wise
engine.getState().getListCharacters(0)[0]->setNewHealth(25);
engine.getState().getListCharacters(0)[0]->setPrecision(15, 15, 15, 15);// precision to 1
engine.getState().getListCharacters(0)[0]->setDodge(8, 8);// set dodge to 0
engine.getState().getListCharacters(1)[0]->setNewHealth(25);
engine.getState().getListCharacters(1)[0]->setPrecision(15, 15, 15, 15);// precision to 1
engine.getState().getListCharacters(1)[0]->setDodge(8, 8);// set dodge to 0
engine.getState().getListCharacters(1)[0]->getCharWeap()->setTypeCapab(TELEPORT); // Teleport Capacity
while (window.isOpen()) {
sf::Event event;
if (booting) {
stateLayer.draw(window);
booting = false;
}
while (1) {
if (firstround) {
p1X = engine.getState().getListCharacters(0)[0]->getPosition().getX();
p1Y = engine.getState().getListCharacters(0)[0]->getPosition().getY();
int priority = 0;
cout << "[Player 1] Character pos( " << engine.getState().getListCharacters(0)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(0)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p1X, ++p1Y};
unique_ptr <engine::Command> ptr_mc1(
new engine::Move_Command(*engine.getState().getListCharacters(0)[0], pos1));
engine.addCommand(move(ptr_mc1), priority++);
cout << "MOVE FROM pos(" << p1X << "," << p1Y << ")" << " TO " << "(" << p1X << "," << p1Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(0)[0]->getMovementLeft() == 0) {
engine.getState().setCurAction(ATTACKING); // Hard set Attacking mode
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
firstround = false;
secondroun = true;
}
engine.update();
}
if (secondroun) {
engine.getState().setCurAction(IDLE);
//Player 2
p2X = engine.getState().getListCharacters(1)[0]->getPosition().getX();
p2Y = engine.getState().getListCharacters(1)[0]->getPosition().getY();
priority = 0;
cout << "[Player 2] Character pos( " << engine.getState().getListCharacters(1)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(1)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p2X, --p2Y};
unique_ptr <engine::Command> ptr_mc2(
new engine::Move_Command(*engine.getState().getListCharacters(1)[0], pos1));
engine.addCommand(move(ptr_mc2), priority++);
cout << "MOVE FROM pos(" << p2X << "," << p2Y << ")" << " TO " << "(" << p2X << "," << p2Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(1)[0]->getMovementLeft() == 0) {
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
secondroun = false;
thirdround = true;
}
engine.update();
}
if (thirdround) {
engine.getState().setCurAction(IDLE);
p1X = engine.getState().getListCharacters(0)[0]->getPosition().getX();
p1Y = engine.getState().getListCharacters(0)[0]->getPosition().getY();
int priority = 0;
cout << "[Player 1] Character pos( " << engine.getState().getListCharacters(0)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(0)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p1X, ++p1Y};
unique_ptr <engine::Command> ptr_mc1(
new engine::Move_Command(*engine.getState().getListCharacters(0)[0], pos1));
engine.addCommand(move(ptr_mc1), priority++);
cout << "MOVE FROM pos(" << p1X << "," << p1Y << ")" << " TO " << "(" << p1X << "," << p1Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(0)[0]->getMovementLeft() == 0) {
engine.getState().setCurAction(ATTACKING); // Hard set Attacking mode
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
thirdround = false;
fourround = true;
}
engine.update();
}
if (fourround) {
engine.getState().setCurAction(IDLE);
//Player 2
p2X = engine.getState().getListCharacters(1)[0]->getPosition().getX();
p2Y = engine.getState().getListCharacters(1)[0]->getPosition().getY();
priority = 0;
cout << "[Player 2] Character pos( " << engine.getState().getListCharacters(1)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(1)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(MOVING); // hard change the sate cur action
Position pos1{p2X, --p2Y};
unique_ptr <engine::Command> ptr_mc2(
new engine::Move_Command(*engine.getState().getListCharacters(1)[0], pos1));
engine.addCommand(move(ptr_mc2), priority++);
cout << "MOVE FROM pos(" << p2X << "," << p2Y << ")" << " TO " << "(" << p2X << "," << p2Y + 1 << ")"
<< endl;
if (engine.getState().getListCharacters(1)[0]->getMovementLeft() == 3) { // has reach attack range
// ==3 because the update isn't done yet
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ac2(
new engine::Attack_Command(*engine.getState().getListCharacters(1)[0],
*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_ac2), priority++);
cout << "ATTACKED";
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
fourround = false;
fiveround = true;
}
engine.update();
}
if (fiveround) {
engine.getState().setCurAction(IDLE);
p1X = engine.getState().getListCharacters(0)[0]->getPosition().getX();
p1Y = engine.getState().getListCharacters(0)[0]->getPosition().getY();
int priority = 0;
cout << "[Player 1] Character pos( " << engine.getState().getListCharacters(0)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(0)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ac1(
new engine::Attack_Command(*engine.getState().getListCharacters(0)[0],
*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_ac1), priority++);
cout << "ATTACKED";
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
fiveround = false;
sixround = true;
engine.update();
}
if (sixround) {
engine.getState().setCurAction(IDLE);
//Player 2
p2X = engine.getState().getListCharacters(1)[0]->getPosition().getX();
p2Y = engine.getState().getListCharacters(1)[0]->getPosition().getY();
priority = 0;
cout << "[Player 2] Character pos( " << engine.getState().getListCharacters(1)[0]->getPosition().getX()
<< " " << engine.getState().getListCharacters(1)[0]->getPosition().getY() << endl;
unique_ptr <engine::Command> ptr_sc(
new engine::Sel_Char_Command(*engine.getState().getListCharacters(1)[0]));
engine.addCommand(move(ptr_sc), priority++);
//cout<< "The First Plyaer Character has been Selected: Sel_Char_Command"<<endl;
Position posTeleport{p2X - 2, p2Y - 2};
unique_ptr <engine::Command> ptr_cap(
new engine::Capab_Command(*engine.getState().getListCharacters(1)[0],
*engine.getState().getListCharacters(0)[0], posTeleport));
engine.addCommand(move(ptr_cap), priority++);
cout << "TELEPORTING" << endl;
usleep(1000000);
engine.getState().setCurAction(ATTACKING);// Show the attack range
cout << "STATE IN ATTACING MODE: SHOW ATTACK RANGE" << endl;
unique_ptr <engine::Command> ptr_ac2(
new engine::Attack_Command(*engine.getState().getListCharacters(1)[0],
*engine.getState().getListCharacters(0)[0]));
engine.addCommand(move(ptr_ac2), priority++);
cout << "ATTACKED";
unique_ptr <engine::Command> ptr_ftc(new engine::Finish_Turn_Command());
engine.addCommand(move(ptr_ftc), priority++);
cout << "FINISHING TURN" << endl;
sixround = false;
engine.update();
}
window.pollEvent(event);
if (event.type == sf::Event::Closed)
window.close();
}
}
} | 47.14 | 119 | 0.534366 | Kuga23 |
4b4a849a3095755fca6a4b889b518508f7977745 | 62,983 | cxx | C++ | Plugins/GenericIOReader/Readers/LANL/GIO/GenericIO.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-07-21T07:15:44.000Z | 2021-07-21T07:15:44.000Z | Plugins/GenericIOReader/Readers/LANL/GIO/GenericIO.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/GenericIOReader/Readers/LANL/GIO/GenericIO.cxx | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-03-13T03:35:01.000Z | 2021-03-13T03:35:01.000Z | /*
* Copyright (C) 2015, UChicago Argonne, LLC
* All Rights Reserved
*
* Generic IO (ANL-15-066)
* Hal Finkel, Argonne National Laboratory
*
* OPEN SOURCE LICENSE
*
* Under the terms of Contract No. DE-AC02-06CH11357 with UChicago Argonne,
* LLC, the U.S. Government retains certain rights in this software.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the names of UChicago Argonne, LLC or the Department of Energy
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* *****************************************************************************
*
* DISCLAIMER
* THE SOFTWARE IS SUPPLIED “AS IS” WITHOUT WARRANTY OF ANY KIND. NEITHER THE
* UNTED STATES GOVERNMENT, NOR THE UNITED STATES DEPARTMENT OF ENERGY, NOR
* UCHICAGO ARGONNE, LLC, NOR ANY OF THEIR EMPLOYEES, MAKES ANY WARRANTY,
* EXPRESS OR IMPLIED, OR ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE
* ACCURACY, COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, DATA, APPARATUS,
* PRODUCT, OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE
* PRIVATELY OWNED RIGHTS.
*
* *****************************************************************************
*/
#define _XOPEN_SOURCE 600
#include "GenericIO.h"
#include "CRC64.h"
#ifndef LANL_GENERICIO_NO_COMPRESSION
extern "C" {
#include "blosc.h"
}
#endif
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <fstream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#ifndef LANL_GENERICIO_NO_MPI
#include <ctime>
#else
#include <time.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef __bgq__
#include <mpix.h>
#endif
namespace lanl
{
#ifndef MPI_UINT64_T
#define MPI_UINT64_T (sizeof(long) == 8 ? MPI_LONG : MPI_LONG_LONG)
#endif
#ifdef _WIN32
#include <Windows.h>
#include <io.h>
#include <stdio.h>
#define S_IRUSR _S_IREAD
#define S_IWUSR _S_IWRITE
#include <direct.h>
#define mkdir(a, b) _mkdir((a))
typedef long long ssize_t;
// Windows-specific functions
void usleep(int waitTime);
int ftruncate(unsigned int fd, size_t size);
int pread(unsigned int fd, void* buf, size_t count, int offset);
int pwrite(unsigned int fd, const void* buf, size_t count, int offset);
void usleep(int waitTime)
{
__int64 time1 = 0, time2 = 0, sysFreq = 0;
QueryPerformanceCounter((LARGE_INTEGER*)&time1);
QueryPerformanceFrequency((LARGE_INTEGER*)&sysFreq);
do
{
QueryPerformanceCounter((LARGE_INTEGER*)&time2);
} while ((time2 - time1) < waitTime);
}
// Convert a POSIX ftruncate to a windows system chsize
int ftruncate(unsigned int fd, size_t size)
{
return _chsize(fd, static_cast<long>(size));
}
// Convert a POSIX read to a windows system read
int pread(unsigned int fd, void* buf, size_t count, int offset)
{
if (_lseek(fd, offset, SEEK_SET) != offset)
return -1;
return _read(fd, (char*)buf, static_cast<unsigned int>(count));
}
// Convert a POSIX write to a windows system write
int pwrite(unsigned int fd, const void* buf, size_t count, int offset)
{
if (_lseek(fd, offset, SEEK_SET) != offset)
return -1;
return _write(fd, (char*)buf, static_cast<unsigned int>(count));
}
#endif
using namespace std;
namespace gio
{
#ifndef LANL_GENERICIO_NO_MPI
GenericFileIO_MPI::~GenericFileIO_MPI()
{
(void)MPI_File_close(&FH);
}
void GenericFileIO_MPI::open(const std::string& FN, bool ForReading)
{
FileName = FN;
int amode = ForReading ? MPI_MODE_RDONLY : (MPI_MODE_WRONLY | MPI_MODE_CREATE);
if (MPI_File_open(Comm, const_cast<char*>(FileName.c_str()), amode, MPI_INFO_NULL, &FH) !=
MPI_SUCCESS)
throw runtime_error(
(!ForReading ? "Unable to create the file: " : "Unable to open the file: ") + FileName);
}
void GenericFileIO_MPI::setSize(size_t sz)
{
if (MPI_File_set_size(FH, sz) != MPI_SUCCESS)
throw runtime_error("Unable to set size for file: " + FileName);
}
void GenericFileIO_MPI::read(void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
MPI_Status status;
if (MPI_File_read_at(FH, offset, buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to read " + D + " from file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
}
}
void GenericFileIO_MPI::write(const void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
MPI_Status status;
if (MPI_File_write_at(FH, offset, (void*)buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to write " + D + " to file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
}
}
void GenericFileIO_MPICollective::read(void* buf, size_t count, off_t offset, const std::string& D)
{
int Continue = 0;
do
{
MPI_Status status;
if (MPI_File_read_at_all(FH, offset, buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to read " + D + " from file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
int NeedContinue = (count > 0);
MPI_Allreduce(&NeedContinue, &Continue, 1, MPI_INT, MPI_SUM, Comm);
} while (Continue);
}
void GenericFileIO_MPICollective::write(
const void* buf, size_t count, off_t offset, const std::string& D)
{
int Continue = 0;
do
{
MPI_Status status;
if (MPI_File_write_at_all(FH, offset, (void*)buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
throw runtime_error("Unable to write " + D + " to file: " + FileName);
int scount;
(void)MPI_Get_count(&status, MPI_BYTE, &scount);
count -= scount;
buf = ((char*)buf) + scount;
offset += scount;
int NeedContinue = (count > 0);
MPI_Allreduce(&NeedContinue, &Continue, 1, MPI_INT, MPI_SUM, Comm);
} while (Continue);
}
#endif
GenericFileIO_POSIX::~GenericFileIO_POSIX()
{
if (FH != -1)
close(FH);
}
void GenericFileIO_POSIX::open(const std::string& FN, bool ForReading)
{
FileName = FN;
errno = 0;
#ifdef _WIN32
// Windows POSIX Must explicitly define O_BINARY otherwise it defaults to text mode
int flags = ForReading ? (O_RDONLY | O_BINARY) : (O_WRONLY | O_CREAT | O_BINARY);
int mode = S_IRUSR | S_IWUSR;
if ((FH = lanl::open(FileName.c_str(), flags, mode)) == -1)
#else
int flags = ForReading ? O_RDONLY : (O_WRONLY | O_CREAT);
int mode = S_IRUSR | S_IWUSR | S_IRGRP;
if ((FH = ::open(FileName.c_str(), flags, mode)) == -1)
#endif
throw runtime_error(
(!ForReading ? "Unable to create the file: " : "Unable to open the file: ") + FileName +
": " + strerror(errno));
}
void GenericFileIO_POSIX::setSize(size_t sz)
{
if (ftruncate(FH, sz) == -1)
throw runtime_error("Unable to set size for file: " + FileName);
}
void GenericFileIO_POSIX::read(void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
ssize_t scount;
errno = 0;
if ((scount = pread(FH, buf, count, offset)) == -1)
{
if (errno == EINTR)
continue;
throw runtime_error(
"Unable to read " + D + " from file: " + FileName + ": " + strerror(errno));
}
count -= scount;
buf = ((char*)buf) + scount;
offset += static_cast<off_t>(scount);
}
}
void GenericFileIO_POSIX::write(const void* buf, size_t count, off_t offset, const std::string& D)
{
while (count > 0)
{
ssize_t scount;
errno = 0;
if ((scount = pwrite(FH, buf, count, offset)) == -1)
{
if (errno == EINTR)
continue;
throw runtime_error(
"Unable to write " + D + " to file: " + FileName + ": " + strerror(errno));
}
count -= scount;
buf = ((char*)buf) + scount;
offset += static_cast<off_t>(scount);
}
}
static bool isBigEndian()
{
const uint32_t one = 1;
return !(*((char*)(&one)));
}
static void bswap(void* v, size_t s)
{
char* p = (char*)v;
for (size_t i = 0; i < s / 2; ++i)
std::swap(p[i], p[s - (i + 1)]);
}
// Using #pragma pack here, instead of __attribute__((packed)) because xlc, at
// least as of v12.1, won't take __attribute__((packed)) on non-POD and/or
// templated types.
#pragma pack(1)
template <typename T, bool IsBigEndian>
struct endian_specific_value
{
operator T() const
{
T rvalue = value;
if (IsBigEndian != isBigEndian())
bswap(&rvalue, sizeof(T));
return rvalue;
};
endian_specific_value& operator=(T nvalue)
{
if (IsBigEndian != isBigEndian())
bswap(&nvalue, sizeof(T));
value = nvalue;
return *this;
}
endian_specific_value& operator+=(T nvalue)
{
*this = *this + nvalue;
return *this;
}
endian_specific_value& operator-=(T nvalue)
{
*this = *this - nvalue;
return *this;
}
private:
T value;
};
static const size_t CRCSize = 8;
static const size_t MagicSize = 8;
static const char* MagicBE = "HACC01B";
static const char* MagicLE = "HACC01L";
template <bool IsBigEndian>
struct GlobalHeader
{
char Magic[MagicSize];
endian_specific_value<uint64_t, IsBigEndian> HeaderSize;
endian_specific_value<uint64_t, IsBigEndian> NElems; // The global total
endian_specific_value<uint64_t, IsBigEndian> Dims[3];
endian_specific_value<uint64_t, IsBigEndian> NVars;
endian_specific_value<uint64_t, IsBigEndian> VarsSize;
endian_specific_value<uint64_t, IsBigEndian> VarsStart;
endian_specific_value<uint64_t, IsBigEndian> NRanks;
endian_specific_value<uint64_t, IsBigEndian> RanksSize;
endian_specific_value<uint64_t, IsBigEndian> RanksStart;
endian_specific_value<uint64_t, IsBigEndian> GlobalHeaderSize;
endian_specific_value<double, IsBigEndian> PhysOrigin[3];
endian_specific_value<double, IsBigEndian> PhysScale[3];
endian_specific_value<uint64_t, IsBigEndian> BlocksSize;
endian_specific_value<uint64_t, IsBigEndian> BlocksStart;
};
enum
{
FloatValue = (1 << 0),
SignedValue = (1 << 1),
ValueIsPhysCoordX = (1 << 2),
ValueIsPhysCoordY = (1 << 3),
ValueIsPhysCoordZ = (1 << 4),
ValueMaybePhysGhost = (1 << 5)
};
static const size_t NameSize = 256;
template <bool IsBigEndian>
struct VariableHeader
{
char Name[NameSize];
endian_specific_value<uint64_t, IsBigEndian> Flags;
endian_specific_value<uint64_t, IsBigEndian> Size;
};
template <bool IsBigEndian>
struct RankHeader
{
endian_specific_value<uint64_t, IsBigEndian> Coords[3];
endian_specific_value<uint64_t, IsBigEndian> NElems;
endian_specific_value<uint64_t, IsBigEndian> Start;
endian_specific_value<uint64_t, IsBigEndian> GlobalRank;
};
static const size_t FilterNameSize = 8;
static const size_t MaxFilters = 4;
template <bool IsBigEndian>
struct BlockHeader
{
char Filters[MaxFilters][FilterNameSize];
endian_specific_value<uint64_t, IsBigEndian> Start;
endian_specific_value<uint64_t, IsBigEndian> Size;
};
template <bool IsBigEndian>
struct CompressHeader
{
endian_specific_value<uint64_t, IsBigEndian> OrigCRC;
};
const char* CompressName = "BLOSC";
#pragma pack()
unsigned GenericIO::DefaultFileIOType = FileIOPOSIX;
int GenericIO::DefaultPartition = 0;
bool GenericIO::DefaultShouldCompress = false;
#ifndef LANL_GENERICIO_NO_MPI
std::size_t GenericIO::CollectiveMPIIOThreshold = 0;
#endif
static bool blosc_initialized = false;
#ifndef LANL_GENERICIO_NO_MPI
void GenericIO::write()
{
if (isBigEndian())
write<true>();
else
write<false>();
}
// Note: writing errors are not currently recoverable (one rank may fail
// while the others don't).
template <bool IsBigEndian>
void GenericIO::write()
{
const char* Magic = IsBigEndian ? MagicBE : MagicLE;
uint64_t FileSize = 0;
int NRanks, Rank;
MPI_Comm_rank(Comm, &Rank);
MPI_Comm_size(Comm, &NRanks);
#ifdef __bgq__
MPI_Barrier(Comm);
#endif
MPI_Comm_split(Comm, Partition, Rank, &SplitComm);
int SplitNRanks, SplitRank;
MPI_Comm_rank(SplitComm, &SplitRank);
MPI_Comm_size(SplitComm, &SplitNRanks);
string LocalFileName;
if (SplitNRanks != NRanks)
{
if (Rank == 0)
{
// In split mode, the specified file becomes the rank map, and the real
// data is partitioned.
vector<int> MapRank, MapPartition;
MapRank.resize(NRanks);
for (int i = 0; i < NRanks; ++i)
MapRank[i] = i;
MapPartition.resize(NRanks);
MPI_Gather(&Partition, 1, MPI_INT, &MapPartition[0], 1, MPI_INT, 0, Comm);
GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
GIO.setNumElems(NRanks);
GIO.addVariable("$rank", MapRank); /* this is for use by humans; the reading
code assumes that the partitions are in
rank order */
GIO.addVariable("$partition", MapPartition);
vector<int> CX, CY, CZ;
int TopoStatus;
MPI_Topo_test(Comm, &TopoStatus);
if (TopoStatus == MPI_CART)
{
CX.resize(NRanks);
CY.resize(NRanks);
CZ.resize(NRanks);
for (int i = 0; i < NRanks; ++i)
{
int C[3];
MPI_Cart_coords(Comm, i, 3, C);
CX[i] = C[0];
CY[i] = C[1];
CZ[i] = C[2];
}
GIO.addVariable("$x", CX);
GIO.addVariable("$y", CY);
GIO.addVariable("$z", CZ);
}
GIO.write();
}
else
{
MPI_Gather(&Partition, 1, MPI_INT, 0, 0, MPI_INT, 0, Comm);
}
stringstream ss;
ss << FileName << "#" << Partition;
LocalFileName = ss.str();
}
else
{
LocalFileName = FileName;
}
RankHeader<IsBigEndian> RHLocal;
int Dims[3], Periods[3], Coords[3];
int TopoStatus;
MPI_Topo_test(Comm, &TopoStatus);
if (TopoStatus == MPI_CART)
{
MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
}
else
{
Dims[0] = NRanks;
std::fill(Dims + 1, Dims + 3, 1);
std::fill(Periods, Periods + 3, 0);
Coords[0] = Rank;
std::fill(Coords + 1, Coords + 3, 0);
}
std::copy(Coords, Coords + 3, RHLocal.Coords);
RHLocal.NElems = NElems;
RHLocal.Start = 0;
RHLocal.GlobalRank = Rank;
bool ShouldCompress = DefaultShouldCompress;
const char* EnvStr = getenv("GENERICIO_COMPRESS");
if (EnvStr)
{
int Mod = atoi(EnvStr);
ShouldCompress = (Mod > 0);
}
bool NeedsBlockHeaders = ShouldCompress;
EnvStr = getenv("GENERICIO_FORCE_BLOCKS");
if (!NeedsBlockHeaders && EnvStr)
{
int Mod = atoi(EnvStr);
NeedsBlockHeaders = (Mod > 0);
}
vector<BlockHeader<IsBigEndian> > LocalBlockHeaders;
vector<void*> LocalData;
vector<bool> LocalHasExtraSpace;
vector<vector<unsigned char> > LocalCData;
if (NeedsBlockHeaders)
{
LocalBlockHeaders.resize(Vars.size());
LocalData.resize(Vars.size());
LocalHasExtraSpace.resize(Vars.size());
if (ShouldCompress)
LocalCData.resize(Vars.size());
for (size_t i = 0; i < Vars.size(); ++i)
{
// Filters null by default, leave null starting address (needs to be
// calculated by the header-writing rank).
memset(&LocalBlockHeaders[i], 0, sizeof(BlockHeader<IsBigEndian>));
if (ShouldCompress)
{
LocalCData[i].resize(sizeof(CompressHeader<IsBigEndian>));
CompressHeader<IsBigEndian>* CH = (CompressHeader<IsBigEndian>*)&LocalCData[i][0];
CH->OrigCRC = crc64_omp(Vars[i].Data, Vars[i].Size * NElems);
#ifndef LANL_GENERICIO_NO_COMPRESSION
#ifdef _OPENMP
#pragma omp master
{
#endif
if (!blosc_initialized)
{
blosc_init();
blosc_initialized = true;
}
#ifdef _OPENMP
blosc_set_nthreads(omp_get_max_threads());
}
#endif
LocalCData[i].resize(LocalCData[i].size() + NElems * Vars[i].Size);
if (blosc_compress(9, 1, Vars[i].Size, NElems * Vars[i].Size, Vars[i].Data,
&LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>), NElems * Vars[i].Size) <= 0)
goto nocomp;
strncpy(LocalBlockHeaders[i].Filters[0], CompressName, FilterNameSize);
size_t CNBytes, CCBytes, CBlockSize;
blosc_cbuffer_sizes(
&LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>), &CNBytes, &CCBytes, &CBlockSize);
LocalCData[i].resize(CCBytes + sizeof(CompressHeader<IsBigEndian>));
LocalBlockHeaders[i].Size = LocalCData[i].size();
LocalCData[i].resize(LocalCData[i].size() + CRCSize);
LocalData[i] = &LocalCData[i][0];
LocalHasExtraSpace[i] = true;
#endif // LANL_GENERICIO_NO_COMPRESSION
}
else
{
nocomp:
LocalBlockHeaders[i].Size = NElems * Vars[i].Size;
LocalData[i] = Vars[i].Data;
LocalHasExtraSpace[i] = Vars[i].HasExtraSpace;
}
}
}
double StartTime = MPI_Wtime();
if (SplitRank == 0)
{
uint64_t HeaderSize = sizeof(GlobalHeader<IsBigEndian>) +
Vars.size() * sizeof(VariableHeader<IsBigEndian>) +
SplitNRanks * sizeof(RankHeader<IsBigEndian>) + CRCSize;
if (NeedsBlockHeaders)
HeaderSize += SplitNRanks * Vars.size() * sizeof(BlockHeader<IsBigEndian>);
vector<char> Header(HeaderSize, 0);
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&Header[0];
std::copy(Magic, Magic + MagicSize, GH->Magic);
GH->HeaderSize = HeaderSize - CRCSize;
GH->NElems = NElems; // This will be updated later
std::copy(Dims, Dims + 3, GH->Dims);
GH->NVars = Vars.size();
GH->VarsSize = sizeof(VariableHeader<IsBigEndian>);
GH->VarsStart = sizeof(GlobalHeader<IsBigEndian>);
GH->NRanks = SplitNRanks;
GH->RanksSize = sizeof(RankHeader<IsBigEndian>);
GH->RanksStart = GH->VarsStart + Vars.size() * sizeof(VariableHeader<IsBigEndian>);
GH->GlobalHeaderSize = sizeof(GlobalHeader<IsBigEndian>);
std::copy(PhysOrigin, PhysOrigin + 3, GH->PhysOrigin);
std::copy(PhysScale, PhysScale + 3, GH->PhysScale);
if (!NeedsBlockHeaders)
{
GH->BlocksSize = GH->BlocksStart = 0;
}
else
{
GH->BlocksSize = sizeof(BlockHeader<IsBigEndian>);
GH->BlocksStart = GH->RanksStart + SplitNRanks * sizeof(RankHeader<IsBigEndian>);
}
uint64_t RecordSize = 0;
VariableHeader<IsBigEndian>* VH = (VariableHeader<IsBigEndian>*)&Header[GH->VarsStart];
for (size_t i = 0; i < Vars.size(); ++i, ++VH)
{
string VName(Vars[i].Name);
VName.resize(NameSize);
std::copy(VName.begin(), VName.end(), VH->Name);
uint64_t VFlags = 0;
if (Vars[i].IsFloat)
VFlags |= FloatValue;
if (Vars[i].IsSigned)
VFlags |= SignedValue;
if (Vars[i].IsPhysCoordX)
VFlags |= ValueIsPhysCoordX;
if (Vars[i].IsPhysCoordY)
VFlags |= ValueIsPhysCoordY;
if (Vars[i].IsPhysCoordZ)
VFlags |= ValueIsPhysCoordZ;
if (Vars[i].MaybePhysGhost)
VFlags |= ValueMaybePhysGhost;
VH->Flags = VFlags;
RecordSize += VH->Size = Vars[i].Size;
}
MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE, &Header[GH->RanksStart], sizeof(RHLocal),
MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
{
MPI_Gather(&LocalBlockHeaders[0], Vars.size() * sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
&Header[GH->BlocksStart], Vars.size() * sizeof(BlockHeader<IsBigEndian>), MPI_BYTE, 0,
SplitComm);
BlockHeader<IsBigEndian>* BH = (BlockHeader<IsBigEndian>*)&Header[GH->BlocksStart];
for (int i = 0; i < SplitNRanks; ++i)
for (size_t j = 0; j < Vars.size(); ++j, ++BH)
{
if (i == 0 && j == 0)
BH->Start = HeaderSize;
else
BH->Start = BH[-1].Start + BH[-1].Size + CRCSize;
}
RankHeader<IsBigEndian>* RH = (RankHeader<IsBigEndian>*)&Header[GH->RanksStart];
RH->Start = HeaderSize;
++RH;
for (int i = 1; i < SplitNRanks; ++i, ++RH)
{
RH->Start = ((BlockHeader<IsBigEndian>*)&Header[GH->BlocksStart])[i * Vars.size()].Start;
GH->NElems += RH->NElems;
}
// Compute the total file size.
uint64_t LastData = BH[-1].Size + CRCSize;
FileSize = BH[-1].Start + LastData;
}
else
{
RankHeader<IsBigEndian>* RH = (RankHeader<IsBigEndian>*)&Header[GH->RanksStart];
RH->Start = HeaderSize;
++RH;
for (int i = 1; i < SplitNRanks; ++i, ++RH)
{
uint64_t PrevNElems = RH[-1].NElems;
uint64_t PrevData = PrevNElems * RecordSize + CRCSize * Vars.size();
RH->Start = RH[-1].Start + PrevData;
GH->NElems += RH->NElems;
}
// Compute the total file size.
uint64_t LastNElems = RH[-1].NElems;
uint64_t LastData = LastNElems * RecordSize + CRCSize * Vars.size();
FileSize = RH[-1].Start + LastData;
}
// Now that the starting offset has been computed, send it back to each rank.
MPI_Scatter(&Header[GH->RanksStart], sizeof(RHLocal), MPI_BYTE, &RHLocal, sizeof(RHLocal),
MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
MPI_Scatter(&Header[GH->BlocksStart], sizeof(BlockHeader<IsBigEndian>) * Vars.size(),
MPI_BYTE, &LocalBlockHeaders[0], sizeof(BlockHeader<IsBigEndian>) * Vars.size(), MPI_BYTE,
0, SplitComm);
uint64_t HeaderCRC = crc64_omp(&Header[0], HeaderSize - CRCSize);
crc64_invert(HeaderCRC, &Header[HeaderSize - CRCSize]);
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
else
FH.get() = new GenericFileIO_POSIX();
FH.get()->open(LocalFileName);
FH.get()->setSize(FileSize);
FH.get()->write(&Header[0], HeaderSize, 0, "header");
close();
}
else
{
MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
MPI_Gather(&LocalBlockHeaders[0], Vars.size() * sizeof(BlockHeader<IsBigEndian>), MPI_BYTE, 0,
0, MPI_BYTE, 0, SplitComm);
MPI_Scatter(0, 0, MPI_BYTE, &RHLocal, sizeof(RHLocal), MPI_BYTE, 0, SplitComm);
if (NeedsBlockHeaders)
MPI_Scatter(0, 0, MPI_BYTE, &LocalBlockHeaders[0],
sizeof(BlockHeader<IsBigEndian>) * Vars.size(), MPI_BYTE, 0, SplitComm);
}
MPI_Barrier(SplitComm);
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(SplitComm);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(SplitComm);
else
FH.get() = new GenericFileIO_POSIX();
FH.get()->open(LocalFileName);
uint64_t Offset = RHLocal.Start;
for (size_t i = 0; i < Vars.size(); ++i)
{
uint64_t WriteSize = NeedsBlockHeaders ? LocalBlockHeaders[i].Size : NElems * Vars[i].Size;
void* Data = NeedsBlockHeaders ? LocalData[i] : Vars[i].Data;
uint64_t CRC = crc64_omp(Data, WriteSize);
bool HasExtraSpace = NeedsBlockHeaders ? LocalHasExtraSpace[i] : Vars[i].HasExtraSpace;
char* CRCLoc = HasExtraSpace ? ((char*)Data) + WriteSize : (char*)&CRC;
if (NeedsBlockHeaders)
Offset = LocalBlockHeaders[i].Start;
// When using extra space for the CRC write, preserve the original contents.
char CRCSave[CRCSize];
if (HasExtraSpace)
std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
crc64_invert(CRC, CRCLoc);
if (HasExtraSpace)
{
FH.get()->write(Data, WriteSize + CRCSize, Offset, Vars[i].Name + " with CRC");
}
else
{
FH.get()->write(Data, WriteSize, Offset, Vars[i].Name);
FH.get()->write(CRCLoc, CRCSize, Offset + WriteSize, Vars[i].Name + " CRC");
}
if (HasExtraSpace)
std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
Offset += WriteSize + CRCSize;
}
close();
MPI_Barrier(Comm);
double EndTime = MPI_Wtime();
double TotalTime = EndTime - StartTime;
double MaxTotalTime;
MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
if (SplitNRanks != NRanks)
{
uint64_t ContribFileSize = (SplitRank == 0) ? FileSize : 0;
MPI_Reduce(&ContribFileSize, &FileSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
}
if (Rank == 0)
{
double Rate = ((double)FileSize) / MaxTotalTime / (1024. * 1024.);
cout << "Wrote " << Vars.size() << " variables to " << FileName << " (" << FileSize
<< " bytes) in " << MaxTotalTime << "s: " << Rate << " MB/s" << endl;
}
MPI_Comm_free(&SplitComm);
SplitComm = MPI_COMM_NULL;
}
#endif // LANL_GENERICIO_NO_MPI
template <bool IsBigEndian>
void GenericIO::readHeaderLeader(void* GHPtr, MismatchBehavior MB, int NRanks, int Rank,
int SplitNRanks, string& LocalFileName, uint64_t& HeaderSize, vector<char>& Header)
{
// May be unused depending on preprocessor. Since it's a static var, it's
// initialized here to make sure it's in an executable block so the compiler
// will accept it.
(void)blosc_initialized;
GlobalHeader<IsBigEndian>& GH = *(GlobalHeader<IsBigEndian>*)GHPtr;
if (MB == MismatchDisallowed)
{
if (SplitNRanks != (int)GH.NRanks)
{
stringstream ss;
ss << "Won't read " << LocalFileName << ": communicator-size mismatch: "
<< "current: " << SplitNRanks << ", file: " << GH.NRanks;
throw runtime_error(ss.str());
}
#ifndef LANL_GENERICIO_NO_MPI
int TopoStatus;
MPI_Topo_test(Comm, &TopoStatus);
if (TopoStatus == MPI_CART)
{
int Dims[3], Periods[3], Coords[3];
MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
bool DimsMatch = true;
for (int i = 0; i < 3; ++i)
{
if ((uint64_t)Dims[i] != GH.Dims[i])
{
DimsMatch = false;
break;
}
}
if (!DimsMatch)
{
stringstream ss;
ss << "Won't read " << LocalFileName << ": communicator-decomposition mismatch: "
<< "current: " << Dims[0] << "x" << Dims[1] << "x" << Dims[2] << ", file: " << GH.Dims[0]
<< "x" << GH.Dims[1] << "x" << GH.Dims[2];
throw runtime_error(ss.str());
}
}
#endif
}
else if (MB == MismatchRedistribute && !Redistributing)
{
Redistributing = true;
int NFileRanks = RankMap.empty() ? (int)GH.NRanks : (int)RankMap.size();
int NFileRanksPerRank = NFileRanks / NRanks;
int NRemFileRank = NFileRanks % NRanks;
if (!NFileRanksPerRank)
{
// We have only the remainder, so the last NRemFileRank ranks get one
// file rank, and the others don't.
if (NRemFileRank && NRanks - Rank <= NRemFileRank)
SourceRanks.push_back(NRanks - (Rank + 1));
}
else
{
// Since NRemFileRank < NRanks, and we don't want to put any extra memory
// load on rank 0 (because rank 0's memory load is normally higher than
// the other ranks anyway), the last NRemFileRank will each take
// (NFileRanksPerRank+1) file ranks.
int FirstFileRank = 0, LastFileRank = NFileRanksPerRank - 1;
for (int i = 1; i <= Rank; ++i)
{
FirstFileRank = LastFileRank + 1;
LastFileRank = FirstFileRank + NFileRanksPerRank - 1;
if (NRemFileRank && NRanks - i <= NRemFileRank)
++LastFileRank;
}
for (int i = FirstFileRank; i <= LastFileRank; ++i)
SourceRanks.push_back(i);
}
}
HeaderSize = GH.HeaderSize;
Header.resize(HeaderSize + CRCSize, '\xFE' /* poison */);
FH.get()->read(&Header[0], HeaderSize + CRCSize, 0, "header");
uint64_t CRC = crc64_omp(&Header[0], HeaderSize + CRCSize);
if (CRC != (uint64_t)-1)
{
throw runtime_error("Header CRC check failed: " + LocalFileName);
}
}
// Note: Errors from this function should be recoverable. This means that if
// one rank throws an exception, then all ranks should.
void GenericIO::openAndReadHeader(MismatchBehavior MB, int EffRank, bool CheckPartMap)
{
int NRanks, Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
MPI_Comm_size(Comm, &NRanks);
#else
Rank = 0;
NRanks = 1;
#endif
if (EffRank == -1)
EffRank = MB == MismatchRedistribute ? 0 : Rank;
if (RankMap.empty() && CheckPartMap)
{
// First, check to see if the file is a rank map.
unsigned long RanksInMap = 0;
if (Rank == 0)
{
try
{
#ifndef LANL_GENERICIO_NO_MPI
GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
#else
GenericIO GIO(FileName, FileIOType);
#endif
GIO.openAndReadHeader(MismatchDisallowed, 0, false);
RanksInMap = static_cast<unsigned long>(GIO.readNumElems());
RankMap.resize(RanksInMap + GIO.requestedExtraSpace() / sizeof(int));
GIO.addVariable("$partition", RankMap, true);
GIO.readData(0, false);
RankMap.resize(RanksInMap);
}
catch (...)
{
RankMap.clear();
RanksInMap = 0;
}
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&RanksInMap, 1, MPI_UNSIGNED_LONG, 0, Comm);
if (RanksInMap > 0)
{
RankMap.resize(RanksInMap);
MPI_Bcast(&RankMap[0], RanksInMap, MPI_INT, 0, Comm);
}
#endif
}
#ifndef LANL_GENERICIO_NO_MPI
if (SplitComm != MPI_COMM_NULL)
MPI_Comm_free(&SplitComm);
#endif
string LocalFileName;
if (RankMap.empty())
{
LocalFileName = FileName;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_dup(MB == MismatchRedistribute ? MPI_COMM_SELF : Comm, &SplitComm);
#endif
}
else
{
stringstream ss;
ss << FileName << "#" << RankMap[EffRank];
LocalFileName = ss.str();
#ifndef LANL_GENERICIO_NO_MPI
if (MB == MismatchRedistribute)
{
MPI_Comm_dup(MPI_COMM_SELF, &SplitComm);
}
else
{
#ifdef __bgq__
MPI_Barrier(Comm);
#endif
MPI_Comm_split(Comm, RankMap[EffRank], Rank, &SplitComm);
}
#endif
}
if (LocalFileName == OpenFileName)
return;
FH.close();
int SplitNRanks, SplitRank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(SplitComm, &SplitRank);
MPI_Comm_size(SplitComm, &SplitNRanks);
#else
SplitRank = 0;
SplitNRanks = 1;
#endif
uint64_t HeaderSize = 0;
vector<char> Header;
if (SplitRank == 0)
{
#ifndef LANL_GENERICIO_NO_MPI
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
else
#endif
FH.get() = new GenericFileIO_POSIX();
#ifndef LANL_GENERICIO_NO_MPI
char True = 1, False = 0;
#endif
try
{
FH.get()->open(LocalFileName, true);
GlobalHeader<false> GH; // endianness does not matter yet...
FH.get()->read(&GH, sizeof(GlobalHeader<false>), 0, "global header");
if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicLE)
{
readHeaderLeader<false>(
&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName, HeaderSize, Header);
}
else if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicBE)
{
readHeaderLeader<true>(
&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName, HeaderSize, Header);
}
else
{
string Error = "invalid file-type identifier";
throw runtime_error("Won't read " + LocalFileName + ": " + Error);
}
#ifndef LANL_GENERICIO_NO_MPI
close();
MPI_Bcast(&True, 1, MPI_BYTE, 0, SplitComm);
#endif
}
catch (...)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&False, 1, MPI_BYTE, 0, SplitComm);
#endif
close();
throw;
}
}
else
{
#ifndef LANL_GENERICIO_NO_MPI
char Okay;
MPI_Bcast(&Okay, 1, MPI_BYTE, 0, SplitComm);
if (!Okay)
throw runtime_error("Failure broadcast from rank 0");
#endif
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&HeaderSize, 1, MPI_UINT64_T, 0, SplitComm);
#endif
Header.resize(HeaderSize, '\xFD' /* poison */);
#ifndef LANL_GENERICIO_NO_MPI
MPI_Bcast(&Header[0], HeaderSize, MPI_BYTE, 0, SplitComm);
#endif
FH.getHeaderCache().clear();
GlobalHeader<false>* GH = (GlobalHeader<false>*)&Header[0];
FH.setIsBigEndian(string(GH->Magic, GH->Magic + MagicSize - 1) == MagicBE);
FH.getHeaderCache().swap(Header);
OpenFileName = LocalFileName;
#ifndef LANL_GENERICIO_NO_MPI
if (!DisableCollErrChecking)
MPI_Barrier(Comm);
if (FileIOType == FileIOMPI)
FH.get() = new GenericFileIO_MPI(SplitComm);
else if (FileIOType == FileIOMPICollective)
FH.get() = new GenericFileIO_MPICollective(SplitComm);
else
FH.get() = new GenericFileIO_POSIX();
int OpenErr = 0, TotOpenErr;
try
{
FH.get()->open(LocalFileName, true);
MPI_Allreduce(
&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM, DisableCollErrChecking ? MPI_COMM_SELF : Comm);
}
catch (...)
{
OpenErr = 1;
MPI_Allreduce(
&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM, DisableCollErrChecking ? MPI_COMM_SELF : Comm);
throw;
}
if (TotOpenErr > 0)
{
stringstream ss;
ss << TotOpenErr << " ranks failed to open file: " << LocalFileName;
throw runtime_error(ss.str());
}
#endif
}
int GenericIO::readNRanks()
{
if (FH.isBigEndian())
return readNRanks<true>();
return readNRanks<false>();
}
template <bool IsBigEndian>
int GenericIO::readNRanks()
{
if (RankMap.size())
return static_cast<int>(RankMap.size());
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
return (int)GH->NRanks;
}
void GenericIO::readDims(int Dims[3])
{
if (FH.isBigEndian())
readDims<true>(Dims);
else
readDims<false>(Dims);
}
template <bool IsBigEndian>
void GenericIO::readDims(int Dims[3])
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
Dims[0] = static_cast<int>(GH->Dims[0]);
Dims[1] = static_cast<int>(GH->Dims[1]);
Dims[2] = static_cast<int>(GH->Dims[2]);
}
uint64_t GenericIO::readTotalNumElems()
{
if (FH.isBigEndian())
return readTotalNumElems<true>();
return readTotalNumElems<false>();
}
template <bool IsBigEndian>
uint64_t GenericIO::readTotalNumElems()
{
if (RankMap.size())
return (uint64_t)-1;
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
return GH->NElems;
}
void GenericIO::readPhysOrigin(double Origin[3])
{
if (FH.isBigEndian())
readPhysOrigin<true>(Origin);
else
readPhysOrigin<false>(Origin);
}
// Define a "safe" version of offsetof (offsetof itself might not work for
// non-POD types, and at least xlC v12.1 will complain about this if you try).
#define offsetof_safe(S, F) (size_t(&(S)->F) - size_t(S))
template <bool IsBigEndian>
void GenericIO::readPhysOrigin(double Origin[3])
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
if (offsetof_safe(GH, PhysOrigin) >= GH->GlobalHeaderSize)
{
std::fill(Origin, Origin + 3, 0.0);
return;
}
std::copy(GH->PhysOrigin, GH->PhysOrigin + 3, Origin);
}
void GenericIO::readPhysScale(double Scale[3])
{
if (FH.isBigEndian())
readPhysScale<true>(Scale);
else
readPhysScale<false>(Scale);
}
template <bool IsBigEndian>
void GenericIO::readPhysScale(double Scale[3])
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
if (offsetof_safe(GH, PhysScale) >= GH->GlobalHeaderSize)
{
std::fill(Scale, Scale + 3, 0.0);
return;
}
std::copy(GH->PhysScale, GH->PhysScale + 3, Scale);
}
template <bool IsBigEndian>
static size_t getRankIndex(
int EffRank, GlobalHeader<IsBigEndian>* GH, vector<int>& RankMap, vector<char>& HeaderCache)
{
if (RankMap.empty())
return EffRank;
for (size_t i = 0; i < GH->NRanks; ++i)
{
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&HeaderCache[GH->RanksStart + i * GH->RanksSize];
if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
return EffRank;
if ((int)RH->GlobalRank == EffRank)
return i;
}
assert(false && "Index requested of an invalid rank");
return (size_t)-1;
}
int GenericIO::readGlobalRankNumber(int EffRank)
{
if (FH.isBigEndian())
return readGlobalRankNumber<true>(EffRank);
return readGlobalRankNumber<false>(EffRank);
}
template <bool IsBigEndian>
int GenericIO::readGlobalRankNumber(int EffRank)
{
if (EffRank == -1)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &EffRank);
#else
EffRank = 0;
#endif
}
openAndReadHeader(MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
return EffRank;
return (int)RH->GlobalRank;
}
void GenericIO::getSourceRanks(vector<int>& SR)
{
SR.clear();
if (Redistributing)
{
std::copy(SourceRanks.begin(), SourceRanks.end(), std::back_inserter(SR));
return;
}
int Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
#else
Rank = 0;
#endif
SR.push_back(Rank);
}
size_t GenericIO::readNumElems(int EffRank)
{
if (EffRank == -1 && Redistributing)
{
DisableCollErrChecking = true;
size_t TotalSize = 0;
for (size_t i = 0, ie = SourceRanks.size(); i != ie; ++i)
TotalSize += readNumElems(SourceRanks[i]);
DisableCollErrChecking = false;
return TotalSize;
}
if (FH.isBigEndian())
return readNumElems<true>(EffRank);
return readNumElems<false>(EffRank);
}
template <bool IsBigEndian>
size_t GenericIO::readNumElems(int EffRank)
{
if (EffRank == -1)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &EffRank);
#else
EffRank = 0;
#endif
}
openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
return (size_t)RH->NElems;
}
void GenericIO::readDataSection(size_t readOffset, size_t readNumRows, int EffRank,
size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
if (FH.isBigEndian())
readDataSection<true>(readOffset, readNumRows, EffRank, RowOffset, Rank, TotalReadSize, NErrs);
else
readDataSection<false>(readOffset, readNumRows, EffRank, RowOffset, Rank, TotalReadSize, NErrs);
}
void GenericIO::readDataSection(
size_t readOffset, size_t readNumRows, int EffRank, bool PrintStats, bool CollStats)
{
(void)CollStats; // may be unused depending on preprocessor config.
int Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
#else
Rank = 0;
#endif
uint64_t TotalReadSize = 0;
#ifndef LANL_GENERICIO_NO_MPI
double StartTime = MPI_Wtime();
#else
double StartTime = double(clock()) / CLOCKS_PER_SEC;
#endif
int NErrs[3] = { 0, 0, 0 };
if (EffRank == -1 && Redistributing)
{
DisableCollErrChecking = true;
size_t RowOffset = 0;
for (size_t i = 0, ie = SourceRanks.size(); i != ie; ++i)
{
readDataSection(
readOffset, readNumRows, SourceRanks[i], RowOffset, Rank, TotalReadSize, NErrs);
RowOffset += readNumElems(SourceRanks[i]);
}
DisableCollErrChecking = false;
}
else
{
readDataSection(readOffset, readNumRows, EffRank, 0, Rank, TotalReadSize, NErrs);
}
int AllNErrs[3];
#ifndef LANL_GENERICIO_NO_MPI
MPI_Allreduce(NErrs, AllNErrs, 3, MPI_INT, MPI_SUM, Comm);
#else
AllNErrs[0] = NErrs[0];
AllNErrs[1] = NErrs[1];
AllNErrs[2] = NErrs[2];
#endif
if (AllNErrs[0] > 0 || AllNErrs[1] > 0 || AllNErrs[2] > 0)
{
stringstream ss;
ss << "Experienced " << AllNErrs[0] << " I/O error(s), " << AllNErrs[1] << " CRC error(s) and "
<< AllNErrs[2] << " decompression CRC error(s) reading: " << OpenFileName;
throw runtime_error(ss.str());
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Barrier(Comm);
#endif
#ifndef LANL_GENERICIO_NO_MPI
double EndTime = MPI_Wtime();
#else
double EndTime = double(clock()) / CLOCKS_PER_SEC;
#endif
double TotalTime = EndTime - StartTime;
double MaxTotalTime;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
else
#endif
MaxTotalTime = TotalTime;
uint64_t AllTotalReadSize;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalReadSize, &AllTotalReadSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
else
#endif
AllTotalReadSize = TotalReadSize;
if (Rank == 0 && PrintStats)
{
double Rate = ((double)AllTotalReadSize) / MaxTotalTime / (1024. * 1024.);
cout << "Read " << Vars.size() << " variables from " << FileName << " (" << AllTotalReadSize
<< " bytes) in " << MaxTotalTime << "s: " << Rate << " MB/s [excluding header read]"
<< endl;
}
}
// Note: Errors from this function should be recoverable. This means that if
// one rank throws an exception, then all ranks should.
template <bool IsBigEndian>
void GenericIO::readDataSection(size_t readOffset, size_t readNumRows, int EffRank,
size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
if (EffRank == -1)
EffRank = Rank;
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
for (size_t i = 0; i < Vars.size(); ++i)
{
uint64_t Offset = RH->Start;
bool VarFound = false;
for (uint64_t j = 0; j < GH->NVars; ++j)
{
VariableHeader<IsBigEndian>* VH =
(VariableHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->VarsStart + j * GH->VarsSize];
string VName(VH->Name, VH->Name + NameSize);
size_t VNameNull = VName.find('\0');
if (VNameNull < NameSize)
VName.resize(VNameNull);
uint64_t ReadSize = RH->NElems * VH->Size + CRCSize;
if (VName != Vars[i].Name)
{
Offset += ReadSize;
continue;
}
VarFound = true;
bool IsFloat = (VH->Flags & FloatValue) != 0, IsSigned = (VH->Flags & SignedValue) != 0;
if (VH->Size != Vars[i].Size)
{
stringstream ss;
ss << "Size mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << Vars[i].Size << ", file: " << VH->Size;
throw runtime_error(ss.str());
}
else if (IsFloat != Vars[i].IsFloat)
{
string Float("float"), Int("integer");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsFloat ? Float : Int)
<< ", file: " << (IsFloat ? Float : Int);
throw runtime_error(ss.str());
}
else if (IsSigned != Vars[i].IsSigned)
{
string Signed("signed"), Uns("unsigned");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsSigned ? Signed : Uns)
<< ", file: " << (IsSigned ? Signed : Uns);
throw runtime_error(ss.str());
}
size_t VarOffset = RowOffset * Vars[i].Size;
void* VarData = ((char*)Vars[i].Data) + VarOffset;
vector<unsigned char> LData;
void* Data = VarData;
bool HasExtraSpace = Vars[i].HasExtraSpace;
(void)HasExtraSpace; // Only used in assert, unused in release builds.
if (offsetof_safe(GH, BlocksStart) < GH->GlobalHeaderSize && GH->BlocksSize > 0)
{
BlockHeader<IsBigEndian>* BH =
(BlockHeader<IsBigEndian>*)&FH
.getHeaderCache()[GH->BlocksStart + (RankIndex * GH->NVars + j) * GH->BlocksSize];
ReadSize = BH->Size + CRCSize;
Offset = BH->Start;
if (strncmp(BH->Filters[0], CompressName, FilterNameSize) == 0)
{
LData.resize(ReadSize);
Data = &LData[0];
HasExtraSpace = true;
}
else if (BH->Filters[0][0] != '\0')
{
stringstream ss;
ss << "Unknown filter \"" << BH->Filters[0] << "\" on variable " << Vars[i].Name;
throw runtime_error(ss.str());
}
}
assert(HasExtraSpace && "Extra space required for reading");
int Retry = 0;
{
int RetryCount = 300;
const char* EnvStr = getenv("GENERICIO_RETRY_COUNT");
if (EnvStr)
RetryCount = atoi(EnvStr);
int RetrySleep = 100; // ms
EnvStr = getenv("GENERICIO_RETRY_SLEEP");
if (EnvStr)
RetrySleep = atoi(EnvStr);
for (; Retry < RetryCount; ++Retry)
{
try
{
//
// Read section
ReadSize = readNumRows * VH->Size;
Offset = Offset + readOffset * VH->Size;
FH.get()->read(Data, ReadSize, static_cast<off_t>(Offset), Vars[i].Name);
break;
}
catch (...)
{
}
usleep(1000 * RetrySleep);
}
if (Retry == RetryCount)
{
++NErrs[0];
break;
}
else if (Retry > 0)
{
EnvStr = getenv("GENERICIO_VERBOSE");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
std::cerr << "Rank " << RankTmp << ": " << Retry
<< " I/O retries were necessary for reading " << Vars[i].Name
<< " from: " << OpenFileName << "\n";
std::cerr.flush();
}
}
}
}
TotalReadSize += ReadSize;
// Byte swap the data if necessary.
if (IsBigEndian != isBigEndian())
for (size_t k = 0; k < RH->NElems; ++k)
{
char* OffsetTmp = ((char*)VarData) + k * Vars[i].Size;
bswap(OffsetTmp, Vars[i].Size);
}
break;
}
if (!VarFound)
throw runtime_error("Variable " + Vars[i].Name + " not found in: " + OpenFileName);
}
}
void GenericIO::readCoords(int Coords[3], int EffRank)
{
if (EffRank == -1 && Redistributing)
{
std::fill(Coords, Coords + 3, 0);
return;
}
if (FH.isBigEndian())
readCoords<true>(Coords, EffRank);
else
readCoords<false>(Coords, EffRank);
}
template <bool IsBigEndian>
void GenericIO::readCoords(int Coords[3], int EffRank)
{
if (EffRank == -1)
{
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &EffRank);
#else
EffRank = 0;
#endif
}
openAndReadHeader(MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
Coords[0] = static_cast<int>(RH->Coords[0]);
Coords[1] = static_cast<int>(RH->Coords[1]);
Coords[2] = static_cast<int>(RH->Coords[2]);
}
void GenericIO::readData(int EffRank, bool PrintStats, bool CollStats)
{
(void)CollStats; // may be unused depending on preprocessor config.
int Rank;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(Comm, &Rank);
#else
Rank = 0;
#endif
uint64_t TotalReadSize = 0;
#ifndef LANL_GENERICIO_NO_MPI
double StartTime = MPI_Wtime();
#else
double StartTime = double(clock()) / CLOCKS_PER_SEC;
#endif
int NErrs[3] = { 0, 0, 0 };
if (EffRank == -1 && Redistributing)
{
DisableCollErrChecking = true;
size_t RowOffset = 0;
for (size_t i = 0, ie = SourceRanks.size(); i != ie; ++i)
{
readData(SourceRanks[i], RowOffset, Rank, TotalReadSize, NErrs);
RowOffset += readNumElems(SourceRanks[i]);
}
DisableCollErrChecking = false;
}
else
{
readData(EffRank, 0, Rank, TotalReadSize, NErrs);
}
int AllNErrs[3];
#ifndef LANL_GENERICIO_NO_MPI
MPI_Allreduce(NErrs, AllNErrs, 3, MPI_INT, MPI_SUM, Comm);
#else
AllNErrs[0] = NErrs[0];
AllNErrs[1] = NErrs[1];
AllNErrs[2] = NErrs[2];
#endif
if (AllNErrs[0] > 0 || AllNErrs[1] > 0 || AllNErrs[2] > 0)
{
stringstream ss;
ss << "Experienced " << AllNErrs[0] << " I/O error(s), " << AllNErrs[1] << " CRC error(s) and "
<< AllNErrs[2] << " decompression CRC error(s) reading: " << OpenFileName;
throw runtime_error(ss.str());
}
#ifndef LANL_GENERICIO_NO_MPI
MPI_Barrier(Comm);
#endif
#ifndef LANL_GENERICIO_NO_MPI
double EndTime = MPI_Wtime();
#else
double EndTime = double(clock()) / CLOCKS_PER_SEC;
#endif
double TotalTime = EndTime - StartTime;
double MaxTotalTime;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
else
#endif
MaxTotalTime = TotalTime;
uint64_t AllTotalReadSize;
#ifndef LANL_GENERICIO_NO_MPI
if (CollStats)
MPI_Reduce(&TotalReadSize, &AllTotalReadSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
else
#endif
AllTotalReadSize = TotalReadSize;
if (Rank == 0 && PrintStats)
{
double Rate = ((double)AllTotalReadSize) / MaxTotalTime / (1024. * 1024.);
cout << "Read " << Vars.size() << " variables from " << FileName << " (" << AllTotalReadSize
<< " bytes) in " << MaxTotalTime << "s: " << Rate << " MB/s [excluding header read]"
<< endl;
}
}
void GenericIO::readData(
int EffRank, size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
if (FH.isBigEndian())
readData<true>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
else
readData<false>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
}
// Note: Errors from this function should be recoverable. This means that if
// one rank throws an exception, then all ranks should.
template <bool IsBigEndian>
void GenericIO::readData(
int EffRank, size_t RowOffset, int Rank, uint64_t& TotalReadSize, int NErrs[3])
{
openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed, EffRank, false);
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
if (EffRank == -1)
EffRank = Rank;
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
assert(RankIndex < GH->NRanks && "Invalid rank specified");
RankHeader<IsBigEndian>* RH =
(RankHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->RanksStart + RankIndex * GH->RanksSize];
for (size_t i = 0; i < Vars.size(); ++i)
{
uint64_t Offset = RH->Start;
bool VarFound = false;
for (uint64_t j = 0; j < GH->NVars; ++j)
{
VariableHeader<IsBigEndian>* VH =
(VariableHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->VarsStart + j * GH->VarsSize];
string VName(VH->Name, VH->Name + NameSize);
size_t VNameNull = VName.find('\0');
if (VNameNull < NameSize)
VName.resize(VNameNull);
uint64_t ReadSize = RH->NElems * VH->Size + CRCSize;
if (VName != Vars[i].Name)
{
Offset += ReadSize;
continue;
}
VarFound = true;
bool IsFloat = (VH->Flags & FloatValue) != 0, IsSigned = (VH->Flags & SignedValue) != 0;
if (VH->Size != Vars[i].Size)
{
stringstream ss;
ss << "Size mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << Vars[i].Size << ", file: " << VH->Size;
throw runtime_error(ss.str());
}
else if (IsFloat != Vars[i].IsFloat)
{
string Float("float"), Int("integer");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsFloat ? Float : Int)
<< ", file: " << (IsFloat ? Float : Int);
throw runtime_error(ss.str());
}
else if (IsSigned != Vars[i].IsSigned)
{
string Signed("signed"), Uns("unsigned");
stringstream ss;
ss << "Type mismatch for variable " << Vars[i].Name << " in: " << OpenFileName
<< ": current: " << (Vars[i].IsSigned ? Signed : Uns)
<< ", file: " << (IsSigned ? Signed : Uns);
throw runtime_error(ss.str());
}
size_t VarOffset = RowOffset * Vars[i].Size;
void* VarData = ((char*)Vars[i].Data) + VarOffset;
vector<unsigned char> LData;
void* Data = VarData;
bool HasExtraSpace = Vars[i].HasExtraSpace;
if (offsetof_safe(GH, BlocksStart) < GH->GlobalHeaderSize && GH->BlocksSize > 0)
{
BlockHeader<IsBigEndian>* BH =
(BlockHeader<IsBigEndian>*)&FH
.getHeaderCache()[GH->BlocksStart + (RankIndex * GH->NVars + j) * GH->BlocksSize];
ReadSize = BH->Size + CRCSize;
Offset = BH->Start;
if (strncmp(BH->Filters[0], CompressName, FilterNameSize) == 0)
{
LData.resize(ReadSize);
Data = &LData[0];
HasExtraSpace = true;
}
else if (BH->Filters[0][0] != '\0')
{
stringstream ss;
ss << "Unknown filter \"" << BH->Filters[0] << "\" on variable " << Vars[i].Name;
throw runtime_error(ss.str());
}
}
assert(HasExtraSpace && "Extra space required for reading");
char CRCSave[CRCSize];
char* CRCLoc = ((char*)Data) + ReadSize - CRCSize;
if (HasExtraSpace)
std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
int Retry = 0;
{
int RetryCount = 300;
const char* EnvStr = getenv("GENERICIO_RETRY_COUNT");
if (EnvStr)
RetryCount = atoi(EnvStr);
int RetrySleep = 100; // ms
EnvStr = getenv("GENERICIO_RETRY_SLEEP");
if (EnvStr)
RetrySleep = atoi(EnvStr);
for (; Retry < RetryCount; ++Retry)
{
try
{
FH.get()->read(Data, ReadSize, static_cast<off_t>(Offset), Vars[i].Name);
break;
}
catch (...)
{
}
usleep(1000 * RetrySleep);
}
if (Retry == RetryCount)
{
++NErrs[0];
break;
}
else if (Retry > 0)
{
EnvStr = getenv("GENERICIO_VERBOSE");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
std::cerr << "Rank " << RankTmp << ": " << Retry
<< " I/O retries were necessary for reading " << Vars[i].Name
<< " from: " << OpenFileName << "\n";
std::cerr.flush();
}
}
}
}
TotalReadSize += ReadSize;
uint64_t CRC = crc64_omp(Data, ReadSize);
if (CRC != (uint64_t)-1)
{
++NErrs[1];
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
// All ranks will do this and have a good time!
string dn = "gio_crc_errors";
mkdir(dn.c_str(), 0777);
srand(static_cast<unsigned int>(time(0)));
int DumpNum = rand();
stringstream ssd;
ssd << dn << "/gio_crc_error_dump." << RankTmp << "." << DumpNum << ".bin";
stringstream ss;
ss << dn << "/gio_crc_error_log." << RankTmp << ".txt";
ofstream ofs(ss.str().c_str(), ofstream::out | ofstream::app);
ofs << "On-Disk CRC Error Report:\n";
ofs << "Variable: " << Vars[i].Name << "\n";
ofs << "File: " << OpenFileName << "\n";
ofs << "I/O Retries: " << Retry << "\n";
ofs << "Size: " << ReadSize << " bytes\n";
ofs << "Offset: " << Offset << " bytes\n";
ofs << "CRC: " << CRC << " (expected is -1)\n";
ofs << "Dump file: " << ssd.str() << "\n";
ofs << "\n";
ofs.close();
ofstream dofs(ssd.str().c_str(), ofstream::out);
dofs.write((const char*)Data, ReadSize);
dofs.close();
uint64_t RawCRC = crc64_omp(Data, ReadSize - CRCSize);
unsigned char* UData = (unsigned char*)Data;
crc64_invert(RawCRC, &UData[ReadSize - CRCSize]);
#if 1
crc64_omp(Data, ReadSize);
#else // Commenting because NewCRC cannot == -1 (uint64) and this is debugging code.
// uint64_t NewCRC = crc64_omp(Data, ReadSize);
// std::cerr << "Recalculated CRC: " << NewCRC << ((NewCRC == -1) ? "ok" : "bad") << "\n";
#endif
break;
}
if (HasExtraSpace)
std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
if (LData.size())
{
CompressHeader<IsBigEndian>* CH = (CompressHeader<IsBigEndian>*)&LData[0];
#ifndef LANL_GENERICIO_NO_COMPRESSION
#ifdef _OPENMP
#pragma omp master
{
#endif
if (!blosc_initialized)
{
blosc_init();
blosc_initialized = true;
}
#ifdef _OPENMP
blosc_set_nthreads(omp_get_max_threads());
}
#endif
blosc_decompress(
&LData[0] + sizeof(CompressHeader<IsBigEndian>), VarData, Vars[i].Size * RH->NElems);
#endif // LANL_GENERICIO_NO_COMPRESSION
if (CH->OrigCRC != crc64_omp(VarData, Vars[i].Size * RH->NElems))
{
++NErrs[2];
break;
}
}
// Byte swap the data if necessary.
if (IsBigEndian != isBigEndian())
for (size_t k = 0; k < RH->NElems; ++k)
{
char* OffsetTmp = ((char*)VarData) + k * Vars[i].Size;
bswap(OffsetTmp, Vars[i].Size);
}
break;
}
if (!VarFound)
throw runtime_error("Variable " + Vars[i].Name + " not found in: " + OpenFileName);
// This is for debugging.
if (NErrs[0] || NErrs[1] || NErrs[2])
{
const char* EnvStr = getenv("GENERICIO_VERBOSE");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int RankTmp;
#ifndef LANL_GENERICIO_NO_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &RankTmp);
#else
RankTmp = 0;
#endif
std::cerr << "Rank " << RankTmp << ": " << NErrs[0] << " I/O error(s), " << NErrs[1]
<< " CRC error(s) and " << NErrs[2]
<< " decompression CRC error(s) reading: " << Vars[i].Name
<< " from: " << OpenFileName << "\n";
std::cerr.flush();
}
}
}
if (NErrs[0] || NErrs[1] || NErrs[2])
break;
}
}
void GenericIO::getVariableInfo(vector<VariableInfo>& VI)
{
if (FH.isBigEndian())
getVariableInfo<true>(VI);
else
getVariableInfo<false>(VI);
}
template <bool IsBigEndian>
void GenericIO::getVariableInfo(vector<VariableInfo>& VI)
{
assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
GlobalHeader<IsBigEndian>* GH = (GlobalHeader<IsBigEndian>*)&FH.getHeaderCache()[0];
for (uint64_t j = 0; j < GH->NVars; ++j)
{
VariableHeader<IsBigEndian>* VH =
(VariableHeader<IsBigEndian>*)&FH.getHeaderCache()[GH->VarsStart + j * GH->VarsSize];
string VName(VH->Name, VH->Name + NameSize);
size_t VNameNull = VName.find('\0');
if (VNameNull < NameSize)
VName.resize(VNameNull);
bool IsFloat = (VH->Flags & FloatValue) != 0, IsSigned = (VH->Flags & SignedValue) != 0,
IsPhysCoordX = ((VH->Flags & ValueIsPhysCoordX) != 0),
IsPhysCoordY = ((VH->Flags & ValueIsPhysCoordY) != 0),
IsPhysCoordZ = ((VH->Flags & ValueIsPhysCoordZ) != 0),
MaybePhysGhost = ((VH->Flags & ValueMaybePhysGhost) != 0);
VI.push_back(VariableInfo(VName, (size_t)VH->Size, IsFloat, IsSigned, IsPhysCoordX,
IsPhysCoordY, IsPhysCoordZ, MaybePhysGhost));
}
}
void GenericIO::setNaturalDefaultPartition()
{
#ifdef __bgq__
DefaultPartition = MPIX_IO_link_id();
#else
#ifndef LANL_GENERICIO_NO_MPI
bool UseName = true;
const char* EnvStr = getenv("GENERICIO_PARTITIONS_USE_NAME");
if (EnvStr)
{
int Mod = atoi(EnvStr);
UseName = (Mod != 0);
}
if (UseName)
{
// This is a heuristic to generate ~256 partitions based on the
// names of the nodes.
char Name[MPI_MAX_PROCESSOR_NAME];
int Len = 0;
MPI_Get_processor_name(Name, &Len);
unsigned char color = 0;
for (int i = 0; i < Len; ++i)
color += (unsigned char)Name[i];
DefaultPartition = color;
}
// This is for debugging.
EnvStr = getenv("GENERICIO_RANK_PARTITIONS");
if (EnvStr)
{
int Mod = atoi(EnvStr);
if (Mod > 0)
{
int Rank;
MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
DefaultPartition += Rank % Mod;
}
}
#endif
#endif
}
} /* END namespace cosmotk */
} /* END namespace lanl */
| 28.370721 | 100 | 0.625327 | psavery |
4b4a88a92eb5389cc24518a5e9e3e5b05e3510f6 | 423 | cc | C++ | src/ppl/nn/engines/x86/kernels/onnx/constant_kernel.cc | wolf15/ppl.nn | ac23e5eb518039536f1ef39b43c63d6bda900e77 | [
"Apache-2.0"
] | 1 | 2021-06-30T14:07:37.000Z | 2021-06-30T14:07:37.000Z | src/ppl/nn/engines/x86/kernels/onnx/constant_kernel.cc | wolf15/ppl.nn | ac23e5eb518039536f1ef39b43c63d6bda900e77 | [
"Apache-2.0"
] | null | null | null | src/ppl/nn/engines/x86/kernels/onnx/constant_kernel.cc | wolf15/ppl.nn | ac23e5eb518039536f1ef39b43c63d6bda900e77 | [
"Apache-2.0"
] | null | null | null | #include "ppl/nn/engines/x86/kernels/onnx/constant_kernel.h"
using namespace std;
using namespace ppl::common;
namespace ppl { namespace nn { namespace x86 {
RetCode ConstantKernel::DoExecute(KernelExecContext* ctx) {
auto output = ctx->GetOutput<TensorImpl>(0);
GetDevice()->CopyFromHost(&output->GetBufferDesc(), param_->data.data(), output->GetShape());
return RC_SUCCESS;
}
}}} // namespace ppl::nn::x86
| 30.214286 | 97 | 0.728132 | wolf15 |
4b4af7404b2bc9c13c9bfaddb37f9d5ae6b508a7 | 572 | cpp | C++ | src/leetcode/8/61231414_wrong_answer.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/leetcode/8/61231414_wrong_answer.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/leetcode/8/61231414_wrong_answer.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isdigit(char ch) {
return (ch <= '9' && ch >= '0');
}
int myAtoi(string str) {
#define int long long
int pos = 0, ret = 0, fl = 1;
char ch;
while(pos < (int)str.length() && !isdigit(ch = str[pos++])) if(ch == '-') (fl = -1);
for(ret = ch - '0'; pos < (int)str.length() && isdigit(ch = str[pos++]); ret *= 10, ret += ch - '0');
ret *= fl;
if(ret > INT_MAX) return INT_MAX;
if(ret < INT_MIN) return INT_MIN;
return (int)ret;
#undef int
}
}; | 31.777778 | 109 | 0.472028 | lnkkerst |
4b4c4d4b90790b30be2c6ce0010ef3f8ab971bdb | 3,898 | cpp | C++ | devices/laihost/laihost.cpp | JartC0ding/horizon | 2b9a75b45ac768a8da0f7a98f164a37690dc583f | [
"MIT"
] | null | null | null | devices/laihost/laihost.cpp | JartC0ding/horizon | 2b9a75b45ac768a8da0f7a98f164a37690dc583f | [
"MIT"
] | null | null | null | devices/laihost/laihost.cpp | JartC0ding/horizon | 2b9a75b45ac768a8da0f7a98f164a37690dc583f | [
"MIT"
] | null | null | null | extern "C" {
#include <lai/host.h>
#include <acpispec/tables.h>
}
#include <memory/page_table_manager.h>
#include <memory/page_frame_allocator.h>
#include <utils/abort.h>
#include <utils/log.h>
#include <utils/string.h>
#include <utils/port.h>
#include <pci/pci.h>
#include <timer/timer.h>
#include <acpi/acpi.h>
extern "C" {
void* laihost_map(size_t address, size_t count) {
for (int i = 0; i < count / 0x1000; i++) {
memory::global_page_table_manager.map_memory((void*) (address + i * 0x1000), (void*) (address + i * 0x1000));
}
return (void*) address;
}
void laihost_unmap(void* pointer, size_t count) {
debugf("WARNING: laihost_unmap: %x %d not implemented!\n", pointer, count);
}
void laihost_log(int level, const char* msg) {
switch (level) {
case LAI_WARN_LOG:
debugf("WARNING: %s\n", msg);
break;
case LAI_DEBUG_LOG:
debugf("DEBUG: %s\n", msg);
break;
default:
debugf("UNKNOWN: %s\n", msg);
break;
}
}
__attribute__((noreturn)) void laihost_panic(const char* msg) {
abortf("laihost: %s\n", msg);
}
void* laihost_malloc(size_t size) {
return memory::global_allocator.request_pages(size / 0x1000 + 1);
}
void* laihost_realloc(void *oldptr, size_t newsize, size_t oldsize) {
if (newsize == 0) {
laihost_free(oldptr, oldsize);
return nullptr;
} else if (!oldptr) {
return laihost_malloc(newsize);
} else if (newsize <= oldsize) {
return oldptr;
} else {
void* newptr = laihost_malloc(newsize);
memcpy(newptr, oldptr, oldsize);
return newptr;
}
}
void laihost_free(void *ptr, size_t size) {
memory::global_allocator.free_pages(ptr, size / 0x1000 + 1);
}
void laihost_outb(uint16_t port, uint8_t val) {
outb(port, val);
}
void laihost_outw(uint16_t port, uint16_t val) {
outw(port, val);
}
void laihost_outd(uint16_t port, uint32_t val) {
outl(port, val);
}
uint8_t laihost_inb(uint16_t port) {
return inb(port);
}
uint16_t laihost_inw(uint16_t port) {
return inw(port);
}
uint32_t laihost_ind(uint16_t port) {
return inl(port);
}
void laihost_pci_writeb(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset, uint8_t val) {
pci::pci_writeb(bus, slot, fun, offset, val);
}
void laihost_pci_writew(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset, uint16_t val) {
pci::pci_writew(bus, slot, fun, offset, val);
}
void laihost_pci_writed(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset, uint32_t val) {
pci::pci_writed(bus, slot, fun, offset, val);
}
uint8_t laihost_pci_readb(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset) {
return pci::pci_readb(bus, slot, fun, offset);
}
uint16_t laihost_pci_readw(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset) {
return pci::pci_readw(bus, slot, fun, offset);
}
uint32_t laihost_pci_readd(uint16_t seg, uint8_t bus, uint8_t slot, uint8_t fun, uint16_t offset) {
return pci::pci_readd(bus, slot, fun, offset);
}
void laihost_sleep(uint64_t ms) {
timer::global_timer->sleep(ms);
}
uint64_t laihost_timer(void) {
laihost_panic("laihost_timer not implemented! What is that even?");
}
void laihost_handle_amldebug(lai_variable_t* var) {
debugf("DEBUG: laihost_handle_amldebug with %x\n", var);
}
int laihost_sync_wait(struct lai_sync_state *sync, unsigned int val, int64_t timeout) {
debugf("WARNING: laihost_sync_wait not implemented!\n");
return -1;
}
void laihost_sync_wake(struct lai_sync_state *sync) {
debugf("WARNING: laihost_sync_wake not implemented!\n");
}
void* laihost_scan(const char *sig, size_t index) {
if (memcmp(sig, "DSDT", 4) == 0) {
return (void*) (uint64_t) ((acpi_fadt_t*) acpi::find_table(global_bootinfo, (char*) "FACP", 0))->dsdt;
} else {
return acpi::find_table(global_bootinfo, (char*) sig, index);
}
}
} | 26.161074 | 112 | 0.693689 | JartC0ding |
4b4d9667bcd8c48992dafb1598dcc5c44defc873 | 4,160 | cpp | C++ | example/Reading/source/main.cpp | HamletDuFromage/Simple-INI-Parser | ca427f98dc25620432430c563d9a73534b942c37 | [
"0BSD"
] | null | null | null | example/Reading/source/main.cpp | HamletDuFromage/Simple-INI-Parser | ca427f98dc25620432430c563d9a73534b942c37 | [
"0BSD"
] | null | null | null | example/Reading/source/main.cpp | HamletDuFromage/Simple-INI-Parser | ca427f98dc25620432430c563d9a73534b942c37 | [
"0BSD"
] | null | null | null | /*
* SimpleIniParser
* Copyright (c) 2020 Nichole Mattera
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <iostream>
#include <fstream>
#include <switch.h>
#include <SimpleIniParser.hpp>
#include <vector>
using namespace simpleIniParser;
void writeOption(IniOption * option, bool withTab) {
switch (option->type) {
case IniOptionType::SemicolonComment:
std::cout << ((withTab) ? "\t" : "") << "Type: Semicolon Comment, Value: \"" << option->value << "\"\n";
break;
case IniOptionType::HashtagComment:
std::cout << ((withTab) ? "\t" : "") << "Type: Hashtag Comment, Value: \"" << option->value << "\"\n";
break;
default:
std::cout << ((withTab) ? "\t" : "") << "Type: Option, Key: \"" << option->key << "\", Value: \"" << option->value << "\"\n";
break;
}
}
void writeSection(IniSection * section) {
switch (section->type) {
case IniSectionType::SemicolonComment:
std::cout << "Type: Semicolon Comment, Value: \"" << section->value << "\"\n";
break;
case IniSectionType::HashtagComment:
std::cout << "Type: Hashtag Comment, Value: \"" << section->value << "\"\n";
break;
case IniSectionType::HekateCaption:
std::cout << "Type: Hekate Caption, Value: \"" << section->value << "\"\n";
break;
default:
std::cout << "Type: Section, Value: \"" << section->value << "\"\n";
break;
}
for (auto const& option : section->options) {
writeOption(option, true);
}
std::cout << "\n";
}
int main(int argc, char **argv) {
consoleInit(NULL);
Result rc = romfsInit();
if (R_FAILED(rc)) {
std::cout << "Unable to initialize romfs.\n";
}
else {
Ini * config = Ini::parseFile("romfs:/config.ini");
std::cout << "Reading through an INI file.\n";
std::cout << "=====================================================\n\n";
for (auto const& option : config->options) {
writeOption(option, false);
}
if (config->options.size() > 0)
std::cout << "\n";
for (auto const& section : config->sections) {
writeSection(section);
}
std::cout << "\nGet a specific option from a specific section.\n";
std::cout << "=====================================================\n\n";
std::vector<IniOption *> options = config->findSection("CFW", true, IniSectionType::Section)->findAllOptions("logopath");
for (auto const& option : options) {
writeOption(option, false);
}
IniOption * option = config->findSection("config")->findFirstOption("cUsToMlOgO", false);
std::cout << "Key: \"" << option->key << "\" | Value: \"" << option->value << "\"\n";
IniOption * option2 = config->findSection("CFW", true, IniSectionType::Section)->findFirstOption("option comment test", false, IniOptionType::HashtagComment, IniOptionSearchField::Value);
std::cout << "Key: \"" << option2->key << "\" | Value: \"" << option2->value << "\"\n\n";
delete config;
}
std::cout << "\nPress any key to close.\n";
while(appletMainLoop())
{
hidScanInput();
if (hidKeysDown(CONTROLLER_P1_AUTO))
break;
consoleUpdate(NULL);
}
consoleExit(NULL);
return 0;
} | 33.821138 | 195 | 0.568029 | HamletDuFromage |
4b4d9c3b2d73165f35ead04dcae80358ea85ee85 | 374 | cpp | C++ | examples/error_mitigation/simple_mitiq.cpp | ausbin/qcor | e9e0624a0e14b1b980ce9265b71c9b394abc60a8 | [
"BSD-3-Clause"
] | 59 | 2019-08-22T18:40:38.000Z | 2022-03-09T04:12:42.000Z | examples/error_mitigation/simple_mitiq.cpp | ausbin/qcor | e9e0624a0e14b1b980ce9265b71c9b394abc60a8 | [
"BSD-3-Clause"
] | 137 | 2019-09-13T15:50:18.000Z | 2021-12-06T14:19:46.000Z | examples/error_mitigation/simple_mitiq.cpp | ausbin/qcor | e9e0624a0e14b1b980ce9265b71c9b394abc60a8 | [
"BSD-3-Clause"
] | 26 | 2019-07-08T17:30:35.000Z | 2021-12-03T16:24:12.000Z | // run error mitigation with mitiq with
// $ qcor -qpu aer[noise-model:noise_model.json] -shots 4096 -em mitiq simple_mitiq.cpp
// $ ./a.out
__qpu__ void noisy_zero(qreg q) {
for (int i = 0; i < 100; i++) {
X(q[0]);
}
Measure(q[0]);
}
int main() {
qreg q = qalloc(1);
noisy_zero(q);
std::cout << "Expectation: " << q.exp_val_z() << "\n";
} | 23.375 | 87 | 0.564171 | ausbin |
4b5209642cd837eb185a7620bf2c05692dbb57e3 | 62,359 | cpp | C++ | src/pal/src/map/virtual.cpp | chrisaut/coreclr | 849da1bdf828256624dac634eefe8590e48f0c26 | [
"MIT"
] | null | null | null | src/pal/src/map/virtual.cpp | chrisaut/coreclr | 849da1bdf828256624dac634eefe8590e48f0c26 | [
"MIT"
] | null | null | null | src/pal/src/map/virtual.cpp | chrisaut/coreclr | 849da1bdf828256624dac634eefe8590e48f0c26 | [
"MIT"
] | 1 | 2021-02-24T10:01:34.000Z | 2021-02-24T10:01:34.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*++
Module Name:
virtual.cpp
Abstract:
Implementation of virtual memory management functions.
--*/
#include "pal/thread.hpp"
#include "pal/cs.hpp"
#include "pal/malloc.hpp"
#include "pal/file.hpp"
#include "pal/seh.hpp"
#include "pal/dbgmsg.h"
#include "pal/virtual.h"
#include "pal/map.h"
#include "pal/init.h"
#include "common.h"
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#if HAVE_VM_ALLOCATE
#include <mach/vm_map.h>
#include <mach/mach_init.h>
#endif // HAVE_VM_ALLOCATE
using namespace CorUnix;
SET_DEFAULT_DEBUG_CHANNEL(VIRTUAL);
CRITICAL_SECTION virtual_critsec;
// The first node in our list of allocated blocks.
static PCMI pVirtualMemory;
/* We need MAP_ANON. However on some platforms like HP-UX, it is defined as MAP_ANONYMOUS */
#if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
#define MAP_ANON MAP_ANONYMOUS
#endif
/*++
Function:
ReserveVirtualMemory()
Helper function that is used by Virtual* APIs and ExecutableMemoryAllocator
to reserve virtual memory from the OS.
--*/
static LPVOID ReserveVirtualMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize); /* Size of Region */
// A memory allocator that allocates memory from a pre-reserved region
// of virtual memory that is located near the CoreCLR library.
static ExecutableMemoryAllocator g_executableMemoryAllocator;
//
//
// Virtual Memory Logging
//
// We maintain a lightweight in-memory circular buffer recording virtual
// memory operations so that we can better diagnose failures and crashes
// caused by one of these operations mishandling memory in some way.
//
//
namespace VirtualMemoryLogging
{
// Specifies the operation being logged
enum class VirtualOperation
{
Allocate = 0x10,
Reserve = 0x20,
Commit = 0x30,
Decommit = 0x40,
Release = 0x50,
};
// Indicates that the attempted operation has failed
const DWORD FailedOperationMarker = 0x80000000;
// An entry in the in-memory log
struct LogRecord
{
LONG RecordId;
DWORD Operation;
LPVOID CurrentThread;
LPVOID RequestedAddress;
LPVOID ReturnedAddress;
SIZE_T Size;
DWORD AllocationType;
DWORD Protect;
};
// Maximum number of records in the in-memory log
const LONG MaxRecords = 128;
// Buffer used to store the logged data
volatile LogRecord logRecords[MaxRecords];
// Current record number. Use (recordNumber % MaxRecords) to determine
// the current position in the circular buffer.
volatile LONG recordNumber = 0;
// Record an entry in the in-memory log
void LogVaOperation(
IN VirtualOperation operation,
IN LPVOID requestedAddress,
IN SIZE_T size,
IN DWORD flAllocationType,
IN DWORD flProtect,
IN LPVOID returnedAddress,
IN BOOL result)
{
LONG i = InterlockedIncrement(&recordNumber) - 1;
LogRecord* curRec = (LogRecord*)&logRecords[i % MaxRecords];
curRec->RecordId = i;
curRec->CurrentThread = (LPVOID)pthread_self();
curRec->RequestedAddress = requestedAddress;
curRec->ReturnedAddress = returnedAddress;
curRec->Size = size;
curRec->AllocationType = flAllocationType;
curRec->Protect = flProtect;
curRec->Operation = static_cast<DWORD>(operation) | (result ? 0 : FailedOperationMarker);
}
}
/*++
Function:
VIRTUALInitialize()
Initializes this section's critical section.
Return value:
TRUE if initialization succeeded
FALSE otherwise.
--*/
extern "C"
BOOL
VIRTUALInitialize(bool initializeExecutableMemoryAllocator)
{
TRACE("Initializing the Virtual Critical Sections. \n");
InternalInitializeCriticalSection(&virtual_critsec);
pVirtualMemory = NULL;
if (initializeExecutableMemoryAllocator)
{
g_executableMemoryAllocator.Initialize();
}
return TRUE;
}
/***
*
* VIRTUALCleanup()
* Deletes this section's critical section.
*
*/
extern "C"
void VIRTUALCleanup()
{
PCMI pEntry;
PCMI pTempEntry;
CPalThread * pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
// Clean up the allocated memory.
pEntry = pVirtualMemory;
while ( pEntry )
{
WARN( "The memory at %d was not freed through a call to VirtualFree.\n",
pEntry->startBoundary );
free(pEntry->pAllocState);
free(pEntry->pProtectionState );
pTempEntry = pEntry;
pEntry = pEntry->pNext;
free(pTempEntry );
}
pVirtualMemory = NULL;
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
TRACE( "Deleting the Virtual Critical Sections. \n" );
DeleteCriticalSection( &virtual_critsec );
}
/***
*
* VIRTUALContainsInvalidProtectionFlags()
* Returns TRUE if an invalid flag is specified. FALSE otherwise.
*/
static BOOL VIRTUALContainsInvalidProtectionFlags( IN DWORD flProtect )
{
if ( ( flProtect & ~( PAGE_NOACCESS | PAGE_READONLY |
PAGE_READWRITE | PAGE_EXECUTE | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE ) ) != 0 )
{
return TRUE;
}
else
{
return FALSE;
}
}
/****
*
* VIRTUALIsPageCommitted
*
* SIZE_T nBitToRetrieve - Which page to check.
*
* Returns TRUE if committed, FALSE otherwise.
*
*/
static BOOL VIRTUALIsPageCommitted( SIZE_T nBitToRetrieve, CONST PCMI pInformation )
{
SIZE_T nByteOffset = 0;
UINT nBitOffset = 0;
UINT byteMask = 0;
if ( !pInformation )
{
ERROR( "pInformation was NULL!\n" );
return FALSE;
}
nByteOffset = nBitToRetrieve / CHAR_BIT;
nBitOffset = nBitToRetrieve % CHAR_BIT;
byteMask = 1 << nBitOffset;
if ( pInformation->pAllocState[ nByteOffset ] & byteMask )
{
return TRUE;
}
else
{
return FALSE;
}
}
/*********
*
* VIRTUALGetAllocationType
*
* IN SIZE_T Index - The page within the range to retrieve
* the state for.
*
* IN pInformation - The virtual memory object.
*
*/
static INT VIRTUALGetAllocationType( SIZE_T Index, CONST PCMI pInformation )
{
if ( VIRTUALIsPageCommitted( Index, pInformation ) )
{
return MEM_COMMIT;
}
else
{
return MEM_RESERVE;
}
}
/****
*
* VIRTUALSetPageBits
*
* IN UINT nStatus - Bit set / reset [0: reset, any other value: set].
* IN SIZE_T nStartingBit - The bit to set.
*
* IN SIZE_T nNumberOfBits - The range of bits to set.
* IN BYTE* pBitArray - A pointer the array to be manipulated.
*
* Returns TRUE on success, FALSE otherwise.
* Turn on/off memory status bits.
*
*/
static BOOL VIRTUALSetPageBits ( UINT nStatus, SIZE_T nStartingBit,
SIZE_T nNumberOfBits, BYTE * pBitArray )
{
/* byte masks for optimized modification of partial bytes (changing less
than 8 bits in a single byte). note that bits are treated in little
endian order : value 1 is bit 0; value 128 is bit 7. in the binary
representations below, bit 0 is on the right */
/* start masks : for modifying bits >= n while preserving bits < n.
example : if nStartignBit%8 is 3, then bits 0, 1, 2 remain unchanged
while bits 3..7 are changed; startmasks[3] can be used for this. */
static const BYTE startmasks[8] = {
0xff, /* start at 0 : 1111 1111 */
0xfe, /* start at 1 : 1111 1110 */
0xfc, /* start at 2 : 1111 1100 */
0xf8, /* start at 3 : 1111 1000 */
0xf0, /* start at 4 : 1111 0000 */
0xe0, /* start at 5 : 1110 0000 */
0xc0, /* start at 6 : 1100 0000 */
0x80 /* start at 7 : 1000 0000 */
};
/* end masks : for modifying bits <= n while preserving bits > n.
example : if the last bit to change is 5, then bits 6 & 7 stay unchanged
while bits 1..5 are changed; endmasks[5] can be used for this. */
static const BYTE endmasks[8] = {
0x01, /* end at 0 : 0000 0001 */
0x03, /* end at 1 : 0000 0011 */
0x07, /* end at 2 : 0000 0111 */
0x0f, /* end at 3 : 0000 1111 */
0x1f, /* end at 4 : 0001 1111 */
0x3f, /* end at 5 : 0011 1111 */
0x7f, /* end at 6 : 0111 1111 */
0xff /* end at 7 : 1111 1111 */
};
/* last example : if only the middle of a byte must be changed, both start
and end masks can be combined (bitwise AND) to obtain the correct mask.
if we want to change bits 2 to 4 :
startmasks[2] : 0xfc 1111 1100 (change 2,3,4,5,6,7)
endmasks[4]: 0x1f 0001 1111 (change 0,1,2,3,4)
bitwise AND : 0x1c 0001 1100 (change 2,3,4)
*/
BYTE byte_mask;
SIZE_T nLastBit;
SIZE_T nFirstByte;
SIZE_T nLastByte;
SIZE_T nFullBytes;
TRACE( "VIRTUALSetPageBits( nStatus = %d, nStartingBit = %d, "
"nNumberOfBits = %d, pBitArray = 0x%p )\n",
nStatus, nStartingBit, nNumberOfBits, pBitArray );
if ( 0 == nNumberOfBits )
{
ERROR( "nNumberOfBits was 0!\n" );
return FALSE;
}
nLastBit = nStartingBit+nNumberOfBits-1;
nFirstByte = nStartingBit / 8;
nLastByte = nLastBit / 8;
/* handle partial first byte (if any) */
if(0 != (nStartingBit % 8))
{
byte_mask = startmasks[nStartingBit % 8];
/* if 1st byte is the only changing byte, combine endmask to preserve
trailing bits (see 3rd example above) */
if( nLastByte == nFirstByte)
{
byte_mask &= endmasks[nLastBit % 8];
}
/* byte_mask contains 1 for bits to change, 0 for bits to leave alone */
if(0 == nStatus)
{
/* bits to change must be set to 0 : invert byte_mask (giving 0 for
bits to change), use bitwise AND */
pBitArray[nFirstByte] &= ~byte_mask;
}
else
{
/* bits to change must be set to 1 : use bitwise OR */
pBitArray[nFirstByte] |= byte_mask;
}
/* stop right away if only 1 byte is being modified */
if(nLastByte == nFirstByte)
{
return TRUE;
}
/* we're done with the 1st byte; skip over it */
nFirstByte++;
}
/* number of bytes to change, excluding the last byte (handled separately)*/
nFullBytes = nLastByte - nFirstByte;
if(0 != nFullBytes)
{
// Turn off/on dirty bits
memset( &(pBitArray[nFirstByte]), (0 == nStatus) ? 0 : 0xFF, nFullBytes );
}
/* handle last (possibly partial) byte */
byte_mask = endmasks[nLastBit % 8];
/* byte_mask contains 1 for bits to change, 0 for bits to leave alone */
if(0 == nStatus)
{
/* bits to change must be set to 0 : invert byte_mask (giving 0 for
bits to change), use bitwise AND */
pBitArray[nLastByte] &= ~byte_mask;
}
else
{
/* bits to change must be set to 1 : use bitwise OR */
pBitArray[nLastByte] |= byte_mask;
}
return TRUE;
}
/****
*
* VIRTUALSetAllocState
*
* IN UINT nAction - Which action to perform.
* IN SIZE_T nStartingBit - The bit to set.
*
* IN SIZE_T nNumberOfBits - The range of bits to set.
* IN PCMI pStateArray - A pointer the array to be manipulated.
*
* Returns TRUE on success, FALSE otherwise.
* Turn bit on to indicate committed, turn bit off to indicate reserved.
*
*/
static BOOL VIRTUALSetAllocState( UINT nAction, SIZE_T nStartingBit,
SIZE_T nNumberOfBits, CONST PCMI pInformation )
{
TRACE( "VIRTUALSetAllocState( nAction = %d, nStartingBit = %d, "
"nNumberOfBits = %d, pStateArray = 0x%p )\n",
nAction, nStartingBit, nNumberOfBits, pInformation );
if ( !pInformation )
{
ERROR( "pInformation was invalid!\n" );
return FALSE;
}
return VIRTUALSetPageBits((MEM_COMMIT == nAction) ? 1 : 0, nStartingBit,
nNumberOfBits, pInformation->pAllocState);
}
/****
*
* VIRTUALFindRegionInformation( )
*
* IN UINT_PTR address - The address to look for.
*
* Returns the PCMI if found, NULL otherwise.
*/
static PCMI VIRTUALFindRegionInformation( IN UINT_PTR address )
{
PCMI pEntry = NULL;
TRACE( "VIRTUALFindRegionInformation( %#x )\n", address );
pEntry = pVirtualMemory;
while( pEntry )
{
if ( pEntry->startBoundary > address )
{
/* Gone past the possible location in the list. */
pEntry = NULL;
break;
}
if ( pEntry->startBoundary + pEntry->memSize > address )
{
break;
}
pEntry = pEntry->pNext;
}
return pEntry;
}
/*++
Function :
VIRTUALReleaseMemory
Removes a PCMI entry from the list.
Returns true on success. FALSE otherwise.
--*/
static BOOL VIRTUALReleaseMemory( PCMI pMemoryToBeReleased )
{
BOOL bRetVal = TRUE;
if ( !pMemoryToBeReleased )
{
ASSERT( "Invalid pointer.\n" );
return FALSE;
}
if ( pMemoryToBeReleased == pVirtualMemory )
{
/* This is either the first entry, or the only entry. */
pVirtualMemory = pMemoryToBeReleased->pNext;
if ( pMemoryToBeReleased->pNext )
{
pMemoryToBeReleased->pNext->pPrevious = NULL;
}
}
else /* Could be anywhere in the list. */
{
/* Delete the entry from the linked list. */
if ( pMemoryToBeReleased->pPrevious )
{
pMemoryToBeReleased->pPrevious->pNext = pMemoryToBeReleased->pNext;
}
if ( pMemoryToBeReleased->pNext )
{
pMemoryToBeReleased->pNext->pPrevious = pMemoryToBeReleased->pPrevious;
}
}
free( pMemoryToBeReleased->pAllocState );
pMemoryToBeReleased->pAllocState = NULL;
free( pMemoryToBeReleased->pProtectionState );
pMemoryToBeReleased->pProtectionState = NULL;
free( pMemoryToBeReleased );
pMemoryToBeReleased = NULL;
return bRetVal;
}
/****
* VIRTUALConvertWinFlags() -
* Converts win32 protection flags to
* internal VIRTUAL flags.
*
*/
static BYTE VIRTUALConvertWinFlags( IN DWORD flProtect )
{
BYTE MemAccessControl = 0;
switch ( flProtect & 0xff )
{
case PAGE_NOACCESS :
MemAccessControl = VIRTUAL_NOACCESS;
break;
case PAGE_READONLY :
MemAccessControl = VIRTUAL_READONLY;
break;
case PAGE_READWRITE :
MemAccessControl = VIRTUAL_READWRITE;
break;
case PAGE_EXECUTE :
MemAccessControl = VIRTUAL_EXECUTE;
break;
case PAGE_EXECUTE_READ :
MemAccessControl = VIRTUAL_EXECUTE_READ;
break;
case PAGE_EXECUTE_READWRITE:
MemAccessControl = VIRTUAL_EXECUTE_READWRITE;
break;
default :
MemAccessControl = 0;
ERROR( "Incorrect or no protection flags specified.\n" );
break;
}
return MemAccessControl;
}
/****
* VIRTUALConvertVirtualFlags() -
* Converts internal virtual protection
* flags to their win32 counterparts.
*/
static DWORD VIRTUALConvertVirtualFlags( IN BYTE VirtualProtect )
{
DWORD MemAccessControl = 0;
if ( VirtualProtect == VIRTUAL_READONLY )
{
MemAccessControl = PAGE_READONLY;
}
else if ( VirtualProtect == VIRTUAL_READWRITE )
{
MemAccessControl = PAGE_READWRITE;
}
else if ( VirtualProtect == VIRTUAL_EXECUTE_READWRITE )
{
MemAccessControl = PAGE_EXECUTE_READWRITE;
}
else if ( VirtualProtect == VIRTUAL_EXECUTE_READ )
{
MemAccessControl = PAGE_EXECUTE_READ;
}
else if ( VirtualProtect == VIRTUAL_EXECUTE )
{
MemAccessControl = PAGE_EXECUTE;
}
else if ( VirtualProtect == VIRTUAL_NOACCESS )
{
MemAccessControl = PAGE_NOACCESS;
}
else
{
MemAccessControl = 0;
ERROR( "Incorrect or no protection flags specified.\n" );
}
return MemAccessControl;
}
/***
* Displays the linked list.
*
*/
#if defined _DEBUG
static void VIRTUALDisplayList( void )
{
if (!DBG_ENABLED(DLI_TRACE, defdbgchan))
return;
PCMI p;
SIZE_T count;
SIZE_T index;
CPalThread * pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
p = pVirtualMemory;
count = 0;
while ( p ) {
DBGOUT( "Entry %d : \n", count );
DBGOUT( "\t startBoundary %#x \n", p->startBoundary );
DBGOUT( "\t memSize %d \n", p->memSize );
DBGOUT( "\t pAllocState " );
for ( index = 0; index < p->memSize / VIRTUAL_PAGE_SIZE; index++)
{
DBGOUT( "[%d] ", VIRTUALGetAllocationType( index, p ) );
}
DBGOUT( "\t pProtectionState " );
for ( index = 0; index < p->memSize / VIRTUAL_PAGE_SIZE; index++ )
{
DBGOUT( "[%d] ", (UINT)p->pProtectionState[ index ] );
}
DBGOUT( "\n" );
DBGOUT( "\t accessProtection %d \n", p->accessProtection );
DBGOUT( "\t allocationType %d \n", p->allocationType );
DBGOUT( "\t pNext %p \n", p->pNext );
DBGOUT( "\t pLast %p \n", p->pPrevious );
count++;
p = p->pNext;
}
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
}
#endif
#ifdef DEBUG
void VerifyRightEntry(PCMI pEntry)
{
volatile PCMI pRight = pEntry->pNext;
SIZE_T endAddress;
if (pRight != nullptr)
{
endAddress = ((SIZE_T)pEntry->startBoundary) + pEntry->memSize;
_ASSERTE(endAddress <= (SIZE_T)pRight->startBoundary);
}
}
void VerifyLeftEntry(PCMI pEntry)
{
volatile PCMI pLeft = pEntry->pPrevious;
SIZE_T endAddress;
if (pLeft != NULL)
{
endAddress = ((SIZE_T)pLeft->startBoundary) + pLeft->memSize;
_ASSERTE(endAddress <= (SIZE_T)pEntry->startBoundary);
}
}
#endif // DEBUG
/****
* VIRTUALStoreAllocationInfo()
*
* Stores the allocation information in the linked list.
* NOTE: The caller must own the critical section.
*/
static BOOL VIRTUALStoreAllocationInfo(
IN UINT_PTR startBoundary, /* Start of the region. */
IN SIZE_T memSize, /* Size of the region. */
IN DWORD flAllocationType, /* Allocation Types. */
IN DWORD flProtection ) /* Protections flags on the memory. */
{
PCMI pNewEntry = nullptr;
PCMI pMemInfo = nullptr;
SIZE_T nBufferSize = 0;
if ((memSize & VIRTUAL_PAGE_MASK) != 0)
{
ERROR("The memory size was not a multiple of the page size. \n");
return FALSE;
}
if (!(pNewEntry = (PCMI)InternalMalloc(sizeof(*pNewEntry))))
{
ERROR( "Unable to allocate memory for the structure.\n");
return FALSE;
}
pNewEntry->startBoundary = startBoundary;
pNewEntry->memSize = memSize;
pNewEntry->allocationType = flAllocationType;
pNewEntry->accessProtection = flProtection;
nBufferSize = memSize / VIRTUAL_PAGE_SIZE / CHAR_BIT;
if ((memSize / VIRTUAL_PAGE_SIZE) % CHAR_BIT != 0)
{
nBufferSize++;
}
pNewEntry->pAllocState = (BYTE*)InternalMalloc(nBufferSize);
pNewEntry->pProtectionState = (BYTE*)InternalMalloc((memSize / VIRTUAL_PAGE_SIZE));
if (pNewEntry->pAllocState && pNewEntry->pProtectionState)
{
/* Set the intial allocation state, and initial allocation protection. */
VIRTUALSetAllocState(MEM_RESERVE, 0, nBufferSize * CHAR_BIT, pNewEntry);
memset(pNewEntry->pProtectionState,
VIRTUALConvertWinFlags(flProtection),
memSize / VIRTUAL_PAGE_SIZE);
}
else
{
ERROR( "Unable to allocate memory for the structure.\n");
if (pNewEntry->pProtectionState) free(pNewEntry->pProtectionState);
pNewEntry->pProtectionState = nullptr;
if (pNewEntry->pAllocState) free(pNewEntry->pAllocState);
pNewEntry->pAllocState = nullptr;
free(pNewEntry);
pNewEntry = nullptr;
return FALSE;
}
pMemInfo = pVirtualMemory;
if (pMemInfo && pMemInfo->startBoundary < startBoundary)
{
/* Look for the correct insert point */
TRACE("Looking for the correct insert location.\n");
while (pMemInfo->pNext && (pMemInfo->pNext->startBoundary < startBoundary))
{
pMemInfo = pMemInfo->pNext;
}
pNewEntry->pNext = pMemInfo->pNext;
pNewEntry->pPrevious = pMemInfo;
if (pNewEntry->pNext)
{
pNewEntry->pNext->pPrevious = pNewEntry;
}
pMemInfo->pNext = pNewEntry;
}
else
{
/* This is the first entry in the list. */
pNewEntry->pNext = pMemInfo;
pNewEntry->pPrevious = nullptr;
if (pNewEntry->pNext)
{
pNewEntry->pNext->pPrevious = pNewEntry;
}
pVirtualMemory = pNewEntry ;
}
#ifdef DEBUG
VerifyRightEntry(pNewEntry);
VerifyLeftEntry(pNewEntry);
#endif // DEBUG
return TRUE;
}
/******
*
* VIRTUALReserveMemory() - Helper function that actually reserves the memory.
*
* NOTE: I call SetLastError in here, because many different error states
* exists, and that would be very complicated to work around.
*
*/
static LPVOID VIRTUALReserveMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize, /* Size of Region */
IN DWORD flAllocationType, /* Type of allocation */
IN DWORD flProtect) /* Type of access protection */
{
LPVOID pRetVal = NULL;
UINT_PTR StartBoundary;
SIZE_T MemSize;
TRACE( "Reserving the memory now..\n");
// First, figure out where we're trying to reserve the memory and
// how much we need. On most systems, requests to mmap must be
// page-aligned and at multiples of the page size.
StartBoundary = (UINT_PTR)lpAddress & ~BOUNDARY_64K;
/* Add the sizes, and round down to the nearest page boundary. */
MemSize = ( ((UINT_PTR)lpAddress + dwSize + VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK ) -
StartBoundary;
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
// If this is a request for special executable (JIT'ed) memory then, first of all,
// try to get memory from the executable memory allocator to satisfy the request.
if (((flAllocationType & MEM_RESERVE_EXECUTABLE) != 0) && (lpAddress == NULL))
{
pRetVal = g_executableMemoryAllocator.AllocateMemory(MemSize);
}
if (pRetVal == NULL)
{
// Try to reserve memory from the OS
pRetVal = ReserveVirtualMemory(pthrCurrent, (LPVOID)StartBoundary, MemSize);
}
if (pRetVal != NULL)
{
if ( !lpAddress )
{
/* Compute the real values instead of the null values. */
StartBoundary = (UINT_PTR)pRetVal & ~VIRTUAL_PAGE_MASK;
MemSize = ( ((UINT_PTR)pRetVal + dwSize + VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK ) -
StartBoundary;
}
if ( !VIRTUALStoreAllocationInfo( StartBoundary, MemSize,
flAllocationType, flProtect ) )
{
ASSERT( "Unable to store the structure in the list.\n");
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
munmap( pRetVal, MemSize );
pRetVal = NULL;
}
}
LogVaOperation(
VirtualMemoryLogging::VirtualOperation::Reserve,
lpAddress,
dwSize,
flAllocationType,
flProtect,
pRetVal,
pRetVal != NULL);
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
return pRetVal;
}
/******
*
* ReserveVirtualMemory() - Helper function that is used by Virtual* APIs
* and ExecutableMemoryAllocator to reserve virtual memory from the OS.
*
*/
static LPVOID ReserveVirtualMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize) /* Size of Region */
{
UINT_PTR StartBoundary = (UINT_PTR)lpAddress;
SIZE_T MemSize = dwSize;
TRACE( "Reserving the memory now.\n");
// Most platforms will only commit memory if it is dirtied,
// so this should not consume too much swap space.
int mmapFlags = 0;
#if HAVE_VM_ALLOCATE
// Allocate with vm_allocate first, then map at the fixed address.
int result = vm_allocate(mach_task_self(),
&StartBoundary,
MemSize,
((LPVOID) StartBoundary != nullptr) ? FALSE : TRUE);
if (result != KERN_SUCCESS)
{
ERROR("vm_allocate failed to allocated the requested region!\n");
pthrCurrent->SetLastError(ERROR_INVALID_ADDRESS);
return nullptr;
}
mmapFlags |= MAP_FIXED;
#endif // HAVE_VM_ALLOCATE
mmapFlags |= MAP_ANON | MAP_PRIVATE;
LPVOID pRetVal = mmap((LPVOID) StartBoundary,
MemSize,
PROT_NONE,
mmapFlags,
-1 /* fd */,
0 /* offset */);
if (pRetVal == MAP_FAILED)
{
ERROR( "Failed due to insufficient memory.\n" );
#if HAVE_VM_ALLOCATE
vm_deallocate(mach_task_self(), StartBoundary, MemSize);
#endif // HAVE_VM_ALLOCATE
pthrCurrent->SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
/* Check to see if the region is what we asked for. */
if (lpAddress != nullptr && StartBoundary != (UINT_PTR)pRetVal)
{
ERROR("We did not get the region we asked for from mmap!\n");
pthrCurrent->SetLastError(ERROR_INVALID_ADDRESS);
munmap(pRetVal, MemSize);
return nullptr;
}
#if MMAP_ANON_IGNORES_PROTECTION
if (mprotect(pRetVal, MemSize, PROT_NONE) != 0)
{
ERROR("mprotect failed to protect the region!\n");
pthrCurrent->SetLastError(ERROR_INVALID_ADDRESS);
munmap(pRetVal, MemSize);
return nullptr;
}
#endif // MMAP_ANON_IGNORES_PROTECTION
return pRetVal;
}
/******
*
* VIRTUALCommitMemory() - Helper function that actually commits the memory.
*
* NOTE: I call SetLastError in here, because many different error states
* exists, and that would be very complicated to work around.
*
*/
static LPVOID
VIRTUALCommitMemory(
IN CPalThread *pthrCurrent, /* Currently executing thread */
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize, /* Size of Region */
IN DWORD flAllocationType, /* Type of allocation */
IN DWORD flProtect) /* Type of access protection */
{
UINT_PTR StartBoundary = 0;
SIZE_T MemSize = 0;
PCMI pInformation = 0;
LPVOID pRetVal = NULL;
BOOL IsLocallyReserved = FALSE;
SIZE_T totalPages;
INT allocationType, curAllocationType;
INT protectionState, curProtectionState;
SIZE_T initialRunStart;
SIZE_T runStart;
SIZE_T runLength;
SIZE_T index;
INT nProtect;
INT vProtect;
if ( lpAddress )
{
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
/* Add the sizes, and round down to the nearest page boundary. */
MemSize = ( ((UINT_PTR)lpAddress + dwSize + VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK ) -
StartBoundary;
}
else
{
MemSize = ( dwSize + VIRTUAL_PAGE_MASK ) & ~VIRTUAL_PAGE_MASK;
}
/* See if we have already reserved this memory. */
pInformation = VIRTUALFindRegionInformation( StartBoundary );
if ( !pInformation )
{
/* According to the new MSDN docs, if MEM_COMMIT is specified,
and the memory is not reserved, you reserve and then commit.
*/
LPVOID pReservedMemory =
VIRTUALReserveMemory( pthrCurrent, lpAddress, dwSize,
flAllocationType, flProtect );
TRACE( "Reserve and commit the memory!\n " );
if ( pReservedMemory )
{
/* Re-align the addresses and try again to find the memory. */
StartBoundary = (UINT_PTR)pReservedMemory & ~VIRTUAL_PAGE_MASK;
MemSize = ( ((UINT_PTR)pReservedMemory + dwSize + VIRTUAL_PAGE_MASK)
& ~VIRTUAL_PAGE_MASK ) - StartBoundary;
pInformation = VIRTUALFindRegionInformation( StartBoundary );
if ( !pInformation )
{
ASSERT( "Unable to locate the region information.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
pRetVal = NULL;
goto done;
}
IsLocallyReserved = TRUE;
}
else
{
ERROR( "Unable to reserve the memory.\n" );
/* Don't set last error here, it will already be set. */
pRetVal = NULL;
goto done;
}
}
TRACE( "Committing the memory now..\n");
// Pages that aren't already committed need to be committed. Pages that
// are committed don't need to be committed, but they might need to have
// their permissions changed.
// To get this right, we find runs of pages with similar states and
// permissions. If a run is not committed, we commit it and then set
// its permissions. If a run is committed but has different permissions
// from what we're trying to set, we set its permissions. Finally,
// if a run is already committed and has the right permissions,
// we don't need to do anything to it.
totalPages = MemSize / VIRTUAL_PAGE_SIZE;
runStart = (StartBoundary - pInformation->startBoundary) /
VIRTUAL_PAGE_SIZE; // Page index
initialRunStart = runStart;
allocationType = VIRTUALGetAllocationType(runStart, pInformation);
protectionState = pInformation->pProtectionState[runStart];
curAllocationType = allocationType;
curProtectionState = protectionState;
runLength = 1;
nProtect = W32toUnixAccessControl(flProtect);
vProtect = VIRTUALConvertWinFlags(flProtect);
if (totalPages > pInformation->memSize / VIRTUAL_PAGE_SIZE - runStart)
{
ERROR("Trying to commit beyond the end of the region!\n");
goto error;
}
while(runStart < initialRunStart + totalPages)
{
// Find the next run of pages
for(index = runStart + 1; index < initialRunStart + totalPages;
index++)
{
curAllocationType = VIRTUALGetAllocationType(index, pInformation);
curProtectionState = pInformation->pProtectionState[index];
if (curAllocationType != allocationType ||
curProtectionState != protectionState)
{
break;
}
runLength++;
}
StartBoundary = pInformation->startBoundary + runStart * VIRTUAL_PAGE_SIZE;
MemSize = runLength * VIRTUAL_PAGE_SIZE;
if (allocationType != MEM_COMMIT)
{
// Commit the pages
if (mprotect((void *) StartBoundary, MemSize, PROT_WRITE | PROT_READ) != 0)
{
ERROR("mprotect() failed! Error(%d)=%s\n", errno, strerror(errno));
goto error;
}
VIRTUALSetAllocState(MEM_COMMIT, runStart, runLength, pInformation);
if (nProtect == (PROT_WRITE | PROT_READ))
{
// Handle this case specially so we don't bother
// mprotect'ing the region.
memset(pInformation->pProtectionState + runStart,
vProtect, runLength);
}
protectionState = VIRTUAL_READWRITE;
}
if (protectionState != vProtect)
{
// Change permissions.
if (mprotect((void *) StartBoundary, MemSize, nProtect) != -1)
{
memset(pInformation->pProtectionState + runStart,
vProtect, runLength);
}
else
{
ERROR("mprotect() failed! Error(%d)=%s\n",
errno, strerror(errno));
goto error;
}
}
runStart = index;
runLength = 1;
allocationType = curAllocationType;
protectionState = curProtectionState;
}
pRetVal = (void *) (pInformation->startBoundary + initialRunStart * VIRTUAL_PAGE_SIZE);
goto done;
error:
if ( flAllocationType & MEM_RESERVE || IsLocallyReserved )
{
munmap( pRetVal, MemSize );
if ( VIRTUALReleaseMemory( pInformation ) == FALSE )
{
ASSERT( "Unable to remove the PCMI entry from the list.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
pRetVal = NULL;
goto done;
}
pInformation = NULL;
pRetVal = NULL;
}
done:
LogVaOperation(
VirtualMemoryLogging::VirtualOperation::Commit,
lpAddress,
dwSize,
flAllocationType,
flProtect,
pRetVal,
pRetVal != NULL);
return pRetVal;
}
/*++
Function:
VirtualAlloc
Note:
MEM_TOP_DOWN, MEM_PHYSICAL, MEM_WRITE_WATCH are not supported.
Unsupported flags are ignored.
Page size on i386 is set to 4k.
See MSDN doc.
--*/
LPVOID
PALAPI
VirtualAlloc(
IN LPVOID lpAddress, /* Region to reserve or commit */
IN SIZE_T dwSize, /* Size of Region */
IN DWORD flAllocationType, /* Type of allocation */
IN DWORD flProtect) /* Type of access protection */
{
LPVOID pRetVal = NULL;
CPalThread *pthrCurrent;
PERF_ENTRY(VirtualAlloc);
ENTRY("VirtualAlloc(lpAddress=%p, dwSize=%u, flAllocationType=%#x, \
flProtect=%#x)\n", lpAddress, dwSize, flAllocationType, flProtect);
pthrCurrent = InternalGetCurrentThread();
if ( ( flAllocationType & MEM_WRITE_WATCH ) != 0 )
{
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
goto done;
}
/* Test for un-supported flags. */
if ( ( flAllocationType & ~( MEM_COMMIT | MEM_RESERVE | MEM_TOP_DOWN | MEM_RESERVE_EXECUTABLE ) ) != 0 )
{
ASSERT( "flAllocationType can be one, or any combination of MEM_COMMIT, \
MEM_RESERVE, MEM_TOP_DOWN, or MEM_RESERVE_EXECUTABLE.\n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
goto done;
}
if ( VIRTUALContainsInvalidProtectionFlags( flProtect ) )
{
ASSERT( "flProtect can be one of PAGE_READONLY, PAGE_READWRITE, or \
PAGE_EXECUTE_READWRITE || PAGE_NOACCESS. \n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
goto done;
}
if ( flAllocationType & MEM_TOP_DOWN )
{
WARN( "Ignoring the allocation flag MEM_TOP_DOWN.\n" );
}
LogVaOperation(
VirtualMemoryLogging::VirtualOperation::Allocate,
lpAddress,
dwSize,
flAllocationType,
flProtect,
NULL,
TRUE);
if ( flAllocationType & MEM_RESERVE )
{
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
pRetVal = VIRTUALReserveMemory( pthrCurrent, lpAddress, dwSize, flAllocationType, flProtect );
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
if ( !pRetVal )
{
/* Error messages are already displayed, just leave. */
goto done;
}
}
if ( flAllocationType & MEM_COMMIT )
{
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
if ( pRetVal != NULL )
{
/* We are reserving and committing. */
pRetVal = VIRTUALCommitMemory( pthrCurrent, pRetVal, dwSize,
flAllocationType, flProtect );
}
else
{
/* Just a commit. */
pRetVal = VIRTUALCommitMemory( pthrCurrent, lpAddress, dwSize,
flAllocationType, flProtect );
}
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
}
done:
#if defined _DEBUG
VIRTUALDisplayList();
#endif
LOGEXIT("VirtualAlloc returning %p\n ", pRetVal );
PERF_EXIT(VirtualAlloc);
return pRetVal;
}
/*++
Function:
VirtualFree
See MSDN doc.
--*/
BOOL
PALAPI
VirtualFree(
IN LPVOID lpAddress, /* Address of region. */
IN SIZE_T dwSize, /* Size of region. */
IN DWORD dwFreeType ) /* Operation type. */
{
BOOL bRetVal = TRUE;
CPalThread *pthrCurrent;
PERF_ENTRY(VirtualFree);
ENTRY("VirtualFree(lpAddress=%p, dwSize=%u, dwFreeType=%#x)\n",
lpAddress, dwSize, dwFreeType);
pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
/* Sanity Checks. */
if ( !lpAddress )
{
ERROR( "lpAddress cannot be NULL. You must specify the base address of\
regions to be de-committed. \n" );
pthrCurrent->SetLastError( ERROR_INVALID_ADDRESS );
bRetVal = FALSE;
goto VirtualFreeExit;
}
if ( !( dwFreeType & MEM_RELEASE ) && !(dwFreeType & MEM_DECOMMIT ) )
{
ERROR( "dwFreeType must contain one of the following: \
MEM_RELEASE or MEM_DECOMMIT\n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
bRetVal = FALSE;
goto VirtualFreeExit;
}
/* You cannot release and decommit in one call.*/
if ( dwFreeType & MEM_RELEASE && dwFreeType & MEM_DECOMMIT )
{
ERROR( "MEM_RELEASE cannot be combined with MEM_DECOMMIT.\n" );
bRetVal = FALSE;
goto VirtualFreeExit;
}
if ( dwFreeType & MEM_DECOMMIT )
{
UINT_PTR StartBoundary = 0;
SIZE_T MemSize = 0;
if ( dwSize == 0 )
{
ERROR( "dwSize cannot be 0. \n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
bRetVal = FALSE;
goto VirtualFreeExit;
}
/*
* A two byte range straddling 2 pages caues both pages to be either
* released or decommitted. So round the dwSize up to the next page
* boundary and round the lpAddress down to the next page boundary.
*/
MemSize = (((UINT_PTR)(dwSize) + ((UINT_PTR)(lpAddress) & VIRTUAL_PAGE_MASK)
+ VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK);
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
PCMI pUnCommittedMem;
pUnCommittedMem = VIRTUALFindRegionInformation( StartBoundary );
if (!pUnCommittedMem)
{
ASSERT( "Unable to locate the region information.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
bRetVal = FALSE;
goto VirtualFreeExit;
}
TRACE( "Un-committing the following page(s) %d to %d.\n",
StartBoundary, MemSize );
// Explicitly calling mmap instead of mprotect here makes it
// that much more clear to the operating system that we no
// longer need these pages.
if ( mmap( (LPVOID)StartBoundary, MemSize, PROT_NONE,
MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0 ) != MAP_FAILED )
{
#if (MMAP_ANON_IGNORES_PROTECTION)
if (mprotect((LPVOID) StartBoundary, MemSize, PROT_NONE) != 0)
{
ASSERT("mprotect failed to protect the region!\n");
pthrCurrent->SetLastError(ERROR_INTERNAL_ERROR);
munmap((LPVOID) StartBoundary, MemSize);
bRetVal = FALSE;
goto VirtualFreeExit;
}
#endif // MMAP_ANON_IGNORES_PROTECTION
SIZE_T index = 0;
SIZE_T nNumOfPagesToChange = 0;
/* We can now commit this memory by calling VirtualAlloc().*/
index = (StartBoundary - pUnCommittedMem->startBoundary) / VIRTUAL_PAGE_SIZE;
nNumOfPagesToChange = MemSize / VIRTUAL_PAGE_SIZE;
VIRTUALSetAllocState( MEM_RESERVE, index,
nNumOfPagesToChange, pUnCommittedMem );
goto VirtualFreeExit;
}
else
{
ASSERT( "mmap() returned an abnormal value.\n" );
bRetVal = FALSE;
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
goto VirtualFreeExit;
}
}
if ( dwFreeType & MEM_RELEASE )
{
PCMI pMemoryToBeReleased =
VIRTUALFindRegionInformation( (UINT_PTR)lpAddress );
if ( !pMemoryToBeReleased )
{
ERROR( "lpAddress must be the base address returned by VirtualAlloc.\n" );
pthrCurrent->SetLastError( ERROR_INVALID_ADDRESS );
bRetVal = FALSE;
goto VirtualFreeExit;
}
if ( dwSize != 0 )
{
ERROR( "dwSize must be 0 if you are releasing the memory.\n" );
pthrCurrent->SetLastError( ERROR_INVALID_PARAMETER );
bRetVal = FALSE;
goto VirtualFreeExit;
}
TRACE( "Releasing the following memory %d to %d.\n",
pMemoryToBeReleased->startBoundary, pMemoryToBeReleased->memSize );
if ( munmap( (LPVOID)pMemoryToBeReleased->startBoundary,
pMemoryToBeReleased->memSize ) == 0 )
{
if ( VIRTUALReleaseMemory( pMemoryToBeReleased ) == FALSE )
{
ASSERT( "Unable to remove the PCMI entry from the list.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
bRetVal = FALSE;
goto VirtualFreeExit;
}
pMemoryToBeReleased = NULL;
}
else
{
ASSERT( "Unable to unmap the memory, munmap() returned an abnormal value.\n" );
pthrCurrent->SetLastError( ERROR_INTERNAL_ERROR );
bRetVal = FALSE;
goto VirtualFreeExit;
}
}
VirtualFreeExit:
LogVaOperation(
(dwFreeType & MEM_DECOMMIT) ? VirtualMemoryLogging::VirtualOperation::Decommit
: VirtualMemoryLogging::VirtualOperation::Release,
lpAddress,
dwSize,
dwFreeType,
0,
NULL,
bRetVal);
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
LOGEXIT( "VirtualFree returning %s.\n", bRetVal == TRUE ? "TRUE" : "FALSE" );
PERF_EXIT(VirtualFree);
return bRetVal;
}
/*++
Function:
VirtualProtect
See MSDN doc.
--*/
BOOL
PALAPI
VirtualProtect(
IN LPVOID lpAddress,
IN SIZE_T dwSize,
IN DWORD flNewProtect,
OUT PDWORD lpflOldProtect)
{
BOOL bRetVal = FALSE;
PCMI pEntry = NULL;
SIZE_T MemSize = 0;
UINT_PTR StartBoundary = 0;
SIZE_T Index = 0;
SIZE_T NumberOfPagesToChange = 0;
SIZE_T OffSet = 0;
CPalThread * pthrCurrent;
PERF_ENTRY(VirtualProtect);
ENTRY("VirtualProtect(lpAddress=%p, dwSize=%u, flNewProtect=%#x, "
"flOldProtect=%p)\n",
lpAddress, dwSize, flNewProtect, lpflOldProtect);
pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
MemSize = (((UINT_PTR)(dwSize) + ((UINT_PTR)(lpAddress) & VIRTUAL_PAGE_MASK)
+ VIRTUAL_PAGE_MASK) & ~VIRTUAL_PAGE_MASK);
if ( VIRTUALContainsInvalidProtectionFlags( flNewProtect ) )
{
ASSERT( "flProtect can be one of PAGE_NOACCESS, PAGE_READONLY, "
"PAGE_READWRITE, PAGE_EXECUTE, PAGE_EXECUTE_READ "
", or PAGE_EXECUTE_READWRITE. \n" );
SetLastError( ERROR_INVALID_PARAMETER );
goto ExitVirtualProtect;
}
if ( !lpflOldProtect)
{
ERROR( "lpflOldProtect was invalid.\n" );
SetLastError( ERROR_NOACCESS );
goto ExitVirtualProtect;
}
pEntry = VIRTUALFindRegionInformation( StartBoundary );
if ( NULL != pEntry )
{
/* See if the pages are committed. */
Index = OffSet = StartBoundary - pEntry->startBoundary == 0 ?
0 : ( StartBoundary - pEntry->startBoundary ) / VIRTUAL_PAGE_SIZE;
NumberOfPagesToChange = MemSize / VIRTUAL_PAGE_SIZE;
TRACE( "Number of pages to check %d, starting page %d \n", NumberOfPagesToChange, Index );
for ( ; Index < NumberOfPagesToChange; Index++ )
{
if ( !VIRTUALIsPageCommitted( Index, pEntry ) )
{
ERROR( "You can only change the protection attributes"
" on committed memory.\n" )
SetLastError( ERROR_INVALID_ADDRESS );
goto ExitVirtualProtect;
}
}
}
if ( 0 == mprotect( (LPVOID)StartBoundary, MemSize,
W32toUnixAccessControl( flNewProtect ) ) )
{
/* Reset the access protection. */
TRACE( "Number of pages to change %d, starting page %d \n",
NumberOfPagesToChange, OffSet );
/*
* Set the old protection flags. We only use the first flag, so
* if there were several regions with each with different flags only the
* first region's protection flag will be returned.
*/
if ( pEntry )
{
*lpflOldProtect =
VIRTUALConvertVirtualFlags( pEntry->pProtectionState[ OffSet ] );
memset( pEntry->pProtectionState + OffSet,
VIRTUALConvertWinFlags( flNewProtect ),
NumberOfPagesToChange );
}
else
{
*lpflOldProtect = PAGE_EXECUTE_READWRITE;
}
bRetVal = TRUE;
}
else
{
ERROR( "%s\n", strerror( errno ) );
if ( errno == EINVAL )
{
SetLastError( ERROR_INVALID_ADDRESS );
}
else if ( errno == EACCES )
{
SetLastError( ERROR_INVALID_ACCESS );
}
}
ExitVirtualProtect:
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
#if defined _DEBUG
VIRTUALDisplayList();
#endif
LOGEXIT( "VirtualProtect returning %s.\n", bRetVal == TRUE ? "TRUE" : "FALSE" );
PERF_EXIT(VirtualProtect);
return bRetVal;
}
#if HAVE_VM_ALLOCATE
//---------------------------------------------------------------------------------------
//
// Convert a vm_prot_t flag on the Mach kernel to the corresponding memory protection on Windows.
//
// Arguments:
// protection - Mach protection to be converted
//
// Return Value:
// Return the corresponding memory protection on Windows (e.g. PAGE_READ_WRITE, etc.)
//
static DWORD VirtualMapMachProtectToWinProtect(vm_prot_t protection)
{
if (protection & VM_PROT_READ)
{
if (protection & VM_PROT_WRITE)
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE_READWRITE;
}
else
{
return PAGE_READWRITE;
}
}
else
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE_READ;
}
else
{
return PAGE_READONLY;
}
}
}
else
{
if (protection & VM_PROT_WRITE)
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE_WRITECOPY;
}
else
{
return PAGE_WRITECOPY;
}
}
else
{
if (protection & VM_PROT_EXECUTE)
{
return PAGE_EXECUTE;
}
else
{
return PAGE_NOACCESS;
}
}
}
}
static void VM_ALLOCATE_VirtualQuery(LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer)
{
kern_return_t MachRet;
vm_address_t vm_address;
vm_size_t vm_size;
vm_region_flavor_t vm_flavor;
mach_msg_type_number_t infoCnt;
mach_port_t object_name;
#ifdef BIT64
vm_region_basic_info_data_64_t info;
infoCnt = VM_REGION_BASIC_INFO_COUNT_64;
vm_flavor = VM_REGION_BASIC_INFO_64;
#else
vm_region_basic_info_data_t info;
infoCnt = VM_REGION_BASIC_INFO_COUNT;
vm_flavor = VM_REGION_BASIC_INFO;
#endif
vm_address = (vm_address_t)lpAddress;
#ifdef BIT64
MachRet = vm_region_64(
#else
MachRet = vm_region(
#endif
mach_task_self(),
&vm_address,
&vm_size,
vm_flavor,
(vm_region_info_t)&info,
&infoCnt,
&object_name);
if (MachRet != KERN_SUCCESS) {
return;
}
if (vm_address > (vm_address_t)lpAddress) {
/* lpAddress was pointing into a free region */
lpBuffer->State = MEM_FREE;
return;
}
lpBuffer->BaseAddress = (PVOID)vm_address;
// We don't actually have any information on the Mach kernel which maps to AllocationProtect.
lpBuffer->AllocationProtect = VM_PROT_NONE;
lpBuffer->RegionSize = (SIZE_T)vm_size;
if (info.reserved)
{
lpBuffer->State = MEM_RESERVE;
}
else
{
lpBuffer->State = MEM_COMMIT;
}
lpBuffer->Protect = VirtualMapMachProtectToWinProtect(info.protection);
/* Note that if a mapped region and a private region are adjacent, this
will return MEM_PRIVATE but the region size will span
both the mapped and private regions. */
if (!info.shared)
{
lpBuffer->Type = MEM_PRIVATE;
}
else
{
// What should this be? It's either MEM_MAPPED or MEM_IMAGE, but without an image list,
// we can't determine which one it is.
lpBuffer->Type = MEM_MAPPED;
}
}
#endif // HAVE_VM_ALLOCATE
/*++
Function:
VirtualQuery
See MSDN doc.
--*/
SIZE_T
PALAPI
VirtualQuery(
IN LPCVOID lpAddress,
OUT PMEMORY_BASIC_INFORMATION lpBuffer,
IN SIZE_T dwLength)
{
PCMI pEntry = NULL;
UINT_PTR StartBoundary = 0;
CPalThread * pthrCurrent;
PERF_ENTRY(VirtualQuery);
ENTRY("VirtualQuery(lpAddress=%p, lpBuffer=%p, dwLength=%u)\n",
lpAddress, lpBuffer, dwLength);
pthrCurrent = InternalGetCurrentThread();
InternalEnterCriticalSection(pthrCurrent, &virtual_critsec);
if ( !lpBuffer)
{
ERROR( "lpBuffer has to be a valid pointer.\n" );
pthrCurrent->SetLastError( ERROR_NOACCESS );
goto ExitVirtualQuery;
}
if ( dwLength < sizeof( *lpBuffer ) )
{
ERROR( "dwLength cannot be smaller then the size of *lpBuffer.\n" );
pthrCurrent->SetLastError( ERROR_BAD_LENGTH );
goto ExitVirtualQuery;
}
StartBoundary = (UINT_PTR)lpAddress & ~VIRTUAL_PAGE_MASK;
#if MMAP_IGNORES_HINT
// Make sure we have memory to map before we try to query it.
VIRTUALGetBackingFile(pthrCurrent);
// If we're suballocating, claim that any memory that isn't in our
// suballocated block is already allocated. This keeps callers from
// using these results to try to allocate those blocks and failing.
if (StartBoundary < (UINT_PTR) gBackingBaseAddress ||
StartBoundary >= (UINT_PTR) gBackingBaseAddress + BACKING_FILE_SIZE)
{
if (StartBoundary < (UINT_PTR) gBackingBaseAddress)
{
lpBuffer->RegionSize = (UINT_PTR) gBackingBaseAddress - StartBoundary;
}
else
{
lpBuffer->RegionSize = -StartBoundary;
}
lpBuffer->BaseAddress = (void *) StartBoundary;
lpBuffer->State = MEM_COMMIT;
lpBuffer->Type = MEM_MAPPED;
lpBuffer->AllocationProtect = 0;
lpBuffer->Protect = 0;
goto ExitVirtualQuery;
}
#endif // MMAP_IGNORES_HINT
/* Find the entry. */
pEntry = VIRTUALFindRegionInformation( StartBoundary );
if ( !pEntry )
{
/* Can't find a match, or no list present. */
/* Next, looking for this region in file maps */
if (!MAPGetRegionInfo((LPVOID)StartBoundary, lpBuffer))
{
// When all else fails, call vm_region() if it's available.
// Initialize the State to be MEM_FREE, in which case AllocationBase, AllocationProtect,
// Protect, and Type are all undefined.
lpBuffer->BaseAddress = (LPVOID)StartBoundary;
lpBuffer->RegionSize = 0;
lpBuffer->State = MEM_FREE;
#if HAVE_VM_ALLOCATE
VM_ALLOCATE_VirtualQuery(lpAddress, lpBuffer);
#endif
}
}
else
{
/* Starting page. */
SIZE_T Index = ( StartBoundary - pEntry->startBoundary ) / VIRTUAL_PAGE_SIZE;
/* Attributes to check for. */
BYTE AccessProtection = pEntry->pProtectionState[ Index ];
INT AllocationType = VIRTUALGetAllocationType( Index, pEntry );
SIZE_T RegionSize = 0;
TRACE( "Index = %d, Number of Pages = %d. \n",
Index, pEntry->memSize / VIRTUAL_PAGE_SIZE );
while ( Index < pEntry->memSize / VIRTUAL_PAGE_SIZE &&
VIRTUALGetAllocationType( Index, pEntry ) == AllocationType &&
pEntry->pProtectionState[ Index ] == AccessProtection )
{
RegionSize += VIRTUAL_PAGE_SIZE;
Index++;
}
TRACE( "RegionSize = %d.\n", RegionSize );
/* Fill the structure.*/
lpBuffer->AllocationProtect = pEntry->accessProtection;
lpBuffer->BaseAddress = (LPVOID)StartBoundary;
lpBuffer->Protect = AllocationType == MEM_COMMIT ?
VIRTUALConvertVirtualFlags( AccessProtection ) : 0;
lpBuffer->RegionSize = RegionSize;
lpBuffer->State =
( AllocationType == MEM_COMMIT ? MEM_COMMIT : MEM_RESERVE );
WARN( "Ignoring lpBuffer->Type. \n" );
}
ExitVirtualQuery:
InternalLeaveCriticalSection(pthrCurrent, &virtual_critsec);
LOGEXIT( "VirtualQuery returning %d.\n", sizeof( *lpBuffer ) );
PERF_EXIT(VirtualQuery);
return sizeof( *lpBuffer );
}
/*++
Function:
GetWriteWatch
See MSDN doc.
--*/
UINT
PALAPI
GetWriteWatch(
IN DWORD dwFlags,
IN PVOID lpBaseAddress,
IN SIZE_T dwRegionSize,
OUT PVOID *lpAddresses,
IN OUT PULONG_PTR lpdwCount,
OUT PULONG lpdwGranularity
)
{
// TODO: implement this method
*lpAddresses = NULL;
*lpdwCount = 0;
// Until it is implemented, return non-zero value as an indicator of failure
return 1;
}
/*++
Function:
ResetWriteWatch
See MSDN doc.
--*/
UINT
PALAPI
ResetWriteWatch(
IN LPVOID lpBaseAddress,
IN SIZE_T dwRegionSize
)
{
// TODO: implement this method
// Until it is implemented, return non-zero value as an indicator of failure
return 1;
}
/*++
Function :
ReserveMemoryFromExecutableAllocator
This function is used to reserve a region of virual memory (not commited)
that is located close to the coreclr library. The memory comes from the virtual
address range that is managed by ExecutableMemoryAllocator.
--*/
void* ReserveMemoryFromExecutableAllocator(CPalThread* pThread, SIZE_T allocationSize)
{
InternalEnterCriticalSection(pThread, &virtual_critsec);
void* mem = g_executableMemoryAllocator.AllocateMemory(allocationSize);
InternalLeaveCriticalSection(pThread, &virtual_critsec);
return mem;
}
/*++
Function:
ExecutableMemoryAllocator::Initialize()
This function initializes the allocator. It should be called early during process startup
(when process address space is pretty much empty) in order to have a chance to reserve
sufficient amount of memory that is close to the coreclr library.
--*/
void ExecutableMemoryAllocator::Initialize()
{
m_startAddress = NULL;
m_nextFreeAddress = NULL;
m_totalSizeOfReservedMemory = 0;
m_remainingReservedMemory = 0;
// Enable the executable memory allocator on 64-bit platforms only
// because 32-bit platforms have limited amount of virtual address space.
#ifdef BIT64
TryReserveInitialMemory();
#endif // BIT64
}
/*++
Function:
ExecutableMemoryAllocator::TryReserveInitialMemory()
This function is called during PAL initialization. It opportunistically tries to reserve
a large chunk of virtual memory that can be later used to store JIT'ed code.\
--*/
void ExecutableMemoryAllocator::TryReserveInitialMemory()
{
CPalThread* pthrCurrent = InternalGetCurrentThread();
int32_t sizeOfAllocation = MaxExecutableMemorySize;
int32_t startAddressIncrement;
UINT_PTR startAddress;
UINT_PTR coreclrLoadAddress;
const int32_t MemoryProbingIncrement = 128 * 1024 * 1024;
// Try to find and reserve an available region of virtual memory that is located
// within 2GB range (defined by the MaxExecutableMemorySize constant) from the
// location of the coreclr library.
// Potentially, as a possible future improvement, we can get precise information
// about available memory ranges by parsing data from '/proc/self/maps'.
// But since this code is called early during process startup, the user address space
// is pretty much empty so the simple algorithm that is implemented below is sufficient
// for this purpose.
// First of all, we need to determine the current address of libcoreclr. Please note that depending on
// the OS implementation, the library is usually loaded either at the end or at the start of the user
// address space. If the library is loaded at low addresses then try to reserve memory above libcoreclr
// (thus avoiding reserving memory below 4GB; besides some operating systems do not allow that).
// If libcoreclr is loaded at high addresses then try to reserve memory below its location.
coreclrLoadAddress = (UINT_PTR)PAL_GetSymbolModuleBase((void*)VirtualAlloc);
if ((coreclrLoadAddress < 0xFFFFFFFF) || ((coreclrLoadAddress - MaxExecutableMemorySize) < 0xFFFFFFFF))
{
// Try to allocate above the location of libcoreclr
startAddress = coreclrLoadAddress + CoreClrLibrarySize;
startAddressIncrement = MemoryProbingIncrement;
}
else
{
// Try to allocate below the location of libcoreclr
startAddress = coreclrLoadAddress - MaxExecutableMemorySize;
startAddressIncrement = 0;
}
// Do actual memory reservation.
do
{
m_startAddress = ReserveVirtualMemory(pthrCurrent, (void*)startAddress, sizeOfAllocation);
if (m_startAddress != NULL)
{
// Memory has been successfully reserved.
m_totalSizeOfReservedMemory = sizeOfAllocation;
// Randomize the location at which we start allocating from the reserved memory range.
int32_t randomOffset = GenerateRandomStartOffset();
m_nextFreeAddress = (void*)(((UINT_PTR)m_startAddress) + randomOffset);
m_remainingReservedMemory = sizeOfAllocation - randomOffset;
break;
}
// Try to allocate a smaller region
sizeOfAllocation -= MemoryProbingIncrement;
startAddress += startAddressIncrement;
} while (sizeOfAllocation >= MemoryProbingIncrement);
}
/*++
Function:
ExecutableMemoryAllocator::AllocateMemory
This function attempts to allocate the requested amount of memory from its reserved virtual
address space. The function will return NULL if the allocation request cannot
be satisfied by the memory that is currently available in the allocator.
Note: This function MUST be called with the virtual_critsec lock held.
--*/
void* ExecutableMemoryAllocator::AllocateMemory(SIZE_T allocationSize)
{
void* allocatedMemory = NULL;
// Allocation size must be in multiples of the virtual page size.
_ASSERTE((allocationSize & VIRTUAL_PAGE_MASK) == 0);
// The code below assumes that the caller owns the virtual_critsec lock.
// So the calculations are not done in thread-safe manner.
if ((allocationSize > 0) && (allocationSize <= m_remainingReservedMemory))
{
allocatedMemory = m_nextFreeAddress;
m_nextFreeAddress = (void*)(((UINT_PTR)m_nextFreeAddress) + allocationSize);
m_remainingReservedMemory -= allocationSize;
}
return allocatedMemory;
}
/*++
Function:
ExecutableMemoryAllocator::GenerateRandomStartOffset()
This function returns a random offset (in multiples of the virtual page size)
at which the allocator should start allocating memory from its reserved memory range.
--*/
int32_t ExecutableMemoryAllocator::GenerateRandomStartOffset()
{
int32_t pageCount;
const int32_t MaxStartPageOffset = 64;
// This code is similar to what coreclr runtime does on Windows.
// It generates a random number of pages to skip between 0...MaxStartPageOffset.
srandom(time(NULL));
pageCount = (int32_t)(MaxStartPageOffset * (int64_t)random() / RAND_MAX);
return pageCount * VIRTUAL_PAGE_SIZE;
}
| 30.198063 | 108 | 0.614474 | chrisaut |
4b5334791fd558dd47efd07d0e0f53ecfd1088e1 | 1,282 | cc | C++ | handy/port_posix.cc | onlyet/handy | 780548fc7433c7f3ec541b15a7e87efb996a7218 | [
"BSD-2-Clause"
] | 2 | 2018-04-27T15:32:37.000Z | 2019-12-27T13:04:58.000Z | handy/port_posix.cc | OnlYet/handy | 780548fc7433c7f3ec541b15a7e87efb996a7218 | [
"BSD-2-Clause"
] | 1 | 2018-11-13T06:41:51.000Z | 2018-11-13T06:41:51.000Z | handy/port_posix.cc | OnlYet/handy | 780548fc7433c7f3ec541b15a7e87efb996a7218 | [
"BSD-2-Clause"
] | null | null | null | #include "port_posix.h"
#include <netdb.h>
#include <pthread.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#define OS_LINUX
namespace handy {
namespace port {
#ifdef OS_LINUX
struct in_addr getHostByName(const std::string &host) {
struct in_addr addr;
char buf[1024];
struct hostent hent;
struct hostent *he = NULL;
int herrno = 0;
memset(&hent, 0, sizeof hent);
int r = gethostbyname_r(host.c_str(), &hent, buf, sizeof buf, &he, &herrno);
if (r == 0 && he && he->h_addrtype == AF_INET) {
addr = *reinterpret_cast<struct in_addr *>(he->h_addr);
} else {
addr.s_addr = INADDR_NONE;
}
return addr;
}
uint64_t gettid() {
return syscall(SYS_gettid);
}
#elif defined(OS_MACOSX)
struct in_addr getHostByName(const std::string &host) {
struct in_addr addr;
struct hostent *he = gethostbyname(host.c_str());
if (he && he->h_addrtype == AF_INET) {
addr = *reinterpret_cast<struct in_addr *>(he->h_addr);
} else {
addr.s_addr = INADDR_NONE;
}
return addr;
}
uint64_t gettid() {
pthread_t tid = pthread_self();
uint64_t uid = 0;
memcpy(&uid, &tid, std::min(sizeof(tid), sizeof(uid)));
return uid;
}
#endif
} // namespace port
} // namespace handy | 25.137255 | 80 | 0.638846 | onlyet |
4b53deea56787cb6b802da4d1dc5e7358e42ed8a | 10,359 | cc | C++ | src/Worker.cc | tsw303005/MapReduce | e29778a439210963a7cd8047e55123e0c810b79b | [
"MIT"
] | null | null | null | src/Worker.cc | tsw303005/MapReduce | e29778a439210963a7cd8047e55123e0c810b79b | [
"MIT"
] | null | null | null | src/Worker.cc | tsw303005/MapReduce | e29778a439210963a7cd8047e55123e0c810b79b | [
"MIT"
] | null | null | null | #include "Worker.h"
Worker::Worker(char **argv, int cpu_num, int rank, int size) {
this->job_name = std::string(argv[1]);
this->num_reducer = std::stoi(argv[2]);
this->delay = std::stoi(argv[3]);
this->input_filename = std::string(argv[4]);
this->chunk_size = std::stoi(argv[5]);
this->output_dir = std::string(argv[7]);
this->rank = rank;
this->cpu_num = cpu_num;
this->node_num = rank;
this->available_num = 0;
this->scheduler_index = size - 1;
this->mapper_thread_number = cpu_num - 1;
this->reducer_thread_number = 1;
this->threads = new pthread_t[cpu_num];
this->lock = new std::mutex;
this->send_lock = new std::mutex;
}
Worker::~Worker() {
delete this->lock;
delete this->send_lock;
std::cout << "[Info]: Worker "<< this->rank << " terminate\n";
}
void Worker::DeleteFile(std::string filename) {
int result = 0;
char *f = NULL;
f = (char*)malloc(sizeof(char) * (filename.length() + 1));
for (int i = 0; i < filename.length(); i++) {
f[i] = filename[i];
}
f[filename.length()] = '\0';
result = std::remove(f);
if (result != -1) {
std::cout << "[Info]: Remove file " << filename << " successfully\n";
}
free(f);
}
void Worker::ThreadPoolMapper() {
bool task_finished = false;
MPI_Status status;
int signal = 1;
int request[2];
int chunk_index[2];
this->job_mapper = new std::queue<Chunk>;
this->job_finished = new std::queue<int>;
// allocate mapper thread
for (int i = 0; i < this->mapper_thread_number; i++) {
pthread_create(&this->threads[i], NULL, Worker::MapperFunction, (void*)this);
}
while (!task_finished) {
// check available thread number
while (this->available_num == 0);
request[0] = 0;
request[1] = 0;
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
MPI_Recv(chunk_index, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD, &status);
this->lock->lock();
this->job_mapper->push({chunk_index[0], chunk_index[1]});
this->lock->unlock();
// mapper job done
if (chunk_index[0] == -1) {
task_finished = true;
}
}
// check all mapper thread return
for (int i = 0; i < this->mapper_thread_number; i++) {
pthread_join(this->threads[i], NULL);
}
while (!this->job_finished->empty()) {
request[0] = 1;
request[1] = this->job_finished->front();
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
this->job_finished->pop();
}
// delete queue
delete this->job_mapper;
delete this->job_finished;
MPI_Barrier(MPI_COMM_WORLD);
}
void Worker::ThreadPoolReducer() {
bool task_finished = false;
MPI_Status status;
int signal = 1;
int request[2];
int reducer_index;
this->job_reducer = new std::queue<int>;
this->job_finished = new std::queue<int>;
for (int i = 0; i < this->reducer_thread_number; i++) {
pthread_create(&this->threads[i], NULL, Worker::ReducerFunction, this);
}
while (!task_finished) {
// check available thread
while (this->available_num == 0);
request[0] = 0;
request[1] = 0;
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
MPI_Recv(&reducer_index, 1, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD, &status);
this->lock->lock();
this->job_reducer->push(reducer_index);
this->lock->unlock();
if (reducer_index == -1) { // reducer job done
task_finished = true;
}
}
// check all mapper thread return
for (int i = 0; i < this->reducer_thread_number; i++) {
pthread_join(this->threads[i], NULL);
}
while (!this->job_finished->empty()) {
request[0] = 1;
request[1] = this->job_finished->front();
MPI_Send(request, 2, MPI_INT, this->scheduler_index, 0, MPI_COMM_WORLD);
this->job_finished->pop();
}
// delete queue
delete this->job_reducer;
delete this->job_finished;
MPI_Barrier(MPI_COMM_WORLD);
}
void* Worker::MapperFunction(void *input) {
Worker *mapper = (Worker*)input;
Count *word_count = new Count;
Word *words = new Word;
Chunk chunk;
bool task_finished = false;
while (!task_finished) {
chunk.first = -1;
mapper->lock->lock();
if (!mapper->job_mapper->empty()) {
chunk = mapper->job_mapper->front();
if (chunk.first == -1) {
task_finished = true;
} else {
mapper->available_num -= 1;
mapper->job_mapper->pop();
}
}
mapper->lock->unlock();
if (chunk.first != -1) {
if (chunk.second != mapper->rank && WAIT) {
sleep(mapper->delay);
}
word_count->clear();
words->clear();
// Input Split
mapper->InputSplit(chunk.first, word_count, words);
// get word partition number
std::vector<std::vector<std::string>> split_result(mapper->num_reducer + 1);
for (auto word : *words) {
split_result[mapper->Partition(mapper->num_reducer, word)].push_back(word);
}
// generate intermediate file
for (int i = 1; i <= mapper->num_reducer; i++) {
std::string chunk_str = std::to_string(chunk.first);
std::string reducer_num_str = std::to_string(i);
std::string filename = "./intermediate_file/" + chunk_str + "_" + reducer_num_str + ".txt";
std::ofstream myfile(filename);
for (auto word : split_result[i]) {
myfile << word << " " << (*word_count)[word] << "\n";
}
myfile.close();
}
mapper->lock->lock();
mapper->job_finished->push(chunk.first);
mapper->available_num += 1;
mapper->lock->unlock();
}
}
delete word_count;
delete words;
pthread_exit(NULL);
}
void Worker::InputSplit(int chunk, Count *word_count, Word *words) {
int start_pos = 1 + (chunk - 1) * this->chunk_size;
// read chunk file
std::ifstream input_file(this->input_filename);
std::string line;
// find the chunk start position
for (int i = 1; i < start_pos; i++) {
getline(input_file, line);
}
for (int i = 1; i <= this->chunk_size; i++) {
getline(input_file, line);
this->Map(line, word_count, words);
}
input_file.close();
}
void Worker::Map(std::string line, Count *word_count, Word *words) {
int pos = 0;
std::string word;
std::vector<std::string> tmp_words;
while ((pos = line.find(" ")) != std::string::npos) {
word = line.substr(0, pos);
tmp_words.push_back(word);
line.erase(0, pos + 1);
}
if (!line.empty())
tmp_words.push_back(line);
for (auto w : tmp_words) {
if (word_count->count(w) == 0) {
words->push_back(w);
(*word_count)[w] = 1;
} else {
(*word_count)[w] += 1;
}
}
}
int Worker::Partition(int num_reducer, std::string word) {
return ((word.length() % num_reducer) + 1);
}
void* Worker::ReducerFunction(void* input) {
Worker *reducer = (Worker*)input;
Count *word_count = new Count;
Total *total = new Total;
Collect *group = new Collect;
int task;
bool task_finished = false;
while (!task_finished) {
task = -1;
reducer->lock->lock();
if (!reducer->job_reducer->empty()) {
task = reducer->job_reducer->front();
if (task == -1) {
task_finished = true;
} else {
reducer->available_num -= 1;
reducer->job_reducer->pop();
}
}
reducer->lock->unlock();
if (task != -1) {
word_count->clear();
total->clear();
group->clear();
// read intermediate file
reducer->ReadFile(task, total);
// sort words
reducer->Sort(total);
// group
reducer->Group(total, group);
// reduce
reducer->Reduce(group, word_count);
// output
reducer->Output(word_count, task);
reducer->lock->lock();
reducer->job_finished->push(task);
reducer->available_num += 1;
reducer->lock->unlock();
}
}
delete word_count;
delete total;
delete group;
pthread_exit(NULL);
}
void Worker::ReadFile(int task, Total *total) {
std::string filename;
std::string reducer_num_str = std::to_string(task);
std::string word;
int count;
filename = "./intermediate_file/" + reducer_num_str + ".txt";
std::ifstream input_file(filename);
while (input_file >> word >> count) {
total->push_back({word, count});
}
input_file.close();
DeleteFile(filename);
}
bool Worker::cmp(Item a, Item b) {
return a.first < b.first;
}
void Worker::Sort(Total *total) {
sort(total->begin(), total->end(), cmp);
}
void Worker::Group(Total *total, Collect *group) {
for (auto item : *total) {
if (group->count(item.first) == 0) {
std::vector<int> tmp_vec;
tmp_vec.clear();
(*group)[item.first] = tmp_vec;
(*group)[item.first].push_back(item.second);
} else {
(*group)[item.first].push_back(item.second);
}
}
}
void Worker::Reduce(Collect *group, Count *word_count) {
for (auto item : *group) {
(*word_count)[item.first] = 0;
for (auto num : item.second) {
(*word_count)[item.first] += num;
}
}
}
void Worker::Output(Count *word_count, int task) {
std::string task_str = std::to_string(task);
std::string filename = this->output_dir + this->job_name + "-" + task_str + ".out";
std::ofstream myfile(filename);
for (auto word : *word_count) {
myfile << word.first << " " << word.second << "\n";
}
myfile.close();
} | 28.458791 | 107 | 0.551212 | tsw303005 |
4b544ad0ecd7ada690a6c1b109de0382c6378e86 | 3,501 | hpp | C++ | heart/src/problem/cell_factories/PlaneStimulusCellFactory.hpp | stu-l/Chaste | 8efa8b440660553af66804067639f237c855f557 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | heart/src/problem/cell_factories/PlaneStimulusCellFactory.hpp | stu-l/Chaste | 8efa8b440660553af66804067639f237c855f557 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | heart/src/problem/cell_factories/PlaneStimulusCellFactory.hpp | stu-l/Chaste | 8efa8b440660553af66804067639f237c855f557 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2005-2022, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PLANESTIMULUSCELLFACTORY_HPP_
#define PLANESTIMULUSCELLFACTORY_HPP_
#include <boost/shared_ptr.hpp>
#include "AbstractCardiacCellFactory.hpp"
#include "LogFile.hpp"
#include "SimpleStimulus.hpp"
/**
* PlaneStimulusCellFactory provides cells within 1e-5 of x=0 with a SimpleStimulus.
*/
template<class CELL, unsigned ELEMENT_DIM, unsigned SPACE_DIM = ELEMENT_DIM>
class PlaneStimulusCellFactory : public AbstractCardiacCellFactory<ELEMENT_DIM,SPACE_DIM>
{
protected:
/** The stimulus to apply at stimulated nodes */
boost::shared_ptr<SimpleStimulus> mpStimulus;
public:
/**
* Constructor
* @param stimulusMagnitude The magnitude of the simple stimulus to be applied (defaults to -600).
* @param stimulusDuration The duration of the simple stimulus to be applied (defaults to 0.5ms).
*/
PlaneStimulusCellFactory(double stimulusMagnitude=-600, double stimulusDuration=0.5)
: AbstractCardiacCellFactory<ELEMENT_DIM,SPACE_DIM>()
{
mpStimulus.reset(new SimpleStimulus(stimulusMagnitude, stimulusDuration));
LOG(1, "Defined a PlaneStimulusCellFactory<"<<SPACE_DIM<<"> with SimpleStimulus("<<stimulusMagnitude<<","<< stimulusDuration<< ")\n");
}
/**
* @param pNode Pointer to the node.
* @return A cardiac cell which corresponds to this node.
*/
AbstractCardiacCellInterface* CreateCardiacCellForTissueNode(Node<SPACE_DIM>* pNode)
{
double x = pNode->GetPoint()[0];
///\todo remove magic number? (#1884)
if (x*x<=1e-10)
{
return new CELL(this->mpSolver, mpStimulus);
}
else
{
return new CELL(this->mpSolver, this->mpZeroStimulus);
}
}
};
#endif /*PLANESTIMULUSCELLFACTORY_HPP_*/
| 38.472527 | 142 | 0.748072 | stu-l |
4b552c1892dbbbcfd60a47b4272ada7a60f94504 | 3,499 | cpp | C++ | GDADPRG_HO6/GameObjectPool.cpp | NeilDG/GDADPRG-GDPARCM_Courseware | 771509ec7b3eb6d6375807819ca9da957dd22641 | [
"MIT"
] | null | null | null | GDADPRG_HO6/GameObjectPool.cpp | NeilDG/GDADPRG-GDPARCM_Courseware | 771509ec7b3eb6d6375807819ca9da957dd22641 | [
"MIT"
] | null | null | null | GDADPRG_HO6/GameObjectPool.cpp | NeilDG/GDADPRG-GDPARCM_Courseware | 771509ec7b3eb6d6375807819ca9da957dd22641 | [
"MIT"
] | null | null | null | #include "GameObjectPool.h"
#include <iostream>
#include "GameObjectManager.h"
GameObjectPool::GameObjectPool(string tag, APoolable* poolableCopy, int poolableSize, AGameObject* parent)
{
this->tag = tag;
this->objectCopy = poolableCopy;
this->maxPoolSize = poolableSize;
this->parent = parent;
}
GameObjectPool::~GameObjectPool()
{
//this->objectCopy = NULL;
//this->parent = NULL;
delete this->objectCopy;
delete this->parent;
for (int i = 0; i < this->availableObjects.size(); i++) {
GameObjectManager::getInstance()->deleteObject(this->availableObjects[i]);
}
for (int i = 0; i < this->usedObjects.size(); i++) {
GameObjectManager::getInstance()->deleteObject(this->usedObjects[i]);
}
this->availableObjects.clear(); this->availableObjects.shrink_to_fit();
this->usedObjects.clear(); this->usedObjects.shrink_to_fit();
std::cout << "Object pool " << this->getTag() << " destroyed. \n";
}
//initializes the object pool
void GameObjectPool::initialize()
{
for (int i = 0; i < this->maxPoolSize; i++) {
APoolable* poolableObject = this->objectCopy->clone();
//instantiate object but disable it.
if (this->parent != NULL) {
this->parent->attachChild(poolableObject);
}
else {
GameObjectManager::getInstance()->addObject(poolableObject);
}
poolableObject->setEnabled(false);
this->availableObjects.push_back(poolableObject);
}
}
bool GameObjectPool::hasObjectAvailable(int requestSize)
{
return requestSize <= this->availableObjects.size();
}
APoolable* GameObjectPool::requestPoolable()
{
if (this->hasObjectAvailable(1)) {
APoolable* poolableObject = this->availableObjects[this->availableObjects.size() - 1];
this->availableObjects.erase(this->availableObjects.begin() + this->availableObjects.size() - 1);
this->usedObjects.push_back(poolableObject);
//std::cout << "Requested object. Available: " << this->availableObjects.size() << " Used: " << this->usedObjects.size() << "\n";
this->setEnabled(poolableObject, true);
return poolableObject;
}
else {
std::cout << " No more poolable " + this->objectCopy->getName() + " available! \n";
return NULL;
}
}
ObjectList GameObjectPool::requestPoolableBatch(int size)
{
ObjectList returnList;
if (this->hasObjectAvailable(size)) {
for (int i = 0; i < size; i++) {
returnList.push_back(this->requestPoolable());
}
}
else {
std::cout << "Insufficient " + this->objectCopy->getName() + " available in pool. Count is: " << this->availableObjects.size() <<
" while requested is " << size << "!\n";
}
return returnList;
}
void GameObjectPool::releasePoolable(APoolable* poolableObject)
{
//find object in used
int index = -1;
for (int i = 0; i < this->usedObjects.size(); i++) {
if (this->usedObjects[i] == poolableObject) {
index = i;
break;
}
}
//std::cout << "Poolable index in used: " << index << "\n";
if (index > -1) {
this->usedObjects.erase(this->usedObjects.begin() + index);
this->availableObjects.push_back(poolableObject);
this->setEnabled(poolableObject, false);
}
}
void GameObjectPool::releasePoolableBatch(ObjectList objectList)
{
for (int i = 0; i < objectList.size(); i++) {
this->releasePoolable(objectList[i]);
}
}
string GameObjectPool::getTag()
{
return this->tag;
}
void GameObjectPool::setEnabled(APoolable* poolableObject, bool flag)
{
if (flag) {
poolableObject->setEnabled(true);
poolableObject->onActivate();
}
else {
poolableObject->setEnabled(false);
poolableObject->onRelease();
}
}
| 26.11194 | 131 | 0.692769 | NeilDG |
4b5783feaffc0d23f3d088d4a5ee3bf15ee2c6b1 | 198 | cpp | C++ | ExaHyPE/exahype/solvers/CellWiseCoupling.cpp | linusseelinger/ExaHyPE-Tsunami | 92a6e14926862e1584ef1e935874c91d252e8112 | [
"BSD-3-Clause"
] | 2 | 2019-08-14T22:41:26.000Z | 2020-02-04T19:30:24.000Z | ExaHyPE/exahype/solvers/CellWiseCoupling.cpp | linusseelinger/ExaHyPE-Tsunami | 92a6e14926862e1584ef1e935874c91d252e8112 | [
"BSD-3-Clause"
] | null | null | null | ExaHyPE/exahype/solvers/CellWiseCoupling.cpp | linusseelinger/ExaHyPE-Tsunami | 92a6e14926862e1584ef1e935874c91d252e8112 | [
"BSD-3-Clause"
] | 3 | 2019-07-22T10:27:36.000Z | 2020-05-11T12:25:29.000Z | #include "exahype/solvers/CellWiseCoupling.h"
exahype::solvers::CellWiseCoupling::CellWiseCoupling(double time, double repeat):
SolverCoupling( SolverCoupling::Type::CellWise, time, repeat) {
}
| 28.285714 | 81 | 0.787879 | linusseelinger |
4b57dce6491d197f21456d7d3dbb59514309aad5 | 5,034 | cpp | C++ | src/VK/base/ExtFreeSync2.cpp | Zakhrov/Cauldron | 6c50024f6cd4495a1c6d18a58fa4875072ffa243 | [
"MIT"
] | 1 | 2019-07-24T12:02:40.000Z | 2019-07-24T12:02:40.000Z | src/VK/base/ExtFreeSync2.cpp | Zakhrov/Cauldron | 6c50024f6cd4495a1c6d18a58fa4875072ffa243 | [
"MIT"
] | null | null | null | src/VK/base/ExtFreeSync2.cpp | Zakhrov/Cauldron | 6c50024f6cd4495a1c6d18a58fa4875072ffa243 | [
"MIT"
] | null | null | null | // AMD AMDUtils code
//
// Copyright(c) 2018 Advanced Micro Devices, Inc.All rights reserved.
// 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 "ExtFreeSync2.h"
#include "Misc/Misc.h"
#include <vulkan/vulkan.h>
namespace CAULDRON_VK
{
static PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR g_vkGetPhysicalDeviceSurfaceCapabilities2KHR = nullptr;
static PFN_vkGetDeviceProcAddr g_vkGetDeviceProcAddr = nullptr;
static PFN_vkSetHdrMetadataEXT g_vkSetHdrMetadataEXT = nullptr;
#ifdef _WIN32
static PFN_vkAcquireFullScreenExclusiveModeEXT g_vkAcquireFullScreenExclusiveModeEXT = nullptr;
static PFN_vkReleaseFullScreenExclusiveModeEXT g_vkReleaseFullScreenExclusiveModeEXT = nullptr;
#endif
static PFN_vkGetPhysicalDeviceSurfaceFormats2KHR g_vkGetPhysicalDeviceSurfaceFormats2KHR = nullptr;
#ifdef _WIN32
static PFN_vkGetDeviceGroupSurfacePresentModes2EXT g_vkGetDeviceGroupSurfacePresentModes2EXT = nullptr;
static PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT g_vkGetPhysicalDeviceSurfacePresentModes2EXT = nullptr;
static PFN_vkSetLocalDimmingAMD g_vkSetLocalDimmingAMD = nullptr;
#endif
static PFN_vkGetPhysicalDevicePresentRectanglesKHR g_vkGetPhysicalDevicePresentRectanglesKHR = nullptr;
bool ExtFreeSync2CheckExtensions(DeviceProperties *pDP)
{
bool res = true;
#ifdef _WIN32
std::vector<const char *> required_extension_names = { VK_EXT_HDR_METADATA_EXTENSION_NAME, VK_AMD_DISPLAY_NATIVE_HDR_EXTENSION_NAME, VK_EXT_FULL_SCREEN_EXCLUSIVE_EXTENSION_NAME };
for (auto& ext : required_extension_names)
{
if (pDP->Add(ext) == false)
{
Trace(format("FreeSync2 disabled, missing extension: %s\n", ext));
res = false;
}
}
#else
res = false;
Trace(format("FreeSync2 disabled, unsupported platform"));
#endif
return res;
}
void ExtFreeSync2Init(VkInstance instance)
{
g_vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr");
assert(g_vkGetDeviceProcAddr);
g_vkGetPhysicalDeviceSurfaceFormats2KHR = (PFN_vkGetPhysicalDeviceSurfaceFormats2KHR)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfaceFormats2KHR");
assert(g_vkGetPhysicalDeviceSurfaceFormats2KHR);
#ifdef _WIN32
g_vkGetPhysicalDeviceSurfacePresentModes2EXT = (PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceSurfacePresentModes2EXT");
assert(g_vkGetPhysicalDeviceSurfacePresentModes2EXT);
g_vkGetDeviceGroupSurfacePresentModes2EXT = (PFN_vkGetDeviceGroupSurfacePresentModes2EXT)vkGetInstanceProcAddr(instance, "vkGetDeviceGroupSurfacePresentModes2EXT");
assert(g_vkGetDeviceGroupSurfacePresentModes2EXT);
#endif
}
void ExtFreeSync2Init(VkDevice device)
{
g_vkSetHdrMetadataEXT = (PFN_vkSetHdrMetadataEXT)g_vkGetDeviceProcAddr(device, "vkSetHdrMetadataEXT");
assert(g_vkSetHdrMetadataEXT);
#ifdef _WIN32
g_vkAcquireFullScreenExclusiveModeEXT = (PFN_vkAcquireFullScreenExclusiveModeEXT)g_vkGetDeviceProcAddr(device, "vkAcquireFullScreenExclusiveModeEXT");
assert(g_vkAcquireFullScreenExclusiveModeEXT);
g_vkReleaseFullScreenExclusiveModeEXT = (PFN_vkReleaseFullScreenExclusiveModeEXT)g_vkGetDeviceProcAddr(device, "vkReleaseFullScreenExclusiveModeEXT");
assert(g_vkReleaseFullScreenExclusiveModeEXT);
g_vkSetLocalDimmingAMD = (PFN_vkSetLocalDimmingAMD)g_vkGetDeviceProcAddr(device, "vkSetLocalDimmingAMD");
assert(g_vkSetLocalDimmingAMD);
#endif
g_vkGetPhysicalDevicePresentRectanglesKHR = (PFN_vkGetPhysicalDevicePresentRectanglesKHR)g_vkGetDeviceProcAddr(device, "vkGetPhysicalDevicePresentRectanglesKHR");
assert(g_vkGetPhysicalDevicePresentRectanglesKHR);
}
} | 48.403846 | 187 | 0.77056 | Zakhrov |
4b5911b16b46bea84b40d6018d6bfa651aa697d5 | 2,110 | cc | C++ | tests/CSGNodeTest.cc | simoncblyth/CSG | 9022100123cbc982b741a9e9ae9a544956818770 | [
"Apache-2.0"
] | null | null | null | tests/CSGNodeTest.cc | simoncblyth/CSG | 9022100123cbc982b741a9e9ae9a544956818770 | [
"Apache-2.0"
] | null | null | null | tests/CSGNodeTest.cc | simoncblyth/CSG | 9022100123cbc982b741a9e9ae9a544956818770 | [
"Apache-2.0"
] | null | null | null | // ./CSGNodeTest.sh
#include <vector>
#include <iomanip>
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "sutil_vec_math.h"
#include "CSGNode.h"
#include "Sys.h"
void test_copy()
{
glm::mat4 m0(1.f);
glm::mat4 m1(2.f);
glm::mat4 m2(3.f);
m0[0][3] = Sys::int_as_float(42);
m1[0][3] = Sys::int_as_float(52);
m2[0][3] = Sys::int_as_float(62);
std::vector<glm::mat4> node ;
node.push_back(m0);
node.push_back(m1);
node.push_back(m2);
std::vector<CSGNode> node_(3) ;
memcpy( node_.data(), node.data(), sizeof(CSGNode)*node_.size() );
CSGNode* n_ = node_.data();
CSGNode::Dump( n_, node_.size(), "CSGNodeTest" );
}
void test_zero()
{
CSGNode nd = {} ;
assert( nd.gtransformIdx() == 0u );
assert( nd.complement() == false );
unsigned tr = 42u ;
nd.setTransform( tr );
assert( nd.gtransformIdx() == tr );
assert( nd.complement() == false );
nd.setComplement(true);
assert( nd.gtransformIdx() == tr );
assert( nd.complement() == true );
std::cout << nd.desc() << std::endl ;
}
void test_sphere()
{
CSGNode nd = CSGNode::Sphere(100.f);
std::cout << nd.desc() << std::endl ;
}
void test_change_transform()
{
CSGNode nd = {} ;
std::vector<unsigned> uu = {1001, 100, 10, 5, 6, 0, 20, 101, 206 } ;
// checking changing the transform whilst preserving the complement
for(int i=0 ; i < int(uu.size()-1) ; i++)
{
const unsigned& u0 = uu[i] ;
const unsigned& u1 = uu[i+1] ;
nd.setComplement( u0 % 2 == 0 );
nd.setTransform(u0);
bool c0 = nd.complement();
nd.zeroTransformComplement();
nd.setComplement(c0) ;
nd.setTransform( u1 );
bool c1 = nd.complement();
assert( c0 == c1 );
unsigned u1_chk = nd.gtransformIdx();
assert( u1_chk == u1 );
}
}
int main(int argc, char** argv)
{
std::cout << argv[0] << std::endl ;
//test_zero();
//test_sphere();
//test_copy();
test_change_transform();
return 0 ;
}
| 20.095238 | 72 | 0.563981 | simoncblyth |
4b5917d3c368dd0f8781755970b0334e422fdd9a | 1,101 | cpp | C++ | 0001-0100/0073.cpp | YKR/LeetCode2019 | e4c6346eae5c7b85ba53249c46051700a73dd95e | [
"MIT"
] | null | null | null | 0001-0100/0073.cpp | YKR/LeetCode2019 | e4c6346eae5c7b85ba53249c46051700a73dd95e | [
"MIT"
] | null | null | null | 0001-0100/0073.cpp | YKR/LeetCode2019 | e4c6346eae5c7b85ba53249c46051700a73dd95e | [
"MIT"
] | null | null | null | class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return;
int n = matrix.size(), m = matrix[0].size();
bool lastRowZero = false;
for (int j = 0; j < m; ++j)
if (matrix[0][j] == 0)
{
lastRowZero = true;
break;
}
for (int i = 1; i < n; ++i)
{
bool thisRowZero = false;
for (int j = 0; j < m; ++j)
if (matrix[i][j] == 0)
{
thisRowZero = true;
for (int k = i - 1; k >= 0; --k)
matrix[k][j] = 0;
}
for (int j = 0; j < m; ++j)
if (matrix[i-1][j] == 0)
matrix[i][j] = 0;
if (lastRowZero)
for (int j = 0; j < m; ++j)
matrix[i-1][j] = 0;
lastRowZero = thisRowZero;
}
if (lastRowZero)
for (int j = 0; j < m; ++j)
matrix[n-1][j] = 0;
}
}; | 31.457143 | 56 | 0.347866 | YKR |
4b5afc308f388cadad67a3a4a95f9471189f6432 | 6,054 | cpp | C++ | rclcpp/src/rclcpp/executors/static_single_threaded_executor.cpp | asorbini/rclcpp | bc9abd02cd1f34107449e5e849063de7f0e9f71f | [
"Apache-2.0"
] | 1 | 2021-02-01T23:39:44.000Z | 2021-02-01T23:39:44.000Z | rclcpp/src/rclcpp/executors/static_single_threaded_executor.cpp | sanjayaranga/rclcpp | 1c92e6d6091aae88422ad568761b736abf846e98 | [
"Apache-2.0"
] | null | null | null | rclcpp/src/rclcpp/executors/static_single_threaded_executor.cpp | sanjayaranga/rclcpp | 1c92e6d6091aae88422ad568761b736abf846e98 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Nobleo Technology
//
// 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 "rclcpp/executors/static_single_threaded_executor.hpp"
#include <memory>
#include <vector>
#include "rclcpp/scope_exit.hpp"
using rclcpp::executors::StaticSingleThreadedExecutor;
using rclcpp::experimental::ExecutableList;
StaticSingleThreadedExecutor::StaticSingleThreadedExecutor(
const rclcpp::ExecutorOptions & options)
: rclcpp::Executor(options)
{
entities_collector_ = std::make_shared<StaticExecutorEntitiesCollector>();
}
StaticSingleThreadedExecutor::~StaticSingleThreadedExecutor() {}
void
StaticSingleThreadedExecutor::spin()
{
if (spinning.exchange(true)) {
throw std::runtime_error("spin() called while already spinning");
}
RCLCPP_SCOPE_EXIT(this->spinning.store(false); );
// Set memory_strategy_ and exec_list_ based on weak_nodes_
// Prepare wait_set_ based on memory_strategy_
entities_collector_->init(&wait_set_, memory_strategy_, &interrupt_guard_condition_);
RCLCPP_SCOPE_EXIT(entities_collector_->fini());
while (rclcpp::ok(this->context_) && spinning.load()) {
// Refresh wait set and wait for work
entities_collector_->refresh_wait_set();
execute_ready_executables();
}
}
void
StaticSingleThreadedExecutor::add_callback_group(
rclcpp::CallbackGroup::SharedPtr group_ptr,
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr,
bool notify)
{
bool is_new_node = entities_collector_->add_callback_group(group_ptr, node_ptr);
if (is_new_node && notify) {
// Interrupt waiting to handle new node
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
void
StaticSingleThreadedExecutor::add_node(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr, bool notify)
{
bool is_new_node = entities_collector_->add_node(node_ptr);
if (is_new_node && notify) {
// Interrupt waiting to handle new node
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
void
StaticSingleThreadedExecutor::add_node(std::shared_ptr<rclcpp::Node> node_ptr, bool notify)
{
this->add_node(node_ptr->get_node_base_interface(), notify);
}
void
StaticSingleThreadedExecutor::remove_callback_group(
rclcpp::CallbackGroup::SharedPtr group_ptr, bool notify)
{
bool node_removed = entities_collector_->remove_callback_group(group_ptr);
// If the node was matched and removed, interrupt waiting
if (node_removed && notify) {
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
void
StaticSingleThreadedExecutor::remove_node(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr, bool notify)
{
bool node_removed = entities_collector_->remove_node(node_ptr);
if (!node_removed) {
throw std::runtime_error("Node needs to be associated with this executor.");
}
// If the node was matched and removed, interrupt waiting
if (notify) {
if (rcl_trigger_guard_condition(&interrupt_guard_condition_) != RCL_RET_OK) {
throw std::runtime_error(rcl_get_error_string().str);
}
}
}
std::vector<rclcpp::CallbackGroup::WeakPtr>
StaticSingleThreadedExecutor::get_all_callback_groups()
{
return entities_collector_->get_all_callback_groups();
}
std::vector<rclcpp::CallbackGroup::WeakPtr>
StaticSingleThreadedExecutor::get_manually_added_callback_groups()
{
return entities_collector_->get_manually_added_callback_groups();
}
std::vector<rclcpp::CallbackGroup::WeakPtr>
StaticSingleThreadedExecutor::get_automatically_added_callback_groups_from_nodes()
{
return entities_collector_->get_automatically_added_callback_groups_from_nodes();
}
void
StaticSingleThreadedExecutor::remove_node(std::shared_ptr<rclcpp::Node> node_ptr, bool notify)
{
this->remove_node(node_ptr->get_node_base_interface(), notify);
}
void
StaticSingleThreadedExecutor::execute_ready_executables()
{
// Execute all the ready subscriptions
for (size_t i = 0; i < wait_set_.size_of_subscriptions; ++i) {
if (i < entities_collector_->get_number_of_subscriptions()) {
if (wait_set_.subscriptions[i]) {
execute_subscription(entities_collector_->get_subscription(i));
}
}
}
// Execute all the ready timers
for (size_t i = 0; i < wait_set_.size_of_timers; ++i) {
if (i < entities_collector_->get_number_of_timers()) {
if (wait_set_.timers[i] && entities_collector_->get_timer(i)->is_ready()) {
execute_timer(entities_collector_->get_timer(i));
}
}
}
// Execute all the ready services
for (size_t i = 0; i < wait_set_.size_of_services; ++i) {
if (i < entities_collector_->get_number_of_services()) {
if (wait_set_.services[i]) {
execute_service(entities_collector_->get_service(i));
}
}
}
// Execute all the ready clients
for (size_t i = 0; i < wait_set_.size_of_clients; ++i) {
if (i < entities_collector_->get_number_of_clients()) {
if (wait_set_.clients[i]) {
execute_client(entities_collector_->get_client(i));
}
}
}
// Execute all the ready waitables
for (size_t i = 0; i < entities_collector_->get_number_of_waitables(); ++i) {
auto waitable = entities_collector_->get_waitable(i);
if (waitable->is_ready(&wait_set_)) {
auto data = waitable->take_data();
waitable->execute(data);
}
}
}
| 32.724324 | 94 | 0.746283 | asorbini |
4b5cf1061cc899d4e701a0869bad5e25290fd409 | 176 | hpp | C++ | src/HTMLElements/HTMLHeadElement.hpp | windlessStorm/WebWhir | 0ed261427d4f4e4f81b62816dc0d94bfacd0890b | [
"MIT"
] | 90 | 2017-04-03T21:42:57.000Z | 2022-01-22T11:08:56.000Z | src/HTMLElements/HTMLHeadElement.hpp | windlessStorm/WebWhir | 0ed261427d4f4e4f81b62816dc0d94bfacd0890b | [
"MIT"
] | 21 | 2017-03-06T21:45:36.000Z | 2017-03-06T21:45:37.000Z | src/HTMLElements/HTMLHeadElement.hpp | windlessStorm/WebWhir | 0ed261427d4f4e4f81b62816dc0d94bfacd0890b | [
"MIT"
] | 17 | 2017-04-15T22:42:13.000Z | 2021-12-20T09:50:15.000Z | #ifndef HTMLHEADELEMENT_H
#define HTMLHEADELEMENT_H
#include "HTMLElement.hpp"
class HTMLHeadElement : public HTMLElement
{
public:
HTMLHeadElement();
};
#endif
| 13.538462 | 42 | 0.738636 | windlessStorm |
4b5d23ce14403f0f3a7a4f2dbf24030ab0cfe1b9 | 6,496 | cc | C++ | chrome/browser/ui/network_profile_bubble.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | chrome/browser/ui/network_profile_bubble.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/network_profile_bubble.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // 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 "chrome/browser/ui/network_profile_bubble.h"
#include <windows.h>
#include <wtsapi32.h>
// Make sure we link the wtsapi lib file in.
#pragma comment(lib, "wtsapi32.lib")
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "content/public/browser/browser_thread.h"
namespace {
// The duration of the silent period before we start nagging the user again.
const int kSilenceDurationDays = 100;
// The number of warnings to be shown on consequtive starts of Chrome before the
// silent period starts.
const int kMaxWarnings = 2;
// Implementation of chrome::BrowserListObserver used to wait for a browser
// window.
class BrowserListObserver : public chrome::BrowserListObserver {
private:
virtual ~BrowserListObserver();
// Overridden from chrome::BrowserListObserver:
virtual void OnBrowserAdded(Browser* browser) override;
virtual void OnBrowserRemoved(Browser* browser) override;
virtual void OnBrowserSetLastActive(Browser* browser) override;
};
BrowserListObserver::~BrowserListObserver() {
}
void BrowserListObserver::OnBrowserAdded(Browser* browser) {
}
void BrowserListObserver::OnBrowserRemoved(Browser* browser) {
}
void BrowserListObserver::OnBrowserSetLastActive(Browser* browser) {
NetworkProfileBubble::ShowNotification(browser);
// No need to observe anymore.
BrowserList::RemoveObserver(this);
delete this;
}
// The name of the UMA histogram collecting our stats.
const char kMetricNetworkedProfileCheck[] = "NetworkedProfile.Check";
} // namespace
// static
bool NetworkProfileBubble::notification_shown_ = false;
// static
bool NetworkProfileBubble::ShouldCheckNetworkProfile(Profile* profile) {
PrefService* prefs = profile->GetPrefs();
if (prefs->GetInteger(prefs::kNetworkProfileWarningsLeft))
return !notification_shown_;
int64 last_check = prefs->GetInt64(prefs::kNetworkProfileLastWarningTime);
base::TimeDelta time_since_last_check =
base::Time::Now() - base::Time::FromTimeT(last_check);
if (time_since_last_check.InDays() > kSilenceDurationDays) {
prefs->SetInteger(prefs::kNetworkProfileWarningsLeft, kMaxWarnings);
return !notification_shown_;
}
return false;
}
// static
void NetworkProfileBubble::CheckNetworkProfile(
const base::FilePath& profile_folder) {
DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
// On Windows notify the users if their profiles are located on a network
// share as we don't officially support this setup yet.
// However we don't want to bother users on Cytrix setups as those have no
// real choice and their admins must be well aware of the risks associated.
// Also the command line flag --no-network-profile-warning can stop this
// warning from popping up. In this case we can skip the check to make the
// start faster.
// Collect a lot of stats along the way to see which cases do occur in the
// wild often enough.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNoNetworkProfileWarning)) {
RecordUmaEvent(METRIC_CHECK_SUPPRESSED);
return;
}
LPWSTR buffer = NULL;
DWORD buffer_length = 0;
// Checking for RDP is cheaper than checking for a network drive so do this
// one first.
if (!::WTSQuerySessionInformation(WTS_CURRENT_SERVER, WTS_CURRENT_SESSION,
WTSClientProtocolType,
&buffer, &buffer_length)) {
RecordUmaEvent(METRIC_CHECK_FAILED);
return;
}
unsigned short* type = reinterpret_cast<unsigned short*>(buffer);
// We should warn the users if they have their profile on a network share only
// if running on a local session.
if (*type == WTS_PROTOCOL_TYPE_CONSOLE) {
bool profile_on_network = false;
if (!profile_folder.empty()) {
base::FilePath temp_file;
// Try to create some non-empty temp file in the profile dir and use
// it to check if there is a reparse-point free path to it.
if (base::CreateTemporaryFileInDir(profile_folder, &temp_file) &&
(base::WriteFile(temp_file, ".", 1) == 1)) {
base::FilePath normalized_temp_file;
if (!base::NormalizeFilePath(temp_file, &normalized_temp_file))
profile_on_network = true;
} else {
RecordUmaEvent(METRIC_CHECK_IO_FAILED);
}
base::DeleteFile(temp_file, false);
}
if (profile_on_network) {
RecordUmaEvent(METRIC_PROFILE_ON_NETWORK);
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&NotifyNetworkProfileDetected));
} else {
RecordUmaEvent(METRIC_PROFILE_NOT_ON_NETWORK);
}
} else {
RecordUmaEvent(METRIC_REMOTE_SESSION);
}
::WTSFreeMemory(buffer);
}
// static
void NetworkProfileBubble::SetNotificationShown(bool shown) {
notification_shown_ = shown;
}
// static
void NetworkProfileBubble::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kNetworkProfileWarningsLeft,
kMaxWarnings,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterInt64Pref(
prefs::kNetworkProfileLastWarningTime,
0,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
void NetworkProfileBubble::RecordUmaEvent(MetricNetworkedProfileCheck event) {
UMA_HISTOGRAM_ENUMERATION(kMetricNetworkedProfileCheck,
event,
METRIC_NETWORKED_PROFILE_CHECK_SIZE);
}
// static
void NetworkProfileBubble::NotifyNetworkProfileDetected() {
Browser* browser = chrome::FindLastActiveWithHostDesktopType(
chrome::GetActiveDesktop());
if (browser)
ShowNotification(browser);
else
BrowserList::AddObserver(new BrowserListObserver());
}
| 34.37037 | 80 | 0.735991 | kjthegod |
4b5d7d1c3d2bcdbfcb3610abe894088b437df312 | 2,087 | cpp | C++ | src/stubgenerator/stubgenerator.cpp | WinBuilds/libjson-rpc-cpp | eb3404156b389f3e76e859ca764a2f1a45da3bb5 | [
"MIT"
] | null | null | null | src/stubgenerator/stubgenerator.cpp | WinBuilds/libjson-rpc-cpp | eb3404156b389f3e76e859ca764a2f1a45da3bb5 | [
"MIT"
] | null | null | null | src/stubgenerator/stubgenerator.cpp | WinBuilds/libjson-rpc-cpp | eb3404156b389f3e76e859ca764a2f1a45da3bb5 | [
"MIT"
] | null | null | null | /*************************************************************************
* libjson-rpc-cpp
*************************************************************************
* @file stubgenerator.cpp
* @date 01.05.2013
* @author Peter Spiess-Knafl <dev@spiessknafl.at>
* @license See attached LICENSE.txt
************************************************************************/
#include <algorithm>
#include <fstream>
#include <jsonrpccpp/common/specificationparser.h>
#include <argtable/argtable3.h>
#include "client/cppclientstubgenerator.h"
#include "client/jsclientstubgenerator.h"
#include "client/pyclientstubgenerator.h"
#include "helper/cpphelper.h"
#include "server/cppserverstubgenerator.h"
#include "stubgenerator.h"
using namespace std;
using namespace jsonrpc;
#define EXIT_ERROR(X) \
cerr << X << endl; \
arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); \
return 1;
StubGenerator::StubGenerator(const string &stubname,
std::vector<Procedure> &procedures,
ostream &outputstream)
: CodeGenerator(outputstream), stubname(stubname), procedures(procedures) {}
StubGenerator::StubGenerator(const string &stubname,
std::vector<Procedure> &procedures,
const std::string &filename)
: CodeGenerator(filename), stubname(stubname), procedures(procedures) {}
StubGenerator::~StubGenerator() {}
string StubGenerator::replaceAll(const string &text, const string &fnd,
const string &rep) {
string result = text;
replaceAll2(result, fnd, rep);
return result;
}
void StubGenerator::replaceAll2(string &result, const string &find,
const string &replace) {
size_t pos = result.find(find);
while (pos != string::npos) {
result.replace(pos, find.length(), replace);
pos = result.find(find, pos + replace.length());
}
}
| 35.982759 | 80 | 0.55103 | WinBuilds |
4b5dee04ebcc36f796ac7481fa4d22eb71b1bbd2 | 866 | cpp | C++ | API/Driver/OpenGL/src/Command/Query.cpp | Gpinchon/OCRA | 341bb07facc616f1f8a27350054d1e86f022d7c6 | [
"Apache-2.0"
] | null | null | null | API/Driver/OpenGL/src/Command/Query.cpp | Gpinchon/OCRA | 341bb07facc616f1f8a27350054d1e86f022d7c6 | [
"Apache-2.0"
] | null | null | null | API/Driver/OpenGL/src/Command/Query.cpp | Gpinchon/OCRA | 341bb07facc616f1f8a27350054d1e86f022d7c6 | [
"Apache-2.0"
] | null | null | null | #include <GL/Command/Buffer.hpp>
#include <GL/QueryPool.hpp>
OCRA_DECLARE_HANDLE(OCRA::Command::Buffer);
OCRA_DECLARE_HANDLE(OCRA::QueryPool);
namespace OCRA::Command
{
void BeginQuery(
const Command::Buffer::Handle& a_CommandBuffer,
const QueryPool::Handle& a_QueryPool,
const uint32_t& a_QueryIndex)
{
a_CommandBuffer->PushCommand([queryPool = a_QueryPool, queryIndex = a_QueryIndex](Buffer::ExecutionState& a_ExecutionState) {
queryPool->Begin(queryIndex);
});
}
void EndQuery(
const Command::Buffer::Handle& a_CommandBuffer,
const QueryPool::Handle& a_QueryPool,
const uint32_t& a_QueryIndex)
{
a_CommandBuffer->PushCommand([queryPool = a_QueryPool, queryIndex = a_QueryIndex](Buffer::ExecutionState& a_ExecutionState) {
queryPool->End(queryIndex);
});
}
} | 32.074074 | 129 | 0.69746 | Gpinchon |
4b5f0b462215ce3c27fb8d26902faf397c88f791 | 18,192 | cpp | C++ | rmf_fleet_adapter/rmf_rxcpp/RxCpp-4.1.0/Rx/v2/test/operators/publish.cpp | Capstone-S13/rmf_ros2 | 66721dd2ab5a458c050bad154c6a17d8e4b5c8f4 | [
"Apache-2.0"
] | 1,451 | 2018-05-04T21:36:08.000Z | 2022-03-27T07:42:45.000Z | rmf_fleet_adapter/rmf_rxcpp/RxCpp-4.1.0/Rx/v2/test/operators/publish.cpp | Capstone-S13/rmf_ros2 | 66721dd2ab5a458c050bad154c6a17d8e4b5c8f4 | [
"Apache-2.0"
] | 150 | 2018-05-10T10:38:19.000Z | 2022-03-24T14:15:11.000Z | rmf_fleet_adapter/rmf_rxcpp/RxCpp-4.1.0/Rx/v2/test/operators/publish.cpp | Capstone-S13/rmf_ros2 | 66721dd2ab5a458c050bad154c6a17d8e4b5c8f4 | [
"Apache-2.0"
] | 220 | 2018-05-05T08:11:16.000Z | 2022-03-13T10:34:41.000Z | #include "../test.h"
#include <rxcpp/operators/rx-publish.hpp>
#include <rxcpp/operators/rx-connect_forever.hpp>
#include <rxcpp/operators/rx-ref_count.hpp>
#include <rxcpp/operators/rx-map.hpp>
#include <rxcpp/operators/rx-merge.hpp>
SCENARIO("publish range", "[!hide][range][subject][publish][subject][operators]"){
GIVEN("a range"){
WHEN("published"){
auto published = rxs::range<int>(0, 10).publish();
std::cout << "subscribe to published" << std::endl;
published.subscribe(
// on_next
[](int v){std::cout << v << ", ";},
// on_completed
[](){std::cout << " done." << std::endl;});
std::cout << "connect to published" << std::endl;
published.connect();
}
WHEN("ref_count is used"){
auto published = rxs::range<int>(0, 10).publish().ref_count();
std::cout << "subscribe to ref_count" << std::endl;
published.subscribe(
// on_next
[](int v){std::cout << v << ", ";},
// on_completed
[](){std::cout << " done." << std::endl;});
}
WHEN("connect_forever is used"){
auto published = rxs::range<int>(0, 10).publish().connect_forever();
std::cout << "subscribe to connect_forever" << std::endl;
published.subscribe(
// on_next
[](int v){std::cout << v << ", ";},
// on_completed
[](){std::cout << " done." << std::endl;});
}
}
}
SCENARIO("publish ref_count", "[range][subject][publish][ref_count][operators]"){
GIVEN("a range"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<double> on;
const rxsc::test::messages<long> out;
static const long start_created = 0;
static const long start_subscribed = 100;
static const long start_unsubscribed = 200;
static const auto next_time = start_subscribed + 1;
static const auto completed_time = next_time + 1;
auto xs = sc.make_hot_observable({ // [0.0, 10.0]
on.next(next_time, 0.0),
on.next(next_time, 1.0),
on.next(next_time, 2.0),
on.next(next_time, 3.0),
on.next(next_time, 4.0),
on.next(next_time, 5.0),
on.next(next_time, 6.0),
on.next(next_time, 7.0),
on.next(next_time, 8.0),
on.next(next_time, 9.0),
on.next(next_time, 10.0),
on.completed(completed_time)
});
auto xs3 = sc.make_hot_observable({ // [0.0, 3.0]
on.next(next_time, 0.0),
on.next(next_time, 1.0),
on.next(next_time, 2.0),
on.next(next_time, 3.0),
on.completed(completed_time)
});
WHEN("ref_count is used"){
auto res = w.start(
[&xs]() {
return xs
.publish()
.ref_count();
},
start_created,
start_subscribed,
start_unsubscribed
);
THEN("the output contains exactly the input") {
auto required = rxu::to_vector({
on.next(next_time, 0.0),
on.next(next_time, 1.0),
on.next(next_time, 2.0),
on.next(next_time, 3.0),
on.next(next_time, 4.0),
on.next(next_time, 5.0),
on.next(next_time, 6.0),
on.next(next_time, 7.0),
on.next(next_time, 8.0),
on.next(next_time, 9.0),
on.next(next_time, 10.0),
on.completed(completed_time)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
}
WHEN("ref_count(other) is used"){
auto res = w.start(
[&xs]() {
auto published = xs.publish();
auto map_to_int = published.map([](double v) { return (long) v; });
// Ensures that 'ref_count(other)' has the source value type,
// not the publisher's value type.
auto with_ref_count = map_to_int.ref_count(published);
return with_ref_count;
},
start_created,
start_subscribed,
start_unsubscribed
);
THEN("the output contains the long-ified input") {
auto required = rxu::to_vector({
out.next(next_time, 0L),
out.next(next_time, 1L),
out.next(next_time, 2L),
out.next(next_time, 3L),
out.next(next_time, 4L),
out.next(next_time, 5L),
out.next(next_time, 6L),
out.next(next_time, 7L),
out.next(next_time, 8L),
out.next(next_time, 9L),
out.next(next_time, 10L),
out.completed(completed_time)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
}
WHEN("ref_count(other) is used in a diamond"){
auto source = rxs::range<double>(0, 3);
int published_on_next_count = 0;
auto res = w.start(
[&xs3, &published_on_next_count]() {
// Ensure we only subscribe once to 'published' when its in a diamond.
auto next = xs3.map(
[&](double v) {
published_on_next_count++;
return v;
}
);
auto published = next.publish();
// Ensures that 'x.ref_count(other)' has the 'x' value type, not the other's
// value type.
auto map_to_int = published.map([](double v) { return (long) v; });
auto left = map_to_int.map([](long v) { return v * 2; });
auto right = map_to_int.map([](long v) { return v * 100; });
auto merge = left.merge(right);
auto with_ref_count = merge.ref_count(published);
return with_ref_count;
},
start_created,
start_subscribed,
start_unsubscribed
);
THEN("the output is subscribed to only once when its in a diamond") {
// Ensure we only subscribe once to 'published' when its in a diamond.
CHECK(published_on_next_count == 4);
}
THEN("the output left,right is interleaved without being biased towards one side.") {
auto required = rxu::to_vector({
out.next(next_time, 0L),
out.next(next_time, 0L),
out.next(next_time, 2L),
out.next(next_time, 100L),
out.next(next_time, 4L),
out.next(next_time, 200L),
out.next(next_time, 6L),
out.next(next_time, 300L),
out.completed(completed_time)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("publish basic", "[publish][multicast][subject][operators]"){
GIVEN("a test hot observable of longs"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto xs = sc.make_hot_observable({
on.next(110, 7),
on.next(220, 3),
on.next(280, 4),
on.next(290, 1),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(410, 13),
on.next(430, 2),
on.next(450, 9),
on.next(520, 11),
on.next(560, 20),
on.completed(600)
});
auto res = w.make_subscriber<int>();
rx::connectable_observable<int> ys;
WHEN("subscribed and then connected"){
w.schedule_absolute(rxsc::test::created_time,
[&ys, &xs](const rxsc::schedulable&){
ys = xs.publish().as_dynamic();
//ys = xs.publish_last().as_dynamic();
});
w.schedule_absolute(rxsc::test::subscribed_time,
[&ys, &res](const rxsc::schedulable&){
ys.subscribe(res);
});
w.schedule_absolute(rxsc::test::unsubscribed_time,
[&res](const rxsc::schedulable&){
res.unsubscribe();
});
{
rx::composite_subscription connection;
w.schedule_absolute(300,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(400,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(500,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(550,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(650,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(800,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
w.start();
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(520, 11)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there were 3 subscription/unsubscription"){
auto required = rxu::to_vector({
on.subscribe(300, 400),
on.subscribe(500, 550),
on.subscribe(650, 800)
});
auto actual = xs.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("publish error", "[publish][error][multicast][subject][operators]"){
GIVEN("a test hot observable of longs"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
std::runtime_error ex("publish on_error");
auto xs = sc.make_hot_observable({
on.next(110, 7),
on.next(220, 3),
on.next(280, 4),
on.next(290, 1),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(410, 13),
on.next(430, 2),
on.next(450, 9),
on.next(520, 11),
on.next(560, 20),
on.error(600, ex)
});
auto res = w.make_subscriber<int>();
rx::connectable_observable<int> ys;
WHEN("subscribed and then connected"){
w.schedule_absolute(rxsc::test::created_time,
[&ys, &xs](const rxsc::schedulable&){
ys = xs.publish().as_dynamic();
});
w.schedule_absolute(rxsc::test::subscribed_time,
[&ys, &res](const rxsc::schedulable&){
ys.subscribe(res);
});
w.schedule_absolute(rxsc::test::unsubscribed_time,
[&res](const rxsc::schedulable&){
res.unsubscribe();
});
{
rx::composite_subscription connection;
w.schedule_absolute(300,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(400,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(500,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(800,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
w.start();
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(520, 11),
on.next(560, 20),
on.error(600, ex)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there were 3 subscription/unsubscription"){
auto required = rxu::to_vector({
on.subscribe(300, 400),
on.subscribe(500, 600)
});
auto actual = xs.subscriptions();
REQUIRE(required == actual);
}
}
}
}
SCENARIO("publish basic with initial value", "[publish][multicast][behavior][operators]"){
GIVEN("a test hot observable of longs"){
auto sc = rxsc::make_test();
auto w = sc.create_worker();
const rxsc::test::messages<int> on;
auto xs = sc.make_hot_observable({
on.next(110, 7),
on.next(220, 3),
on.next(280, 4),
on.next(290, 1),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(410, 13),
on.next(430, 2),
on.next(450, 9),
on.next(520, 11),
on.next(560, 20),
on.completed(600)
});
auto res = w.make_subscriber<int>();
rx::connectable_observable<int> ys;
WHEN("subscribed and then connected"){
w.schedule_absolute(rxsc::test::created_time,
[&ys, &xs](const rxsc::schedulable&){
ys = xs.publish(1979).as_dynamic();
});
w.schedule_absolute(rxsc::test::subscribed_time,
[&ys, &res](const rxsc::schedulable&){
ys.subscribe(res);
});
w.schedule_absolute(rxsc::test::unsubscribed_time,
[&res](const rxsc::schedulable&){
res.unsubscribe();
});
{
rx::composite_subscription connection;
w.schedule_absolute(300,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(400,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(500,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(550,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
{
rx::composite_subscription connection;
w.schedule_absolute(650,
[connection, &ys](const rxsc::schedulable&){
ys.connect(connection);
});
w.schedule_absolute(800,
[connection](const rxsc::schedulable&){
connection.unsubscribe();
});
}
w.start();
THEN("the output only contains items sent while subscribed"){
auto required = rxu::to_vector({
on.next(200, 1979),
on.next(340, 8),
on.next(360, 5),
on.next(370, 6),
on.next(390, 7),
on.next(520, 11)
});
auto actual = res.get_observer().messages();
REQUIRE(required == actual);
}
THEN("there were 3 subscription/unsubscription"){
auto required = rxu::to_vector({
on.subscribe(300, 400),
on.subscribe(500, 550),
on.subscribe(650, 800)
});
auto actual = xs.subscriptions();
REQUIRE(required == actual);
}
}
}
}
| 34.259887 | 97 | 0.445031 | Capstone-S13 |
4b5f3bbb80365fb815744bb378f3c8e80225ee07 | 9,256 | cpp | C++ | UnrealEngine-4.11.2-release/Engine/Source/Runtime/AIModule/Private/EnvironmentQuery/Tests/EnvQueryTest_Pathfinding.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2016-10-01T21:35:52.000Z | 2016-10-01T21:35:52.000Z | UnrealEngine-4.11.2-release/Engine/Source/Runtime/AIModule/Private/EnvironmentQuery/Tests/EnvQueryTest_Pathfinding.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | null | null | null | UnrealEngine-4.11.2-release/Engine/Source/Runtime/AIModule/Private/EnvironmentQuery/Tests/EnvQueryTest_Pathfinding.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2021-04-27T08:48:33.000Z | 2021-04-27T08:48:33.000Z | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "AIModulePrivate.h"
#include "AI/Navigation/NavigationSystem.h"
#include "AI/Navigation/NavAgentInterface.h"
#include "EnvironmentQuery/Contexts/EnvQueryContext_Querier.h"
#include "EnvironmentQuery/Items/EnvQueryItemType_VectorBase.h"
#include "EnvironmentQuery/Tests/EnvQueryTest_Pathfinding.h"
#define LOCTEXT_NAMESPACE "EnvQueryGenerator"
UEnvQueryTest_Pathfinding::UEnvQueryTest_Pathfinding(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
Context = UEnvQueryContext_Querier::StaticClass();
Cost = EEnvTestCost::High;
ValidItemType = UEnvQueryItemType_VectorBase::StaticClass();
TestMode = EEnvTestPathfinding::PathExist;
PathFromContext.DefaultValue = true;
SkipUnreachable.DefaultValue = true;
FloatValueMin.DefaultValue = 1000.0f;
FloatValueMax.DefaultValue = 1000.0f;
SetWorkOnFloatValues(TestMode != EEnvTestPathfinding::PathExist);
}
void UEnvQueryTest_Pathfinding::RunTest(FEnvQueryInstance& QueryInstance) const
{
UObject* QueryOwner = QueryInstance.Owner.Get();
BoolValue.BindData(QueryOwner, QueryInstance.QueryID);
PathFromContext.BindData(QueryOwner, QueryInstance.QueryID);
SkipUnreachable.BindData(QueryOwner, QueryInstance.QueryID);
FloatValueMin.BindData(QueryOwner, QueryInstance.QueryID);
FloatValueMax.BindData(QueryOwner, QueryInstance.QueryID);
bool bWantsPath = BoolValue.GetValue();
bool bPathToItem = PathFromContext.GetValue();
bool bDiscardFailed = SkipUnreachable.GetValue();
float MinThresholdValue = FloatValueMin.GetValue();
float MaxThresholdValue = FloatValueMax.GetValue();
UNavigationSystem* NavSys = QueryInstance.World->GetNavigationSystem();
if (NavSys == nullptr)
{
return;
}
ANavigationData* NavData = FindNavigationData(*NavSys, QueryOwner);
if (NavData == nullptr)
{
return;
}
TArray<FVector> ContextLocations;
if (!QueryInstance.PrepareContext(Context, ContextLocations))
{
return;
}
EPathFindingMode::Type PFMode(EPathFindingMode::Regular);
if (GetWorkOnFloatValues())
{
FFindPathSignature FindPathFunc;
FindPathFunc.BindUObject(this, TestMode == EEnvTestPathfinding::PathLength ?
(bPathToItem ? &UEnvQueryTest_Pathfinding::FindPathLengthTo : &UEnvQueryTest_Pathfinding::FindPathLengthFrom) :
(bPathToItem ? &UEnvQueryTest_Pathfinding::FindPathCostTo : &UEnvQueryTest_Pathfinding::FindPathCostFrom) );
NavData->BeginBatchQuery();
for (FEnvQueryInstance::ItemIterator It(this, QueryInstance); It; ++It)
{
const FVector ItemLocation = GetItemLocation(QueryInstance, It.GetIndex());
for (int32 ContextIndex = 0; ContextIndex < ContextLocations.Num(); ContextIndex++)
{
const float PathValue = FindPathFunc.Execute(ItemLocation, ContextLocations[ContextIndex], PFMode, *NavData, *NavSys, QueryOwner);
It.SetScore(TestPurpose, FilterType, PathValue, MinThresholdValue, MaxThresholdValue);
if (bDiscardFailed && PathValue >= BIG_NUMBER)
{
It.ForceItemState(EEnvItemStatus::Failed);
}
}
}
NavData->FinishBatchQuery();
}
else
{
NavData->BeginBatchQuery();
if (bPathToItem)
{
for (FEnvQueryInstance::ItemIterator It(this, QueryInstance); It; ++It)
{
const FVector ItemLocation = GetItemLocation(QueryInstance, It.GetIndex());
for (int32 ContextIndex = 0; ContextIndex < ContextLocations.Num(); ContextIndex++)
{
const bool bFoundPath = TestPathTo(ItemLocation, ContextLocations[ContextIndex], PFMode, *NavData, *NavSys, QueryOwner);
It.SetScore(TestPurpose, FilterType, bFoundPath, bWantsPath);
}
}
}
else
{
for (FEnvQueryInstance::ItemIterator It(this, QueryInstance); It; ++It)
{
const FVector ItemLocation = GetItemLocation(QueryInstance, It.GetIndex());
for (int32 ContextIndex = 0; ContextIndex < ContextLocations.Num(); ContextIndex++)
{
const bool bFoundPath = TestPathFrom(ItemLocation, ContextLocations[ContextIndex], PFMode, *NavData, *NavSys, QueryOwner);
It.SetScore(TestPurpose, FilterType, bFoundPath, bWantsPath);
}
}
}
NavData->FinishBatchQuery();
}
}
FText UEnvQueryTest_Pathfinding::GetDescriptionTitle() const
{
FString ModeDesc[] = { TEXT("PathExist"), TEXT("PathCost"), TEXT("PathLength") };
FString DirectionDesc = PathFromContext.IsDynamic() ?
FString::Printf(TEXT("%s, direction: %s"), *UEnvQueryTypes::DescribeContext(Context).ToString(), *PathFromContext.ToString()) :
FString::Printf(TEXT("%s %s"), PathFromContext.DefaultValue ? TEXT("from") : TEXT("to"), *UEnvQueryTypes::DescribeContext(Context).ToString());
return FText::FromString(FString::Printf(TEXT("%s: %s"), *ModeDesc[TestMode], *DirectionDesc));
}
FText UEnvQueryTest_Pathfinding::GetDescriptionDetails() const
{
FText DiscardDesc = LOCTEXT("DiscardUnreachable", "discard unreachable");
FText Desc2;
if (SkipUnreachable.IsDynamic())
{
Desc2 = FText::Format(FText::FromString("{0}: {1}"), DiscardDesc, FText::FromString(SkipUnreachable.ToString()));
}
else if (SkipUnreachable.DefaultValue)
{
Desc2 = DiscardDesc;
}
FText TestParamDesc = GetWorkOnFloatValues() ? DescribeFloatTestParams() : DescribeBoolTestParams("existing path");
if (!Desc2.IsEmpty())
{
return FText::Format(FText::FromString("{0}\n{1}"), Desc2, TestParamDesc);
}
return TestParamDesc;
}
#if WITH_EDITOR
void UEnvQueryTest_Pathfinding::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (PropertyChangedEvent.Property && PropertyChangedEvent.Property->GetFName() == GET_MEMBER_NAME_CHECKED(UEnvQueryTest_Pathfinding,TestMode))
{
SetWorkOnFloatValues(TestMode != EEnvTestPathfinding::PathExist);
}
}
#endif
void UEnvQueryTest_Pathfinding::PostLoad()
{
Super::PostLoad();
SetWorkOnFloatValues(TestMode != EEnvTestPathfinding::PathExist);
}
bool UEnvQueryTest_Pathfinding::TestPathFrom(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ItemPos, ContextPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
const bool bPathExists = NavSys.TestPathSync(Query, Mode);
return bPathExists;
}
bool UEnvQueryTest_Pathfinding::TestPathTo(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ContextPos, ItemPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
const bool bPathExists = NavSys.TestPathSync(Query, Mode);
return bPathExists;
}
float UEnvQueryTest_Pathfinding::FindPathCostFrom(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ItemPos, ContextPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetCost() : BIG_NUMBER;
}
float UEnvQueryTest_Pathfinding::FindPathCostTo(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ContextPos, ItemPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetCost() : BIG_NUMBER;
}
float UEnvQueryTest_Pathfinding::FindPathLengthFrom(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ItemPos, ContextPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetLength() : BIG_NUMBER;
}
float UEnvQueryTest_Pathfinding::FindPathLengthTo(const FVector& ItemPos, const FVector& ContextPos, EPathFindingMode::Type Mode, const ANavigationData& NavData, UNavigationSystem& NavSys, const UObject* PathOwner) const
{
FPathFindingQuery Query(PathOwner, NavData, ContextPos, ItemPos, UNavigationQueryFilter::GetQueryFilter(NavData, FilterClass));
Query.SetAllowPartialPaths(false);
FPathFindingResult Result = NavSys.FindPathSync(Query, Mode);
return (Result.IsSuccessful()) ? Result.Path->GetLength() : BIG_NUMBER;
}
ANavigationData* UEnvQueryTest_Pathfinding::FindNavigationData(UNavigationSystem& NavSys, UObject* Owner) const
{
INavAgentInterface* NavAgent = Cast<INavAgentInterface>(Owner);
if (NavAgent)
{
return NavSys.GetNavDataForProps(NavAgent->GetNavAgentPropertiesRef());
}
return NavSys.GetMainNavData(FNavigationSystem::DontCreate);
}
#undef LOCTEXT_NAMESPACE
| 39.896552 | 222 | 0.784032 | armroyce |
4b60e237f32d8903ee202101513eabbd349fab27 | 352 | cpp | C++ | src/core/aa_clip.cpp | nicelbole/skia.c | ce60902da5768973316075917e347d5f61097e74 | [
"Apache-2.0"
] | null | null | null | src/core/aa_clip.cpp | nicelbole/skia.c | ce60902da5768973316075917e347d5f61097e74 | [
"Apache-2.0"
] | null | null | null | src/core/aa_clip.cpp | nicelbole/skia.c | ce60902da5768973316075917e347d5f61097e74 | [
"Apache-2.0"
] | null | null | null | AAClip* create_aa_clip()
{
AAClip *clip = malloc(sizeof(AAClip));
clip->bounds.setEmpty();
clip->run_head = nullptr;
return clip;
}
AAClip* create_aa_clip(const AAClip& src)
{
AAClip* clip = malloc(sizeof(AAClip));
clip->run_head = nullptr;
*clip = src;
return clip;
}
void delete_aa_clip(AAClip* clip)
{
free_runs_aa_clip(clip);
}
| 16.761905 | 41 | 0.6875 | nicelbole |
4b610bec63b9e74ff0100d2707996f2b72a7c074 | 2,892 | cpp | C++ | src/mongo/db/pipeline/accumulator.cpp | wentingwang/morphus | af40299a5f07fd3157946112738f602a566a9908 | [
"Apache-2.0"
] | 24 | 2015-10-15T00:03:57.000Z | 2021-04-25T18:21:31.000Z | src/mongo/db/pipeline/accumulator.cpp | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | 1 | 2015-06-02T12:19:19.000Z | 2015-06-02T12:19:19.000Z | src/mongo/db/pipeline/accumulator.cpp | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | 3 | 2017-07-26T11:17:11.000Z | 2021-11-30T00:11:32.000Z | /**
* Copyright (c) 2011 10gen 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/>.
*/
#include "pch.h"
#include "db/pipeline/accumulator.h"
#include "db/jsobj.h"
#include "util/mongoutils/str.h"
namespace mongo {
using namespace mongoutils;
void Accumulator::addOperand(
const intrusive_ptr<Expression> &pExpression) {
uassert(15943, str::stream() << "group accumulator " <<
getOpName() << " only accepts one operand",
vpOperand.size() < 1);
ExpressionNary::addOperand(pExpression);
}
Accumulator::Accumulator():
ExpressionNary() {
}
void Accumulator::opToBson(BSONObjBuilder *pBuilder, StringData opName,
StringData fieldName, bool requireExpression) const {
verify(vpOperand.size() == 1);
BSONObjBuilder builder;
vpOperand[0]->addToBsonObj(&builder, opName, requireExpression);
pBuilder->append(fieldName, builder.done());
}
void Accumulator::addToBsonObj(BSONObjBuilder *pBuilder,
StringData fieldName,
bool requireExpression) const {
opToBson(pBuilder, getOpName(), fieldName, requireExpression);
}
void Accumulator::addToBsonArray(BSONArrayBuilder *pBuilder) const {
verify(false); // these can't appear in arrays
}
void agg_framework_reservedErrors() {
uassert(16030, "reserved error", false);
uassert(16031, "reserved error", false);
uassert(16032, "reserved error", false);
uassert(16033, "reserved error", false);
uassert(16036, "reserved error", false);
uassert(16037, "reserved error", false);
uassert(16038, "reserved error", false);
uassert(16039, "reserved error", false);
uassert(16040, "reserved error", false);
uassert(16041, "reserved error", false);
uassert(16042, "reserved error", false);
uassert(16043, "reserved error", false);
uassert(16044, "reserved error", false);
uassert(16045, "reserved error", false);
uassert(16046, "reserved error", false);
uassert(16047, "reserved error", false);
uassert(16048, "reserved error", false);
uassert(16049, "reserved error", false);
}
}
| 36.607595 | 84 | 0.641425 | wentingwang |
4b611427d23e90bf2bff67429967beaebd7a79bc | 2,407 | cpp | C++ | bucket_BB/clucene/patches/patch-src__core__CLucene__util__BitSet.cpp | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 17 | 2017-04-22T21:53:52.000Z | 2021-01-21T16:57:55.000Z | bucket_BB/clucene/patches/patch-src__core__CLucene__util__BitSet.cpp | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 186 | 2017-09-12T20:46:52.000Z | 2021-11-27T18:15:14.000Z | bucket_BB/clucene/patches/patch-src__core__CLucene__util__BitSet.cpp | jrmarino/ravensource | 91d599fd1f2af55270258d15e72c62774f36033e | [
"FTL"
] | 74 | 2017-09-06T14:48:01.000Z | 2021-08-28T02:48:27.000Z | --- src/core/CLucene/util/BitSet.cpp.orig 2011-03-17 00:21:07 UTC
+++ src/core/CLucene/util/BitSet.cpp
@@ -32,6 +32,25 @@ const uint8_t BitSet::BYTE_COUNTS[256] =
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
+const uint8_t BitSet::BYTE_OFFSETS[256] = {
+ 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
+ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
+
+
BitSet::BitSet( const BitSet& copy ) :
_size( copy._size ),
_count(-1)
@@ -180,19 +199,32 @@ BitSet* BitSet::clone() const {
return factor * (4 + (8+40)*count()) < size();
}
- int32_t BitSet::nextSetBit(int32_t fromIndex) const {
+ int32_t BitSet::nextSetBit(int32_t fromIndex) const
+ {
if (fromIndex < 0)
_CLTHROWT(CL_ERR_IndexOutOfBounds, _T("fromIndex < 0"));
if (fromIndex >= _size)
return -1;
- while (true) {
- if ((bits[fromIndex >> 3] & (1 << (fromIndex & 7))) != 0)
- return fromIndex;
- if (++fromIndex == _size)
- return -1;
+ int _max = ( _size+7 ) >> 3;
+
+ unsigned int i = (int)( fromIndex>>3 );
+ unsigned int subIndex = fromIndex & 0x7; // index within the byte
+ uint8_t byte = bits[i] >> subIndex; // skip all the bits to the right of index
+
+ if ( byte != 0 )
+ {
+ return ( ( i<<3 ) + subIndex + BYTE_OFFSETS[ byte ] );
+ }
+
+ while( ++i < _max )
+ {
+ byte = bits[i];
+ if ( byte != 0 )
+ return ( ( i<<3 ) + BYTE_OFFSETS[ byte ] );
}
+ return -1;
}
CL_NS_END
| 35.397059 | 86 | 0.427919 | jrmarino |
4b625c2b53bbb7da89a23da8837473a212e765e9 | 376,712 | cc | C++ | 3rdParty/V8/v7.1.302.28/test/cctest/test-assembler-mips.cc | cclauss/arangodb | 089f7a7e60483f0fb73171d159f922dd3de283e9 | [
"BSL-1.0",
"Apache-2.0"
] | 4 | 2019-04-20T15:56:13.000Z | 2019-12-23T07:14:01.000Z | 3rdParty/V8/v7.1.302.28/test/cctest/test-assembler-mips.cc | fceller/arangodb | 22eec2e35407d868ac36f06b9abdbee3fb3c3ef3 | [
"Apache-2.0"
] | 1 | 2019-02-13T09:53:48.000Z | 2019-02-13T09:53:48.000Z | 3rdParty/V8/v7.1.302.28/test/cctest/test-assembler-mips.cc | fceller/arangodb | 22eec2e35407d868ac36f06b9abdbee3fb3c3ef3 | [
"Apache-2.0"
] | null | null | null | // Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream> // NOLINT(readability/streams)
#include "src/v8.h"
#include "src/assembler-inl.h"
#include "src/base/utils/random-number-generator.h"
#include "src/disassembler.h"
#include "src/heap/factory.h"
#include "src/macro-assembler.h"
#include "src/mips/macro-assembler-mips.h"
#include "src/simulator.h"
#include "test/cctest/cctest.h"
namespace v8 {
namespace internal {
// Define these function prototypes to match JSEntryFunction in execution.cc.
// TODO(mips): Refine these signatures per test case.
typedef Object*(F1)(int x, int p1, int p2, int p3, int p4);
typedef Object*(F2)(int x, int y, int p2, int p3, int p4);
typedef Object*(F3)(void* p, int p1, int p2, int p3, int p4);
typedef Object*(F4)(void* p0, void* p1, int p2, int p3, int p4);
#define __ assm.
TEST(MIPS0) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// Addition.
__ addu(v0, a0, a1);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int res = reinterpret_cast<int>(f.Call(0xAB0, 0xC, 0, 0, 0));
CHECK_EQ(static_cast<int32_t>(0xABC), res);
}
TEST(MIPS1) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
__ mov(a1, a0);
__ li(v0, 0);
__ b(&C);
__ nop();
__ bind(&L);
__ addu(v0, v0, a1);
__ addiu(a1, a1, -1);
__ bind(&C);
__ xori(v1, a1, 0);
__ Branch(&L, ne, v1, Operand(0));
__ nop();
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F1>::FromCode(*code);
int res = reinterpret_cast<int>(f.Call(50, 0, 0, 0, 0));
CHECK_EQ(1275, res);
}
TEST(MIPS2) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label exit, error;
// ----- Test all instructions.
// Test lui, ori, and addiu, used in the li pseudo-instruction.
// This way we can then safely load registers with chosen values.
__ ori(t0, zero_reg, 0);
__ lui(t0, 0x1234);
__ ori(t0, t0, 0);
__ ori(t0, t0, 0x0F0F);
__ ori(t0, t0, 0xF0F0);
__ addiu(t1, t0, 1);
__ addiu(t2, t1, -0x10);
// Load values in temporary registers.
__ li(t0, 0x00000004);
__ li(t1, 0x00001234);
__ li(t2, 0x12345678);
__ li(t3, 0x7FFFFFFF);
__ li(t4, 0xFFFFFFFC);
__ li(t5, 0xFFFFEDCC);
__ li(t6, 0xEDCBA988);
__ li(t7, 0x80000000);
// SPECIAL class.
__ srl(v0, t2, 8); // 0x00123456
__ sll(v0, v0, 11); // 0x91A2B000
__ sra(v0, v0, 3); // 0xF2345600
__ srav(v0, v0, t0); // 0xFF234560
__ sllv(v0, v0, t0); // 0xF2345600
__ srlv(v0, v0, t0); // 0x0F234560
__ Branch(&error, ne, v0, Operand(0x0F234560));
__ nop();
__ addu(v0, t0, t1); // 0x00001238
__ subu(v0, v0, t0); // 0x00001234
__ Branch(&error, ne, v0, Operand(0x00001234));
__ nop();
__ addu(v1, t3, t0);
__ Branch(&error, ne, v1, Operand(0x80000003));
__ nop();
__ subu(v1, t7, t0); // 0x7FFFFFFC
__ Branch(&error, ne, v1, Operand(0x7FFFFFFC));
__ nop();
__ and_(v0, t1, t2); // 0x00001230
__ or_(v0, v0, t1); // 0x00001234
__ xor_(v0, v0, t2); // 0x1234444C
__ nor(v0, v0, t2); // 0xEDCBA987
__ Branch(&error, ne, v0, Operand(0xEDCBA983));
__ nop();
__ slt(v0, t7, t3);
__ Branch(&error, ne, v0, Operand(0x1));
__ nop();
__ sltu(v0, t7, t3);
__ Branch(&error, ne, v0, Operand(zero_reg));
__ nop();
// End of SPECIAL class.
__ addiu(v0, zero_reg, 0x7421); // 0x00007421
__ addiu(v0, v0, -0x1); // 0x00007420
__ addiu(v0, v0, -0x20); // 0x00007400
__ Branch(&error, ne, v0, Operand(0x00007400));
__ nop();
__ addiu(v1, t3, 0x1); // 0x80000000
__ Branch(&error, ne, v1, Operand(0x80000000));
__ nop();
__ slti(v0, t1, 0x00002000); // 0x1
__ slti(v0, v0, 0xFFFF8000); // 0x0
__ Branch(&error, ne, v0, Operand(zero_reg));
__ nop();
__ sltiu(v0, t1, 0x00002000); // 0x1
__ sltiu(v0, v0, 0x00008000); // 0x1
__ Branch(&error, ne, v0, Operand(0x1));
__ nop();
__ andi(v0, t1, 0xF0F0); // 0x00001030
__ ori(v0, v0, 0x8A00); // 0x00009A30
__ xori(v0, v0, 0x83CC); // 0x000019FC
__ Branch(&error, ne, v0, Operand(0x000019FC));
__ nop();
__ lui(v1, 0x8123); // 0x81230000
__ Branch(&error, ne, v1, Operand(0x81230000));
__ nop();
// Bit twiddling instructions & conditional moves.
// Uses t0-t7 as set above.
__ Clz(v0, t0); // 29
__ Clz(v1, t1); // 19
__ addu(v0, v0, v1); // 48
__ Clz(v1, t2); // 3
__ addu(v0, v0, v1); // 51
__ Clz(v1, t7); // 0
__ addu(v0, v0, v1); // 51
__ Branch(&error, ne, v0, Operand(51));
__ Movn(a0, t3, t0); // Move a0<-t3 (t0 is NOT 0).
__ Ins(a0, t1, 12, 8); // 0x7FF34FFF
__ Branch(&error, ne, a0, Operand(0x7FF34FFF));
__ Movz(a0, t6, t7); // a0 not updated (t7 is NOT 0).
__ Ext(a1, a0, 8, 12); // 0x34F
__ Branch(&error, ne, a1, Operand(0x34F));
__ Movz(a0, t6, v1); // a0<-t6, v0 is 0, from 8 instr back.
__ Branch(&error, ne, a0, Operand(t6));
// Everything was correctly executed. Load the expected result.
__ li(v0, 0x31415926);
__ b(&exit);
__ nop();
__ bind(&error);
// Got an error. Return a wrong result.
__ li(v0, 666);
__ bind(&exit);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int res = reinterpret_cast<int>(f.Call(0xAB0, 0xC, 0, 0, 0));
CHECK_EQ(static_cast<int32_t>(0x31415926), res);
}
TEST(MIPS3) {
// Test floating point instructions.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
double c;
double d;
double e;
double f;
double g;
double h;
double i;
float fa;
float fb;
float fc;
float fd;
float fe;
float ff;
float fg;
} T;
T t;
// Create a function that accepts &t, and loads, manipulates, and stores
// the doubles t.a ... t.f.
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
// Double precision floating point instructions.
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
__ add_d(f8, f4, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(T, c))); // c = a + b.
__ mov_d(f10, f8); // c
__ neg_d(f12, f6); // -b
__ sub_d(f10, f10, f12);
__ Sdc1(f10, MemOperand(a0, offsetof(T, d))); // d = c - (-b).
__ Sdc1(f4, MemOperand(a0, offsetof(T, b))); // b = a.
__ li(t0, 120);
__ mtc1(t0, f14);
__ cvt_d_w(f14, f14); // f14 = 120.0.
__ mul_d(f10, f10, f14);
__ Sdc1(f10, MemOperand(a0, offsetof(T, e))); // e = d * 120 = 1.8066e16.
__ div_d(f12, f10, f4);
__ Sdc1(f12, MemOperand(a0, offsetof(T, f))); // f = e / a = 120.44.
__ sqrt_d(f14, f12);
__ Sdc1(f14, MemOperand(a0, offsetof(T, g)));
// g = sqrt(f) = 10.97451593465515908537
if (IsMipsArchVariant(kMips32r2)) {
__ Ldc1(f4, MemOperand(a0, offsetof(T, h)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, i)));
__ madd_d(f14, f6, f4, f6);
__ Sdc1(f14, MemOperand(a0, offsetof(T, h)));
}
// Single precision floating point instructions.
__ lwc1(f4, MemOperand(a0, offsetof(T, fa)) );
__ lwc1(f6, MemOperand(a0, offsetof(T, fb)) );
__ add_s(f8, f4, f6);
__ swc1(f8, MemOperand(a0, offsetof(T, fc)) ); // fc = fa + fb.
__ neg_s(f10, f6); // -fb
__ sub_s(f10, f8, f10);
__ swc1(f10, MemOperand(a0, offsetof(T, fd)) ); // fd = fc - (-fb).
__ swc1(f4, MemOperand(a0, offsetof(T, fb)) ); // fb = fa.
__ li(t0, 120);
__ mtc1(t0, f14);
__ cvt_s_w(f14, f14); // f14 = 120.0.
__ mul_s(f10, f10, f14);
__ swc1(f10, MemOperand(a0, offsetof(T, fe)) ); // fe = fd * 120
__ div_s(f12, f10, f4);
__ swc1(f12, MemOperand(a0, offsetof(T, ff)) ); // ff = fe / fa
__ sqrt_s(f14, f12);
__ swc1(f14, MemOperand(a0, offsetof(T, fg)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
// Double test values.
t.a = 1.5e14;
t.b = 2.75e11;
t.c = 0.0;
t.d = 0.0;
t.e = 0.0;
t.f = 0.0;
t.h = 1.5;
t.i = 2.75;
// Single test values.
t.fa = 1.5e6;
t.fb = 2.75e4;
t.fc = 0.0;
t.fd = 0.0;
t.fe = 0.0;
t.ff = 0.0;
f.Call(&t, 0, 0, 0, 0);
// Expected double results.
CHECK_EQ(1.5e14, t.a);
CHECK_EQ(1.5e14, t.b);
CHECK_EQ(1.50275e14, t.c);
CHECK_EQ(1.50550e14, t.d);
CHECK_EQ(1.8066e16, t.e);
CHECK_EQ(120.44, t.f);
CHECK_EQ(10.97451593465515908537, t.g);
if (IsMipsArchVariant(kMips32r2)) {
CHECK_EQ(6.875, t.h);
}
// Expected single results.
CHECK_EQ(1.5e6, t.fa);
CHECK_EQ(1.5e6, t.fb);
CHECK_EQ(1.5275e06, t.fc);
CHECK_EQ(1.5550e06, t.fd);
CHECK_EQ(1.866e08, t.fe);
CHECK_EQ(124.40000152587890625, t.ff);
CHECK_EQ(11.1534748077392578125, t.fg);
}
TEST(MIPS4) {
// Exchange between GP anf FP registers is done through memory
// on FPXX compiled binaries and architectures that do not support
// MTHC1 and MTFC1. If this is the case, skipping this test.
if (IsFpxxMode() &&
(IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson))) {
return;
}
// Test moves between floating point and integer registers.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
double c;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
// Swap f4 and f6, by using four integer registers, t0-t3.
if (IsFp32Mode()) {
__ mfc1(t0, f4);
__ mfc1(t1, f5);
__ mfc1(t2, f6);
__ mfc1(t3, f7);
__ mtc1(t0, f6);
__ mtc1(t1, f7);
__ mtc1(t2, f4);
__ mtc1(t3, f5);
} else {
CHECK(!IsMipsArchVariant(kMips32r1) && !IsMipsArchVariant(kLoongson));
DCHECK(IsFp64Mode() || IsFpxxMode());
__ mfc1(t0, f4);
__ mfhc1(t1, f4);
__ mfc1(t2, f6);
__ mfhc1(t3, f6);
__ mtc1(t0, f6);
__ mthc1(t1, f6);
__ mtc1(t2, f4);
__ mthc1(t3, f4);
}
// Store the swapped f4 and f5 back to memory.
__ Sdc1(f4, MemOperand(a0, offsetof(T, a)));
__ Sdc1(f6, MemOperand(a0, offsetof(T, c)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 1.5e22;
t.b = 2.75e11;
t.c = 17.17;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(2.75e11, t.a);
CHECK_EQ(2.75e11, t.b);
CHECK_EQ(1.5e22, t.c);
}
TEST(MIPS5) {
// Test conversions between doubles and integers.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
int i;
int j;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
// Load all structure elements to registers.
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
__ lw(t0, MemOperand(a0, offsetof(T, i)) );
__ lw(t1, MemOperand(a0, offsetof(T, j)) );
// Convert double in f4 to int in element i.
__ cvt_w_d(f8, f4);
__ mfc1(t2, f8);
__ sw(t2, MemOperand(a0, offsetof(T, i)) );
// Convert double in f6 to int in element j.
__ cvt_w_d(f10, f6);
__ mfc1(t3, f10);
__ sw(t3, MemOperand(a0, offsetof(T, j)) );
// Convert int in original i (t0) to double in a.
__ mtc1(t0, f12);
__ cvt_d_w(f0, f12);
__ Sdc1(f0, MemOperand(a0, offsetof(T, a)));
// Convert int in original j (t1) to double in b.
__ mtc1(t1, f14);
__ cvt_d_w(f2, f14);
__ Sdc1(f2, MemOperand(a0, offsetof(T, b)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 1.5e4;
t.b = 2.75e8;
t.i = 12345678;
t.j = -100000;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(12345678.0, t.a);
CHECK_EQ(-100000.0, t.b);
CHECK_EQ(15000, t.i);
CHECK_EQ(275000000, t.j);
}
TEST(MIPS6) {
// Test simple memory loads and stores.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint32_t ui;
int32_t si;
int32_t r1;
int32_t r2;
int32_t r3;
int32_t r4;
int32_t r5;
int32_t r6;
} T;
T t;
Assembler assm(AssemblerOptions{}, nullptr, 0);
Label L, C;
// Basic word load/store.
__ lw(t0, MemOperand(a0, offsetof(T, ui)) );
__ sw(t0, MemOperand(a0, offsetof(T, r1)) );
// lh with positive data.
__ lh(t1, MemOperand(a0, offsetof(T, ui)) );
__ sw(t1, MemOperand(a0, offsetof(T, r2)) );
// lh with negative data.
__ lh(t2, MemOperand(a0, offsetof(T, si)) );
__ sw(t2, MemOperand(a0, offsetof(T, r3)) );
// lhu with negative data.
__ lhu(t3, MemOperand(a0, offsetof(T, si)) );
__ sw(t3, MemOperand(a0, offsetof(T, r4)) );
// lb with negative data.
__ lb(t4, MemOperand(a0, offsetof(T, si)) );
__ sw(t4, MemOperand(a0, offsetof(T, r5)) );
// sh writes only 1/2 of word.
__ lui(t5, 0x3333);
__ ori(t5, t5, 0x3333);
__ sw(t5, MemOperand(a0, offsetof(T, r6)) );
__ lhu(t5, MemOperand(a0, offsetof(T, si)) );
__ sh(t5, MemOperand(a0, offsetof(T, r6)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.ui = 0x11223344;
t.si = 0x99AABBCC;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.r1);
#if __BYTE_ORDER == __LITTLE_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x3344), t.r2);
CHECK_EQ(static_cast<int32_t>(0xFFFFBBCC), t.r3);
CHECK_EQ(static_cast<int32_t>(0x0000BBCC), t.r4);
CHECK_EQ(static_cast<int32_t>(0xFFFFFFCC), t.r5);
CHECK_EQ(static_cast<int32_t>(0x3333BBCC), t.r6);
#elif __BYTE_ORDER == __BIG_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x1122), t.r2);
CHECK_EQ(static_cast<int32_t>(0xFFFF99AA), t.r3);
CHECK_EQ(static_cast<int32_t>(0x000099AA), t.r4);
CHECK_EQ(static_cast<int32_t>(0xFFFFFF99), t.r5);
CHECK_EQ(static_cast<int32_t>(0x99AA3333), t.r6);
#else
#error Unknown endianness
#endif
}
TEST(MIPS7) {
// Test floating point compare and branch instructions.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
double c;
double d;
double e;
double f;
int32_t result;
} T;
T t;
// Create a function that accepts &t, and loads, manipulates, and stores
// the doubles t.a ... t.f.
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label neither_is_nan, less_than, outa_here;
__ Ldc1(f4, MemOperand(a0, offsetof(T, a)));
__ Ldc1(f6, MemOperand(a0, offsetof(T, b)));
if (!IsMipsArchVariant(kMips32r6)) {
__ c(UN, D, f4, f6);
__ bc1f(&neither_is_nan);
} else {
__ cmp(UN, L, f2, f4, f6);
__ bc1eqz(&neither_is_nan, f2);
}
__ nop();
__ sw(zero_reg, MemOperand(a0, offsetof(T, result)) );
__ Branch(&outa_here);
__ bind(&neither_is_nan);
if (IsMipsArchVariant(kLoongson)) {
__ c(OLT, D, f6, f4);
__ bc1t(&less_than);
} else if (IsMipsArchVariant(kMips32r6)) {
__ cmp(OLT, L, f2, f6, f4);
__ bc1nez(&less_than, f2);
} else {
__ c(OLT, D, f6, f4, 2);
__ bc1t(&less_than, 2);
}
__ nop();
__ sw(zero_reg, MemOperand(a0, offsetof(T, result)) );
__ Branch(&outa_here);
__ bind(&less_than);
__ Addu(t0, zero_reg, Operand(1));
__ sw(t0, MemOperand(a0, offsetof(T, result)) ); // Set true.
// This test-case should have additional tests.
__ bind(&outa_here);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 1.5e14;
t.b = 2.75e11;
t.c = 2.0;
t.d = -4.0;
t.e = 0.0;
t.f = 0.0;
t.result = 0;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(1.5e14, t.a);
CHECK_EQ(2.75e11, t.b);
CHECK_EQ(1, t.result);
}
TEST(MIPS8) {
// Test ROTR and ROTRV instructions.
if (IsMipsArchVariant(kMips32r2)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t input;
int32_t result_rotr_4;
int32_t result_rotr_8;
int32_t result_rotr_12;
int32_t result_rotr_16;
int32_t result_rotr_20;
int32_t result_rotr_24;
int32_t result_rotr_28;
int32_t result_rotrv_4;
int32_t result_rotrv_8;
int32_t result_rotrv_12;
int32_t result_rotrv_16;
int32_t result_rotrv_20;
int32_t result_rotrv_24;
int32_t result_rotrv_28;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// Basic word load.
__ lw(t0, MemOperand(a0, offsetof(T, input)) );
// ROTR instruction (called through the Ror macro).
__ Ror(t1, t0, 0x0004);
__ Ror(t2, t0, 0x0008);
__ Ror(t3, t0, 0x000C);
__ Ror(t4, t0, 0x0010);
__ Ror(t5, t0, 0x0014);
__ Ror(t6, t0, 0x0018);
__ Ror(t7, t0, 0x001C);
// Basic word store.
__ sw(t1, MemOperand(a0, offsetof(T, result_rotr_4)) );
__ sw(t2, MemOperand(a0, offsetof(T, result_rotr_8)) );
__ sw(t3, MemOperand(a0, offsetof(T, result_rotr_12)) );
__ sw(t4, MemOperand(a0, offsetof(T, result_rotr_16)) );
__ sw(t5, MemOperand(a0, offsetof(T, result_rotr_20)) );
__ sw(t6, MemOperand(a0, offsetof(T, result_rotr_24)) );
__ sw(t7, MemOperand(a0, offsetof(T, result_rotr_28)) );
// ROTRV instruction (called through the Ror macro).
__ li(t7, 0x0004);
__ Ror(t1, t0, t7);
__ li(t7, 0x0008);
__ Ror(t2, t0, t7);
__ li(t7, 0x000C);
__ Ror(t3, t0, t7);
__ li(t7, 0x0010);
__ Ror(t4, t0, t7);
__ li(t7, 0x0014);
__ Ror(t5, t0, t7);
__ li(t7, 0x0018);
__ Ror(t6, t0, t7);
__ li(t7, 0x001C);
__ Ror(t7, t0, t7);
// Basic word store.
__ sw(t1, MemOperand(a0, offsetof(T, result_rotrv_4)) );
__ sw(t2, MemOperand(a0, offsetof(T, result_rotrv_8)) );
__ sw(t3, MemOperand(a0, offsetof(T, result_rotrv_12)) );
__ sw(t4, MemOperand(a0, offsetof(T, result_rotrv_16)) );
__ sw(t5, MemOperand(a0, offsetof(T, result_rotrv_20)) );
__ sw(t6, MemOperand(a0, offsetof(T, result_rotrv_24)) );
__ sw(t7, MemOperand(a0, offsetof(T, result_rotrv_28)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.input = 0x12345678;
f.Call(&t, 0x0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x81234567), t.result_rotr_4);
CHECK_EQ(static_cast<int32_t>(0x78123456), t.result_rotr_8);
CHECK_EQ(static_cast<int32_t>(0x67812345), t.result_rotr_12);
CHECK_EQ(static_cast<int32_t>(0x56781234), t.result_rotr_16);
CHECK_EQ(static_cast<int32_t>(0x45678123), t.result_rotr_20);
CHECK_EQ(static_cast<int32_t>(0x34567812), t.result_rotr_24);
CHECK_EQ(static_cast<int32_t>(0x23456781), t.result_rotr_28);
CHECK_EQ(static_cast<int32_t>(0x81234567), t.result_rotrv_4);
CHECK_EQ(static_cast<int32_t>(0x78123456), t.result_rotrv_8);
CHECK_EQ(static_cast<int32_t>(0x67812345), t.result_rotrv_12);
CHECK_EQ(static_cast<int32_t>(0x56781234), t.result_rotrv_16);
CHECK_EQ(static_cast<int32_t>(0x45678123), t.result_rotrv_20);
CHECK_EQ(static_cast<int32_t>(0x34567812), t.result_rotrv_24);
CHECK_EQ(static_cast<int32_t>(0x23456781), t.result_rotrv_28);
}
}
TEST(MIPS9) {
// Test BRANCH improvements.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label exit, exit2, exit3;
__ Branch(&exit, ge, a0, Operand(zero_reg));
__ Branch(&exit2, ge, a0, Operand(0x00001FFF));
__ Branch(&exit3, ge, a0, Operand(0x0001FFFF));
__ bind(&exit);
__ bind(&exit2);
__ bind(&exit3);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
}
TEST(MIPS10) {
// Test conversions between doubles and words.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double a;
double b;
int32_t dbl_mant;
int32_t dbl_exp;
int32_t word;
int32_t b_word;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label L, C;
if (IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson)) return;
// Load all structure elements to registers.
// (f0, f1) = a (fp32), f0 = a (fp64)
__ Ldc1(f0, MemOperand(a0, offsetof(T, a)));
__ mfc1(t0, f0); // t0 = f0(31..0)
__ mfhc1(t1, f0); // t1 = sign_extend(f0(63..32))
__ sw(t0, MemOperand(a0, offsetof(T, dbl_mant))); // dbl_mant = t0
__ sw(t1, MemOperand(a0, offsetof(T, dbl_exp))); // dbl_exp = t1
// Convert double in f0 to word, save hi/lo parts.
__ cvt_w_d(f0, f0); // a_word = (word)a
__ mfc1(t0, f0); // f0 has a 32-bits word. t0 = a_word
__ sw(t0, MemOperand(a0, offsetof(T, word))); // word = a_word
// Convert the b word to double b.
__ lw(t0, MemOperand(a0, offsetof(T, b_word)));
__ mtc1(t0, f8); // f8 has a 32-bits word.
__ cvt_d_w(f10, f8);
__ Sdc1(f10, MemOperand(a0, offsetof(T, b)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.a = 2.147483646e+09; // 0x7FFFFFFE -> 0xFF80000041DFFFFF as double.
t.b_word = 0x0FF00FF0; // 0x0FF00FF0 -> 0x as double.
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x41DFFFFF), t.dbl_exp);
CHECK_EQ(static_cast<int32_t>(0xFF800000), t.dbl_mant);
CHECK_EQ(static_cast<int32_t>(0x7FFFFFFE), t.word);
// 0x0FF00FF0 -> 2.6739096+e08
CHECK_EQ(2.6739096e08, t.b);
}
TEST(MIPS11) {
// Do not run test on MIPS32r6, as these instructions are removed.
if (IsMipsArchVariant(kMips32r6)) return;
// Test LWL, LWR, SWL and SWR instructions.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t reg_init;
int32_t mem_init;
int32_t lwl_0;
int32_t lwl_1;
int32_t lwl_2;
int32_t lwl_3;
int32_t lwr_0;
int32_t lwr_1;
int32_t lwr_2;
int32_t lwr_3;
int32_t swl_0;
int32_t swl_1;
int32_t swl_2;
int32_t swl_3;
int32_t swr_0;
int32_t swr_1;
int32_t swr_2;
int32_t swr_3;
} T;
T t;
Assembler assm(AssemblerOptions{}, nullptr, 0);
// Test all combinations of LWL and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, lwl_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t1, MemOperand(a0, offsetof(T, mem_init) + 1) );
__ sw(t1, MemOperand(a0, offsetof(T, lwl_1)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t2, MemOperand(a0, offsetof(T, mem_init) + 2) );
__ sw(t2, MemOperand(a0, offsetof(T, lwl_2)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ lwl(t3, MemOperand(a0, offsetof(T, mem_init) + 3) );
__ sw(t3, MemOperand(a0, offsetof(T, lwl_3)) );
// Test all combinations of LWR and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, lwr_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t1, MemOperand(a0, offsetof(T, mem_init) + 1) );
__ sw(t1, MemOperand(a0, offsetof(T, lwr_1)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t2, MemOperand(a0, offsetof(T, mem_init) + 2) );
__ sw(t2, MemOperand(a0, offsetof(T, lwr_2)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ lwr(t3, MemOperand(a0, offsetof(T, mem_init) + 3) );
__ sw(t3, MemOperand(a0, offsetof(T, lwr_3)) );
// Test all combinations of SWL and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, swl_0)) );
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t0, MemOperand(a0, offsetof(T, swl_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t1, MemOperand(a0, offsetof(T, swl_1)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t1, MemOperand(a0, offsetof(T, swl_1) + 1) );
__ lw(t2, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t2, MemOperand(a0, offsetof(T, swl_2)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t2, MemOperand(a0, offsetof(T, swl_2) + 2) );
__ lw(t3, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t3, MemOperand(a0, offsetof(T, swl_3)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ swl(t3, MemOperand(a0, offsetof(T, swl_3) + 3) );
// Test all combinations of SWR and vAddr.
__ lw(t0, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t0, MemOperand(a0, offsetof(T, swr_0)) );
__ lw(t0, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t0, MemOperand(a0, offsetof(T, swr_0)) );
__ lw(t1, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t1, MemOperand(a0, offsetof(T, swr_1)) );
__ lw(t1, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t1, MemOperand(a0, offsetof(T, swr_1) + 1) );
__ lw(t2, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t2, MemOperand(a0, offsetof(T, swr_2)) );
__ lw(t2, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t2, MemOperand(a0, offsetof(T, swr_2) + 2) );
__ lw(t3, MemOperand(a0, offsetof(T, mem_init)) );
__ sw(t3, MemOperand(a0, offsetof(T, swr_3)) );
__ lw(t3, MemOperand(a0, offsetof(T, reg_init)) );
__ swr(t3, MemOperand(a0, offsetof(T, swr_3) + 3) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.reg_init = 0xAABBCCDD;
t.mem_init = 0x11223344;
f.Call(&t, 0, 0, 0, 0);
#if __BYTE_ORDER == __LITTLE_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x44BBCCDD), t.lwl_0);
CHECK_EQ(static_cast<int32_t>(0x3344CCDD), t.lwl_1);
CHECK_EQ(static_cast<int32_t>(0x223344DD), t.lwl_2);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwl_3);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwr_0);
CHECK_EQ(static_cast<int32_t>(0xAA112233), t.lwr_1);
CHECK_EQ(static_cast<int32_t>(0xAABB1122), t.lwr_2);
CHECK_EQ(static_cast<int32_t>(0xAABBCC11), t.lwr_3);
CHECK_EQ(static_cast<int32_t>(0x112233AA), t.swl_0);
CHECK_EQ(static_cast<int32_t>(0x1122AABB), t.swl_1);
CHECK_EQ(static_cast<int32_t>(0x11AABBCC), t.swl_2);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swl_3);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swr_0);
CHECK_EQ(static_cast<int32_t>(0xBBCCDD44), t.swr_1);
CHECK_EQ(static_cast<int32_t>(0xCCDD3344), t.swr_2);
CHECK_EQ(static_cast<int32_t>(0xDD223344), t.swr_3);
#elif __BYTE_ORDER == __BIG_ENDIAN
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwl_0);
CHECK_EQ(static_cast<int32_t>(0x223344DD), t.lwl_1);
CHECK_EQ(static_cast<int32_t>(0x3344CCDD), t.lwl_2);
CHECK_EQ(static_cast<int32_t>(0x44BBCCDD), t.lwl_3);
CHECK_EQ(static_cast<int32_t>(0xAABBCC11), t.lwr_0);
CHECK_EQ(static_cast<int32_t>(0xAABB1122), t.lwr_1);
CHECK_EQ(static_cast<int32_t>(0xAA112233), t.lwr_2);
CHECK_EQ(static_cast<int32_t>(0x11223344), t.lwr_3);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swl_0);
CHECK_EQ(static_cast<int32_t>(0x11AABBCC), t.swl_1);
CHECK_EQ(static_cast<int32_t>(0x1122AABB), t.swl_2);
CHECK_EQ(static_cast<int32_t>(0x112233AA), t.swl_3);
CHECK_EQ(static_cast<int32_t>(0xDD223344), t.swr_0);
CHECK_EQ(static_cast<int32_t>(0xCCDD3344), t.swr_1);
CHECK_EQ(static_cast<int32_t>(0xBBCCDD44), t.swr_2);
CHECK_EQ(static_cast<int32_t>(0xAABBCCDD), t.swr_3);
#else
#error Unknown endianness
#endif
}
TEST(MIPS12) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t x;
int32_t y;
int32_t y1;
int32_t y2;
int32_t y3;
int32_t y4;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ mov(t6, fp); // Save frame pointer.
__ mov(fp, a0); // Access struct T by fp.
__ lw(t0, MemOperand(a0, offsetof(T, y)) );
__ lw(t3, MemOperand(a0, offsetof(T, y4)) );
__ addu(t1, t0, t3);
__ subu(t4, t0, t3);
__ nop();
__ push(t0); // These instructions disappear after opt.
__ Pop();
__ addu(t0, t0, t0);
__ nop();
__ Pop(); // These instructions disappear after opt.
__ push(t3);
__ nop();
__ push(t3); // These instructions disappear after opt.
__ pop(t3);
__ nop();
__ push(t3);
__ pop(t4);
__ nop();
__ sw(t0, MemOperand(fp, offsetof(T, y)) );
__ lw(t0, MemOperand(fp, offsetof(T, y)) );
__ nop();
__ sw(t0, MemOperand(fp, offsetof(T, y)) );
__ lw(t1, MemOperand(fp, offsetof(T, y)) );
__ nop();
__ push(t1);
__ lw(t1, MemOperand(fp, offsetof(T, y)) );
__ pop(t1);
__ nop();
__ push(t1);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t1);
__ nop();
__ push(t1);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t2);
__ nop();
__ push(t2);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t1);
__ nop();
__ push(t1);
__ lw(t2, MemOperand(fp, offsetof(T, y)) );
__ pop(t3);
__ nop();
__ mov(fp, t6);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.x = 1;
t.y = 2;
t.y1 = 3;
t.y2 = 4;
t.y3 = 0XBABA;
t.y4 = 0xDEDA;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(3, t.y1);
}
TEST(MIPS13) {
// Test Cvt_d_uw and Trunc_uw_d macros.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double cvt_big_out;
double cvt_small_out;
uint32_t trunc_big_out;
uint32_t trunc_small_out;
uint32_t cvt_big_in;
uint32_t cvt_small_in;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ sw(t0, MemOperand(a0, offsetof(T, cvt_small_in)));
__ Cvt_d_uw(f10, t0, f4);
__ Sdc1(f10, MemOperand(a0, offsetof(T, cvt_small_out)));
__ Trunc_uw_d(f10, f10, f4);
__ swc1(f10, MemOperand(a0, offsetof(T, trunc_small_out)));
__ sw(t0, MemOperand(a0, offsetof(T, cvt_big_in)));
__ Cvt_d_uw(f8, t0, f4);
__ Sdc1(f8, MemOperand(a0, offsetof(T, cvt_big_out)));
__ Trunc_uw_d(f8, f8, f4);
__ swc1(f8, MemOperand(a0, offsetof(T, trunc_big_out)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.cvt_big_in = 0xFFFFFFFF;
t.cvt_small_in = 333;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(t.cvt_big_out, static_cast<double>(t.cvt_big_in));
CHECK_EQ(t.cvt_small_out, static_cast<double>(t.cvt_small_in));
CHECK_EQ(static_cast<int>(t.trunc_big_out), static_cast<int>(t.cvt_big_in));
CHECK_EQ(static_cast<int>(t.trunc_small_out),
static_cast<int>(t.cvt_small_in));
}
TEST(MIPS14) {
// Test round, floor, ceil, trunc, cvt.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
#define ROUND_STRUCT_ELEMENT(x) \
uint32_t x##_isNaN2008; \
int32_t x##_up_out; \
int32_t x##_down_out; \
int32_t neg_##x##_up_out; \
int32_t neg_##x##_down_out; \
uint32_t x##_err1_out; \
uint32_t x##_err2_out; \
uint32_t x##_err3_out; \
uint32_t x##_err4_out; \
int32_t x##_invalid_result;
typedef struct {
double round_up_in;
double round_down_in;
double neg_round_up_in;
double neg_round_down_in;
double err1_in;
double err2_in;
double err3_in;
double err4_in;
ROUND_STRUCT_ELEMENT(round)
ROUND_STRUCT_ELEMENT(floor)
ROUND_STRUCT_ELEMENT(ceil)
ROUND_STRUCT_ELEMENT(trunc)
ROUND_STRUCT_ELEMENT(cvt)
} T;
T t;
#undef ROUND_STRUCT_ELEMENT
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// Save FCSR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
#define RUN_ROUND_TEST(x) \
__ cfc1(t0, FCSR); \
__ sw(t0, MemOperand(a0, offsetof(T, x##_isNaN2008))); \
__ Ldc1(f0, MemOperand(a0, offsetof(T, round_up_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, x##_up_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, round_down_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, x##_down_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, neg_round_up_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, neg_##x##_up_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, neg_round_down_in))); \
__ x##_w_d(f0, f0); \
__ swc1(f0, MemOperand(a0, offsetof(T, neg_##x##_down_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err1_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err1_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err2_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err2_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err3_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err3_out))); \
\
__ Ldc1(f0, MemOperand(a0, offsetof(T, err4_in))); \
__ ctc1(zero_reg, FCSR); \
__ x##_w_d(f0, f0); \
__ cfc1(a2, FCSR); \
__ sw(a2, MemOperand(a0, offsetof(T, x##_err4_out))); \
__ swc1(f0, MemOperand(a0, offsetof(T, x##_invalid_result)));
RUN_ROUND_TEST(round)
RUN_ROUND_TEST(floor)
RUN_ROUND_TEST(ceil)
RUN_ROUND_TEST(trunc)
RUN_ROUND_TEST(cvt)
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.round_up_in = 123.51;
t.round_down_in = 123.49;
t.neg_round_up_in = -123.5;
t.neg_round_down_in = -123.49;
t.err1_in = 123.51;
t.err2_in = 1;
t.err3_in = static_cast<double>(1) + 0xFFFFFFFF;
t.err4_in = NAN;
f.Call(&t, 0, 0, 0, 0);
#define GET_FPU_ERR(x) (static_cast<int>(x & kFCSRFlagMask))
#define CHECK_NAN2008(x) (x & kFCSRNaN2008FlagMask)
#define CHECK_ROUND_RESULT(type) \
CHECK(GET_FPU_ERR(t.type##_err1_out) & kFCSRInexactFlagMask); \
CHECK_EQ(0, GET_FPU_ERR(t.type##_err2_out)); \
CHECK(GET_FPU_ERR(t.type##_err3_out) & kFCSRInvalidOpFlagMask); \
CHECK(GET_FPU_ERR(t.type##_err4_out) & kFCSRInvalidOpFlagMask); \
if (CHECK_NAN2008(t.type##_isNaN2008) && kArchVariant == kMips32r6) {\
CHECK_EQ(static_cast<int32_t>(0), t.type##_invalid_result);\
} else {\
CHECK_EQ(static_cast<int32_t>(kFPUInvalidResult), t.type##_invalid_result);\
}
CHECK_ROUND_RESULT(round);
CHECK_ROUND_RESULT(floor);
CHECK_ROUND_RESULT(ceil);
CHECK_ROUND_RESULT(cvt);
}
TEST(MIPS15) {
// Test chaining of label usages within instructions (issue 1644).
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
Label target;
__ beq(v0, v1, &target);
__ nop();
__ bne(v0, v1, &target);
__ nop();
__ bind(&target);
__ nop();
}
// ----------------------mips32r6 specific tests----------------------
TEST(seleqz_selnez) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test {
int a;
int b;
int c;
int d;
double e;
double f;
double g;
double h;
float i;
float j;
float k;
float l;
} Test;
Test test;
// Integer part of test.
__ addiu(t1, zero_reg, 1); // t1 = 1
__ seleqz(t3, t1, zero_reg); // t3 = 1
__ sw(t3, MemOperand(a0, offsetof(Test, a))); // a = 1
__ seleqz(t2, t1, t1); // t2 = 0
__ sw(t2, MemOperand(a0, offsetof(Test, b))); // b = 0
__ selnez(t3, t1, zero_reg); // t3 = 1;
__ sw(t3, MemOperand(a0, offsetof(Test, c))); // c = 0
__ selnez(t3, t1, t1); // t3 = 1
__ sw(t3, MemOperand(a0, offsetof(Test, d))); // d = 1
// Floating point part of test.
__ Ldc1(f0, MemOperand(a0, offsetof(Test, e))); // src
__ Ldc1(f2, MemOperand(a0, offsetof(Test, f))); // test
__ lwc1(f8, MemOperand(a0, offsetof(Test, i)) ); // src
__ lwc1(f10, MemOperand(a0, offsetof(Test, j)) ); // test
__ seleqz_d(f4, f0, f2);
__ selnez_d(f6, f0, f2);
__ seleqz_s(f12, f8, f10);
__ selnez_s(f14, f8, f10);
__ Sdc1(f4, MemOperand(a0, offsetof(Test, g))); // src
__ Sdc1(f6, MemOperand(a0, offsetof(Test, h))); // src
__ swc1(f12, MemOperand(a0, offsetof(Test, k)) ); // src
__ swc1(f14, MemOperand(a0, offsetof(Test, l)) ); // src
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(1, test.a);
CHECK_EQ(0, test.b);
CHECK_EQ(0, test.c);
CHECK_EQ(1, test.d);
const int test_size = 3;
const int input_size = 5;
double inputs_D[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
double outputs_D[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
double tests_D[test_size*2] = {2.8, 2.9, -2.8, -2.9,
18446744073709551616.0, 18446744073709555712.0};
float inputs_S[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
float outputs_S[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
float tests_S[test_size*2] = {2.9, 2.8, -2.9, -2.8,
18446744073709551616.0, 18446746272732807168.0};
for (int j=0; j < test_size; j+=2) {
for (int i=0; i < input_size; i++) {
test.e = inputs_D[i];
test.f = tests_D[j];
test.i = inputs_S[i];
test.j = tests_S[j];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(outputs_D[i], test.g);
CHECK_EQ(0, test.h);
CHECK_EQ(outputs_S[i], test.k);
CHECK_EQ(0, test.l);
test.f = tests_D[j+1];
test.j = tests_S[j+1];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(0, test.g);
CHECK_EQ(outputs_D[i], test.h);
CHECK_EQ(0, test.k);
CHECK_EQ(outputs_S[i], test.l);
}
}
}
}
TEST(min_max) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
struct TestFloat {
double a;
double b;
double c;
double d;
float e;
float f;
float g;
float h;
};
TestFloat test;
const double dnan = std::numeric_limits<double>::quiet_NaN();
const double dinf = std::numeric_limits<double>::infinity();
const double dminf = -std::numeric_limits<double>::infinity();
const float fnan = std::numeric_limits<float>::quiet_NaN();
const float finf = std::numeric_limits<float>::infinity();
const float fminf = std::numeric_limits<float>::infinity();
const int kTableLength = 13;
double inputsa[kTableLength] = {2.0, 3.0, dnan, 3.0, -0.0, 0.0, dinf,
dnan, 42.0, dinf, dminf, dinf, dnan};
double inputsb[kTableLength] = {3.0, 2.0, 3.0, dnan, 0.0, -0.0, dnan,
dinf, dinf, 42.0, dinf, dminf, dnan};
double outputsdmin[kTableLength] = {2.0, 2.0, 3.0, 3.0, -0.0,
-0.0, dinf, dinf, 42.0, 42.0,
dminf, dminf, dnan};
double outputsdmax[kTableLength] = {3.0, 3.0, 3.0, 3.0, 0.0, 0.0, dinf,
dinf, dinf, dinf, dinf, dinf, dnan};
float inputse[kTableLength] = {2.0, 3.0, fnan, 3.0, -0.0, 0.0, finf,
fnan, 42.0, finf, fminf, finf, fnan};
float inputsf[kTableLength] = {3.0, 2.0, 3.0, fnan, 0.0, -0.0, fnan,
finf, finf, 42.0, finf, fminf, fnan};
float outputsfmin[kTableLength] = {2.0, 2.0, 3.0, 3.0, -0.0,
-0.0, finf, finf, 42.0, 42.0,
fminf, fminf, fnan};
float outputsfmax[kTableLength] = {3.0, 3.0, 3.0, 3.0, 0.0, 0.0, finf,
finf, finf, finf, finf, finf, fnan};
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, b)));
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, e)));
__ lwc1(f6, MemOperand(a0, offsetof(TestFloat, f)));
__ min_d(f10, f4, f8);
__ max_d(f12, f4, f8);
__ min_s(f14, f2, f6);
__ max_s(f16, f2, f6);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, c)));
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, d)));
__ swc1(f14, MemOperand(a0, offsetof(TestFloat, g)));
__ swc1(f16, MemOperand(a0, offsetof(TestFloat, h)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputsa[i];
test.b = inputsb[i];
test.e = inputse[i];
test.f = inputsf[i];
f.Call(&test, 0, 0, 0, 0);
CHECK_EQ(0, memcmp(&test.c, &outputsdmin[i], sizeof(test.c)));
CHECK_EQ(0, memcmp(&test.d, &outputsdmax[i], sizeof(test.d)));
CHECK_EQ(0, memcmp(&test.g, &outputsfmin[i], sizeof(test.g)));
CHECK_EQ(0, memcmp(&test.h, &outputsfmax[i], sizeof(test.h)));
}
}
}
TEST(rint_d) {
if (IsMipsArchVariant(kMips32r6)) {
const int kTableLength = 30;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
double b;
int fcsr;
}TestFloat;
TestFloat test;
double inputs[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E+308, 6.27463370218383111104242366943E-307,
309485009821345068724781056.89,
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RN[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 0,
309485009821345068724781057.0,
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RZ[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RP[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 1,
309485009821345068724781057.0,
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
double outputs_RM[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E147,
1.7976931348623157E308, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
int fcsr_inputs[4] =
{kRoundToNearest, kRoundToZero, kRoundToPlusInf, kRoundToMinusInf};
double* outputs[4] = {outputs_RN, outputs_RZ, outputs_RP, outputs_RM};
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ lw(t0, MemOperand(a0, offsetof(TestFloat, fcsr)) );
__ cfc1(t1, FCSR);
__ ctc1(t0, FCSR);
__ rint_d(f8, f4);
__ Sdc1(f8, MemOperand(a0, offsetof(TestFloat, b)));
__ ctc1(t1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int j = 0; j < 4; j++) {
test.fcsr = fcsr_inputs[j];
for (int i = 0; i < kTableLength; i++) {
test.a = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs[j][i]);
}
}
}
}
TEST(sel) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test {
double dd;
double ds;
double dt;
float fd;
float fs;
float ft;
} Test;
Test test;
__ Ldc1(f0, MemOperand(a0, offsetof(Test, dd))); // test
__ Ldc1(f2, MemOperand(a0, offsetof(Test, ds))); // src1
__ Ldc1(f4, MemOperand(a0, offsetof(Test, dt))); // src2
__ lwc1(f6, MemOperand(a0, offsetof(Test, fd)) ); // test
__ lwc1(f8, MemOperand(a0, offsetof(Test, fs)) ); // src1
__ lwc1(f10, MemOperand(a0, offsetof(Test, ft)) ); // src2
__ sel_d(f0, f2, f4);
__ sel_s(f6, f8, f10);
__ Sdc1(f0, MemOperand(a0, offsetof(Test, dd)));
__ swc1(f6, MemOperand(a0, offsetof(Test, fd)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
const int test_size = 3;
const int input_size = 5;
double inputs_dt[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
double inputs_ds[input_size] = {0.1, 69.88, -91.325,
18446744073709551625.0, -18446744073709551625.0};
float inputs_ft[input_size] = {0.0, 65.2, -70.32,
18446744073709551621.0, -18446744073709551621.0};
float inputs_fs[input_size] = {0.1, 69.88, -91.325,
18446744073709551625.0, -18446744073709551625.0};
double tests_D[test_size*2] = {2.8, 2.9, -2.8, -2.9,
18446744073709551616.0, 18446744073709555712.0};
float tests_S[test_size*2] = {2.9, 2.8, -2.9, -2.8,
18446744073709551616.0, 18446746272732807168.0};
for (int j=0; j < test_size; j+=2) {
for (int i=0; i < input_size; i++) {
test.dt = inputs_dt[i];
test.dd = tests_D[j];
test.ds = inputs_ds[i];
test.ft = inputs_ft[i];
test.fd = tests_S[j];
test.fs = inputs_fs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dd, inputs_ds[i]);
CHECK_EQ(test.fd, inputs_fs[i]);
test.dd = tests_D[j+1];
test.fd = tests_S[j+1];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dd, inputs_dt[i]);
CHECK_EQ(test.fd, inputs_ft[i]);
}
}
}
}
TEST(rint_s) {
if (IsMipsArchVariant(kMips32r6)) {
const int kTableLength = 30;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float b;
int fcsr;
}TestFloat;
TestFloat test;
float inputs[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E+38, 6.27463370218383111104242366943E-37,
309485009821345068724781056.89,
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RN[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 0,
309485009821345068724781057.0,
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RZ[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RP[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 1,
309485009821345068724781057.0,
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
float outputs_RM[kTableLength] = {18446744073709551617.0,
4503599627370496.0, -4503599627370496.0,
1.26782468584154733584017312973E30, 1.44860108245951772690707170478E37,
1.7976931348623157E38, 0,
309485009821345068724781057.0,
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
37778931862957161709568.0, 37778931862957161709569.0,
37778931862957161709580.0, 37778931862957161709581.0,
37778931862957161709582.0, 37778931862957161709583.0,
37778931862957161709584.0, 37778931862957161709585.0,
37778931862957161709586.0, 37778931862957161709587.0};
int fcsr_inputs[4] =
{kRoundToNearest, kRoundToZero, kRoundToPlusInf, kRoundToMinusInf};
float* outputs[4] = {outputs_RN, outputs_RZ, outputs_RP, outputs_RM};
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, a)) );
__ lw(t0, MemOperand(a0, offsetof(TestFloat, fcsr)) );
__ cfc1(t1, FCSR);
__ ctc1(t0, FCSR);
__ rint_s(f8, f4);
__ swc1(f8, MemOperand(a0, offsetof(TestFloat, b)) );
__ ctc1(t1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int j = 0; j < 4; j++) {
test.fcsr = fcsr_inputs[j];
for (int i = 0; i < kTableLength; i++) {
test.a = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs[j][i]);
}
}
}
}
TEST(Cvt_d_uw) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_struct {
unsigned input;
uint64_t output;
} TestStruct;
unsigned inputs[] = {0x0, 0xFFFFFFFF, 0x80000000, 0x7FFFFFFF};
uint64_t outputs[] = {0x0, 0x41EFFFFFFFE00000, 0x41E0000000000000,
0x41DFFFFFFFC00000};
int kTableLength = sizeof(inputs)/sizeof(inputs[0]);
TestStruct test;
__ lw(t1, MemOperand(a0, offsetof(TestStruct, input)));
__ Cvt_d_uw(f4, t1, f6);
__ Sdc1(f4, MemOperand(a0, offsetof(TestStruct, output)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.input = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
// Check outputs
CHECK_EQ(test.output, outputs[i]);
}
}
TEST(mina_maxa) {
if (IsMipsArchVariant(kMips32r6)) {
const int kTableLength = 23;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dnan = std::numeric_limits<double>::quiet_NaN();
const double dinf = std::numeric_limits<double>::infinity();
const double dminf = -std::numeric_limits<double>::infinity();
const float fnan = std::numeric_limits<float>::quiet_NaN();
const float finf = std::numeric_limits<float>::infinity();
const float fminf = std::numeric_limits<float>::infinity();
struct TestFloat {
double a;
double b;
double resd;
double resd1;
float c;
float d;
float resf;
float resf1;
};
TestFloat test;
double inputsa[kTableLength] = {
5.3, 4.8, 6.1, 9.8, 9.8, 9.8, -10.0, -8.9, -9.8, -10.0, -8.9, -9.8,
dnan, 3.0, -0.0, 0.0, dinf, dnan, 42.0, dinf, dminf, dinf, dnan};
double inputsb[kTableLength] = {
4.8, 5.3, 6.1, -10.0, -8.9, -9.8, 9.8, 9.8, 9.8, -9.8, -11.2, -9.8,
3.0, dnan, 0.0, -0.0, dnan, dinf, dinf, 42.0, dinf, dminf, dnan};
double resd[kTableLength] = {
4.8, 4.8, 6.1, 9.8, -8.9, -9.8, 9.8, -8.9, -9.8, -9.8, -8.9, -9.8,
3.0, 3.0, -0.0, -0.0, dinf, dinf, 42.0, 42.0, dminf, dminf, dnan};
double resd1[kTableLength] = {
5.3, 5.3, 6.1, -10.0, 9.8, 9.8, -10.0, 9.8, 9.8, -10.0, -11.2, -9.8,
3.0, 3.0, 0.0, 0.0, dinf, dinf, dinf, dinf, dinf, dinf, dnan};
float inputsc[kTableLength] = {
5.3, 4.8, 6.1, 9.8, 9.8, 9.8, -10.0, -8.9, -9.8, -10.0, -8.9, -9.8,
fnan, 3.0, -0.0, 0.0, finf, fnan, 42.0, finf, fminf, finf, fnan};
float inputsd[kTableLength] = {4.8, 5.3, 6.1, -10.0, -8.9, -9.8,
9.8, 9.8, 9.8, -9.8, -11.2, -9.8,
3.0, fnan, -0.0, 0.0, fnan, finf,
finf, 42.0, finf, fminf, fnan};
float resf[kTableLength] = {
4.8, 4.8, 6.1, 9.8, -8.9, -9.8, 9.8, -8.9, -9.8, -9.8, -8.9, -9.8,
3.0, 3.0, -0.0, -0.0, finf, finf, 42.0, 42.0, fminf, fminf, fnan};
float resf1[kTableLength] = {
5.3, 5.3, 6.1, -10.0, 9.8, 9.8, -10.0, 9.8, 9.8, -10.0, -11.2, -9.8,
3.0, 3.0, 0.0, 0.0, finf, finf, finf, finf, finf, finf, fnan};
__ Ldc1(f2, MemOperand(a0, offsetof(TestFloat, a)));
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, b)));
__ lwc1(f8, MemOperand(a0, offsetof(TestFloat, c)) );
__ lwc1(f10, MemOperand(a0, offsetof(TestFloat, d)) );
__ mina_d(f6, f2, f4);
__ mina_s(f12, f8, f10);
__ maxa_d(f14, f2, f4);
__ maxa_s(f16, f8, f10);
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, resf)) );
__ Sdc1(f6, MemOperand(a0, offsetof(TestFloat, resd)));
__ swc1(f16, MemOperand(a0, offsetof(TestFloat, resf1)) );
__ Sdc1(f14, MemOperand(a0, offsetof(TestFloat, resd1)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputsa[i];
test.b = inputsb[i];
test.c = inputsc[i];
test.d = inputsd[i];
(f.Call(&test, 0, 0, 0, 0));
if (i < kTableLength - 1) {
CHECK_EQ(test.resd, resd[i]);
CHECK_EQ(test.resf, resf[i]);
CHECK_EQ(test.resd1, resd1[i]);
CHECK_EQ(test.resf1, resf1[i]);
} else {
CHECK(std::isnan(test.resd));
CHECK(std::isnan(test.resf));
CHECK(std::isnan(test.resd1));
CHECK(std::isnan(test.resf1));
}
}
}
}
// ----------------------mips32r2 specific tests----------------------
TEST(trunc_l) {
if (IsMipsArchVariant(kMips32r2) && IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c; // a trunc result
int64_t d; // b trunc result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ trunc_l_d(f8, f4);
__ trunc_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(movz_movn) {
if (IsMipsArchVariant(kMips32r2)) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
int32_t rt;
double a;
double b;
double bold;
double b1;
double bold1;
float c;
float d;
float dold;
float d1;
float dold1;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
double inputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
float outputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
double outputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
__ Ldc1(f2, MemOperand(a0, offsetof(TestFloat, a)));
__ lwc1(f6, MemOperand(a0, offsetof(TestFloat, c)) );
__ lw(t0, MemOperand(a0, offsetof(TestFloat, rt)) );
__ Move(f12, 0.0);
__ Move(f10, 0.0);
__ Move(f16, 0.0);
__ Move(f14, 0.0);
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, bold)));
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, dold)) );
__ Sdc1(f16, MemOperand(a0, offsetof(TestFloat, bold1)));
__ swc1(f14, MemOperand(a0, offsetof(TestFloat, dold1)) );
__ movz_s(f10, f6, t0);
__ movz_d(f12, f2, t0);
__ movn_s(f14, f6, t0);
__ movn_d(f16, f2, t0);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, d)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, b)));
__ swc1(f14, MemOperand(a0, offsetof(TestFloat, d1)) );
__ Sdc1(f16, MemOperand(a0, offsetof(TestFloat, b1)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.c = inputs_S[i];
test.rt = 1;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, test.bold);
CHECK_EQ(test.d, test.dold);
CHECK_EQ(test.b1, outputs_D[i]);
CHECK_EQ(test.d1, outputs_S[i]);
test.rt = 0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs_D[i]);
CHECK_EQ(test.d, outputs_S[i]);
CHECK_EQ(test.b1, test.bold1);
CHECK_EQ(test.d1, test.dold1);
}
}
}
TEST(movt_movd) {
if (IsMipsArchVariant(kMips32r2)) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
typedef struct test_float {
double srcd;
double dstd;
double dstdold;
double dstd1;
double dstdold1;
float srcf;
float dstf;
float dstfold;
float dstf1;
float dstfold1;
int32_t cc;
int32_t fcsr;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
5.3, -5.3, 20.8, -2.9
};
double inputs_S[kTableLength] = {
4.88, 4.8, -4.8, -0.29
};
float outputs_S[kTableLength] = {
4.88, 4.8, -4.8, -0.29
};
double outputs_D[kTableLength] = {
5.3, -5.3, 20.8, -2.9
};
int condition_flags[8] = {0, 1, 2, 3, 4, 5, 6, 7};
for (int i = 0; i < kTableLength; i++) {
test.srcd = inputs_D[i];
test.srcf = inputs_S[i];
for (int j = 0; j< 8; j++) {
test.cc = condition_flags[j];
if (test.cc == 0) {
test.fcsr = 1 << 23;
} else {
test.fcsr = 1 << (24+condition_flags[j]);
}
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ Ldc1(f2, MemOperand(a0, offsetof(TestFloat, srcd)));
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, srcf)) );
__ lw(t1, MemOperand(a0, offsetof(TestFloat, fcsr)) );
__ cfc1(t0, FCSR);
__ ctc1(t1, FCSR);
__ li(t2, 0x0);
__ mtc1(t2, f12);
__ mtc1(t2, f10);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstdold)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstfold)) );
__ movt_s(f12, f4, test.cc);
__ movt_d(f10, f2, test.cc);
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstf)) );
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstd)));
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstdold1)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstfold1)) );
__ movf_s(f12, f4, test.cc);
__ movf_d(f10, f2, test.cc);
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, dstf1)) );
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, dstd1)));
__ ctc1(t0, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dstf, outputs_S[i]);
CHECK_EQ(test.dstd, outputs_D[i]);
CHECK_EQ(test.dstf1, test.dstfold1);
CHECK_EQ(test.dstd1, test.dstdold1);
test.fcsr = 0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dstf, test.dstfold);
CHECK_EQ(test.dstd, test.dstdold);
CHECK_EQ(test.dstf1, outputs_S[i]);
CHECK_EQ(test.dstd1, outputs_D[i]);
}
}
}
}
// ----------------------tests for all archs--------------------------
TEST(cvt_w_d) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
int32_t b;
int32_t fcsr;
}Test;
const int kTableLength = 24;
double inputs[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, 2147483653.0
};
double outputs_RN[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
double outputs_RZ[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
double outputs_RP[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
double outputs_RM[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
2147483637.0, 2147483638.0, 2147483639.0,
2147483640.0, 2147483641.0, 2147483642.0,
2147483643.0, 2147483644.0, 2147483645.0,
2147483646.0, 2147483647.0, kFPUInvalidResult};
int fcsr_inputs[4] =
{kRoundToNearest, kRoundToZero, kRoundToPlusInf, kRoundToMinusInf};
double* outputs[4] = {outputs_RN, outputs_RZ, outputs_RP, outputs_RM};
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lw(t0, MemOperand(a0, offsetof(Test, fcsr)) );
__ cfc1(t1, FCSR);
__ ctc1(t0, FCSR);
__ cvt_w_d(f8, f4);
__ swc1(f8, MemOperand(a0, offsetof(Test, b)) );
__ ctc1(t1, FCSR);
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int j = 0; j < 4; j++) {
test.fcsr = fcsr_inputs[j];
for (int i = 0; i < kTableLength; i++) {
test.a = inputs[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs[j][i]);
}
}
}
TEST(trunc_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a trunc result
int32_t d; // b trunc result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult,
0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ trunc_w_d(f8, f4);
__ trunc_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(round_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a trunc result
int32_t d; // b trunc result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
kFPUInvalidResult, 0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ round_w_d(f8, f4);
__ round_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(round_l) {
if (IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c;
int64_t d;
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 3.0, 2.0, 3.0, 4.0, 4.0,
-2.0, -3.0, -2.0, -3.0, -4.0, -4.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ round_l_d(f8, f4);
__ round_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(sub) {
const int kTableLength = 12;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float b;
float resultS;
double c;
double d;
double resultD;
}TestFloat;
TestFloat test;
double inputfs_D[kTableLength] = {
5.3, 4.8, 2.9, -5.3, -4.8, -2.9,
5.3, 4.8, 2.9, -5.3, -4.8, -2.9
};
double inputft_D[kTableLength] = {
4.8, 5.3, 2.9, 4.8, 5.3, 2.9,
-4.8, -5.3, -2.9, -4.8, -5.3, -2.9
};
double outputs_D[kTableLength] = {
0.5, -0.5, 0.0, -10.1, -10.1, -5.8,
10.1, 10.1, 5.8, -0.5, 0.5, 0.0
};
float inputfs_S[kTableLength] = {
5.3, 4.8, 2.9, -5.3, -4.8, -2.9,
5.3, 4.8, 2.9, -5.3, -4.8, -2.9
};
float inputft_S[kTableLength] = {
4.8, 5.3, 2.9, 4.8, 5.3, 2.9,
-4.8, -5.3, -2.9, -4.8, -5.3, -2.9
};
float outputs_S[kTableLength] = {
0.5, -0.5, 0.0, -10.1, -10.1, -5.8,
10.1, 10.1, 5.8, -0.5, 0.5, 0.0
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, b)) );
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, c)));
__ Ldc1(f10, MemOperand(a0, offsetof(TestFloat, d)));
__ sub_s(f6, f2, f4);
__ sub_d(f12, f8, f10);
__ swc1(f6, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputfs_S[i];
test.b = inputft_S[i];
test.c = inputfs_D[i];
test.d = inputft_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, outputs_S[i]);
CHECK_EQ(test.resultD, outputs_D[i]);
}
}
TEST(sqrt_rsqrt_recip) {
const int kTableLength = 4;
const double deltaDouble = 2E-15;
const float deltaFloat = 2E-7;
const float sqrt2_s = sqrt(2);
const double sqrt2_d = sqrt(2);
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float resultS;
float resultS1;
float resultS2;
double c;
double resultD;
double resultD1;
double resultD2;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
0.0L, 4.0L, 2.0L, 4e-28L
};
double outputs_D[kTableLength] = {
0.0L, 2.0L, sqrt2_d, 2e-14L
};
float inputs_S[kTableLength] = {
0.0, 4.0, 2.0, 4e-28
};
float outputs_S[kTableLength] = {
0.0, 2.0, sqrt2_s, 2e-14
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, c)));
__ sqrt_s(f6, f2);
__ sqrt_d(f12, f8);
if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
__ rsqrt_d(f14, f8);
__ rsqrt_s(f16, f2);
__ recip_d(f18, f8);
__ recip_s(f4, f2);
}
__ swc1(f6, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
__ swc1(f16, MemOperand(a0, offsetof(TestFloat, resultS1)) );
__ Sdc1(f14, MemOperand(a0, offsetof(TestFloat, resultD1)));
__ swc1(f4, MemOperand(a0, offsetof(TestFloat, resultS2)) );
__ Sdc1(f18, MemOperand(a0, offsetof(TestFloat, resultD2)));
}
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
float f1;
double d1;
test.a = inputs_S[i];
test.c = inputs_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, outputs_S[i]);
CHECK_EQ(test.resultD, outputs_D[i]);
if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
if (i != 0) {
f1 = test.resultS1 - 1.0F/outputs_S[i];
f1 = (f1 < 0) ? f1 : -f1;
CHECK(f1 <= deltaFloat);
d1 = test.resultD1 - 1.0L/outputs_D[i];
d1 = (d1 < 0) ? d1 : -d1;
CHECK(d1 <= deltaDouble);
f1 = test.resultS2 - 1.0F/inputs_S[i];
f1 = (f1 < 0) ? f1 : -f1;
CHECK(f1 <= deltaFloat);
d1 = test.resultD2 - 1.0L/inputs_D[i];
d1 = (d1 < 0) ? d1 : -d1;
CHECK(d1 <= deltaDouble);
} else {
CHECK_EQ(test.resultS1, 1.0F/outputs_S[i]);
CHECK_EQ(test.resultD1, 1.0L/outputs_D[i]);
CHECK_EQ(test.resultS2, 1.0F/inputs_S[i]);
CHECK_EQ(test.resultD2, 1.0L/inputs_D[i]);
}
}
}
}
TEST(neg) {
const int kTableLength = 3;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float resultS;
double c;
double resultD;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
0.0, 4.0, -2.0
};
double outputs_D[kTableLength] = {
0.0, -4.0, 2.0
};
float inputs_S[kTableLength] = {
0.0, 4.0, -2.0
};
float outputs_S[kTableLength] = {
0.0, -4.0, 2.0
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, c)));
__ neg_s(f6, f2);
__ neg_d(f12, f8);
__ swc1(f6, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_S[i];
test.c = inputs_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, outputs_S[i]);
CHECK_EQ(test.resultD, outputs_D[i]);
}
}
TEST(mul) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float a;
float b;
float resultS;
double c;
double d;
double resultD;
}TestFloat;
TestFloat test;
double inputfs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
double inputft_D[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
float inputfs_S[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
float inputft_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, a)) );
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, b)) );
__ Ldc1(f6, MemOperand(a0, offsetof(TestFloat, c)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, d)));
__ mul_s(f10, f2, f4);
__ mul_d(f12, f6, f8);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, resultS)) );
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, resultD)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputfs_S[i];
test.b = inputft_S[i];
test.c = inputfs_D[i];
test.d = inputft_D[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.resultS, inputfs_S[i]*inputft_S[i]);
CHECK_EQ(test.resultD, inputfs_D[i]*inputft_D[i]);
}
}
TEST(mov) {
const int kTableLength = 4;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
double b;
float c;
float d;
}TestFloat;
TestFloat test;
double inputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
double inputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
float outputs_S[kTableLength] = {
4.8, 4.8, -4.8, -0.29
};
double outputs_D[kTableLength] = {
5.3, -5.3, 5.3, -2.9
};
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ lwc1(f6, MemOperand(a0, offsetof(TestFloat, c)) );
__ mov_s(f8, f6);
__ mov_d(f10, f4);
__ swc1(f8, MemOperand(a0, offsetof(TestFloat, d)) );
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, b)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.c = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.b, outputs_D[i]);
CHECK_EQ(test.d, outputs_S[i]);
}
}
TEST(floor_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a floor result
int32_t d; // b floor result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
kFPUInvalidResult,
0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ floor_w_d(f8, f4);
__ floor_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(floor_l) {
if (IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c;
int64_t d;
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
2.0, 2.0, 2.0, 3.0, 3.0, 3.0,
-3.0, -3.0, -3.0, -4.0, -4.0, -4.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ floor_l_d(f8, f4);
__ floor_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(ceil_w) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int32_t c; // a floor result
int32_t d; // b floor result
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult, kFPUInvalidResult,
kFPUInvalidResult};
double outputsNaN2008[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
kFPUInvalidResult,
0,
kFPUInvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ ceil_w_d(f8, f4);
__ ceil_w_s(f10, f6);
__ swc1(f8, MemOperand(a0, offsetof(Test, c)) );
__ swc1(f10, MemOperand(a0, offsetof(Test, d)) );
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) && kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
TEST(ceil_l) {
if (IsFp64Mode()) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
const double dFPU64InvalidResult = static_cast<double>(kFPU64InvalidResult);
typedef struct test_float {
uint32_t isNaN2008;
double a;
float b;
int64_t c;
int64_t d;
}Test;
const int kTableLength = 15;
double inputs_D[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<double>::quiet_NaN(),
std::numeric_limits<double>::infinity()
};
float inputs_S[kTableLength] = {
2.1, 2.6, 2.5, 3.1, 3.6, 3.5,
-2.1, -2.6, -2.5, -3.1, -3.6, -3.5,
2147483648.0,
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity()
};
double outputs[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0, dFPU64InvalidResult,
dFPU64InvalidResult};
double outputsNaN2008[kTableLength] = {
3.0, 3.0, 3.0, 4.0, 4.0, 4.0,
-2.0, -2.0, -2.0, -3.0, -3.0, -3.0,
2147483648.0,
0,
dFPU64InvalidResult};
__ cfc1(t1, FCSR);
__ sw(t1, MemOperand(a0, offsetof(Test, isNaN2008)));
__ Ldc1(f4, MemOperand(a0, offsetof(Test, a)));
__ lwc1(f6, MemOperand(a0, offsetof(Test, b)) );
__ ceil_l_d(f8, f4);
__ ceil_l_s(f10, f6);
__ Sdc1(f8, MemOperand(a0, offsetof(Test, c)));
__ Sdc1(f10, MemOperand(a0, offsetof(Test, d)));
__ jr(ra);
__ nop();
Test test;
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
for (int i = 0; i < kTableLength; i++) {
test.a = inputs_D[i];
test.b = inputs_S[i];
(f.Call(&test, 0, 0, 0, 0));
if ((test.isNaN2008 & kFCSRNaN2008FlagMask) &&
kArchVariant == kMips32r6) {
CHECK_EQ(test.c, outputsNaN2008[i]);
} else {
CHECK_EQ(test.c, outputs[i]);
}
CHECK_EQ(test.d, test.c);
}
}
}
TEST(jump_tables1) {
// Test jump tables with forward jumps.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
const int kNumCases = 512;
int values[kNumCases];
isolate->random_number_generator()->NextBytes(values, sizeof(values));
Label labels[kNumCases];
__ addiu(sp, sp, -4);
__ sw(ra, MemOperand(sp));
Label done;
{
__ BlockTrampolinePoolFor(kNumCases + 7);
PredictableCodeSizeScope predictable(&assm, (kNumCases + 7) * kInstrSize);
__ nal();
__ nop();
__ sll(at, a0, 2);
__ addu(at, at, ra);
__ lw(at, MemOperand(at, 5 * kInstrSize));
__ jr(at);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ dd(&labels[i]);
}
}
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
__ lui(v0, (values[i] >> 16) & 0xFFFF);
__ ori(v0, v0, values[i] & 0xFFFF);
__ b(&done);
__ nop();
}
__ bind(&done);
__ lw(ra, MemOperand(sp));
__ addiu(sp, sp, 4);
__ jr(ra);
__ nop();
CHECK_EQ(0, assm.UnboundLabelsCount());
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F1>::FromCode(*code);
for (int i = 0; i < kNumCases; ++i) {
int res = reinterpret_cast<int>(f.Call(i, 0, 0, 0, 0));
::printf("f(%d) = %d\n", i, res);
CHECK_EQ(values[i], res);
}
}
TEST(jump_tables2) {
// Test jump tables with backward jumps.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
const int kNumCases = 512;
int values[kNumCases];
isolate->random_number_generator()->NextBytes(values, sizeof(values));
Label labels[kNumCases];
__ addiu(sp, sp, -4);
__ sw(ra, MemOperand(sp));
Label done, dispatch;
__ b(&dispatch);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
__ lui(v0, (values[i] >> 16) & 0xFFFF);
__ ori(v0, v0, values[i] & 0xFFFF);
__ b(&done);
__ nop();
}
__ bind(&dispatch);
{
__ BlockTrampolinePoolFor(kNumCases + 7);
PredictableCodeSizeScope predictable(&assm, (kNumCases + 7) * kInstrSize);
__ nal();
__ nop();
__ sll(at, a0, 2);
__ addu(at, at, ra);
__ lw(at, MemOperand(at, 5 * kInstrSize));
__ jr(at);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ dd(&labels[i]);
}
}
__ bind(&done);
__ lw(ra, MemOperand(sp));
__ addiu(sp, sp, 4);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F1>::FromCode(*code);
for (int i = 0; i < kNumCases; ++i) {
int res = reinterpret_cast<int>(f.Call(i, 0, 0, 0, 0));
::printf("f(%d) = %d\n", i, res);
CHECK_EQ(values[i], res);
}
}
TEST(jump_tables3) {
// Test jump tables with backward jumps and embedded heap objects.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
Assembler assm(AssemblerOptions{}, nullptr, 0);
const int kNumCases = 256;
Handle<Object> values[kNumCases];
for (int i = 0; i < kNumCases; ++i) {
double value = isolate->random_number_generator()->NextDouble();
values[i] = isolate->factory()->NewHeapNumber(value, TENURED);
}
Label labels[kNumCases];
Object* obj;
int32_t imm32;
__ addiu(sp, sp, -4);
__ sw(ra, MemOperand(sp));
Label done, dispatch;
__ b(&dispatch);
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
obj = *values[i];
imm32 = reinterpret_cast<intptr_t>(obj);
__ lui(v0, (imm32 >> 16) & 0xFFFF);
__ ori(v0, v0, imm32 & 0xFFFF);
__ b(&done);
__ nop();
}
__ bind(&dispatch);
{
__ BlockTrampolinePoolFor(kNumCases + 7);
PredictableCodeSizeScope predictable(&assm, (kNumCases + 7) * kInstrSize);
__ nal();
__ nop();
__ sll(at, a0, 2);
__ addu(at, at, ra);
__ lw(at, MemOperand(at, 5 * kInstrSize));
__ jr(at);
__ nop();
for (int i = 0; i < kNumCases; ++i) {
__ dd(&labels[i]);
}
}
__ bind(&done);
__ lw(ra, MemOperand(sp));
__ addiu(sp, sp, 4);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F1>::FromCode(*code);
for (int i = 0; i < kNumCases; ++i) {
Handle<Object> result(f.Call(i, 0, 0, 0, 0), isolate);
#ifdef OBJECT_PRINT
::printf("f(%d) = ", i);
result->Print(std::cout);
::printf("\n");
#endif
CHECK(values[i].is_identical_to(result));
}
}
TEST(BITSWAP) {
// Test BITSWAP
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
int32_t r1;
int32_t r2;
int32_t r3;
int32_t r4;
} T;
T t;
Assembler assm(AssemblerOptions{}, nullptr, 0);
__ lw(a2, MemOperand(a0, offsetof(T, r1)));
__ nop();
__ bitswap(a1, a2);
__ sw(a1, MemOperand(a0, offsetof(T, r1)));
__ lw(a2, MemOperand(a0, offsetof(T, r2)));
__ nop();
__ bitswap(a1, a2);
__ sw(a1, MemOperand(a0, offsetof(T, r2)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.r1 = 0x781A15C3;
t.r2 = 0x8B71FCDE;
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(static_cast<int32_t>(0x1E58A8C3), t.r1);
CHECK_EQ(static_cast<int32_t>(0xD18E3F7B), t.r2);
}
}
TEST(class_fmt) {
if (IsMipsArchVariant(kMips32r6)) {
// Test CLASS.fmt instruction.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
double dSignalingNan;
double dQuietNan;
double dNegInf;
double dNegNorm;
double dNegSubnorm;
double dNegZero;
double dPosInf;
double dPosNorm;
double dPosSubnorm;
double dPosZero;
float fSignalingNan;
float fQuietNan;
float fNegInf;
float fNegNorm;
float fNegSubnorm;
float fNegZero;
float fPosInf;
float fPosNorm;
float fPosSubnorm;
float fPosZero; } T;
T t;
// Create a function that accepts &t, and loads, manipulates, and stores
// the doubles t.a ... t.f.
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ Ldc1(f4, MemOperand(a0, offsetof(T, dSignalingNan)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dSignalingNan)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dQuietNan)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dQuietNan)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegInf)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegInf)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegNorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegNorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegSubnorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegSubnorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dNegZero)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dNegZero)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosInf)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosInf)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosNorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosNorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosSubnorm)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosSubnorm)));
__ Ldc1(f4, MemOperand(a0, offsetof(T, dPosZero)));
__ class_d(f6, f4);
__ Sdc1(f6, MemOperand(a0, offsetof(T, dPosZero)));
// Testing instruction CLASS.S
__ lwc1(f4, MemOperand(a0, offsetof(T, fSignalingNan)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fSignalingNan)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fQuietNan)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fQuietNan)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegInf)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegInf)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegNorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegNorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegSubnorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegSubnorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fNegZero)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fNegZero)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosInf)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosInf)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosNorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosNorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosSubnorm)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosSubnorm)));
__ lwc1(f4, MemOperand(a0, offsetof(T, fPosZero)));
__ class_s(f6, f4);
__ swc1(f6, MemOperand(a0, offsetof(T, fPosZero)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
t.dSignalingNan = std::numeric_limits<double>::signaling_NaN();
t.dQuietNan = std::numeric_limits<double>::quiet_NaN();
t.dNegInf = -1.0 / 0.0;
t.dNegNorm = -5.0;
t.dNegSubnorm = -DBL_MIN / 2.0;
t.dNegZero = -0.0;
t.dPosInf = 2.0 / 0.0;
t.dPosNorm = 275.35;
t.dPosSubnorm = DBL_MIN / 2.0;
t.dPosZero = +0.0;
// Float test values
t.fSignalingNan = std::numeric_limits<float>::signaling_NaN();
t.fQuietNan = std::numeric_limits<float>::quiet_NaN();
t.fNegInf = -0.5/0.0;
t.fNegNorm = -FLT_MIN;
t.fNegSubnorm = -FLT_MIN / 1.5;
t.fNegZero = -0.0;
t.fPosInf = 100000.0 / 0.0;
t.fPosNorm = FLT_MAX;
t.fPosSubnorm = FLT_MIN / 20.0;
t.fPosZero = +0.0;
f.Call(&t, 0, 0, 0, 0);
// Expected double results.
CHECK_EQ(bit_cast<int64_t>(t.dSignalingNan), 0x001);
CHECK_EQ(bit_cast<int64_t>(t.dQuietNan), 0x002);
CHECK_EQ(bit_cast<int64_t>(t.dNegInf), 0x004);
CHECK_EQ(bit_cast<int64_t>(t.dNegNorm), 0x008);
CHECK_EQ(bit_cast<int64_t>(t.dNegSubnorm), 0x010);
CHECK_EQ(bit_cast<int64_t>(t.dNegZero), 0x020);
CHECK_EQ(bit_cast<int64_t>(t.dPosInf), 0x040);
CHECK_EQ(bit_cast<int64_t>(t.dPosNorm), 0x080);
CHECK_EQ(bit_cast<int64_t>(t.dPosSubnorm), 0x100);
CHECK_EQ(bit_cast<int64_t>(t.dPosZero), 0x200);
// Expected float results.
CHECK_EQ(bit_cast<int32_t>(t.fSignalingNan), 0x001);
CHECK_EQ(bit_cast<int32_t>(t.fQuietNan), 0x002);
CHECK_EQ(bit_cast<int32_t>(t.fNegInf), 0x004);
CHECK_EQ(bit_cast<int32_t>(t.fNegNorm), 0x008);
CHECK_EQ(bit_cast<int32_t>(t.fNegSubnorm), 0x010);
CHECK_EQ(bit_cast<int32_t>(t.fNegZero), 0x020);
CHECK_EQ(bit_cast<int32_t>(t.fPosInf), 0x040);
CHECK_EQ(bit_cast<int32_t>(t.fPosNorm), 0x080);
CHECK_EQ(bit_cast<int32_t>(t.fPosSubnorm), 0x100);
CHECK_EQ(bit_cast<int32_t>(t.fPosZero), 0x200);
}
}
TEST(ABS) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
int64_t fir;
double a;
float b;
double fcsr;
} TestFloat;
TestFloat test;
// Save FIR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ abs_d(f10, f4);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, a)));
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, b)));
__ abs_s(f10, f4);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, b)));
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.a = -2.0;
test.b = -2.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, 2.0);
CHECK_EQ(test.b, 2.0);
test.a = 2.0;
test.b = 2.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, 2.0);
CHECK_EQ(test.b, 2.0);
// Testing biggest positive number
test.a = std::numeric_limits<double>::max();
test.b = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::max());
CHECK_EQ(test.b, std::numeric_limits<float>::max());
// Testing smallest negative number
test.a = -std::numeric_limits<double>::max(); // lowest()
test.b = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::max());
CHECK_EQ(test.b, std::numeric_limits<float>::max());
// Testing smallest positive number
test.a = -std::numeric_limits<double>::min();
test.b = -std::numeric_limits<float>::min();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::min());
CHECK_EQ(test.b, std::numeric_limits<float>::min());
// Testing infinity
test.a = -std::numeric_limits<double>::max()
/ std::numeric_limits<double>::min();
test.b = -std::numeric_limits<float>::max()
/ std::numeric_limits<float>::min();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.a, std::numeric_limits<double>::max()
/ std::numeric_limits<double>::min());
CHECK_EQ(test.b, std::numeric_limits<float>::max()
/ std::numeric_limits<float>::min());
test.a = std::numeric_limits<double>::quiet_NaN();
test.b = std::numeric_limits<float>::quiet_NaN();
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.a));
CHECK(std::isnan(test.b));
test.a = std::numeric_limits<double>::signaling_NaN();
test.b = std::numeric_limits<float>::signaling_NaN();
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.a));
CHECK(std::isnan(test.b));
}
TEST(ADD_FMT) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double a;
double b;
double c;
float fa;
float fb;
float fc;
} TestFloat;
TestFloat test;
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, b)));
__ add_d(f10, f8, f4);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, c)));
__ lwc1(f4, MemOperand(a0, offsetof(TestFloat, fa)));
__ lwc1(f8, MemOperand(a0, offsetof(TestFloat, fb)));
__ add_s(f10, f8, f4);
__ swc1(f10, MemOperand(a0, offsetof(TestFloat, fc)));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.a = 2.0;
test.b = 3.0;
test.fa = 2.0;
test.fb = 3.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.c, 5.0);
CHECK_EQ(test.fc, 5.0);
test.a = std::numeric_limits<double>::max();
test.b = -std::numeric_limits<double>::max(); // lowest()
test.fa = std::numeric_limits<float>::max();
test.fb = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.c, 0.0);
CHECK_EQ(test.fc, 0.0);
test.a = std::numeric_limits<double>::max();
test.b = std::numeric_limits<double>::max();
test.fa = std::numeric_limits<float>::max();
test.fb = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK(!std::isfinite(test.c));
CHECK(!std::isfinite(test.fc));
test.a = 5.0;
test.b = std::numeric_limits<double>::signaling_NaN();
test.fa = 5.0;
test.fb = std::numeric_limits<float>::signaling_NaN();
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.c));
CHECK(std::isnan(test.fc));
}
TEST(C_COND_FMT) {
if ((IsMipsArchVariant(kMips32r1)) || (IsMipsArchVariant(kMips32r2))) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double dOp1;
double dOp2;
uint32_t dF;
uint32_t dUn;
uint32_t dEq;
uint32_t dUeq;
uint32_t dOlt;
uint32_t dUlt;
uint32_t dOle;
uint32_t dUle;
float fOp1;
float fOp2;
uint32_t fF;
uint32_t fUn;
uint32_t fEq;
uint32_t fUeq;
uint32_t fOlt;
uint32_t fUlt;
uint32_t fOle;
uint32_t fUle;
} TestFloat;
TestFloat test;
__ li(t1, 1);
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, dOp1)));
__ Ldc1(f6, MemOperand(a0, offsetof(TestFloat, dOp2)));
__ lwc1(f14, MemOperand(a0, offsetof(TestFloat, fOp1)));
__ lwc1(f16, MemOperand(a0, offsetof(TestFloat, fOp2)));
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(F, f4, f6, 0);
__ c_s(F, f14, f16, 2);
__ movt(t2, t1, 0);
__ movt(t3, t1, 2);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dF)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fF)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(UN, f4, f6, 2);
__ c_s(UN, f14, f16, 4);
__ movt(t2, t1, 2);
__ movt(t3, t1, 4);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUn)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUn)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(EQ, f4, f6, 4);
__ c_s(EQ, f14, f16, 6);
__ movt(t2, t1, 4);
__ movt(t3, t1, 6);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dEq)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fEq)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(UEQ, f4, f6, 6);
__ c_s(UEQ, f14, f16, 0);
__ movt(t2, t1, 6);
__ movt(t3, t1, 0);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUeq)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUeq)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(OLT, f4, f6, 0);
__ c_s(OLT, f14, f16, 2);
__ movt(t2, t1, 0);
__ movt(t3, t1, 2);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dOlt)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fOlt)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(ULT, f4, f6, 2);
__ c_s(ULT, f14, f16, 4);
__ movt(t2, t1, 2);
__ movt(t3, t1, 4);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUlt)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUlt)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(OLE, f4, f6, 4);
__ c_s(OLE, f14, f16, 6);
__ movt(t2, t1, 4);
__ movt(t3, t1, 6);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dOle)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fOle)) );
__ mov(t2, zero_reg);
__ mov(t3, zero_reg);
__ c_d(ULE, f4, f6, 6);
__ c_s(ULE, f14, f16, 0);
__ movt(t2, t1, 6);
__ movt(t3, t1, 0);
__ sw(t2, MemOperand(a0, offsetof(TestFloat, dUle)) );
__ sw(t3, MemOperand(a0, offsetof(TestFloat, fUle)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.dOp1 = 2.0;
test.dOp2 = 3.0;
test.fOp1 = 2.0;
test.fOp2 = 3.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 0U);
CHECK_EQ(test.dEq, 0U);
CHECK_EQ(test.dUeq, 0U);
CHECK_EQ(test.dOlt, 1U);
CHECK_EQ(test.dUlt, 1U);
CHECK_EQ(test.dOle, 1U);
CHECK_EQ(test.dUle, 1U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 0U);
CHECK_EQ(test.fEq, 0U);
CHECK_EQ(test.fUeq, 0U);
CHECK_EQ(test.fOlt, 1U);
CHECK_EQ(test.fUlt, 1U);
CHECK_EQ(test.fOle, 1U);
CHECK_EQ(test.fUle, 1U);
test.dOp1 = std::numeric_limits<double>::max();
test.dOp2 = std::numeric_limits<double>::min();
test.fOp1 = std::numeric_limits<float>::min();
test.fOp2 = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 0U);
CHECK_EQ(test.dEq, 0U);
CHECK_EQ(test.dUeq, 0U);
CHECK_EQ(test.dOlt, 0U);
CHECK_EQ(test.dUlt, 0U);
CHECK_EQ(test.dOle, 0U);
CHECK_EQ(test.dUle, 0U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 0U);
CHECK_EQ(test.fEq, 0U);
CHECK_EQ(test.fUeq, 0U);
CHECK_EQ(test.fOlt, 0U);
CHECK_EQ(test.fUlt, 0U);
CHECK_EQ(test.fOle, 0U);
CHECK_EQ(test.fUle, 0U);
test.dOp1 = -std::numeric_limits<double>::max(); // lowest()
test.dOp2 = -std::numeric_limits<double>::max(); // lowest()
test.fOp1 = std::numeric_limits<float>::max();
test.fOp2 = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 0U);
CHECK_EQ(test.dEq, 1U);
CHECK_EQ(test.dUeq, 1U);
CHECK_EQ(test.dOlt, 0U);
CHECK_EQ(test.dUlt, 0U);
CHECK_EQ(test.dOle, 1U);
CHECK_EQ(test.dUle, 1U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 0U);
CHECK_EQ(test.fEq, 1U);
CHECK_EQ(test.fUeq, 1U);
CHECK_EQ(test.fOlt, 0U);
CHECK_EQ(test.fUlt, 0U);
CHECK_EQ(test.fOle, 1U);
CHECK_EQ(test.fUle, 1U);
test.dOp1 = std::numeric_limits<double>::quiet_NaN();
test.dOp2 = 0.0;
test.fOp1 = std::numeric_limits<float>::quiet_NaN();
test.fOp2 = 0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dF, 0U);
CHECK_EQ(test.dUn, 1U);
CHECK_EQ(test.dEq, 0U);
CHECK_EQ(test.dUeq, 1U);
CHECK_EQ(test.dOlt, 0U);
CHECK_EQ(test.dUlt, 1U);
CHECK_EQ(test.dOle, 0U);
CHECK_EQ(test.dUle, 1U);
CHECK_EQ(test.fF, 0U);
CHECK_EQ(test.fUn, 1U);
CHECK_EQ(test.fEq, 0U);
CHECK_EQ(test.fUeq, 1U);
CHECK_EQ(test.fOlt, 0U);
CHECK_EQ(test.fUlt, 1U);
CHECK_EQ(test.fOle, 0U);
CHECK_EQ(test.fUle, 1U);
}
}
TEST(CMP_COND_FMT) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
double dOp1;
double dOp2;
double dF;
double dUn;
double dEq;
double dUeq;
double dOlt;
double dUlt;
double dOle;
double dUle;
double dOr;
double dUne;
double dNe;
float fOp1;
float fOp2;
float fF;
float fUn;
float fEq;
float fUeq;
float fOlt;
float fUlt;
float fOle;
float fUle;
float fOr;
float fUne;
float fNe;
} TestFloat;
TestFloat test;
__ li(t1, 1);
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, dOp1)));
__ Ldc1(f6, MemOperand(a0, offsetof(TestFloat, dOp2)));
__ lwc1(f14, MemOperand(a0, offsetof(TestFloat, fOp1)));
__ lwc1(f16, MemOperand(a0, offsetof(TestFloat, fOp2)));
__ cmp_d(F, f2, f4, f6);
__ cmp_s(F, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dF)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fF)) );
__ cmp_d(UN, f2, f4, f6);
__ cmp_s(UN, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUn)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUn)) );
__ cmp_d(EQ, f2, f4, f6);
__ cmp_s(EQ, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dEq)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fEq)) );
__ cmp_d(UEQ, f2, f4, f6);
__ cmp_s(UEQ, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUeq)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUeq)) );
__ cmp_d(LT, f2, f4, f6);
__ cmp_s(LT, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dOlt)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fOlt)) );
__ cmp_d(ULT, f2, f4, f6);
__ cmp_s(ULT, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUlt)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUlt)) );
__ cmp_d(LE, f2, f4, f6);
__ cmp_s(LE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dOle)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fOle)) );
__ cmp_d(ULE, f2, f4, f6);
__ cmp_s(ULE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUle)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUle)) );
__ cmp_d(ORD, f2, f4, f6);
__ cmp_s(ORD, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dOr)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fOr)) );
__ cmp_d(UNE, f2, f4, f6);
__ cmp_s(UNE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dUne)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fUne)) );
__ cmp_d(NE, f2, f4, f6);
__ cmp_s(NE, f12, f14, f16);
__ Sdc1(f2, MemOperand(a0, offsetof(TestFloat, dNe)));
__ swc1(f12, MemOperand(a0, offsetof(TestFloat, fNe)) );
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
uint64_t dTrue = 0xFFFFFFFFFFFFFFFF;
uint64_t dFalse = 0x0000000000000000;
uint32_t fTrue = 0xFFFFFFFF;
uint32_t fFalse = 0x00000000;
test.dOp1 = 2.0;
test.dOp2 = 3.0;
test.fOp1 = 2.0;
test.fOp2 = 3.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fTrue);
test.dOp1 = std::numeric_limits<double>::max();
test.dOp2 = std::numeric_limits<double>::min();
test.fOp1 = std::numeric_limits<float>::min();
test.fOp2 = -std::numeric_limits<float>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fFalse);
test.dOp1 = -std::numeric_limits<double>::max(); // lowest()
test.dOp2 = -std::numeric_limits<double>::max(); // lowest()
test.fOp1 = std::numeric_limits<float>::max();
test.fOp2 = std::numeric_limits<float>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fTrue);
test.dOp1 = std::numeric_limits<double>::quiet_NaN();
test.dOp2 = 0.0;
test.fOp1 = std::numeric_limits<float>::quiet_NaN();
test.fOp2 = 0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(bit_cast<uint64_t>(test.dF), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUn), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dEq), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUeq), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOlt), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUlt), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOle), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUle), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dOr), dFalse);
CHECK_EQ(bit_cast<uint64_t>(test.dUne), dTrue);
CHECK_EQ(bit_cast<uint64_t>(test.dNe), dFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fF), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUn), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fEq), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUeq), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOlt), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUlt), fTrue);
CHECK_EQ(bit_cast<uint32_t>(test.fOle), fFalse);
CHECK_EQ(bit_cast<uint32_t>(test.fUle), fTrue);
}
}
TEST(CVT) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test_float {
float cvt_d_s_in;
double cvt_d_s_out;
int32_t cvt_d_w_in;
double cvt_d_w_out;
int64_t cvt_d_l_in;
double cvt_d_l_out;
float cvt_l_s_in;
int64_t cvt_l_s_out;
double cvt_l_d_in;
int64_t cvt_l_d_out;
double cvt_s_d_in;
float cvt_s_d_out;
int32_t cvt_s_w_in;
float cvt_s_w_out;
int64_t cvt_s_l_in;
float cvt_s_l_out;
float cvt_w_s_in;
int32_t cvt_w_s_out;
double cvt_w_d_in;
int32_t cvt_w_d_out;
} TestFloat;
TestFloat test;
// Save FCSR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
#define GENERATE_CVT_TEST(x, y, z) \
__ y##c1(f0, MemOperand(a0, offsetof(TestFloat, x##_in))); \
__ x(f0, f0); \
__ nop(); \
__ z##c1(f0, MemOperand(a0, offsetof(TestFloat, x##_out)));
GENERATE_CVT_TEST(cvt_d_s, lw, Sd)
GENERATE_CVT_TEST(cvt_d_w, lw, Sd)
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
GENERATE_CVT_TEST(cvt_d_l, Ld, Sd)
}
if (IsFp64Mode()) {
GENERATE_CVT_TEST(cvt_l_s, lw, Sd)
GENERATE_CVT_TEST(cvt_l_d, Ld, Sd)
}
GENERATE_CVT_TEST(cvt_s_d, Ld, sw)
GENERATE_CVT_TEST(cvt_s_w, lw, sw)
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
GENERATE_CVT_TEST(cvt_s_l, Ld, sw)
}
GENERATE_CVT_TEST(cvt_w_s, lw, sw)
GENERATE_CVT_TEST(cvt_w_d, Ld, sw)
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
test.cvt_d_s_in = -0.51;
test.cvt_d_w_in = -1;
test.cvt_d_l_in = -1;
test.cvt_l_s_in = -0.51;
test.cvt_l_d_in = -0.51;
test.cvt_s_d_in = -0.51;
test.cvt_s_w_in = -1;
test.cvt_s_l_in = -1;
test.cvt_w_s_in = -0.51;
test.cvt_w_d_in = -0.51;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(-1, test.cvt_l_s_out);
CHECK_EQ(-1, test.cvt_l_d_out);
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(-1, test.cvt_w_s_out);
CHECK_EQ(-1, test.cvt_w_d_out);
test.cvt_d_s_in = 0.49;
test.cvt_d_w_in = 1;
test.cvt_d_l_in = 1;
test.cvt_l_s_in = 0.49;
test.cvt_l_d_in = 0.49;
test.cvt_s_d_in = 0.49;
test.cvt_s_w_in = 1;
test.cvt_s_l_in = 1;
test.cvt_w_s_in = 0.49;
test.cvt_w_d_in = 0.49;
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(0, test.cvt_l_s_out);
CHECK_EQ(0, test.cvt_l_d_out);
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(0, test.cvt_w_s_out);
CHECK_EQ(0, test.cvt_w_d_out);
test.cvt_d_s_in = std::numeric_limits<float>::max();
test.cvt_d_w_in = std::numeric_limits<int32_t>::max();
test.cvt_d_l_in = std::numeric_limits<int64_t>::max();
test.cvt_l_s_in = std::numeric_limits<float>::max();
test.cvt_l_d_in = std::numeric_limits<double>::max();
test.cvt_s_d_in = std::numeric_limits<double>::max();
test.cvt_s_w_in = std::numeric_limits<int32_t>::max();
test.cvt_s_l_in = std::numeric_limits<int64_t>::max();
test.cvt_w_s_in = std::numeric_limits<float>::max();
test.cvt_w_d_in = std::numeric_limits<double>::max();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(test.cvt_l_s_out, std::numeric_limits<int64_t>::max());
CHECK_EQ(test.cvt_l_d_out, std::numeric_limits<int64_t>::max());
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(test.cvt_w_s_out, std::numeric_limits<int32_t>::max());
CHECK_EQ(test.cvt_w_d_out, std::numeric_limits<int32_t>::max());
test.cvt_d_s_in = -std::numeric_limits<float>::max(); // lowest()
test.cvt_d_w_in = std::numeric_limits<int32_t>::min(); // lowest()
test.cvt_d_l_in = std::numeric_limits<int64_t>::min(); // lowest()
test.cvt_l_s_in = -std::numeric_limits<float>::max(); // lowest()
test.cvt_l_d_in = -std::numeric_limits<double>::max(); // lowest()
test.cvt_s_d_in = -std::numeric_limits<double>::max(); // lowest()
test.cvt_s_w_in = std::numeric_limits<int32_t>::min(); // lowest()
test.cvt_s_l_in = std::numeric_limits<int64_t>::min(); // lowest()
test.cvt_w_s_in = -std::numeric_limits<float>::max(); // lowest()
test.cvt_w_d_in = -std::numeric_limits<double>::max(); // lowest()
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
// The returned value when converting from fixed-point to float-point
// is not consistent between board, simulator and specification
// in this test case, therefore modifying the test
if (IsFp64Mode()) {
CHECK(test.cvt_l_s_out == std::numeric_limits<int64_t>::min() ||
test.cvt_l_s_out == std::numeric_limits<int64_t>::max());
CHECK(test.cvt_l_d_out == std::numeric_limits<int64_t>::min() ||
test.cvt_l_d_out == std::numeric_limits<int64_t>::max());
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK(test.cvt_w_s_out == std::numeric_limits<int32_t>::min() ||
test.cvt_w_s_out == std::numeric_limits<int32_t>::max());
CHECK(test.cvt_w_d_out == std::numeric_limits<int32_t>::min() ||
test.cvt_w_d_out == std::numeric_limits<int32_t>::max());
test.cvt_d_s_in = std::numeric_limits<float>::min();
test.cvt_d_w_in = std::numeric_limits<int32_t>::min();
test.cvt_d_l_in = std::numeric_limits<int64_t>::min();
test.cvt_l_s_in = std::numeric_limits<float>::min();
test.cvt_l_d_in = std::numeric_limits<double>::min();
test.cvt_s_d_in = std::numeric_limits<double>::min();
test.cvt_s_w_in = std::numeric_limits<int32_t>::min();
test.cvt_s_l_in = std::numeric_limits<int64_t>::min();
test.cvt_w_s_in = std::numeric_limits<float>::min();
test.cvt_w_d_in = std::numeric_limits<double>::min();
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.cvt_d_s_out, static_cast<double>(test.cvt_d_s_in));
CHECK_EQ(test.cvt_d_w_out, static_cast<double>(test.cvt_d_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_d_l_out, static_cast<double>(test.cvt_d_l_in));
}
if (IsFp64Mode()) {
CHECK_EQ(0, test.cvt_l_s_out);
CHECK_EQ(0, test.cvt_l_d_out);
}
CHECK_EQ(test.cvt_s_d_out, static_cast<float>(test.cvt_s_d_in));
CHECK_EQ(test.cvt_s_w_out, static_cast<float>(test.cvt_s_w_in));
if ((IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) &&
IsFp64Mode()) {
CHECK_EQ(test.cvt_s_l_out, static_cast<float>(test.cvt_s_l_in));
}
CHECK_EQ(0, test.cvt_w_s_out);
CHECK_EQ(0, test.cvt_w_d_out);
}
TEST(DIV_FMT) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
typedef struct test {
double dOp1;
double dOp2;
double dRes;
float fOp1;
float fOp2;
float fRes;
} Test;
Test test;
// Save FCSR.
__ cfc1(a1, FCSR);
// Disable FPU exceptions.
__ ctc1(zero_reg, FCSR);
__ Ldc1(f4, MemOperand(a0, offsetof(Test, dOp1)));
__ Ldc1(f2, MemOperand(a0, offsetof(Test, dOp2)));
__ nop();
__ div_d(f6, f4, f2);
__ Sdc1(f6, MemOperand(a0, offsetof(Test, dRes)));
__ lwc1(f4, MemOperand(a0, offsetof(Test, fOp1)) );
__ lwc1(f2, MemOperand(a0, offsetof(Test, fOp2)) );
__ nop();
__ div_s(f6, f4, f2);
__ swc1(f6, MemOperand(a0, offsetof(Test, fRes)) );
// Restore FCSR.
__ ctc1(a1, FCSR);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&test, 0, 0, 0, 0));
const int test_size = 3;
double dOp1[test_size] = {
5.0,
DBL_MAX,
DBL_MAX,
};
double dOp2[test_size] = {
2.0,
2.0,
-DBL_MAX,
};
double dRes[test_size] = {
2.5,
DBL_MAX / 2.0,
-1.0,
};
float fOp1[test_size] = {
5.0,
FLT_MAX,
FLT_MAX,
};
float fOp2[test_size] = {
2.0,
2.0,
-FLT_MAX,
};
float fRes[test_size] = {
2.5,
FLT_MAX / 2.0,
-1.0,
};
for (int i = 0; i < test_size; i++) {
test.dOp1 = dOp1[i];
test.dOp2 = dOp2[i];
test.fOp1 = fOp1[i];
test.fOp2 = fOp2[i];
(f.Call(&test, 0, 0, 0, 0));
CHECK_EQ(test.dRes, dRes[i]);
CHECK_EQ(test.fRes, fRes[i]);
}
test.dOp1 = DBL_MAX;
test.dOp2 = -0.0;
test.fOp1 = FLT_MAX;
test.fOp2 = -0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK(!std::isfinite(test.dRes));
CHECK(!std::isfinite(test.fRes));
test.dOp1 = 0.0;
test.dOp2 = -0.0;
test.fOp1 = 0.0;
test.fOp2 = -0.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.dRes));
CHECK(std::isnan(test.fRes));
test.dOp1 = std::numeric_limits<double>::quiet_NaN();
test.dOp2 = -5.0;
test.fOp1 = std::numeric_limits<float>::quiet_NaN();
test.fOp2 = -5.0;
(f.Call(&test, 0, 0, 0, 0));
CHECK(std::isnan(test.dRes));
CHECK(std::isnan(test.fRes));
}
uint32_t run_align(uint32_t rs_value, uint32_t rt_value, uint8_t bp) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ align(v0, a0, a1, bp);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res =
reinterpret_cast<uint32_t>(f.Call(rs_value, rt_value, 0, 0, 0));
return res;
}
TEST(r6_align) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAlign {
uint32_t rs_value;
uint32_t rt_value;
uint8_t bp;
uint32_t expected_res;
};
// clang-format off
struct TestCaseAlign tc[] = {
// rs_value, rt_value, bp, expected_res
{0x11223344, 0xAABBCCDD, 0, 0xAABBCCDD},
{0x11223344, 0xAABBCCDD, 1, 0xBBCCDD11},
{0x11223344, 0xAABBCCDD, 2, 0xCCDD1122},
{0x11223344, 0xAABBCCDD, 3, 0xDD112233},
};
// clang-format on
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAlign);
for (size_t i = 0; i < nr_test_cases; ++i) {
CHECK_EQ(tc[i].expected_res, run_align(tc[i].rs_value,
tc[i].rt_value, tc[i].bp));
}
}
}
uint32_t PC; // The program counter.
uint32_t run_aluipc(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ aluipc(v0, offset);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
PC = (uint32_t)code->entry(); // Set the program counter.
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_aluipc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAluipc {
int16_t offset;
};
struct TestCaseAluipc tc[] = {
// offset
{ -32768 }, // 0x8000
{ -1 }, // 0xFFFF
{ 0 },
{ 1 },
{ 32767 }, // 0x7FFF
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAluipc);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_aluipc(tc[i].offset);
// Now, the program_counter (PC) is set.
uint32_t expected_res = ~0x0FFFF & (PC + (tc[i].offset << 16));
CHECK_EQ(expected_res, res);
}
}
}
uint32_t run_auipc(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ auipc(v0, offset);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
PC = (uint32_t)code->entry(); // Set the program counter.
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_auipc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAuipc {
int16_t offset;
};
struct TestCaseAuipc tc[] = {
// offset
{ -32768 }, // 0x8000
{ -1 }, // 0xFFFF
{ 0 },
{ 1 },
{ 32767 }, // 0x7FFF
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAuipc);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_auipc(tc[i].offset);
// Now, the program_counter (PC) is set.
uint32_t expected_res = PC + (tc[i].offset << 16);
CHECK_EQ(expected_res, res);
}
}
}
uint32_t run_lwpc(int offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
// 256k instructions; 2^8k
// addiu t7, t0, 0xFFFF; (0x250FFFFF)
// ...
// addiu t4, t0, 0x0000; (0x250C0000)
uint32_t addiu_start_1 = 0x25000000;
for (int32_t i = 0xFFFFF; i >= 0xC0000; --i) {
uint32_t addiu_new = addiu_start_1 + i;
__ dd(addiu_new);
}
__ lwpc(t8, offset); // offset 0; 0xEF080000 (t8 register)
__ mov(v0, t8);
// 256k instructions; 2^8k
// addiu t0, t0, 0x0000; (0x25080000)
// ...
// addiu t3, t0, 0xFFFF; (0x250BFFFF)
uint32_t addiu_start_2 = 0x25000000;
for (int32_t i = 0x80000; i <= 0xBFFFF; ++i) {
uint32_t addiu_new = addiu_start_2 + i;
__ dd(addiu_new);
}
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_lwpc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseLwpc {
int offset;
uint32_t expected_res;
};
// clang-format off
struct TestCaseLwpc tc[] = {
// offset, expected_res
{ -262144, 0x250FFFFF }, // offset 0x40000
{ -4, 0x250C0003 },
{ -1, 0x250C0000 },
{ 0, 0xEF080000 },
{ 1, 0x03001025 }, // mov(v0, t8)
{ 2, 0x25080000 },
{ 4, 0x25080002 },
{ 262143, 0x250BFFFD }, // offset 0x3FFFF
};
// clang-format on
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseLwpc);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_lwpc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
uint32_t run_jic(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label get_program_counter, stop_execution;
__ push(ra);
__ li(v0, 0);
__ li(t1, 0x66);
__ addiu(v0, v0, 0x1); // <-- offset = -32
__ addiu(v0, v0, 0x2);
__ addiu(v0, v0, 0x10);
__ addiu(v0, v0, 0x20);
__ beq(v0, t1, &stop_execution);
__ nop();
__ nal(); // t0 <- program counter
__ mov(t0, ra);
__ jic(t0, offset);
__ addiu(v0, v0, 0x100);
__ addiu(v0, v0, 0x200);
__ addiu(v0, v0, 0x1000);
__ addiu(v0, v0, 0x2000); // <--- offset = 16
__ pop(ra);
__ jr(ra);
__ nop();
__ bind(&stop_execution);
__ pop(ra);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_jic) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseJic {
// As rt will be used t0 register which will have value of
// the program counter for the jic instruction.
int16_t offset;
uint32_t expected_res;
};
struct TestCaseJic tc[] = {
// offset, expected_result
{ 16, 0x2033 },
{ 4, 0x3333 },
{ -32, 0x66 },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseJic);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_jic(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
uint64_t run_beqzc(int32_t value, int32_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label stop_execution;
__ li(v0, 0);
__ li(t1, 0x66);
__ addiu(v0, v0, 0x1); // <-- offset = -32
__ addiu(v0, v0, 0x2);
__ addiu(v0, v0, 0x10);
__ addiu(v0, v0, 0x20);
__ beq(v0, t1, &stop_execution);
__ nop();
__ beqzc(a0, offset); // BEQZC rs, offset
__ addiu(v0, v0, 0x1);
__ addiu(v0, v0, 0x100);
__ addiu(v0, v0, 0x200);
__ addiu(v0, v0, 0x1000);
__ addiu(v0, v0, 0x2000); // <--- offset = 16
__ jr(ra);
__ nop();
__ bind(&stop_execution);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(value, 0, 0, 0, 0));
return res;
}
TEST(r6_beqzc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseBeqzc {
uint32_t value;
int32_t offset;
uint32_t expected_res;
};
// clang-format off
struct TestCaseBeqzc tc[] = {
// value, offset, expected_res
{ 0x0, -8, 0x66 },
{ 0x0, 0, 0x3334 },
{ 0x0, 1, 0x3333 },
{ 0xABC, 1, 0x3334 },
{ 0x0, 4, 0x2033 },
};
// clang-format on
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBeqzc);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_beqzc(tc[i].value, tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
void load_elements_of_vector(MacroAssembler& assm, const uint64_t elements[],
MSARegister w, Register t0, Register t1) {
__ li(t0, static_cast<uint32_t>(elements[0] & 0xFFFFFFFF));
__ li(t1, static_cast<uint32_t>((elements[0] >> 32) & 0xFFFFFFFF));
__ insert_w(w, 0, t0);
__ insert_w(w, 1, t1);
__ li(t0, static_cast<uint32_t>(elements[1] & 0xFFFFFFFF));
__ li(t1, static_cast<uint32_t>((elements[1] >> 32) & 0xFFFFFFFF));
__ insert_w(w, 2, t0);
__ insert_w(w, 3, t1);
}
inline void store_elements_of_vector(MacroAssembler& assm, MSARegister w,
Register a) {
__ st_d(w, MemOperand(a, 0));
}
typedef union {
uint8_t b[16];
uint16_t h[8];
uint32_t w[4];
uint64_t d[2];
} msa_reg_t;
struct TestCaseMsaBranch {
uint64_t wt_lo;
uint64_t wt_hi;
};
template <typename Branch>
void run_bz_bnz(TestCaseMsaBranch* input, Branch GenerateBranch,
bool branched) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, NULL, 0, v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
typedef struct {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wd_lo;
uint64_t wd_hi;
} T;
T t = {0x20B9CC4F1A83E0C5, 0xA27E1B5F2F5BB18A, 0x0000000000000000,
0x0000000000000000};
msa_reg_t res;
Label do_not_move_w0_to_w2;
load_elements_of_vector(assm, &t.ws_lo, w0, t0, t1);
load_elements_of_vector(assm, &t.wd_lo, w2, t0, t1);
load_elements_of_vector(assm, &input->wt_lo, w1, t0, t1);
GenerateBranch(assm, do_not_move_w0_to_w2);
__ nop();
__ move_v(w2, w0);
__ bind(&do_not_move_w0_to_w2);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
if (branched) {
CHECK_EQ(t.wd_lo, res.d[0]);
CHECK_EQ(t.wd_hi, res.d[1]);
} else {
CHECK_EQ(t.ws_lo, res.d[0]);
CHECK_EQ(t.ws_hi, res.d[1]);
}
}
TEST(MSA_bz_bnz) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
TestCaseMsaBranch tz_v[] = {
{0x0, 0x0}, {0xABC, 0x0}, {0x0, 0xABC}, {0xABC, 0xABC}};
for (unsigned i = 0; i < arraysize(tz_v); ++i) {
run_bz_bnz(
&tz_v[i],
[](MacroAssembler& assm, Label& br_target) { __ bz_v(w1, &br_target); },
tz_v[i].wt_lo == 0 && tz_v[i].wt_hi == 0);
}
#define TEST_BZ_DF(input_array, lanes, instruction, int_type) \
for (unsigned i = 0; i < arraysize(input_array); ++i) { \
int j; \
int_type* element = reinterpret_cast<int_type*>(&input_array[i]); \
for (j = 0; j < lanes; ++j) { \
if (element[j] == 0) { \
break; \
} \
} \
run_bz_bnz(&input_array[i], \
[](MacroAssembler& assm, Label& br_target) { \
__ instruction(w1, &br_target); \
}, \
j != lanes); \
}
TestCaseMsaBranch tz_b[] = {{0x0, 0x0},
{0xBC0000, 0x0},
{0x0, 0xAB000000000000CD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_b, kMSALanesByte, bz_b, int8_t)
TestCaseMsaBranch tz_h[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_h, kMSALanesHalf, bz_h, int16_t)
TestCaseMsaBranch tz_w[] = {{0x0, 0x0},
{0xBCDE123400000000, 0x0},
{0x0, 0x000000001234ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_w, kMSALanesWord, bz_w, int32_t)
TestCaseMsaBranch tz_d[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BZ_DF(tz_d, kMSALanesDword, bz_d, int64_t)
#undef TEST_BZ_DF
TestCaseMsaBranch tnz_v[] = {
{0x0, 0x0}, {0xABC, 0x0}, {0x0, 0xABC}, {0xABC, 0xABC}};
for (unsigned i = 0; i < arraysize(tnz_v); ++i) {
run_bz_bnz(&tnz_v[i],
[](MacroAssembler& assm, Label& br_target) {
__ bnz_v(w1, &br_target);
},
tnz_v[i].wt_lo != 0 || tnz_v[i].wt_hi != 0);
}
#define TEST_BNZ_DF(input_array, lanes, instruction, int_type) \
for (unsigned i = 0; i < arraysize(input_array); ++i) { \
int j; \
int_type* element = reinterpret_cast<int_type*>(&input_array[i]); \
for (j = 0; j < lanes; ++j) { \
if (element[j] == 0) { \
break; \
} \
} \
run_bz_bnz(&input_array[i], \
[](MacroAssembler& assm, Label& br_target) { \
__ instruction(w1, &br_target); \
}, \
j == lanes); \
}
TestCaseMsaBranch tnz_b[] = {{0x0, 0x0},
{0xBC0000, 0x0},
{0x0, 0xAB000000000000CD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_b, 16, bnz_b, int8_t)
TestCaseMsaBranch tnz_h[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_h, 8, bnz_h, int16_t)
TestCaseMsaBranch tnz_w[] = {{0x0, 0x0},
{0xBCDE123400000000, 0x0},
{0x0, 0x000000001234ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_w, 4, bnz_w, int32_t)
TestCaseMsaBranch tnz_d[] = {{0x0, 0x0},
{0xBCDE0000, 0x0},
{0x0, 0xABCD00000000ABCD},
{0x123456789ABCDEF0, 0xAAAAAAAAAAAAAAAA}};
TEST_BNZ_DF(tnz_d, 2, bnz_d, int64_t)
#undef TEST_BNZ_DF
}
uint32_t run_jialc(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label main_block, get_program_counter;
__ push(ra);
__ li(v0, 0);
__ beq(v0, v0, &main_block);
__ nop();
// Block 1
__ addiu(v0, v0, 0x1); // <-- offset = -40
__ addiu(v0, v0, 0x2);
__ jr(ra);
__ nop();
// Block 2
__ addiu(v0, v0, 0x10); // <-- offset = -24
__ addiu(v0, v0, 0x20);
__ jr(ra);
__ nop();
// Block 3 (Main)
__ bind(&main_block);
__ nal(); // t0 <- program counter
__ mov(t0, ra);
__ jialc(t0, offset);
__ addiu(v0, v0, 0x4);
__ pop(ra);
__ jr(ra);
__ nop();
// Block 4
__ addiu(v0, v0, 0x100); // <-- offset = 20
__ addiu(v0, v0, 0x200);
__ jr(ra);
__ nop();
// Block 5
__ addiu(v0, v0, 0x1000); // <--- offset = 36
__ addiu(v0, v0, 0x2000);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_jialc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseJialc {
int16_t offset;
uint32_t expected_res;
};
struct TestCaseJialc tc[] = {
// offset, expected_res
{ -40, 0x7 },
{ -24, 0x34 },
{ 20, 0x304 },
{ 36, 0x3004 }
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseJialc);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_jialc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
static uint32_t run_addiupc(int32_t imm19) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ addiupc(v0, imm19);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
PC = (uint32_t)code->entry(); // Set the program counter.
uint32_t rs = reinterpret_cast<uint32_t>(f.Call(imm19, 0, 0, 0, 0));
return rs;
}
TEST(r6_addiupc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAddiupc {
int32_t imm19;
};
TestCaseAddiupc tc[] = {
// imm19
{-262144}, // 0x40000
{-1}, // 0x7FFFF
{0},
{1}, // 0x00001
{262143} // 0x3FFFF
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAddiupc);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_addiupc(tc[i].imm19);
// Now, the program_counter (PC) is set.
uint32_t expected_res = PC + (tc[i].imm19 << 2);
CHECK_EQ(expected_res, res);
}
}
}
int32_t run_bc(int32_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label continue_1, stop_execution;
__ push(ra);
__ li(v0, 0);
__ li(t8, 0);
__ li(t9, 2); // A condition for stopping execution.
for (int32_t i = -100; i <= -11; ++i) {
__ addiu(v0, v0, 1);
}
__ addiu(t8, t8, 1); // -10
__ beq(t8, t9, &stop_execution); // -9
__ nop(); // -8
__ beq(t8, t8, &continue_1); // -7
__ nop(); // -6
__ bind(&stop_execution);
__ pop(ra); // -5, -4
__ jr(ra); // -3
__ nop(); // -2
__ bind(&continue_1);
__ bc(offset); // -1
for (int32_t i = 0; i <= 99; ++i) {
__ addiu(v0, v0, 1);
}
__ pop(ra);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int32_t res = reinterpret_cast<int32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_bc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseBc {
int32_t offset;
int32_t expected_res;
};
struct TestCaseBc tc[] = {
// offset, expected_result
{ -100, (abs(-100) - 10) * 2 },
{ -11, (abs(-100) - 10 + 1) },
{ 0, (abs(-100) - 10 + 1 + 99) },
{ 1, (abs(-100) - 10 + 99) },
{ 99, (abs(-100) - 10 + 1) },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBc);
for (size_t i = 0; i < nr_test_cases; ++i) {
int32_t res = run_bc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
int32_t run_balc(int32_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label continue_1, stop_execution;
__ push(ra);
__ li(v0, 0);
__ li(t8, 0);
__ li(t9, 2); // A condition for stopping execution.
__ beq(t8, t8, &continue_1);
__ nop();
uint32_t instruction_addiu = 0x24420001; // addiu v0, v0, 1
for (int32_t i = -117; i <= -57; ++i) {
__ dd(instruction_addiu);
}
__ jr(ra); // -56
__ nop(); // -55
for (int32_t i = -54; i <= -4; ++i) {
__ dd(instruction_addiu);
}
__ jr(ra); // -3
__ nop(); // -2
__ bind(&continue_1);
__ balc(offset); // -1
__ pop(ra); // 0, 1
__ jr(ra); // 2
__ nop(); // 3
for (int32_t i = 4; i <= 44; ++i) {
__ dd(instruction_addiu);
}
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int32_t res = reinterpret_cast<int32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
uint32_t run_aui(uint32_t rs, uint16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ li(t0, rs);
__ aui(v0, t0, offset);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(r6_aui) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseAui {
uint32_t rs;
uint16_t offset;
uint32_t ref_res;
};
struct TestCaseAui tc[] = {
// input, offset, result
{0xFFFEFFFF, 1, 0xFFFFFFFF},
{0xFFFFFFFF, 0, 0xFFFFFFFF},
{0, 0xFFFF, 0xFFFF0000},
{0x0008FFFF, 0xFFF7, 0xFFFFFFFF},
{32767, 32767, 0x7FFF7FFF},
// overflow cases
{0xFFFFFFFF, 0x1, 0x0000FFFF},
{0xFFFFFFFF, 0xFFFF, 0xFFFEFFFF},
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseAui);
for (size_t i = 0; i < nr_test_cases; ++i) {
PC = 0;
uint32_t res = run_aui(tc[i].rs, tc[i].offset);
CHECK_EQ(tc[i].ref_res, res);
}
}
}
TEST(r6_balc) {
if (IsMipsArchVariant(kMips32r6)) {
CcTest::InitializeVM();
struct TestCaseBalc {
int32_t offset;
int32_t expected_res;
};
struct TestCaseBalc tc[] = {
// offset, expected_result
{ -117, 61 },
{ -54, 51 },
{ 0, 0 },
{ 4, 41 },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBalc);
for (size_t i = 0; i < nr_test_cases; ++i) {
int32_t res = run_balc(tc[i].offset);
CHECK_EQ(tc[i].expected_res, res);
}
}
}
uint32_t run_bal(int16_t offset) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ mov(t0, ra);
__ bal(offset); // Equivalent for "BGEZAL zero_reg, offset".
__ nop();
__ mov(ra, t0);
__ jr(ra);
__ nop();
__ li(v0, 1);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(bal) {
CcTest::InitializeVM();
struct TestCaseBal {
int16_t offset;
uint32_t expected_res;
};
struct TestCaseBal tc[] = {
// offset, expected_res
{ 4, 1 },
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseBal);
for (size_t i = 0; i < nr_test_cases; ++i) {
CHECK_EQ(tc[i].expected_res, run_bal(tc[i].offset));
}
}
TEST(Trampoline) {
// Private member of Assembler class.
static const int kMaxBranchOffset = (1 << (18 - 1)) - 1;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label done;
size_t nr_calls = kMaxBranchOffset / (2 * kInstrSize) + 2;
for (size_t i = 0; i < nr_calls; ++i) {
__ BranchShort(&done, eq, a0, Operand(a1));
}
__ bind(&done);
__ Ret(USE_DELAY_SLOT);
__ mov(v0, zero_reg);
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
int32_t res = reinterpret_cast<int32_t>(f.Call(42, 42, 0, 0, 0));
CHECK_EQ(0, res);
}
template <class T>
struct TestCaseMaddMsub {
T fr, fs, ft, fd_add, fd_sub;
};
template <typename T, typename F>
void helper_madd_msub_maddf_msubf(F func) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
T x = std::sqrt(static_cast<T>(2.0));
T y = std::sqrt(static_cast<T>(3.0));
T z = std::sqrt(static_cast<T>(5.0));
T x2 = 11.11, y2 = 22.22, z2 = 33.33;
TestCaseMaddMsub<T> test_cases[] = {
{x, y, z, 0.0, 0.0},
{x, y, -z, 0.0, 0.0},
{x, -y, z, 0.0, 0.0},
{x, -y, -z, 0.0, 0.0},
{-x, y, z, 0.0, 0.0},
{-x, y, -z, 0.0, 0.0},
{-x, -y, z, 0.0, 0.0},
{-x, -y, -z, 0.0, 0.0},
{-3.14, 0.2345, -123.000056, 0.0, 0.0},
{7.3, -23.257, -357.1357, 0.0, 0.0},
{x2, y2, z2, 0.0, 0.0},
{x2, y2, -z2, 0.0, 0.0},
{x2, -y2, z2, 0.0, 0.0},
{x2, -y2, -z2, 0.0, 0.0},
{-x2, y2, z2, 0.0, 0.0},
{-x2, y2, -z2, 0.0, 0.0},
{-x2, -y2, z2, 0.0, 0.0},
{-x2, -y2, -z2, 0.0, 0.0},
};
if (std::is_same<T, float>::value) {
__ lwc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
__ lwc1(f6, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fs)));
__ lwc1(f8, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, ft)));
__ lwc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
} else if (std::is_same<T, double>::value) {
__ Ldc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
__ Ldc1(f6, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fs)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, ft)));
__ Ldc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<T>, fr)));
} else {
UNREACHABLE();
}
func(assm);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F3>::FromCode(*code);
const size_t kTableLength = sizeof(test_cases) / sizeof(TestCaseMaddMsub<T>);
TestCaseMaddMsub<T> tc;
for (size_t i = 0; i < kTableLength; i++) {
tc.fr = test_cases[i].fr;
tc.fs = test_cases[i].fs;
tc.ft = test_cases[i].ft;
(f.Call(&tc, 0, 0, 0, 0));
T res_add = 0;
T res_sub = 0;
if (IsMipsArchVariant(kMips32r2)) {
res_add = (tc.fs * tc.ft) + tc.fr;
res_sub = (tc.fs * tc.ft) - tc.fr;
} else if (IsMipsArchVariant(kMips32r6)) {
res_add = std::fma(tc.fs, tc.ft, tc.fr);
res_sub = std::fma(-tc.fs, tc.ft, tc.fr);
} else {
UNREACHABLE();
}
CHECK_EQ(tc.fd_add, res_add);
CHECK_EQ(tc.fd_sub, res_sub);
}
}
TEST(madd_msub_s) {
if (!IsMipsArchVariant(kMips32r2)) return;
helper_madd_msub_maddf_msubf<float>([](MacroAssembler& assm) {
__ madd_s(f10, f4, f6, f8);
__ swc1(f10, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_add)));
__ msub_s(f16, f4, f6, f8);
__ swc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_sub)));
});
}
TEST(madd_msub_d) {
if (!IsMipsArchVariant(kMips32r2)) return;
helper_madd_msub_maddf_msubf<double>([](MacroAssembler& assm) {
__ madd_d(f10, f4, f6, f8);
__ Sdc1(f10, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_add)));
__ msub_d(f16, f4, f6, f8);
__ Sdc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_sub)));
});
}
TEST(maddf_msubf_s) {
if (!IsMipsArchVariant(kMips32r6)) return;
helper_madd_msub_maddf_msubf<float>([](MacroAssembler& assm) {
__ maddf_s(f4, f6, f8);
__ swc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_add)));
__ msubf_s(f16, f6, f8);
__ swc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<float>, fd_sub)));
});
}
TEST(maddf_msubf_d) {
if (!IsMipsArchVariant(kMips32r6)) return;
helper_madd_msub_maddf_msubf<double>([](MacroAssembler& assm) {
__ maddf_d(f4, f6, f8);
__ Sdc1(f4, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_add)));
__ msubf_d(f16, f6, f8);
__ Sdc1(f16, MemOperand(a0, offsetof(TestCaseMaddMsub<double>, fd_sub)));
});
}
uint32_t run_Subu(uint32_t imm, int32_t num_instr) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
Label code_start;
__ bind(&code_start);
__ Subu(v0, zero_reg, imm);
CHECK_EQ(assm.SizeOfCodeGeneratedSince(&code_start), num_instr * kInstrSize);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(Subu) {
CcTest::InitializeVM();
// Test Subu macro-instruction for min_int16 and max_int16 border cases.
// For subtracting int16 immediate values we use addiu.
struct TestCaseSubu {
uint32_t imm;
uint32_t expected_res;
int32_t num_instr;
};
// We call Subu(v0, zero_reg, imm) to test cases listed below.
// 0 - imm = expected_res
struct TestCaseSubu tc[] = {
// imm, expected_res, num_instr
{0xFFFF8000, 0x8000, 2}, // min_int16
// Generates ori + addu
// We can't have just addiu because -min_int16 > max_int16 so use
// register. We can load min_int16 to at register with addiu and then
// subtract at with subu, but now we use ori + addu because -min_int16 can
// be loaded using ori.
{0x8000, 0xFFFF8000, 1}, // max_int16 + 1
// Generates addiu
// max_int16 + 1 is not int16 but -(max_int16 + 1) is, just use addiu.
{0xFFFF7FFF, 0x8001, 2}, // min_int16 - 1
// Generates ori + addu
// To load this value to at we need two instructions and another one to
// subtract, lui + ori + subu. But we can load -value to at using just
// ori and then add at register with addu.
{0x8001, 0xFFFF7FFF, 2}, // max_int16 + 2
// Generates ori + subu
// Not int16 but is uint16, load value to at with ori and subtract with
// subu.
{0x00010000, 0xFFFF0000, 2},
// Generates lui + subu
// Load value using lui to at and subtract with subu.
{0x00010001, 0xFFFEFFFF, 3},
// Generates lui + ori + subu
// We have to generate three instructions in this case.
};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseSubu);
for (size_t i = 0; i < nr_test_cases; ++i) {
CHECK_EQ(tc[i].expected_res, run_Subu(tc[i].imm, tc[i].num_instr));
}
}
TEST(MSA_fill_copy) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint32_t u8;
uint32_t u16;
uint32_t u32;
uint32_t s8;
uint32_t s16;
uint32_t s32;
} T;
T t;
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
{
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, 0xA512B683);
__ fill_b(w0, t0);
__ fill_h(w2, t0);
__ fill_w(w4, t0);
__ copy_u_b(t1, w0, 11);
__ sw(t1, MemOperand(a0, offsetof(T, u8)));
__ copy_u_h(t1, w2, 6);
__ sw(t1, MemOperand(a0, offsetof(T, u16)));
__ copy_u_w(t1, w4, 3);
__ sw(t1, MemOperand(a0, offsetof(T, u32)));
__ copy_s_b(t1, w0, 8);
__ sw(t1, MemOperand(a0, offsetof(T, s8)));
__ copy_s_h(t1, w2, 5);
__ sw(t1, MemOperand(a0, offsetof(T, s16)));
__ copy_s_w(t1, w4, 1);
__ sw(t1, MemOperand(a0, offsetof(T, s32)));
__ jr(ra);
__ nop();
}
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
f.Call(&t, 0, 0, 0, 0);
CHECK_EQ(0x83u, t.u8);
CHECK_EQ(0xB683u, t.u16);
CHECK_EQ(0xA512B683u, t.u32);
CHECK_EQ(0xFFFFFF83u, t.s8);
CHECK_EQ(0xFFFFB683u, t.s16);
CHECK_EQ(0xA512B683u, t.s32);
}
TEST(MSA_fill_copy_2) {
// Similar to MSA_fill_copy test, but also check overlaping between MSA and
// FPU registers with same numbers
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint32_t w0;
uint32_t w1;
uint32_t w2;
uint32_t w3;
} T;
T t[2];
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
{
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, 0xAAAAAAAA);
__ li(t1, 0x55555555);
__ fill_w(w0, t0);
__ fill_w(w2, t0);
__ FmoveLow(f0, t1);
__ FmoveHigh(f2, t1);
#define STORE_MSA_REG(w_reg, base, scratch) \
__ copy_u_w(scratch, w_reg, 0); \
__ sw(scratch, MemOperand(base, offsetof(T, w0))); \
__ copy_u_w(scratch, w_reg, 1); \
__ sw(scratch, MemOperand(base, offsetof(T, w1))); \
__ copy_u_w(scratch, w_reg, 2); \
__ sw(scratch, MemOperand(base, offsetof(T, w2))); \
__ copy_u_w(scratch, w_reg, 3); \
__ sw(scratch, MemOperand(base, offsetof(T, w3)));
STORE_MSA_REG(w0, a0, t2)
STORE_MSA_REG(w2, a1, t2)
#undef STORE_MSA_REG
__ jr(ra);
__ nop();
}
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F4>::FromCode(*code);
f.Call(&t[0], &t[1], 0, 0, 0);
CHECK_EQ(0x55555555, t[0].w0);
CHECK_EQ(0xAAAAAAAA, t[0].w1);
CHECK_EQ(0xAAAAAAAA, t[0].w2);
CHECK_EQ(0xAAAAAAAA, t[0].w3);
CHECK_EQ(0xAAAAAAAA, t[1].w0);
CHECK_EQ(0x55555555, t[1].w1);
CHECK_EQ(0xAAAAAAAA, t[1].w2);
CHECK_EQ(0xAAAAAAAA, t[1].w3);
}
TEST(MSA_fill_copy_3) {
// Similar to MSA_fill_copy test, but also check overlaping between MSA and
// FPU registers with same numbers
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint64_t d0;
uint64_t d1;
} T;
T t[2];
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
{
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, 0xAAAAAAAA);
__ li(t1, 0x55555555);
__ Move(f0, t0, t0);
__ Move(f2, t0, t0);
__ fill_w(w0, t1);
__ fill_w(w2, t1);
__ Sdc1(f0, MemOperand(a0, offsetof(T, d0)));
__ Sdc1(f2, MemOperand(a1, offsetof(T, d0)));
__ jr(ra);
__ nop();
}
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F4>::FromCode(*code);
f.Call(&t[0], &t[1], 0, 0, 0);
CHECK_EQ(0x5555555555555555, t[0].d0);
CHECK_EQ(0x5555555555555555, t[1].d0);
}
template <typename T>
void run_msa_insert(int32_t rs_value, int n, msa_reg_t* w) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
__ li(t0, -1);
__ li(t1, rs_value);
__ fill_w(w0, t0);
if (std::is_same<T, int8_t>::value) {
DCHECK_LT(n, 16);
__ insert_b(w0, n, t1);
} else if (std::is_same<T, int16_t>::value) {
DCHECK_LT(n, 8);
__ insert_h(w0, n, t1);
} else if (std::is_same<T, int32_t>::value) {
DCHECK_LT(n, 4);
__ insert_w(w0, n, t1);
} else {
UNREACHABLE();
}
store_elements_of_vector(assm, w0, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(w, 0, 0, 0, 0));
}
TEST(MSA_insert) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseInsert {
uint32_t input;
int n;
uint64_t exp_res_lo;
uint64_t exp_res_hi;
};
struct TestCaseInsert tc_b[] = {
// input, n, exp_res_lo, exp_res_hi
{0xA2, 13, 0xFFFFFFFFFFFFFFFFu, 0xFFFFA2FFFFFFFFFFu},
{0x73, 10, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFFF73FFFFu},
{0x3494, 5, 0xFFFF94FFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu},
{0xA6B8, 1, 0xFFFFFFFFFFFFB8FFu, 0xFFFFFFFFFFFFFFFFu}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseInsert); ++i) {
msa_reg_t res;
run_msa_insert<int8_t>(tc_b[i].input, tc_b[i].n, &res);
CHECK_EQ(tc_b[i].exp_res_lo, res.d[0]);
CHECK_EQ(tc_b[i].exp_res_hi, res.d[1]);
}
struct TestCaseInsert tc_h[] = {
// input, n, exp_res_lo, exp_res_hi
{0x85A2, 7, 0xFFFFFFFFFFFFFFFFu, 0x85A2FFFFFFFFFFFFu},
{0xE873, 5, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFFE873FFFFu},
{0x3494, 3, 0x3494FFFFFFFFFFFFu, 0xFFFFFFFFFFFFFFFFu},
{0xA6B8, 1, 0xFFFFFFFFA6B8FFFFu, 0xFFFFFFFFFFFFFFFFu}};
for (size_t i = 0; i < sizeof(tc_h) / sizeof(TestCaseInsert); ++i) {
msa_reg_t res;
run_msa_insert<int16_t>(tc_h[i].input, tc_h[i].n, &res);
CHECK_EQ(tc_h[i].exp_res_lo, res.d[0]);
CHECK_EQ(tc_h[i].exp_res_hi, res.d[1]);
}
struct TestCaseInsert tc_w[] = {
// input, n, exp_res_lo, exp_res_hi
{0xD2F085A2u, 3, 0xFFFFFFFFFFFFFFFFu, 0xD2F085A2FFFFFFFFu},
{0x4567E873u, 2, 0xFFFFFFFFFFFFFFFFu, 0xFFFFFFFF4567E873u},
{0xACDB3494u, 1, 0xACDB3494FFFFFFFFu, 0xFFFFFFFFFFFFFFFFu},
{0x89ABA6B8u, 0, 0xFFFFFFFF89ABA6B8u, 0xFFFFFFFFFFFFFFFFu}};
for (size_t i = 0; i < sizeof(tc_w) / sizeof(TestCaseInsert); ++i) {
msa_reg_t res;
run_msa_insert<int32_t>(tc_w[i].input, tc_w[i].n, &res);
CHECK_EQ(tc_w[i].exp_res_lo, res.d[0]);
CHECK_EQ(tc_w[i].exp_res_hi, res.d[1]);
}
}
TEST(MSA_move_v) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wd_lo;
uint64_t wd_hi;
} T;
T t[] = {{0x20B9CC4F1A83E0C5, 0xA27E1B5F2F5BB18A, 0x1E86678B52F8E1FF,
0x706E51290AC76FB9},
{0x4414AED7883FFD18, 0x047D183A06B67016, 0x4EF258CF8D822870,
0x2686B73484C2E843},
{0xD38FF9D048884FFC, 0x6DC63A57C0943CA7, 0x8520CA2F3E97C426,
0xA9913868FB819C59}};
for (unsigned i = 0; i < arraysize(t); ++i) {
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
load_elements_of_vector(assm, &t[i].ws_lo, w0, t0, t1);
load_elements_of_vector(assm, &t[i].wd_lo, w2, t0, t1);
__ move_v(w2, w0);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&t[i].wd_lo, 0, 0, 0, 0));
CHECK_EQ(t[i].ws_lo, t[i].wd_lo);
CHECK_EQ(t[i].ws_hi, t[i].wd_hi);
}
}
template <typename ExpectFunc, typename OperFunc>
void run_msa_sldi(OperFunc GenerateOperation,
ExpectFunc GenerateExpectedResult) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
typedef struct {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wd_lo;
uint64_t wd_hi;
} T;
T t[] = {{0x20B9CC4F1A83E0C5, 0xA27E1B5F2F5BB18A, 0x1E86678B52F8E1FF,
0x706E51290AC76FB9},
{0x4414AED7883FFD18, 0x047D183A06B67016, 0x4EF258CF8D822870,
0x2686B73484C2E843},
{0xD38FF9D048884FFC, 0x6DC63A57C0943CA7, 0x8520CA2F3E97C426,
0xA9913868FB819C59}};
uint64_t res[2];
for (unsigned i = 0; i < arraysize(t); ++i) {
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
load_elements_of_vector(assm, &t[i].ws_lo, w0, t0, t1);
load_elements_of_vector(assm, &t[i].wd_lo, w2, t0, t1);
GenerateOperation(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res[0], 0, 0, 0, 0));
GenerateExpectedResult(reinterpret_cast<uint8_t*>(&t[i].ws_lo),
reinterpret_cast<uint8_t*>(&t[i].wd_lo));
CHECK_EQ(res[0], t[i].wd_lo);
CHECK_EQ(res[1], t[i].wd_hi);
}
}
TEST(MSA_sldi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
#define SLDI_DF(s, k) \
uint8_t v[32]; \
for (unsigned i = 0; i < s; i++) { \
v[i] = ws[s * k + i]; \
v[i + s] = wd[s * k + i]; \
} \
for (unsigned i = 0; i < s; i++) { \
wd[s * k + i] = v[i + n]; \
}
for (int n = 0; n < 16; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_b(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
SLDI_DF(kMSARegSize / sizeof(int8_t) / kBitsPerByte, 0)
});
}
for (int n = 0; n < 8; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_h(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
for (int k = 0; k < 2; ++k) {
SLDI_DF(kMSARegSize / sizeof(int16_t) / kBitsPerByte, k)
}
});
}
for (int n = 0; n < 4; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_w(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
for (int k = 0; k < 4; ++k) {
SLDI_DF(kMSARegSize / sizeof(int32_t) / kBitsPerByte, k)
}
});
}
for (int n = 0; n < 2; ++n) {
run_msa_sldi([n](MacroAssembler& assm) { __ sldi_d(w2, w0, n); },
[n](uint8_t* ws, uint8_t* wd) {
for (int k = 0; k < 8; ++k) {
SLDI_DF(kMSARegSize / sizeof(int64_t) / kBitsPerByte, k)
}
});
}
#undef SLDI_DF
}
void run_msa_ctc_cfc(uint32_t value) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, value);
__ li(t2, 0);
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ cfcmsa(t2, msareg);
__ ctcmsa(msareg, t1);
__ sw(t2, MemOperand(a0, 0));
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
uint32_t res;
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(value & 0x0167FFFF, res);
}
TEST(MSA_cfc_ctc) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const uint32_t mask_without_cause = 0xFF9C0FFF;
const uint32_t mask_always_zero = 0x0167FFFF;
const uint32_t mask_enables = 0x00000F80;
uint32_t test_case[] = {0x2D5EDE31, 0x07955425, 0x15B7DBE3, 0x2BF8BC37,
0xE6AAE923, 0x24D0F68D, 0x41AFA84C, 0x2D6BF64F,
0x925014BD, 0x4DBA7E61};
for (unsigned i = 0; i < arraysize(test_case); i++) {
// Setting enable bits and corresponding cause bits could result in
// exception raised and this prevents that from happening
test_case[i] = (~test_case[i] & mask_enables) << 5 |
(test_case[i] & mask_without_cause);
run_msa_ctc_cfc(test_case[i] & mask_always_zero);
}
}
struct ExpResShf {
uint8_t i8;
uint64_t lo;
uint64_t hi;
};
void run_msa_i8(SecondaryField opcode, uint64_t ws_lo, uint64_t ws_hi,
uint8_t i8) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
uint64_t wd_lo = 0xF35862E13E38F8B0;
uint64_t wd_hi = 0x4F41FFDEF2BFE636;
#define LOAD_W_REG(lo, hi, w_reg) \
__ li(t0, static_cast<uint32_t>(lo & 0xFFFFFFFF)); \
__ li(t1, static_cast<uint32_t>((lo >> 32) & 0xFFFFFFFF)); \
__ insert_w(w_reg, 0, t0); \
__ insert_w(w_reg, 1, t1); \
__ li(t0, static_cast<uint32_t>(hi & 0xFFFFFFFF)); \
__ li(t1, static_cast<uint32_t>((hi >> 32) & 0xFFFFFFFF)); \
__ insert_w(w_reg, 2, t0); \
__ insert_w(w_reg, 3, t1);
LOAD_W_REG(ws_lo, ws_hi, w0)
switch (opcode) {
case ANDI_B:
__ andi_b(w2, w0, i8);
break;
case ORI_B:
__ ori_b(w2, w0, i8);
break;
case NORI_B:
__ nori_b(w2, w0, i8);
break;
case XORI_B:
__ xori_b(w2, w0, i8);
break;
case BMNZI_B:
LOAD_W_REG(wd_lo, wd_hi, w2);
__ bmnzi_b(w2, w0, i8);
break;
case BMZI_B:
LOAD_W_REG(wd_lo, wd_hi, w2);
__ bmzi_b(w2, w0, i8);
break;
case BSELI_B:
LOAD_W_REG(wd_lo, wd_hi, w2);
__ bseli_b(w2, w0, i8);
break;
case SHF_B:
__ shf_b(w2, w0, i8);
break;
case SHF_H:
__ shf_h(w2, w0, i8);
break;
case SHF_W:
__ shf_w(w2, w0, i8);
break;
default:
UNREACHABLE();
}
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
#undef LOAD_W_REG
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
uint64_t mask = i8 * 0x0101010101010101ull;
switch (opcode) {
case ANDI_B:
CHECK_EQ(ws_lo & mask, res.d[0]);
CHECK_EQ(ws_hi & mask, res.d[1]);
break;
case ORI_B:
CHECK_EQ(ws_lo | mask, res.d[0]);
CHECK_EQ(ws_hi | mask, res.d[1]);
break;
case NORI_B:
CHECK_EQ(~(ws_lo | mask), res.d[0]);
CHECK_EQ(~(ws_hi | mask), res.d[1]);
break;
case XORI_B:
CHECK_EQ(ws_lo ^ mask, res.d[0]);
CHECK_EQ(ws_hi ^ mask, res.d[1]);
break;
case BMNZI_B:
CHECK_EQ((ws_lo & mask) | (wd_lo & ~mask), res.d[0]);
CHECK_EQ((ws_hi & mask) | (wd_hi & ~mask), res.d[1]);
break;
case BMZI_B:
CHECK_EQ((ws_lo & ~mask) | (wd_lo & mask), res.d[0]);
CHECK_EQ((ws_hi & ~mask) | (wd_hi & mask), res.d[1]);
break;
case BSELI_B:
CHECK_EQ((ws_lo & ~wd_lo) | (mask & wd_lo), res.d[0]);
CHECK_EQ((ws_hi & ~wd_hi) | (mask & wd_hi), res.d[1]);
break;
case SHF_B: {
struct ExpResShf exp_b[] = {
// i8, exp_lo, exp_hi
{0xFFu, 0x11111111B9B9B9B9, 0xF7F7F7F7C8C8C8C8},
{0x0u, 0x62626262DFDFDFDF, 0xD6D6D6D6C8C8C8C8},
{0xE4u, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636},
{0x1Bu, 0x1B756911C3D9A7B9, 0xAE94A5F79C8AEFC8},
{0xB1u, 0x662B6253E8C4DF12, 0x0D3AD6803F8BC88B},
{0x4Eu, 0x62E1F358F8B03E38, 0xFFDE4F41E636F2BF},
{0x27u, 0x1B697511C3A7D9B9, 0xAEA594F79CEF8AC8}};
for (size_t i = 0; i < sizeof(exp_b) / sizeof(ExpResShf); ++i) {
if (exp_b[i].i8 == i8) {
CHECK_EQ(exp_b[i].lo, res.d[0]);
CHECK_EQ(exp_b[i].hi, res.d[1]);
}
}
} break;
case SHF_H: {
struct ExpResShf exp_h[] = {
// i8, exp_lo, exp_hi
{0xFFu, 0x1169116911691169, 0xF7A5F7A5F7A5F7A5},
{0x0u, 0x12DF12DF12DF12DF, 0x8BC88BC88BC88BC8},
{0xE4u, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636},
{0x1Bu, 0xD9C3B9A7751B1169, 0x8A9CC8EF94AEF7A5},
{0xB1u, 0x53622B6612DFC4E8, 0x80D63A0D8BC88B3F},
{0x4Eu, 0x3E38F8B0F35862E1, 0xF2BFE6364F41FFDE},
{0x27u, 0xD9C3751BB9A71169, 0x8A9C94AEC8EFF7A5}};
for (size_t i = 0; i < sizeof(exp_h) / sizeof(ExpResShf); ++i) {
if (exp_h[i].i8 == i8) {
CHECK_EQ(exp_h[i].lo, res.d[0]);
CHECK_EQ(exp_h[i].hi, res.d[1]);
}
}
} break;
case SHF_W: {
struct ExpResShf exp_w[] = {
// i8, exp_lo, exp_hi
{0xFFu, 0xF7A594AEF7A594AE, 0xF7A594AEF7A594AE},
{0x0u, 0xC4E812DFC4E812DF, 0xC4E812DFC4E812DF},
{0xE4u, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636},
{0x1Bu, 0xC8EF8A9CF7A594AE, 0xB9A7D9C31169751B},
{0xB1u, 0xC4E812DF2B665362, 0x8B3F8BC83A0D80D6},
{0x4Eu, 0x4F41FFDEF2BFE636, 0xF35862E13E38F8B0},
{0x27u, 0x1169751BF7A594AE, 0xB9A7D9C3C8EF8A9C}};
for (size_t i = 0; i < sizeof(exp_w) / sizeof(ExpResShf); ++i) {
if (exp_w[i].i8 == i8) {
CHECK_EQ(exp_w[i].lo, res.d[0]);
CHECK_EQ(exp_w[i].hi, res.d[1]);
}
}
} break;
default:
UNREACHABLE();
}
}
struct TestCaseMsaI8 {
uint64_t input_lo;
uint64_t input_hi;
uint8_t i8;
};
TEST(MSA_andi_ori_nori_xori) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI8 tc[] = {// input_lo, input_hi, i8
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0xFFu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0u},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x3Bu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0xD9u}};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI8); ++i) {
run_msa_i8(ANDI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(ORI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(NORI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(XORI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
}
}
TEST(MSA_bmnzi_bmzi_bseli) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI8 tc[] = {// input_lo, input_hi, i8
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0xFFu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0u},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x3Bu},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0xD9u}};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI8); ++i) {
run_msa_i8(BMNZI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(BMZI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(BSELI_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
}
}
TEST(MSA_shf) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI8 tc[] = {
// input_lo, input_hi, i8
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0xFFu}, // 3333
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0u}, // 0000
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0xE4u}, // 3210
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x1Bu}, // 0123
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0xB1u}, // 2301
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x4Eu}, // 1032
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x27u} // 0213
};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI8); ++i) {
run_msa_i8(SHF_B, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(SHF_H, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
run_msa_i8(SHF_W, tc[i].input_lo, tc[i].input_hi, tc[i].i8);
}
}
uint32_t run_Ins(uint32_t imm, uint32_t source, uint16_t pos, uint16_t size) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ li(v0, imm);
__ li(t0, source);
__ Ins(v0, t0, pos, size);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(Ins) {
CcTest::InitializeVM();
// run_Ins(rt_value, rs_value, pos, size), expected_result
CHECK_EQ(run_Ins(0x55555555, 0xABCDEF01, 31, 1), 0xD5555555);
CHECK_EQ(run_Ins(0x55555555, 0xABCDEF02, 30, 2), 0x95555555);
CHECK_EQ(run_Ins(0x01234567, 0xFABCDEFF, 0, 32), 0xFABCDEFF);
// Results with positive sign.
CHECK_EQ(run_Ins(0x55555550, 0x80000001, 0, 1), 0x55555551);
CHECK_EQ(run_Ins(0x55555555, 0x40000001, 0, 32), 0x40000001);
CHECK_EQ(run_Ins(0x55555555, 0x20000001, 1, 31), 0x40000003);
CHECK_EQ(run_Ins(0x55555555, 0x80700001, 8, 24), 0x70000155);
CHECK_EQ(run_Ins(0x55555555, 0x80007001, 16, 16), 0x70015555);
CHECK_EQ(run_Ins(0x55555555, 0x80000071, 24, 8), 0x71555555);
CHECK_EQ(run_Ins(0x75555555, 0x40000000, 31, 1), 0x75555555);
// Results with negative sign.
CHECK_EQ(run_Ins(0x85555550, 0x80000001, 0, 1), 0x85555551);
CHECK_EQ(run_Ins(0x55555555, 0x80000001, 0, 32), 0x80000001);
CHECK_EQ(run_Ins(0x55555555, 0x40000001, 1, 31), 0x80000003);
CHECK_EQ(run_Ins(0x55555555, 0x80800001, 8, 24), 0x80000155);
CHECK_EQ(run_Ins(0x55555555, 0x80008001, 16, 16), 0x80015555);
CHECK_EQ(run_Ins(0x55555555, 0x80000081, 24, 8), 0x81555555);
CHECK_EQ(run_Ins(0x75555555, 0x00000001, 31, 1), 0xF5555555);
}
uint32_t run_Ext(uint32_t source, uint16_t pos, uint16_t size) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
__ li(v0, 0xFFFFFFFF);
__ li(t0, source);
__ Ext(v0, t0, pos, size);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
auto f = GeneratedCode<F2>::FromCode(*code);
uint32_t res = reinterpret_cast<uint32_t>(f.Call(0, 0, 0, 0, 0));
return res;
}
TEST(Ext) {
CcTest::InitializeVM();
// Source values with negative sign.
// run_Ext(rs_value, pos, size), expected_result
CHECK_EQ(run_Ext(0x80000001, 0, 1), 0x00000001);
CHECK_EQ(run_Ext(0x80000001, 0, 32), 0x80000001);
CHECK_EQ(run_Ext(0x80000002, 1, 31), 0x40000001);
CHECK_EQ(run_Ext(0x80000100, 8, 24), 0x00800001);
CHECK_EQ(run_Ext(0x80010000, 16, 16), 0x00008001);
CHECK_EQ(run_Ext(0x81000000, 24, 8), 0x00000081);
CHECK_EQ(run_Ext(0x80000000, 31, 1), 0x00000001);
// Source values with positive sign.
CHECK_EQ(run_Ext(0x00000001, 0, 1), 0x00000001);
CHECK_EQ(run_Ext(0x40000001, 0, 32), 0x40000001);
CHECK_EQ(run_Ext(0x40000002, 1, 31), 0x20000001);
CHECK_EQ(run_Ext(0x40000100, 8, 24), 0x00400001);
CHECK_EQ(run_Ext(0x40010000, 16, 16), 0x00004001);
CHECK_EQ(run_Ext(0x41000000, 24, 8), 0x00000041);
CHECK_EQ(run_Ext(0x40000000, 31, 1), 0x00000000);
}
struct TestCaseMsaI5 {
uint64_t ws_lo;
uint64_t ws_hi;
uint32_t i5;
};
template <typename InstFunc, typename OperFunc>
void run_msa_i5(struct TestCaseMsaI5* input, bool i5_sign_ext,
InstFunc GenerateI5InstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
int32_t i5 =
i5_sign_ext ? static_cast<int32_t>(input->i5 << 27) >> 27 : input->i5;
load_elements_of_vector(assm, &(input->ws_lo), w0, t0, t1);
GenerateI5InstructionFunc(assm, i5);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input->ws_lo, input->i5), res.d[0]);
CHECK_EQ(GenerateOperationFunc(input->ws_hi, input->i5), res.d[1]);
}
TEST(MSA_addvi_subvi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI5 tc[] = {
// ws_lo, ws_hi, i5
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x0000001F},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0000000F},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x00000005},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x00000010},
{0xFFAB807F807FFFCD, 0x7F23FF80FF567F80, 0x0000000F},
{0x80FFEFFF7F12807F, 0x807F80FF7FDEFF78, 0x00000010}};
#define ADDVI_DF(lanes, mask) \
uint64_t res = 0; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = (kMSARegSize / lanes) * i; \
res |= ((((ws >> shift) & mask) + i5) & mask) << shift; \
} \
return res
#define SUBVI_DF(lanes, mask) \
uint64_t res = 0; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = (kMSARegSize / lanes) * i; \
res |= ((((ws >> shift) & mask) - i5) & mask) << shift; \
} \
return res
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI5); ++i) {
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_b(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesByte, UINT8_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_h(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesHalf, UINT16_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_w(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesWord, UINT32_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ addvi_d(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { ADDVI_DF(kMSALanesDword, UINT64_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_b(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesByte, UINT8_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_h(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesHalf, UINT16_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_w(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesWord, UINT32_MAX); });
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ subvi_d(w2, w0, i5); },
[](uint64_t ws, uint32_t i5) { SUBVI_DF(kMSALanesDword, UINT64_MAX); });
}
#undef ADDVI_DF
#undef SUBVI_DF
}
TEST(MSA_maxi_mini) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI5 tc[] = {
// ws_lo, ws_hi, i5
{0x7F80FF3480FF7F00, 0x8D7FFF80FF7F6780, 0x0000001F},
{0x7F80FF3480FF7F00, 0x8D7FFF80FF7F6780, 0x0000000F},
{0x7F80FF3480FF7F00, 0x8D7FFF80FF7F6780, 0x00000010},
{0x80007FFF91DAFFFF, 0x7FFF8000FFFF5678, 0x0000001F},
{0x80007FFF91DAFFFF, 0x7FFF8000FFFF5678, 0x0000000F},
{0x80007FFF91DAFFFF, 0x7FFF8000FFFF5678, 0x00000010},
{0x7FFFFFFF80000000, 0x12345678FFFFFFFF, 0x0000001F},
{0x7FFFFFFF80000000, 0x12345678FFFFFFFF, 0x0000000F},
{0x7FFFFFFF80000000, 0x12345678FFFFFFFF, 0x00000010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x0000001F},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x0000000F},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x00000010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x00000015},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x00000009},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x00000003}};
#define MAXI_MINI_S_DF(lanes, mask, func) \
[](uint64_t ws, uint32_t ui5) { \
uint64_t res = 0; \
int64_t i5 = ArithmeticShiftRight(static_cast<int64_t>(ui5) << 59, 59); \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
int64_t elem = \
static_cast<int64_t>(((ws >> shift) & mask) << (64 - elem_size)) >> \
(64 - elem_size); \
res |= static_cast<uint64_t>(func(elem, i5) & mask) << shift; \
} \
return res; \
}
#define MAXI_MINI_U_DF(lanes, mask, func) \
[](uint64_t ws, uint32_t ui5) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= (func(elem, static_cast<uint64_t>(ui5)) & mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI5); ++i) {
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_b(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesByte, UINT8_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_h(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesHalf, UINT16_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_w(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesWord, UINT32_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ maxi_s_d(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesDword, UINT64_MAX, Max));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_b(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesByte, UINT8_MAX, Min));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_h(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesHalf, UINT16_MAX, Min));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_w(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesWord, UINT32_MAX, Min));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ mini_s_d(w2, w0, i5); },
MAXI_MINI_S_DF(kMSALanesDword, UINT64_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_b(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesByte, UINT8_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_h(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesHalf, UINT16_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_w(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesWord, UINT32_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ maxi_u_d(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesDword, UINT64_MAX, Max));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_b(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesByte, UINT8_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_h(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesHalf, UINT16_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_w(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesWord, UINT32_MAX, Min));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ mini_u_d(w2, w0, i5); },
MAXI_MINI_U_DF(kMSALanesDword, UINT64_MAX, Min));
}
#undef MAXI_MINI_S_DF
#undef MAXI_MINI_U_DF
}
TEST(MSA_ceqi_clti_clei) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaI5 tc[] = {
{0xFF69751BB9A7D9C3, 0xF7A594AEC8FF8A9C, 0x0000001F},
{0xE669FFFFB9A7D9C3, 0xF7A594AEFFFF8A9C, 0x0000001F},
{0xFFFFFFFFB9A7D9C3, 0xF7A594AEFFFFFFFF, 0x0000001F},
{0x2B0B5362C4E812DF, 0x3A0D80D68B3F0BC8, 0x0000000B},
{0x2B66000BC4E812DF, 0x3A0D000B8B3F8BC8, 0x0000000B},
{0x0000000BC4E812DF, 0x3A0D80D60000000B, 0x0000000B},
{0xF38062E13E38F8B0, 0x8041FFDEF2BFE636, 0x00000010},
{0xF35880003E38F8B0, 0x4F41FFDEF2BF8000, 0x00000010},
{0xF35862E180000000, 0x80000000F2BFE636, 0x00000010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x00000015},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x00000009},
{0xF30062E13E38F800, 0x4F00FFDEF2BF0036, 0x00000000}};
#define CEQI_CLTI_CLEI_S_DF(lanes, mask, func) \
[](uint64_t ws, uint32_t ui5) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
int64_t i5 = ArithmeticShiftRight(static_cast<int64_t>(ui5) << 59, 59); \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
int64_t elem = \
static_cast<int64_t>(((ws >> shift) & mask) << (64 - elem_size)) >> \
(64 - elem_size); \
res |= static_cast<uint64_t>((func)&mask) << shift; \
} \
return res; \
}
#define CEQI_CLTI_CLEI_U_DF(lanes, mask, func) \
[](uint64_t ws, uint64_t ui5) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaI5); ++i) {
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_b(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesByte, UINT8_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_h(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesHalf, UINT16_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_w(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesWord, UINT32_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ ceqi_d(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesDword, UINT64_MAX,
!Compare(elem, i5) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_b(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, i5) == -1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_h(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, i5) == -1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_w(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, i5) == -1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clti_s_d(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, i5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_b(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, i5) != 1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_h(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, i5) != 1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_w(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, i5) != 1) ? -1u : 0u));
run_msa_i5(
&tc[i], true,
[](MacroAssembler& assm, int32_t i5) { __ clei_s_d(w2, w0, i5); },
CEQI_CLTI_CLEI_S_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, i5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_b(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_h(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_w(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clti_u_d(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, ui5) == -1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_b(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesByte, UINT8_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_h(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesHalf, UINT16_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_w(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesWord, UINT32_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
run_msa_i5(
&tc[i], false,
[](MacroAssembler& assm, int32_t i5) { __ clei_u_d(w2, w0, i5); },
CEQI_CLTI_CLEI_U_DF(kMSALanesDword, UINT64_MAX,
(Compare(elem, ui5) != 1) ? -1ull : 0ull));
}
#undef CEQI_CLTI_CLEI_S_DF
#undef CEQI_CLTI_CLEI_U_DF
}
struct TestCaseMsa2R {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t exp_res_lo;
uint64_t exp_res_hi;
};
template <typename Func>
void run_msa_2r(const struct TestCaseMsa2R* input,
Func Generate2RInstructionFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, reinterpret_cast<const uint64_t*>(input), w0,
t0, t1);
Generate2RInstructionFunc(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(input->exp_res_lo, res.d[0]);
CHECK_EQ(input->exp_res_hi, res.d[1]);
}
TEST(MSA_pcnt) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2R tc_b[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0808080808080808, 0x0808080808080808},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C,
0x0204050405050504, 0x0704030503070304},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8,
0x0404040303040207, 0x0403010504060403},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636,
0x0603030405030503, 0x0502080605070504}};
struct TestCaseMsa2R tc_h[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0010001000100010, 0x0010001000100010},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C,
0x00060009000A0009, 0x000B0008000A0007},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8,
0x0008000700070009, 0x00070006000A0007},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636,
0x0009000700080008, 0x0007000E000C0009}};
struct TestCaseMsa2R tc_w[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0000002000000020, 0x0000002000000020},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C,
0x0000000F00000013, 0x0000001300000011},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8,
0x0000000F00000010, 0x0000000D00000011},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636,
0x0000001000000010, 0x0000001500000015}};
struct TestCaseMsa2R tc_d[] = {
// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0x40, 0x40},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x22, 0x24},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x1F, 0x1E},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x20, 0x2A}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseMsa2R); ++i) {
run_msa_2r(&tc_b[i], [](MacroAssembler& assm) { __ pcnt_b(w2, w0); });
run_msa_2r(&tc_h[i], [](MacroAssembler& assm) { __ pcnt_h(w2, w0); });
run_msa_2r(&tc_w[i], [](MacroAssembler& assm) { __ pcnt_w(w2, w0); });
run_msa_2r(&tc_d[i], [](MacroAssembler& assm) { __ pcnt_d(w2, w0); });
}
}
TEST(MSA_nlzc) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2R tc_b[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000,
0x0808080808080808, 0x0808080808080808},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x1169350B07030100, 0x7F011402381F0A6C,
0x0301020405060708, 0x0107030602030401},
{0x010806003478121F, 0x03013016073F7B08,
0x0704050802010303, 0x0607020305020104},
{0x0168321100083803, 0x07113F03013F1676,
0x0701020308040206, 0x0503020607020301}};
struct TestCaseMsa2R tc_h[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000,
0x0010001000100010, 0x0010001000100010},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x00010007000A003C, 0x37A5001E00010002,
0x000F000D000C000A, 0x0002000B000F000E},
{0x0026066200780EDF, 0x003D0003000F00C8,
0x000A000500090004, 0x000A000E000C0008},
{0x335807E100480030, 0x01410FDE12BF5636,
0x000200050009000A, 0x0007000400030001}};
struct TestCaseMsa2R tc_w[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000,
0x0000002000000020, 0x0000002000000020},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x00000005000007C3, 0x000014AE00006A9C,
0x0000001D00000015, 0x0000001300000011},
{0x00009362000112DF, 0x000380D6003F8BC8,
0x000000100000000F, 0x0000000E0000000A},
{0x135862E17E38F8B0, 0x0061FFDE03BFE636,
0x0000000300000001, 0x0000000900000006}};
struct TestCaseMsa2R tc_d[] = {
// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0x0000000000000000, 0x0000000000000000, 0x40, 0x40},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0, 0},
{0x000000000000014E, 0x00000000000176DA, 0x37, 0x2F},
{0x00000062C4E812DF, 0x000065D68B3F8BC8, 0x19, 0x11},
{0x00000000E338F8B0, 0x0754534ACAB32654, 0x20, 0x5}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseMsa2R); ++i) {
run_msa_2r(&tc_b[i], [](MacroAssembler& assm) { __ nlzc_b(w2, w0); });
run_msa_2r(&tc_h[i], [](MacroAssembler& assm) { __ nlzc_h(w2, w0); });
run_msa_2r(&tc_w[i], [](MacroAssembler& assm) { __ nlzc_w(w2, w0); });
run_msa_2r(&tc_d[i], [](MacroAssembler& assm) { __ nlzc_d(w2, w0); });
}
}
TEST(MSA_nloc) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2R tc_b[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0808080808080808, 0x0808080808080808},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xEE96CAF4F8FCFEFF, 0x80FEEBFDC7E0F593,
0x0301020405060708, 0x0107030602030401},
{0xFEF7F9FFCB87EDE0, 0xFCFECFE9F8C084F7,
0x0704050802010303, 0x0607020305020104},
{0xFE97CDEEFFF7C7FC, 0xF8EEC0FCFEC0E989,
0x0701020308040206, 0x0503020607020301}};
struct TestCaseMsa2R tc_h[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0010001000100010, 0x0010001000100010},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFEFFF8FFF5FFC3, 0xC85AFFE1FFFEFFFD,
0x000F000D000C000A, 0x0002000B000F000E},
{0xFFD9F99DFF87F120, 0xFFC2FFFCFFF0FF37,
0x000A000500090004, 0x000A000E000C0008},
{0xCCA7F81EFFB7FFCF, 0xFEBEF021ED40A9C9,
0x000200050009000A, 0x0007000400030001}};
struct TestCaseMsa2R tc_w[] = {// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0000002000000020, 0x0000002000000020},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFAFFFFF83C, 0xFFFFEB51FFFF9563,
0x0000001D00000015, 0x0000001300000011},
{0xFFFF6C9DFFFEED20, 0xFFFC7F29FFC07437,
0x000000100000000F, 0x0000000E0000000A},
{0xECA79D1E81C7074F, 0xFF9E0021FC4019C9,
0x0000000300000001, 0x0000000900000006}};
struct TestCaseMsa2R tc_d[] = {
// ws_lo, ws_hi, exp_res_lo, exp_res_hi
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0x40, 0x40},
{0x0000000000000000, 0x0000000000000000, 0, 0},
{0xFFFFFFFFFFFFFEB1, 0xFFFFFFFFFFFE8925, 0x37, 0x2F},
{0xFFFFFF9D3B17ED20, 0xFFFF9A2974C07437, 0x19, 0x11},
{0xFFFFFFFF1CC7074F, 0xF8ABACB5354CD9AB, 0x20, 0x5}};
for (size_t i = 0; i < sizeof(tc_b) / sizeof(TestCaseMsa2R); ++i) {
run_msa_2r(&tc_b[i], [](MacroAssembler& assm) { __ nloc_b(w2, w0); });
run_msa_2r(&tc_h[i], [](MacroAssembler& assm) { __ nloc_h(w2, w0); });
run_msa_2r(&tc_w[i], [](MacroAssembler& assm) { __ nloc_w(w2, w0); });
run_msa_2r(&tc_d[i], [](MacroAssembler& assm) { __ nloc_d(w2, w0); });
}
}
struct TestCaseMsa2RF_F_U {
float ws1;
float ws2;
float ws3;
float ws4;
uint32_t exp_res_1;
uint32_t exp_res_2;
uint32_t exp_res_3;
uint32_t exp_res_4;
};
struct TestCaseMsa2RF_D_U {
double ws1;
double ws2;
uint64_t exp_res_1;
uint64_t exp_res_2;
};
TEST(MSA_fclass) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
#define BIT(n) (0x1 << n)
#define SNAN_BIT BIT(0)
#define QNAN_BIT BIT(1)
#define NEG_INFINITY_BIT BIT((2))
#define NEG_NORMAL_BIT BIT(3)
#define NEG_SUBNORMAL_BIT BIT(4)
#define NEG_ZERO_BIT BIT(5)
#define POS_INFINITY_BIT BIT(6)
#define POS_NORMAL_BIT BIT(7)
#define POS_SUBNORMAL_BIT BIT(8)
#define POS_ZERO_BIT BIT(9)
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_U tc_s[] = {
{1.f, -0.00001, 208e10f, -34.8e-30f, POS_NORMAL_BIT, NEG_NORMAL_BIT,
POS_NORMAL_BIT, NEG_NORMAL_BIT},
{inf_float, -inf_float, 0, -0.f, POS_INFINITY_BIT, NEG_INFINITY_BIT,
POS_ZERO_BIT, NEG_ZERO_BIT},
{3.036e-40f, -6.392e-43f, 1.41e-45f, -1.17e-38f, POS_SUBNORMAL_BIT,
NEG_SUBNORMAL_BIT, POS_SUBNORMAL_BIT, NEG_SUBNORMAL_BIT}};
const struct TestCaseMsa2RF_D_U tc_d[] = {
{1., -0.00000001, POS_NORMAL_BIT, NEG_NORMAL_BIT},
{208e10, -34.8e-300, POS_NORMAL_BIT, NEG_NORMAL_BIT},
{inf_double, -inf_double, POS_INFINITY_BIT, NEG_INFINITY_BIT},
{0, -0., POS_ZERO_BIT, NEG_ZERO_BIT},
{1.036e-308, -6.392e-309, POS_SUBNORMAL_BIT, NEG_SUBNORMAL_BIT},
{1.41e-323, -3.17e208, POS_SUBNORMAL_BIT, NEG_NORMAL_BIT}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fclass_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fclass_d(w2, w0); });
}
#undef BIT
#undef SNAN_BIT
#undef QNAN_BIT
#undef NEG_INFINITY_BIT
#undef NEG_NORMAL_BIT
#undef NEG_SUBNORMAL_BIT
#undef NEG_ZERO_BIT
#undef POS_INFINITY_BIT
#undef POS_NORMAL_BIT
#undef POS_SUBNORMAL_BIT
#undef POS_ZERO_BIT
}
struct TestCaseMsa2RF_F_I {
float ws1;
float ws2;
float ws3;
float ws4;
int32_t exp_res_1;
int32_t exp_res_2;
int32_t exp_res_3;
int32_t exp_res_4;
};
struct TestCaseMsa2RF_D_I {
double ws1;
double ws2;
int64_t exp_res_1;
int64_t exp_res_2;
};
TEST(MSA_ftrunc_s) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const float qNaN_float = std::numeric_limits<float>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const double qNaN_double = std::numeric_limits<double>::quiet_NaN();
const int32_t max_int32 = std::numeric_limits<int32_t>::max();
const int32_t min_int32 = std::numeric_limits<int32_t>::min();
const int64_t max_int64 = std::numeric_limits<int64_t>::max();
const int64_t min_int64 = std::numeric_limits<int64_t>::min();
const struct TestCaseMsa2RF_F_I tc_s[] = {
{inf_float, 2.345f, -324.9235f, 30004.51f, max_int32, 2, -324, 30004},
{-inf_float, -0.983f, 0.0832f, static_cast<float>(max_int32) * 3.f,
min_int32, 0, 0, max_int32},
{-23.125f, qNaN_float, 2 * static_cast<float>(min_int32), -0.f, -23, 0,
min_int32, 0}};
const struct TestCaseMsa2RF_D_I tc_d[] = {
{inf_double, 2.345, max_int64, 2},
{-324.9235, 246569139.51, -324, 246569139},
{-inf_double, -0.983, min_int64, 0},
{0.0832, 6 * static_cast<double>(max_int64), 0, max_int64},
{-21453889872.94, qNaN_double, -21453889872, 0},
{2 * static_cast<double>(min_int64), -0., min_int64, 0}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ftrunc_s_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ftrunc_s_d(w2, w0); });
}
}
TEST(MSA_ftrunc_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const float qNaN_float = std::numeric_limits<float>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const double qNaN_double = std::numeric_limits<double>::quiet_NaN();
const uint32_t max_uint32 = std::numeric_limits<uint32_t>::max();
const uint64_t max_uint64 = std::numeric_limits<uint64_t>::max();
const struct TestCaseMsa2RF_F_U tc_s[] = {
{inf_float, 2.345f, -324.9235f, 30004.51f, max_uint32, 2, 0, 30004},
{-inf_float, 0.983f, 0.0832f, static_cast<float>(max_uint32) * 3., 0, 0,
0, max_uint32},
{23.125f, qNaN_float, -0.982, -0.f, 23, 0, 0, 0}};
const struct TestCaseMsa2RF_D_U tc_d[] = {
{inf_double, 2.345, max_uint64, 2},
{-324.9235, 246569139.51, 0, 246569139},
{-inf_double, -0.983, 0, 0},
{0.0832, 6 * static_cast<double>(max_uint64), 0, max_uint64},
{21453889872.94, qNaN_double, 21453889872, 0},
{0.9889, -0., 0, 0}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ftrunc_u_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ftrunc_u_d(w2, w0); });
}
}
struct TestCaseMsa2RF_F_F {
float ws1;
float ws2;
float ws3;
float ws4;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_D_D {
double ws1;
double ws2;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_fsqrt) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_F tc_s[] = {
{81.f, 576.f, inf_float, -0.f, 9.f, 24.f, inf_float, -0.f}};
const struct TestCaseMsa2RF_D_D tc_d[] = {{81., inf_double, 9., inf_double},
{331776., -0., 576, -0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fsqrt_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fsqrt_d(w2, w0); });
}
}
TEST(MSA_frsqrt) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_F tc_s[] = {
{81.f, 576.f, inf_float, -0.f, 1.f / 9.f, 1.f / 24.f, 0.f, -inf_float},
{0.f, 1.f / 576.f, 1.f / 81.f, 1.f / 4.f, inf_float, 24.f, 9.f, 2.f}};
const struct TestCaseMsa2RF_D_D tc_d[] = {
{81., inf_double, 1. / 9., 0.},
{331776., -0., 1. / 576., -inf_double},
{0., 1. / 81, inf_double, 9.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ frsqrt_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ frsqrt_d(w2, w0); });
}
}
TEST(MSA_frcp) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa2RF_F_F tc_s[] = {
{12.f, 576.f, inf_float, -0.f, 1.f / 12.f, 1.f / 576.f, 0.f, -inf_float},
{0.f, 1.f / 576.f, -inf_float, 1.f / 400.f, inf_float, 576.f, -0.f,
400.f}};
const struct TestCaseMsa2RF_D_D tc_d[] = {
{81., inf_double, 1. / 81., 0.},
{331777., -0., 1. / 331777., -inf_double},
{0., 1. / 80, inf_double, 80.},
{1. / 40000., -inf_double, 40000., -0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ frcp_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ frcp_d(w2, w0); });
}
}
void test_frint_s(size_t data_size, TestCaseMsa2RF_F_F tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ frint_w(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
void test_frint_d(size_t data_size, TestCaseMsa2RF_D_D tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ frint_d(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
TEST(MSA_frint) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_F_F tc_s1[] = {
{0.f, 4.51f, 1.49f, -12.51f, 0.f, 5.f, 1.f, -13.f},
{-1.32f, -23.38f, 2.8f, -32.5f, -1.f, -23.f, 3.f, -32.f}};
struct TestCaseMsa2RF_D_D tc_d1[] = {{0., 4.51, 0., 5.},
{1.49, -12.51, 1., -13.},
{-1.32, -23.38, -1., -23.},
{2.8, -32.6, 3., -33.}};
test_frint_s(sizeof(tc_s1), tc_s1, kRoundToNearest);
test_frint_d(sizeof(tc_d1), tc_d1, kRoundToNearest);
struct TestCaseMsa2RF_F_F tc_s2[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0.f, 4.f, 1.f, -12.f},
{-1.f, -23.38f, 2.8f, -32.6f, -1.f, -23.f, 2.f, -32.f}};
struct TestCaseMsa2RF_D_D tc_d2[] = {{0., 4.5, 0., 4.},
{1.49, -12.51, 1., -12.},
{-1., -23.38, -1., -23.},
{2.8, -32.6, 2., -32.}};
test_frint_s(sizeof(tc_s2), tc_s2, kRoundToZero);
test_frint_d(sizeof(tc_d2), tc_d2, kRoundToZero);
struct TestCaseMsa2RF_F_F tc_s3[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0.f, 5.f, 2.f, -12.f},
{-1.f, -23.38f, 2.8f, -32.6f, -1.f, -23.f, 3.f, -32.f}};
struct TestCaseMsa2RF_D_D tc_d3[] = {{0., 4.5, 0., 5.},
{1.49, -12.51, 2., -12.},
{-1., -23.38, -1., -23.},
{2.8, -32.6, 3., -32.}};
test_frint_s(sizeof(tc_s3), tc_s3, kRoundToPlusInf);
test_frint_d(sizeof(tc_d3), tc_d3, kRoundToPlusInf);
struct TestCaseMsa2RF_F_F tc_s4[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0.f, 4.f, 1.f, -13.f},
{-1.f, -23.38f, 2.8f, -32.6f, -1.f, -24.f, 2.f, -33.f}};
struct TestCaseMsa2RF_D_D tc_d4[] = {{0., 4.5, 0., 4.},
{1.49, -12.51, 1., -13.},
{-1., -23.38, -1., -24.},
{2.8, -32.6, 2., -33.}};
test_frint_s(sizeof(tc_s4), tc_s4, kRoundToMinusInf);
test_frint_d(sizeof(tc_d4), tc_d4, kRoundToMinusInf);
}
TEST(MSA_flog2) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
struct TestCaseMsa2RF_F_F tc_s[] = {
{std::ldexp(0.58f, -48), std::ldexp(0.5f, 110), std::ldexp(1.11f, -130),
inf_float, -49.f, 109.f, -130.f, inf_float},
{0.f, -0.f, std::ldexp(0.89f, -12), std::ldexp(0.32f, 126), -inf_float,
-inf_float, -13.f, 124.f}};
struct TestCaseMsa2RF_D_D tc_d[] = {
{std::ldexp(0.58, -48), std::ldexp(0.5, 110), -49., 109.},
{std::ldexp(1.11, -1050), inf_double, -1050., inf_double},
{0., -0., -inf_double, -inf_double},
{std::ldexp(0.32, 1021), std::ldexp(1.23, -123), 1019., -123.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_F_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ flog2_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_D_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ flog2_d(w2, w0); });
}
}
void test_ftint_s_s(size_t data_size, TestCaseMsa2RF_F_I tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_F_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_s_w(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
void test_ftint_s_d(size_t data_size, TestCaseMsa2RF_D_I tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_D_I); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_s_d(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
TEST(MSA_ftint_s) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const int32_t int32_max = std::numeric_limits<int32_t>::max();
const int32_t int32_min = std::numeric_limits<int32_t>::min();
const int64_t int64_max = std::numeric_limits<int64_t>::max();
const int64_t int64_min = std::numeric_limits<int64_t>::min();
struct TestCaseMsa2RF_F_I tc_s1[] = {
{0.f, 4.51f, 1.49f, -12.51f, 0, 5, 1, -13},
{-0.32f, -23.38f, 2.8f, -32.6f, 0, -23, 3, -33},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d1[] = {
{0., 4.51, 0, 5},
{1.49, -12.51, 1, -13},
{-0.32, -23.38, 0, -23},
{2.8, -32.6, 3, -33},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s1), tc_s1, kRoundToNearest);
test_ftint_s_d(sizeof(tc_d1), tc_d1, kRoundToNearest);
struct TestCaseMsa2RF_F_I tc_s2[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, -12},
{-0.f, -23.38f, 2.8f, -32.6f, -0, -23, 2, -32},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d2[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, -12},
{-0., -23.38, -0, -23},
{2.8, -32.6, 2, -32},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s2), tc_s2, kRoundToZero);
test_ftint_s_d(sizeof(tc_d2), tc_d2, kRoundToZero);
struct TestCaseMsa2RF_F_I tc_s3[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 5, 2, -12},
{-0.f, -23.38f, 2.8f, -32.6f, -0, -23, 3, -32},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d3[] = {
{0., 4.5, 0, 5},
{1.49, -12.51, 2, -12},
{-0., -23.38, -0, -23},
{2.8, -32.6, 3, -32},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s3), tc_s3, kRoundToPlusInf);
test_ftint_s_d(sizeof(tc_d3), tc_d3, kRoundToPlusInf);
struct TestCaseMsa2RF_F_I tc_s4[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, -13},
{-0.f, -23.38f, 2.8f, -32.6f, -0, -24, 2, -33},
{inf_float, -inf_float, 3.f * int32_min, 4.f * int32_max, int32_max,
int32_min, int32_min, int32_max}};
struct TestCaseMsa2RF_D_I tc_d4[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, -13},
{-0., -23.38, -0, -24},
{2.8, -32.6, 2, -33},
{inf_double, -inf_double, int64_max, int64_min},
{33.23 * int64_min, 4000. * int64_max, int64_min, int64_max}};
test_ftint_s_s(sizeof(tc_s4), tc_s4, kRoundToMinusInf);
test_ftint_s_d(sizeof(tc_d4), tc_d4, kRoundToMinusInf);
}
void test_ftint_u_s(size_t data_size, TestCaseMsa2RF_F_U tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_F_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_u_w(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
void test_ftint_u_d(size_t data_size, TestCaseMsa2RF_D_U tc_d[],
int rounding_mode) {
for (size_t i = 0; i < data_size / sizeof(TestCaseMsa2RF_D_U); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[&rounding_mode](MacroAssembler& assm) {
MSAControlRegister msareg = {kMSACSRRegister};
__ li(t0, static_cast<uint32_t>(rounding_mode));
__ cfcmsa(t1, msareg);
__ ctcmsa(msareg, t0);
__ ftint_u_d(w2, w0);
__ ctcmsa(msareg, t1);
});
}
}
TEST(MSA_ftint_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
const uint32_t uint32_max = std::numeric_limits<uint32_t>::max();
const uint64_t uint64_max = std::numeric_limits<uint64_t>::max();
struct TestCaseMsa2RF_F_U tc_s1[] = {
{0.f, 4.51f, 1.49f, -12.51f, 0, 5, 1, 0},
{-0.32f, 23.38f, 2.8f, 32.6f, 0, 23, 3, 33},
{inf_float, -inf_float, 0, 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d1[] = {
{0., 4.51, 0, 5},
{1.49, -12.51, 1, 0},
{-0.32, 23.38, 0, 23},
{2.8, 32.6, 3, 33},
{inf_double, -inf_double, uint64_max, 0},
{-0., 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s1), tc_s1, kRoundToNearest);
test_ftint_u_d(sizeof(tc_d1), tc_d1, kRoundToNearest);
struct TestCaseMsa2RF_F_U tc_s2[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, 0},
{-0.f, 23.38f, 2.8f, 32.6f, 0, 23, 2, 32},
{inf_float, -inf_float, 0., 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d2[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, 0},
{-0., 23.38, 0, 23},
{2.8, 32.6, 2, 32},
{inf_double, -inf_double, uint64_max, 0},
{-0.2345, 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s2), tc_s2, kRoundToZero);
test_ftint_u_d(sizeof(tc_d2), tc_d2, kRoundToZero);
struct TestCaseMsa2RF_F_U tc_s3[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 5, 2, 0},
{-0.f, 23.38f, 2.8f, 32.6f, 0, 24, 3, 33},
{inf_float, -inf_float, 0, 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d3[] = {
{0., 4.5, 0, 5},
{1.49, -12.51, 2, 0},
{-0., 23.38, -0, 24},
{2.8, 32.6, 3, 33},
{inf_double, -inf_double, uint64_max, 0},
{-0.5252, 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s3), tc_s3, kRoundToPlusInf);
test_ftint_u_d(sizeof(tc_d3), tc_d3, kRoundToPlusInf);
struct TestCaseMsa2RF_F_U tc_s4[] = {
{0.f, 4.5f, 1.49f, -12.51f, 0, 4, 1, 0},
{-0.f, 23.38f, 2.8f, 32.6f, 0, 23, 2, 32},
{inf_float, -inf_float, 0, 4.f * uint32_max, uint32_max, 0, 0,
uint32_max}};
struct TestCaseMsa2RF_D_U tc_d4[] = {
{0., 4.5, 0, 4},
{1.49, -12.51, 1, 0},
{-0., 23.38, -0, 23},
{2.8, 32.6, 2, 32},
{inf_double, -inf_double, uint64_max, 0},
{-0.098797, 4000. * uint64_max, 0, uint64_max}};
test_ftint_u_s(sizeof(tc_s4), tc_s4, kRoundToMinusInf);
test_ftint_u_d(sizeof(tc_d4), tc_d4, kRoundToMinusInf);
}
struct TestCaseMsa2RF_U_F {
uint32_t ws1;
uint32_t ws2;
uint32_t ws3;
uint32_t ws4;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_U_D {
uint64_t ws1;
uint64_t ws2;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_ffint_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_U_F tc_s[] = {
{0, 345, 234, 1000, 0.f, 345.f, 234.f, 1000.f}};
struct TestCaseMsa2RF_U_D tc_d[] = {{0, 345, 0., 345.},
{234, 1000, 234., 1000.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffint_u_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_U_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffint_u_d(w2, w0); });
}
}
struct TestCaseMsa2RF_I_F {
int32_t ws1;
int32_t ws2;
int32_t ws3;
int32_t ws4;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_I_D {
int64_t ws1;
int64_t ws2;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_ffint_s) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_I_F tc_s[] = {
{0, 345, -234, 1000, 0.f, 345.f, -234.f, 1000.f}};
struct TestCaseMsa2RF_I_D tc_d[] = {{0, 345, 0., 345.},
{-234, 1000, -234., 1000.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_I_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffint_s_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_I_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffint_s_d(w2, w0); });
}
}
struct TestCaseMsa2RF_U16_F {
uint16_t ws1;
uint16_t ws2;
uint16_t ws3;
uint16_t ws4;
uint16_t ws5;
uint16_t ws6;
uint16_t ws7;
uint16_t ws8;
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct TestCaseMsa2RF_F_D {
float ws1;
float ws2;
float ws3;
float ws4;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_fexupl) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
struct TestCaseMsa2RF_U16_F tc_s[] = {
{1, 2, 0x7C00, 0x0C00, 0, 0x7C00, 0xFC00, 0x8000, 0.f, inf_float,
-inf_float, -0.f},
{0xFC00, 0xFFFF, 0x00FF, 0x8000, 0x81FE, 0x8000, 0x0345, 0xAAAA,
-3.0398368835e-5f, -0.f, 4.9889088e-5f, -5.2062988281e-2f},
{3, 4, 0x5555, 6, 0x2AAA, 0x8700, 0x7777, 0x6A8B, 5.2062988281e-2f,
-1.06811523458e-4f, 3.0576e4f, 3.35e3f}};
struct TestCaseMsa2RF_F_D tc_d[] = {
{0.f, 123.456f, inf_float, -0.f, inf_double, -0.},
{-inf_float, -3.f, 0.f, -inf_float, 0., -inf_double},
{2.3f, 3., 1.37747639043129518071e-41f, -3.22084585277826e35f,
1.37747639043129518071e-41, -3.22084585277826e35}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fexupl_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_F_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fexupl_d(w2, w0); });
}
}
TEST(MSA_fexupr) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const double inf_double = std::numeric_limits<double>::infinity();
struct TestCaseMsa2RF_U16_F tc_s[] = {
{0, 0x7C00, 0xFC00, 0x8000, 1, 2, 0x7C00, 0x0C00, 0.f, inf_float,
-inf_float, -0.f},
{0x81FE, 0x8000, 0x0345, 0xAAAA, 0xFC00, 0xFFFF, 0x00FF, 0x8000,
-3.0398368835e-5f, -0.f, 4.9889088e-5f, -5.2062988281e-2f},
{0x2AAA, 0x8700, 0x7777, 0x6A8B, 3, 4, 0x5555, 6, 5.2062988281e-2f,
-1.06811523458e-4f, 3.0576e4f, 3.35e3f}};
struct TestCaseMsa2RF_F_D tc_d[] = {
{inf_float, -0.f, 0.f, 123.456f, inf_double, -0.},
{0.f, -inf_float, -inf_float, -3.f, 0., -inf_double},
{1.37747639043129518071e-41f, -3.22084585277826e35f, 2.3f, 3.,
1.37747639043129518071e-41, -3.22084585277826e35}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ fexupr_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_F_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ fexupr_d(w2, w0); });
}
}
struct TestCaseMsa2RF_U32_D {
uint32_t ws1;
uint32_t ws2;
uint32_t ws3;
uint32_t ws4;
double exp_res_1;
double exp_res_2;
};
TEST(MSA_ffql) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_U16_F tc_s[] = {{0, 3, 0xFFFF, 0x8000, 0x8000, 0xE000,
0x0FF0, 0, -1.f, -0.25f,
0.12451171875f, 0.f}};
struct TestCaseMsa2RF_U32_D tc_d[] = {
{0, 45, 0x80000000, 0xE0000000, -1., -0.25},
{0x28379, 0xAAAA5555, 0x024903D3, 0, 17.853239085525274277e-3, 0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffql_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_U32_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffql_d(w2, w0); });
}
}
TEST(MSA_ffqr) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa2RF_U16_F tc_s[] = {{0x8000, 0xE000, 0x0FF0, 0, 0, 3,
0xFFFF, 0x8000, -1.f, -0.25f,
0.12451171875f, 0.f}};
struct TestCaseMsa2RF_U32_D tc_d[] = {
{0x80000000, 0xE0000000, 0, 45, -1., -0.25},
{0x024903D3, 0, 0x28379, 0xAAAA5555, 17.853239085525274277e-3, 0.}};
for (size_t i = 0; i < sizeof(tc_s) / sizeof(TestCaseMsa2RF_U16_F); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_s[i]),
[](MacroAssembler& assm) { __ ffqr_w(w2, w0); });
}
for (size_t i = 0; i < sizeof(tc_d) / sizeof(TestCaseMsa2RF_U32_D); ++i) {
run_msa_2r(reinterpret_cast<const TestCaseMsa2R*>(&tc_d[i]),
[](MacroAssembler& assm) { __ ffqr_d(w2, w0); });
}
}
struct TestCaseMsaVector {
uint64_t wd_lo;
uint64_t wd_hi;
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wt_lo;
uint64_t wt_hi;
};
template <typename InstFunc, typename OperFunc>
void run_msa_vector(struct TestCaseMsaVector* input,
InstFunc GenerateVectorInstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, &(input->ws_lo), w0, t0, t1);
load_elements_of_vector(assm, &(input->wt_lo), w2, t0, t1);
load_elements_of_vector(assm, &(input->wd_lo), w4, t0, t1);
GenerateVectorInstructionFunc(assm);
store_elements_of_vector(assm, w4, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input->wd_lo, input->ws_lo, input->wt_lo),
res.d[0]);
CHECK_EQ(GenerateOperationFunc(input->wd_hi, input->ws_hi, input->wt_hi),
res.d[1]);
}
TEST(MSA_vector) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaVector tc[] = {
// wd_lo, wd_hi, ws_lo, ws_hi, wt_lo, wt_hi
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0xDCD39D91F9057627,
0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 0x49547AAD691DA4CA},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0x401614523D830549,
0xD7C46D613F50EDDD, 0x52284CBC60A1562B, 0x1756ED510D8849CD},
{0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 0xD6E2D2EBCB40D72F,
0x13A619AFCE67B079, 0x36CCE284343E40F9, 0xB4E8F44FD148BF7F}};
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaVector); ++i) {
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ and_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ws & wt; });
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ or_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ws | wt; });
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ nor_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ~(ws | wt); });
run_msa_vector(
&tc[i], [](MacroAssembler& assm) { __ xor_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) { return ws ^ wt; });
run_msa_vector(&tc[i], [](MacroAssembler& assm) { __ bmnz_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) {
return (ws & wt) | (wd & ~wt);
});
run_msa_vector(&tc[i], [](MacroAssembler& assm) { __ bmz_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) {
return (ws & ~wt) | (wd & wt);
});
run_msa_vector(&tc[i], [](MacroAssembler& assm) { __ bsel_v(w4, w0, w2); },
[](uint64_t wd, uint64_t ws, uint64_t wt) {
return (ws & ~wd) | (wt & wd);
});
}
}
struct TestCaseMsaBit {
uint64_t wd_lo;
uint64_t wd_hi;
uint64_t ws_lo;
uint64_t ws_hi;
uint32_t m;
};
template <typename InstFunc, typename OperFunc>
void run_msa_bit(struct TestCaseMsaBit* input, InstFunc GenerateInstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, &(input->ws_lo), w0, t0, t1);
load_elements_of_vector(assm, &(input->wd_lo), w2, t0, t1);
GenerateInstructionFunc(assm, input->m);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input->wd_lo, input->ws_lo, input->m),
res.d[0]);
CHECK_EQ(GenerateOperationFunc(input->wd_hi, input->ws_hi, input->m),
res.d[1]);
}
TEST(MSA_slli_srai_srli) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {
// wd_lo, wd_hi ws_lo, ws_hi, m
{0, 0, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 3},
{0, 0, 0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0, 0, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0, 0, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0, 0, 0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0, 0, 0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0, 0, 0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0, 0, 0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define SLLI_SRLI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
return res; \
}
#define SRAI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
int64_t elem = \
static_cast<int64_t>(((ws >> shift) & mask) << (64 - elem_size)) >> \
(64 - elem_size); \
res |= static_cast<uint64_t>((func)&mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_b(w2, w0, m % 8); },
SLLI_SRLI_DF(kMSALanesByte, UINT8_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_h(w2, w0, m % 16); },
SLLI_SRLI_DF(kMSALanesHalf, UINT16_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_w(w2, w0, m % 32); },
SLLI_SRLI_DF(kMSALanesWord, UINT32_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ slli_d(w2, w0, m % 64); },
SLLI_SRLI_DF(kMSALanesDword, UINT64_MAX, (elem << (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_b(w2, w0, m % 8); },
SLLI_SRLI_DF(kMSALanesByte, UINT8_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_h(w2, w0, m % 16); },
SLLI_SRLI_DF(kMSALanesHalf, UINT16_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_w(w2, w0, m % 32); },
SLLI_SRLI_DF(kMSALanesWord, UINT32_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srli_d(w2, w0, m % 64); },
SLLI_SRLI_DF(kMSALanesDword, UINT64_MAX, (elem >> (m % elem_size))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_b(w2, w0, m % 8); },
SLLI_SRLI_DF(
kMSALanesByte, UINT8_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_h(w2, w0, m % 16); },
SLLI_SRLI_DF(
kMSALanesHalf, UINT16_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_w(w2, w0, m % 32); },
SLLI_SRLI_DF(
kMSALanesWord, UINT32_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srlri_d(w2, w0, m % 64); },
SLLI_SRLI_DF(
kMSALanesDword, UINT64_MAX,
(elem >> (m % elem_size)) + ((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_b(w2, w0, m % 8); },
SRAI_DF(kMSALanesByte, UINT8_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_h(w2, w0, m % 16); },
SRAI_DF(kMSALanesHalf, UINT16_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_w(w2, w0, m % 32); },
SRAI_DF(kMSALanesWord, UINT32_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srai_d(w2, w0, m % 64); },
SRAI_DF(kMSALanesDword, UINT64_MAX,
ArithmeticShiftRight(elem, m % elem_size)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_b(w2, w0, m % 8); },
SRAI_DF(kMSALanesByte, UINT8_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_h(w2, w0, m % 16); },
SRAI_DF(kMSALanesHalf, UINT16_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_w(w2, w0, m % 32); },
SRAI_DF(kMSALanesWord, UINT32_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ srari_d(w2, w0, m % 64); },
SRAI_DF(kMSALanesDword, UINT64_MAX,
ArithmeticShiftRight(elem, m % elem_size) +
((elem >> (m % elem_size - 1)) & 0x1)));
}
#undef SLLI_SRLI_DF
#undef SRAI_DF
}
TEST(MSA_bclri_bseti_bnegi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {
// wd_lo, wd_hi, ws_lo, ws_hi, m
{0, 0, 0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 3},
{0, 0, 0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0, 0, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0, 0, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0, 0, 0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0, 0, 0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0, 0, 0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0, 0, 0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define BCLRI_BSETI_BNEGI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem = (ws >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_b(w2, w0, m % 8); },
BCLRI_BSETI_BNEGI_DF(kMSALanesByte, UINT8_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_h(w2, w0, m % 16); },
BCLRI_BSETI_BNEGI_DF(kMSALanesHalf, UINT16_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_w(w2, w0, m % 32); },
BCLRI_BSETI_BNEGI_DF(kMSALanesWord, UINT32_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bclri_d(w2, w0, m % 64); },
BCLRI_BSETI_BNEGI_DF(kMSALanesDword, UINT64_MAX,
(~(1ull << (m % elem_size)) & elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_b(w2, w0, m % 8); },
BCLRI_BSETI_BNEGI_DF(kMSALanesByte, UINT8_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_h(w2, w0, m % 16); },
BCLRI_BSETI_BNEGI_DF(kMSALanesHalf, UINT16_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_w(w2, w0, m % 32); },
BCLRI_BSETI_BNEGI_DF(kMSALanesWord, UINT32_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bseti_d(w2, w0, m % 64); },
BCLRI_BSETI_BNEGI_DF(kMSALanesDword, UINT64_MAX,
((1ull << (m % elem_size)) | elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_b(w2, w0, m % 8); },
BCLRI_BSETI_BNEGI_DF(kMSALanesByte, UINT8_MAX,
((1ull << (m % elem_size)) ^ elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_h(w2, w0, m % 16); },
BCLRI_BSETI_BNEGI_DF(kMSALanesHalf, UINT16_MAX,
((1ull << (m % elem_size)) ^ elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_w(w2, w0, m % 32); },
BCLRI_BSETI_BNEGI_DF(kMSALanesWord, UINT32_MAX,
((1ull << (m % elem_size)) ^ elem)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ bnegi_d(w2, w0, m % 64); },
BCLRI_BSETI_BNEGI_DF(kMSALanesDword, UINT64_MAX,
((1ull << (m % elem_size)) ^ elem)));
}
#undef BCLRI_BSETI_BNEGI_DF
}
TEST(MSA_binsli_binsri) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {// wd_lo, wd_hi, ws_lo, ws_hi, m
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0xF35862E13E38F8B0, 0x4F41FFDEF2BFE636, 3},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0x53F4457553BBD5B4, 0x5FB8250EACC296B2,
0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0xF61BFDB0F312E6FC, 0xC9437568DD1EA925,
0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define BINSLI_BINSRI_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
int bits = m % elem_size + 1; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t ws_elem = (ws >> shift) & mask; \
if (bits == elem_size) { \
res |= (ws_elem & mask) << shift; \
} else { \
uint64_t r_mask = (1ull << bits) - 1; \
uint64_t l_mask = r_mask << (elem_size - bits); \
USE(l_mask); \
uint64_t wd_elem = (wd >> shift) & mask; \
res |= ((func)&mask) << shift; \
} \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_b(w2, w0, m % 8); },
BINSLI_BINSRI_DF(kMSALanesByte, UINT8_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_h(w2, w0, m % 16); },
BINSLI_BINSRI_DF(kMSALanesHalf, UINT16_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_w(w2, w0, m % 32); },
BINSLI_BINSRI_DF(kMSALanesWord, UINT32_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsli_d(w2, w0, m % 64); },
BINSLI_BINSRI_DF(kMSALanesDword, UINT64_MAX,
((ws_elem & l_mask) | (wd_elem & ~l_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_b(w2, w0, m % 8); },
BINSLI_BINSRI_DF(kMSALanesByte, UINT8_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_h(w2, w0, m % 16); },
BINSLI_BINSRI_DF(kMSALanesHalf, UINT16_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_w(w2, w0, m % 32); },
BINSLI_BINSRI_DF(kMSALanesWord, UINT32_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ binsri_d(w2, w0, m % 64); },
BINSLI_BINSRI_DF(kMSALanesDword, UINT64_MAX,
((ws_elem & r_mask) | (wd_elem & ~r_mask))));
}
#undef BINSLI_BINSRI_DF
}
TEST(MSA_sat_s_sat_u) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsaBit tc[] = {
// wd_lo, wd_hi, ws_lo, ws_hi, m
{0, 0, 0xF35862E13E3808B0, 0x4F41FFDEF2BFE636, 3},
{0, 0, 0x64BE4F6DBE9CAA51, 0x6B23DE1A687D9CB9, 5},
{0, 0, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 9},
{0, 0, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 13},
{0, 0, 0x566BE7BA4365B70A, 0x01EBBC1937D76CB4, 21},
{0, 0, 0x380E2DEB9D3F8AAE, 0x017E0DE0BCC6CA42, 30},
{0, 0, 0xA46A3A9BCB43F4E5, 0x1C62C8473BDFCFFB, 45},
{0, 0, 0xF6759D85F23B5A2B, 0x5C042AE42C6D12C1, 61}};
#define SAT_DF(lanes, mask, func) \
[](uint64_t wd, uint64_t ws, uint32_t m) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
m %= elem_size; \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
uint64_t elem_u64 = (ws >> shift) & mask; \
int64_t elem_i64 = static_cast<int64_t>(elem_u64 << (64 - elem_size)) >> \
(64 - elem_size); \
USE(elem_i64); \
res |= ((func)&mask) << shift; \
} \
return res; \
}
#define M_MAX_INT(x) static_cast<int64_t>((1LL << ((x)-1)) - 1)
#define M_MIN_INT(x) static_cast<int64_t>(-(1LL << ((x)-1)))
#define M_MAX_UINT(x) static_cast<uint64_t>(-1ULL >> (64 - (x)))
for (size_t i = 0; i < sizeof(tc) / sizeof(TestCaseMsaBit); ++i) {
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_b(w2, w0, m % 8); },
SAT_DF(kMSALanesByte, UINT8_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_h(w2, w0, m % 16); },
SAT_DF(kMSALanesHalf, UINT16_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_w(w2, w0, m % 32); },
SAT_DF(kMSALanesWord, UINT32_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_u_d(w2, w0, m % 64); },
SAT_DF(kMSALanesDword, UINT64_MAX,
(elem_u64 < M_MAX_UINT(m + 1) ? elem_u64 : M_MAX_UINT(m + 1))));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_b(w2, w0, m % 8); },
SAT_DF(
kMSALanesByte, UINT8_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_h(w2, w0, m % 16); },
SAT_DF(
kMSALanesHalf, UINT16_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_w(w2, w0, m % 32); },
SAT_DF(
kMSALanesWord, UINT32_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
run_msa_bit(
&tc[i],
[](MacroAssembler& assm, uint32_t m) { __ sat_s_d(w2, w0, m % 64); },
SAT_DF(
kMSALanesDword, UINT64_MAX,
(elem_i64 < M_MIN_INT(m + 1)
? M_MIN_INT(m + 1)
: elem_i64 > M_MAX_INT(m + 1) ? M_MAX_INT(m + 1) : elem_i64)));
}
#undef SAT_DF
#undef M_MAX_INT
#undef M_MIN_INT
#undef M_MAX_UINT
}
template <typename InstFunc, typename OperFunc>
void run_msa_i10(int32_t input, InstFunc GenerateVectorInstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
GenerateVectorInstructionFunc(assm, input);
store_elements_of_vector(assm, w0, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(GenerateOperationFunc(input), res.d[0]);
CHECK_EQ(GenerateOperationFunc(input), res.d[1]);
}
TEST(MSA_ldi) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
// signed 10bit integers: -512 .. 511
int32_t tc[] = {0, -1, 1, 256, -256, -178, 352, -512, 511};
#define LDI_DF(lanes, mask) \
[](int32_t s10) { \
uint64_t res = 0; \
int elem_size = kMSARegSize / lanes; \
int64_t s10_64 = \
ArithmeticShiftRight(static_cast<int64_t>(s10) << 54, 54); \
for (int i = 0; i < lanes / 2; ++i) { \
int shift = elem_size * i; \
res |= static_cast<uint64_t>(s10_64 & mask) << shift; \
} \
return res; \
}
for (size_t i = 0; i < sizeof(tc) / sizeof(int32_t); ++i) {
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_b(w0, s10); },
LDI_DF(kMSALanesByte, UINT8_MAX));
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_h(w0, s10); },
LDI_DF(kMSALanesHalf, UINT16_MAX));
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_w(w0, s10); },
LDI_DF(kMSALanesWord, UINT32_MAX));
run_msa_i10(tc[i],
[](MacroAssembler& assm, int32_t s10) { __ ldi_d(w0, s10); },
LDI_DF(kMSALanesDword, UINT64_MAX));
}
#undef LDI_DF
}
template <typename T, typename InstFunc>
void run_msa_mi10(InstFunc GenerateVectorInstructionFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
T in_test_vector[1024];
T out_test_vector[1024];
T* in_array_middle = in_test_vector + arraysize(in_test_vector) / 2;
T* out_array_middle = out_test_vector + arraysize(out_test_vector) / 2;
v8::base::RandomNumberGenerator rand_gen(FLAG_random_seed);
for (unsigned int i = 0; i < arraysize(in_test_vector); i++) {
in_test_vector[i] = static_cast<T>(rand_gen.NextInt());
out_test_vector[i] = 0;
}
GenerateVectorInstructionFunc(assm);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F4>::FromCode(*code);
(f.Call(in_array_middle, out_array_middle, 0, 0, 0));
CHECK_EQ(memcmp(in_test_vector, out_test_vector, arraysize(in_test_vector)),
0);
}
TEST(MSA_load_store_vector) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
run_msa_mi10<uint8_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 16) {
__ ld_b(w0, MemOperand(a0, i));
__ st_b(w0, MemOperand(a1, i));
}
});
run_msa_mi10<uint16_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 8) {
__ ld_h(w0, MemOperand(a0, i));
__ st_h(w0, MemOperand(a1, i));
}
});
run_msa_mi10<uint32_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 4) {
__ ld_w(w0, MemOperand(a0, i));
__ st_w(w0, MemOperand(a1, i));
}
});
run_msa_mi10<uint64_t>([](MacroAssembler& assm) {
for (int i = -512; i < 512; i += 2) {
__ ld_d(w0, MemOperand(a0, i));
__ st_d(w0, MemOperand(a1, i));
}
});
}
struct TestCaseMsa3R {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wt_lo;
uint64_t wt_hi;
uint64_t wd_lo;
uint64_t wd_hi;
};
static const uint64_t Unpredictable = 0x312014017725ll;
template <typename InstFunc, typename OperFunc>
void run_msa_3r(struct TestCaseMsa3R* input, InstFunc GenerateI5InstructionFunc,
OperFunc GenerateOperationFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(assm, &(input->wt_lo), w0, t0, t1);
load_elements_of_vector(assm, &(input->ws_lo), w1, t0, t1);
load_elements_of_vector(assm, &(input->wd_lo), w2, t0, t1);
GenerateI5InstructionFunc(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
GenerateOperationFunc(&input->ws_lo, &input->wt_lo, &input->wd_lo);
if (input->wd_lo != Unpredictable) {
CHECK_EQ(input->wd_lo, res.d[0]);
}
if (input->wd_hi != Unpredictable) {
CHECK_EQ(input->wd_hi, res.d[1]);
}
}
TEST(MSA_3R_instructions) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
struct TestCaseMsa3R tc[] = {
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3,
0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF,
0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8},
{0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3,
0xF7A594AEC8EF8A9C, 0x1169751BB9A7D9C3, 0xF7A594AEC8EF8A9C},
{0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF,
0x3A0D80D68B3F8BC8, 0x2B665362C4E812DF, 0x3A0D80D68B3F8BC8},
{0xFFAB807F807FFFCD, 0x7F23FF80FF567F80, 0xFFAB807F807FFFCD,
0x7F23FF80FF567F80, 0xFFAB807F807FFFCD, 0x7F23FF80FF567F80},
{0x80FFEFFF7F12807F, 0x807F80FF7FDEFF78, 0x80FFEFFF7F12807F,
0x807F80FF7FDEFF78, 0x80FFEFFF7F12807F, 0x807F80FF7FDEFF78},
{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF},
{0x0000000000000000, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
0x0000000000000000, 0x0000000000000000, 0xFFFFFFFFFFFFFFFF},
{0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000,
0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000, 0xFFFF0000FFFF0000},
{0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00,
0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00, 0xFF00FF00FF00FF00},
{0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0,
0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0, 0xF0F0F0F0F0F0F0F0},
{0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF,
0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF, 0xFF0000FFFF0000FF},
{0xFFFF00000000FFFF, 0xFFFF00000000FFFF, 0xFFFF00000000FFFF,
0xFFFF00000000FFFF, 0xFFFF00000000FFFF, 0xFFFF00000000FFFF}};
#define SLL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>((wt[i] >> shift) & mask) % size_in_bits; \
res |= (static_cast<uint64_t>(src_op << shift_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define SRA_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = ((wt[i] >> shift) & mask) % size_in_bits; \
res |= (static_cast<uint64_t>(ArithmeticShiftRight(src_op, shift_op) & \
mask)) \
<< shift; \
} \
wd[i] = res; \
}
#define SRL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
res |= (static_cast<uint64_t>(src_op >> shift_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define BCRL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
T r = (static_cast<T>(~(1ull << shift_op)) & src_op) & mask; \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BSET_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
T r = (static_cast<T>(1ull << shift_op) | src_op) & mask; \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BNEG_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
T r = (static_cast<T>(1ull << shift_op) ^ src_op) & mask; \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BINSL_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
int bits = shift_op + 1; \
T r; \
if (bits == size_in_bits) { \
r = static_cast<T>(ws_op); \
} else { \
uint64_t mask2 = ((1ull << bits) - 1) << (size_in_bits - bits); \
r = static_cast<T>((static_cast<T>(mask2) & ws_op) | \
(static_cast<T>(~mask2) & wd_op)); \
} \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define BINSR_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
T shift_op = static_cast<T>(((wt[i] >> shift) & mask) % size_in_bits); \
int bits = shift_op + 1; \
T r; \
if (bits == size_in_bits) { \
r = static_cast<T>(ws_op); \
} else { \
uint64_t mask2 = (1ull << bits) - 1; \
r = static_cast<T>((static_cast<T>(mask2) & ws_op) | \
(static_cast<T>(~mask2) & wd_op)); \
} \
res |= static_cast<uint64_t>(r) << shift; \
} \
wd[i] = res; \
}
#define ADDV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op + wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define SUBV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op - wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MAX_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Max<T>(ws_op, wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define MIN_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Min<T>(ws_op, wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define MAXA_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= \
(static_cast<uint64_t>(Nabs(ws_op) < Nabs(wt_op) ? ws_op : wt_op) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define MINA_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= \
(static_cast<uint64_t>(Nabs(ws_op) > Nabs(wt_op) ? ws_op : wt_op) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define CEQ_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(!Compare(ws_op, wt_op) ? -1ull : 0ull) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define CLT_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>((Compare(ws_op, wt_op) == -1) ? -1ull \
: 0ull) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define CLE_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>((Compare(ws_op, wt_op) != 1) ? -1ull \
: 0ull) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define ADD_A_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Abs(ws_op) + Abs(wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define ADDS_A_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = Nabs(static_cast<T>((ws[i] >> shift) & mask)); \
T wt_op = Nabs(static_cast<T>((wt[i] >> shift) & mask)); \
T r; \
if (ws_op < -std::numeric_limits<T>::max() - wt_op) { \
r = std::numeric_limits<T>::max(); \
} else { \
r = -(ws_op + wt_op); \
} \
res |= (static_cast<uint64_t>(r) & mask) << shift; \
} \
wd[i] = res; \
}
#define ADDS_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(SaturateAdd(ws_op, wt_op)) & mask) \
<< shift; \
} \
wd[i] = res; \
}
#define AVE_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>( \
((wt_op & ws_op) + ((ws_op ^ wt_op) >> 1)) & mask)) \
<< shift; \
} \
wd[i] = res; \
}
#define AVER_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>( \
((wt_op | ws_op) - ((ws_op ^ wt_op) >> 1)) & mask)) \
<< shift; \
} \
wd[i] = res; \
}
#define SUBS_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(SaturateSub(ws_op, wt_op)) & mask) \
<< shift; \
} \
wd[i] = res; \
}
#define SUBSUS_U_DF(T, lanes, mask) \
typedef typename std::make_unsigned<T>::type uT; \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
uT ws_op = static_cast<uT>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
T r; \
if (wt_op > 0) { \
uT wtu = static_cast<uT>(wt_op); \
if (wtu > ws_op) { \
r = 0; \
} else { \
r = static_cast<T>(ws_op - wtu); \
} \
} else { \
if (ws_op > std::numeric_limits<uT>::max() + wt_op) { \
r = static_cast<T>(std::numeric_limits<uT>::max()); \
} else { \
r = static_cast<T>(ws_op - wt_op); \
} \
} \
res |= (static_cast<uint64_t>(r) & mask) << shift; \
} \
wd[i] = res; \
}
#define SUBSUU_S_DF(T, lanes, mask) \
typedef typename std::make_unsigned<T>::type uT; \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
uT ws_op = static_cast<uT>((ws[i] >> shift) & mask); \
uT wt_op = static_cast<uT>((wt[i] >> shift) & mask); \
uT wdu; \
T r; \
if (ws_op > wt_op) { \
wdu = ws_op - wt_op; \
if (wdu > std::numeric_limits<T>::max()) { \
r = std::numeric_limits<T>::max(); \
} else { \
r = static_cast<T>(wdu); \
} \
} else { \
wdu = wt_op - ws_op; \
CHECK(-std::numeric_limits<T>::max() == \
std::numeric_limits<T>::min() + 1); \
if (wdu <= std::numeric_limits<T>::max()) { \
r = -static_cast<T>(wdu); \
} else { \
r = std::numeric_limits<T>::min(); \
} \
} \
res |= (static_cast<uint64_t>(r) & mask) << shift; \
} \
wd[i] = res; \
}
#define ASUB_S_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(Abs(ws_op - wt_op)) & mask) << shift; \
} \
wd[i] = res; \
}
#define ASUB_U_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op > wt_op ? ws_op - wt_op \
: wt_op - ws_op) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define MULV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(ws_op * wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MADDV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(wd_op + ws_op * wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MSUBV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
T wd_op = static_cast<T>((wd[i] >> shift) & mask); \
res |= (static_cast<uint64_t>(wd_op - ws_op * wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define DIV_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
if (wt_op == 0) { \
res = Unpredictable; \
break; \
} \
res |= (static_cast<uint64_t>(ws_op / wt_op) & mask) << shift; \
} \
wd[i] = res; \
}
#define MOD_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T ws_op = static_cast<T>((ws[i] >> shift) & mask); \
T wt_op = static_cast<T>((wt[i] >> shift) & mask); \
if (wt_op == 0) { \
res = Unpredictable; \
break; \
} \
res |= (static_cast<uint64_t>(wt_op != 0 ? ws_op % wt_op : 0) & mask) \
<< shift; \
} \
wd[i] = res; \
}
#define SRAR_DF(T, lanes, mask) \
int size_in_bits = kMSARegSize / lanes; \
for (int i = 0; i < 2; i++) { \
uint64_t res = 0; \
for (int j = 0; j < lanes / 2; ++j) { \
uint64_t shift = size_in_bits * j; \
T src_op = static_cast<T>((ws[i] >> shift) & mask); \
T shift_op = ((wt[i] >> shift) & mask) % size_in_bits; \
uint32_t bit = shift_op == 0 ? 0 : src_op >> (shift_op - 1) & 1; \
res |= (static_cast<uint64_t>(ArithmeticShiftRight(src_op, shift_op) + \
bit) & \
mask) \
<< shift; \
} \
wd[i] = res; \
}
#define PCKEV_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[i] = wt_p[2 * i]; \
wd_p[i + lanes / 2] = ws_p[2 * i]; \
}
#define PCKOD_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[i] = wt_p[2 * i + 1]; \
wd_p[i + lanes / 2] = ws_p[2 * i + 1]; \
}
#define ILVL_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[i + lanes / 2]; \
wd_p[2 * i + 1] = ws_p[i + lanes / 2]; \
}
#define ILVR_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[i]; \
wd_p[2 * i + 1] = ws_p[i]; \
}
#define ILVEV_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[2 * i]; \
wd_p[2 * i + 1] = ws_p[2 * i]; \
}
#define ILVOD_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes / 2; ++i) { \
wd_p[2 * i] = wt_p[2 * i + 1]; \
wd_p[2 * i + 1] = ws_p[2 * i + 1]; \
}
#define VSHF_DF(T, lanes, mask) \
T* ws_p = reinterpret_cast<T*>(ws); \
T* wt_p = reinterpret_cast<T*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
const int mask_not_valid = 0xC0; \
const int mask_6bits = 0x3F; \
for (int i = 0; i < lanes; ++i) { \
if ((wd_p[i] & mask_not_valid)) { \
wd_p[i] = 0; \
} else { \
int k = (wd_p[i] & mask_6bits) % (lanes * 2); \
wd_p[i] = k > lanes ? ws_p[k - lanes] : wt_p[k]; \
} \
}
#define HADD_DF(T, T_small, lanes) \
T_small* ws_p = reinterpret_cast<T_small*>(ws); \
T_small* wt_p = reinterpret_cast<T_small*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes; ++i) { \
wd_p[i] = static_cast<T>(ws_p[2 * i + 1]) + static_cast<T>(wt_p[2 * i]); \
}
#define HSUB_DF(T, T_small, lanes) \
T_small* ws_p = reinterpret_cast<T_small*>(ws); \
T_small* wt_p = reinterpret_cast<T_small*>(wt); \
T* wd_p = reinterpret_cast<T*>(wd); \
for (int i = 0; i < lanes; ++i) { \
wd_p[i] = static_cast<T>(ws_p[2 * i + 1]) - static_cast<T>(wt_p[2 * i]); \
}
#define TEST_CASE(V) \
V(sll_b, SLL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(sll_h, SLL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(sll_w, SLL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(sll_d, SLL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(srl_b, SRL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(srl_h, SRL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(srl_w, SRL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(srl_d, SRL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(bclr_b, BCRL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(bclr_h, BCRL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(bclr_w, BCRL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(bclr_d, BCRL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(bset_b, BSET_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(bset_h, BSET_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(bset_w, BSET_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(bset_d, BSET_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(bneg_b, BNEG_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(bneg_h, BNEG_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(bneg_w, BNEG_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(bneg_d, BNEG_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(binsl_b, BINSL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(binsl_h, BINSL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(binsl_w, BINSL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(binsl_d, BINSL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(binsr_b, BINSR_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(binsr_h, BINSR_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(binsr_w, BINSR_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(binsr_d, BINSR_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(addv_b, ADDV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(addv_h, ADDV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(addv_w, ADDV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(addv_d, ADDV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(subv_b, SUBV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subv_h, SUBV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subv_w, SUBV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subv_d, SUBV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(max_s_b, MAX_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(max_s_h, MAX_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(max_s_w, MAX_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(max_s_d, MAX_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(max_u_b, MAX_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(max_u_h, MAX_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(max_u_w, MAX_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(max_u_d, MAX_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(min_s_b, MIN_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(min_s_h, MIN_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(min_s_w, MIN_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(min_s_d, MIN_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(min_u_b, MIN_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(min_u_h, MIN_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(min_u_w, MIN_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(min_u_d, MIN_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(max_a_b, MAXA_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(max_a_h, MAXA_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(max_a_w, MAXA_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(max_a_d, MAXA_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(min_a_b, MINA_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(min_a_h, MINA_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(min_a_w, MINA_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(min_a_d, MINA_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(ceq_b, CEQ_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ceq_h, CEQ_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ceq_w, CEQ_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ceq_d, CEQ_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(clt_s_b, CLT_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(clt_s_h, CLT_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(clt_s_w, CLT_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(clt_s_d, CLT_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(clt_u_b, CLT_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(clt_u_h, CLT_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(clt_u_w, CLT_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(clt_u_d, CLT_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(cle_s_b, CLE_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(cle_s_h, CLE_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(cle_s_w, CLE_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(cle_s_d, CLE_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(cle_u_b, CLE_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(cle_u_h, CLE_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(cle_u_w, CLE_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(cle_u_d, CLE_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(add_a_b, ADD_A_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(add_a_h, ADD_A_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(add_a_w, ADD_A_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(add_a_d, ADD_A_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(adds_a_b, ADDS_A_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(adds_a_h, ADDS_A_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(adds_a_w, ADDS_A_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(adds_a_d, ADDS_A_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(adds_s_b, ADDS_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(adds_s_h, ADDS_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(adds_s_w, ADDS_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(adds_s_d, ADDS_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(adds_u_b, ADDS_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(adds_u_h, ADDS_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(adds_u_w, ADDS_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(adds_u_d, ADDS_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ave_s_b, AVE_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(ave_s_h, AVE_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(ave_s_w, AVE_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(ave_s_d, AVE_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(ave_u_b, AVE_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ave_u_h, AVE_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ave_u_w, AVE_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ave_u_d, AVE_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(aver_s_b, AVER_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(aver_s_h, AVER_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(aver_s_w, AVER_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(aver_s_d, AVER_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(aver_u_b, AVER_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(aver_u_h, AVER_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(aver_u_w, AVER_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(aver_u_d, AVER_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(subs_s_b, SUBS_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subs_s_h, SUBS_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subs_s_w, SUBS_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subs_s_d, SUBS_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(subs_u_b, SUBS_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(subs_u_h, SUBS_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(subs_u_w, SUBS_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(subs_u_d, SUBS_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(subsus_u_b, SUBSUS_U_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subsus_u_h, SUBSUS_U_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subsus_u_w, SUBSUS_U_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subsus_u_d, SUBSUS_U_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(subsuu_s_b, SUBSUU_S_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(subsuu_s_h, SUBSUU_S_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(subsuu_s_w, SUBSUU_S_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(subsuu_s_d, SUBSUU_S_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(asub_s_b, ASUB_S_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(asub_s_h, ASUB_S_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(asub_s_w, ASUB_S_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(asub_s_d, ASUB_S_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(asub_u_b, ASUB_U_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(asub_u_h, ASUB_U_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(asub_u_w, ASUB_U_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(asub_u_d, ASUB_U_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(mulv_b, MULV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(mulv_h, MULV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(mulv_w, MULV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(mulv_d, MULV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(maddv_b, MADDV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(maddv_h, MADDV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(maddv_w, MADDV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(maddv_d, MADDV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(msubv_b, MSUBV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(msubv_h, MSUBV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(msubv_w, MSUBV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(msubv_d, MSUBV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(div_s_b, DIV_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(div_s_h, DIV_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(div_s_w, DIV_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(div_s_d, DIV_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(div_u_b, DIV_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(div_u_h, DIV_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(div_u_w, DIV_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(div_u_d, DIV_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(mod_s_b, MOD_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(mod_s_h, MOD_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(mod_s_w, MOD_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(mod_s_d, MOD_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(mod_u_b, MOD_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(mod_u_h, MOD_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(mod_u_w, MOD_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(mod_u_d, MOD_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(srlr_b, SRAR_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(srlr_h, SRAR_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(srlr_w, SRAR_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(srlr_d, SRAR_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(pckev_b, PCKEV_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(pckev_h, PCKEV_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(pckev_w, PCKEV_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(pckev_d, PCKEV_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(pckod_b, PCKOD_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(pckod_h, PCKOD_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(pckod_w, PCKOD_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(pckod_d, PCKOD_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvl_b, ILVL_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvl_h, ILVL_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvl_w, ILVL_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvl_d, ILVL_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvr_b, ILVR_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvr_h, ILVR_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvr_w, ILVR_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvr_d, ILVR_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvev_b, ILVEV_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvev_h, ILVEV_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvev_w, ILVEV_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvev_d, ILVEV_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(ilvod_b, ILVOD_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(ilvod_h, ILVOD_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(ilvod_w, ILVOD_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(ilvod_d, ILVOD_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(vshf_b, VSHF_DF, uint8_t, kMSALanesByte, UINT8_MAX) \
V(vshf_h, VSHF_DF, uint16_t, kMSALanesHalf, UINT16_MAX) \
V(vshf_w, VSHF_DF, uint32_t, kMSALanesWord, UINT32_MAX) \
V(vshf_d, VSHF_DF, uint64_t, kMSALanesDword, UINT64_MAX) \
V(hadd_s_h, HADD_DF, int16_t, int8_t, kMSALanesHalf) \
V(hadd_s_w, HADD_DF, int32_t, int16_t, kMSALanesWord) \
V(hadd_s_d, HADD_DF, int64_t, int32_t, kMSALanesDword) \
V(hadd_u_h, HADD_DF, uint16_t, uint8_t, kMSALanesHalf) \
V(hadd_u_w, HADD_DF, uint32_t, uint16_t, kMSALanesWord) \
V(hadd_u_d, HADD_DF, uint64_t, uint32_t, kMSALanesDword) \
V(hsub_s_h, HSUB_DF, int16_t, int8_t, kMSALanesHalf) \
V(hsub_s_w, HSUB_DF, int32_t, int16_t, kMSALanesWord) \
V(hsub_s_d, HSUB_DF, int64_t, int32_t, kMSALanesDword) \
V(hsub_u_h, HSUB_DF, uint16_t, uint8_t, kMSALanesHalf) \
V(hsub_u_w, HSUB_DF, uint32_t, uint16_t, kMSALanesWord) \
V(hsub_u_d, HSUB_DF, uint64_t, uint32_t, kMSALanesDword)
#define RUN_TEST(instr, verify, type, lanes, mask) \
run_msa_3r(&tc[i], [](MacroAssembler& assm) { __ instr(w2, w1, w0); }, \
[](uint64_t* ws, uint64_t* wt, uint64_t* wd) { \
verify(type, lanes, mask); \
});
for (size_t i = 0; i < arraysize(tc); ++i) {
TEST_CASE(RUN_TEST)
}
#define RUN_TEST2(instr, verify, type, lanes, mask) \
for (unsigned i = 0; i < arraysize(tc); i++) { \
for (unsigned j = 0; j < 3; j++) { \
for (unsigned k = 0; k < lanes; k++) { \
type* element = reinterpret_cast<type*>(&tc[i]); \
element[k + j * lanes] &= std::numeric_limits<type>::max(); \
} \
} \
} \
run_msa_3r(&tc[i], [](MacroAssembler& assm) { __ instr(w2, w1, w0); }, \
[](uint64_t* ws, uint64_t* wt, uint64_t* wd) { \
verify(type, lanes, mask); \
});
#define TEST_CASE2(V) \
V(sra_b, SRA_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(sra_h, SRA_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(sra_w, SRA_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(sra_d, SRA_DF, int64_t, kMSALanesDword, UINT64_MAX) \
V(srar_b, SRAR_DF, int8_t, kMSALanesByte, UINT8_MAX) \
V(srar_h, SRAR_DF, int16_t, kMSALanesHalf, UINT16_MAX) \
V(srar_w, SRAR_DF, int32_t, kMSALanesWord, UINT32_MAX) \
V(srar_d, SRAR_DF, int64_t, kMSALanesDword, UINT64_MAX)
for (size_t i = 0; i < arraysize(tc); ++i) {
TEST_CASE2(RUN_TEST2)
}
#undef TEST_CASE
#undef TEST_CASE2
#undef RUN_TEST
#undef RUN_TEST2
#undef SLL_DF
#undef SRL_DF
#undef SRA_DF
#undef BCRL_DF
#undef BSET_DF
#undef BNEG_DF
#undef BINSL_DF
#undef BINSR_DF
#undef ADDV_DF
#undef SUBV_DF
#undef MAX_DF
#undef MIN_DF
#undef MAXA_DF
#undef MINA_DF
#undef CEQ_DF
#undef CLT_DF
#undef CLE_DF
#undef ADD_A_DF
#undef ADDS_A_DF
#undef ADDS_DF
#undef AVE_DF
#undef AVER_DF
#undef SUBS_DF
#undef SUBSUS_U_DF
#undef SUBSUU_S_DF
#undef ASUB_S_DF
#undef ASUB_U_DF
#undef MULV_DF
#undef MADDV_DF
#undef MSUBV_DF
#undef DIV_DF
#undef MOD_DF
#undef SRAR_DF
#undef PCKEV_DF
#undef PCKOD_DF
#undef ILVL_DF
#undef ILVR_DF
#undef ILVEV_DF
#undef ILVOD_DF
#undef VSHF_DF
#undef HADD_DF
#undef HSUB_DF
} // namespace internal
struct TestCaseMsa3RF {
uint64_t ws_lo;
uint64_t ws_hi;
uint64_t wt_lo;
uint64_t wt_hi;
uint64_t wd_lo;
uint64_t wd_hi;
};
struct ExpectedResult_MSA3RF {
uint64_t exp_res_lo;
uint64_t exp_res_hi;
};
template <typename Func>
void run_msa_3rf(const struct TestCaseMsa3RF* input,
const struct ExpectedResult_MSA3RF* output,
Func Generate2RInstructionFunc) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, NULL, 0, v8::internal::CodeObjectRequired::kYes);
CpuFeatureScope fscope(&assm, MIPS_SIMD);
msa_reg_t res;
load_elements_of_vector(
assm, reinterpret_cast<const uint64_t*>(&input->ws_lo), w0, t0, t1);
load_elements_of_vector(
assm, reinterpret_cast<const uint64_t*>(&input->wt_lo), w1, t0, t1);
load_elements_of_vector(
assm, reinterpret_cast<const uint64_t*>(&input->wd_lo), w2, t0, t1);
Generate2RInstructionFunc(assm);
store_elements_of_vector(assm, w2, a0);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, Code::STUB, Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
auto f = GeneratedCode<F3>::FromCode(*code);
(f.Call(&res, 0, 0, 0, 0));
CHECK_EQ(output->exp_res_lo, res.d[0]);
CHECK_EQ(output->exp_res_hi, res.d[1]);
}
struct TestCaseMsa3RF_F {
float ws_1, ws_2, ws_3, ws_4;
float wt_1, wt_2, wt_3, wt_4;
float wd_1, wd_2, wd_3, wd_4;
};
struct ExpRes_32I {
int32_t exp_res_1;
int32_t exp_res_2;
int32_t exp_res_3;
int32_t exp_res_4;
};
struct TestCaseMsa3RF_D {
double ws_lo, ws_hi;
double wt_lo, wt_hi;
double wd_lo, wd_hi;
};
struct ExpRes_64I {
int64_t exp_res_lo;
int64_t exp_res_hi;
};
TEST(MSA_floating_point_quiet_compare) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float qnan_f = std::numeric_limits<float>::quiet_NaN();
const double qnan_d = std::numeric_limits<double>::quiet_NaN();
const float inf_f = std::numeric_limits<float>::infinity();
const double inf_d = std::numeric_limits<double>::infinity();
const int32_t ones = -1;
const struct TestCaseMsa3RF_F tc_w[]{
{qnan_f, -qnan_f, inf_f, 2.14e9f, // ws
qnan_f, 0.f, qnan_f, -2.14e9f, // wt
0, 0, 0, 0}, // wd
{inf_f, -inf_f, -3.4e38f, 1.5e-45f, -inf_f, -inf_f, -inf_f, inf_f, 0, 0,
0, 0},
{0.f, 19.871e24f, -1.5e-45f, -1.5e-45f, -19.871e24f, 19.871e24f, 1.5e-45f,
-1.5e-45f, 0, 0, 0, 0}};
const struct TestCaseMsa3RF_D tc_d[]{
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{qnan_d, -qnan_d, qnan_f, 0., 0, 0},
{inf_d, 9.22e18, qnan_d, -9.22e18, 0, 0},
{inf_d, inf_d, -inf_d, inf_d, 0, 0},
{-2.3e-308, 5e-324, -inf_d, inf_d, 0, 0},
{0., 24.1e87, -1.6e308, 24.1e87, 0, 0},
{-5e-324, -5e-324, 5e-324, -5e-324, 0, 0}};
const struct ExpectedResult_MSA3RF exp_res_fcaf = {0, 0};
const struct ExpRes_32I exp_res_fcun_w[] = {
{ones, ones, ones, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
const struct ExpRes_64I exp_res_fcun_d[] = {{ones, ones}, {ones, 0}, {0, 0},
{0, 0}, {0, 0}, {0, 0}};
const struct ExpRes_32I exp_res_fceq_w[] = {
{0, 0, 0, 0}, {0, ones, 0, 0}, {0, ones, 0, ones}};
const struct ExpRes_64I exp_res_fceq_d[] = {{0, 0}, {0, 0}, {0, ones},
{0, 0}, {0, ones}, {0, ones}};
const struct ExpRes_32I exp_res_fcueq_w[] = {
{ones, ones, ones, 0}, {0, ones, 0, 0}, {0, ones, 0, ones}};
const struct ExpRes_64I exp_res_fcueq_d[] = {
{ones, ones}, {ones, 0}, {0, ones}, {0, 0}, {0, ones}, {0, ones}};
const struct ExpRes_32I exp_res_fclt_w[] = {
{0, 0, 0, 0}, {0, 0, 0, ones}, {0, 0, ones, 0}};
const struct ExpRes_64I exp_res_fclt_d[] = {{0, 0}, {0, 0}, {0, 0},
{0, ones}, {0, 0}, {ones, 0}};
const struct ExpRes_32I exp_res_fcult_w[] = {
{ones, ones, ones, 0}, {0, 0, 0, ones}, {0, 0, ones, 0}};
const struct ExpRes_64I exp_res_fcult_d[] = {
{ones, ones}, {ones, 0}, {0, 0}, {0, ones}, {0, 0}, {ones, 0}};
const struct ExpRes_32I exp_res_fcle_w[] = {
{0, 0, 0, 0}, {0, ones, 0, ones}, {0, ones, ones, ones}};
const struct ExpRes_64I exp_res_fcle_d[] = {
{0, 0}, {0, 0}, {0, ones}, {0, ones}, {0, ones}, {ones, ones}};
const struct ExpRes_32I exp_res_fcule_w[] = {
{ones, ones, ones, 0}, {0, ones, 0, ones}, {0, ones, ones, ones}};
const struct ExpRes_64I exp_res_fcule_d[] = {
{ones, ones}, {ones, 0}, {0, ones}, {0, ones}, {0, ones}, {ones, ones}};
const struct ExpRes_32I exp_res_fcor_w[] = {
{0, 0, 0, ones}, {ones, ones, ones, ones}, {ones, ones, ones, ones}};
const struct ExpRes_64I exp_res_fcor_d[] = {{0, 0}, {0, ones},
{ones, ones}, {ones, ones},
{ones, ones}, {ones, ones}};
const struct ExpRes_32I exp_res_fcune_w[] = {
{ones, ones, ones, ones}, {ones, 0, ones, ones}, {ones, 0, ones, 0}};
const struct ExpRes_64I exp_res_fcune_d[] = {{ones, ones}, {ones, ones},
{ones, 0}, {ones, ones},
{ones, 0}, {ones, 0}};
const struct ExpRes_32I exp_res_fcne_w[] = {
{0, 0, 0, ones}, {ones, 0, ones, ones}, {ones, 0, ones, 0}};
const struct ExpRes_64I exp_res_fcne_d[] = {
{0, 0}, {0, ones}, {ones, 0}, {ones, ones}, {ones, 0}, {ones, 0}};
#define TEST_FP_QUIET_COMPARE_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FP_QUIET_COMPARE_D(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FP_QUIET_COMPARE_W(fcaf_w, &tc_w[i], &exp_res_fcaf)
TEST_FP_QUIET_COMPARE_W(fcun_w, &tc_w[i], &exp_res_fcun_w[i])
TEST_FP_QUIET_COMPARE_W(fceq_w, &tc_w[i], &exp_res_fceq_w[i])
TEST_FP_QUIET_COMPARE_W(fcueq_w, &tc_w[i], &exp_res_fcueq_w[i])
TEST_FP_QUIET_COMPARE_W(fclt_w, &tc_w[i], &exp_res_fclt_w[i])
TEST_FP_QUIET_COMPARE_W(fcult_w, &tc_w[i], &exp_res_fcult_w[i])
TEST_FP_QUIET_COMPARE_W(fcle_w, &tc_w[i], &exp_res_fcle_w[i])
TEST_FP_QUIET_COMPARE_W(fcule_w, &tc_w[i], &exp_res_fcule_w[i])
TEST_FP_QUIET_COMPARE_W(fcor_w, &tc_w[i], &exp_res_fcor_w[i])
TEST_FP_QUIET_COMPARE_W(fcune_w, &tc_w[i], &exp_res_fcune_w[i])
TEST_FP_QUIET_COMPARE_W(fcne_w, &tc_w[i], &exp_res_fcne_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FP_QUIET_COMPARE_D(fcaf_d, &tc_d[i], &exp_res_fcaf)
TEST_FP_QUIET_COMPARE_D(fcun_d, &tc_d[i], &exp_res_fcun_d[i])
TEST_FP_QUIET_COMPARE_D(fceq_d, &tc_d[i], &exp_res_fceq_d[i])
TEST_FP_QUIET_COMPARE_D(fcueq_d, &tc_d[i], &exp_res_fcueq_d[i])
TEST_FP_QUIET_COMPARE_D(fclt_d, &tc_d[i], &exp_res_fclt_d[i])
TEST_FP_QUIET_COMPARE_D(fcult_d, &tc_d[i], &exp_res_fcult_d[i])
TEST_FP_QUIET_COMPARE_D(fcle_d, &tc_d[i], &exp_res_fcle_d[i])
TEST_FP_QUIET_COMPARE_D(fcule_d, &tc_d[i], &exp_res_fcule_d[i])
TEST_FP_QUIET_COMPARE_D(fcor_d, &tc_d[i], &exp_res_fcor_d[i])
TEST_FP_QUIET_COMPARE_D(fcune_d, &tc_d[i], &exp_res_fcune_d[i])
TEST_FP_QUIET_COMPARE_D(fcne_d, &tc_d[i], &exp_res_fcne_d[i])
}
#undef TEST_FP_QUIET_COMPARE_W
#undef TEST_FP_QUIET_COMPARE_D
}
template <typename T>
inline const T* fadd_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] + src2[i];
}
return dst;
}
template <typename T>
inline const T* fsub_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] - src2[i];
}
return dst;
}
template <typename T>
inline const T* fmul_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] * src2[i];
}
return dst;
}
template <typename T>
inline const T* fdiv_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = src1[i] / src2[i];
}
return dst;
}
template <typename T>
inline const T* fmadd_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = std::fma(src1[i], src2[i], src3[i]);
}
return dst;
}
template <typename T>
inline const T* fmsub_function(const T* src1, const T* src2, const T* src3,
T* dst) {
for (uint64_t i = 0; i < kMSALanesByte / sizeof(T); i++) {
dst[i] = std::fma(src1[i], -src2[i], src3[i]);
}
return dst;
}
TEST(MSA_floating_point_arithmetic) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_f = std::numeric_limits<float>::infinity();
const double inf_d = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
{0.3, -2.14e13f, inf_f, 0.f, // ws
-inf_f, std::sqrt(8.e-26f), -23.e34, -2.14e9f, // wt
-1e30f, 4.6e12f, 0, 2.14e9f}, // wd
{3.4e38f, -1.2e-38f, 1e19f, -1e19f, 3.4e38f, 1.2e-38f, -1e19f, -1e-19f,
3.4e38f, 1.2e-38f * 3, 3.4e38f, -4e19f},
{-3e-31f, 3e10f, 1e25f, 123.f, 1e-14f, 1e-34f, 4e25f, 321.f, 3e-17f,
2e-24f, 2.f, -123456.f}};
const struct TestCaseMsa3RF_D tc_d[] = {
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{0.3, -2.14e103, -inf_d, std::sqrt(8.e-206), -1e30, 4.6e102},
{inf_d, 0., -23.e304, -2.104e9, 0, 2.104e9},
{3.4e307, -1.2e-307, 3.4e307, 1.2e-307, 3.4e307, 1.2e-307 * 3},
{1e154, -1e154, -1e154, -1e-154, 2.9e38, -4e19},
{-3e-301, 3e100, 1e-104, 1e-304, 3e-107, 2e-204},
{1e205, 123., 4e205, 321., 2., -123456.}};
struct ExpectedResult_MSA3RF dst_container;
#define FP_ARITHMETIC_DF_W(instr, function, src1, src2, src3) \
run_msa_3rf( \
reinterpret_cast<const struct TestCaseMsa3RF*>(src1), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(function( \
src1, src2, src3, reinterpret_cast<float*>(&dst_container))), \
[](MacroAssembler& assm) { __ instr(w2, w0, w1); });
#define FP_ARITHMETIC_DF_D(instr, function, src1, src2, src3) \
run_msa_3rf( \
reinterpret_cast<const struct TestCaseMsa3RF*>(src1), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(function( \
src1, src2, src3, reinterpret_cast<double*>(&dst_container))), \
[](MacroAssembler& assm) { __ instr(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
FP_ARITHMETIC_DF_W(fadd_w, fadd_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fsub_w, fsub_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fmul_w, fmul_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fdiv_w, fdiv_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fmadd_w, fmadd_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
FP_ARITHMETIC_DF_W(fmsub_w, fmsub_function, &tc_w[i].ws_1, &tc_w[i].wt_1,
&tc_w[i].wd_1)
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
FP_ARITHMETIC_DF_D(fadd_d, fadd_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fsub_d, fsub_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fmul_d, fmul_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fdiv_d, fdiv_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fmadd_d, fmadd_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
FP_ARITHMETIC_DF_D(fmsub_d, fmsub_function, &tc_d[i].ws_lo, &tc_d[i].wt_lo,
&tc_d[i].wd_lo)
}
#undef FP_ARITHMETIC_DF_W
#undef FP_ARITHMETIC_DF_D
}
struct ExpRes_F {
float exp_res_1;
float exp_res_2;
float exp_res_3;
float exp_res_4;
};
struct ExpRes_D {
double exp_res_1;
double exp_res_2;
};
TEST(MSA_fmin_fmin_a_fmax_fmax_a) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_f = std::numeric_limits<float>::infinity();
const double inf_d = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
{0.3f, -2.14e13f, inf_f, -0.f, // ws
-inf_f, -std::sqrt(8.e26f), -23.e34f, -2.14e9f, // wt
0, 0, 0, 0}, // wd
{3.4e38f, 1.2e-41f, 1e19f, 1e19f, // ws
3.4e38f, -1.1e-41f, -1e-42f, -1e29f, // wt
0, 0, 0, 0}}; // wd
const struct TestCaseMsa3RF_D tc_d[] = {
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{0.3, -2.14e103, -inf_d, -std::sqrt(8e206), 0, 0},
{inf_d, -0., -23e304, -2.14e90, 0, 0},
{3.4e307, 1.2e-320, 3.4e307, -1.1e-320, 0, 0},
{1e154, 1e154, -1e-321, -1e174, 0, 0}};
const struct ExpRes_F exp_res_fmax_w[] = {{0.3f, -2.14e13f, inf_f, -0.f},
{3.4e38f, 1.2e-41f, 1e19f, 1e19f}};
const struct ExpRes_F exp_res_fmax_a_w[] = {
{-inf_f, -std::sqrt(8e26f), inf_f, -2.14e9f},
{3.4e38f, 1.2e-41f, 1e19f, -1e29f}};
const struct ExpRes_F exp_res_fmin_w[] = {
{-inf_f, -std::sqrt(8.e26f), -23e34f, -2.14e9f},
{3.4e38f, -1.1e-41f, -1e-42f, -1e29f}};
const struct ExpRes_F exp_res_fmin_a_w[] = {
{0.3, -2.14e13f, -23.e34f, -0.f}, {3.4e38f, -1.1e-41f, -1e-42f, 1e19f}};
const struct ExpRes_D exp_res_fmax_d[] = {
{0.3, -2.14e103}, {inf_d, -0.}, {3.4e307, 1.2e-320}, {1e154, 1e154}};
const struct ExpRes_D exp_res_fmax_a_d[] = {{-inf_d, -std::sqrt(8e206)},
{inf_d, -2.14e90},
{3.4e307, 1.2e-320},
{1e154, -1e174}};
const struct ExpRes_D exp_res_fmin_d[] = {{-inf_d, -std::sqrt(8e206)},
{-23e304, -2.14e90},
{3.4e307, -1.1e-320},
{-1e-321, -1e174}};
const struct ExpRes_D exp_res_fmin_a_d[] = {
{0.3, -2.14e103}, {-23e304, -0.}, {3.4e307, -1.1e-320}, {-1e-321, 1e154}};
#define TEST_FP_MIN_MAX_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FP_MIN_MAX_D(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FP_MIN_MAX_W(fmax_w, &tc_w[i], &exp_res_fmax_w[i])
TEST_FP_MIN_MAX_W(fmax_a_w, &tc_w[i], &exp_res_fmax_a_w[i])
TEST_FP_MIN_MAX_W(fmin_w, &tc_w[i], &exp_res_fmin_w[i])
TEST_FP_MIN_MAX_W(fmin_a_w, &tc_w[i], &exp_res_fmin_a_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FP_MIN_MAX_D(fmax_d, &tc_d[i], &exp_res_fmax_d[i])
TEST_FP_MIN_MAX_D(fmax_a_d, &tc_d[i], &exp_res_fmax_a_d[i])
TEST_FP_MIN_MAX_D(fmin_d, &tc_d[i], &exp_res_fmin_d[i])
TEST_FP_MIN_MAX_D(fmin_a_d, &tc_d[i], &exp_res_fmin_a_d[i])
}
#undef TEST_FP_MIN_MAX_W
#undef TEST_FP_MIN_MAX_D
}
struct TestCaseMsa3RF_16I {
int16_t ws_1, ws_2, ws_3, ws_4, ws_5, ws_6, ws_7, ws_8;
int16_t wt_1, wt_2, wt_3, wt_4, wt_5, wt_6, wt_7, wt_8;
int16_t wd_1, wd_2, wd_3, wd_4, wd_5, wd_6, wd_7, wd_8;
};
struct ExpRes_16I {
int16_t exp_res_1;
int16_t exp_res_2;
int16_t exp_res_3;
int16_t exp_res_4;
int16_t exp_res_5;
int16_t exp_res_6;
int16_t exp_res_7;
int16_t exp_res_8;
};
struct TestCaseMsa3RF_32I {
int32_t ws_1, ws_2, ws_3, ws_4;
int32_t wt_1, wt_2, wt_3, wt_4;
int32_t wd_1, wd_2, wd_3, wd_4;
};
TEST(MSA_fixed_point_arithmetic) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const struct TestCaseMsa3RF tc_h[]{
{0x800080007FFF7FFF, 0xE1ED8000FAD3863A, 0x80007FFF00AF7FFF,
0x800015A77FFFA0EB, 0x7FFF800080007FFF, 0x80007FFF1F207364},
{0x800080007FFF006A, 0x002AFFC4329AD87B, 0x80007FFF7FFF00F3,
0xFFECFFB4D0D7F429, 0x80007FFF80007C33, 0x54AC6BBCE53B8C91}};
const struct TestCaseMsa3RF tc_w[]{
{0x8000000080000000, 0x7FFFFFFF7FFFFFFF, 0x800000007FFFFFFF,
0x00001FF37FFFFFFF, 0x7FFFFFFF80000000, 0x800000007FFFFFFF},
{0xE1ED035580000000, 0xFAD3863AED462C0B, 0x8000000015A70AEC,
0x7FFFFFFFA0EBD354, 0x800000007FFFFFFF, 0xD0D7F4291F207364},
{0x8000000080000000, 0x7FFFFFFF0000DA1F, 0x800000007FFFFFFF,
0x7FFFFFFF00F39C3B, 0x800000007FFFFFFF, 0x800000007C33F2FD},
{0x0000AC33FFFF329A, 0x54AC6BBCE53BD87B, 0xFFFFE2B4D0D7F429,
0x0355ED462C0B1FF3, 0xB5DEB625939DD3F9, 0xE642ADFA69519596}};
const struct ExpectedResult_MSA3RF exp_res_mul_q_h[] = {
{0x7FFF800100AE7FFE, 0x1E13EA59FAD35A74},
{0x7FFF80017FFE0000, 0xFFFF0000ED5B03A7}};
const struct ExpectedResult_MSA3RF exp_res_madd_q_h[] = {
{0x7FFF800080AE7FFF, 0x9E136A5819F37FFF},
{0x00000000FFFE7C33, 0x54AB6BBCD2969038}};
const struct ExpectedResult_MSA3RF exp_res_msub_q_h[] = {
{0xFFFFFFFF80000000, 0x80007FFF244C18EF},
{0x80007FFF80007C32, 0x54AC6BBBF7DF88E9}};
const struct ExpectedResult_MSA3RF exp_res_mulr_q_h[] = {
{0x7FFF800100AF7FFE, 0x1E13EA59FAD35A75},
{0x7FFF80017FFE0001, 0x00000000ED5B03A8}};
const struct ExpectedResult_MSA3RF exp_res_maddr_q_h[] = {
{0x7FFF800080AF7FFF, 0x9E136A5819F37FFF},
{0x00000000FFFE7C34, 0x54AC6BBCD2969039}};
const struct ExpectedResult_MSA3RF exp_res_msubr_q_h[] = {
{0xFFFFFFFF80000001, 0x80007FFF244D18EF},
{0x80007FFF80007C32, 0x54AC6BBCF7E088E9}};
const struct ExpectedResult_MSA3RF exp_res_mul_q_w[] = {
{0x7FFFFFFF80000001, 0x00001FF27FFFFFFE},
{0x1E12FCABEA58F514, 0xFAD3863A0DE8DEE1},
{0x7FFFFFFF80000001, 0x7FFFFFFE0000019F},
{0xFFFFFFFF00004BAB, 0x0234E1FBF6CA3EE0}};
const struct ExpectedResult_MSA3RF exp_res_madd_q_w[] = {
{0x7FFFFFFF80000000, 0x80001FF27FFFFFFF},
{0x9E12FCAB6A58F513, 0xCBAB7A632D095245},
{0x0000000000000000, 0xFFFFFFFE7C33F49C},
{0xB5DEB624939E1FA4, 0xE8778FF5601BD476}};
const struct ExpectedResult_MSA3RF exp_res_msub_q_w[] = {
{0xFFFFFFFFFFFFFFFF, 0x8000000000000000},
{0x800000007FFFFFFF, 0xD6046DEE11379482},
{0x800000007FFFFFFF, 0x800000007C33F15D},
{0xB5DEB625939D884D, 0xE40DCBFE728756B5}};
const struct ExpectedResult_MSA3RF exp_res_mulr_q_w[] = {
{0x7FFFFFFF80000001, 0x00001FF37FFFFFFE},
{0x1E12FCABEA58F514, 0xFAD3863A0DE8DEE2},
{0x7FFFFFFF80000001, 0x7FFFFFFE0000019F},
{0x0000000000004BAC, 0x0234E1FCF6CA3EE1}};
const struct ExpectedResult_MSA3RF exp_res_maddr_q_w[] = {
{0x7FFFFFFF80000000, 0x80001FF37FFFFFFF},
{0x9E12FCAB6A58F513, 0xCBAB7A632D095246},
{0x0000000000000000, 0xFFFFFFFE7C33F49C},
{0xB5DEB625939E1FA5, 0xE8778FF6601BD477}};
const struct ExpectedResult_MSA3RF exp_res_msubr_q_w[] = {
{0xFFFFFFFFFFFFFFFF, 0x8000000000000001},
{0x800000007FFFFFFF, 0xD6046DEF11379482},
{0x800000007FFFFFFF, 0x800000007C33F15E},
{0xB5DEB625939D884D, 0xE40DCBFE728756B5}};
#define TEST_FIXED_POINT_DF_H(instruction, src, exp_res) \
run_msa_3rf((src), (exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FIXED_POINT_DF_W(instruction, src, exp_res) \
run_msa_3rf((src), (exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_h); i++) {
TEST_FIXED_POINT_DF_H(mul_q_h, &tc_h[i], &exp_res_mul_q_h[i])
TEST_FIXED_POINT_DF_H(madd_q_h, &tc_h[i], &exp_res_madd_q_h[i])
TEST_FIXED_POINT_DF_H(msub_q_h, &tc_h[i], &exp_res_msub_q_h[i])
TEST_FIXED_POINT_DF_H(mulr_q_h, &tc_h[i], &exp_res_mulr_q_h[i])
TEST_FIXED_POINT_DF_H(maddr_q_h, &tc_h[i], &exp_res_maddr_q_h[i])
TEST_FIXED_POINT_DF_H(msubr_q_h, &tc_h[i], &exp_res_msubr_q_h[i])
}
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FIXED_POINT_DF_W(mul_q_w, &tc_w[i], &exp_res_mul_q_w[i])
TEST_FIXED_POINT_DF_W(madd_q_w, &tc_w[i], &exp_res_madd_q_w[i])
TEST_FIXED_POINT_DF_W(msub_q_w, &tc_w[i], &exp_res_msub_q_w[i])
TEST_FIXED_POINT_DF_W(mulr_q_w, &tc_w[i], &exp_res_mulr_q_w[i])
TEST_FIXED_POINT_DF_W(maddr_q_w, &tc_w[i], &exp_res_maddr_q_w[i])
TEST_FIXED_POINT_DF_W(msubr_q_w, &tc_w[i], &exp_res_msubr_q_w[i])
}
#undef TEST_FIXED_POINT_DF_H
#undef TEST_FIXED_POINT_DF_W
}
TEST(MSA_fexdo) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float inf_float = std::numeric_limits<float>::infinity();
const float nan_float = std::numeric_limits<float>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
// ws_1, ws_2, ws_3, ws_4, wt_1, wt_2, wt_3, wt_4, wd_1, wd_2, wd_3, wd_4
{inf_float, nan_float, 66505.f, 65504.f, 6.2e-5f, 5e-5f, -32.42f,
-inf_float, 0, 0, 0, 0},
{-0.f, 0.f, 123.567f, -765.321f, -6e-8f, 5.9e-8f, 1e-7f, -1e-20f, 0, 0, 0,
0},
{1e-36f, 1e20f, -1e20f, 2e-20f, 6e-8f, -2.9e-8f, -66505.f, -65504.f, 0, 0,
0, 0}};
const struct TestCaseMsa3RF_D tc_d[] = {
// ws_lo, ws_hi, wt_lo, wt_hi, wd_lo, wd_hi
{inf_double, -1234., 4e38, 3.4e38, 0, 0},
{1.2e-38, 1.1e-39, -38.92f, -inf_double, 0, 0},
{-0., 0., 123.567e31, -765.321e33, 0, 0},
{-1.5e-45, 1.3e-45, 1e-42, -1e-200, 0, 0},
{1e-202, 1e158, -1e159, 1e14, 0, 0},
{1.5e-42, 1.3e-46, -123.567e31, 765.321e33, 0, 0}};
const struct ExpRes_16I exp_res_fexdo_w[] = {
{static_cast<int16_t>(0x0410), static_cast<int16_t>(0x0347),
static_cast<int16_t>(0xD00D), static_cast<int16_t>(0xFC00),
static_cast<int16_t>(0x7C00), static_cast<int16_t>(0x7DFF),
static_cast<int16_t>(0x7C00), static_cast<int16_t>(0x7BFF)},
{static_cast<int16_t>(0x8001), static_cast<int16_t>(0x0001),
static_cast<int16_t>(0x0002), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0x8000), static_cast<int16_t>(0x0000),
static_cast<int16_t>(0x57B9), static_cast<int16_t>(0xE1FB)},
{static_cast<int16_t>(0x0001), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0xFC00), static_cast<int16_t>(0xFBFF),
static_cast<int16_t>(0x0000), static_cast<int16_t>(0x7C00),
static_cast<int16_t>(0xFC00), static_cast<int16_t>(0x0000)}};
const struct ExpRes_32I exp_res_fexdo_d[] = {
{bit_cast<int32_t>(0x7F800000), bit_cast<int32_t>(0x7F7FC99E),
bit_cast<int32_t>(0x7F800000), bit_cast<int32_t>(0xC49A4000)},
{bit_cast<int32_t>(0xC21BAE14), bit_cast<int32_t>(0xFF800000),
bit_cast<int32_t>(0x0082AB1E), bit_cast<int32_t>(0x000BFA5A)},
{bit_cast<int32_t>(0x7673B164), bit_cast<int32_t>(0xFB13653D),
bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x00000000)},
{bit_cast<int32_t>(0x000002CA), bit_cast<int32_t>(0x80000000),
bit_cast<int32_t>(0x80000001), bit_cast<int32_t>(0x00000001)},
{bit_cast<int32_t>(0xFF800000), bit_cast<int32_t>(0x56B5E621),
bit_cast<int32_t>(0x00000000), bit_cast<int32_t>(0x7F800000)},
{bit_cast<int32_t>(0xF673B164), bit_cast<int32_t>(0x7B13653D),
bit_cast<int32_t>(0x0000042E), bit_cast<int32_t>(0x00000000)}};
#define TEST_FEXDO_H(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FEXDO_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FEXDO_H(fexdo_h, &tc_w[i], &exp_res_fexdo_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FEXDO_W(fexdo_w, &tc_d[i], &exp_res_fexdo_d[i])
}
#undef TEST_FEXDO_H
#undef TEST_FEXDO_W
}
TEST(MSA_ftq) {
if (!IsMipsArchVariant(kMips32r6) || !CpuFeatures::IsSupported(MIPS_SIMD))
return;
CcTest::InitializeVM();
const float nan_float = std::numeric_limits<float>::quiet_NaN();
const float inf_float = std::numeric_limits<float>::infinity();
const double nan_double = std::numeric_limits<double>::quiet_NaN();
const double inf_double = std::numeric_limits<double>::infinity();
const struct TestCaseMsa3RF_F tc_w[] = {
{1.f, -0.999f, 1.5f, -31e-6, 1e-7, -0.598, 0.0023, -0.f, 0, 0, 0, 0},
{100.f, -102.f, -1.1f, 1.3f, 0.f, -1.f, 0.9999f, -0.000322, 0, 0, 0, 0},
{nan_float, inf_float, -inf_float, -nan_float, -1e-40, 3e-44, 8.3e36,
-0.00003, 0, 0, 0, 0}};
const struct TestCaseMsa3RF_D tc_d[] = {
{1., -0.999, 1.5, -31e-6, 0, 0},
{1e-7, -0.598, 0.0023, -0.f, 0, 0},
{100.f, -102.f, -1.1f, 1.3f, 0, 0},
{0.f, -1.f, 0.9999f, -0.000322, 0, 0},
{nan_double, inf_double, -inf_double, -nan_double, 0, 0},
{-3e306, 2e-307, 9e307, 2e-307, 0, 0}};
const struct ExpRes_16I exp_res_ftq_w[] = {
{static_cast<int16_t>(0x0000), static_cast<int16_t>(0xB375),
static_cast<int16_t>(0x004B), static_cast<int16_t>(0x0000),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0x8021),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0xFFFF)},
{static_cast<int16_t>(0x0000), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0x7FFD), static_cast<int16_t>(0xFFF5),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0x8000),
static_cast<int16_t>(0x8000), static_cast<int16_t>(0x7FFF)},
{static_cast<int16_t>(0x0000), static_cast<int16_t>(0x0000),
static_cast<int16_t>(0x7FFF), static_cast<int16_t>(0xFFFF),
static_cast<int16_t>(0x0000), static_cast<int16_t>(0x7FFF),
static_cast<int16_t>(0x8000), static_cast<int16_t>(0x0000)}};
const struct ExpRes_32I exp_res_ftq_d[] = {
{bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0xFFFEFBF4),
bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0x8020C49C)},
{bit_cast<int32_t>(0x004B5DCC), bit_cast<int32_t>(0x00000000),
bit_cast<int32_t>(0x000000D7), bit_cast<int32_t>(0xB374BC6A)},
{bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x7FFFFFFF),
bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0x80000000)},
{bit_cast<int32_t>(0x7FFCB900), bit_cast<int32_t>(0xFFF572DE),
bit_cast<int32_t>(0x00000000), bit_cast<int32_t>(0x80000000)},
{bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x00000000),
bit_cast<int32_t>(0x00000000), bit_cast<int32_t>(0x7FFFFFFF)},
{bit_cast<int32_t>(0x7FFFFFFF), bit_cast<int32_t>(0x00000000),
bit_cast<int32_t>(0x80000000), bit_cast<int32_t>(0x00000000)}};
#define TEST_FTQ_H(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
#define TEST_FTQ_W(instruction, src, exp_res) \
run_msa_3rf(reinterpret_cast<const struct TestCaseMsa3RF*>(src), \
reinterpret_cast<const struct ExpectedResult_MSA3RF*>(exp_res), \
[](MacroAssembler& assm) { __ instruction(w2, w0, w1); });
for (uint64_t i = 0; i < arraysize(tc_w); i++) {
TEST_FTQ_H(ftq_h, &tc_w[i], &exp_res_ftq_w[i])
}
for (uint64_t i = 0; i < arraysize(tc_d); i++) {
TEST_FTQ_W(ftq_w, &tc_d[i], &exp_res_ftq_d[i])
}
#undef TEST_FTQ_H
#undef TEST_FTQ_W
}
#undef __
} // namespace internal
} // namespace v8
| 36.017975 | 80 | 0.562576 | cclauss |
b49ee02b8dfc79ea768391b51d38ec4b44863f61 | 2,412 | cc | C++ | leetcode/ds_list_missing_number.cc | prashrock/C- | 3ed46815d40b3e42cd9f36d23c8ee2a9de742323 | [
"MIT"
] | 1 | 2016-12-05T10:42:46.000Z | 2016-12-05T10:42:46.000Z | leetcode/ds_list_missing_number.cc | prashrock/CPP | 3ed46815d40b3e42cd9f36d23c8ee2a9de742323 | [
"MIT"
] | null | null | null | leetcode/ds_list_missing_number.cc | prashrock/CPP | 3ed46815d40b3e42cd9f36d23c8ee2a9de742323 | [
"MIT"
] | null | null | null | //g++-5 --std=c++11 -Wall -g -o ds_list_missing_number ds_list_missing_number.cc
/**
* @file Find Missing Number from Array
* @brief Given array containing n distinct integers [0, n) find missing integer
*/
// https://leetcode.com/problems/missing-number/
#include <iostream> /* std::cout */
#include <iomanip> /* std::setw */
#include <cmath> /* pow */
#include <cassert> /* assert */
#include <algorithm> /* std::max */
#include <vector> /* std::vector */
#include <string> /* std::string, */
#include <cstring> /* std::strtok */
#include <unordered_map> /* std::unordered_map container */
using namespace std;
/**
* Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find
* the one that is missing from the array.
* For example,
* Given nums = [0, 1, 3] return 2.
* Note:
* Your algorithm should run in linear runtime complexity. Could you implement it
* using only constant extra space complexity?
*/
/* Since numbers are in a specific sequence [0, n), use AP *
* to deduce what should be the total of all numbers. Next *
* subtract this from observed total to find missing elem */
int missingNumber(vector<int>& nums) {
/* sum of n numbers (1, 2, 3, ... n) = n(n+1)/2. *
* Handle 0 as a spl case */
int n = nums.size();
unsigned long obs_sum = 0, calc_sum = n * (n + 1) / 2;
for(int i = 0; i < (int)nums.size(); ++i) obs_sum += nums[i];
return calc_sum - obs_sum;
}
int main()
{
int ans, exp;
vector<int> nums;
nums = {0}; exp = 1;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
nums = {1}; exp = 0;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
nums = {5, 4, 6, 3, 1, 2}; exp = 0;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
nums = {5, 0, 6, 3, 1, 2}; exp = 4;
ans = missingNumber(nums);
if(ans != exp) goto Errmain;
cout << "All test-cases passed." << endl;
return 0;
Errmain:
cout << "Error: Missing Integer failed for - ";
for(auto val: nums) cout << val << ", "; cout << endl;
cout << "Expected = " << exp << " Got = " << ans << endl;
return -1;
}
| 33.5 | 81 | 0.538972 | prashrock |
b49f395cef0e4b108b73c6ae583ef37eff3d02eb | 4,137 | cpp | C++ | Vendor/Include/bullet/BulletCollision/Gimpact/btContactProcessing.cpp | allogic/Redshift | 4606267b53e3d094ba588acb9ceaa97e3289632b | [
"MIT"
] | null | null | null | Vendor/Include/bullet/BulletCollision/Gimpact/btContactProcessing.cpp | allogic/Redshift | 4606267b53e3d094ba588acb9ceaa97e3289632b | [
"MIT"
] | null | null | null | Vendor/Include/bullet/BulletCollision/Gimpact/btContactProcessing.cpp | allogic/Redshift | 4606267b53e3d094ba588acb9ceaa97e3289632b | [
"MIT"
] | null | null | null |
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include <bullet/BulletCollision/Gimpact/btContactProcessing.h>
#define MAX_COINCIDENT 8
struct CONTACT_KEY_TOKEN
{
unsigned int m_key;
int m_value;
CONTACT_KEY_TOKEN()
{
}
CONTACT_KEY_TOKEN(unsigned int key, int token)
{
m_key = key;
m_value = token;
}
CONTACT_KEY_TOKEN(const CONTACT_KEY_TOKEN& rtoken)
{
m_key = rtoken.m_key;
m_value = rtoken.m_value;
}
inline bool operator<(const CONTACT_KEY_TOKEN& other) const
{
return (m_key < other.m_key);
}
inline bool operator>(const CONTACT_KEY_TOKEN& other) const
{
return (m_key > other.m_key);
}
};
class CONTACT_KEY_TOKEN_COMP
{
public:
bool operator()(const CONTACT_KEY_TOKEN& a, const CONTACT_KEY_TOKEN& b) const
{
return (a < b);
}
};
void btContactArray::merge_contacts(
const btContactArray& contacts, bool normal_contact_average)
{
clear();
int i;
if (contacts.size() == 0) return;
if (contacts.size() == 1)
{
push_back(contacts[0]);
return;
}
btAlignedObjectArray<CONTACT_KEY_TOKEN> keycontacts;
keycontacts.reserve(contacts.size());
//fill key contacts
for (i = 0; i < contacts.size(); i++)
{
keycontacts.push_back(CONTACT_KEY_TOKEN(contacts[i].calc_key_contact(), i));
}
//sort keys
keycontacts.quickSort(CONTACT_KEY_TOKEN_COMP());
// Merge contacts
int coincident_count = 0;
btVector3 coincident_normals[MAX_COINCIDENT];
unsigned int last_key = keycontacts[0].m_key;
unsigned int key = 0;
push_back(contacts[keycontacts[0].m_value]);
GIM_CONTACT* pcontact = &(*this)[0];
for (i = 1; i < keycontacts.size(); i++)
{
key = keycontacts[i].m_key;
const GIM_CONTACT* scontact = &contacts[keycontacts[i].m_value];
if (last_key == key) //same points
{
//merge contact
if (pcontact->m_depth - CONTACT_DIFF_EPSILON > scontact->m_depth) //)
{
*pcontact = *scontact;
coincident_count = 0;
}
else if (normal_contact_average)
{
if (btFabs(pcontact->m_depth - scontact->m_depth) < CONTACT_DIFF_EPSILON)
{
if (coincident_count < MAX_COINCIDENT)
{
coincident_normals[coincident_count] = scontact->m_normal;
coincident_count++;
}
}
}
}
else
{ //add new contact
if (normal_contact_average && coincident_count > 0)
{
pcontact->interpolate_normals(coincident_normals, coincident_count);
coincident_count = 0;
}
push_back(*scontact);
pcontact = &(*this)[this->size() - 1];
}
last_key = key;
}
}
void btContactArray::merge_contacts_unique(const btContactArray& contacts)
{
clear();
if (contacts.size() == 0) return;
if (contacts.size() == 1)
{
push_back(contacts[0]);
return;
}
GIM_CONTACT average_contact = contacts[0];
for (int i = 1; i < contacts.size(); i++)
{
average_contact.m_point += contacts[i].m_point;
average_contact.m_normal += contacts[i].m_normal * contacts[i].m_depth;
}
//divide
btScalar divide_average = 1.0f / ((btScalar)contacts.size());
average_contact.m_point *= divide_average;
average_contact.m_normal *= divide_average;
average_contact.m_depth = average_contact.m_normal.length();
average_contact.m_normal /= average_contact.m_depth;
}
| 23.505682 | 243 | 0.719604 | allogic |
b49f6ce41d181e942f2e4dab67fbb039f4a6d4dd | 6,047 | cpp | C++ | Source/Falcor/Core/API/D3D12/D3D12Resource.cpp | jeongsoopark/Falcor | 48aa4e28d6812ced004b56c83484de03b19526fa | [
"BSD-3-Clause"
] | 2 | 2019-11-04T03:46:56.000Z | 2019-11-05T03:25:31.000Z | Source/Falcor/Core/API/D3D12/D3D12Resource.cpp | wowhyuck/Falcor | 48aa4e28d6812ced004b56c83484de03b19526fa | [
"BSD-3-Clause"
] | 8 | 2019-10-30T10:32:19.000Z | 2019-11-21T14:55:25.000Z | Source/Falcor/Core/API/D3D12/D3D12Resource.cpp | wowhyuck/Falcor | 48aa4e28d6812ced004b56c83484de03b19526fa | [
"BSD-3-Clause"
] | 2 | 2019-10-31T06:34:55.000Z | 2019-11-27T16:54:42.000Z | /***************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#include "stdafx.h"
#include "D3D12Resource.h"
#include "Utils/StringUtils.h"
namespace Falcor
{
const D3D12_HEAP_PROPERTIES kDefaultHeapProps =
{
D3D12_HEAP_TYPE_DEFAULT,
D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
D3D12_MEMORY_POOL_UNKNOWN,
0,
0
};
const D3D12_HEAP_PROPERTIES kUploadHeapProps =
{
D3D12_HEAP_TYPE_UPLOAD,
D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
D3D12_MEMORY_POOL_UNKNOWN,
0,
0,
};
const D3D12_HEAP_PROPERTIES kReadbackHeapProps =
{
D3D12_HEAP_TYPE_READBACK,
D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
D3D12_MEMORY_POOL_UNKNOWN,
0,
0
};
D3D12_RESOURCE_FLAGS getD3D12ResourceFlags(Resource::BindFlags flags)
{
D3D12_RESOURCE_FLAGS d3d = D3D12_RESOURCE_FLAG_NONE;
bool uavRequired = is_set(flags, Resource::BindFlags::UnorderedAccess) || is_set(flags, Resource::BindFlags::AccelerationStructure);
if (uavRequired)
{
d3d |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
}
if (is_set(flags, Resource::BindFlags::DepthStencil))
{
if (is_set(flags, Resource::BindFlags::ShaderResource) == false)
{
d3d |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
}
d3d |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
}
if (is_set(flags, Resource::BindFlags::RenderTarget))
{
d3d |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
}
return d3d;
}
D3D12_RESOURCE_STATES getD3D12ResourceState(Resource::State s)
{
switch (s)
{
case Resource::State::Undefined:
case Resource::State::Common:
return D3D12_RESOURCE_STATE_COMMON;
case Resource::State::ConstantBuffer:
case Resource::State::VertexBuffer:
return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
case Resource::State::CopyDest:
return D3D12_RESOURCE_STATE_COPY_DEST;
case Resource::State::CopySource:
return D3D12_RESOURCE_STATE_COPY_SOURCE;
case Resource::State::DepthStencil:
return D3D12_RESOURCE_STATE_DEPTH_WRITE; // If depth-writes are disabled, return D3D12_RESOURCE_STATE_DEPTH_WRITE
case Resource::State::IndexBuffer:
return D3D12_RESOURCE_STATE_INDEX_BUFFER;
case Resource::State::IndirectArg:
return D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
case Resource::State::Predication:
return D3D12_RESOURCE_STATE_PREDICATION;
case Resource::State::Present:
return D3D12_RESOURCE_STATE_PRESENT;
case Resource::State::RenderTarget:
return D3D12_RESOURCE_STATE_RENDER_TARGET;
case Resource::State::ResolveDest:
return D3D12_RESOURCE_STATE_RESOLVE_DEST;
case Resource::State::ResolveSource:
return D3D12_RESOURCE_STATE_RESOLVE_SOURCE;
case Resource::State::ShaderResource:
return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; // Need the shader usage mask in case the SRV is used by non-PS
case Resource::State::StreamOut:
return D3D12_RESOURCE_STATE_STREAM_OUT;
case Resource::State::UnorderedAccess:
return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
case Resource::State::GenericRead:
return D3D12_RESOURCE_STATE_GENERIC_READ;
case Resource::State::NonPixelShader:
return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
case Resource::State::AccelerationStructure:
return D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE;
default:
should_not_get_here();
return D3D12_RESOURCE_STATE_GENERIC_READ;
}
}
void Resource::apiSetName()
{
std::wstring ws = string_2_wstring(mName);
mApiHandle->SetName(ws.c_str());
}
SharedResourceApiHandle Resource::createSharedApiHandle()
{
ID3D12DevicePtr pDevicePtr = gpDevice->getApiHandle();
auto s = string_2_wstring(mName);
SharedResourceApiHandle pHandle;
HRESULT res = pDevicePtr->CreateSharedHandle(mApiHandle, 0, GENERIC_ALL, s.c_str(), &pHandle);
if (res == S_OK) return pHandle;
else return nullptr;
}
}
| 39.012903 | 140 | 0.676699 | jeongsoopark |
b49fb7d26b8c0162262044733b2279cbcbf30db6 | 823 | cpp | C++ | construct-binary-tree-from-preorder-and-inorder/main.cpp | rickytan/LeetCode | 7df9a47928552babaf5d2abf1d153bd92d44be09 | [
"MIT"
] | 1 | 2015-04-04T18:32:31.000Z | 2015-04-04T18:32:31.000Z | construct-binary-tree-from-preorder-and-inorder/main.cpp | rickytan/LeetCode | 7df9a47928552babaf5d2abf1d153bd92d44be09 | [
"MIT"
] | null | null | null | construct-binary-tree-from-preorder-and-inorder/main.cpp | rickytan/LeetCode | 7df9a47928552babaf5d2abf1d153bd92d44be09 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
if (inorder.empty())
return NULL;
int value = preorder[0];
preorder.erase(preorder.begin());
TreeNode *root = new TreeNode(value);
vector<int>::iterator index = std::find(inorder.begin(), inorder.end(), value);
vector<int> left(inorder.begin(), index);
root->left = buildTree(preorder, left);
vector<int> right(index + 1, inorder.end());
root->right = buildTree(preorder, right);
return root;
}
};
int main()
{
}
| 22.861111 | 87 | 0.602673 | rickytan |
b49ff458628b0c5c3cdfe7da2ac9780d026ce4b4 | 12,220 | cpp | C++ | kvbc/src/ReplicaImp.cpp | sync-bft/concord-clone | fcc5a454ca16446f04351676f330df2382699929 | [
"Apache-2.0"
] | null | null | null | kvbc/src/ReplicaImp.cpp | sync-bft/concord-clone | fcc5a454ca16446f04351676f330df2382699929 | [
"Apache-2.0"
] | null | null | null | kvbc/src/ReplicaImp.cpp | sync-bft/concord-clone | fcc5a454ca16446f04351676f330df2382699929 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018-2020 VMware, all rights reserved
//
// KV Blockchain replica implementation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <unistd.h>
#include "ReplicaImp.h"
#include <inttypes.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <exception>
#include <utility>
#include "assertUtils.hpp"
#include "communication/CommDefs.hpp"
#include "kv_types.hpp"
#include "hex_tools.h"
#include "replica_state_sync.h"
#include "sliver.hpp"
#include "bftengine/DbMetadataStorage.hpp"
using bft::communication::ICommunication;
using bftEngine::bcst::StateTransferDigest;
using namespace concord::diagnostics;
using concord::storage::DBMetadataStorage;
namespace concord::kvbc {
/**
* Opens the database and creates the replica thread. Replica state moves to
* Starting.
*/
Status ReplicaImp::start() {
LOG_INFO(logger, "ReplicaImp::Start() id = " << m_replicaConfig.replicaId);
if (m_currentRepStatus != RepStatus::Idle) {
return Status::IllegalOperation("todo");
}
m_currentRepStatus = RepStatus::Starting;
if (m_replicaConfig.isReadOnly) {
LOG_INFO(logger, "ReadOnly mode");
m_replicaPtr =
bftEngine::IReplica::createNewRoReplica(m_replicaConfig, m_stateTransfer, m_ptrComm, m_metadataStorage);
} else {
createReplicaAndSyncState();
}
m_replicaPtr->setControlStateManager(controlStateManager_);
m_replicaPtr->SetAggregator(aggregator_);
m_replicaPtr->start();
m_currentRepStatus = RepStatus::Running;
/// TODO(IG, GG)
/// add return value to start/stop
return Status::OK();
}
void ReplicaImp::createReplicaAndSyncState() {
bool isNewStorage = m_metadataStorage->isNewStorage();
bool erasedMetaData;
m_replicaPtr = bftEngine::IReplica::createNewReplica(
m_replicaConfig, m_cmdHandler, m_stateTransfer, m_ptrComm, m_metadataStorage, erasedMetaData);
if (erasedMetaData) isNewStorage = true;
LOG_INFO(logger, "createReplicaAndSyncState: isNewStorage= " << isNewStorage);
if (!isNewStorage && !m_stateTransfer->isCollectingState()) {
uint64_t removedBlocksNum = replicaStateSync_->execute(
logger, *m_bcDbAdapter, getLastReachableBlockNum(), m_replicaPtr->getLastExecutedSequenceNum());
LOG_INFO(logger,
"createReplicaAndSyncState: removedBlocksNum = "
<< removedBlocksNum << ", new m_lastBlock = " << getLastBlockNum()
<< ", new m_lastReachableBlock = " << getLastReachableBlockNum());
}
}
/**
* Closes the database. Call `wait()` after this to wait for thread to stop.
*/
Status ReplicaImp::stop() {
m_currentRepStatus = RepStatus::Stopping;
m_replicaPtr->stop();
m_currentRepStatus = RepStatus::Idle;
return Status::OK();
}
ReplicaImp::RepStatus ReplicaImp::getReplicaStatus() const { return m_currentRepStatus; }
const ILocalKeyValueStorageReadOnly &ReplicaImp::getReadOnlyStorage() { return *this; }
Status ReplicaImp::addBlockToIdleReplica(const SetOfKeyValuePairs &updates) {
if (getReplicaStatus() != IReplica::RepStatus::Idle) {
return Status::IllegalOperation("");
}
BlockId d;
return addBlockInternal(updates, d);
}
Status ReplicaImp::get(const Sliver &key, Sliver &outValue) const {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
TimeRecorder scoped_timer(*histograms_.get_value);
BlockId dummy;
return getInternal(getLastBlockNum(), key, outValue, dummy);
}
Status ReplicaImp::get(BlockId readVersion, const Sliver &key, Sliver &outValue, BlockId &outBlock) const {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
TimeRecorder scoped_timer(*histograms_.get_block);
return getInternal(readVersion, key, outValue, outBlock);
}
Status ReplicaImp::getBlockData(BlockId blockId, SetOfKeyValuePairs &outBlockData) const {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
try {
TimeRecorder scoped_timer(*histograms_.get_block_data);
Sliver block = getBlockInternal(blockId);
outBlockData = m_bcDbAdapter->getBlockData(block);
} catch (const NotFoundException &e) {
LOG_ERROR(logger, e.what());
return Status::NotFound("todo");
}
return Status::OK();
}
Status ReplicaImp::mayHaveConflictBetween(const Sliver &key, BlockId fromBlock, BlockId toBlock, bool &outRes) const {
// TODO(GG): add assert or print warning if fromBlock==0 (all keys have a
// conflict in block 0)
TimeRecorder scoped_timer(*histograms_.may_have_conflict_between);
// we conservatively assume that we have a conflict
outRes = true;
Sliver dummy;
BlockId block = 0;
Status s = getInternal(toBlock, key, dummy, block);
if (s.isOK() && block < fromBlock) {
outRes = false;
}
return s;
}
Status ReplicaImp::addBlock(const SetOfKeyValuePairs &updates,
BlockId &outBlockId,
const concordUtils::SpanWrapper & /*parent_span*/) {
// TODO(GG): check legality of operation (the method should be invoked from
// the replica's internal thread)
// TODO(GG): what do we want to do with several identical keys in the same
// block?
TimeRecorder scoped_timer(*histograms_.add_block);
return addBlockInternal(updates, outBlockId);
}
void ReplicaImp::deleteGenesisBlock() {
const auto genesisBlock = m_bcDbAdapter->getGenesisBlockId();
if (genesisBlock == 0) {
throw std::logic_error{"Cannot delete the genesis block from an empty blockchain"};
}
m_bcDbAdapter->deleteBlock(genesisBlock);
}
BlockId ReplicaImp::deleteBlocksUntil(BlockId until) {
const auto genesisBlock = m_bcDbAdapter->getGenesisBlockId();
if (genesisBlock == 0) {
throw std::logic_error{"Cannot delete a block range from an empty blockchain"};
} else if (until <= genesisBlock) {
throw std::invalid_argument{"Invalid 'until' value passed to deleteBlocksUntil()"};
}
const auto lastBlock = getLastBlock();
const auto lastDeletedBlock = std::min(lastBlock, until - 1);
for (auto i = genesisBlock; i <= lastDeletedBlock; ++i) {
m_bcDbAdapter->deleteBlock(i);
}
return lastDeletedBlock;
}
void ReplicaImp::set_command_handler(ICommandsHandler *handler) {
m_cmdHandler = handler;
m_cmdHandler->setControlStateManager(controlStateManager_);
}
ReplicaImp::ReplicaImp(ICommunication *comm,
const bftEngine::ReplicaConfig &replicaConfig,
std::unique_ptr<IStorageFactory> storageFactory,
std::shared_ptr<concordMetrics::Aggregator> aggregator)
: logger(logging::getLogger("skvbc.replicaImp")),
m_currentRepStatus(RepStatus::Idle),
m_ptrComm(comm),
m_replicaConfig(replicaConfig),
aggregator_(aggregator) {
bftEngine::bcst::Config state_transfer_config;
state_transfer_config.myReplicaId = m_replicaConfig.replicaId;
state_transfer_config.cVal = m_replicaConfig.cVal;
state_transfer_config.fVal = m_replicaConfig.fVal;
state_transfer_config.numReplicas = m_replicaConfig.numReplicas + m_replicaConfig.numRoReplicas;
state_transfer_config.metricsDumpIntervalSeconds = std::chrono::seconds(m_replicaConfig.metricsDumpIntervalSeconds);
state_transfer_config.isReadOnly = replicaConfig.isReadOnly;
if (replicaConfig.maxNumOfReservedPages > 0)
state_transfer_config.maxNumOfReservedPages = replicaConfig.maxNumOfReservedPages;
if (replicaConfig.sizeOfReservedPage > 0) state_transfer_config.sizeOfReservedPage = replicaConfig.sizeOfReservedPage;
state_transfer_config.sourceReplicaReplacementTimeoutMilli =
replicaConfig.get("sourceReplicaReplacementTimeoutMilli", 5000);
auto dbSet = storageFactory->newDatabaseSet();
m_bcDbAdapter = std::move(dbSet.dbAdapter);
dbSet.dataDBClient->setAggregator(aggregator);
dbSet.metadataDBClient->setAggregator(aggregator);
m_metadataDBClient = dbSet.metadataDBClient;
auto stKeyManipulator = std::shared_ptr<storage::ISTKeyManipulator>{storageFactory->newSTKeyManipulator()};
m_stateTransfer =
bftEngine::bcst::create(state_transfer_config, this, m_metadataDBClient, stKeyManipulator, aggregator_);
m_metadataStorage = new DBMetadataStorage(m_metadataDBClient.get(), storageFactory->newMetadataKeyManipulator());
controlStateManager_ =
std::make_shared<bftEngine::ControlStateManager>(m_stateTransfer, m_replicaConfig.sizeOfReservedPage);
}
ReplicaImp::~ReplicaImp() {
if (m_replicaPtr) {
if (m_replicaPtr->isRunning()) {
m_replicaPtr->stop();
}
}
}
Status ReplicaImp::addBlockInternal(const SetOfKeyValuePairs &updates, BlockId &outBlockId) {
outBlockId = m_bcDbAdapter->addBlock(updates);
return Status::OK();
}
Status ReplicaImp::getInternal(BlockId readVersion, const Key &key, Sliver &outValue, BlockId &outBlock) const {
const auto clear = [&outValue, &outBlock]() {
outValue = Sliver{};
outBlock = 0;
};
try {
std::tie(outValue, outBlock) = m_bcDbAdapter->getValue(key, readVersion);
} catch (const NotFoundException &) {
clear();
} catch (const std::exception &e) {
clear();
return Status::GeneralError(std::string{"getInternal() failed to get value due to a DBAdapter error: "} + e.what());
} catch (...) {
clear();
return Status::GeneralError("getInternal() failed to get value due to an unknown DBAdapter error");
}
return Status::OK();
}
/*
* This method can't return false by current insertBlockInternal impl.
* It is used only by State Transfer to synchronize state between replicas.
*/
bool ReplicaImp::putBlock(const uint64_t blockId, const char *block_data, const uint32_t blockSize) {
Sliver block = Sliver::copy(block_data, blockSize);
if (m_bcDbAdapter->hasBlock(blockId)) {
// if we already have a block with the same ID
RawBlock existingBlock = m_bcDbAdapter->getRawBlock(blockId);
if (existingBlock.length() != block.length() || memcmp(existingBlock.data(), block.data(), block.length()) != 0) {
// the replica is corrupted !
LOG_ERROR(logger,
"found block " << blockId << ", size in db is " << existingBlock.length() << ", inserted is "
<< block.length() << ", data in db " << existingBlock << ", data inserted " << block);
LOG_ERROR(logger,
"Block size test " << (existingBlock.length() != block.length()) << ", block data test "
<< (memcmp(existingBlock.data(), block.data(), block.length())));
m_bcDbAdapter->deleteBlock(blockId);
throw std::runtime_error(__PRETTY_FUNCTION__ + std::string("data corrupted blockId: ") + std::to_string(blockId));
}
} else {
m_bcDbAdapter->addRawBlock(block, blockId);
}
return true;
}
RawBlock ReplicaImp::getBlockInternal(BlockId blockId) const { return m_bcDbAdapter->getRawBlock(blockId); }
/*
* This method assumes that *outBlock is big enough to hold block content
* The caller is the owner of the memory
*/
bool ReplicaImp::getBlock(uint64_t blockId, char *outBlock, uint32_t *outBlockSize) {
try {
RawBlock block = getBlockInternal(blockId);
*outBlockSize = block.length();
memcpy(outBlock, block.data(), block.length());
return true;
} catch (const NotFoundException &e) {
LOG_FATAL(logger, e.what());
throw;
}
}
bool ReplicaImp::hasBlock(BlockId blockId) const { return m_bcDbAdapter->hasBlock(blockId); }
bool ReplicaImp::getPrevDigestFromBlock(BlockId blockId, StateTransferDigest *outPrevBlockDigest) {
ConcordAssert(blockId > 0);
try {
RawBlock result = getBlockInternal(blockId);
auto parentDigest = m_bcDbAdapter->getParentDigest(result);
ConcordAssert(outPrevBlockDigest != nullptr);
static_assert(parentDigest.size() == BLOCK_DIGEST_SIZE);
static_assert(sizeof(StateTransferDigest) == BLOCK_DIGEST_SIZE);
memcpy(outPrevBlockDigest, parentDigest.data(), BLOCK_DIGEST_SIZE);
return true;
} catch (const NotFoundException &e) {
LOG_FATAL(logger, "Block not found for parent digest, ID: " << blockId << " " << e.what());
throw;
}
}
} // namespace concord::kvbc
| 36.477612 | 120 | 0.723404 | sync-bft |
b4a07feb3a01881c7c13ffc77852481b1c248c06 | 1,139 | hh | C++ | include/ftk/utils/scatter.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 19 | 2018-11-01T02:15:17.000Z | 2022-03-28T16:55:00.000Z | include/ftk/utils/scatter.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 12 | 2019-04-14T12:49:41.000Z | 2021-10-20T03:59:21.000Z | include/ftk/utils/scatter.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 9 | 2019-02-08T19:40:46.000Z | 2021-06-15T00:31:09.000Z | #ifndef _DIYEXT_SCATTER_HH
#define _DIYEXT_SCATTER_HH
#include <ftk/external/diy/mpi.hpp>
#include <ftk/utils/serialization.hh>
#include <numeric>
namespace diy { namespace mpi {
template <typename Obj>
inline void scatterv(const communicator& comm,
const std::vector<Obj> &ins,
Obj &out,
int root = 0)
{
#if FTK_HAVE_MPI
assert(ins.size() == comm.size());
const int np = comm.size(), rank = comm.rank();
// prepare sendbuf
std::string sendbuf;
StringBuffer sb(sendbuf);
std::vector<int> sendcounts(np), displs(np);
for (int i = 0; i < ins.size(); i ++) {
displs[i] = sendbuf.size();
save(sb, ins[i]);
sendcounts[i] = sendbuf.size() - displs[i];
}
// bcast counts and displs
broadcast(comm, sendcounts, root);
broadcast(comm, displs, root);
// prepare recvbuf
std::string recvbuf;
recvbuf.resize( sendcounts[rank] );
// call MPI_Scatterv
MPI_Scatterv(&sendbuf[0], &sendcounts[0], &displs[0], MPI_CHAR,
&recvbuf[0], recvbuf.size(), MPI_CHAR,
root, comm);
// unseralize
StringBuffer bb(recvbuf);
load(bb, out);
#else
out = ins[0];
#endif
}
}}
#endif
| 20.339286 | 65 | 0.651449 | hguo |
b4a240be38ac640a2e444854cc45f56d12abeecb | 13,324 | hxx | C++ | main/starmath/source/mathmlimport.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/starmath/source/mathmlimport.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/starmath/source/mathmlimport.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
#ifndef _MATHMLIMPORT_HXX_
#define _MATHMLIMPORT_HXX_
#include <xmloff/xmlimp.hxx>
#include <xmloff/xmlexp.hxx>
#include <xmloff/DocumentSettingsContext.hxx>
#include <xmloff/xmltoken.hxx>
#include <node.hxx>
class SfxMedium;
namespace com { namespace sun { namespace star {
namespace io {
class XInputStream;
class XOutputStream; }
namespace beans {
class XPropertySet; }
} } }
////////////////////////////////////////////////////////////
class SmXMLImportWrapper
{
com::sun::star::uno::Reference<com::sun::star::frame::XModel> xModel;
public:
SmXMLImportWrapper(com::sun::star::uno::Reference<com::sun::star::frame::XModel> &rRef)
: xModel(rRef) {}
sal_uLong Import(SfxMedium &rMedium);
sal_uLong ReadThroughComponent(
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xInputStream,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xModelComponent,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rFactory,
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropSet,
const sal_Char* pFilterName,
sal_Bool bEncrypted );
sal_uLong ReadThroughComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > xModelComponent,
const sal_Char* pStreamName,
const sal_Char* pCompatibilityStreamName,
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rFactory,
::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet > & rPropSet,
const sal_Char* pFilterName );
};
////////////////////////////////////////////////////////////
class SmXMLImport : public SvXMLImport
{
SvXMLTokenMap *pPresLayoutElemTokenMap;
SvXMLTokenMap *pPresLayoutAttrTokenMap;
SvXMLTokenMap *pFencedAttrTokenMap;
SvXMLTokenMap *pOperatorAttrTokenMap;
SvXMLTokenMap *pAnnotationAttrTokenMap;
SvXMLTokenMap *pPresElemTokenMap;
SvXMLTokenMap *pPresScriptEmptyElemTokenMap;
SvXMLTokenMap *pPresTableElemTokenMap;
SvXMLTokenMap *pColorTokenMap;
SmNodeStack aNodeStack;
sal_Bool bSuccess;
String aText;
public:
// #110680#
SmXMLImport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
sal_uInt16 nImportFlags=IMPORT_ALL);
virtual ~SmXMLImport() throw ();
// XServiceInfo (override parent method)
::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
// XUnoTunnel
sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rId ) throw(::com::sun::star::uno::RuntimeException);
static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
void SAL_CALL endDocument(void)
throw( ::com::sun::star::xml::sax::SAXException,
::com::sun::star::uno::RuntimeException );
SvXMLImportContext *CreateContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateMathContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateRowContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateFracContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateNumberContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTextContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateAnnotationContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateStringContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateIdentifierContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateOperatorContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSpaceContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSqrtContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateRootContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateStyleContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreatePaddedContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreatePhantomContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateFencedContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateErrorContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSubContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSupContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateSubSupContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateUnderContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateOverContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateUnderOverContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateMultiScriptsContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateNoneContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreatePrescriptsContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTableContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTableRowContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateTableCellContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateAlignGroupContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
SvXMLImportContext *CreateActionContext(sal_uInt16 nPrefix,
const rtl::OUString &rLocalName,
const com::sun::star::uno::Reference <
com::sun::star::xml::sax::XAttributeList> &xAttrList);
const SvXMLTokenMap &GetPresLayoutElemTokenMap();
const SvXMLTokenMap &GetPresLayoutAttrTokenMap();
const SvXMLTokenMap &GetFencedAttrTokenMap();
const SvXMLTokenMap &GetOperatorAttrTokenMap();
const SvXMLTokenMap &GetAnnotationAttrTokenMap();
const SvXMLTokenMap &GetPresElemTokenMap();
const SvXMLTokenMap &GetPresScriptEmptyElemTokenMap();
const SvXMLTokenMap &GetPresTableElemTokenMap();
const SvXMLTokenMap &GetColorTokenMap();
SmNodeStack & GetNodeStack() { return aNodeStack; }
SmNode *GetTree() { return aNodeStack.Pop(); }
sal_Bool GetSuccess() { return bSuccess; }
String &GetText() { return aText; }
virtual void SetViewSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps);
virtual void SetConfigurationSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps);
};
////////////////////////////////////////////////////////////
enum SmXMLMathElemTokenMap
{
XML_TOK_MATH
};
enum SmXMLPresLayoutElemTokenMap
{
XML_TOK_SEMANTICS,
XML_TOK_MSTYLE,
XML_TOK_MERROR,
XML_TOK_MPHANTOM,
XML_TOK_MROW,
XML_TOK_MFRAC,
XML_TOK_MSQRT,
XML_TOK_MROOT,
XML_TOK_MSUB,
XML_TOK_MSUP,
XML_TOK_MSUBSUP,
XML_TOK_MMULTISCRIPTS,
XML_TOK_MUNDER,
XML_TOK_MOVER,
XML_TOK_MUNDEROVER,
XML_TOK_MTABLE,
XML_TOK_MACTION,
XML_TOK_MFENCED,
XML_TOK_MPADDED
};
enum SmXMLPresLayoutAttrTokenMap
{
XML_TOK_FONTWEIGHT,
XML_TOK_FONTSTYLE,
XML_TOK_FONTSIZE,
XML_TOK_FONTFAMILY,
XML_TOK_COLOR,
XML_TOK_MATHCOLOR
};
enum SmXMLFencedAttrTokenMap
{
XML_TOK_OPEN,
XML_TOK_CLOSE
};
enum SmXMLPresTableElemTokenMap
{
XML_TOK_MTR,
XML_TOK_MTD
};
enum SmXMLPresElemTokenMap
{
XML_TOK_ANNOTATION,
XML_TOK_MI,
XML_TOK_MN,
XML_TOK_MO,
XML_TOK_MTEXT,
XML_TOK_MSPACE,
XML_TOK_MS,
XML_TOK_MALIGNGROUP
};
enum SmXMLPresScriptEmptyElemTokenMap
{
XML_TOK_MPRESCRIPTS,
XML_TOK_NONE
};
enum SmXMLOperatorAttrTokenMap
{
XML_TOK_STRETCHY
};
enum SmXMLAnnotationAttrTokenMap
{
XML_TOK_ENCODING
};
////////////////////////////////////////////////////////////
#endif
| 38.62029 | 141 | 0.666992 | Grosskopf |
b4a4f274283ff435bf2e8f4a7db55a429580833e | 1,229 | cpp | C++ | tests/unit/src/get_all_widgets.cpp | igagis/morda | dd7b58f7cb2689d56b7796cc9b6b9302aad1a529 | [
"MIT"
] | 69 | 2016-12-07T05:56:53.000Z | 2020-11-27T20:59:05.000Z | tests/unit/src/get_all_widgets.cpp | igagis/morda | dd7b58f7cb2689d56b7796cc9b6b9302aad1a529 | [
"MIT"
] | 103 | 2015-07-10T14:42:21.000Z | 2020-09-09T16:16:21.000Z | tests/unit/src/get_all_widgets.cpp | igagis/morda | dd7b58f7cb2689d56b7796cc9b6b9302aad1a529 | [
"MIT"
] | 18 | 2016-11-22T14:41:37.000Z | 2020-04-22T18:16:10.000Z | #include <tst/set.hpp>
#include <tst/check.hpp>
#include <morda/gui.hpp>
#include <morda/widgets/group/column.hpp>
#include "../../harness/util/dummy_context.hpp"
namespace{
tst::set set("get_all_widgets", [](tst::suite& suite){
suite.add("get_all_widgets_function", []{
morda::gui m(make_dummy_context());
auto w = m.context->inflater.inflate(treeml::read(R"qwertyuiop(
@container{
@column{
id{1}
}
@column{
id{2}
@column{
id{3}
}
@row{
id{4}
@pile{
id{8}
@column{
id{9}
}
}
}
}
@pile{
id{5}
@column{
id{6}
@row{
id{7}
}
}
}
}
)qwertyuiop"));
std::vector<std::string> expected_ids = {{
"1", "2", "3", "6", "9"
}};
tst::check(w != nullptr, SL);
auto aaas = w->get_all_widgets<morda::column>();
tst::check_ne(aaas.size(), size_t(0), SL);
for(const auto& id : expected_ids){
auto i = std::find_if(
aaas.begin(),
aaas.end(),
[&id](const decltype(aaas)::value_type& wg) -> bool {
return wg->id == id;
}
);
tst::check(i != aaas.end(), SL) << "id = '" << id <<"' not found";
}
});
});
}
| 16.835616 | 78 | 0.498779 | igagis |
b4a6e99d62c96a7bf64bf4102df97e5e0a62de59 | 15,362 | cc | C++ | src/fcst/source/layers/catalyst_layer.cc | jeremyjiezhou/Learn-PyTorch | 7e4404609bacd2ec796f6ca3ea118e8e34ab4a22 | [
"MIT"
] | 24 | 2016-10-04T20:49:55.000Z | 2022-03-12T19:07:10.000Z | src/fcst/source/layers/catalyst_layer.cc | jeremyjiezhou/Learn-PyTorch | 7e4404609bacd2ec796f6ca3ea118e8e34ab4a22 | [
"MIT"
] | null | null | null | src/fcst/source/layers/catalyst_layer.cc | jeremyjiezhou/Learn-PyTorch | 7e4404609bacd2ec796f6ca3ea118e8e34ab4a22 | [
"MIT"
] | 9 | 2016-12-11T22:15:03.000Z | 2020-11-21T13:51:05.000Z | //---------------------------------------------------------------------------
//
// FCST: Fuel Cell Simulation Toolbox
//
// Copyright (C) 2013 by Energy Systems Design Laboratory, University of Alberta
//
// This software is distributed under the MIT License.
// For more information, see the README file in /doc/LICENSE
//
// - Class: catalyst_layer.cc
// - Description: Base Catalyst Layer Class. It implements the interface for other catalyst layer class
// and some common methods.
// - Developers: Marc Secanell (2011-2013) and Madhur Bhaiya (2013)
// - $Id: catalyst_layer.cc 2605 2014-08-15 03:36:44Z secanell $
//
//---------------------------------------------------------------------------
#include <layers/catalyst_layer.h>
namespace NAME = FuelCellShop::Layer;
//---------------------------------------------------------------------------
template <int dim>
NAME::CatalystLayer<dim>::CatalystLayer(const std::string& name)
: NAME::PorousLayer<dim>(name)
{
this->reactant = nothing;
//this->constant_solutions[temperature_of_REV] = 0.; // For debug checking purposes
this->constant_solutions[total_pressure] = 0.; // For debug checking purposes
electrolyte = boost::shared_ptr<FuelCellShop::Material::PolymerElectrolyteBase > ();
catalyst_support = boost::shared_ptr< FuelCellShop::Material::CatalystSupportBase > ();
catalyst = boost::shared_ptr< FuelCellShop::Material::CatalystBase > ();
default_materials = true;
kinetics = boost::shared_ptr< FuelCellShop::Kinetics::BaseKinetics > ();
}
//---------------------------------------------------------------------------
template <int dim>
NAME::CatalystLayer<dim>::CatalystLayer()
: NAME::PorousLayer<dim> ()
{
this->reactant = nothing;
//this->constant_solutions[temperature_of_REV] = 0.; // For debug checking purposes
this->constant_solutions[total_pressure] = 0.; // For debug checking purposes
}
//---------------------------------------------------------------------------
template <int dim>
NAME::CatalystLayer<dim>::~CatalystLayer()
{
// No need to delete boost pointers since boost manages memory allocation
}
//---------------------------------------------------------------------------
template <int dim>
void
NAME::CatalystLayer<dim>::declare_parameters (const std::string& name,
ParameterHandler ¶m) const
{
FuelCellShop::Layer::PorousLayer<dim>::declare_parameters(name,param);
param.enter_subsection("Fuel cell data");
{
param.enter_subsection(name);
{
param.declare_entry("Catalyst layer type",
"DummyCL",
Patterns::Selection("DummyCL | HomogeneousCL | MultiScaleCL"),
" ");
param.declare_entry("Catalyst type",
"Platinum",
Patterns::Selection("Platinum"),
" ");
param.declare_entry("Catalyst support type",
"CarbonBlack",
Patterns::Selection("CarbonBlack"),
" ");
param.declare_entry("Electrolyte type",
"Nafion",
Patterns::Selection("Nafion"),
" ");
param.declare_entry("Kinetics type",
"TafelKinetics",
Patterns::Selection("TafelKinetics | ButlerVolmerKinetics | DoubleTrapKinetics | DualPathKinetics"),
" ");
// Note: This must be called within the section of the CL
FuelCellShop::Material::CatalystBase::declare_Catalyst_parameters(param);
FuelCellShop::Material::CatalystSupportBase::declare_CatalystSupport_parameters(param);
FuelCellShop::Material::PolymerElectrolyteBase::declare_PolymerElectrolyte_parameters(param);
FuelCellShop::Kinetics::BaseKinetics::declare_Kinetics_parameters(param);
}
param.leave_subsection();
}
param.leave_subsection();
}
//---------------------------------------------------------------------------
template <int dim>
void
NAME::CatalystLayer<dim>::initialize (ParameterHandler ¶m)
{
NAME::PorousLayer<dim>::initialize(param);
param.enter_subsection("Fuel cell data");
{
param.enter_subsection(this->name);
{
catalyst_type = param.get("Catalyst type");
catalyst_support_type = param.get("Catalyst support type");
electrolyte_type = param.get("Electrolyte type");
kinetics_type = param.get("Kinetics type");
catalyst = FuelCellShop::Material::CatalystBase::create_Catalyst(param, catalyst_type);
catalyst_support = FuelCellShop::Material::CatalystSupportBase::create_CatalystSupport(param, catalyst_support_type);
electrolyte = FuelCellShop::Material::PolymerElectrolyteBase::create_PolymerElectrolyte(param, electrolyte_type);
kinetics = FuelCellShop::Kinetics::BaseKinetics::create_Kinetics(param, kinetics_type);
kinetics->set_catalyst(catalyst.get());
kinetics->set_electrolyte(electrolyte.get());
}
param.leave_subsection();
}
param.leave_subsection();
}
//---------------------------------------------------------------------------
template <int dim>
void
NAME::CatalystLayer<dim>::set_solution(const std::vector< SolutionVariable >& sols)
{
Assert( std::find_if(sols.begin(), sols.end(), FuelCellShop::is_phiS) != sols.end(), ExcMessage("VariableNames::electronic_electrical_potential should exist in input vector to CatalystLayer::set_solution.") );
Assert( std::find_if(sols.begin(), sols.end(), FuelCellShop::is_phiM) != sols.end(), ExcMessage("VariableNames::protonic_electrical_potential should exist in input vector to CatalystLayer::set_solution.") );
std::vector<SolutionVariable> reactant_concentrations;
//-- Check if the problem is isothermal or non-isothermal and extract index for T:
int index_T = -1;
for (unsigned int s=0; s < sols.size(); ++s) {
if (sols[s].get_variablename() == temperature_of_REV){
index_T = s;
break;
}
}
//Ensure that we only compute with "current" solutions
this->solutions.clear();
for (unsigned int i=0; i < sols.size(); ++i)
{
if (sols[i].get_variablename() == electronic_electrical_potential)
{
this->kinetics->set_solid_potential(sols.at(i));
this->solutions[electronic_electrical_potential] = sols.at(i);
}
else if (sols[i].get_variablename() == protonic_electrical_potential)
{
this->kinetics->set_electrolyte_potential(sols.at(i));
this->solutions[protonic_electrical_potential] = sols.at(i);
}
else if( sols[i].get_variablename() == hydrogen_concentration )
{
AssertThrow( this->electrolyte->get_H_H2() != 0, ExcMessage("Henry's constant for hydrogen not initialized in the electrolyte object of the catalyst layer.") );
std::vector<double> hydrogen_concentration_old_GL(sols[i].size());
if (index_T >= 0) // Non-isothermal
for(unsigned int q = 0; q < hydrogen_concentration_old_GL.size(); ++q)
hydrogen_concentration_old_GL[q] = Constants::R()*sols.at(index_T)[q]*sols.at(i)[q]/(this->electrolyte->get_H_H2()*1.0e-6);
else
{
AssertThrow( this->constant_solutions.at(temperature_of_REV) != 0., ExcMessage("Temperature not initialized in the catalyst layer using set_T method.") );
for(unsigned int q = 0; q < hydrogen_concentration_old_GL.size(); ++q)
hydrogen_concentration_old_GL[q] = Constants::R()*this->constant_solutions.at(temperature_of_REV)*sols.at(i)[q]/(this->electrolyte->get_H_H2()*1.0e-6);
}
this->solutions[VariableNames::hydrogen_concentration] = FuelCellShop::SolutionVariable( hydrogen_concentration_old_GL,
VariableNames::hydrogen_concentration);
this->reactant = VariableNames::hydrogen_concentration;
reactant_concentrations.push_back( FuelCellShop::SolutionVariable( hydrogen_concentration_old_GL,
VariableNames::hydrogen_concentration) );
}
else if( sols[i].get_variablename() == oxygen_concentration )
{
AssertThrow( this->electrolyte->get_H_O2() != 0, ExcMessage("Henry's constant for oxygen not initialized in the electrolyte object of the catalyst layer.") );
std::vector<double> oxygen_concentration_old_GL(sols[i].size());
if (index_T >= 0) // Non-isothermal
{
for(unsigned int q = 0; q < oxygen_concentration_old_GL.size(); ++q)
oxygen_concentration_old_GL[q] = Constants::R()*sols.at(index_T)[q]*sols.at(i)[q]/(this->electrolyte->get_H_O2()*1.0e-6);
}
else
{
AssertThrow( this->constant_solutions.at(temperature_of_REV) != 0., ExcMessage("Temperature not initialized in the catalyst layer using set_T method.") );
for(unsigned int q = 0; q < oxygen_concentration_old_GL.size(); ++q)
oxygen_concentration_old_GL[q] = Constants::R()*this->constant_solutions.at(temperature_of_REV)*sols.at(i)[q]/(this->electrolyte->get_H_O2()*1.0e-6);
}
this->solutions[VariableNames::oxygen_concentration] = FuelCellShop::SolutionVariable( oxygen_concentration_old_GL,
VariableNames::oxygen_concentration);
this->reactant = VariableNames::oxygen_concentration;
reactant_concentrations.push_back( FuelCellShop::SolutionVariable( oxygen_concentration_old_GL, VariableNames::oxygen_concentration) );
}
else if (sols[i].get_variablename() == temperature_of_REV)
{
this->kinetics->set_temperature(sols.at(i));
this->solutions[temperature_of_REV] = sols.at(i);
}
else if (sols[i].get_variablename() == membrane_water_content)
{
this->solutions[membrane_water_content] = sols.at(i);
}
else if (sols[i].get_variablename() == oxygen_molar_fraction)
{
Assert( this->constant_solutions.at(total_pressure) != 0., ExcMessage("Total pressure not initialized in the catalyst layer using set_P method.") );
AssertThrow( this->electrolyte->get_H_O2() != 0, ExcMessage("Henry's constant for oxygen not initialized in the electrolyte object of the catalyst layer.") );
this->solutions[oxygen_molar_fraction] = sols.at(i);
this->reactant = oxygen_molar_fraction;
std::vector<double> oxy(sols[i].size());
for (unsigned int q=0; q<oxy.size(); ++q)
oxy[q] = sols.at(i)[q] * (this->constant_solutions.at(total_pressure)/this->electrolyte->get_H_O2());
reactant_concentrations.push_back( SolutionVariable(oxy, oxygen_concentration) );
}
else if (sols[i].get_variablename() == hydrogen_molar_fraction)
{
Assert( this->constant_solutions.at(total_pressure) != 0., ExcMessage("Total pressure not initialized in the catalyst layer using set_P method.") );
AssertThrow( this->electrolyte->get_H_H2() != 0, ExcMessage("Henry's constant for hydrogen not initialized in the electrolyte object of the catalyst layer.") );
this->solutions[hydrogen_molar_fraction] = sols.at(i);
this->reactant = hydrogen_molar_fraction;
std::vector<double> hyd(sols[i].size());
for (unsigned int q=0; q<hyd.size(); ++q)
hyd[q] = sols.at(i)[q] * (this->constant_solutions.at(total_pressure)/this->electrolyte->get_H_H2());
reactant_concentrations.push_back( SolutionVariable(hyd, hydrogen_concentration) );
}
}
Assert( reactant_concentrations.size() > 0, ExcMessage("At least one reactant concentration/molar fraction is required in input vector to CatalystLayer::set_solution.") );
this->kinetics->set_reactant_concentrations(reactant_concentrations);
this->n_quad = this->solutions[protonic_electrical_potential].size();
//Check for temperature, initialize if needed be
if (this->solutions.find(temperature_of_REV) == this->solutions.end())
{
Assert( this->constant_solutions.at(temperature_of_REV) != 0., ExcMessage("Temperature not initialized in the catalyst layer using set_T method for isothermal case.") );
this->solutions[temperature_of_REV] = SolutionVariable(this->constant_solutions.at(temperature_of_REV), this->n_quad, temperature_of_REV);
this->kinetics->set_temperature( this->solutions[temperature_of_REV] );
}
//Check for lambda, initialize if needed be
if (this->solutions.find(membrane_water_content) == this->solutions.end())
{
this->solutions[membrane_water_content] = SolutionVariable(12.0, this->n_quad, membrane_water_content);
}
//If anything that was being supplied before is no longer being supplied,
#ifdef DEBUG
std::vector<VariableNames> current_names;
for(unsigned int j =0; j < sols.size(); j++)
current_names.push_back(sols[j].get_variablename());
/*
Assert( std::is_permutation(common_names.begin(), common_names.end(), current_names.begin()), ExcMessage("Inconsistent provision of solutions to catalyst layer from application, "
"be consistent and always provide the same set of solutions"));
common_names = current_names;
*/
#endif
}
//---------------------------------------------------------------------------
template <int dim>
FuelCellShop::SolutionMap
NAME::CatalystLayer<dim>::get_coverages(){
SolutionMap sols;
if(this->kinetics->has_coverage(OH_coverage)){
std::vector<double> OH_c;
this->kinetics->OH_coverage(OH_c);
sols.push_back(SolutionVariable(OH_c, OH_coverage));
}
else
sols.push_back(SolutionVariable(0.0, this->solutions.size(), OH_coverage));
if(this->kinetics->has_coverage(O_coverage)){
std::vector<double> O_c;
this->kinetics->O_coverage(O_c);
sols.push_back(SolutionVariable(O_c, O_coverage));
}
else
sols.push_back(SolutionVariable(0.0, this->solutions.size(), O_coverage));
return sols;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Explicit instantiations.
template class NAME::CatalystLayer<deal_II_dimension>;
| 46.978593 | 213 | 0.593217 | jeremyjiezhou |
b4a7433fbd7f183050b4626f558d7b32054c877f | 2,437 | cc | C++ | rtc_base/testutils.cc | airmelody5211/webrtc-clone | 943843f1da42e47668c22ca758830334167f1b17 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | rtc_base/testutils.cc | zhangj1024/webrtc | 3a6b729a8edaabd2fe324e1f6f830869ec38d5ab | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | rtc_base/testutils.cc | zhangj1024/webrtc | 3a6b729a8edaabd2fe324e1f6f830869ec38d5ab | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright 2007 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 "rtc_base/testutils.h"
namespace webrtc {
namespace testing {
StreamSink::StreamSink() = default;
StreamSink::~StreamSink() = default;
StreamSource::StreamSource() {
Clear();
}
StreamSource::~StreamSource() = default;
StreamState StreamSource::GetState() const {
return state_;
}
StreamResult StreamSource::Read(void* buffer,
size_t buffer_len,
size_t* read,
int* error) {
if (SS_CLOSED == state_) {
if (error)
*error = -1;
return SR_ERROR;
}
if ((SS_OPENING == state_) || (readable_data_.size() <= read_block_)) {
return SR_BLOCK;
}
size_t count = std::min(buffer_len, readable_data_.size() - read_block_);
memcpy(buffer, &readable_data_[0], count);
size_t new_size = readable_data_.size() - count;
// Avoid undefined access beyond the last element of the vector.
// This only happens when new_size is 0.
if (count < readable_data_.size()) {
memmove(&readable_data_[0], &readable_data_[count], new_size);
}
readable_data_.resize(new_size);
if (read)
*read = count;
return SR_SUCCESS;
}
StreamResult StreamSource::Write(const void* data,
size_t data_len,
size_t* written,
int* error) {
if (SS_CLOSED == state_) {
if (error)
*error = -1;
return SR_ERROR;
}
if (SS_OPENING == state_) {
return SR_BLOCK;
}
if (SIZE_UNKNOWN != write_block_) {
if (written_data_.size() >= write_block_) {
return SR_BLOCK;
}
if (data_len > (write_block_ - written_data_.size())) {
data_len = write_block_ - written_data_.size();
}
}
if (written)
*written = data_len;
const char* cdata = static_cast<const char*>(data);
written_data_.insert(written_data_.end(), cdata, cdata + data_len);
return SR_SUCCESS;
}
void StreamSource::Close() {
state_ = SS_CLOSED;
}
} // namespace testing
} // namespace webrtc
| 27.382022 | 75 | 0.629462 | airmelody5211 |
b4a756dcb85a3911a1482af0b3334cc0e585488d | 243 | cpp | C++ | libs/core/render/src/bksge_core_render_frame_buffer.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/src/bksge_core_render_frame_buffer.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/src/bksge_core_render_frame_buffer.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file bksge_core_render_frame_buffer.cpp
*
* @brief FrameBuffer の実装
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#if !defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/inl/frame_buffer_inl.hpp>
#endif
| 18.692308 | 54 | 0.695473 | myoukaku |
b4a884b2d92d9c9e3a74e342111feea17c0bff18 | 2,691 | cc | C++ | third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mobile.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mobile.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mobile.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mobile.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_theme_engine.h"
#include "third_party/blink/renderer/core/scroll/scrollbar.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
namespace blink {
static const WebThemeEngine::ScrollbarStyle& ScrollbarStyle() {
static bool initialized = false;
DEFINE_STATIC_LOCAL(WebThemeEngine::ScrollbarStyle, style,
(WebThemeEngine::ScrollbarStyle{3, 4, 0x80808080}));
if (!initialized) {
// During device emulation, the chrome WebThemeEngine implementation may not
// be the mobile theme which can provide the overlay scrollbar styles.
// In the case the following call will do nothing and we'll use the default
// styles specified above.
Platform::Current()->ThemeEngine()->GetOverlayScrollbarStyle(&style);
DCHECK(style.thumb_thickness);
initialized = true;
}
return style;
}
ScrollbarThemeOverlayMobile& ScrollbarThemeOverlayMobile::GetInstance() {
// For unit tests which don't have Platform::Current()->ThemeEngine().
if (MockScrollbarsEnabled()) {
DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, theme, ());
return theme;
}
DEFINE_STATIC_LOCAL(
ScrollbarThemeOverlayMobile, theme,
(ScrollbarStyle().thumb_thickness, ScrollbarStyle().scrollbar_margin,
ScrollbarStyle().color));
return theme;
}
ScrollbarThemeOverlayMobile::ScrollbarThemeOverlayMobile(int thumb_thickness,
int scrollbar_margin,
Color color)
: ScrollbarThemeOverlay(thumb_thickness, scrollbar_margin), color_(color) {}
void ScrollbarThemeOverlayMobile::PaintThumb(GraphicsContext& context,
const Scrollbar& scrollbar,
const IntRect& rect) {
if (!scrollbar.Enabled())
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(context, scrollbar,
DisplayItem::kScrollbarThumb))
return;
DrawingRecorder recorder(context, scrollbar, DisplayItem::kScrollbarThumb);
context.FillRect(rect, color_);
}
} // namespace blink
| 40.772727 | 82 | 0.697882 | sarang-apps |
b4a96cd3a1e8fba64a73730d66fc74f02cd14db2 | 4,881 | cpp | C++ | src/mongo/dbtests/keypatterntests.cpp | wonderslug/mongo | 8da54bf660d2a5095e0e20c94734f784d49f0aeb | [
"Apache-2.0"
] | 1 | 2015-07-17T04:37:51.000Z | 2015-07-17T04:37:51.000Z | src/mongo/dbtests/keypatterntests.cpp | wonderslug/mongo | 8da54bf660d2a5095e0e20c94734f784d49f0aeb | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/keypatterntests.cpp | wonderslug/mongo | 8da54bf660d2a5095e0e20c94734f784d49f0aeb | [
"Apache-2.0"
] | null | null | null | // keypatterntests.cpp - Tests for the KeyPattern class
//
/**
* Copyright (C) 2012 10gen 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.
*/
#include "mongo/db/keypattern.h"
#include "mongo/dbtests/dbtests.h"
namespace KeyPatternTests {
class ExtendRangeBoundTests {
public:
void run() {
BSONObj bound = BSON( "a" << 55 );
BSONObj longBound = BSON("a" << 55 << "b" << 66);
//test keyPattern shorter than bound, should fail
{
KeyPattern keyPat( BSON( "a" << 1 ) );
ASSERT_THROWS( keyPat.extendRangeBound( longBound, false ), MsgAssertionException );
}
//test keyPattern doesn't match bound, should fail
{
KeyPattern keyPat( BSON( "b" << 1 ) );
ASSERT_THROWS( keyPat.extendRangeBound( bound, false ), MsgAssertionException );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "c" << 1) );
ASSERT_THROWS( keyPat.extendRangeBound( longBound, false ), MsgAssertionException );
}
//test keyPattern same as bound
{
KeyPattern keyPat( BSON( "a" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55) );
}
{
KeyPattern keyPat( BSON( "a" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55) );
}
//test keyPattern longer than bound, simple
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << 1) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MINKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << 1) );
BSONObj newB = keyPat.extendRangeBound( bound, true );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MAXKEY ) );
}
//test keyPattern longer than bound, more complex pattern directions
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MAXKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1) );
BSONObj newB = keyPat.extendRangeBound( bound, true );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MINKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1 << "c" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, false );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MAXKEY << "c" << MINKEY ) );
}
{
KeyPattern keyPat( BSON( "a" << 1 << "b" << -1 << "c" << 1 ) );
BSONObj newB = keyPat.extendRangeBound( bound, true );
ASSERT_EQUALS( newB , BSON("a" << 55 << "b" << MINKEY << "c" << MAXKEY ) );
}
}
};
class All : public Suite {
public:
All() : Suite( "keypattern" ) {
}
void setupTests() {
add< ExtendRangeBoundTests >();
}
} myall;
} // namespace KeyPatternTests
| 40.338843 | 100 | 0.544356 | wonderslug |
b4aa0f8d7ffcaf0004af1791b153c8e4f88443eb | 5,565 | cc | C++ | src/eckit/thread/ThreadPool.cc | dvuckovic/eckit | 58a918e7be8fe073f37683abf639374ab1ad3e4f | [
"Apache-2.0"
] | 10 | 2018-03-01T22:11:10.000Z | 2021-05-17T14:13:58.000Z | src/eckit/thread/ThreadPool.cc | dvuckovic/eckit | 58a918e7be8fe073f37683abf639374ab1ad3e4f | [
"Apache-2.0"
] | 43 | 2018-04-11T11:13:44.000Z | 2022-03-31T15:28:03.000Z | src/eckit/thread/ThreadPool.cc | dvuckovic/eckit | 58a918e7be8fe073f37683abf639374ab1ad3e4f | [
"Apache-2.0"
] | 20 | 2018-03-07T21:36:50.000Z | 2022-03-30T13:25:25.000Z | /*
* (C) Copyright 1996- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
// File ThreadPool.cc
// Baudouin Raoult - (c) ECMWF Feb 12
#include "eckit/thread/ThreadPool.h"
#include "eckit/runtime/Monitor.h"
#include "eckit/thread/AutoLock.h"
#include "eckit/thread/Thread.h"
#include "eckit/thread/ThreadControler.h"
//----------------------------------------------------------------------------------------------------------------------
namespace eckit {
//----------------------------------------------------------------------------------------------------------------------
class ThreadPoolThread : public Thread {
ThreadPool& owner_;
void run();
public:
ThreadPoolThread(ThreadPool& owner) :
owner_(owner) {}
};
void ThreadPoolThread::run() {
owner_.notifyStart();
Monitor::instance().name(owner_.name());
// Log::info() << "Start of ThreadPoolThread " << std::endl;
for (;;) {
Monitor::instance().show(false);
Log::status() << "-" << std::endl;
ThreadPoolTask* r = owner_.next();
if (!r)
break;
Monitor::instance().show(true);
r->pool_ = &owner_;
try {
r->execute();
}
catch (std::exception& e) {
Log::error() << "** " << e.what() << " Caught in " << Here() << std::endl;
Log::error() << "** Exception is reported" << std::endl;
owner_.error(e.what());
}
try {
delete r;
}
catch (std::exception& e) {
Log::error() << "** " << e.what() << " Caught in " << Here() << std::endl;
Log::error() << "** Exception is reported" << std::endl;
owner_.error(e.what());
}
owner_.endTask();
}
// Log::info() << "End of ThreadPoolThread " << std::endl;
owner_.notifyEnd();
}
ThreadPool::ThreadPool(const std::string& name, size_t count, size_t stack) :
count_(0), stack_(stack), running_(0), tasks_(0), name_(name), error_(false) {
// Log::info() << "ThreadPool::ThreadPool " << nme_ << " " << count << std::endl;
resize(count);
}
ThreadPool::~ThreadPool() {
// Log::info() << "ThreadPool::~ThreadPool " << name_ << std::endl;
try {
waitForThreads();
}
catch (std::exception& e) {
Log::error() << "** " << e.what() << " Caught in " << Here() << std::endl;
Log::error() << "** Exception is ignored" << std::endl;
}
}
void ThreadPool::waitForThreads() {
for (size_t i = 0; i < count_; i++) {
push(0);
}
AutoLock<MutexCond> lock(done_);
// Log::info() << "ThreadPool::waitForThreads " << name_ << " running: " << running_ << std::endl;
while (running_) {
// Log::info() << "ThreadPool::waitForThreads " << name_ << " running: " << running_ << std::endl;
done_.wait();
}
if (error_) {
error_ = false;
throw SeriousBug(std::string("ThreadPool::waitForThreads: ") + errorMessage_);
}
}
void ThreadPool::notifyStart() {
AutoLock<MutexCond> lock(done_);
running_++;
done_.signal();
// Log::info() << "ThreadPool::notifyStart " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::notifyEnd() {
AutoLock<MutexCond> lock(done_);
running_--;
done_.signal();
// Log::info() << "ThreadPool::notifyEnd " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::startTask() {
AutoLock<MutexCond> lock(active_);
tasks_++;
active_.signal();
// Log::info() << "ThreadPool::notifyStart " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::endTask() {
AutoLock<MutexCond> lock(active_);
tasks_--;
active_.signal();
// Log::info() << "ThreadPool::notifyStart " << name_ << " running: " << running_ << std::endl;
}
void ThreadPool::error(const std::string& msg) {
AutoLock<MutexCond> lock(done_);
if (error_)
errorMessage_ += " | ";
error_ = true;
errorMessage_ += msg;
}
void ThreadPool::push(ThreadPoolTask* r) {
if (r) {
startTask();
}
AutoLock<MutexCond> lock(ready_);
queue_.push_back(r);
ready_.signal();
}
void ThreadPool::push(std::list<ThreadPoolTask*>& l) {
AutoLock<MutexCond> lock(ready_);
for (std::list<ThreadPoolTask*>::iterator j = l.begin(); j != l.end(); ++j)
queue_.push_back((*j));
l.clear();
ready_.signal();
}
ThreadPoolTask* ThreadPool::next() {
AutoLock<MutexCond> lock(ready_);
while (queue_.empty())
ready_.wait();
ThreadPoolTask* r = queue_.front();
queue_.pop_front();
if (!queue_.empty())
ready_.signal();
return r;
}
void ThreadPool::wait() {
AutoLock<MutexCond> lock(active_);
while (tasks_) {
active_.wait();
}
}
void ThreadPool::resize(size_t size) {
while (count_ > size) {
push(0);
count_--;
}
while (count_ < size) {
ThreadControler c(new ThreadPoolThread(*this), true, stack_);
c.start();
count_++;
}
}
ThreadPoolTask::~ThreadPoolTask() {}
//----------------------------------------------------------------------------------------------------------------------
} // namespace eckit
| 25.645161 | 120 | 0.532435 | dvuckovic |
b4aa9cc7048eb0c33ed984dc932031a41f2588b7 | 99,824 | cpp | C++ | src/urAPI.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | 1 | 2015-11-05T00:50:07.000Z | 2015-11-05T00:50:07.000Z | src/urAPI.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | null | null | null | src/urAPI.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | null | null | null | /*
* urAPI.c
* urMus
*
* Created by Georg Essl on 6/20/09.
* Copyright 2009 Georg Essl. All rights reserved. See LICENSE.txt for license details.
*
*/
#include "urAPI.h"
#include "urGraphics.h"
#include "MachTimer.h"
//TODO//#include "RIOAudioUnitLayer.h"
#include "urSound.h"
#include "httpServer.h"
// Make EAGLview global so lua interface can grab it without breaking a leg over IMP
#ifdef TARGET_IPHONE
extern EAGLView* g_glView;
#endif
// This is to transport error and print messages to EAGLview
extern string errorstr;
extern bool newerror;
// Global lua state
lua_State *lua;
// Region based API below, this is inspired by WoW's frame API with many modifications and expansions.
// Our engine supports paging, region horizontal and vertical scrolling, full multi-touch and more.
// Hardcoded for now... lazy me
#define MAX_PAGES 30
int currentPage;
urAPI_Region_t* firstRegion[MAX_PAGES] = {nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil};
urAPI_Region_t* lastRegion[MAX_PAGES] = {nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil};
int numRegions[MAX_PAGES] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
urAPI_Region_t* UIParent = nil;
ursAPI_FlowBox_t* FBNope = nil;
MachTimer* systimer;
const char DEFAULT_RPOINT[] = "BOTTOMLEFT";
#define STRATA_PARENT 0
#define STRATA_BACKGROUND 1
#define STRATA_LOW 2
#define STRATA_MEDIUM 3
#define STRATA_HIGH 4
#define STRATA_DIALOG 5
#define STRATA_FULLSCREEN 6
#define STRATA_FULLSCREEN_DIALOG 7
#define STRATA_TOOLTIP 8
#define LAYER_BACKGROUND 1
#define LAYER_BORDER 2
#define LAYER_ARTWORK 3
#define LAYER_OVERLAY 4
#define LAYER_HIGHLIGHT 5
urAPI_Region_t* findRegionHit(float x, float y)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage] */; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
return nil;
}
void callAllOnLeaveRegions(float x, float y)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil ; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height
&& t->OnLeave != 0)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
{
t->entered = false;
callScript(t->OnLeave, t);
}
}
}
void callAllOnEnterLeaveRegions(int nr, float* x, float* y, float* ox, float* oy)
{
bool didenter;
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage] */; t=t->prev)
{
for(int i=0; i<nr; i++)
{
if(!(x[i] >= t->left && x[i] <= t->left+t->width &&
y[i] >= t->bottom && y[i] <= t->bottom+t->height) &&
ox[i] >= t->left && ox[i] <= t->left+t->width &&
oy[i] >= t->bottom && oy[i] <= t->bottom+t->height
&& t->OnLeave != 0)
{
// if(t->entered)
// {
t->entered = false;
callScript(t->OnLeave, t);
// }
// else
// {
// int a=0;
// }
}
else if(x[i] >= t->left && x[i] <= t->left+t->width &&
y[i] >= t->bottom && y[i] <= t->bottom+t->height &&
(!(ox[i] >= t->left && ox[i] <= t->left+t->width &&
oy[i] >= t->bottom && oy[i] <= t->bottom+t->height) || !t->entered)
&& t->OnEnter != 0)
{
// didenter = true;
// if(!t->entered)
// {
t->entered = true;
callScript(t->OnEnter, t);
// }
// else
// {
// int a=0;
// }
}
}
// if(t->entered && !didenter)
// {
// t->entered = false;
// callScript(t->OnLeave, t);
// }
// didenter = false;
}
}
urAPI_Region_t* findRegionDraggable(float x, float y)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage]*/; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isMovable && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
return nil;
}
urAPI_Region_t* findRegionXScrolled(float x, float y, float dx)
{
if(fabs(dx) > 0.9)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage]*/; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isScrollXEnabled && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
}
return nil;
}
urAPI_Region_t* findRegionYScrolled(float x, float y, float dy)
{
if(fabs(dy) > 0.9*3)
{
for(urAPI_Region_t* t=lastRegion[currentPage]; t != nil /* && t != firstRegion[currentPage]*/; t=t->prev)
{
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height && t->isScrollYEnabled && t->isTouchEnabled)
if(t->isClipping==false || (x >= t->clipleft && x <= t->clipleft+t->clipwidth &&
y >= t->clipbottom && y <= t->clipbottom+t->clipheight))
return t;
}
}
return nil;
}
void layoutchildren(urAPI_Region_t* region)
{
urAPI_Region_t* child = region->firstchild;
while(child!=NULL)
{
child->update = true;
layout(child);
child = child->nextchild;
}
}
bool visibleparent(urAPI_Region_t* region)
{
if(region == UIParent)
return true;
urAPI_Region_t* parent = region->parent;
while(parent != UIParent && parent->isVisible == true)
{
parent = parent->parent;
}
if(parent == UIParent)
return true;
else
return false;
}
void showchildren(urAPI_Region_t* region)
{
urAPI_Region_t* child = region->firstchild;
while(child!=NULL)
{
if(child->isShown)
{
child->isVisible = true;
if(region->OnShow != 0)
callScript(region->OnShow, region);
showchildren(child);
}
child = child->nextchild;
}
}
void hidechildren(urAPI_Region_t* region)
{
urAPI_Region_t* child = region->firstchild;
while(child!=NULL)
{
if(child->isVisible)
{
child->isVisible = false;
if(region->OnHide != 0)
callScript(region->OnHide, region);
hidechildren(child);
}
child = child->nextchild;
}
}
// This function is heavily informed by Jerry's base.lua in wowsim function, which is covered by a BSD-style (open) license.
// (EDIT) Fixed it up. Was buggy as is and didn't properly align for most anchor sides.
bool layout(urAPI_Region_t* region)
{
if(region == nil) return false;
bool update = region->update;
if(!update)
{
if(region->relativeRegion)
update = layout(region->relativeRegion);
else
update = layout(region->parent);
}
if(!update) return false;
float left, right, top, bottom, width, height, cx, cy,x,y;
left = right = top = bottom = width = height = cx = cy = x = y = -1000000;
const char* point = region->point;
if(point == nil)
point = DEFAULT_RPOINT;
urAPI_Region_t* relativeRegion = region->relativeRegion;
if(relativeRegion == nil)
relativeRegion = region->parent;
if(relativeRegion == nil)
relativeRegion = UIParent; // This should be another layer but we don't care for now
const char* relativePoint = region->relativePoint;
if(relativePoint == nil)
relativePoint = DEFAULT_RPOINT;
if(!strcmp(relativePoint, "ALL"))
{
left = relativeRegion->left;
bottom = relativeRegion->bottom;
width = relativeRegion->width;
height = relativeRegion->height;
}
else if(!strcmp(relativePoint,"TOPLEFT"))
{
x = relativeRegion->left;
y = relativeRegion->top;
}
else if(!strcmp(relativePoint,"TOPRIGHT"))
{
x = relativeRegion->right;
y = relativeRegion->top;
}
else if(!strcmp(relativePoint,"TOP"))
{
x = relativeRegion->cx;
y = relativeRegion->top;
}
else if(!strcmp(relativePoint,"LEFT"))
{
x = relativeRegion->left;
y = relativeRegion->cy;
}
else if(!strcmp(relativePoint,"RIGHT"))
{
x = relativeRegion->right;
y = relativeRegion->cy;
}
else if(!strcmp(relativePoint,"CENTER"))
{
x = relativeRegion->cx;
y = relativeRegion->cy;
}
else if(!strcmp(relativePoint,"BOTTOMLEFT"))
{
x = relativeRegion->left;
y = relativeRegion->bottom;
}
else if(!strcmp(relativePoint,"BOTTOMRIGHT"))
{
x = relativeRegion->right;
y = relativeRegion->bottom;
}
else if(!strcmp(relativePoint,"BOTTOM"))
{
x = relativeRegion->cx;
y = relativeRegion->bottom;
}
else
{
// Error!!
luaL_error(lua, "Unknown relativePoint when layouting regions.");
return false;
}
x = x+region->ofsx;
y = y+region->ofsy;
if(!strcmp(point,"TOPLEFT"))
{
left = x;
top = y;
}
else if(!strcmp(point,"TOPRIGHT"))
{
right = x;
top = y;
}
else if(!strcmp(point,"TOP"))
{
cx = x;
top = y;
}
else if(!strcmp(point,"LEFT"))
{
left = x;
cy = y; // Another typo here
}
else if(!strcmp(point,"RIGHT"))
{
right = x;
cy = y;
}
else if(!strcmp(point,"CENTER"))
{
cx = x;
cy = y;
}
else if(!strcmp(point,"BOTTOMLEFT"))
{
left = x;
bottom = y;
}
else if(!strcmp(point,"BOTTOMRIGHT"))
{
right = x;
bottom = y;
}
else if(!strcmp(point,"BOTTOM"))
{
cx = x;
bottom = y;
}
else
{
// Error!!
luaL_error(lua, "Unknown relativePoint when layouting regions.");
return false;
}
if(left > 0 && right > 0)
{
width = right - left;
}
if(top > 0 && bottom > 0)
{
height = top - bottom;
}
if(width == -1000000 && region->width > 0) width = region->width;
if(height == -1000000 && region->height > 0) height = region->height;
if(left == -1000000 && width > 0)
{
if(right>0) left = right - width;
else if(cx>0)
{
left = cx - width/2; // This was buggy. Fixing it up.
right = cx + width/2;
}
}
if(bottom == -1000000 && height > 0)
{
if(top>0) bottom = top - height;
if(cy>0)
{
bottom = cy - height/2; // This was buggy. Fixing it up.
top = cy + height/2;
}
}
update = false;
if(left != region->left || bottom != region->bottom || width != region->width || height != region->height)
update = true;
region->left = left;
region->bottom = bottom;
region->width = width;
region->height = height;
region->cx = left + width/2;
region->cy = bottom + height/2;
top = bottom + height; // All this was missing with bad effects
region->top = top;
right = left + width;
region->right = right;
region->update = false;
if(update)
{
layoutchildren(region);
// callScript("OnSizeChanged", width, height)
}
return update;
}
//------------------------------------------------------------------------------
// Our custom lua API
//------------------------------------------------------------------------------
static urAPI_Region_t *checkregion(lua_State *lua, int nr)
{
// void *region = luaL_checkudata(lua, nr, "URAPI.region");
luaL_checktype(lua, nr, LUA_TTABLE);
lua_rawgeti(lua, nr, 0);
void *region = lua_touserdata(lua, -1);
lua_pop(lua,1);
luaL_argcheck(lua, region!= NULL, nr, "'region' expected");
return (urAPI_Region_t*)region;
}
static urAPI_Texture_t *checktexture(lua_State *lua, int nr)
{
void *texture = luaL_checkudata(lua, nr, "URAPI.texture");
luaL_argcheck(lua, texture!= NULL, nr, "'texture' expected");
return (urAPI_Texture_t*)texture;
}
static urAPI_TextLabel_t *checktextlabel(lua_State *lua, int nr)
{
void *textlabel = luaL_checkudata(lua, nr, "URAPI.textlabel");
luaL_argcheck(lua, textlabel!= NULL, nr, "'textlabel' expected");
return (urAPI_TextLabel_t*)textlabel;
}
static ursAPI_FlowBox_t *checkflowbox(lua_State *lua, int nr)
{
luaL_checktype(lua, nr, LUA_TTABLE);
lua_rawgeti(lua, nr, 0);
void *flowbox = lua_touserdata(lua, -1);
lua_pop(lua,1);
luaL_argcheck(lua, flowbox!= NULL, nr, "'flowbox' expected");
return (ursAPI_FlowBox_t*)flowbox;
}
// NEW!!
static int l_NumRegions(lua_State *lua)
{
lua_pushnumber(lua, numRegions[currentPage]);
return 1;
}
static int l_EnumerateRegions(lua_State *lua)
{
urAPI_Region_t* region;
if(lua_isnil(lua,1))
{
region = UIParent->next;
}
else
{
region = checkregion(lua,1);
if(region!=nil)
region = region->next;
}
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
return 1;
}
// Region events to support
// OnDragStart
// OnDragStop
// OnEnter
// OnEvent
// OnHide
// OnLeave
// OnTouchDown
// OnTouchUp
// OnReceiveDrag (NYI)
// OnShow
// OnSizeChanged
// OnUpdate
// OnDoubleTap (UR!)
bool callAllOnUpdate(float time)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnUpdate != 0)
callScriptWith1Args(t->OnUpdate, t,time);
}
return true;
}
bool callAllOnPageEntered(float page)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnPageEntered != 0)
callScriptWith1Args(t->OnPageEntered, t,page);
}
return true;
}
bool callAllOnPageLeft(float page)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnPageLeft != 0)
callScriptWith1Args(t->OnPageLeft, t,page);
}
return true;
}
bool callAllOnLocation(float latitude, float longitude)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnLocation != 0)
callScriptWith2Args(t->OnLocation,t,latitude, longitude);
}
return true;
}
bool callAllOnHeading(float x, float y, float z, float north)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnHeading != 0)
callScriptWith4Args(t->OnHeading,t,x,y,z,north);
}
return true;
}
bool callAllOnAccelerate(float x, float y, float z)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnAccelerate != 0)
callScriptWith3Args(t->OnAccelerate,t,x,y,z);
}
return true;
}
bool callAllOnNetIn(float a)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnNetIn != 0)
callScriptWith1Args(t->OnNetIn,t,a);
}
return true;
}
bool callAllOnNetConnect(const char* name)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnNetConnect != 0)
callScriptWith1String(t->OnNetConnect,t,name);
}
return true;
}
bool callAllOnNetDisconnect(const char* name)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnNetDisconnect != 0)
callScriptWith1String(t->OnNetDisconnect,t,name);
}
return true;
}
#ifdef SANDWICH_SUPPORT
bool callAllOnPressure(float p)
{
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnPressure != 0)
callScriptWith1Args(t->OnPressure,t,p);
}
return true;
}
#endif
bool callAllOnMicrophone(SInt32* mic_buffer, UInt32 bufferlen)
{
lua_getglobal(lua, "urMicData");
if(lua_isnil(lua, -1) || !lua_istable(lua,-1)) // Channel doesn't exist or is falsely set up
{
lua_pop(lua,1);
return false;
}
for(UInt32 i=0;i<bufferlen; i++)
{
lua_pushnumber(lua, mic_buffer[i]);
lua_rawseti(lua, -2, i+1);
}
lua_setglobal(lua, "urMicData");
for(urAPI_Region_t* t=firstRegion[currentPage]; t != nil; t=t->next)
{
if(t->OnMicrophone != 0)
callScriptWith1Global(t->OnMicrophone, t, "urMicData");
}
return true;
}
bool callScriptWith4Args(int func_ref, urAPI_Region_t* region, float a, float b, float c, float d)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
lua_pushnumber(lua,b);
lua_pushnumber(lua,c);
lua_pushnumber(lua,d);
if(lua_pcall(lua,5,0,0) != 0)
{
// Error!!
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith3Args(int func_ref, urAPI_Region_t* region, float a, float b, float c)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
lua_pushnumber(lua,b);
lua_pushnumber(lua,c);
if(lua_pcall(lua,4,0,0) != 0)
{
// Error!!
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith2Args(int func_ref, urAPI_Region_t* region, float a, float b)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
lua_pushnumber(lua,b);
if(lua_pcall(lua,3,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith1Args(int func_ref, urAPI_Region_t* region, float a)
{
if(func_ref == 0) return false;
// int func_ref = region->OnDragging;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushnumber(lua,a);
if(lua_pcall(lua,2,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith1Global(int func_ref, urAPI_Region_t* region, const char* globaldata)
{
if(func_ref == 0) return false;
// int func_ref = region->OnDragging;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_getglobal(lua, globaldata);
if(lua_pcall(lua,2,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScriptWith1String(int func_ref, urAPI_Region_t* region, const char* name)
{
if(func_ref == 0) return false;
// int func_ref = region->OnDragging;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
lua_pushstring(lua, name);
if(lua_pcall(lua,2,0,0) != 0)
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
bool callScript(int func_ref, urAPI_Region_t* region)
{
if(func_ref == 0) return false;
// Call lua function by stored Reference
lua_rawgeti(lua,LUA_REGISTRYINDEX, func_ref);
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
if(lua_pcall(lua,1,0,0) != 0) // find table of udata here!!
{
//<return Error>
const char* error = lua_tostring(lua, -1);
errorstr = error; // DPrinting errors for now
newerror = true;
return false;
}
// OK!
return true;
}
int region_Handle(lua_State* lua)
{
urAPI_Region_t* region
= checkregion(lua,1);
//get parameter
const char* handler = luaL_checkstring(lua, 2);
if(lua_isnil(lua,3))
{
if(!strcmp(handler, "OnDragStart"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnDragStart);
region->OnDragStart = 0;
}
else if(!strcmp(handler, "OnDragStop"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnDragStop);
region->OnDragStop = 0;
}
else if(!strcmp(handler, "OnEnter"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnEnter);
region->OnEnter = 0;
}
else if(!strcmp(handler, "OnEvent"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnEvent);
region->OnEvent = 0;
}
else if(!strcmp(handler, "OnHide"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnHide);
region->OnHide = 0;
}
else if(!strcmp(handler, "OnLeave"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnLeave);
region->OnLeave = 0;
}
else if(!strcmp(handler, "OnTouchDown"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnTouchDown);
region->OnTouchDown = 0;
}
else if(!strcmp(handler, "OnTouchUp"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnTouchUp);
region->OnTouchUp = 0;
}
else if(!strcmp(handler, "OnShow"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnShow);
region->OnShow = 0;
}
else if(!strcmp(handler, "OnSizeChanged"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnSizeChanged);
region->OnSizeChanged = 0;
}
else if(!strcmp(handler, "OnUpdate"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnUpdate);
region->OnUpdate = 0;
}
else if(!strcmp(handler, "OnDoubleTap"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnDoubleTap);
region->OnDoubleTap = 0;
}
else if(!strcmp(handler, "OnAccelerate"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnAccelerate);
region->OnAccelerate = 0;
}
else if(!strcmp(handler, "OnNetIn"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnNetIn);
region->OnNetIn = 0;
}
else if(!strcmp(handler, "OnNetConnect"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnNetConnect);
region->OnNetConnect = 0;
}
else if(!strcmp(handler, "OnNetDisconnect"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnNetDisconnect);
region->OnNetDisconnect = 0;
}
#ifdef SANDWICH_SUPPORT
else if(!strcmp(handler, "OnPressure"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnPressure);
region->OnPressure = 0;
}
#endif
else if(!strcmp(handler, "OnHeading"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnHeading);
region->OnHeading = 0;
}
else if(!strcmp(handler, "OnLocation"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnLocation);
region->OnLocation = 0;
}
else if(!strcmp(handler, "OnMicrophone"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnMicrophone);
region->OnMicrophone = 0;
}
else if(!strcmp(handler, "OnHorizontalScroll"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnHorizontalScroll);
region->OnHorizontalScroll = 0;
}
else if(!strcmp(handler, "OnVerticalScroll"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnVerticalScroll);
region->OnVerticalScroll = 0;
}
else if(!strcmp(handler, "OnPageEntered"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnPageEntered);
region->OnPageEntered = 0;
}
else if(!strcmp(handler, "OnPageLeft"))
{
luaL_unref(lua, LUA_REGISTRYINDEX, region->OnPageLeft);
region->OnPageLeft = 0;
}
else
luaL_error(lua, "Trying to set a script for an unknown event: %s",handler);
return 0; // Error, unknown event
return 1;
}
else
{
luaL_argcheck(lua, lua_isfunction(lua,3), 3, "'function' expected");
if(lua_isfunction(lua,3))
{
/* char* func = (char*)lua_topointer(lua,3);
// <Also get some other info like function name, argument count>
// Load the function to memory
luaL_loadbuffer(lua,func,strlen(func),"LuaFunction");
lua_pop(lua,1);
*/
// Store funtion reference
lua_pushvalue(lua, 3);
int func_ref = luaL_ref(lua, LUA_REGISTRYINDEX);
// OnDragStart
// OnDragStop
// OnEnter
// OnEvent
// OnHide
// OnLeave
// OnTouchDown
// OnTouchUp
// OnReceiveDrag (NYI)
// OnShow
// OnSizeChanged
// OnUpdate
// OnDoubleTap (UR!)
if(!strcmp(handler, "OnDragStart"))
region->OnDragStart = func_ref;
else if(!strcmp(handler, "OnDragStop"))
region->OnDragStop = func_ref;
else if(!strcmp(handler, "OnEnter"))
region->OnEnter = func_ref;
else if(!strcmp(handler, "OnEvent"))
region->OnEvent = func_ref;
else if(!strcmp(handler, "OnHide"))
region->OnHide = func_ref;
else if(!strcmp(handler, "OnLeave"))
region->OnLeave = func_ref;
else if(!strcmp(handler, "OnTouchDown"))
region->OnTouchDown = func_ref;
else if(!strcmp(handler, "OnTouchUp"))
region->OnTouchUp = func_ref;
else if(!strcmp(handler, "OnShow"))
region->OnShow = func_ref;
else if(!strcmp(handler, "OnSizeChanged"))
region->OnSizeChanged = func_ref;
else if(!strcmp(handler, "OnUpdate"))
region->OnUpdate = func_ref;
else if(!strcmp(handler, "OnDoubleTap"))
region->OnDoubleTap = func_ref;
else if(!strcmp(handler, "OnAccelerate"))
region->OnAccelerate = func_ref;
else if(!strcmp(handler, "OnNetIn"))
region->OnNetIn = func_ref;
else if(!strcmp(handler, "OnNetConnect"))
region->OnNetConnect = func_ref;
else if(!strcmp(handler, "OnNetDisconnect"))
region->OnNetDisconnect = func_ref;
#ifdef SANDWICH_SUPPORT
else if(!strcmp(handler, "OnPressure"))
region->OnPressure = func_ref;
#endif
else if(!strcmp(handler, "OnHeading"))
region->OnHeading = func_ref;
else if(!strcmp(handler, "OnLocation"))
region->OnLocation = func_ref;
else if(!strcmp(handler, "OnMicrophone"))
region->OnMicrophone = func_ref;
else if(!strcmp(handler, "OnHorizontalScroll"))
region->OnHorizontalScroll = func_ref;
else if(!strcmp(handler, "OnVerticalScroll"))
region->OnVerticalScroll = func_ref;
else if(!strcmp(handler, "OnPageEntered"))
region->OnPageEntered = func_ref;
else if(!strcmp(handler, "OnPageLeft"))
region->OnPageLeft = func_ref;
else
luaL_unref(lua, LUA_REGISTRYINDEX, func_ref);
// OK!
return 1;
}
return 0;
}
}
int region_SetHeight(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_Number height = luaL_checknumber(lua,2);
region->height=height;
if(region->textlabel!=NULL)
region->textlabel->updatestring = true;
region->update = true;
if(!layout(region)) // Change may not have had a layouting effect on parent, but still could affect children that are anchored to Y
layoutchildren(region);
return 0;
}
int region_SetWidth(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_Number width = luaL_checknumber(lua,2);
region->width=width;
if(region->textlabel!=NULL)
region->textlabel->updatestring = true;
region->update = true;
if(!layout(region)) // Change may not have had a layouting effect on parent, but still could affect children that are anchored to X
layoutchildren(region);
return 0;
}
int region_EnableInput(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enableinput = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isTouchEnabled = enableinput;
return 0;
}
int region_EnableHorizontalScroll(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enablescrollx = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isScrollXEnabled = enablescrollx;
return 0;
}
int region_EnableVerticalScroll(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enablescrolly = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isScrollYEnabled = enablescrolly;
return 0;
}
int region_EnableClipping(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool enableclipping = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isClipping = enableclipping;
return 0;
}
int region_SetClipRegion(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
t->clipleft = luaL_checknumber(lua, 2);
t->clipbottom = luaL_checknumber(lua, 3);
t->clipwidth = luaL_checknumber(lua, 4);
t->clipheight = luaL_checknumber(lua, 5);
return 0;
}
int region_ClipRegion(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
lua_pushnumber(lua, t->clipleft);
lua_pushnumber(lua, t->clipbottom);
lua_pushnumber(lua, t->clipwidth);
lua_pushnumber(lua, t->clipheight);
return 4;
}
int region_EnableMoving(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool setmovable = lua_toboolean(lua,2);//!lua_isnil(lua,2);
region->isMovable = setmovable;
return 0;
}
int region_EnableResizing(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool setresizable = lua_toboolean(lua,2);//!lua_isnil(lua,2);
region->isResizable = setresizable;
return 0;
}
void ClampRegion(urAPI_Region_t* region);
int region_SetAnchor(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region==UIParent) return 0;
lua_Number ofsx;
lua_Number ofsy;
urAPI_Region_t* relativeRegion = UIParent;
const char* point = luaL_checkstring(lua, 2);
const char* relativePoint = DEFAULT_RPOINT;
if(lua_isnil(lua,3)) // SetAnchor(point);
{
}
else
{
if(lua_isnumber(lua, 3) && lua_isnumber(lua, 4)) // SetAnchor(point, x,y);
{
ofsx = luaL_checknumber(lua, 3);
ofsy = luaL_checknumber(lua, 4);
}
else
{
if(lua_isstring(lua, 3)) // SetAnchor(point, "relativeRegion")
{
// find parent here
}
else // SetAnchor(point, relativeRegion)
relativeRegion = checkregion(lua, 3);
if(lua_isstring(lua, 4))
relativePoint = luaL_checkstring(lua, 4);
if(lua_isnumber(lua, 5) && lua_isnumber(lua, 6)) // SetAnchor(point, x,y);
{
ofsx = luaL_checknumber(lua, 5);
ofsy = luaL_checknumber(lua, 6);
}
}
}
if(relativeRegion == region)
{
luaL_error(lua, "Cannot anchor a region to itself.");
return 0;
}
if(region->point != NULL)
free(region->point);
region->point = (char*)malloc(strlen(point)+1);
strcpy(region->point, point);
region->relativeRegion = relativeRegion;
if(relativeRegion != region->parent)
{
removeChild(region->parent, region);
region->parent = relativeRegion;
addChild(relativeRegion, region);
}
if(region->relativePoint != NULL)
free(region->relativePoint);
region->relativePoint = (char*)malloc(strlen(relativePoint)+1);
strcpy(region->relativePoint, relativePoint);
region->ofsx = ofsx;
region->ofsy = ofsy;
region->update = true;
layout(region);
if(region->isClamped)
ClampRegion(region);
return true;
}
int region_Show(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
region->isShown = true;
if(visibleparent(region)) // Check visibility change for children
{
region->isVisible = true;
if(region->OnShow != 0)
callScript(region->OnShow, region);
showchildren(region);
}
return 0;
}
int region_Hide(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
region->isVisible = false;
region->isShown = false;
if(region->OnHide != 0)
callScript(region->OnHide, region);
hidechildren(region); // parent got hidden so hide children too.
return 0;
}
const char STRATASTRING_PARENT[] = "PARENT";
const char STRATASTRING_BACKGROUND[] = "BACKGROUND";
const char STRATASTRING_LOW[] = "LOW";
const char STRATASTRING_MEDIUM[] = "MEDIUM";
const char STRATASTRING_HIGH[] = "HIGH";
const char STRATASTRING_DIALOG[] = "DIALOG";
const char STRATASTRING_FULLSCREEN[] = "FULLSCREEN";
const char STRATASTRING_FULLSCREEN_DIALOG[] = "FULLSCREEN_DIALOG";
const char STRATASTRING_TOOLTIP[] = "TOOLTIP";
const char* region_strataindex2str(int strataidx)
{
switch(strataidx)
{
case STRATA_PARENT:
return STRATASTRING_PARENT;
case STRATA_BACKGROUND:
return STRATASTRING_BACKGROUND;
case STRATA_LOW:
return STRATASTRING_LOW;
case STRATA_MEDIUM:
return STRATASTRING_MEDIUM;
case STRATA_HIGH:
return STRATASTRING_HIGH;
case STRATA_FULLSCREEN:
return STRATASTRING_FULLSCREEN;
case STRATA_FULLSCREEN_DIALOG:
return STRATASTRING_FULLSCREEN_DIALOG;
case STRATA_TOOLTIP:
return STRATASTRING_TOOLTIP;
default:
return nil;
}
}
int region_strata2index(const char* strata)
{
if(!strcmp(strata, "PARENT"))
return STRATA_PARENT;
else if(!strcmp(strata, "BACKGROUND"))
return STRATA_BACKGROUND;
else if(!strcmp(strata, "LOW"))
return STRATA_LOW;
else if(!strcmp(strata, "MEDIUM"))
return STRATA_MEDIUM;
else if(!strcmp(strata, "HIGH"))
return STRATA_HIGH;
else if(!strcmp(strata, "DIALOG"))
return STRATA_DIALOG;
else if(!strcmp(strata, "FULLSCREEN"))
return STRATA_FULLSCREEN;
else if(!strcmp(strata, "FULLSCREEN_DIALOG"))
return STRATA_FULLSCREEN_DIALOG;
else if(!strcmp(strata, "TOOLTIP"))
return STRATA_TOOLTIP;
else
{
return -1; // unknown strata
}
}
const char LAYERSTRING_BACKGROUND[] = "BACKGROUND";
const char LAYERSTRING_BORDER[] = "BORDER";
const char LAYERSTRING_ARTWORK[] = "ARTWORK";
const char LAYERSTRING_OVERLAY[] = "OVERLAY";
const char LAYERSTRING_HIGHLIGHT[] = "HIGHLIGHT";
const char* region_layerindex2str(int layeridx)
{
switch(layeridx)
{
case LAYER_BACKGROUND:
return LAYERSTRING_BACKGROUND;
case LAYER_BORDER:
return LAYERSTRING_BORDER;
case LAYER_ARTWORK:
return LAYERSTRING_ARTWORK;
case LAYER_OVERLAY:
return LAYERSTRING_OVERLAY;
case LAYER_HIGHLIGHT:
return LAYERSTRING_HIGHLIGHT;
default:
return nil;
}
}
int region_layer2index(const char* layer)
{
if(!strcmp(layer, "BACKGROUND"))
return LAYER_BACKGROUND;
else if(!strcmp(layer, "BORDER"))
return LAYER_BORDER;
else if(!strcmp(layer, "ARTWORK"))
return LAYER_ARTWORK;
else if(!strcmp(layer, "OVERLAY"))
return LAYER_OVERLAY;
else if(!strcmp(layer, "HIGHLIGHT"))
return LAYER_HIGHLIGHT;
else
{
return -1; // unknown layer
}
}
const char WRAPSTRING_WORD[] = "WORD";
const char WRAPSTRING_CHAR[] = "CHAR";
const char WRAPSTRING_CLIP[] = "CLIP";
const char* textlabel_wrapindex2str(int wrapidx)
{
switch(wrapidx)
{
case WRAP_WORD:
return WRAPSTRING_WORD;
case WRAP_CHAR:
return WRAPSTRING_CHAR;
case WRAP_CLIP:
return WRAPSTRING_CLIP;
default:
return nil;
}
}
int textlabel_wrap2index(const char* wrap)
{
if(!strcmp(wrap, "WORD"))
return WRAP_WORD;
else if(!strcmp(wrap, "CHAR"))
return WRAP_CHAR;
else if(!strcmp(wrap, "CLIP"))
return WRAP_CLIP;
else
{
return -1; // unknown wrap
}
}
void l_SortStrata(urAPI_Region_t* region, int strata)
{
if(region->prev == nil && firstRegion[currentPage] == region) // first region!
{
firstRegion[currentPage] = region->next; // unlink!
firstRegion[currentPage]->prev = nil;
}
else if(region->next == nil && lastRegion[currentPage] == region) // last region!
{
lastRegion[currentPage] = region->prev; // unlink!
lastRegion[currentPage]->next = nil;
}
else if(region->prev != NULL && region->next !=NULL)
{
region->prev->next = region->next; // unlink!
region->next->prev = region->prev;
}
for(urAPI_Region_t* t=firstRegion[currentPage]; t!=NULL; t=t->next)
{
if(t->strata!=STRATA_PARENT) // ignoring PARENT strata regions.
{
if(t->strata > strata) // insert here!
{
if(t == firstRegion[currentPage])
firstRegion[currentPage] = region;
region->prev = t->prev;
if(t->prev != NULL) // Again, may be the first.
t->prev->next = region;
region->next = t; // Link in
t->prev = region; // fix links
region->strata = strata;
// region->prev->next = region;
return; // Done.
}
}
}
if(region!=lastRegion[currentPage])
{
region->prev = lastRegion[currentPage];
region->next = nil;
lastRegion[currentPage]->next = region;
lastRegion[currentPage] = region;
}
else
{
lastRegion[currentPage] = nil;
}
}
void l_setstrataindex(urAPI_Region_t* region , int strataindex)
{
if(strataindex == STRATA_PARENT)
{
region->strata = strataindex;
urAPI_Region_t* p = region->parent;
int newstrataindex = 1;
do
{
if (p->strata != STRATA_PARENT) newstrataindex = p->strata;
p = p->parent;
}
while(p!=NULL && p->strata == 0);
l_SortStrata(region, newstrataindex);
}
if (strataindex > 0 && strataindex != region->strata)
{
region->strata = strataindex;
l_SortStrata(region, strataindex);
}
}
int region_SetLayer(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
const char* strata = luaL_checkstring(lua,2);
if(strata)
{
int strataindex = region_strata2index(strata);
if( region == firstRegion[currentPage] && region == lastRegion[currentPage])
{
// This is a sole region, no need to stratify
}
else
l_setstrataindex(region , strataindex);
region->strata = strataindex;
}
return 0;
}
int region_Parent(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region != nil)
{
region = region->parent;
lua_rawgeti(lua,LUA_REGISTRYINDEX, region->tableref);
return 1;
}
else
return 0;
}
int region_Children(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
urAPI_Region_t* child = region->firstchild;
int childcount = 0;
while(child!=NULL)
{
childcount++;
lua_rawgeti(lua,LUA_REGISTRYINDEX, child->tableref);
child = child->nextchild;
}
return childcount;
}
int region_Alpha(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->alpha);
return 1;
}
int region_SetAlpha(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_Number alpha = luaL_checknumber(lua,2);
if(alpha > 1.0) alpha = 1.0;
else if(alpha < 0.0) alpha = 0.0;
region->alpha=alpha;
return 0;
}
int region_Name(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushstring(lua, region->name);
return 1;
}
int region_Bottom(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->bottom);
return 1;
}
int region_Center(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->cx);
lua_pushnumber(lua, region->cy);
return 2;
}
int region_Height(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->height);
return 1;
}
int region_Left(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->left);
return 1;
}
int region_Right(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->right);
return 1;
}
int region_Top(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->top);
return 1;
}
int region_Width(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, region->width);
return 1;
}
int region_NumAnchors(lua_State* lua)
{
// urAPI_Region_t* region = checkregion(lua,1);
lua_pushnumber(lua, 1); // NYI always 1 point for now
return 1;
}
int region_Anchor(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushstring(lua, region->point);
if(region->relativeRegion)
{
lua_rawgeti(lua, LUA_REGISTRYINDEX, region->relativeRegion->tableref);
}
else
lua_pushnil(lua);
lua_pushstring(lua, region->relativePoint);
lua_pushnumber(lua, region->ofsx);
lua_pushnumber(lua, region->ofsy);
return 5;
}
int region_IsShown(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushboolean(lua, region->isVisible);
return 1;
}
int region_IsVisible(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool visible = false;
if(region->parent!=NULL)
visible = region->isVisible && region->parent->isVisible;
else
visible = region->isVisible;
lua_pushboolean(lua, visible );
return 1;
}
void setParent(urAPI_Region_t* region, urAPI_Region_t* parent)
{
if(region!= NULL && parent!= NULL && region != parent)
{
region->relativeRegion = parent;
removeChild(region->parent, region);
if(parent == UIParent)
region->parent = UIParent;
else
{
region->parent = parent;
addChild(parent, region);
}
}
}
int region_SetParent(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
urAPI_Region_t* parent = checkregion(lua, 2);
setParent(region, parent);
region->update = true;
layout(region);
return 0;
}
int region_Layer(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
lua_pushstring(lua, region_strataindex2str(region->strata));
return 1;
}
// NEW!!
int region_Lower(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region->prev != nil)
{
urAPI_Region_t* temp = region->prev;
region->prev = temp->prev;
temp->next = region->next;
temp->prev = region;
region->next = temp;
}
return 0;
}
int region_Raise(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region->next != nil)
{
urAPI_Region_t* temp = region->next;
region->next = temp->next;
temp->prev = region->prev;
temp->next = region;
region->prev = temp;
}
return 0;
}
void removeRegion(urAPI_Region_t* region)
{
int currentPage = region->page;
if(firstRegion[currentPage] == region)
firstRegion[currentPage] = region->next;
if(region->prev != NULL)
region->prev->next = region->next;
if(region->next != NULL)
region->next->prev = region->prev;
if(lastRegion[currentPage] == region)
lastRegion[currentPage] = region->prev;
numRegions[currentPage]--;
}
void freeTexture(urAPI_Texture_t* texture)
{
if(texture->backgroundTex!= NULL)
delete texture->backgroundTex;
// free(texture); // GC should take care of this ... maybe
}
void freeTextLabel(urAPI_TextLabel_t* textlabel)
{
if(textlabel->textlabelTex != NULL)
delete textlabel->textlabelTex;
// delete textlabel; // GC should take care of this ... maybe
}
void freeRegion(urAPI_Region_t* region)
{
removeChild(region->parent, region);
removeRegion(region);
if(region->texture != NULL)
freeTexture(region->texture);
if(region->textlabel != NULL)
freeTextLabel(region->textlabel);
delete region;
}
int region_Free(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
freeRegion(region);
}
int l_FreeAllRegions(lua_State* lua)
{
urAPI_Region_t* t=lastRegion[currentPage];
urAPI_Region_t* p;
while(t != nil)
{
t->isVisible = false;
t->isShown = false;
t->isMovable = false;
t->isResizable = false;
t->isTouchEnabled = false;
t->isScrollXEnabled = false;
t->isScrollYEnabled = false;
t->isVisible = false;
t->isShown = false;
t->isDragged = false;
t->isResized = false;
t->isClamped = false;
t->isClipping = false;
p=t->prev;
freeRegion(t);
t = p;
}
return 0;
}
int region_IsToplevel(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool istop = false;
if(region == lastRegion[currentPage])
{
istop = true;
}
lua_pushboolean(lua, istop);
return 1;
}
int region_MoveToTop(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
if(region != lastRegion[currentPage])
{
if(region->prev != nil) // Could be first region!
region->prev->next = region->next; // unlink!
region->next->prev = region->prev;
// and make last
lastRegion[currentPage]->next = region;
region->next = nil;
lastRegion[currentPage] = region;
}
return 0;
}
// ENDNEW!!
void instantiateTexture(urAPI_Region_t* t);
char TEXTURE_SOLID[] = "Solid Texture";
#define GRADIENT_ORIENTATION_VERTICAL 0
#define GRADIENT_ORIENTATION_HORIZONTAL 1
#define GRADIENT_ORIENTATION_DOWNWARD 2
#define GRADIENT_ORIENTATION_UPWARD 3
int region_Texture(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
const char* texturename;
const char* texturelayer;
int texturelayerindex=1;
float r,g,b,a;
r = 255;
g = 255;
b = 255;
a = 255;
if(lua_gettop(lua)<2 || lua_isnil(lua,2)) // this can legitimately be nil.
texturename = nil;
else
{
if(lua_isstring(lua,2) && lua_gettop(lua) <4)
{
texturename = luaL_checkstring(lua,2);
if(lua_gettop(lua)==3 && !lua_isnil(lua,3)) // this should be set.
{
texturelayer = luaL_checkstring(lua,3);
texturelayerindex = region_layer2index(texturelayer);
}
// NYI arg3.. are inheritsFrom regions
}
else if(lua_isnumber(lua,2)) {
texturename = nil;
r = luaL_checknumber(lua, 2);
if(lua_gettop(lua)>2)
{
g = luaL_checknumber(lua,3);
if(lua_gettop(lua)>3)
{
b = luaL_checknumber(lua,4);
a = 255;
if(lua_gettop(lua)>4)
a = luaL_checknumber(lua,5);
}
else
{
g = r;
b = r;
a = g;
}
}
else {
g = r;
b = r;
a = 255;
}
}
}
urAPI_Texture_t* mytexture = (urAPI_Texture_t*)lua_newuserdata(lua, sizeof(urAPI_Texture_t));
mytexture->blendmode = BLEND_DISABLED;
mytexture->texcoords[0] = 0.0;
mytexture->texcoords[1] = 1.0;
mytexture->texcoords[2] = 1.0;
mytexture->texcoords[3] = 1.0;
mytexture->texcoords[4] = 0.0;
mytexture->texcoords[5] = 0.0;
mytexture->texcoords[6] = 1.0;
mytexture->texcoords[7] = 0.0;
if(texturename == NULL)
mytexture->texturepath = TEXTURE_SOLID;
else
{
mytexture->texturepath = (char*)malloc(strlen(texturename)+1);
strcpy(mytexture->texturepath, texturename);
// mytexture->texturepath = texturename;
}
mytexture->modifyRect = false;
mytexture->isDesaturated = false;
mytexture->isTiled = true;
mytexture->fill = false;
// mytexture->gradientOrientation = GRADIENT_ORIENTATION_VERTICAL; OBSOLETE
mytexture->gradientUL[0] = 255; // R
mytexture->gradientUL[1] = 255; // G
mytexture->gradientUL[2] = 255; // B
mytexture->gradientUL[3] = 255; // A
mytexture->gradientUR[0] = 255; // R
mytexture->gradientUR[1] = 255; // G
mytexture->gradientUR[2] = 255; // B
mytexture->gradientUR[3] = 255; // A
mytexture->gradientBL[0] = 255; // R
mytexture->gradientBL[1] = 255; // G
mytexture->gradientBL[2] = 255; // B
mytexture->gradientBL[3] = 255; // A
mytexture->gradientBR[0] = 255; // R
mytexture->gradientBR[1] = 255; // G
mytexture->gradientBR[2] = 255; // B
mytexture->gradientBR[3] = 255; // A
mytexture->texturesolidcolor[0] = r; // R for solid
mytexture->texturesolidcolor[1] = g; // G
mytexture->texturesolidcolor[2] = b; // B
mytexture->texturesolidcolor[3] = a; // A
mytexture->backgroundTex = NULL;
region->texture = mytexture; // HACK
mytexture->region = region;
luaL_getmetatable(lua, "URAPI.texture");
lua_setmetatable(lua, -2);
if(mytexture->backgroundTex == nil && mytexture->texturepath != TEXTURE_SOLID)
{
instantiateTexture(mytexture->region);
}
return 1;
}
char textlabel_empty[] = "";
const char textlabel_defaultfont[] = "Helvetica";
int region_TextLabel(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
const char* texturename;
const char* texturelayer;
int texturelayerindex=1;
if(lua_gettop(lua)<2 || lua_isnil(lua,2)) // this can legitimately be nil.
texturename = nil;
else
if(!lua_isnil(lua,3)) // this should be set.
{
texturelayer = luaL_checkstring(lua,3);
texturelayerindex = region_layer2index(texturelayer);
}
// NYI arg3.. are inheritsFrom regions
urAPI_TextLabel_t* mytextlabel = (urAPI_TextLabel_t*)lua_newuserdata(lua, sizeof(urAPI_TextLabel_t));
region->textlabel = mytextlabel; // HACK
mytextlabel->text = textlabel_empty;
mytextlabel->updatestring = true;
mytextlabel->font = textlabel_defaultfont;
mytextlabel->justifyh = JUSTIFYH_CENTER;
mytextlabel->justifyv = JUSTIFYV_MIDDLE;
mytextlabel->shadowcolor[0] = 0.0;
mytextlabel->shadowcolor[1] = 0.0;
mytextlabel->shadowcolor[2] = 0.0;
mytextlabel->shadowcolor[3] = 128.0;
mytextlabel->shadowoffset[0] = 0.0;
mytextlabel->shadowoffset[1] = 0.0;
mytextlabel->shadowblur = 0.0;
mytextlabel->drawshadow = false;
mytextlabel->linespacing = 2;
mytextlabel->textcolor[0] = 255.0;
mytextlabel->textcolor[1] = 255.0;
mytextlabel->textcolor[2] = 255.0;
mytextlabel->textcolor[3] = 255.0;
mytextlabel->textheight = 12;
mytextlabel->wrap = WRAP_WORD;
mytextlabel->rotation = 0.0;
mytextlabel->textlabelTex = nil;
luaL_getmetatable(lua, "URAPI.textlabel");
lua_setmetatable(lua, -2);
return 1;
}
#include <vector>
#include <string>
static std::vector<std::string> ur_log;
void ur_Log(const char * str) {
ur_log.push_back(str);
}
extern "C" {
char * ur_GetLog(int since, int *nlog);
}
char * ur_GetLog(int since, int *nlog) {
if(since<0) since=0;
std::string str="";
for(int i=since;i<ur_log.size();i++) {
str+=ur_log[i];
str+="\n";
}
char *result=(char *)malloc(str.length()+1);
strcpy(result, str.c_str());
*nlog=ur_log.size();
return result;
}
int l_DPrint(lua_State* lua)
{
const char* str = luaL_checkstring(lua,1);
if(str!=nil)
{
ur_Log(str);
errorstr = str;
newerror = true;
}
return 0;
}
int l_InputFocus(lua_State* lua)
{
// NYI
return 0;
}
int l_HasInput(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
bool isover = false;
float x,y;
// NYI
if(x >= t->left && x <= t->left+t->width &&
y >= t->bottom && y <= t->bottom+t->height /*&& t->isTouchEnabled*/)
isover = true;
lua_pushboolean(lua, isover);
return 1;
}
extern int SCREEN_WIDTH;
extern int SCREEN_HEIGHT;
int l_ScreenHeight(lua_State* lua)
{
lua_pushnumber(lua, SCREEN_HEIGHT);
return 1;
}
int l_ScreenWidth(lua_State* lua)
{
lua_pushnumber(lua, SCREEN_WIDTH);
return 1;
}
extern float cursorpositionx[MAX_FINGERS];
extern float cursorpositiony[MAX_FINGERS];
// UR: New arg "finger" allows to specify which finger to get position for. nil defaults to 0.
int l_InputPosition(lua_State* lua)
{
int finger = 0;
if(lua_gettop(lua) > 0 && !lua_isnil(lua, 1))
finger = luaL_checknumber(lua, 1);
lua_pushnumber(lua, cursorpositionx[finger]);
lua_pushnumber(lua, SCREEN_HEIGHT-cursorpositiony[finger]);
return 2;
}
int l_Time(lua_State* lua)
{
#ifdef TARGET_IPHONE
lua_pushnumber(lua, [systimer elapsedSec]);
#else
lua_pushnumber(lua, systimer->elapsedSec());
#endif
return 1;
}
int l_RunScript(lua_State* lua)
{
const char* script = luaL_checkstring(lua,1);
if(script != NULL)
luaL_dostring(lua,script);
return 0;
}
int l_StartHTTPServer(lua_State *lua)
{
#ifdef TARGET_IPHONE
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSArray *paths;
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath;
if ([paths count] > 0)
documentPath = [paths objectAtIndex:0];
// start off http server
http_start([resourcePath UTF8String],
[documentPath UTF8String]);
#else
// TODO : use internal storage path
#endif
return 0;
}
int l_StopHTTPServer(lua_State *lua)
{
http_stop();
return 0;
}
int l_HTTPServer(lua_State *lua)
{
const char *ip = http_ip_address();
if (ip) {
lua_pushstring(lua, ip);
lua_pushstring(lua, http_ip_port());
return 2;
} else {
return 0;
}
}
static int audio_initialized = false;
int l_StartAudio(lua_State* lua)
{
#ifdef TARGET_IPHONE
if(!audio_initialized)
{
initializeRIOAudioLayer();
}
else
playRIOAudioLayer();
#else
//TODO// audio stuff
#endif
return 0;
}
int l_PauseAudio(lua_State* lua)
{
#ifdef TARGET_IPHONE
stopRIOAudioLayer();
#else
//TODO// audio stuff
#endif
return 0;
}
static int l_setanimspeed(lua_State *lua)
{
double ds = luaL_checknumber(lua, 1);
#ifdef TARGET_IPHONE
g_glView.animationInterval = ds;
#endif
return 0;
}
int texture_SetTexture(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
if(lua_isnumber(lua,2) && lua_isnumber(lua,3) && lua_isnumber(lua,4))
{
t->texturepath = TEXTURE_SOLID;
t->texturesolidcolor[0] = luaL_checknumber(lua, 2);
t->texturesolidcolor[1] = luaL_checknumber(lua, 3);
t->texturesolidcolor[2] = luaL_checknumber(lua, 4);
if(lua_isnumber(lua, 5))
t->texturesolidcolor[3] = luaL_checknumber(lua, 5);
else
t->texturesolidcolor[3] = 255;
}
else
{
const char* texturename = luaL_checkstring(lua,2);
if(t->texturepath != TEXTURE_SOLID && t->texturepath != NULL)
free(t->texturepath);
t->texturepath = (char*)malloc(strlen(texturename)+1);
strcpy(t->texturepath, texturename);
if(t->backgroundTex != NULL) delete t->backgroundTex; // Antileak
t->backgroundTex = nil;
instantiateTexture(t->region);
}
return 0;
}
int texture_SetGradientColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
const char* orientation = luaL_checkstring(lua, 2);
float minR = luaL_checknumber(lua, 3);
float minG = luaL_checknumber(lua, 4);
float minB = luaL_checknumber(lua, 5);
float minA = luaL_checknumber(lua, 6);
float maxR = luaL_checknumber(lua, 7);
float maxG = luaL_checknumber(lua, 8);
float maxB = luaL_checknumber(lua, 9);
float maxA = luaL_checknumber(lua, 10);
if(!strcmp(orientation, "HORIZONTAL"))
{
t->gradientUL[0] = minR;
t->gradientUL[1] = minG;
t->gradientUL[2] = minB;
t->gradientUL[3] = minA;
t->gradientBL[0] = minR;
t->gradientBL[1] = minG;
t->gradientBL[2] = minB;
t->gradientBL[3] = minA;
t->gradientUR[0] = maxR;
t->gradientUR[1] = maxG;
t->gradientUR[2] = maxB;
t->gradientUR[3] = maxA;
t->gradientBR[0] = maxR;
t->gradientBR[1] = maxG;
t->gradientBR[2] = maxB;
t->gradientBR[3] = maxA;
}
else if(!strcmp(orientation, "VERTICAL"))
{
t->gradientUL[0] = minR;
t->gradientUL[1] = minG;
t->gradientUL[2] = minB;
t->gradientUL[3] = minA;
t->gradientUR[0] = minR;
t->gradientUR[1] = minG;
t->gradientUR[2] = minB;
t->gradientUR[3] = minA;
t->gradientBL[0] = maxR;
t->gradientBL[1] = maxG;
t->gradientBL[2] = maxB;
t->gradientBL[3] = maxA;
t->gradientBR[0] = maxR;
t->gradientBR[1] = maxG;
t->gradientBR[2] = maxB;
t->gradientBR[3] = maxA;
}
else if(!strcmp(orientation, "TOP")) // UR! Allows to set the full gradient in 2 calls.
{
t->gradientUL[0] = minR;
t->gradientUL[1] = minG;
t->gradientUL[2] = minB;
t->gradientUL[3] = minA;
t->gradientUR[0] = maxR;
t->gradientUR[1] = maxG;
t->gradientUR[2] = maxB;
t->gradientUR[3] = maxA;
}
else if(!strcmp(orientation, "BOTTOM")) // UR!
{
t->gradientBL[0] = minR;
t->gradientBL[1] = minG;
t->gradientBL[2] = minB;
t->gradientBL[3] = minA;
t->gradientBR[0] = maxR;
t->gradientBR[1] = maxG;
t->gradientBR[2] = maxB;
t->gradientBR[3] = maxA;
}
return 0;
}
int texture_Texture(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
// NYI still don't know how to return user values
return 0;
}
int texture_SetSolidColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float vertR = luaL_checknumber(lua, 2);
float vertG = luaL_checknumber(lua, 3);
float vertB = luaL_checknumber(lua, 4);
float vertA = 255;
if(lua_gettop(lua)==5)
vertA = luaL_checknumber(lua, 5);
t->texturesolidcolor[0] = vertR;
t->texturesolidcolor[1] = vertG;
t->texturesolidcolor[2] = vertB;
t->texturesolidcolor[3] = vertA;
return 0;
}
int texture_SolidColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->texturesolidcolor[0]);
lua_pushnumber(lua, t->texturesolidcolor[1]);
lua_pushnumber(lua, t->texturesolidcolor[2]);
lua_pushnumber(lua, t->texturesolidcolor[3]);
return 4;
}
int texture_SetTexCoord(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
if(lua_gettop(lua)==5)
{
float left = luaL_checknumber(lua, 2);
float right = luaL_checknumber(lua, 3);
float top = luaL_checknumber(lua, 4);
float bottom = luaL_checknumber(lua, 5);
t->texcoords[0] = left; //ULx
t->texcoords[1] = top; // ULy
t->texcoords[2] = right; // URx
t->texcoords[3] = top; // URy
t->texcoords[4] = left; // BLx
t->texcoords[5] = bottom; // BLy
t->texcoords[6] = right; // BRx
t->texcoords[7] = bottom; // BRy
}
else if(lua_gettop(lua)==9)
{
t->texcoords[0] = luaL_checknumber(lua, 2);
t->texcoords[1] = luaL_checknumber(lua, 3);
t->texcoords[2] = luaL_checknumber(lua, 4);
t->texcoords[3] = luaL_checknumber(lua, 5);
t->texcoords[4] = luaL_checknumber(lua, 6);
t->texcoords[5] = luaL_checknumber(lua, 7);
t->texcoords[6] = luaL_checknumber(lua, 8);
t->texcoords[7] = luaL_checknumber(lua, 9);
}
return 0;
}
int texture_TexCoord(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->texcoords[0]);
lua_pushnumber(lua, t->texcoords[1]);
lua_pushnumber(lua, t->texcoords[2]);
lua_pushnumber(lua, t->texcoords[3]);
lua_pushnumber(lua, t->texcoords[4]);
lua_pushnumber(lua, t->texcoords[5]);
lua_pushnumber(lua, t->texcoords[6]);
lua_pushnumber(lua, t->texcoords[7]);
return 8;
}
int texture_SetRotation(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float angle = luaL_checknumber(lua, 2);
float s = sqrt(2.0)/2.0*sin(angle);
float c = sqrt(2.0)/2.0*cos(angle);
// x = r*math.sin(angle+math.pi/4)
// y = r*math.cos(angle+math.pi/4)
// hand.t:SetTexCoord(.5-x,.5+y, .5+y,.5+x, .5-y,.5-x, .5+x,.5-y)
// r = math.sqrt(2)/2
t->texcoords[0] = 0.5-s;
t->texcoords[1] = 0.5+c;
t->texcoords[2] = 0.5+c;
t->texcoords[3] = 0.5+s;
t->texcoords[4] = 0.5-c;
t->texcoords[5] = 0.5-s;
t->texcoords[6] = 0.5+s;
t->texcoords[7] = 0.5-c;
return 0;
}
int texture_SetTiling(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
t->isTiled = lua_toboolean(lua,2);
return 0;
}
int region_EnableClamping(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
bool clamped = lua_toboolean(lua,2); //!lua_isnil(lua,2);
region->isClamped = clamped;
return 0;
}
int region_RegionOverlap(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
urAPI_Region_t* region2 = checkregion(lua,2);
if( region->left < region2->right &&
region2->left < region->right &&
region->bottom < region2->top &&
region2->bottom < region->top)
{
lua_pushboolean(lua, true);
return 1;
}
return 0;
}
int texture_SetTexCoordModifiesRect(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
bool modifyrect = lua_toboolean(lua,2); //!lua_isnil(lua,2);
t->modifyRect = modifyrect;
return 0;
}
int texture_TexCoordModifiesRect(lua_State* lua)
{
urAPI_Texture_t* t= checktexture(lua, 1);
lua_pushboolean(lua, t->modifyRect);
return 1;
}
int texture_SetDesaturated(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
bool isDesaturated = lua_toboolean(lua,2); //!lua_isnil(lua,2);
t->isDesaturated = isDesaturated;
return 0;
}
int texture_IsDesaturated(lua_State* lua)
{
urAPI_Texture_t* t= checktexture(lua, 1);
lua_pushboolean(lua, t->isDesaturated);
return 1;
}
const char BLENDSTR_DISABLED[] = "DISABLED";
const char BLENDSTR_BLEND[] = "BLEND";
const char BLENDSTR_ALPHAKEY[] = "ALPHAKEY";
const char BLENDSTR_ADD[] = "ADD";
const char BLENDSTR_MOD[] = "MOD";
const char BLENDSTR_SUB[] = "SUB";
int texture_SetBlendMode(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
const char* blendmode = luaL_checkstring(lua, 2);
if(!strcmp(blendmode, BLENDSTR_DISABLED))
t->blendmode = BLEND_DISABLED;
else if(!strcmp(blendmode, BLENDSTR_BLEND))
t->blendmode = BLEND_BLEND;
else if(!strcmp(blendmode, BLENDSTR_ALPHAKEY))
t->blendmode = BLEND_ALPHAKEY;
else if(!strcmp(blendmode, BLENDSTR_ADD))
t->blendmode = BLEND_ADD;
else if(!strcmp(blendmode, BLENDSTR_MOD))
t->blendmode = BLEND_MOD;
else if(!strcmp(blendmode, BLENDSTR_SUB))
t->blendmode = BLEND_SUB;
else
{
// NYI unknown blend
}
return 0;
}
int texture_BlendMode(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
const char* returnstr;
switch(t->blendmode)
{
case BLEND_DISABLED:
returnstr = BLENDSTR_DISABLED;
break;
case BLEND_BLEND:
returnstr = BLENDSTR_BLEND;
break;
case BLEND_ALPHAKEY:
returnstr = BLENDSTR_ALPHAKEY;
break;
case BLEND_ADD:
returnstr = BLENDSTR_ADD;
break;
case BLEND_MOD:
returnstr = BLENDSTR_MOD;
break;
case BLEND_SUB:
returnstr = BLENDSTR_SUB;
break;
default:
luaL_error(lua, "Bogus blend mode found! Please report.");
return 0; // Error, unknown event
// returnstr = BLENDSTR_DISABLED; // This should never happen!! Error case NYI
break;
}
lua_pushstring(lua, returnstr);
return 1;
}
void drawLineToTexture(urAPI_Texture_t *texture, float startx, float starty, float endx, float endy);
int texture_Line(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float startx = luaL_checknumber(lua, 2);
float starty = luaL_checknumber(lua, 3);
float endx = luaL_checknumber(lua, 4);
float endy = luaL_checknumber(lua, 5);
if(t->backgroundTex != nil)
drawLineToTexture(t, startx, starty, endx, endy);
return 0;
}
void drawEllipseToTexture(urAPI_Texture_t *texture, float x, float y, float w, float h);
int texture_Ellipse(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x = luaL_checknumber(lua, 2);
float y = luaL_checknumber(lua, 3);
float w = luaL_checknumber(lua, 4);
float h = luaL_checknumber(lua, 5);
if(t->backgroundTex != nil)
drawEllipseToTexture(t, x, y, w, h);
return 0;
}
void drawQuadToTexture(urAPI_Texture_t *texture, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4);
int texture_Quad(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x1 = luaL_checknumber(lua, 2);
float y1 = luaL_checknumber(lua, 3);
float x2 = luaL_checknumber(lua, 4);
float y2 = luaL_checknumber(lua, 5);
float x3 = luaL_checknumber(lua, 6);
float y3 = luaL_checknumber(lua, 7);
float x4 = luaL_checknumber(lua, 8);
float y4 = luaL_checknumber(lua, 9);
if(t->backgroundTex != nil)
drawQuadToTexture(t, x1, y1, x2, y2, x3, y3, x4, y4);
return 0;
}
int texture_Rect(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x = luaL_checknumber(lua, 2);
float y = luaL_checknumber(lua, 3);
float w = luaL_checknumber(lua, 4);
float h = luaL_checknumber(lua, 5);
if(t->backgroundTex != nil)
drawQuadToTexture(t, x, y, x+w, y, x+w, y+h, x, y+h);
return 0;
}
int texture_SetFill(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
bool fill = lua_toboolean(lua,2); //!lua_isnil(lua,2);
t->fill = fill;
return 0;
}
void clearTexture(urTexture* t, float r, float g, float b, float a);
int texture_Clear(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float r = 0.0;
float g = 0.0;
float b = 0.0;
float a = 1.0;
if(lua_gettop(lua)>3)
{
r = luaL_checknumber(lua, 2)/255.0;
g = luaL_checknumber(lua, 3)/255.0;
b = luaL_checknumber(lua, 4)/255.0;
}
if(lua_gettop(lua)==5)
{
a = luaL_checknumber(lua, 5)/255.0;
}
if(t->backgroundTex == nil && t->texturepath != TEXTURE_SOLID)
instantiateTexture(t->region);
if(t->backgroundTex != nil)
clearTexture(t->backgroundTex,r,g,b,a);
return 0;
}
int texture_Width(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->width);
return 1;
}
int texture_Height(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
lua_pushnumber(lua, t->height);
return 1;
}
void ClearBrushTexture();
int texture_ClearBrush(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
delete t->backgroundTex;
t->backgroundTex = nil;
ClearBrushTexture();
}
void drawPointToTexture(urAPI_Texture_t *texture, float x, float y);
int texture_Point(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float x = luaL_checknumber(lua, 2);
float y = luaL_checknumber(lua, 3);
if(t->backgroundTex != nil)
drawPointToTexture(t, x, y);
return 0;
}
void SetBrushSize(float size);
int texture_SetBrushSize(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float size = luaL_checknumber(lua, 2);
SetBrushSize(size);
return 0;
}
int texture_SetBrushColor(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float vertR = luaL_checknumber(lua, 2);
float vertG = luaL_checknumber(lua, 3);
float vertB = luaL_checknumber(lua, 4);
float vertA = 255;
if(lua_gettop(lua)==5)
vertA = luaL_checknumber(lua, 5);
t->texturebrushcolor[0] = vertR;
t->texturebrushcolor[1] = vertG;
t->texturebrushcolor[2] = vertB;
t->texturebrushcolor[3] = vertA;
return 0;
}
float BrushSize();
int texture_BrushSize(lua_State* lua)
{
urAPI_Texture_t* t = checktexture(lua, 1);
float size = BrushSize();
lua_pushnumber(lua, size);
return 1;
}
void SetBrushTexture(urTexture* t);
int region_UseAsBrush(lua_State* lua)
{
urAPI_Region_t* t = checkregion(lua, 1);
if(t->texture->backgroundTex == nil && t->texture->texturepath != TEXTURE_SOLID)
instantiateTexture(t);
SetBrushTexture(t->texture->backgroundTex);
return 0;
}
int textlabel_Font(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushstring(lua, t->font);
return 1;
}
int textlabel_SetFont(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->font = luaL_checkstring(lua,2); // NYI
return 0;
}
const char JUSTIFYH_STRING_CENTER[] = "CENTER";
const char JUSTIFYH_STRING_LEFT[] = "LEFT";
const char JUSTIFYH_STRING_RIGHT[] = "RIGHT";
const char JUSTIFYV_STRING_MIDDLE[] = "MIDDLE";
const char JUSTIFYV_STRING_TOP[] = "TOP";
const char JUSTIFYV_STRING_BOTTOM[] = "BOTTOM";
int textlabel_HorizontalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyh;
switch(t->justifyh)
{
case JUSTIFYH_CENTER:
justifyh = JUSTIFYH_STRING_CENTER;
break;
case JUSTIFYH_LEFT:
justifyh = JUSTIFYH_STRING_LEFT;
break;
case JUSTIFYH_RIGHT:
justifyh = JUSTIFYH_STRING_RIGHT;
break;
}
lua_pushstring(lua, justifyh);
return 1;
}
int textlabel_SetHorizontalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyh = luaL_checkstring(lua, 2);
if(!strcmp(justifyh, JUSTIFYH_STRING_CENTER))
t->justifyh = JUSTIFYH_CENTER;
else if(!strcmp(justifyh, JUSTIFYH_STRING_LEFT))
t->justifyh = JUSTIFYH_LEFT;
else if(!strcmp(justifyh, JUSTIFYH_STRING_RIGHT))
t->justifyh = JUSTIFYH_RIGHT;
return 0;
}
int textlabel_VerticalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyv;
switch(t->justifyv)
{
case JUSTIFYV_MIDDLE:
justifyv = JUSTIFYV_STRING_MIDDLE;
break;
case JUSTIFYV_TOP:
justifyv = JUSTIFYV_STRING_TOP;
break;
case JUSTIFYV_BOTTOM:
justifyv = JUSTIFYV_STRING_BOTTOM;
break;
}
lua_pushstring(lua, justifyv);
return 1;
}
int textlabel_SetVerticalAlign(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* justifyv = luaL_checkstring(lua, 2);
if(!strcmp(justifyv, JUSTIFYV_STRING_MIDDLE))
t->justifyv = JUSTIFYV_MIDDLE;
else if(!strcmp(justifyv, JUSTIFYV_STRING_TOP))
t->justifyv = JUSTIFYV_TOP;
else if(!strcmp(justifyv, JUSTIFYV_STRING_BOTTOM))
t->justifyv = JUSTIFYV_BOTTOM;
return 0;
}
int textlabel_SetWrap(lua_State* lua)
{
urAPI_TextLabel_t* textlabel = checktextlabel(lua,1);
const char* wrap = luaL_checkstring(lua,2);
if(wrap)
{
textlabel->wrap = textlabel_wrap2index(wrap);
}
return 0;
}
int textlabel_Wrap(lua_State* lua)
{
urAPI_TextLabel_t* textlabel = checktextlabel(lua,1);
lua_pushstring(lua, textlabel_wrapindex2str(textlabel->wrap));
return 1;
}
int textlabel_ShadowColor(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->shadowcolor[0]);
lua_pushnumber(lua, t->shadowcolor[1]);
lua_pushnumber(lua, t->shadowcolor[2]);
lua_pushnumber(lua, t->shadowcolor[3]);
return 4;
}
int textlabel_SetShadowColor(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->shadowcolor[0] = luaL_checknumber(lua,2);
t->shadowcolor[1] = luaL_checknumber(lua,3);
t->shadowcolor[2] = luaL_checknumber(lua,4);
t->shadowcolor[3] = luaL_checknumber(lua,5);
t->drawshadow = true;
t->updatestring = true;
return 0;
}
int textlabel_ShadowOffset(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->shadowoffset[0]);
lua_pushnumber(lua, t->shadowoffset[1]);
return 2;
}
int textlabel_SetShadowOffset(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->shadowoffset[0] = luaL_checknumber(lua,2);
t->shadowoffset[1] = luaL_checknumber(lua,3);
t->updatestring = true;
return 0;
}
int textlabel_ShadowBlur(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->shadowblur);
return 1;
}
int textlabel_SetShadowBlur(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->shadowblur = luaL_checknumber(lua,2);
t->updatestring = true;
return 0;
}
int textlabel_Spacing(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->linespacing);
return 1;
}
int textlabel_SetSpacing(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->linespacing = luaL_checknumber(lua,2);
return 0;
}
int textlabel_Color(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->textcolor[0]);
lua_pushnumber(lua, t->textcolor[1]);
lua_pushnumber(lua, t->textcolor[2]);
lua_pushnumber(lua, t->textcolor[3]);
return 4;
}
int textlabel_SetColor(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->textcolor[0] = luaL_checknumber(lua,2);
t->textcolor[1] = luaL_checknumber(lua,3);
t->textcolor[2] = luaL_checknumber(lua,4);
t->textcolor[3] = luaL_checknumber(lua,5);
return 0;
}
int textlabel_Height(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->stringheight); // NYI
return 1;
}
int textlabel_Width(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushnumber(lua, t->stringwidth); // NYI
return 1;
}
int textlabel_SetLabelHeight(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->textheight = luaL_checknumber(lua,2);
return 0;
}
int textlabel_Label(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
lua_pushstring(lua, t->text);
return 1;
}
int textlabel_SetLabel(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* text = luaL_checkstring(lua,2);
if(t->text != NULL && t->text != textlabel_empty)
free(t->text);
t->text = (char*)malloc(strlen(text)+1);
strcpy(t->text, text);
t->updatestring = true;
return 0;
}
int textlabel_SetFormattedText(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
const char* text = luaL_checkstring(lua,2);
if(t->text != NULL && t->text != textlabel_empty)
free(t->text);
t->text = (char*)malloc(strlen(text)+1);
strcpy(t->text, text);
// NYI
return 0;
}
int textlabel_SetRotation(lua_State* lua)
{
urAPI_TextLabel_t* t = checktextlabel(lua, 1);
t->rotation = luaL_checknumber(lua,2);
return 0;
}
static const struct luaL_reg textlabelfuncs [] =
{
{"Font", textlabel_Font},
{"HorizontalAlign", textlabel_HorizontalAlign},
{"VerticalAlign", textlabel_VerticalAlign},
{"ShadowColor", textlabel_ShadowColor},
{"ShadowOffset", textlabel_ShadowOffset},
{"ShadowBlur", textlabel_ShadowBlur},
{"Spacing", textlabel_Spacing},
{"Color", textlabel_Color},
{"SetFont", textlabel_SetFont},
{"SetHorizontalAlign", textlabel_SetHorizontalAlign},
{"SetVerticalAlign", textlabel_SetVerticalAlign},
{"SetShadowColor", textlabel_SetShadowColor},
{"SetShadowOffset", textlabel_SetShadowOffset},
{"SetShadowBlur", textlabel_SetShadowBlur},
{"SetSpacing", textlabel_SetSpacing},
{"SetColor", textlabel_SetColor},
{"Height", textlabel_Height},
{"Width", textlabel_Width},
{"Label", textlabel_Label},
{"SetFormattedText", textlabel_SetFormattedText},
{"SetWrap", textlabel_SetWrap},
{"Wrap", textlabel_Wrap},
{"SetLabel", textlabel_SetLabel},
{"SetLabelHeight", textlabel_SetLabelHeight},
{"SetRotation", textlabel_SetRotation},
{NULL, NULL}
};
int texture_gc(lua_State* lua)
{
urAPI_Texture_t* region = checktexture(lua,1);
int a = 0;
return 0;
}
static const struct luaL_reg texturefuncs [] =
{
{"SetTexture", texture_SetTexture},
// {"SetGradient", texture_SetGradient},
{"SetGradientColor", texture_SetGradientColor},
{"Texture", texture_Texture},
{"SetSolidColor", texture_SetSolidColor},
{"SolidColor", texture_SolidColor},
{"SetTexCoord", texture_SetTexCoord},
{"TexCoord", texture_TexCoord},
{"SetRotation", texture_SetRotation},
{"SetTexCoordModifiesRect", texture_SetTexCoordModifiesRect},
{"TexCoordModifiesRect", texture_TexCoordModifiesRect},
{"SetDesaturated", texture_SetDesaturated},
{"IsDesaturated", texture_IsDesaturated},
{"SetBlendMode", texture_SetBlendMode},
{"BlendMode", texture_BlendMode},
{"Line", texture_Line},
{"Point", texture_Point},
{"Ellipse", texture_Ellipse},
{"Quad", texture_Quad},
{"Rect", texture_Rect},
{"Clear", texture_Clear},
{"ClearBrush", texture_ClearBrush},
{"SetFill", texture_SetFill},
{"SetBrushSize", texture_SetBrushSize},
{"BrushSize", texture_BrushSize},
{"SetBrushColor", texture_SetBrushColor},
{"SetTiling", texture_SetTiling},
{"Width", texture_Width},
{"Height", texture_Height},
// {"__gc", texture_gc},
{NULL, NULL}
};
int region_gc(lua_State* lua)
{
urAPI_Region_t* region = checkregion(lua,1);
int a = 0;
return 0;
}
static const struct luaL_reg regionfuncs [] =
{
{"EnableMoving", region_EnableMoving},
{"EnableResizing", region_EnableResizing},
{"Handle", region_Handle},
{"SetHeight", region_SetHeight},
{"SetWidth", region_SetWidth},
{"Show", region_Show},
{"Hide", region_Hide},
{"EnableInput", region_EnableInput},
{"EnableHorizontalScroll", region_EnableHorizontalScroll},
{"EnableVerticalScroll", region_EnableVerticalScroll},
{"SetAnchor", region_SetAnchor},
{"SetLayer", region_SetLayer},
{"Parent", region_Parent},
{"Children", region_Children},
{"Name", region_Name},
{"Bottom", region_Bottom},
{"Center", region_Center},
{"Height", region_Height},
{"Left", region_Left},
{"NumAnchors", region_NumAnchors},
{"Anchor", region_Anchor},
{"Right", region_Right},
{"Top", region_Top},
{"Width", region_Width},
{"IsShown", region_IsShown},
{"IsVisible", region_IsVisible},
{"SetParent", region_SetParent},
{"SetAlpha", region_SetAlpha},
{"Alpha", region_Alpha},
{"Layer", region_Layer},
{"Texture", region_Texture},
{"TextLabel", region_TextLabel},
// NEW!!
{"Lower", region_Lower},
{"Raise", region_Raise},
{"IsToplevel", region_IsToplevel},
{"MoveToTop", region_MoveToTop},
{"EnableClamping", region_EnableClamping},
// ENDNEW!!
{"RegionOverlap", region_RegionOverlap},
{"UseAsBrush", region_UseAsBrush},
{"EnableClipping", region_EnableClipping},
{"SetClipRegion", region_SetClipRegion},
{"ClipRegion", region_ClipRegion},
{"__gc", region_gc},
{NULL, NULL}
};
static const luaL_reg regionmetas[] = {
{"__gc", region_gc},
{0, 0}
};
void addChild(urAPI_Region_t *parent, urAPI_Region_t *child)
{
if(parent->firstchild == NULL)
parent->firstchild = child;
else
{
urAPI_Region_t *findlast = parent->firstchild;
while(findlast->nextchild != NULL)
{
findlast = findlast->nextchild;
}
if(findlast->nextchild != child)
findlast->nextchild = child;
}
}
void removeChild(urAPI_Region_t *parent, urAPI_Region_t *child)
{
if(parent->firstchild != NULL)
{
if(parent->firstchild == child)
{
parent->firstchild = parent->firstchild->nextchild;
}
else
{
urAPI_Region_t *findlast = parent->firstchild;
while(findlast->nextchild != NULL && findlast->nextchild != child)
{
findlast = findlast->nextchild;
}
if(findlast->nextchild == child)
{
findlast->nextchild = findlast->nextchild->nextchild;
child->nextchild = NULL;
}
else
{
int a = 0;
}
}
}
}
static int l_Region(lua_State *lua)
{
const char *regiontype = NULL;
const char *regionName = NULL;
urAPI_Region_t *parentRegion = NULL;
if(lua_gettop(lua)>0) // Allow for no arg construction
{
regiontype = luaL_checkstring(lua, 1);
regionName = luaL_checkstring(lua, 2);
// urAPI_Region_t *parentRegion = (urAPI_Region_t*)luaL_checkudata(lua, 4, "URAPI.region");
luaL_checktype(lua, 3, LUA_TTABLE);
lua_rawgeti(lua, 3, 0);
parentRegion = (urAPI_Region_t*)lua_touserdata(lua,4);
luaL_argcheck(lua, parentRegion!= NULL, 4, "'region' expected");
// const char *inheritsRegion = luaL_checkstring(lua, 1); //NYI
}
else
{
parentRegion = UIParent;
}
// NEW!! Return region in a table at index 0
lua_newtable(lua);
luaL_register(lua, NULL, regionfuncs);
// urAPI_Region_t *myregion = (urAPI_Region_t*)lua_newuserdata(lua, sizeof(urAPI_Region_t)); // User data is our value
urAPI_Region_t *myregion = (urAPI_Region_t*)malloc(sizeof(urAPI_Region_t)); // User data is our value
lua_pushlightuserdata(lua, myregion);
// luaL_register(lua, NULL, regionmetas);
// luaL_openlib(lua, 0, regionmetas, 0); /* fill metatable */
lua_rawseti(lua, -2, 0); // Set this to index 0
myregion->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myregion->tableref);
lua_pushliteral(lua, "__gc"); /* mutex destructor */
lua_pushcfunction(lua, region_gc);
lua_rawset(lua, -3);
// ENDNEW!!
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myregion->next = nil;
myregion->parent = parentRegion;
myregion->firstchild = NULL;
myregion->nextchild = NULL;
// addChild(parentRegion, myregion);
// myregion->name = regionName; // NYI
// Link it into the global region list
myregion->name = regionName;
myregion->type = regiontype;
myregion->ofsx = 0.0;
myregion->ofsy = 0.0;
myregion->width = 160.0;
myregion->height = 160.0;
myregion->bottom = 1.0;
myregion->left = 1.0;
myregion->top = myregion->bottom + myregion->height;
myregion->right = myregion->left + myregion->width;
myregion->cx = 80.0;
myregion->cy = 80.0;
myregion->ofsx = 0.0;
myregion->ofsy = 0.0;
myregion->clipleft = 0.0;
myregion->clipbottom = 0.0;
myregion->clipwidth = SCREEN_WIDTH;
myregion->clipheight = SCREEN_HEIGHT;
myregion->alpha = 1.0;
myregion->isMovable = false;
myregion->isResizable = false;
myregion->isTouchEnabled = false;
myregion->isScrollXEnabled = false;
myregion->isScrollYEnabled = false;
myregion->isVisible = false;
myregion->isDragged = false;
myregion->isClamped = false;
myregion->isClipping = false;
myregion->entered = false;
myregion->strata = STRATA_PARENT;
myregion->OnDragStart = 0;
myregion->OnDragStop = 0;
myregion->OnEnter = 0;
myregion->OnEvent = 0;
myregion->OnHide = 0;
myregion->OnLeave = 0;
myregion->OnTouchDown = 0;
myregion->OnTouchUp = 0;
myregion->OnShow = 0;
myregion->OnShow = 0;
myregion->OnSizeChanged = 0; // needs args (NYI)
myregion->OnUpdate = 0;
myregion->OnDoubleTap = 0; // (UR!)
// All UR!
myregion->OnAccelerate = 0;
myregion->OnNetIn = 0;
myregion->OnNetConnect = 0;
myregion->OnNetDisconnect = 0;
#ifdef SANDWICH_SUPPORT
myregion->OnPressure = 0;
#endif
myregion->OnHeading = 0;
myregion->OnLocation = 0;
myregion->OnMicrophone = 0;
myregion->OnHorizontalScroll = 0;
myregion->OnVerticalScroll = 0;
myregion->OnPageEntered = 0;
myregion->OnPageLeft = 0;
myregion->texture = NULL;
myregion->textlabel = NULL;
myregion->point = NULL;
myregion->relativePoint = NULL;
myregion->relativeRegion = NULL;
myregion->page = currentPage;
if(firstRegion[currentPage] == nil) // first region ever
{
firstRegion[currentPage] = myregion;
lastRegion[currentPage] = myregion;
myregion->next = NULL;
myregion->prev = NULL;
}
else
{
myregion->prev = lastRegion[currentPage];
lastRegion[currentPage]->next = myregion;
lastRegion[currentPage] = myregion;
l_setstrataindex(myregion , myregion->strata);
}
// NEW!!
numRegions[currentPage] ++;
// ENDNEW!!
setParent(myregion, parentRegion);
return 1;
}
int flowbox_Name(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushstring(lua, fb->object->name);
return 1;
}
// Object to to PushOut from.
// In to PushOut into.
// Needs ID on specific IN
int flowbox_SetPushLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int outindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int inindex = luaL_checknumber(lua, 4);
if(outindex >= fb->object->nr_outs || inindex >= target->object->nr_ins)
{
return 0;
}
fb->object->AddPushOut(outindex, &target->object->ins[inindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_SetPullLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int inindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int outindex = luaL_checknumber(lua, 4);
if(inindex >= fb->object->nr_ins || outindex >= target->object->nr_outs)
{
return 0;
}
fb->object->AddPullIn(inindex, &target->object->outs[outindex]);
if(!strcmp(fb->object->name,dacobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveDacTickSinkList.AddSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,visobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveVisTickSinkList.AddSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,netobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveNetTickSinkList.AddSink(&target->object->outs[outindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_IsPushed(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int outindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int inindex = luaL_checknumber(lua, 4);
if(outindex >= fb->object->nr_outs || inindex >= target->object->nr_ins)
{
return 0;
}
if(fb->object->IsPushedOut(outindex, &target->object->ins[inindex]))
{
lua_pushboolean(lua,1);
return 1;
}
else
return 0;
}
int flowbox_IsPulled(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int inindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int outindex = luaL_checknumber(lua, 4);
if(inindex >= fb->object->nr_ins || outindex >= target->object->nr_outs)
{
return 0;
}
if(fb->object->IsPulledIn(inindex, &target->object->outs[outindex]))
{
lua_pushboolean(lua, 1);
return 1;
}
else
return 0;
}
int flowbox_RemovePushLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int outindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int inindex = luaL_checknumber(lua, 4);
if(outindex >= fb->object->nr_outs || inindex >= target->object->nr_ins)
{
return 0;
}
fb->object->RemovePushOut(outindex, &target->object->ins[inindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_RemovePullLink(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int inindex = luaL_checknumber(lua,2);
ursAPI_FlowBox_t* target = checkflowbox(lua, 3);
int outindex = luaL_checknumber(lua, 4);
if(inindex >= fb->object->nr_ins || outindex >= target->object->nr_outs)
{
return 0;
}
fb->object->RemovePullIn(inindex, &target->object->outs[outindex]);
if(!strcmp(fb->object->name,dacobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveDacTickSinkList.RemoveSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,visobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveVisTickSinkList.RemoveSink(&target->object->outs[outindex]);
if(!strcmp(fb->object->name,netobject->name)) // This is hacky and should be done differently. Namely in the sink pulling
urActiveNetTickSinkList.RemoveSink(&target->object->outs[outindex]);
lua_pushboolean(lua, 1);
return 1;
}
int flowbox_IsPushing(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int index = luaL_checknumber(lua,2);
lua_pushboolean(lua, fb->object->firstpullin[index]!=NULL);
return 1;
}
int flowbox_IsPulling(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int index = luaL_checknumber(lua,2);
lua_pushboolean(lua, fb->object->firstpushout[index]!=NULL);
return 1;
}
int flowbox_IsPlaced(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int index = luaL_checknumber(lua,2);
lua_pushboolean(lua, fb->object->ins[index].isplaced);
return 1;
}
int flowbox_NumIns(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->nr_ins);
return 1;
}
int flowbox_NumOuts(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->nr_outs);
return 1;
}
int flowbox_Ins(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int nrins = fb->object->lastin;
for(int j=0; j< nrins; j++)
// if(fb->object->ins[j].name!=(void*)0x1)
lua_pushstring(lua, fb->object->ins[j].name);
// else {
// int a=2;
// }
return nrins;
}
int flowbox_Outs(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
int nrouts = fb->object->lastout;
for(int j=0; j< nrouts; j++)
lua_pushstring(lua, fb->object->outs[j].name);
return nrouts;
}
int flowbox_Push(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
float indata = luaL_checknumber(lua, 2);
fb->object->CallAllPushOuts(indata);
/* if(fb->object->firstpushout[0]!=NULL)
{
ursObject* inobject;
urSoundPushOut* pushto = fb->object->firstpushout[0];
for(;pushto!=NULL; pushto = pushto->next)
{
urSoundIn* in = pushto->in;
inobject = in->object;
in->inFuncTick(inobject, indata);
}
}*/
// callAllPushSources(indata);
return 0;
}
int flowbox_Pull(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
float indata = luaL_checknumber(lua, 2);
fb->object->CallAllPushOuts(indata);
return 0;
}
extern double visoutdata;
int flowbox_Get(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
// float indata = luaL_checknumber(lua, 2);
lua_pushnumber(lua, visoutdata);
return 1;
}
int flowbox_AddFile(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
const char* filename = luaL_checkstring(lua, 2);
if(!strcmp(fb->object->name, "Sample"))
{
Sample_AddFile(fb->object, filename);
}
}
int flowbox_IsInstantiable(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushboolean(lua, !fb->object->noninstantiable);
return 1;
}
int flowbox_InstanceNumber(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->instancenumber);
return 1;
}
int flowbox_NumberInstances(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushnumber(lua, fb->object->instancelist->Last());
return 1;
}
int flowbox_Couple(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
if(fb->object->iscoupled)
{
lua_pushnumber(lua, fb->object->couple_in);
lua_pushnumber(lua, fb->object->couple_out);
return 2;
}
else
return 0;
}
int flowbox_IsCoupled(lua_State *lua)
{
ursAPI_FlowBox_t* fb = checkflowbox(lua, 1);
lua_pushboolean(lua, fb->object->iscoupled);
return 1;
}
// Methods table for the flowbox API
static const struct luaL_reg flowboxfuncs [] =
{
{"Name", flowbox_Name},
{"NumIns", flowbox_NumIns},
{"NumOuts", flowbox_NumOuts},
{"Ins", flowbox_Ins},
{"Outs", flowbox_Outs},
{"SetPushLink", flowbox_SetPushLink},
{"SetPullLink", flowbox_SetPullLink},
{"RemovePushLink", flowbox_RemovePushLink},
{"RemovePullLink", flowbox_RemovePullLink},
{"IsPushed", flowbox_IsPushed},
{"IsPulled", flowbox_IsPulled},
{"Push", flowbox_Push},
{"Pull", flowbox_Pull},
{"Get", flowbox_Get},
{"AddFile", flowbox_AddFile},
{"IsInstantiable", flowbox_IsInstantiable},
{"InstanceNumber", flowbox_InstanceNumber},
{"NumberInstances", flowbox_NumberInstances},
{"Couple", flowbox_Couple},
{"IsCoupled", flowbox_IsCoupled},
{NULL, NULL}
};
static int l_FlowBox(lua_State* lua)
{
const char *flowboxtype = luaL_checkstring(lua, 1);
const char *flowboxName = luaL_checkstring(lua, 2);
// urAPI_flowbox_t *parentflowbox = (urAPI_flowbox_t*)luaL_checkudata(lua, 4, "URAPI.flowbox");
luaL_checktype(lua, 3, LUA_TTABLE);
lua_rawgeti(lua, 3, 0);
ursAPI_FlowBox_t *parentFlowBox = (ursAPI_FlowBox_t*)lua_touserdata(lua,4);
luaL_argcheck(lua, parentFlowBox!= NULL, 4, "'flowbox' expected");
// const char *inheritsflowbox = luaL_checkstring(lua, 1); //NYI
// NEW!! Return flowbox in a table at index 0
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
myflowbox->object = parentFlowBox->object->Clone();
// myflowbox->object->instancenumber = parentFlowBox->object->instancenumber + 1;
// ENDNEW!!
// luaL_getmetatable(lua, "URAPI.flowbox");
// lua_setmetatable(lua, -2);
return 1;
}
void ur_GetSoundBuffer(SInt32* buffer, int channel, int size)
{
lua_getglobal(lua,"urSoundData");
lua_rawgeti(lua, -1, channel);
if(lua_isnil(lua, -1) || !lua_istable(lua,-1)) // Channel doesn't exist or is falsely set up
{
lua_pop(lua,1);
return;
}
for(int i=0; i<size; i++)
{
lua_rawgeti(lua, -1, i+1);
if(lua_isnumber(lua, -1))
buffer[i] = lua_tonumber(lua, -1);
lua_pop(lua,1);
}
lua_pop(lua, 2);
}
int l_SourceNames(lua_State *lua)
{
int nr = urs_NumUrSourceObjects();
for(int i=0; i<nr; i++)
{
lua_pushstring(lua, urs_GetSourceObjectName(i));
}
return nr;
}
int l_ManipulatorNames(lua_State *lua)
{
int nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
lua_pushstring(lua, urs_GetManipulatorObjectName(i));
}
return nr;
}
int l_SinkNames(lua_State *lua)
{
int nr = urs_NumUrSinkObjects();
for(int i=0; i<nr; i++)
{
lua_pushstring(lua, urs_GetSinkObjectName(i));
}
return nr;
}
#ifdef ALLOW_DEFUNCT
int l_NumUrIns(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrManipulatorIns(i));
return 1;
}
}
nr = urs_NumUrSinkObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSinkObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrSinkIns(i));
return 1;
}
}
return 0;
}
int l_NumUrOuts(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrSourceObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSourceObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrSourceOuts(i));
return 1;
}
}
nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
lua_pushnumber(lua, urs_NumUrManipulatorOuts(i));
return 1;
}
}
return 0;
}
int l_GetUrIns(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
int nrins = urs_NumUrManipulatorIns(i);
for(int j=0; j< nrins; j++)
lua_pushstring(lua, urs_GetManipulatorIn(i, j));
return nrins;
}
}
nr = urs_NumUrSinkObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSinkObjectName(i)))
{
int nrins = urs_NumUrSinkIns(i);
for(int j=0; j< nrins; j++)
lua_pushstring(lua, urs_GetSinkIn(i, j));
return nrins;
}
}
return 0;
}
int l_GetUrOuts(lua_State *lua)
{
const char* obj = luaL_checkstring(lua, 1);
int nr = urs_NumUrSourceObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetSourceObjectName(i)))
{
int nrouts = urs_NumUrSourceOuts(i);
for(int j=0; j< nrouts; j++)
lua_pushstring(lua, urs_GetSourceOut(i, j));
return nrouts;
}
}
nr = urs_NumUrManipulatorObjects();
for(int i=0; i<nr; i++)
{
if(!strcmp(obj, urs_GetManipulatorObjectName(i)))
{
int nrouts = urs_NumUrManipulatorOuts(i);
for(int j=0; j< nrouts; j++)
lua_pushstring(lua, urs_GetManipulatorOut(i, j));
return nrouts;
}
}
return 0;
}
#endif
int l_SystemPath(lua_State *lua)
{
#ifdef TARGET_IPHONE
const char* filename = luaL_checkstring(lua,1);
NSString *filename2 = [[NSString alloc] initWithCString:filename];
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:filename2];
const char* filestr = [filePath UTF8String];
lua_pushstring(lua, filestr);
#else
// TODO // find system path
#endif
return 1;
}
int l_DocumentPath(lua_State *lua)
{
#ifdef TARGET_IPHONE
const char* filename = luaL_checkstring(lua,1);
NSString *filename2 = [[NSString alloc] initWithCString:filename];
NSArray *paths;
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0) {
NSString *filePath = [paths objectAtIndex:0];
NSString *resultPath = [NSString stringWithFormat:@"%@/%@", filePath, filename2];
const char* filestr = [resultPath UTF8String];
lua_pushstring(lua, filestr);
}
else
{
luaL_error(lua, "Cannot find the Document path.");
}
#else
// TODO // find document path
#endif
return 1;
}
int l_NumMaxPages(lua_State *lua)
{
int max = MAX_PAGES;
lua_pushnumber(lua, max);
return 1;
}
int l_Page(lua_State *lua)
{
lua_pushnumber(lua, currentPage+1);
return 1;
}
int l_SetPage(lua_State *lua)
{
int oldcurrent;
int num = luaL_checknumber(lua,1);
if(num >= 1 and num <= MAX_PAGES)
{
callAllOnPageLeft(num-1);
oldcurrent = currentPage;
currentPage = num-1;
callAllOnPageEntered(oldcurrent);
}
else
{
// Error!!
luaL_error(lua, "Invalid page number: %d",num);
}
return 0;
}
//------------------------------------------------------------------------------
// Register our API
//------------------------------------------------------------------------------
void l_setupAPI(lua_State *lua)
{
#ifdef TARGET_IPHONE
CGRect screendimensions = [[UIScreen mainScreen] bounds];
SCREEN_WIDTH = screendimensions.size.width;
SCREEN_HEIGHT = screendimensions.size.height;
#else
// for android, SCREEN_WIDTH and SCREEN_HEIGHT are set up in urMus.init(int,int) native function
#endif
// Set global userdata
// Create UIParent
// luaL_newmetatable(lua, "URAPI.region");
// lua_pushstring(lua, "__index");
// lua_pushvalue(lua, -2);
// lua_settable(lua, -3);
// luaL_openlib(lua, NULL, regionfuncs, 0);
lua_newtable(lua);
luaL_register(lua, NULL, regionfuncs);
// urAPI_Region_t *myregion = (urAPI_Region_t*)lua_newuserdata(lua, sizeof(urAPI_Region_t)); // User data is our value
urAPI_Region_t *myregion = (urAPI_Region_t*)malloc(sizeof(urAPI_Region_t)); // User data is our value
lua_pushlightuserdata(lua, myregion);
lua_rawseti(lua, -2, 0); // Set this to index 0
myregion->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myregion->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myregion->strata = STRATA_BACKGROUND;
myregion->parent = NULL;
myregion->top = SCREEN_HEIGHT;
myregion->bottom = 0;
myregion->left = 0;
myregion->right = SCREEN_WIDTH;
myregion->cx = SCREEN_WIDTH/2;
myregion->cy = SCREEN_HEIGHT/2;
myregion->firstchild = NULL;
myregion->point = NULL;
myregion->relativePoint = NULL;
UIParent = myregion;
lua_setglobal(lua, "UIParent");
urs_SetupObjects();
char fbname[255];
for(int source=0; source<ursourceobjectlist.Last(); source++)
{
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myflowbox->object = ursourceobjectlist[source];
FBNope = myflowbox;
strcpy(fbname, "FB");
strcat(fbname, myflowbox->object->name);
lua_setglobal(lua, fbname);
}
for(int manipulator=0; manipulator<urmanipulatorobjectlist.Last(); manipulator++)
{
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myflowbox->object = urmanipulatorobjectlist[manipulator];
FBNope = myflowbox;
strcpy(fbname, "FB");
strcat(fbname, myflowbox->object->name);
lua_setglobal(lua, fbname);
}
for(int sink=0; sink<ursinkobjectlist.Last(); sink++)
{
lua_newtable(lua);
luaL_register(lua, NULL, flowboxfuncs);
ursAPI_FlowBox_t *myflowbox = (ursAPI_FlowBox_t*)malloc(sizeof(ursAPI_FlowBox_t)); // User data is our value
lua_pushlightuserdata(lua, myflowbox);
lua_rawseti(lua, -2, 0); // Set this to index 0
myflowbox->tableref = luaL_ref(lua, LUA_REGISTRYINDEX);
lua_rawgeti(lua, LUA_REGISTRYINDEX, myflowbox->tableref);
// luaL_getmetatable(lua, "URAPI.region");
// lua_setmetatable(lua, -2);
myflowbox->object = ursinkobjectlist[sink];
FBNope = myflowbox;
strcpy(fbname, "FB");
strcat(fbname, myflowbox->object->name);
lua_setglobal(lua, fbname);
}
luaL_newmetatable(lua, "URAPI.texture");
lua_pushstring(lua, "__index");
lua_pushvalue(lua, -2);
lua_settable(lua, -3);
// luaL_openlib(lua, NULL, texturefuncs, 0);
luaL_register(lua, NULL, texturefuncs);
luaL_newmetatable(lua, "URAPI.textlabel");
lua_pushstring(lua, "__index");
lua_pushvalue(lua, -2);
lua_settable(lua, -3);
// luaL_openlib(lua, NULL, textlabelfuncs, 0);
luaL_register(lua, NULL, textlabelfuncs);
// Compats
lua_pushcfunction(lua, l_Region);
lua_setglobal(lua, "Region");
// NEW!!
lua_pushcfunction(lua, l_NumRegions);
lua_setglobal(lua, "NumRegions");
// ENDNEW!!
lua_pushcfunction(lua, l_InputFocus);
lua_setglobal(lua, "InputFocus");
lua_pushcfunction(lua, l_HasInput);
lua_setglobal(lua, "HasInput");
lua_pushcfunction(lua, l_InputPosition);
lua_setglobal(lua, "InputPosition");
lua_pushcfunction(lua, l_ScreenHeight);
lua_setglobal(lua, "ScreenHeight");
lua_pushcfunction(lua, l_ScreenWidth);
lua_setglobal(lua, "ScreenWidth");
lua_pushcfunction(lua, l_Time);
lua_setglobal(lua, "Time");
lua_pushcfunction(lua, l_RunScript);
lua_setglobal(lua, "RunScript");
lua_pushcfunction(lua,l_StartAudio);
lua_setglobal(lua,"StartAudio");
lua_pushcfunction(lua,l_PauseAudio);
lua_setglobal(lua,"PauseAudio");
// HTTP
lua_pushcfunction(lua,l_StartHTTPServer);
lua_setglobal(lua,"StartHTTPServer");
lua_pushcfunction(lua,l_StopHTTPServer);
lua_setglobal(lua,"StopHTTPServer");
lua_pushcfunction(lua,l_HTTPServer);
lua_setglobal(lua,"HTTPServer");
// UR!
lua_pushcfunction(lua, l_setanimspeed);
lua_setglobal(lua, "SetFrameRate");
lua_pushcfunction(lua, l_DPrint);
lua_setglobal(lua, "DPrint");
// URSound!
lua_pushcfunction(lua, l_SourceNames);
lua_setglobal(lua, "SourceNames");
lua_pushcfunction(lua, l_ManipulatorNames);
lua_setglobal(lua, "ManipulatorNames");
lua_pushcfunction(lua, l_SinkNames);
lua_setglobal(lua, "SinkNames");
#ifdef ALLOW_DEFUNCT
lua_pushcfunction(lua, l_NumUrIns);
lua_setglobal(lua, "NumUrIns");
lua_pushcfunction(lua, l_NumUrOuts);
lua_setglobal(lua, "NumUrOuts");
lua_pushcfunction(lua, l_GetUrIns);
lua_setglobal(lua, "GetUrIns");
lua_pushcfunction(lua, l_GetUrOuts);
lua_setglobal(lua, "GetUrOuts");
#endif
lua_pushcfunction(lua, l_FlowBox);
lua_setglobal(lua, "FlowBox");
lua_pushcfunction(lua, l_SystemPath);
lua_setglobal(lua, "SystemPath");
lua_pushcfunction(lua, l_DocumentPath);
lua_setglobal(lua, "DocumentPath");
lua_pushcfunction(lua, l_NumMaxPages);
lua_setglobal(lua, "NumMaxPages");
lua_pushcfunction(lua, l_Page);
lua_setglobal(lua, "Page");
lua_pushcfunction(lua, l_SetPage);
lua_setglobal(lua, "SetPage");
lua_pushcfunction(lua, l_FreeAllRegions);
lua_setglobal(lua, "FreeAllRegions");
// Initialize the global mic buffer table
#ifdef MIC_ARRAY
lua_newtable(lua);
lua_setglobal(lua, "urMicData");
#endif
#ifdef SOUND_ARRAY
// NOTE: SOMETHING IS WEIRD HERE. CAUSES VARIOUS BUGS IF ONE WRITES TO THIS TABLE
lua_newtable(lua);
lua_newtable(lua);
lua_rawseti(lua, -2, 1); // Setting up for stereo for now
lua_newtable(lua);
lua_rawseti(lua, -2, 2); // Can be extended to any number of channels here
lua_setglobal(lua,"urSoundData");
#endif
#ifdef TARGET_IPHONE
systimer = [MachTimer alloc];
[systimer start];
#else
systimer = new MachTimer();
systimer->start();
#endif
}
| 24.34138 | 132 | 0.694021 | jongwook |
b4ab7508b8b65363e2c87d6b37e60967ec9bd4da | 2,552 | cpp | C++ | SimpleEngine/Main.cpp | RichardBangs/SimpleEngine | a4acdf11d05e018db5a55994291475df55856c0c | [
"MIT"
] | null | null | null | SimpleEngine/Main.cpp | RichardBangs/SimpleEngine | a4acdf11d05e018db5a55994291475df55856c0c | [
"MIT"
] | null | null | null | SimpleEngine/Main.cpp | RichardBangs/SimpleEngine | a4acdf11d05e018db5a55994291475df55856c0c | [
"MIT"
] | null | null | null |
#include "glew.h"
#include "freeglut.h"
#include "glm.hpp"
#include "Path.h"
#include "Renderer\RenderableManager.h"
#include "Renderer\Camera.h"
#include "Renderer\ShaderLoader.h"
#include "Renderer\WindowManager.h"
#include "Game\InputManager.h"
#include "Game\GameManager.h"
#include <iostream>
#include <vector>
extern void SetupOpenGLWindow(int argc, char** argv);
extern void OnKeyboardInput(unsigned char key, int x, int y);
extern void OnMouseInput(int button, int state, int x, int y);
extern void OnRender();
extern void SetupScene();
extern void OnClose();
extern void OnTick(int timerId);
Game::GameManager* gameManager;
int main(int argc, char** argv)
{
SetupOpenGLWindow( argc, argv );
return 0;
}
void SetupOpenGLWindow(int argc, char** argv)
{
const int windowWidth = 1600;
const int windowHeight = 800;
const float aspectRatio = (float)windowHeight / windowWidth;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
Renderer::WindowManager::Create();
Renderer::WindowManager::Instance().InitialiseWindow(glm::vec2(100, 100), glm::vec2(windowWidth, windowHeight));
glewInit();
if (glewIsSupported("GL_VERSION_4_5"))
{
std::cout << "GLEW Version 4.5 is supported." << std::endl;
}
else
{
std::cout << "ERROR - GLEW 4.5 Not Supported" << std::endl;
int temp;
std::cin >> temp;
return;
}
glEnable(GL_DEPTH_TEST);
glutKeyboardFunc(OnKeyboardInput);
glutMouseFunc(OnMouseInput);
glutDisplayFunc(OnRender);
glutCloseFunc(OnClose);
glutTimerFunc(1, OnTick, 0);
Renderer::RenderableManager::Create();
Renderer::Camera::Create();
Renderer::Camera::Instance().Scale = glm::vec3(aspectRatio, 1.0f, 1.0f);
gameManager = new Game::GameManager();
glutMainLoop();
}
void OnKeyboardInput(unsigned char key, int x, int y)
{
Game::InputManager::Instance().OnKeyboardInput(key);
}
void OnMouseInput(int button, int state, int x, int y)
{
Game::InputManager::Instance().OnMouseInput(button, state, x, y);
}
void OnUpdate(float dt)
{
gameManager->OnUpdate( dt );
}
void OnRender()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
Renderer::RenderableManager::Instance().Render();
gameManager->OnRender();
glutSwapBuffers();
}
void OnTick(int timerId)
{
OnUpdate(1.0f/60.0f);
OnRender();
glutTimerFunc(1000 / 60, OnTick, 0);
}
void OnClose()
{
glutLeaveMainLoop();
delete gameManager;
Renderer::RenderableManager::Destroy();
Renderer::Camera::Destroy();
Renderer::ShaderLoader::DestroyAllShaders();
} | 20.580645 | 113 | 0.723354 | RichardBangs |
b4ac5ff96fde73b7daa9d1da116a7917e99ad54c | 21,270 | hpp | C++ | lib/include/base_dkg.hpp | fetchai/research-dvrf | 943b335e1733bb9b2ef403e4f8237dfdc4f93952 | [
"Apache-2.0"
] | 16 | 2020-02-08T00:04:58.000Z | 2022-01-18T11:42:07.000Z | lib/include/base_dkg.hpp | fetchai/research-dvrf | 943b335e1733bb9b2ef403e4f8237dfdc4f93952 | [
"Apache-2.0"
] | null | null | null | lib/include/base_dkg.hpp | fetchai/research-dvrf | 943b335e1733bb9b2ef403e4f8237dfdc4f93952 | [
"Apache-2.0"
] | 4 | 2021-07-20T08:56:08.000Z | 2022-01-03T01:48:12.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2019-2020 Fetch.AI Limited
//
// 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 <array>
#include <unordered_map>
#include <cstdint>
#include <cstddef>
#include <iostream>
#include <mutex>
#include "consensus.pb.h"
#include "group_signature_manager.hpp"
#include "messages.hpp"
namespace fetch {
namespace consensus {
/**
* This class implemnents defines the functions required for the DKG
*/
template<class CryptoType, class CryptoVerificationKey>
class BaseDkg {
public:
using PrivateKey = typename CryptoType::PrivateKey;
using Signature = typename CryptoType::Signature;
using GroupPublicKey = typename CryptoType::GroupPublicKey;
using VerificationKey = CryptoVerificationKey;
using MessagePayload = std::string;
struct DkgOutput {
GroupPublicKey groupPublicKey;
std::vector<VerificationKey> publicKeyShares;
PrivateKey privateKey;
DkgOutput(GroupPublicKey groupPublicKey1, std::vector<VerificationKey> publicKeyShares1,
const PrivateKey &privateKey1)
: groupPublicKey{std::move(groupPublicKey1)}, publicKeyShares{std::move(publicKeyShares1)},
privateKey{privateKey1} {}
};
BaseDkg(uint32_t committeeSize, uint32_t threshold) : committeeSize_{committeeSize}, polynomialDegree_{threshold - 1},
groupSignatureManager_{threshold} {
static bool once = []() {
CryptoType::initCrypto();
return true;
}();
CryptoType::setGenerators(this->G, this->H);
if (!once) {
std::cerr << "Node::initPairing failed.\n"; // just to eliminate warnings from the compiler.
}
this->publicKeyShares_.resize(this->committeeSize_);
init(this->C_ik_, this->committeeSize_, this->polynomialDegree_ + 1);
init(this->A_ik_, this->committeeSize_, this->polynomialDegree_ + 1);
init(this->s_ij_, this->committeeSize_, this->committeeSize_);
init(this->sprime_ij_, this->committeeSize_, this->committeeSize_);
init(this->g__s_ij_, this->committeeSize_, this->committeeSize_);
}
virtual ~BaseDkg() = default;
virtual std::pair<fetch::consensus::pb::Broadcast, std::vector<fetch::consensus::pb::PrivateShares>>
createCoefficientsAndShares(uint32_t rank) = 0;
virtual void computeQualCoefficient(fetch::consensus::pb::Broadcast_Coefficients &coefs, uint32_t rank) = 0;
virtual bool setQualCoefficient(uint32_t from, uint32_t i, const std::string &coef) = 0;
virtual bool verifyQualCoefficient(uint32_t rank, uint32_t i) const = 0;
virtual std::pair<bool, bool> verifyQualComplaint(uint32_t nodeIndex, uint32_t fromIndex, const std::string &first,
const std::string &second) = 0;
virtual bool runReconstruction(const std::unordered_map<std::string, uint32_t> &nodesMap) = 0;
virtual void
computePublicKeys(const std::set<std::string> &qual, const std::unordered_map<std::string, uint32_t> &nodesMap) = 0;
virtual SignaturesShare getSignatureShare(const MessagePayload &message, uint32_t rank) = 0;
virtual bool
addSignatureShare(const fetch::consensus::pb::Gossip_SignatureShare &share_msg, uint32_t miner_index) = 0;
/**
* Adds new shares from another DKG member
*
* @param from Index of the sender
* @param rank Our index
* @param shares The private shares message received from the sender
* @return bool indicating whether the shares deserialised correctly
*/
bool setShare(uint32_t from, uint32_t rank, const fetch::consensus::pb::PrivateShares &shares) {
return s_ij_[from][rank].assign(shares.first()) && sprime_ij_[from][rank].assign(shares.second());
}
/**
* Add new coeffcients
*
* @param from Index of the sender
* @param i Index in vector of coefficients
* @param coef Value of coefficient vector at index i as string
* @return bool indicating whether coefficient deserialised correctly
*/
bool setCoefficient(uint32_t from, uint32_t i, const std::string &coef) {
if (C_ik_[from][i].isZero()) {
return C_ik_[from][i].assign(coef);
}
return false;
}
/**
* Checks coefficients broadcasted by cabinet member c_i is consistent with the secret shares
* received from c_i. If false then add to complaints
*
* @return Set of muddle addresses of nodes we complain against
*/
std::set<std::string> computeComplaints(const std::set<std::string> &miners, uint32_t rank) {
std::set<std::string> complaints_local;
uint32_t i = 0;
for (auto &miner : miners) {
if (i != rank) {
if (!C_ik_[i][0].isZero() && !s_ij_[i][rank].isZero()) {
VerificationKey rhs, lhs;
lhs = computeLHS(g__s_ij_[i][rank], G, H, s_ij_[i][rank], sprime_ij_[i][rank]);
rhs = computeRHS(rank, C_ik_[i]);
if (lhs != rhs)
complaints_local.insert(miner);
} else {
complaints_local.insert(miner);
}
}
++i;
}
return complaints_local;
}
/**
* Broadcast private shares after processing complaints
*
* @param shares Shares msg to be broadcasted
* @param reporter String id of the complaint filer
* @param from Owner of original shares
* @param to Recipient of original shares
*/
void broadcastShare(fetch::consensus::pb::Broadcast_Shares &shares, const std::string &reporter,
uint32_t from, uint32_t to) const {
shares.add_first(s_ij_[from][to].toString());
shares.add_second(sprime_ij_[from][to].toString());
shares.add_reporter(reporter);
}
/**
* Verify private shares received
*
* @param reporterIndex Index of member filing complaint
* @param fromIndex Index of the sender of the shares
* @param rank Our index
* @param first First share as string
* @param second Second share as string
* @return bool for whether the shares pass verification with broadcasted coefficients
*/
bool verifyShare(uint32_t reporterIndex, uint32_t fromIndex, uint32_t rank, const std::string &first,
const std::string &second) {
PrivateKey s, sprime;
VerificationKey lhsG, rhsG;
if (s.assign(first) && sprime.assign(second)) {
rhsG = computeRHS(reporterIndex, C_ik_[fromIndex]);
lhsG = computeLHS(G, H, s, sprime);
if (lhsG == rhsG) {
if (reporterIndex == rank) {
s_ij_[fromIndex][rank] = s;
sprime_ij_[fromIndex][rank] = sprime;
g__s_ij_[fromIndex][rank].setZero();
g__s_ij_[fromIndex][rank].mult(G, s_ij_[fromIndex][rank]);
}
return true;
}
return false;
}
return false;
}
/**
* Compute own private key
*
* @param rank Our index
* @param quals Indices of qualified members
*/
void computePrivateKey(uint32_t rank, const std::vector<uint32_t> &quals) {
std::lock_guard<std::mutex> lock(mutex_);
privateKey_.setZero();
xprime_i_.setZero();
for (auto &iq_index : quals) {
privateKey_.add(privateKey_, s_ij_[iq_index][rank]);
xprime_i_.add(xprime_i_, sprime_ij_[iq_index][rank]);
}
}
/**
* Inserting reconstruction shares
*
* @param id String id of member being reconstructed
* @param index Index of member being reconstructed
* @param rank Our index
*/
void newReconstructionShare(const std::string &id, uint32_t index, uint32_t rank) {
std::lock_guard<std::mutex> lock(mutex_);
if (reconstructionShares_.find(id) == reconstructionShares_.end()) {
reconstructionShares_.insert({id, {{}, std::vector<PrivateKey>(committeeSize_)}});
}
reconstructionShares_.at(id).first.insert(rank);
reconstructionShares_.at(id).second[rank] = s_ij_[index][rank];
}
/**
* Verify reconstruction shares received
*
* @param nodeIndex Index of node who is being reconstructed
* @param fromIndex Index of the sender of the shares
* @param reporter Index of the person filing complaint
* @param first First secret share as string
* @param second Second secret share as string
*/
void verifyReconstructionShare(uint32_t nodeIndex, uint32_t fromIndex, const std::string &reporter,
const std::string &first,
const std::string &second) {
std::lock_guard<std::mutex> lock(mutex_);
VerificationKey lhs, rhs;
PrivateKey s, sprime;
if (s.assign(first) and sprime.assign(second)) {
lhs = computeLHS(G, H, s, sprime);
rhs = computeRHS(fromIndex, C_ik_[nodeIndex]);
bool check = lhs == rhs;
if (check) {
if (reconstructionShares_.find(reporter) == reconstructionShares_.end()) {
reconstructionShares_.insert(
{reporter, {{}, std::vector<PrivateKey>(committeeSize_)}});
} else if (reconstructionShares_.at(reporter).second[fromIndex].isZero()) {
return;
}
reconstructionShares_.at(reporter).first.insert(fromIndex); // good share received
reconstructionShares_.at(reporter).second[fromIndex] = s;
}
}
}
std::string computeGroupSignature(const MessagePayload &message) {
std::lock_guard<std::mutex> lock(mutex_);
assert(groupSignatureManager_.numSignatureShares(message) > polynomialDegree_);
Signature sig{lagrangeInterpolation(groupSignatureManager_.signatureShares(message))};
groupSignatureManager_.addSignedMessage(message, sig);
return sig.toString();
}
void setDkgOutput(const DkgOutput &output) {
std::lock_guard<std::mutex> lock(mutex_);
groupPublicKey_ = output.groupPublicKey;
privateKey_ = output.privateKey;
for (size_t i = 0; i < publicKeyShares_.size(); i++) {
publicKeyShares_[i] = output.publicKeyShares[i];
}
}
/// Getter functions
/// @{
std::string groupPublicKey() const {
if (groupPublicKey_.isZero()) {
return "";
}
return groupPublicKey_.toString();
}
std::vector<std::string> publicKeyShares() const {
std::vector<std::string> public_key_shares;
for (uint32_t i = 0; i < committeeSize_; ++i) {
assert(!publicKeyShares_[i].isZero());
public_key_shares.push_back(publicKeyShares_[i].toString());
assert(!public_key_shares[i].empty());
}
return public_key_shares;
}
/// @}
/// Threshold Signing Methods
/// @{
std::string groupSignature(const MessagePayload &message) const {
return groupSignatureManager_.groupSignature(message);
}
bool groupSignatureCompleted(const MessagePayload &message) const {
return groupSignatureManager_.signatureCompleted(message);
}
size_t numSignatureShares(const MessagePayload &message) const {
return groupSignatureManager_.numSignatureShares(message);
}
bool isFinished(const MessagePayload &message) const {
return groupSignatureManager_.numSignatureShares(message) > polynomialDegree_;
}
/// @}
static void initCrypto() {
CryptoType::initCrypto();
}
template<class Generator>
static void setGenerator(Generator &generator) {
CryptoType::setGenerator(generator);
}
template<class Generator>
static void setGenerators(Generator &generator1, Generator &generator2) {
CryptoType::setGenerators(generator1, generator2);
}
/**
* Computes signature share of a message
*
* @param message Message to be signed
* @param privateKey Secret key share
* @return Signature share
*/
static Signature sign(const MessagePayload &message, const PrivateKey &privateKey) {
Signature PH;
Signature sign;
PH.hashAndMap(message);
sign.mult(PH, privateKey);
return sign;
}
/**
* Computes the group signature using the indices and signature shares of threshold_ + 1
* parties
*
* @param shares Unordered map of indices and their corresponding signature shares
* @return Group signature
*/
static Signature lagrangeInterpolation(const std::unordered_map<uint32_t, typename CryptoType::Signature> &shares) {
assert(!shares.empty());
if (shares.size() == 1) {
return shares.begin()->second;
}
Signature res;
PrivateKey a{1};
for (auto &p : shares) {
a.mult(a, typename CryptoType::PrivateKey{uint32_t(p.first + 1)});
}
for (auto &p1 : shares) {
typename CryptoType::PrivateKey b{uint32_t(p1.first + 1)};
for (auto &p2 : shares) {
if (p2.first != p1.first) {
typename CryptoType::PrivateKey local_share1{uint32_t(p1.first)}, local_share2{uint32_t(p2.first)};
local_share2.sub(local_share2, local_share1);
b.mult(b, local_share2);
}
}
b.inv(b);
b.mult(a, b);
typename CryptoType::Signature t;
t.mult(p1.second, b);
res.add(res, t);
}
return res;
}
/**
* Generates the group public key, public key shares and private key share for a number of
* parties and a given signature threshold. Nodes must be allocated the outputs according
* to their index in the cabinet.
*
* @param committeeSize Number of parties for which private key shares are generated
* @param threshold Number of parties required to generate a group signature
* @return Vector of DkgOutputs containing the data to be given to each party
*/
static std::vector<DkgOutput> trustedDealer(uint32_t committeeSize, uint32_t threshold) {
std::vector<DkgOutput> output;
VerificationKey generator;
GroupPublicKey generator2;
setGenerator(generator);
setGenerator(generator2);
// Construct polynomial of degree threshold - 1
std::vector<PrivateKey> vec_a;
vec_a.resize(threshold);
for (uint32_t ii = 0; ii < threshold; ++ii) {
vec_a[ii].random();
}
std::vector<VerificationKey> publicKeyShares(committeeSize);
std::vector<PrivateKey> privateKeyShares(committeeSize);
// Group secret key is polynomial evaluated at 0
GroupPublicKey groupPublicKey;
PrivateKey group_private_key = vec_a[0];
groupPublicKey.mult(generator2, group_private_key);
// Generate committee public keys from their private key contributions
for (uint32_t i = 0; i < committeeSize; ++i) {
PrivateKey pow{i + 1}, tmpF, privateKey, cryptoRank{i + 1};
// Private key is polynomial evaluated at index i
privateKey = vec_a[0];
for (uint32_t k = 1; k < vec_a.size(); k++) {
tmpF.mult(pow, vec_a[k]);
privateKey.add(privateKey, tmpF);
pow.mult(pow, cryptoRank); // adjust index in computation
}
// Public key from private
VerificationKey publicKey;
publicKey.mult(generator, privateKey);
publicKeyShares[i] = publicKey;
privateKeyShares[i] = privateKey;
}
assert(publicKeyShares.size() == committeeSize);
assert(privateKeyShares.size() == committeeSize);
// Compute outputs for each member
for (uint32_t i = 0; i < committeeSize; ++i) {
output.emplace_back(groupPublicKey, publicKeyShares, privateKeyShares[i]);
}
return output;
}
protected:
const uint32_t committeeSize_; ///< Number of participants in DKG
uint32_t polynomialDegree_; ///< Degree of polynomial in DKG
GroupSignatureManager<BaseDkg> groupSignatureManager_;
VerificationKey G;
VerificationKey H;
/// Output of the DKG
/// @{
PrivateKey privateKey_;
GroupPublicKey groupPublicKey_;
std::vector<VerificationKey> publicKeyShares_;
/// @}
/// Temporary variables in DKG
/// @{
PrivateKey xprime_i_;
std::vector<std::vector<PrivateKey> > s_ij_, sprime_ij_;
std::vector<std::vector<VerificationKey>> C_ik_;
std::vector<std::vector<VerificationKey>> A_ik_;
std::vector<std::vector<VerificationKey>> g__s_ij_;
/// @}
std::unordered_map<std::string, std::pair<std::set<std::size_t>, std::vector<PrivateKey>>> reconstructionShares_;
///< Map from id of node_i in complaints to a pair <parties which
///< exposed shares of node_i, the shares that were exposed>
std::mutex mutex_;
virtual fetch::consensus::pb::Broadcast
createCoefficients(const std::vector<PrivateKey> &a_i, const std::vector<PrivateKey> &b_i, uint32_t rank) = 0;
template<typename T>
static void init(std::vector<std::vector<T>> &data, uint32_t i, uint32_t j) {
data.resize(i);
for (auto &data_i : data) {
data_i.resize(j);
}
}
std::vector<fetch::consensus::pb::PrivateShares>
createShares(const std::vector<PrivateKey> &a_i, const std::vector<PrivateKey> &b_i, uint32_t rank) {
std::vector<fetch::consensus::pb::PrivateShares> res;
for (size_t j = 0; j < committeeSize_; ++j) {
computeShares(s_ij_[rank][j], sprime_ij_[rank][j], a_i, b_i, j);
if (j != rank) {
PrivateShares shares{s_ij_[rank][j].toString(), sprime_ij_[rank][j].toString()};
res.emplace_back(shares.handle());
}
}
return res;
}
/**
* LHS and RHS functions are used for checking consistency between publicly broadcasted coefficients
* and secret shares distributed privately
*/
static VerificationKey
computeLHS(VerificationKey &tmpG, const VerificationKey &G,
const VerificationKey &H, const PrivateKey &share1,
const PrivateKey &share2) {
{
VerificationKey tmp2G, lhsG;
tmpG.mult(G, share1);
tmp2G.mult(H, share2);
lhsG.add(tmpG, tmp2G);
return lhsG;
}
}
static VerificationKey
computeLHS(const VerificationKey &G, const VerificationKey &H,
const PrivateKey &share1, const PrivateKey &share2) {
VerificationKey tmpG;
return computeLHS(tmpG, G, H, share1, share2);
}
static void updateRHS(size_t rank, VerificationKey &rhsG,
const std::vector<VerificationKey> &input) {
PrivateKey tmpF{uint32_t(rank + 1)}, cryptoRank{uint32_t(rank + 1)};
VerificationKey tmpG;
assert(input.size() > 0);
for (size_t k = 1; k < input.size(); k++) {
tmpG.mult(input[k], tmpF);
rhsG.add(rhsG, tmpG);
tmpF.mult(tmpF, cryptoRank); // adjust index $i$ in computation
}
}
static VerificationKey
computeRHS(size_t rank, const std::vector<VerificationKey> &input) {
VerificationKey rhsG{input[0]};
assert(input.size() > 0);
updateRHS(rank, rhsG, input);
return rhsG;
}
/**
* Given two polynomials (f and f') with coefficients a_i and b_i, we compute the evaluation of
* these polynomials at different points
*
* @param s_i The value of f(rank)
* @param sprime_i The value of f'(rank)
* @param a_i The vector of coefficients for f
* @param b_i The vector of coefficients for f'
* @param rank The point at which you evaluate the polynomial
*/
static void
computeShares(PrivateKey &s_i, PrivateKey &sprime_i,
const std::vector<PrivateKey> &a_i,
const std::vector<PrivateKey> &b_i,
size_t rank) {
PrivateKey pow{uint32_t(rank + 1)}, tmpF, cryptoRank{uint32_t(rank + 1)};
assert(a_i.size() == b_i.size());
assert(a_i.size() > 0);
s_i = a_i[0];
sprime_i = b_i[0];
for (size_t k = 1; k < a_i.size(); k++) {
tmpF.mult(pow, b_i[k]);
sprime_i.add(sprime_i, tmpF);
tmpF.mult(pow, a_i[k]);
s_i.add(s_i, tmpF);
pow.mult(pow, cryptoRank); // adjust index $j$ in computation
}
}
/**
* Computes the coefficients of a polynomial
*
* @param a Points at which polynomial has been evaluated
* @param b Value of the polynomial at points a
* @return The vector of coefficients of the polynomial
*/
static std::vector<PrivateKey>
interpolatePolynom(const std::vector<PrivateKey> &a,
const std::vector<PrivateKey> &b) {
size_t m = a.size();
if ((b.size() != m) || (m == 0))
throw std::invalid_argument("mcl_interpolate_polynom: bad m");
std::vector<PrivateKey> prod{a}, res(m);
for (size_t k = 0; k < m; k++) {
PrivateKey t1{1};
for (long i = k - 1; i >= 0; i--) {
t1.mult(t1, a[k]);
t1.add(t1, prod[i]);
}
PrivateKey t2;
for (long i = k - 1; i >= 0; i--) {
t2.mult(t2, a[k]);
t2.add(t2, res[i]);
}
t2.sub(b[k], t2);
t1.div(t2, t1);
for (size_t i = 0; i < k; i++) {
t2.mult(prod[i], t1);
res[i].add(res[i], t2);
}
res[k] = t1;
if (k < (m - 1)) {
if (k == 0)
prod[0].negate(prod[0]);
else {
t1.negate(a[k]);
prod[k].add(t1, prod[k - 1]);
for (long i = k - 1; i >= 1; i--) {
t2.mult(prod[i], t1);
prod[i].add(t2, prod[i - 1]);
}
prod[0].mult(prod[0], t1);
}
}
}
return res;
}
};
}
} | 34.473258 | 120 | 0.658063 | fetchai |
b4b01ddff1189da2fcffbeb47138f9644b0fb89c | 1,009 | cpp | C++ | waterbox/bsnescore/bsnes/sfc/coprocessor/sa1/iram.cpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 1,414 | 2015-06-28T09:57:51.000Z | 2021-10-14T03:51:10.000Z | waterbox/bsnescore/bsnes/sfc/coprocessor/sa1/iram.cpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 2,369 | 2015-06-25T01:45:44.000Z | 2021-10-16T08:44:18.000Z | waterbox/bsnescore/bsnes/sfc/coprocessor/sa1/iram.cpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 430 | 2015-06-29T04:28:58.000Z | 2021-10-05T18:24:17.000Z | auto SA1::IRAM::conflict() const -> bool {
if(configuration.hacks.coprocessor.delayedSync) return false;
if((cpu.r.mar & 0x40f800) == 0x003000) return cpu.refresh() == 0; //00-3f,80-bf:3000-37ff
return false;
}
auto SA1::IRAM::read(uint address, uint8 data) -> uint8 {
if(!size()) return data;
address = bus.mirror(address, size());
return WritableMemory::read(address, data);
}
auto SA1::IRAM::write(uint address, uint8 data) -> void {
if(!size()) return;
address = bus.mirror(address, size());
return WritableMemory::write(address, data);
}
auto SA1::IRAM::readCPU(uint address, uint8 data) -> uint8 {
cpu.synchronizeCoprocessors();
return read(address, data);
}
auto SA1::IRAM::writeCPU(uint address, uint8 data) -> void {
cpu.synchronizeCoprocessors();
return write(address, data);
}
auto SA1::IRAM::readSA1(uint address, uint8 data) -> uint8 {
return read(address, data);
}
auto SA1::IRAM::writeSA1(uint address, uint8 data) -> void {
return write(address, data);
}
| 27.27027 | 92 | 0.686819 | Fortranm |
b4b04407fd4a536b00436666f0ba5fe5c63361b9 | 909 | cpp | C++ | venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/test/unit/math/prim/scal/fun/promote_elements_test.cpp | vchiapaikeo/prophet | e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7 | [
"MIT"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/test/unit/math/prim/scal/fun/promote_elements_test.cpp | vchiapaikeo/prophet | e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7 | [
"MIT"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | test/unit/math/prim/scal/fun/promote_elements_test.cpp | riddell-stan/math | d84ee0d991400d6cf4b08a07a4e8d86e0651baea | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/prim/scal.hpp>
#include <stan/math/rev/core/var.hpp>
#include <gtest/gtest.h>
#include <boost/typeof/typeof.hpp>
#include <type_traits>
using stan::math::promote_elements;
using stan::math::var;
TEST(MathFunctionsScalPromote_Elements, int2double) {
int from;
promote_elements<double, int> p;
typedef BOOST_TYPEOF(p.promote(from)) result_t;
bool same = std::is_same<double, result_t>::value;
EXPECT_TRUE(same);
}
TEST(MathFunctionsScalPromote_Elements, double2double) {
double from;
promote_elements<double, double> p;
typedef BOOST_TYPEOF(p.promote(from)) result_t;
bool same = std::is_same<double, result_t>::value;
EXPECT_TRUE(same);
}
TEST(MathFunctionsScalPromote_Elements, double2var) {
double from;
promote_elements<var, double> p;
typedef BOOST_TYPEOF(p.promote(from)) result_t;
bool same = std::is_same<var, result_t>::value;
EXPECT_TRUE(same);
}
| 27.545455 | 56 | 0.752475 | vchiapaikeo |
b4b0744abd82d7c910b256ca203276348aed6a49 | 4,101 | hpp | C++ | ext/src/java/lang/Integer.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/lang/Integer.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/lang/Integer.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/lang/Number.hpp>
#include <java/lang/Comparable.hpp>
struct default_init_tag;
class java::lang::Integer final
: public Number
, public Comparable
{
public:
typedef Number super;
static constexpr int32_t BYTES { int32_t(4) };
private:
static ::char16_tArray* DigitOnes_;
static ::char16_tArray* DigitTens_;
public:
static constexpr int32_t MAX_VALUE { int32_t(2147483647) };
static constexpr int32_t MIN_VALUE { int32_t(-0x7fffffff-1) };
static constexpr int32_t SIZE { int32_t(32) };
private:
static Class* TYPE_;
static ::char16_tArray* digits_;
static constexpr int64_t serialVersionUID { int64_t(1360826667806852920LL) };
static ::int32_tArray* sizeTable_;
int32_t value { };
protected:
void ctor(int32_t value);
void ctor(String* s);
public:
static int32_t bitCount(int32_t i);
int8_t byteValue() override;
static int32_t compare(int32_t x, int32_t y);
int32_t compareTo(Integer* anotherInteger);
static int32_t compareUnsigned(int32_t x, int32_t y);
static Integer* decode(String* nm);
static int32_t divideUnsigned(int32_t dividend, int32_t divisor);
double doubleValue() override;
bool equals(Object* obj) override;
float floatValue() override;
public: /* package */
static int32_t formatUnsignedInt(int32_t val, int32_t shift, ::char16_tArray* buf, int32_t offset, int32_t len);
static void getChars(int32_t i, int32_t index, ::char16_tArray* buf);
public:
static Integer* getInteger(String* nm);
static Integer* getInteger(String* nm, int32_t val);
static Integer* getInteger(String* nm, Integer* val);
int32_t hashCode() override;
static int32_t hashCode(int32_t value);
static int32_t highestOneBit(int32_t i);
int32_t intValue() override;
int64_t longValue() override;
static int32_t lowestOneBit(int32_t i);
static int32_t max(int32_t a, int32_t b);
static int32_t min(int32_t a, int32_t b);
static int32_t numberOfLeadingZeros(int32_t i);
static int32_t numberOfTrailingZeros(int32_t i);
static int32_t parseInt(String* s);
static int32_t parseInt(String* s, int32_t radix);
static int32_t parseUnsignedInt(String* s);
static int32_t parseUnsignedInt(String* s, int32_t radix);
static int32_t remainderUnsigned(int32_t dividend, int32_t divisor);
static int32_t reverse(int32_t i);
static int32_t reverseBytes(int32_t i);
static int32_t rotateLeft(int32_t i, int32_t distance);
static int32_t rotateRight(int32_t i, int32_t distance);
int16_t shortValue() override;
static int32_t signum(int32_t i);
public: /* package */
static int32_t stringSize(int32_t x);
public:
static int32_t sum(int32_t a, int32_t b);
static String* toBinaryString(int32_t i);
static String* toHexString(int32_t i);
static String* toOctalString(int32_t i);
String* toString() override;
static String* toString(int32_t i);
static String* toString(int32_t i, int32_t radix);
static int64_t toUnsignedLong(int32_t x);
static String* toUnsignedString(int32_t i);
static String* toUnsignedString(int32_t i, int32_t radix);
/*static String* toUnsignedString0(int32_t val, int32_t shift); (private) */
static Integer* valueOf(String* s);
static Integer* valueOf(int32_t i);
static Integer* valueOf(String* s, int32_t radix);
// Generated
Integer(int32_t value);
Integer(String* s);
protected:
Integer(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
virtual int32_t compareTo(Object* o) override;
public: /* package */
static ::char16_tArray*& DigitOnes();
static ::char16_tArray*& DigitTens();
public:
static Class*& TYPE();
public: /* package */
static ::char16_tArray*& digits();
static ::int32_tArray*& sizeTable();
private:
virtual ::java::lang::Class* getClass0();
};
| 32.291339 | 116 | 0.717142 | pebble2015 |
b4b1b1587b36708cb4f4e6a416f5bd994fd8848a | 3,665 | cpp | C++ | src/GafferBindings/ReferenceBinding.cpp | PaulDoessel/gaffer-play | 8b72dabb388e12424c230acfb0bd209049b01bd6 | [
"BSD-3-Clause"
] | 1 | 2016-07-31T09:55:09.000Z | 2016-07-31T09:55:09.000Z | src/GafferBindings/ReferenceBinding.cpp | Kthulhu/gaffer | 8995d579d07231988abc92c3ac2788c15c8bc75c | [
"BSD-3-Clause"
] | null | null | null | src/GafferBindings/ReferenceBinding.cpp | Kthulhu/gaffer | 8995d579d07231988abc92c3ac2788c15c8bc75c | [
"BSD-3-Clause"
] | 1 | 2020-02-15T16:15:54.000Z | 2020-02-15T16:15:54.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp" // must be the first include
#include "IECorePython/ScopedGILRelease.h"
#include "Gaffer/Reference.h"
#include "Gaffer/StringPlug.h"
#include "GafferBindings/ReferenceBinding.h"
#include "GafferBindings/NodeBinding.h"
#include "GafferBindings/ExceptionAlgo.h"
#include "GafferBindings/SignalBinding.h"
using namespace boost::python;
using namespace Gaffer;
using namespace GafferBindings;
namespace
{
struct ReferenceLoadedSlotCaller
{
boost::signals::detail::unusable operator()( boost::python::object slot, ReferencePtr r )
{
try
{
slot( r );
}
catch( const error_already_set &e )
{
translatePythonException();
}
return boost::signals::detail::unusable();
}
};
class ReferenceSerialiser : public NodeSerialiser
{
virtual std::string postConstructor( const Gaffer::GraphComponent *graphComponent, const std::string &identifier, const Serialisation &serialisation ) const
{
const Reference *r = static_cast<const Reference *>( graphComponent );
const std::string &fileName = r->fileName();
if( fileName.empty() )
{
return "";
};
return identifier + ".load( \"" + fileName + "\" )\n";
}
};
void load( Reference &r, const std::string &f )
{
IECorePython::ScopedGILRelease gilRelease;
r.load( f );
}
} // namespace
void GafferBindings::bindReference()
{
NodeClass<Reference>()
.def( "load", &load )
.def( "fileName", &Reference::fileName, return_value_policy<copy_const_reference>() )
.def( "referenceLoadedSignal", &Reference::referenceLoadedSignal, return_internal_reference<1>() )
;
SignalClass<Reference::ReferenceLoadedSignal, DefaultSignalCaller<Reference::ReferenceLoadedSignal>, ReferenceLoadedSlotCaller >( "ReferenceLoadedSignal" );
Serialisation::registerSerialiser( Reference::staticTypeId(), new ReferenceSerialiser );
}
| 33.018018 | 157 | 0.703683 | PaulDoessel |
b4b4b7612769a8959e9781c826428e3fcfdb3b7b | 4,441 | cpp | C++ | tinysdl/Game/Tetris/App.cpp | silent1603/silent1603-TinySDL | 7b3470b2e343bcec8d4788de2d817b41bec1141d | [
"MIT"
] | null | null | null | tinysdl/Game/Tetris/App.cpp | silent1603/silent1603-TinySDL | 7b3470b2e343bcec8d4788de2d817b41bec1141d | [
"MIT"
] | null | null | null | tinysdl/Game/Tetris/App.cpp | silent1603/silent1603-TinySDL | 7b3470b2e343bcec8d4788de2d817b41bec1141d | [
"MIT"
] | null | null | null | #include "App.hpp"
namespace Tetris
{
#define MIN_SIZE_WIDTH 600
#define MIN_SIZE_HEIGHT 400
App::App(/* args */) : m_strTitle("Tetris"),
m_iWidth(800),
m_iHeight(600)
{
}
App::~App()
{
}
App::App(std::string title, int width, int height) : m_strTitle(title),
m_iWidth(width),
m_iHeight(height)
{
}
bool App::init()
{
// initiate SDL
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
TETRIS_ERROR("SDL init failed");
return false;
}
// set OpenGL attributes
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
// set profile contetnt for opengl
SDL_GL_SetAttribute(
SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
std::string glsl_version = "#version 330";
#ifdef __APPLE__
// GL 4.1 Core + GLSL 410
glsl_version = "#version 410";
SDL_GL_SetAttribute( // required on Mac OS
SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
#elif __linux__
// GL 4.3 Core + GLSL 430
glsl_version = "#version 430";
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#elif _WIN32
// GL 3.3 + GLSL 330
glsl_version = "#version 330";
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#endif
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
m_sdl2Window = SDL_CreateWindow(
m_strTitle.c_str(),
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
m_iWidth,
m_iHeight,
window_flags);
SDL_SetWindowMinimumSize(m_sdl2Window, MIN_SIZE_WIDTH, MIN_SIZE_HEIGHT);
m_glContext = SDL_GL_CreateContext(m_sdl2Window);
if (m_glContext == nullptr)
{
TETRIS_ERROR("Can't init GLContent");
}
SDL_GL_MakeCurrent(m_sdl2Window, m_glContext);
// enable VSync
SDL_GL_SetSwapInterval(1);
if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
{
TETRIS_ERROR("Couldn't initialize glad");
return false;
}
glViewport(0, 0, m_iWidth, m_iHeight);
glClearColor(0.0f, 0.0f,0.0f, 0.0f);
return true;
}
void App::update()
{
m_isRunning = true;
SDL_Event e;
while (m_isRunning)
{
while (SDL_PollEvent(&e))
{
if (e.type == SDL_QUIT)
{
m_isRunning = false;
}
else {
switch (e.key.keysym.sym)
{
case SDLK_ESCAPE:
m_isRunning = false;
break;
default:
break;
}
}
if (e.type == SDL_WINDOWEVENT)
{
switch (e.window.event)
{
case SDL_WINDOWEVENT_RESIZED:
m_iWidth = e.window.data1;
m_iHeight = e.window.data2;
TETRIS_INFO( m_iWidth);
TETRIS_INFO( m_iHeight);
SDL_SetWindowSize(m_sdl2Window, m_iWidth, m_iHeight);
break;
default:
break;
}
}
}
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
SDL_GL_SwapWindow(m_sdl2Window);
}
}
void App::clean()
{
SDL_GL_DeleteContext(m_glContext);
SDL_DestroyWindow(m_sdl2Window);
SDL_Quit();
}
} | 28.467949 | 126 | 0.517901 | silent1603 |
b4b5b33df2ac6538dd6be817ea7bb9e279244b1a | 178 | cpp | C++ | Iniciante/1008.cpp | nobreconfrade/AKIRA | 6040f6db0efe3a4c9ca7fe360859bf3f3ca58e42 | [
"Apache-2.0"
] | null | null | null | Iniciante/1008.cpp | nobreconfrade/AKIRA | 6040f6db0efe3a4c9ca7fe360859bf3f3ca58e42 | [
"Apache-2.0"
] | null | null | null | Iniciante/1008.cpp | nobreconfrade/AKIRA | 6040f6db0efe3a4c9ca7fe360859bf3f3ca58e42 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <stdio.h>
using namespace std;
int main(){
float a,b,c;
cin>>a>>b>>c;
printf("NUMBER = %.0f\n",a);
printf("SALARY = U$ %.2f\n",b*c);
return 0;
} | 17.8 | 34 | 0.601124 | nobreconfrade |
b4b7bf5748274f32a4a9eafc01bedf69be03d47d | 2,228 | cpp | C++ | samples/stencil/average_env/main.cpp | Jerry-Ma/grppi | d6e5435a2c146605fc53eed899d1777ac0b35699 | [
"ECL-2.0",
"Apache-2.0"
] | 75 | 2017-05-05T08:22:47.000Z | 2022-02-18T23:48:13.000Z | samples/stencil/average_env/main.cpp | Jerry-Ma/grppi | d6e5435a2c146605fc53eed899d1777ac0b35699 | [
"ECL-2.0",
"Apache-2.0"
] | 317 | 2017-03-29T15:26:18.000Z | 2021-10-02T04:18:27.000Z | samples/stencil/average_env/main.cpp | Yagoloco2210/grppi | 03f3712f282298a64b37dc560b28f6109437b774 | [
"ECL-2.0",
"Apache-2.0"
] | 21 | 2017-08-02T14:35:19.000Z | 2022-02-17T22:19:06.000Z | /*
* Copyright 2018 Universidad Carlos III de Madrid
*
* 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.
*/
// Standard library
#include <iostream>
#include <vector>
#include <fstream>
#include <chrono>
#include <string>
#include <numeric>
#include <stdexcept>
// grppi
#include "grppi/grppi.h"
// Samples shared utilities
#include "../../util/util.h"
void compute_avg(grppi::dynamic_execution & e, int n) {
using namespace std;
vector<long long> in;
generate_n(back_inserter(in), n,
[i=0]() mutable { i++; return i*i; });
vector<double> out(n);
grppi::stencil(e, begin(in), end(in), begin(out),
[](auto it, auto n) {
return (*it + std::accumulate(begin(n), end(n), 0)) / double(n.size()+1);
},
[&in](auto it) {
vector<double> r;
if (it!=begin(in)) r.push_back(*prev(it));
if (std::distance(it,end(in))>1) r.push_back(*next(it));
return r;
}
);
copy(begin(out), end(out), ostream_iterator<double>(cout, " "));
cout << endl;
}
void print_message(const std::string & prog, const std::string & msg) {
using namespace std;
cerr << msg << endl;
cerr << "Usage: " << prog << " size mode" << endl;
cerr << " size: Integer value with problem size" << endl;
cerr << " mode:" << endl;
print_available_modes(cerr);
}
int main(int argc, char **argv) {
using namespace std;
if(argc < 3){
print_message(argv[0], "Invalid number of arguments.");
return -1;
}
int n = stoi(argv[1]);
if(n <= 0){
print_message(argv[0], "Invalid problem size. Use a positive number.");
return -1;
}
if (!run_test(argv[2], compute_avg, n)) {
print_message(argv[0], "Invalid policy.");
return -1;
}
return 0;
}
| 25.033708 | 79 | 0.639138 | Jerry-Ma |
b4bab8beddc277e7ec1c0d68931e5cb56e009338 | 6,914 | hpp | C++ | dependencies/osi_clp/Clp/src/ClpDynamicExampleMatrix.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 5 | 2020-01-28T08:38:35.000Z | 2021-06-19T04:11:23.000Z | dependencies/osi_clp/Clp/src/ClpDynamicExampleMatrix.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | null | null | null | dependencies/osi_clp/Clp/src/ClpDynamicExampleMatrix.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 3 | 2019-11-26T14:43:13.000Z | 2021-10-06T08:03:46.000Z | /* $Id$ */
// Copyright (C) 2004, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#ifndef ClpDynamicExampleMatrix_H
#define ClpDynamicExampleMatrix_H
#include "CoinPragma.hpp"
#include "ClpDynamicMatrix.hpp"
class ClpSimplex;
/** This implements a dynamic matrix when we have a limit on the number of
"interesting rows". This version inherits from ClpDynamicMatrix and knows that
the real matrix is gub. This acts just like ClpDynamicMatrix but generates columns.
This "generates" columns by choosing from stored set. It is maent as a starting point
as to how you could use shortest path to generate columns.
So it has its own copy of all data needed. It populates ClpDynamicWatrix with enough
to allow for gub keys and active variables. In turn ClpDynamicMatrix populates
a CoinPackedMatrix with active columns and rows.
As there is one copy here and one in ClpDynamicmatrix these names end in Gen_
It is obviously more efficient to just use ClpDynamicMatrix but the ideas is to
show how much code a user would have to write.
This does not work very well with bounds
*/
class ClpDynamicExampleMatrix : public ClpDynamicMatrix {
public:
/**@name Main functions provided */
//@{
/// Partial pricing
virtual void partialPricing(ClpSimplex * model, double start, double end,
int & bestSequence, int & numberWanted);
/** Creates a variable. This is called after partial pricing and will modify matrix.
Will update bestSequence.
*/
virtual void createVariable(ClpSimplex * model, int & bestSequence);
/** If addColumn forces compression then this allows descendant to know what to do.
If >= then entry stayed in, if -1 then entry went out to lower bound.of zero.
Entries at upper bound (really nonzero) never go out (at present).
*/
virtual void packDown(const int * in, int numberToPack);
//@}
/**@name Constructors, destructor */
//@{
/** Default constructor. */
ClpDynamicExampleMatrix();
/** This is the real constructor.
It assumes factorization frequency will not be changed.
This resizes model !!!!
The contents of original matrix in model will be taken over and original matrix
will be sanitized so can be deleted (to avoid a very small memory leak)
*/
ClpDynamicExampleMatrix(ClpSimplex * model, int numberSets,
int numberColumns, const int * starts,
const double * lower, const double * upper,
const int * startColumn, const int * row,
const double * element, const double * cost,
const double * columnLower = NULL, const double * columnUpper = NULL,
const unsigned char * status = NULL,
const unsigned char * dynamicStatus = NULL,
int numberIds = 0, const int *ids = NULL);
#if 0
/// This constructor just takes over ownership (except for lower, upper)
ClpDynamicExampleMatrix(ClpSimplex * model, int numberSets,
int numberColumns, int * starts,
const double * lower, const double * upper,
int * startColumn, int * row,
double * element, double * cost,
double * columnLower = NULL, double * columnUpper = NULL,
const unsigned char * status = NULL,
const unsigned char * dynamicStatus = NULL,
int numberIds = 0, const int *ids = NULL);
#endif
/** Destructor */
virtual ~ClpDynamicExampleMatrix();
//@}
/**@name Copy method */
//@{
/** The copy constructor. */
ClpDynamicExampleMatrix(const ClpDynamicExampleMatrix&);
ClpDynamicExampleMatrix& operator=(const ClpDynamicExampleMatrix&);
/// Clone
virtual ClpMatrixBase * clone() const ;
//@}
/**@name gets and sets */
//@{
/// Starts of each column
inline CoinBigIndex * startColumnGen() const {
return startColumnGen_;
}
/// rows
inline int * rowGen() const {
return rowGen_;
}
/// elements
inline double * elementGen() const {
return elementGen_;
}
/// costs
inline double * costGen() const {
return costGen_;
}
/// full starts
inline int * fullStartGen() const {
return fullStartGen_;
}
/// ids in next level matrix
inline int * idGen() const {
return idGen_;
}
/// Optional lower bounds on columns
inline double * columnLowerGen() const {
return columnLowerGen_;
}
/// Optional upper bounds on columns
inline double * columnUpperGen() const {
return columnUpperGen_;
}
/// size
inline int numberColumns() const {
return numberColumns_;
}
inline void setDynamicStatusGen(int sequence, DynamicStatus status) {
unsigned char & st_byte = dynamicStatusGen_[sequence];
st_byte = static_cast<unsigned char>(st_byte & ~7);
st_byte = static_cast<unsigned char>(st_byte | status);
}
inline DynamicStatus getDynamicStatusGen(int sequence) const {
return static_cast<DynamicStatus> (dynamicStatusGen_[sequence] & 7);
}
/// Whether flagged
inline bool flaggedGen(int i) const {
return (dynamicStatusGen_[i] & 8) != 0;
}
inline void setFlaggedGen(int i) {
dynamicStatusGen_[i] = static_cast<unsigned char>(dynamicStatusGen_[i] | 8);
}
inline void unsetFlagged(int i) {
dynamicStatusGen_[i] = static_cast<unsigned char>(dynamicStatusGen_[i] & ~8);
}
//@}
protected:
/**@name Data members
The data members are protected to allow access for derived classes. */
//@{
/// size
int numberColumns_;
/// Starts of each column
CoinBigIndex * startColumnGen_;
/// rows
int * rowGen_;
/// elements
double * elementGen_;
/// costs
double * costGen_;
/// start of each set
int * fullStartGen_;
/// for status and which bound
unsigned char * dynamicStatusGen_;
/** identifier for each variable up one level (startColumn_, etc). This is
of length maximumGubColumns_. For this version it is just sequence number
at this level */
int * idGen_;
/// Optional lower bounds on columns
double * columnLowerGen_;
/// Optional upper bounds on columns
double * columnUpperGen_;
//@}
};
#endif
| 36.973262 | 98 | 0.614406 | zyxrrr |
b4bba29492d76f324d1eb8dc7a2a3a6d3362e579 | 8,093 | cpp | C++ | ShaderParser/NodeGraph.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | 3 | 2018-05-17T08:39:39.000Z | 2020-12-09T13:20:26.000Z | ShaderParser/NodeGraph.cpp | djewsbury/XLE | 7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e | [
"MIT"
] | null | null | null | ShaderParser/NodeGraph.cpp | djewsbury/XLE | 7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e | [
"MIT"
] | 2 | 2015-03-03T05:32:39.000Z | 2015-12-04T09:16:54.000Z | // Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "NodeGraph.h"
namespace GraphLanguage
{
const std::string s_resultName = "result";
const std::string ParameterName_NodeInstantiation = "<instantiation>";
NodeGraph::NodeGraph() {}
NodeGraph::~NodeGraph() {}
void NodeGraph::Add(Node&& a) { _nodes.emplace_back(std::move(a)); }
void NodeGraph::Add(Connection&& a) { _connections.emplace_back(std::move(a)); }
bool NodeGraph::IsUpstream(NodeId startNode, NodeId searchingForNode)
{
// Starting at 'startNode', search upstream and see if we find 'searchingForNode'
if (startNode == searchingForNode) {
return true;
}
for (auto i=_connections.cbegin(); i!=_connections.cend(); ++i) {
if (i->OutputNodeId() == startNode) {
auto inputNode = i->InputNodeId();
if (inputNode != NodeId_Interface && inputNode != NodeId_Constant && IsUpstream(i->InputNodeId(), searchingForNode)) {
return true;
}
}
}
return false;
}
bool NodeGraph::IsDownstream(
NodeId startNode,
const NodeId* searchingForNodesStart, const NodeId* searchingForNodesEnd)
{
if (std::find(searchingForNodesStart, searchingForNodesEnd, startNode) != searchingForNodesEnd) {
return true;
}
for (auto i=_connections.cbegin(); i!=_connections.cend(); ++i) {
if (i->InputNodeId() == startNode) {
auto outputNode = i->OutputNodeId();
if (outputNode != NodeId_Interface && outputNode != NodeId_Constant && IsDownstream(outputNode, searchingForNodesStart, searchingForNodesEnd)) {
return true;
}
}
}
return false;
}
bool NodeGraph::HasNode(NodeId nodeId)
{
// Special case node ids are considered to always exist (particularly required when called from Trim())
if (nodeId == NodeId_Interface || nodeId == NodeId_Constant) return true;
return std::find_if(_nodes.begin(), _nodes.end(),
[=](const Node& node) { return node.NodeId() == nodeId; }) != _nodes.end();
}
const Node* NodeGraph::GetNode(NodeId nodeId) const
{
auto res = std::find_if(
_nodes.cbegin(), _nodes.cend(),
[=](const Node& n) { return n.NodeId() == nodeId; });
if (res != _nodes.cend()) {
return &*res;
}
return nullptr;
}
void NodeGraph::Trim(NodeId previewNode)
{
Trim(&previewNode, &previewNode+1);
}
void NodeGraph::Trim(const NodeId* trimNodesBegin, const NodeId* trimNodesEnd)
{
//
// Trim out all of the nodes that are upstream of
// 'previewNode' (except for output nodes that are
// directly written by one of the trim nodes)
//
// Simply
// 1. remove all nodes, unless they are downstream
// of 'previewNode'
// 2. remove all connections that refer to nodes
// that no longer exist
//
// Generally, there won't be an output connection attached
// to the previewNode at the end of the process. So, we
// may need to create one.
//
_nodes.erase(
std::remove_if(
_nodes.begin(), _nodes.end(),
[=](const Node& node) { return !IsDownstream(node.NodeId(), trimNodesBegin, trimNodesEnd); }),
_nodes.end());
_connections.erase(
std::remove_if(
_connections.begin(), _connections.end(),
[=](const Connection& connection)
{ return !HasNode(connection.InputNodeId()) || !HasNode(connection.OutputNodeId()) || connection.OutputNodeId() == NodeId_Interface; }),
_connections.end());
}
///////////////////////////////////////////////////////////////////////////////////////////////////
static void OrderNodes(IteratorRange<NodeId*> range)
{
// We need to sort the upstreams in some way that maintains a
// consistant ordering. The simplied way is just to use node id.
// However we may sometimes want to set priorities for nodes.
// For example, nodes that can "discard" pixels should be priortized
// higher.
std::sort(range.begin(), range.end());
}
static bool SortNodesFunction(
NodeId node,
std::vector<NodeId>& presorted,
std::vector<NodeId>& sorted,
std::vector<NodeId>& marks,
const NodeGraph& graph)
{
if (std::find(presorted.begin(), presorted.end(), node) == presorted.end()) {
return false; // hit a cycle
}
if (std::find(marks.begin(), marks.end(), node) != marks.end()) {
return false; // hit a cycle
}
marks.push_back(node);
std::vector<NodeId> upstream;
upstream.reserve(graph.GetConnections().size());
for (const auto& i:graph.GetConnections())
if (i.OutputNodeId() == node)
upstream.push_back(i.InputNodeId());
OrderNodes(MakeIteratorRange(upstream));
for (const auto& i2:upstream)
SortNodesFunction(i2, presorted, sorted, marks, graph);
sorted.push_back(node);
presorted.erase(std::find(presorted.begin(), presorted.end(), node));
return true;
}
std::vector<NodeId> SortNodes(const NodeGraph& graph, bool& isAcyclic)
{
/*
We need to create a directed acyclic graph from the nodes in 'graph'
-- and then we need to do a topological sort.
This will tell us the order in which to call each function
Basic algorithms:
L <- Empty list that will contain the sorted elements
S <- Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
Depth first sort:
L <- Empty list that will contain the sorted nodes
while there are unmarked nodes do
select an unmarked node n
visit(n)
function visit(node n)
if n has a temporary mark then stop (not a DAG)
if n is not marked (i.e. has not been visited yet) then
mark n temporarily
for each node m with an edge from n to m do
visit(m)
mark n permanently
add n to head of L
*/
std::vector<NodeId> presortedNodes, sortedNodes;
sortedNodes.reserve(graph.GetNodes().size());
for (const auto& i:graph.GetNodes())
presortedNodes.push_back(i.NodeId());
OrderNodes(MakeIteratorRange(presortedNodes));
isAcyclic = true;
while (!presortedNodes.empty()) {
std::vector<NodeId> temporaryMarks;
bool sortReturn = SortNodesFunction(
presortedNodes[0],
presortedNodes, sortedNodes,
temporaryMarks, graph);
if (!sortReturn) {
isAcyclic = false;
break;
}
}
return sortedNodes;
}
}
| 35.968889 | 160 | 0.540344 | pocketgems |
b4bc34420daa43633be23c1cc9e20ad6852e3bfe | 496 | cpp | C++ | Contest 1006/D.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | Contest 1006/D.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | Contest 1006/D.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main() {
unsigned long orig,i,j,tmp;
cin >> orig;
tmp = orig;
if (orig == 1){
cout << "1=1"<<endl;
goto endapp;
}
cout << orig << '=';
for (i = 2; tmp != 1 && i<=orig; ++i){
while (tmp%i == 0){
cout << i;
tmp /= i;
if (tmp != 1) cout << '*';
}
}
cout << endl;
//system("pause>nul");
endapp:
return 0;
} | 19.84 | 42 | 0.431452 | PC-DOS |
b4bdef12b202efb72b46b38e20fb24e47b565294 | 11,416 | cpp | C++ | Server/src/modules/SD3/scripts/eastern_kingdoms/zulgurub/instance_zulgurub.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | null | null | null | Server/src/modules/SD3/scripts/eastern_kingdoms/zulgurub/instance_zulgurub.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | null | null | null | Server/src/modules/SD3/scripts/eastern_kingdoms/zulgurub/instance_zulgurub.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | null | null | null | /**
* ScriptDev3 is an extension for mangos providing enhanced features for
* area triggers, creatures, game objects, instances, items, and spells beyond
* the default database scripting in mangos.
*
* Copyright (C) 2006-2013 ScriptDev2 <http://www.scriptdev2.com/>
* Copyright (C) 2014-2022 MaNGOS <https://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/**
* ScriptData
* SDName: Instance_ZulGurub
* SD%Complete: 80
* SDComment: Missing reset function after killing a boss for Ohgan, Thekal.
* SDCategory: Zul'Gurub
* EndScriptData
*/
#include "precompiled.h"
#include "zulgurub.h"
struct is_zulgurub : public InstanceScript
{
is_zulgurub() : InstanceScript("instance_zulgurub") {}
class instance_zulgurub : public ScriptedInstance
{
public:
instance_zulgurub(Map* pMap) : ScriptedInstance(pMap),
m_bHasIntroYelled(false),
m_bHasAltarYelled(false)
{
Initialize();
}
~instance_zulgurub() {}
void Initialize() override
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
}
// IsEncounterInProgress() const override { return false; } // not active in Zul'Gurub
void OnCreatureCreate(Creature* pCreature) override
{
switch (pCreature->GetEntry())
{
case NPC_LORKHAN:
case NPC_ZATH:
case NPC_THEKAL:
case NPC_JINDO:
case NPC_HAKKAR:
case NPC_BLOODLORD_MANDOKIR:
case NPC_MARLI:
m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();
break;
case NPC_PANTHER_TRIGGER:
if (pCreature->GetPositionY() < -1626)
{
m_lLeftPantherTriggerGUIDList.push_back(pCreature->GetObjectGuid());
}
else
{
m_lRightPantherTriggerGUIDList.push_back(pCreature->GetObjectGuid());
}
break;
}
}
void OnObjectCreate(GameObject* pGo) override
{
switch (pGo->GetEntry())
{
case GO_GONG_OF_BETHEKK:
case GO_FORCEFIELD:
break;
case GO_SPIDER_EGG:
m_lSpiderEggGUIDList.push_back(pGo->GetObjectGuid());
return;
}
m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid();
}
void SetData(uint32 uiType, uint32 uiData) override
{
switch (uiType)
{
case TYPE_JEKLIK:
case TYPE_VENOXIS:
case TYPE_THEKAL:
m_auiEncounter[uiType] = uiData;
if (uiData == DONE)
{
DoLowerHakkarHitPoints();
}
break;
case TYPE_MARLI:
m_auiEncounter[uiType] = uiData;
if (uiData == DONE)
{
DoLowerHakkarHitPoints();
}
if (uiData == FAIL)
{
for (GuidList::const_iterator itr = m_lSpiderEggGUIDList.begin(); itr != m_lSpiderEggGUIDList.end(); ++itr)
{
if (GameObject* pEgg = instance->GetGameObject(*itr))
{
// Note: this type of Gameobject needs to be respawned manually
pEgg->SetRespawnTime(2 * DAY);
pEgg->Respawn();
}
}
}
break;
case TYPE_ARLOKK:
m_auiEncounter[uiType] = uiData;
DoUseDoorOrButton(GO_FORCEFIELD);
if (uiData == DONE)
{
DoLowerHakkarHitPoints();
}
if (uiData == FAIL)
{
// Note: this gameobject should change flags - currently it despawns which isn't correct
if (GameObject* pGong = GetSingleGameObjectFromStorage(GO_GONG_OF_BETHEKK))
{
pGong->SetRespawnTime(2 * DAY);
pGong->Respawn();
}
}
break;
case TYPE_OHGAN:
// Note: SPECIAL instance data is set via ACID!
if (uiData == SPECIAL)
{
if (Creature* pMandokir = GetSingleCreatureFromStorage(NPC_BLOODLORD_MANDOKIR))
{
pMandokir->SetWalk(false);
pMandokir->GetMotionMaster()->MovePoint(1, aMandokirDownstairsPos[0], aMandokirDownstairsPos[1], aMandokirDownstairsPos[2]);
}
}
m_auiEncounter[uiType] = uiData;
break;
case TYPE_LORKHAN:
case TYPE_ZATH:
m_auiEncounter[uiType] = uiData;
break;
case TYPE_SIGNAL_1:
DoYellAtTriggerIfCan(uiData);
return;
}
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " "
<< m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5] << " "
<< m_auiEncounter[6] << " " << m_auiEncounter[7];
m_strInstData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
uint32 GetData(uint32 uiType) const override
{
if (uiType < MAX_ENCOUNTER)
{
return m_auiEncounter[uiType];
}
return 0;
}
uint64 GetData64(uint32 type) const override
{
switch (type)
{
case TYPE_SIGNAL_2:
case TYPE_SIGNAL_3:
if (Creature *p = (const_cast<instance_zulgurub*>(this))->SelectRandomPantherTrigger(type == TYPE_SIGNAL_2))
{
return p->GetObjectGuid().GetRawValue();
}
break;
default:
break;
}
return 0;
}
const char* Save() const override { return m_strInstData.c_str(); }
void Load(const char* chrIn) override
{
if (!chrIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(chrIn);
std::istringstream loadStream(chrIn);
loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3]
>> m_auiEncounter[4] >> m_auiEncounter[5] >> m_auiEncounter[6] >> m_auiEncounter[7];
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (m_auiEncounter[i] == IN_PROGRESS)
{
m_auiEncounter[i] = NOT_STARTED;
}
}
OUT_LOAD_INST_DATA_COMPLETE;
}
private:
void DoLowerHakkarHitPoints()
{
if (Creature* pHakkar = GetSingleCreatureFromStorage(NPC_HAKKAR))
{
if (pHakkar->IsAlive() && pHakkar->GetMaxHealth() > HP_LOSS_PER_PRIEST)
{
pHakkar->SetMaxHealth(pHakkar->GetMaxHealth() - HP_LOSS_PER_PRIEST);
pHakkar->SetHealth(pHakkar->GetHealth() - HP_LOSS_PER_PRIEST);
}
}
}
void DoYellAtTriggerIfCan(uint32 uiTriggerId)
{
if (uiTriggerId == AREATRIGGER_ENTER && !m_bHasIntroYelled)
{
DoOrSimulateScriptTextForThisInstance(SAY_HAKKAR_PROTECT, NPC_HAKKAR);
m_bHasIntroYelled = true;
}
else if (uiTriggerId == AREATRIGGER_ALTAR && !m_bHasAltarYelled)
{
DoOrSimulateScriptTextForThisInstance(SAY_MINION_DESTROY, NPC_HAKKAR);
m_bHasAltarYelled = true;
}
}
Creature* SelectRandomPantherTrigger(bool bIsLeft)
{
GuidList* plTempList = bIsLeft ? &m_lLeftPantherTriggerGUIDList : &m_lRightPantherTriggerGUIDList;
std::vector<Creature*> vTriggers;
vTriggers.reserve(plTempList->size());
for (GuidList::const_iterator itr = plTempList->begin(); itr != plTempList->end(); ++itr)
{
if (Creature* pTemp = instance->GetCreature(*itr))
{
vTriggers.push_back(pTemp);
}
}
if (vTriggers.empty())
{
return nullptr;
}
return vTriggers[urand(0, vTriggers.size() - 1)];
}
uint32 m_auiEncounter[MAX_ENCOUNTER];
std::string m_strInstData;
GuidList m_lRightPantherTriggerGUIDList;
GuidList m_lLeftPantherTriggerGUIDList;
GuidList m_lSpiderEggGUIDList;
bool m_bHasIntroYelled;
bool m_bHasAltarYelled;
};
InstanceData* GetInstanceData(Map* pMap) override
{
return new instance_zulgurub(pMap);
}
};
struct at_zulgurub : public AreaTriggerScript
{
at_zulgurub() : AreaTriggerScript("at_zulgurub") {}
bool AreaTrigger_at_zulgurub(Player* pPlayer, AreaTriggerEntry const* pAt)
{
if (pAt->id == AREATRIGGER_ENTER || pAt->id == AREATRIGGER_ALTAR)
{
if (pPlayer->isGameMaster() || pPlayer->IsDead())
{
return false;
}
if (ScriptedInstance* pInstance = (ScriptedInstance*)pPlayer->GetInstanceData())
{
pInstance->SetData(TYPE_SIGNAL_1, pAt->id);
}
}
return false;
}
};
void AddSC_instance_zulgurub()
{
Script* s;
s = new is_zulgurub();
s->RegisterSelf();
s = new at_zulgurub();
s->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "instance_zulgurub";
//pNewScript->GetInstanceData = &GetInstanceData_instance_zulgurub;
//pNewScript->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "at_zulgurub";
//pNewScript->pAreaTrigger = &AreaTrigger_at_zulgurub;
//pNewScript->RegisterSelf();
}
| 32.617143 | 148 | 0.530221 | ZON3DEV |
b4be27c953d61b8905bae5d0d8eb889e3254fc24 | 441 | hpp | C++ | Classes/ui/pause/PauseLayer.hpp | cpinan/Turbo-Race | c9394c308a8d25ece63a90326bad7283d5005d46 | [
"Apache-2.0"
] | null | null | null | Classes/ui/pause/PauseLayer.hpp | cpinan/Turbo-Race | c9394c308a8d25ece63a90326bad7283d5005d46 | [
"Apache-2.0"
] | null | null | null | Classes/ui/pause/PauseLayer.hpp | cpinan/Turbo-Race | c9394c308a8d25ece63a90326bad7283d5005d46 | [
"Apache-2.0"
] | null | null | null | //
// PauseLayer.hpp
// TurboRace
//
// Created by Carlos Eduardo Pinan Indacochea on 21/02/22.
//
#ifndef PauseLayer_hpp
#define PauseLayer_hpp
#include "cocos2d.h"
enum PauseButtons
{
kTagPauseResumeGame = 0,
kTagPauseGoHome = 1,
kTagPausePlayAgain = 2
};
class PauseLayer : public cocos2d::LayerColor {
public:
PauseLayer();
private:
void onOptionsTapped(cocos2d::Ref* sender);
};
#endif /* PauseLayer_hpp */
| 15.206897 | 59 | 0.698413 | cpinan |
b4bfe6b3eafcda5b6be8c87c328622e205ab7fd9 | 6,335 | cxx | C++ | main/extensions/workben/testcomponent.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/extensions/workben/testcomponent.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/extensions/workben/testcomponent.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
//------------------------------------------------------
// testcomponent - Loads a service and its testcomponent from dlls performs a test.
// Expands the dll-names depending on the actual environment.
// Example : testcomponent stardiv.uno.io.Pipe stm
//
// Therefor the testcode must exist in teststm and the testservice must be named test.stardiv.uno.io.Pipe
//
#include <stdio.h>
#include <smart/com/sun/star/registry/XImplementationRegistration.hxx>
#include <smart/com/sun/star/lang/XComponent.hxx>
//#include <com/sun/star/registry/ stardiv/uno/repos/simplreg.hxx>
#include <vos/dynload.hxx>
#include <vos/diagnose.hxx>
#include <usr/services.hxx>
#include <vcl/svapp.hxx>
#include <usr/ustring.hxx>
#include <tools/string.hxx>
#include <vos/conditn.hxx>
#include <smart/com/sun/star/test/XSimpleTest.hxx>
using namespace rtl;
using namespace vos;
using namespace usr;
// Needed to switch on solaris threads
#ifdef SOLARIS
extern "C" void ChangeGlobalInit();
#endif
int __LOADONCALLAPI main (int argc, char **argv)
{
if( argc < 3) {
printf( "usage : testcomponent service dll [additional dlls]\n" );
exit( 0 );
}
#ifdef SOLARIS
// switch on threads in solaris
ChangeGlobalInit();
#endif
// create service manager
// XMultiServiceFactoryRef xSMgr = getProcessServiceManager();
XMultiServiceFactoryRef xSMgr = createRegistryServiceManager();
OSL_ASSERT( xSMgr.is() );
registerUsrServices( xSMgr );
setProcessServiceManager( xSMgr );
XImplementationRegistrationRef xReg;
XSimpleRegistryRef xSimpleReg;
try {
// Create registration service
XInterfaceRef x = xSMgr->createInstance(
UString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
x->queryInterface( XImplementationRegistration::getSmartUik() , xReg );
/* x = xSMgr->createInstance( L"stardiv.uno.repos.SimpleRegistry" );
OSL_ASSERT( x.is() );
x->queryInterface( XSimpleRegistry::getSmartUik() , xSimpleReg );
OSL_ASSERT( xSimpleReg.is() );
xSimpleReg->open( L"testcomp.rdb" , FALSE , TRUE );
*/ }
catch( Exception& e ) {
printf( "%s\n" , OWStringToOString( e.getName() , CHARSET_SYSTEM ).getStr() );
exit(1);
}
sal_Char szBuf[1024];
OString sTestName;
try {
// Load dll for the tested component
for( int n = 2 ; n <argc ; n ++ ) {
ORealDynamicLoader::computeModuleName( argv[n] , szBuf, 1024 );
UString aDllName( OStringToOWString( szBuf, CHARSET_SYSTEM ) );
xReg->registerImplementation(
UString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName,
xSimpleReg );
}
}
catch( Exception& e ) {
printf( "Couldn't reach dll %s\n" , szBuf );
printf( "%s\n" , OWStringToOString( e.getName() , CHARSET_SYSTEM ).getStr() );
exit(1);
}
try {
// Load dll for the test component
sTestName = "test";
sTestName += argv[2];
ORealDynamicLoader::computeModuleName( sTestName.getStr() , szBuf, 1024 );
UString aDllName = OStringToOWString( szBuf, CHARSET_SYSTEM );
xReg->registerImplementation(
UString::createFromAscii( "com.sun.star.loader.SharedLibrary" ) ,
aDllName,
xSimpleReg );
}
catch( Exception& e ) {
printf( "Couldn't reach dll %s\n" , szBuf );
printf( "%s\n" , OWStringToOString( e.getName() , CHARSET_SYSTEM ).getStr() );
exit(1);
}
// Instantiate test service
sTestName = "test.";
sTestName += argv[1];
XInterfaceRef xIntTest = xSMgr->createInstance( OStringToOWString( sTestName , CHARSET_SYSTEM ) );
XSimpleTestRef xTest( xIntTest , USR_QUERY );
if( ! xTest.is() ) {
printf( "Couldn't instantiate test service \n" );
exit( 1 );
}
INT32 nHandle = 0;
INT32 nNewHandle;
INT32 nErrorCount = 0;
INT32 nWarningCount = 0;
// loop until all test are performed
while( nHandle != -1 ) {
// Instantiate serivce
XInterfaceRef x = xSMgr->createInstance( OStringToOWString( argv[1] , CHARSET_SYSTEM ) );
if( ! x.is() ) {
printf( "Couldn't instantiate service !\n" );
exit( 1 );
}
// do the test
try {
nNewHandle = xTest->test( OStringToOWString( argv[1] , CHARSET_SYSTEM ) , x , nHandle );
}
catch ( Exception& e ) {
printf( "testcomponent : uncaught exception %s\n" ,
OWStringToOString( e.getName(), CHARSET_SYSTEM ).getStr() );
exit(1);
}
catch(...) {
printf( "testcomponent : uncaught unknown exception\n" );
exit(1);
}
// print errors and warning
Sequence<UString> seqErrors = xTest->getErrors();
Sequence<UString> seqWarnings = xTest->getWarnings();
if( seqWarnings.getLen() > nWarningCount ) {
printf( "Warnings during test %d!\n" , nHandle );
for( ; nWarningCount < seqWarnings.getLen() ; nWarningCount ++ ) {
printf( "Warning\n%s\n---------\n" ,
OWStringToOString( seqWarnings.getArray()[nWarningCount], CHARSET_SYSTEM ).getStr() );
}
}
if( seqErrors.getLen() > nErrorCount ) {
printf( "Errors during test %d!\n" , nHandle );
for( ; nErrorCount < seqErrors.getLen() ; nErrorCount ++ ) {
printf( "%s\n" ,
OWStringToOString(
seqErrors.getArray()[nErrorCount], CHARSET_SYSTEM ).getStr() );
}
}
nHandle = nNewHandle;
}
if( xTest->testPassed() ) {
printf( "Test passed !\n" );
}
else {
printf( "Test failed !\n" );
}
XComponentRef rComp( xSMgr , USR_QUERY );
rComp->dispose();
return 0;
}
| 28.926941 | 105 | 0.671823 | Grosskopf |
b4c6dbf231034e03bdfb97199c67fdca208eeaf2 | 3,882 | cpp | C++ | libtorrent/test/main.cpp | majestrate/twister-core | b509c202607f09169b3ca2380390eb91f6486238 | [
"MIT"
] | 754 | 2015-01-04T02:12:17.000Z | 2022-03-20T10:27:35.000Z | libtorrent/test/main.cpp | majestrate/twister-core | b509c202607f09169b3ca2380390eb91f6486238 | [
"MIT"
] | 144 | 2015-01-04T03:36:56.000Z | 2022-02-04T21:54:21.000Z | libtorrent/test/main.cpp | twisterarmy/twister-core | 9584caf124320fd185ec36fa5ffc95cc7891260e | [
"MIT"
] | 185 | 2015-01-04T23:11:39.000Z | 2022-03-03T18:39:19.000Z | /*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <boost/config.hpp>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h> // for exit()
#include "setup_transfer.hpp" // for tests_failure
int test_main();
#include "libtorrent/assert.hpp"
#include "libtorrent/file.hpp"
#include <signal.h>
void sig_handler(int sig)
{
char stack_text[10000];
#if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS
print_backtrace(stack_text, sizeof(stack_text), 30);
#elif defined __FUNCTION__
strcat(stack_text, __FUNCTION__);
#else
stack_text[0] = 0;
#endif
char const* sig_name = 0;
switch (sig)
{
#define SIG(x) case x: sig_name = #x; break
SIG(SIGSEGV);
#ifdef SIGBUS
SIG(SIGBUS);
#endif
SIG(SIGILL);
SIG(SIGABRT);
SIG(SIGFPE);
#ifdef SIGSYS
SIG(SIGSYS);
#endif
#undef SIG
};
fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text);
exit(138);
}
using namespace libtorrent;
int main()
{
#ifdef O_NONBLOCK
// on darwin, stdout is set to non-blocking mode by default
// which sometimes causes tests to fail with EAGAIN just
// by printing logs
int flags = fcntl(fileno(stdout), F_GETFL, 0);
fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);
flags = fcntl(fileno(stderr), F_GETFL, 0);
fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);
#endif
signal(SIGSEGV, &sig_handler);
#ifdef SIGBUS
signal(SIGBUS, &sig_handler);
#endif
signal(SIGILL, &sig_handler);
signal(SIGABRT, &sig_handler);
signal(SIGFPE, &sig_handler);
#ifdef SIGSYS
signal(SIGSYS, &sig_handler);
#endif
char dir[40];
snprintf(dir, sizeof(dir), "test_tmp_%u", rand());
std::string test_dir = complete(dir);
error_code ec;
create_directory(test_dir, ec);
if (ec)
{
fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str());
return 1;
}
#ifdef TORRENT_WINDOWS
SetCurrentDirectoryA(dir);
#else
chdir(dir);
#endif
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
test_main();
#ifndef BOOST_NO_EXCEPTIONS
}
catch (std::exception const& e)
{
std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
tests_failure = true;
}
catch (...)
{
std::cerr << "Terminated with unknown exception\n";
tests_failure = true;
}
#endif
fflush(stdout);
fflush(stderr);
remove_all(test_dir, ec);
if (ec)
fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str());
return tests_failure ? 1 : 0;
}
| 26.958333 | 81 | 0.735188 | majestrate |
b4c8ba33533492c15aee8d37ddd5e8f71a5c8c73 | 9,822 | cpp | C++ | tools/rpc_replay/rpc_replay.cpp | coxin12/brpc | 3d9a6ec81b74c875464fab1a6ab2ebf6081cadaa | [
"Apache-2.0"
] | 1 | 2021-03-21T14:41:57.000Z | 2021-03-21T14:41:57.000Z | tools/rpc_replay/rpc_replay.cpp | shaellancelot/brpc | 88481be8ab5ad23b30727ea17b27ce7557779690 | [
"Apache-2.0"
] | null | null | null | tools/rpc_replay/rpc_replay.cpp | shaellancelot/brpc | 88481be8ab5ad23b30727ea17b27ce7557779690 | [
"Apache-2.0"
] | 1 | 2018-03-13T10:29:40.000Z | 2018-03-13T10:29:40.000Z | // Copyright (c) 2014 Baidu, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Authors: Ge,Jun (gejun@baidu.com)
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <butil/macros.h>
#include <butil/file_util.h>
#include <bvar/bvar.h>
#include <bthread/bthread.h>
#include <brpc/channel.h>
#include <brpc/server.h>
#include <brpc/rpc_dump.h>
#include <brpc/serialized_request.h>
#include "info_thread.h"
DEFINE_string(dir, "", "The directory of dumped requests");
DEFINE_int32(times, 1, "Repeat replaying for so many times");
DEFINE_int32(qps, 0, "Limit QPS if this flag is positive");
DEFINE_int32(thread_num, 0, "Number of threads for replaying");
DEFINE_bool(use_bthread, true, "Use bthread to replay");
DEFINE_string(connection_type, "", "Connection type, choose automatically "
"according to protocol by default");
DEFINE_string(server, "0.0.0.0:8002", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Maximum retry times");
DEFINE_int32(dummy_port, 8899, "Port of dummy server(to monitor replaying)");
bvar::LatencyRecorder g_latency_recorder("rpc_replay");
bvar::Adder<int64_t> g_error_count("rpc_replay_error_count");
bvar::Adder<int64_t> g_sent_count;
// Include channels for all protocols that support both client and server.
class ChannelGroup {
public:
int Init();
~ChannelGroup();
// Get channel by protocol type.
brpc::Channel* channel(brpc::ProtocolType type) {
if ((size_t)type < _chans.size()) {
return _chans[(size_t)type];
}
return NULL;
}
private:
std::vector<brpc::Channel*> _chans;
};
int ChannelGroup::Init() {
{
// force global initialization of rpc.
brpc::Channel dummy_channel;
}
std::vector<std::pair<brpc::ProtocolType, brpc::Protocol> > protocols;
brpc::ListProtocols(&protocols);
size_t max_protocol_size = 0;
for (size_t i = 0; i < protocols.size(); ++i) {
max_protocol_size = std::max(max_protocol_size,
(size_t)protocols[i].first);
}
_chans.resize(max_protocol_size);
for (size_t i = 0; i < protocols.size(); ++i) {
if (protocols[i].second.support_client() &&
protocols[i].second.support_server()) {
const brpc::ProtocolType prot = protocols[i].first;
brpc::Channel* chan = new brpc::Channel;
brpc::ChannelOptions options;
options.protocol = prot;
options.connection_type = FLAGS_connection_type;
options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
options.max_retry = FLAGS_max_retry;
if (chan->Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(),
&options) != 0) {
LOG(ERROR) << "Fail to initialize channel";
return -1;
}
_chans[prot] = chan;
}
}
return 0;
}
ChannelGroup::~ChannelGroup() {
for (size_t i = 0; i < _chans.size(); ++i) {
delete _chans[i];
}
_chans.clear();
}
static void handle_response(brpc::Controller* cntl, int64_t start_time,
bool sleep_on_error/*note*/) {
// TODO(gejun): some bthreads are starved when new bthreads are created
// continuously, which happens when server is down and RPC keeps failing.
// Sleep a while on error to avoid that now.
const int64_t end_time = butil::gettimeofday_us();
const int64_t elp = end_time - start_time;
if (!cntl->Failed()) {
g_latency_recorder << elp;
} else {
g_error_count << 1;
if (sleep_on_error) {
bthread_usleep(10000);
}
}
delete cntl;
}
butil::atomic<int> g_thread_offset(0);
static void* replay_thread(void* arg) {
ChannelGroup* chan_group = static_cast<ChannelGroup*>(arg);
const int thread_offset = g_thread_offset.fetch_add(1, butil::memory_order_relaxed);
double req_rate = FLAGS_qps / (double)FLAGS_thread_num;
brpc::SerializedRequest req;
std::deque<int64_t> timeq;
size_t MAX_QUEUE_SIZE = (size_t)req_rate;
if (MAX_QUEUE_SIZE < 100) {
MAX_QUEUE_SIZE = 100;
} else if (MAX_QUEUE_SIZE > 2000) {
MAX_QUEUE_SIZE = 2000;
}
timeq.push_back(butil::gettimeofday_us());
for (int i = 0; !brpc::IsAskedToQuit() && i < FLAGS_times; ++i) {
brpc::SampleIterator it(FLAGS_dir);
int j = 0;
for (brpc::SampledRequest* sample = it.Next();
!brpc::IsAskedToQuit() && sample != NULL; sample = it.Next(), ++j) {
std::unique_ptr<brpc::SampledRequest> sample_guard(sample);
if ((j % FLAGS_thread_num) != thread_offset) {
continue;
}
brpc::Channel* chan =
chan_group->channel(sample->protocol_type());
if (chan == NULL) {
LOG(ERROR) << "No channel on protocol="
<< sample->protocol_type();
continue;
}
brpc::Controller* cntl = new brpc::Controller;
req.Clear();
cntl->reset_rpc_dump_meta(sample_guard.release());
if (sample->attachment_size() > 0) {
sample->request.cutn(
&req.serialized_data(),
sample->request.size() - sample->attachment_size());
cntl->request_attachment() = sample->request.movable();
} else {
req.serialized_data() = sample->request.movable();
}
g_sent_count << 1;
const int64_t start_time = butil::gettimeofday_us();
if (FLAGS_qps <= 0) {
chan->CallMethod(NULL/*use rpc_dump_context in cntl instead*/,
cntl, &req, NULL/*ignore response*/, NULL);
handle_response(cntl, start_time, true);
} else {
google::protobuf::Closure* done =
brpc::NewCallback(handle_response, cntl, start_time, false);
chan->CallMethod(NULL/*use rpc_dump_context in cntl instead*/,
cntl, &req, NULL/*ignore response*/, done);
const int64_t end_time = butil::gettimeofday_us();
int64_t expected_elp = 0;
int64_t actual_elp = 0;
timeq.push_back(end_time);
if (timeq.size() > MAX_QUEUE_SIZE) {
actual_elp = end_time - timeq.front();
timeq.pop_front();
expected_elp = (size_t)(1000000 * timeq.size() / req_rate);
} else {
actual_elp = end_time - timeq.front();
expected_elp = (size_t)(1000000 * (timeq.size() - 1) / req_rate);
}
if (actual_elp < expected_elp) {
bthread_usleep(expected_elp - actual_elp);
}
}
}
}
return NULL;
}
int main(int argc, char* argv[]) {
// Parse gflags. We recommend you to use gflags as well.
GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_dir.empty() ||
!butil::DirectoryExists(butil::FilePath(FLAGS_dir))) {
LOG(ERROR) << "--dir=<dir-of-dumped-files> is required";
return -1;
}
if (FLAGS_dummy_port >= 0) {
brpc::StartDummyServerAt(FLAGS_dummy_port);
}
ChannelGroup chan_group;
if (chan_group.Init() != 0) {
LOG(ERROR) << "Fail to init ChannelGroup";
return -1;
}
if (FLAGS_thread_num <= 0) {
if (FLAGS_qps <= 0) { // unlimited qps
FLAGS_thread_num = 50;
} else {
FLAGS_thread_num = FLAGS_qps / 10000;
if (FLAGS_thread_num < 1) {
FLAGS_thread_num = 1;
}
if (FLAGS_thread_num > 50) {
FLAGS_thread_num = 50;
}
}
}
std::vector<bthread_t> tids;
tids.resize(FLAGS_thread_num);
if (!FLAGS_use_bthread) {
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (pthread_create(&tids[i], NULL, replay_thread, &chan_group) != 0) {
LOG(ERROR) << "Fail to create pthread";
return -1;
}
}
} else {
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (bthread_start_background(
&tids[i], NULL, replay_thread, &chan_group) != 0) {
LOG(ERROR) << "Fail to create bthread";
return -1;
}
}
}
brpc::InfoThread info_thr;
brpc::InfoThreadOptions info_thr_opt;
info_thr_opt.latency_recorder = &g_latency_recorder;
info_thr_opt.error_count = &g_error_count;
info_thr_opt.sent_count = &g_sent_count;
if (!info_thr.start(info_thr_opt)) {
LOG(ERROR) << "Fail to create info_thread";
return -1;
}
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (!FLAGS_use_bthread) {
pthread_join(tids[i], NULL);
} else {
bthread_join(tids[i], NULL);
}
}
info_thr.stop();
return 0;
}
| 35.716364 | 88 | 0.582264 | coxin12 |
b4c96c9995e47735e8c51f89cf4515a8855830f6 | 1,658 | hpp | C++ | android-31/android/service/notification/NotificationListenerService_Ranking.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/service/notification/NotificationListenerService_Ranking.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/service/notification/NotificationListenerService_Ranking.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../../JObject.hpp"
namespace android::app
{
class NotificationChannel;
}
namespace android::content::pm
{
class ShortcutInfo;
}
class JString;
class JObject;
class JString;
namespace android::service::notification
{
class NotificationListenerService_Ranking : public JObject
{
public:
// Fields
static jint USER_SENTIMENT_NEGATIVE();
static jint USER_SENTIMENT_NEUTRAL();
static jint USER_SENTIMENT_POSITIVE();
static jint VISIBILITY_NO_OVERRIDE();
// QJniObject forward
template<typename ...Ts> explicit NotificationListenerService_Ranking(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
NotificationListenerService_Ranking(QJniObject obj);
// Constructors
NotificationListenerService_Ranking();
// Methods
jboolean canBubble() const;
jboolean canShowBadge() const;
jboolean equals(JObject arg0) const;
android::app::NotificationChannel getChannel() const;
android::content::pm::ShortcutInfo getConversationShortcutInfo() const;
jint getImportance() const;
JString getImportanceExplanation() const;
JString getKey() const;
jlong getLastAudiblyAlertedMillis() const;
jint getLockscreenVisibilityOverride() const;
JString getOverrideGroupKey() const;
jint getRank() const;
JObject getSmartActions() const;
JObject getSmartReplies() const;
jint getSuppressedVisualEffects() const;
jint getUserSentiment() const;
jboolean isAmbient() const;
jboolean isConversation() const;
jboolean isSuspended() const;
jboolean matchesInterruptionFilter() const;
};
} // namespace android::service::notification
| 28.101695 | 176 | 0.764777 | YJBeetle |
b4cb37fb8d82cabc96487db673d422889877bfe4 | 4,070 | cc | C++ | chrome/browser/ui/views/autofill/payments/virtual_card_selection_dialog_browsertest.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 | chrome/browser/ui/views/autofill/payments/virtual_card_selection_dialog_browsertest.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 | chrome/browser/ui/views/autofill/payments/virtual_card_selection_dialog_browsertest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/callback_helpers.h"
#include "base/run_loop.h"
#include "chrome/browser/ui/autofill/payments/virtual_card_selection_dialog_controller_impl.h"
#include "chrome/browser/ui/autofill/payments/virtual_card_selection_dialog_view.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/browser/ui/views/autofill/payments/virtual_card_selection_dialog_view_impl.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "content/public/test/browser_test.h"
#include "ui/views/controls/button/label_button.h"
namespace autofill {
namespace {
constexpr char kOneCardTest[] = "OneCard";
constexpr char kTwoCardsTest[] = "TwoCards";
} // namespace
class VirtualCardSelectionDialogBrowserTest : public DialogBrowserTest {
public:
VirtualCardSelectionDialogBrowserTest() = default;
// DialogBrowserTest:
void ShowUi(const std::string& name) override {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
// Do lazy initialization of VirtualCardSelectionDialogControllerImpl.
VirtualCardSelectionDialogControllerImpl::CreateForWebContents(
web_contents);
CreditCard card1 = test::GetFullServerCard();
if (name == kOneCardTest) {
controller()->ShowDialog({&card1}, base::DoNothing());
} else if (name == kTwoCardsTest) {
CreditCard card2 = test::GetFullServerCard();
controller()->ShowDialog({&card1, &card2}, base::DoNothing());
}
}
VirtualCardSelectionDialogViewImpl* GetDialog() {
if (!controller())
return nullptr;
VirtualCardSelectionDialogView* dialog_view = controller()->dialog_view();
if (!dialog_view)
return nullptr;
return static_cast<VirtualCardSelectionDialogViewImpl*>(dialog_view);
}
VirtualCardSelectionDialogControllerImpl* controller() {
if (!browser() || !browser()->tab_strip_model() ||
!browser()->tab_strip_model()->GetActiveWebContents())
return nullptr;
return VirtualCardSelectionDialogControllerImpl::FromWebContents(
browser()->tab_strip_model()->GetActiveWebContents());
}
private:
DISALLOW_COPY_AND_ASSIGN(VirtualCardSelectionDialogBrowserTest);
};
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
InvokeUi_OneCard) {
ShowAndVerifyUi();
}
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
CanCloseTabWhileDialogShowing) {
ShowUi(kOneCardTest);
VerifyUi();
browser()->tab_strip_model()->GetActiveWebContents()->Close();
base::RunLoop().RunUntilIdle();
}
// Ensures closing browser while dialog being visible is correctly handled.
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
CanCloseBrowserWhileDialogShowing) {
ShowUi(kOneCardTest);
VerifyUi();
browser()->window()->Close();
base::RunLoop().RunUntilIdle();
}
// Ensures dialog is closed when ok button is clicked when there is one card
// available.
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
ClickOkButton_OneCard) {
ShowUi(kOneCardTest);
VerifyUi();
ASSERT_TRUE(GetDialog()->GetOkButton()->GetEnabled());
GetDialog()->AcceptDialog();
base::RunLoop().RunUntilIdle();
}
// TODO(crbug.com/1020740): Add browser test for OK button when there are two
// cards. The logic to update button state will be implemented in the CL adding
// card list in the dialog.
// Ensures dialog is closed when cancel button is clicked.
IN_PROC_BROWSER_TEST_F(VirtualCardSelectionDialogBrowserTest,
ClickCancelButton) {
ShowUi(kOneCardTest);
VerifyUi();
GetDialog()->CancelDialog();
base::RunLoop().RunUntilIdle();
}
// TODO(crbug.com/1020740): Add more browsertests for interactions.
} // namespace autofill
| 34.201681 | 94 | 0.739803 | Ron423c |
b4cbcff6dd3c1ecaabf5a595e8d82e24bcafa1a6 | 21,105 | cpp | C++ | core/conn/odbc/src/odbc/nsksrvr/Interface/linux/Listener_srvr_ps.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 148 | 2015-06-18T21:26:04.000Z | 2017-12-25T01:47:01.000Z | core/conn/odbc/src/odbc/nsksrvr/Interface/linux/Listener_srvr_ps.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 1,352 | 2015-06-20T03:05:01.000Z | 2017-12-25T14:13:18.000Z | core/conn/odbc/src/odbc/nsksrvr/Interface/linux/Listener_srvr_ps.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 166 | 2015-06-19T18:52:10.000Z | 2017-12-27T06:19:32.000Z | /**********************************************************************
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
********************************************************************/
#include <platform_ndcs.h>
#include "errno.h"
#include "Transport.h"
#include "Listener_srvr.h"
#include "TCPIPSystemSrvr.h"
#include "FileSystemSrvr.h"
#include "Global.h"
#include "SrvrConnect.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <linux/unistd.h>
extern SRVR_GLOBAL_Def *srvrGlobal;
extern void SyncPublicationThread();
void CNSKListenerSrvr::closeTCPIPSession(int fnum)
{
shutdown(fnum, SHUT_RDWR);
close(fnum);
FD_CLR(fnum, &read_fds_);
FD_CLR(fnum, &error_fds_);
// if (fnum == max_read_fd_) max_read_fd_--;
// max_read_fd_ = m_nListenSocketFnum;
max_read_fd_ = pipefd[0]; // m_nListenSocketFnum;
}
bool CNSKListenerSrvr::ListenToPort(int port)
{
char tmp[500];
int error;
struct sockaddr_in6 *sin6 = NULL;
struct sockaddr_in *sin4 = NULL;
max_read_fd_ = 0;
if (m_nListenSocketFnum < 1)
{
sprintf(tmp,"ListenToPort[%d][%d]", port, m_nListenSocketFnum );
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, tmp, O_INIT_PROCESS, F_SOCKET, 0, 0);
if (m_bIPv4 == false)
{
//LCOV_EXCL_START
if ((m_nListenSocketFnum = socket(AF_INET6, SOCK_STREAM, 0)) < 0 )
{
m_bIPv4 = true;
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
}
//LCOV_EXCL_STOP
}
else
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
if (m_nListenSocketFnum < 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_SOCKET, errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
if(strncmp(m_TcpProcessName,"$ZTC0",5) != 0)
{
//LCOV_EXCL_START
/*
* bind to a specific interface (m_TcpProcessName is initialized by default to $ztc0)
*/
struct ifaddrs *ifa = NULL, *ifp = NULL;
bool bFoundInterface = false;
if (getifaddrs (&ifp) < 0)
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, "ListenToPort - getifaddrs", O_INIT_PROCESS, F_SOCKET, errno, 0);
goto bailout;
}
for (ifa = ifp; ifa != NULL; ifa = ifa->ifa_next)
{
if(! ifa->ifa_addr)
continue;
if( (m_bIPv4 == true && ifa->ifa_addr->sa_family != AF_INET) ||
(m_bIPv4 == false && ifa->ifa_addr->sa_family != AF_INET6) ||
(strcmp(ifa->ifa_name,m_TcpProcessName) != 0) )
continue;
bFoundInterface = true;
if(m_bIPv4 == false)
{
sin6 = (struct sockaddr_in6*)ifa->ifa_addr;
memcpy(&m_ListenSocketAddr6,sin6,sizeof(m_ListenSocketAddr6));
m_ListenSocketAddr6.sin6_port = htons((uint16_t) port);
break;
}
else
{
sin4 = (struct sockaddr_in*)ifa->ifa_addr;
memcpy(&m_ListenSocketAddr,sin4,sizeof(m_ListenSocketAddr));
m_ListenSocketAddr.sin_port = htons((in_port_t) port);
break;
}
} // for all interfaces
freeifaddrs(ifp);
if(!bFoundInterface)
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, "ListenToPort - no matching interface", O_INIT_PROCESS, F_SOCKET, errno, 0);
goto bailout;
}
//LCOV_EXCL_STOP
}
else
{
/*
* bind to all available interfaces
*/
if (m_bIPv4 == false)
{
//LCOV_EXCL_START
bzero((char*)&m_ListenSocketAddr6,sizeof(m_ListenSocketAddr6));
m_ListenSocketAddr6.sin6_family = AF_INET6;
m_ListenSocketAddr6.sin6_addr = in6addr_any;
m_ListenSocketAddr6.sin6_port = htons((uint16_t) port);
//LCOV_EXCL_STOP
}
else
{
bzero((char*)&m_ListenSocketAddr,sizeof(m_ListenSocketAddr));
m_ListenSocketAddr.sin_family = AF_INET;
m_ListenSocketAddr.sin_addr.s_addr = INADDR_ANY;
m_ListenSocketAddr.sin_port = htons((in_port_t) port);
}
}
int optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_REUSEADDR, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_REUSEADDR);
goto bailout;
//LCOV_EXCL_STOP
}
if (m_bIPv4 == false)
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr6, (int)sizeof(m_ListenSocketAddr6));
else
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr, (int)sizeof(m_ListenSocketAddr));
if (error < 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_BIND, errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_KEEPALIVE, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_KEEPALIVE);
goto bailout;
//LCOV_EXCL_STOP
}
}
error = listen(m_nListenSocketFnum, 100);
FD_ZERO(&read_fds_);
FD_ZERO(&error_fds_);
if(error >= 0)
{
FD_SET(m_nListenSocketFnum,&read_fds_);
FD_SET(m_nListenSocketFnum,&error_fds_);
// Keep track of highest socket file descriptor, for use in "select"
if (m_nListenSocketFnum > max_read_fd_) max_read_fd_ = m_nListenSocketFnum;
}
else
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_LISTENER, "ListenToPort", O_INIT_PROCESS, F_ACCEPT, errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
// If tracing is enabled, display trace info indicating new "listen"
LISTEN_ON_SOCKET((short)m_nListenSocketFnum);
return true;
bailout:
if (m_nListenSocketFnum > 0)
GTransport.m_TCPIPSystemSrvr_list->del_node(m_nListenSocketFnum);
// closeTCPIPSession(m_nListenSocketFnum);
m_nListenSocketFnum = -2;
sprintf(tmp,"bailout ListenToPort[%d][%d]", port, m_nListenSocketFnum );
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, tmp, O_INIT_PROCESS, F_SOCKET, 0, 0);
return false;
}
void* CNSKListenerSrvr::OpenTCPIPSession()
{
CTCPIPSystemSrvr* pnode = NULL;
int error;
int nSocketFnum = -2;
if (m_bIPv4 == false)
{
//LCOV_EXCL_START
m_nAcceptFromSocketAddrLen = sizeof(m_AcceptFromSocketAddr6);
nSocketFnum = accept(m_nListenSocketFnum, (sockaddr*)&m_AcceptFromSocketAddr6, (socklen_t *)&m_nAcceptFromSocketAddrLen);
//LCOV_EXCL_STOP
}
else
{
m_nAcceptFromSocketAddrLen = sizeof(m_AcceptFromSocketAddr);
nSocketFnum = accept(m_nListenSocketFnum, (sockaddr*)&m_AcceptFromSocketAddr, (socklen_t *)&m_nAcceptFromSocketAddrLen);
}
if(nSocketFnum == -1)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"OpenTCPIPSession", O_INIT_PROCESS, F_ACCEPT,
errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
TCP_SetKeepalive(nSocketFnum,
srvrGlobal->clientKeepaliveStatus,
srvrGlobal->clientKeepaliveIdletime,
srvrGlobal->clientKeepaliveIntervaltime,
srvrGlobal->clientKeepaliveRetrycount);
pnode = GTransport.m_TCPIPSystemSrvr_list->ins_node(nSocketFnum);
if (pnode == NULL)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"OpenTCPIPSession", O_INIT_PROCESS, F_INS_NODE,
SRVR_ERR_MEMORY_ALLOCATE, 0);
goto bailout;
//LCOV_EXCL_STOP
}
// clear/zero the set
FD_ZERO(&read_fds_);
FD_ZERO(&error_fds_);
// (re)set the listening socket
FD_SET(m_nListenSocketFnum,&read_fds_);
FD_SET(m_nListenSocketFnum,&error_fds_);
// (re) set the dummy pipe-read-fd
FD_SET(pipefd[0],&read_fds_);
FD_SET(pipefd[0],&error_fds_);
//set the connected socket
FD_SET(pnode->m_nSocketFnum,&read_fds_);
FD_SET(pnode->m_nSocketFnum,&error_fds_);
if (pnode->m_nSocketFnum > max_read_fd_)
max_read_fd_ = pnode->m_nSocketFnum;
m_nSocketFnum = (short) nSocketFnum;
return pnode;
bailout:
if (pnode != NULL)
GTransport.m_TCPIPSystemSrvr_list->del_node(nSocketFnum);
SRVR::BreakDialogue(NULL);
return NULL;
}
void * CNSKListenerSrvr::tcpip_listener(void *arg)
{
// Parameter is the CNSKListenerSrvr object
CNSKListenerSrvr *listener = (CNSKListenerSrvr *) arg;
int numReadyFds;
int handledFds;
ssize_t countRead;
CTCPIPSystemSrvr* pnode=NULL;
fd_set temp_read_fds, temp_error_fds;
struct timeval timeout;
struct timeval *pTimeout;
msg_enable_open_cleanup();
file_enable_open_cleanup();
//create a the dummy pipe
int rc = pipe(listener->pipefd);
if (rc < 0)
{
listener->TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_PIPE, F_INIT_PIPE,SRVR_ERR_UNKNOWN_REQUEST,0);
listener->TCP_TRACE_OUTPUT_R0();
}
FD_SET(listener->pipefd[0],&listener->read_fds_);
FD_SET(listener->pipefd[0],&listener->error_fds_);
if (listener->pipefd[0] > listener->max_read_fd_)
listener->max_read_fd_ = listener->pipefd[0];
// Persistently wait for input on sockets and then act on it.
while(listener->m_bTCPThreadKeepRunning)
{
// Wait for ready-to-read on any of the tcpip ports
memcpy(&temp_read_fds, &listener->read_fds_, sizeof(temp_read_fds));
memcpy(&temp_error_fds, &listener->error_fds_, sizeof(temp_error_fds));
long connIdleTimeout = SRVR::getConnIdleTimeout();
long srvrIdleTimeout = SRVR::getSrvrIdleTimeout();
bool connIdleTimer = false;
bool srvrIdleTimer = false;
if (srvrGlobal->srvrState == SRVR_CONNECTED)
{
if (connIdleTimeout != INFINITE_CONN_IDLE_TIMEOUT)
{
timeout.tv_sec = connIdleTimeout;
timeout.tv_usec = 0;
connIdleTimer = true;
pTimeout = &timeout;
}
else
{
timeout.tv_sec = 0;
timeout.tv_usec = 0;
pTimeout = NULL;
}
}
else
{
if (srvrIdleTimeout != INFINITE_SRVR_IDLE_TIMEOUT)
{
timeout.tv_sec = srvrIdleTimeout;
timeout.tv_usec = 0;
srvrIdleTimer = true;
pTimeout = &timeout;
}
else
{
timeout.tv_sec = 0;
timeout.tv_usec = 0;
pTimeout = NULL;
}
}
numReadyFds = select(listener->max_read_fd_+1, &temp_read_fds, NULL,&temp_error_fds, pTimeout);
srvrGlobal->mutex->lock();
if (numReadyFds == -1)
{
if (errno == EINTR)
{
srvrGlobal->mutex->unlock();
continue;
}
else
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_SELECT,errno,numReadyFds);
abort();
}
}
if (numReadyFds == 0) //Timeout expired
{
if (connIdleTimer)
SRVR::BreakDialogue(NULL);
else if (srvrIdleTimer)
SRVR::srvrIdleTimerExpired(NULL);
else
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_SELECT,errno,numReadyFds);
abort();
}
}
else
{
// Handle all ready-to-read file descriptors
handledFds = 0;
if(FD_ISSET(listener->pipefd[0], &temp_read_fds))
{
//dummy write, exit the loop
listener->m_bTCPThreadKeepRunning = false;
srvrGlobal->mutex->unlock();
break;
}
else if (FD_ISSET(listener->m_nListenSocketFnum,&temp_read_fds))
{
// Initiate a new client session
listener->OpenTCPIPSession();
listener->TRACE_INPUT((short)listener->m_nListenSocketFnum, 0, 0, 0);
handledFds++;
}
else if ((pnode=GTransport.m_TCPIPSystemSrvr_list->m_current_node) != NULL && FD_ISSET(pnode->m_nSocketFnum,&temp_read_fds))
{
short retries = 0;
do
{
countRead = recv(pnode->m_nSocketFnum,
pnode->m_IObuffer,
MAX_TCP_BUFFER_LENGTH, 0);
} while ((countRead < 0) && (errno == EINTR) && (retries++ < 3));
if (countRead <= 0)
{
GTransport.m_TCPIPSystemSrvr_list->del_node(pnode->m_nSocketFnum);
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_SELECT,errno, pnode->m_nSocketFnum);
SRVR::BreakDialogue(NULL);
}
else
{
pnode->m_rlength = countRead;
if (listener->CheckTCPIPRequest(pnode) == NULL)
{
SRVR::BreakDialogue(NULL);
}
}
handledFds++;
}
else
{
listener->TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_FD_ISSET,SRVR_ERR_UNKNOWN_REQUEST, -2);
listener->TCP_TRACE_OUTPUT_R0();
handledFds++;
}
if(handledFds != numReadyFds)
{
listener->TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_FD_ISSET,SRVR_ERR_UNKNOWN_REQUEST,0);
listener->TCP_TRACE_OUTPUT_R0();
}
}
srvrGlobal->mutex->unlock();
} //while(listener->m_bTCPThreadKeepRunning)
return NULL;
}
int CNSKListenerSrvr::runProgram(char* TcpProcessName, long port, int TransportTrace)
{
short fnum,error;
_cc_status cc;
short timeout;
unsigned short countRead;
SB_Tag_Type tag;
sprintf(m_TcpProcessName,"%s",TcpProcessName);
m_port = port;
INITIALIZE_TRACE(TransportTrace);
if ((error = FILE_OPEN_("$RECEIVE",8,&m_ReceiveFnum, 0, 0, 1, 4000)) != 0)
{
SET_ERROR((long)0, NSK, FILE_SYSTEM, UNKNOWN_API, E_SERVER,
"runProgram", O_INIT_PROCESS, F_FILE_OPEN_, error, 0);
return error;
}
if (ListenToPort(port) == false)
return SRVR_ERR_LISTENER_ERROR1;
READUPDATEX(m_ReceiveFnum, m_RequestBuf, MAX_BUFFER_LENGTH );
// Register with association server
SRVR::RegisterSrvr(srvrGlobal->IpAddress, srvrGlobal->HostName);
// Start tcpip listener thread
tcpip_tid = tcpip_listener_thr.create("TCPIP_listener",
CNSKListenerSrvr::tcpip_listener, this);
// Persistently wait for input on $RECEIVE and then act on it.
while(m_bKeepRunning)
{
RESET_ERRORS((long)0);
timeout = -1;
fnum = m_ReceiveFnum;
cc = AWAITIOX(&fnum, OMITREF, &countRead, &tag, timeout);
if (_status_lt(cc)) // some error or XCANCEL
{
//LCOV_EXCL_START
error=0;
XFILE_GETINFO_(fnum, &error);
if (error == 26) // XCANCEL was called
{
//join the tcpip thread
if(tcpip_tid != 0)
tcpip_listener_thr.join(tcpip_tid,NULL);
m_bKeepRunning = false;
break;
}
//LCOV_EXCL_STOP
}
TRACE_INPUT(fnum,countRead,tag,cc);
if (fnum == m_ReceiveFnum)
{
ADD_ONE_TO_HANDLE(&m_call_id);
CheckReceiveMessage(cc, countRead, &m_call_id);
READUPDATEX(m_ReceiveFnum, m_RequestBuf, MAX_BUFFER_LENGTH );
FS_TRACE_OUTPUT(cc);
}
else
{
//LCOV_EXCL_START
TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER, "runProgram",
O_DO_WRITE_READ, F_FILE_COMPLETE, SRVR_ERR_UNKNOWN_REQUEST,
fnum);
//LCOV_EXCL_STOP
}
}
return 0;
}
void CNSKListenerSrvr::SYSTEM_SNAMP(FILE* fp)
{
short info_ele;
char obuffer[1000];
char* pbuffer = obuffer;
int ip;
ip=sprintf(pbuffer,"\t<----SYSTEM SNAP---->\n");
pbuffer +=ip;
ip=sprintf(pbuffer,"\t\t%15.15s\t\t=\t\t%s(%d)\n","srvrState",frmt_serverstate(srvrGlobal->srvrState),srvrGlobal->srvrState);
pbuffer +=ip;
pbuffer = GTransport.m_FSystemSrvr_list->enum_nodes(pbuffer,fp);
pbuffer = GTransport.m_TCPIPSystemSrvr_list->enum_nodes(pbuffer,fp);
fwrite(obuffer, strlen(obuffer),1,fp);
fwrite("\r\n",2,1,fp);
fflush(fp);
}
void CNSKListenerSrvr::terminateThreads(int status)
{
// m_bKeepRunning = false; // break out of $RECEIVE and listen loop
char dummyWriteBuffer[100];
// Calling sync of repository thread here instead of exitServerProcess() since
// this also takes care of the case when the process is stopped via a system message.
SyncPublicationThread();
if(syscall(__NR_gettid) == srvrGlobal->receiveThrId)
{
// we're in the $recv thread
// If the tcp/ip thread is processing a request, the mutex will be locked
// in which case, we'll wait for that request to complete. Once the request
// is complete, the listen loop will exit out because m_bKeepRunning is false
// If we're able to acquire the lock rightaway, it means the tcp/ip thread is
// waiting on a select - we can then safely terminate the thread
/*
if(tcpip_tid != 0 && srvrGlobal->mutex->trylock() == 0)
tcpip_listener_thr.cancel(tcpip_tid);
*/
// Dummy write
if((tcpip_tid != 0) && (pipefd[1] != 0))
{
strcpy(dummyWriteBuffer, "bye-bye tcp/ip thread!");
write(pipefd[1], dummyWriteBuffer, strlen(dummyWriteBuffer));
}
//Wait tcpip thread to exit
if(tcpip_tid != 0)
tcpip_listener_thr.join(tcpip_tid,NULL);
}
else
{
// we're in the tcp/ip thread - we can just cancel the outstanding
// readupdate posted on $receive and exit the thread
int cc = XCANCEL(m_ReceiveFnum);
tcpip_listener_thr.exit(NULL);
}
}
bool CNSKListenerSrvr::verifyPortAvailable(const char * idForPort, int port)
{
char tmp[500];
int error;
struct sockaddr_in6 *sin6 = NULL;
struct sockaddr_in *sin4 = NULL;
max_read_fd_ = 0;
if (m_bIPv4 == false)
{
if ((m_nListenSocketFnum = socket(AF_INET6, SOCK_STREAM, 0)) < 0 )
{
m_bIPv4 = true;
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
}
}
else
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
if (m_nListenSocketFnum < 0)
{
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"verifyPortAvailable", O_INIT_PROCESS, F_SOCKET, errno, 0);
return false;
}
/*
* bind to all available interfaces
*/
if (m_bIPv4 == false)
{
bzero((char*)&m_ListenSocketAddr6,sizeof(m_ListenSocketAddr6));
m_ListenSocketAddr6.sin6_family = AF_INET6;
m_ListenSocketAddr6.sin6_addr = in6addr_any;
m_ListenSocketAddr6.sin6_port = htons((uint16_t) port);
}
else
{
bzero((char*)&m_ListenSocketAddr,sizeof(m_ListenSocketAddr));
m_ListenSocketAddr.sin_family = AF_INET;
m_ListenSocketAddr.sin_addr.s_addr = INADDR_ANY;
m_ListenSocketAddr.sin_port = htons((in_port_t) port);
}
int optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_REUSEADDR, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"verifyPortAvailable", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_REUSEADDR);
return false;
}
if (m_bIPv4 == false)
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr6, (int)sizeof(m_ListenSocketAddr6));
else
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr, (int)sizeof(m_ListenSocketAddr));
if (error < 0)
{
sprintf(tmp,"verifyPortAvailable:[%d]",port);
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
tmp, O_INIT_PROCESS, F_BIND, errno, 0);
return false;
}
optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_KEEPALIVE, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"verifyPortAvailable", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_KEEPALIVE);
return false;
}
return true;
}
| 29.683544 | 146 | 0.641554 | CoderSong2015 |
b4cd3db2b61d2df2b7acb44a0d4910af8ba5d18b | 7,493 | hpp | C++ | heart/src/solver/electrics/monodomain/MonodomainPurkinjeSolver.hpp | SoftMatterMechanics/ApicalStressFibers | 17d343c09a246a50f9e3a3cbfc399ca6bef353ce | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-09-10T16:12:13.000Z | 2020-09-10T16:12:13.000Z | heart/src/solver/electrics/monodomain/MonodomainPurkinjeSolver.hpp | SoftMatterMechanics/ApicalStressFibers | 17d343c09a246a50f9e3a3cbfc399ca6bef353ce | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | heart/src/solver/electrics/monodomain/MonodomainPurkinjeSolver.hpp | SoftMatterMechanics/ApicalStressFibers | 17d343c09a246a50f9e3a3cbfc399ca6bef353ce | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-09-10T16:12:21.000Z | 2020-09-10T16:12:21.000Z | /*
Copyright (c) 2005-2020, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MONODOMAINPURKINJESOLVER_HPP_
#define MONODOMAINPURKINJESOLVER_HPP_
#include "AbstractDynamicLinearPdeSolver.hpp"
#include "MassMatrixAssembler.hpp"
#include "NaturalNeumannSurfaceTermAssembler.hpp"
#include "MonodomainCorrectionTermAssembler.hpp"
#include "MonodomainTissue.hpp"
#include "MonodomainPurkinjeVolumeAssembler.hpp"
#include "MonodomainPurkinjeCableAssembler.hpp"
/**
* Solver class for Monodomain problems on tissues containing Purkinje fibres.
*
* In such problems, there are a subset of nodes of the mesh which are labelled as
* Purkinje nodes (and 1D elements connecting them). There are two variables to be
* computed, the (normal, myocardium) transmembrane voltage (V), defined at ALL nodes
* of the mesh, and the Purkinje voltage (Vp), defined at the purkinje nodes. Hence, the
* Purkinje nodes have two variables defined on them.
*
* For parallelisation/implementation reasons, we choose to have two variables to be
* defined at ALL nodes, introducing dummy variables Vp for non-Purkinje nodes. We set
* Vp = 0 at non-Purkinje nodes. Hence we solve for {V,Vp} at every node in the mesh,
* and PROBLEM_DIM=2. The linear system to be assembled, written as usual in block form
* but actually in striped form in the code, is:
*
* [ A1 0 ][V ] = [b1]
* [ 0 A2 ][Vp] = [b2]
*
* where each block is of size num_nodes.
*
* A1 and b1 are obtained by integrating over 3D myocardium elements and are therefore
* exactly the same as in a normal monodomain problem.
*
* Suppose the nodes are ordered such that all the Purkinje nodes are last. Then the matrix A2
* needs to be of the form
* A2 = [I 0 ]
* [0 Ap]
* where the first block is of size num_non_purkinje_nodes, and the second is of size num_purkinje_nodes.
* Ap is obtained by assembling over 1D purkinje elements. After assembly we add in the identity block,
* which is just represents the equations Vp=0 for the dummy variables (non-purkinje nodes). Finally,
* we similarly have
* b2 = [0 ]
* [bp]
* where bp involves a loop over 1D purkinje elements.
*
* This class implements the above, and is based on (but doesn't inherit from, as the PROBLEM_DIMENSION
* is different) MonodomainSolver.
*
*
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class MonodomainPurkinjeSolver
: public AbstractDynamicLinearPdeSolver<ELEMENT_DIM,SPACE_DIM,2>
{
private:
/** Saved pointer to the mesh in this class, as the pointer saved in the
* parent class (AbstractDynamicLinearPdeSolver::mpMesh) is not declared to
* be a pointer to a mixed mesh
*/
MixedDimensionMesh<ELEMENT_DIM,SPACE_DIM>* mpMixedMesh;
/** Monodomain tissue class (collection of cells, and conductivities) */
MonodomainTissue<ELEMENT_DIM,SPACE_DIM>* mpMonodomainTissue;
/** Boundary conditions */
BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,2>* mpBoundaryConditions;
/**
* The volume assembler, used to set up volume integral parts of the
* LHS matrix
*/
MonodomainPurkinjeVolumeAssembler<ELEMENT_DIM,SPACE_DIM>* mpVolumeAssembler;
/**
* The cable element assembler, used to set up cable integral parts of the
* LHS matrix
*/
MonodomainPurkinjeCableAssembler<ELEMENT_DIM,SPACE_DIM>* mpCableAssembler;
/** Assembler for surface integrals coming from any non-zero Neumann boundary conditions */
NaturalNeumannSurfaceTermAssembler<ELEMENT_DIM,SPACE_DIM,2>* mpNeumannSurfaceTermsAssembler;
// SVI and Purkinje not yet implemented:
// MonodomainCorrectionTermAssembler<ELEMENT_DIM,SPACE_DIM>* mpMonodomainCorrectionTermAssembler;
/** The mass matrix, used to computing the RHS vector */
Mat mMassMatrix;
/** The vector multiplied by the mass matrix. Ie, if the linear system to
* be solved is Ax=b (excluding surface integrals), this vector is z where b=Mz.
*/
Vec mVecForConstructingRhs;
/**
* Implementation of SetupLinearSystem() which uses the assembler to compute the
* LHS matrix, but sets up the RHS vector using the mass-matrix (constructed
* using a separate assembler) multiplied by a vector
*
* @param currentSolution Solution at current time
* @param computeMatrix Whether to compute the matrix of the linear system
*/
void SetupLinearSystem(Vec currentSolution, bool computeMatrix);
/**
* For the block in the LHS matrix corresponding to the Purkinje voltage at myocardium nodes:
* this block is zero after all elements are assembled so, so we set it to be the
* identity block. This is done by just checking which rows of the matrix has zero
* diagonal values.
*/
void SetIdentityBlockToLhsMatrix();
public:
/**
* Overloaded PrepareForSetupLinearSystem() methods which
* gets the cell models to solve themselves
*
* @param currentSolution solution at current time
*/
void PrepareForSetupLinearSystem(Vec currentSolution);
/**
* Overloaded InitialiseForSolve
*
* @param initialSolution initial solution
*/
virtual void InitialiseForSolve(Vec initialSolution);
/**
* Constructor
*
* @param pMesh pointer to the mesh
* @param pTissue pointer to the tissue
* @param pBoundaryConditions pointer to the boundary conditions
*/
MonodomainPurkinjeSolver(MixedDimensionMesh<ELEMENT_DIM,SPACE_DIM>* pMesh,
MonodomainTissue<ELEMENT_DIM,SPACE_DIM>* pTissue,
BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,2>* pBoundaryConditions);
/**
* Destructor
*/
virtual ~MonodomainPurkinjeSolver();
};
#endif // MONODOMAINPURKINJESOLVER_HPP_
| 40.722826 | 106 | 0.73949 | SoftMatterMechanics |
b4d2d41a91ef04a6c22f36a5d1a4454a9662faf1 | 2,250 | cc | C++ | libs/numeric/bindings/lapack/test/ublas_gesv.cc | inducer/boost-numeric-bindings | 1f994e8a2e161cddb6577eacc76b7bc358701cbe | [
"BSL-1.0"
] | 1 | 2019-01-14T19:18:21.000Z | 2019-01-14T19:18:21.000Z | libs/numeric/bindings/lapack/test/ublas_gesv.cc | inducer/boost-numeric-bindings | 1f994e8a2e161cddb6577eacc76b7bc358701cbe | [
"BSL-1.0"
] | null | null | null | libs/numeric/bindings/lapack/test/ublas_gesv.cc | inducer/boost-numeric-bindings | 1f994e8a2e161cddb6577eacc76b7bc358701cbe | [
"BSL-1.0"
] | 1 | 2020-11-23T09:56:06.000Z | 2020-11-23T09:56:06.000Z |
// solving A * X = B
// using driver function gesv()
#include <cstddef>
#include <iostream>
#include <complex>
#include <boost/numeric/bindings/lapack/gesv.hpp>
#include <boost/numeric/bindings/traits/ublas_matrix.hpp>
#include <boost/numeric/bindings/traits/std_vector.hpp>
#include "utils.h"
namespace ublas = boost::numeric::ublas;
namespace lapack = boost::numeric::bindings::lapack;
using std::size_t;
using std::cout;
using std::endl;
typedef std::complex<double> cmpx_t;
typedef ublas::matrix<double, ublas::column_major> m_t;
typedef ublas::matrix<cmpx_t, ublas::column_major> cm_t;
int main() {
cout << endl;
cout << "real system:" << endl << endl;
size_t n = 5;
m_t a (n, n); // system matrix
size_t nrhs = 2;
m_t x (n, nrhs), b (n, nrhs); // b -- right-hand side matrix
std::vector<int> ipiv (n); // pivot vector
init_symm (a);
// [n n-1 n-2 ... 1]
// [n-1 n n-1 ... 2]
// a = [n-2 n-1 n ... 3]
// [ ... ]
// [1 2 ... n-1 n]
m_t aa (a); // copy of a, because a is `lost' after gesv()
for (int i = 0; i < x.size1(); ++i) {
x (i, 0) = 1.;
x (i, 1) = 2.;
}
b = prod (a, x);
print_m (a, "A");
cout << endl;
print_m (b, "B");
cout << endl;
lapack::gesv (a, ipiv, b); // solving the system, b contains x
print_m (b, "X");
cout << endl;
x = prod (aa, b);
print_m (x, "B = A X");
cout << endl;
////////////////////////////////////////////////////////
cout << endl;
cout << "complex system:" << endl << endl;
cm_t ca (3, 3), cb (3, 1), cx (3, 1);
std::vector<int> ipiv2 (3);
ca (0, 0) = cmpx_t (3, 0);
ca (0, 1) = cmpx_t (4, 2);
ca (0, 2) = cmpx_t (-7, 5);
ca (1, 0) = cmpx_t (4, -2);
ca (1, 1) = cmpx_t (-5, 0);
ca (1, 2) = cmpx_t (0, -3);
ca (2, 0) = cmpx_t (-7, -5);
ca (2, 1) = cmpx_t (0, 3);
ca (2, 2) = cmpx_t (2, 0);
print_m (ca, "CA");
cout << endl;
for (int i = 0; i < cx.size1(); ++i)
cx (i, 0) = cmpx_t (1, -1);
cb = prod (ca, cx);
print_m (cb, "CB");
cout << endl;
int ierr = lapack::gesv (ca, ipiv2, cb);
if (ierr == 0)
print_m (cb, "CX");
else
cout << "matrix is singular" << endl;
cout << endl;
}
| 22.277228 | 67 | 0.507111 | inducer |
b4d360a6b712b22de80a1575c1c5a6da1e560128 | 5,130 | cpp | C++ | src/kl25_tsi.cpp | jlsalvat/mbed_frdm-kl25z | cdb70a1e39108d04dd110eb3ffe1a8056fa2e198 | [
"Unlicense"
] | 1 | 2019-11-16T19:37:57.000Z | 2019-11-16T19:37:57.000Z | src/kl25_tsi.cpp | jlsalvat/mbed_frdm-kl25z | cdb70a1e39108d04dd110eb3ffe1a8056fa2e198 | [
"Unlicense"
] | null | null | null | src/kl25_tsi.cpp | jlsalvat/mbed_frdm-kl25z | cdb70a1e39108d04dd110eb3ffe1a8056fa2e198 | [
"Unlicense"
] | null | null | null | #include "kl25_tsi.h"
#include "mbed.h"
/******************************************************************************
* Example 1 : put a cable on A0 pin and touch this pin for lighting red light
#include "mbed.h"
DigitalOut red(LED_RED);
int main(){
uint16_t sense_A0;
tsiInit(TSI_CURRENT_8uA, TSI_CURRENT_64uA, TSI_DV_1_03V, TSI_DIV_16, TSI_12_SCAN);
TSIChannelName channel= tsiActivateChannel(A0);
while(1) {
sense_A0 = 0;
tsiStart((TSIChannelName)channel);
while(!tsiAvalaible()) {
sense_A0= tsiRead();
printf("TOUCH: %d\r\n", sense_A0);
}
if(sense_A0<380)
red=1;
else
red=0;
}
}
*********************************************************************/
/********************************************************************
* Example read TSI in interrupt
#include "mbed.h"
DigitalOut red(LED_RED);
TSIChannelName gChannel;
void ISR_TSI0(){
gFlagTSI=true;
fgpioToggle(FPTA, 12); // D3 out
tsiStart(gChannel);
}
int main(){
uint16_t sense_A0;
tsiInit(TSI_CURRENT_8uA, TSI_CURRENT_64uA, TSI_DV_1_03V, TSI_DIV_16, TSI_12_SCAN);
gChannel= tsiActivateChannel(A0);
tsiSetTreshold(375,330);
tsiEnableInterrupt();
tsiStart(gChannel);
tsi_attachInterrupt(ISR_TSI0);
while(1) {
sense_A0 = 0;
wait(0.1);
if(gFlagTSI){
sense_A0= tsiRead();
printf("TOUCH: %d\r\n", sense_A0);
if (red.read() == 0)
red= 1;
else
red = 0;
gFlagTSI=false;
}
}
}
**********************************************************/
void (*fTSI0)(void);
// RAM interrupt handler relocated
void TSI0_IRQ_Handler(){
fTSI0();
TSI0->GENCS |=TSI_GENCS_OUTRGF_MASK ;//clear TOF
}
void tsiInit(TSI_Charge_Current refChg, TSI_Charge_Current extChg, TSI_DV dvolt, TSI_DIV_PRESCALER ps, TSI_NUMBER_OF_SCAN nscn) {
// The first version is preconfigured for non-noise detection, no interrupts, not running on stop modes, software trigger
SIM->SCGC5 |= SIM_SCGC5_TSI_MASK; // clock gate for TSI
TSI0->GENCS = 0xC0000080 | ((refChg & 0x07) << 21) | ((extChg & 0x07) << 16) | ((dvolt & 0x03) << 19) | ((ps & 0x07) << 13) | ((nscn & 0x1F) << 8);
}
/* Function to configure a pin to work with the corresponding channel (passed as the single parameter) */
TSIChannelName tsiActivateChannel(PinName pin) {
// reads channel number and sets the MUX of the corresponding pin to ALT0 function
unsigned int port = (unsigned int)pin >> PORT_SHIFT;
unsigned int pin_n = (pin&0xFF)>>2;
switch(port){
case 0: SIM->SCGC5|=SIM_SCGC5_PORTA_MASK; break;
case 1: SIM->SCGC5|=SIM_SCGC5_PORTB_MASK; break;
case 2: SIM->SCGC5|=SIM_SCGC5_PORTC_MASK; break;
}
TSIChannelName channel = (TSIChannelName)pinmap_peripheral(pin, PinMap_TSI);
if(((int)channel)==NC)
error("PinName provided to tsiActivateChannel() does not correspond to any known TSI channel.");
printf("port=%d, pn_n=%d, channel=%d\n\r",port,pin_n,channel);
PORT_Type *port_reg = (PORT_Type *)(PORTA_BASE + 0x1000 *port);
port_reg->PCR[pin_n] &= ~PORT_PCR_MUX_MASK;//choose ALT0 pin
return channel;
}
// Function to trigger the reading of a given channel
void tsiStart(TSIChannelName channel) {
//writes 1 to the software trigger bit, defining the channel number in the respective bits
TSI0->GENCS |= TSI_GENCS_EOSF_MASK; // clears EOSF
TSI0->DATA = TSI_DATA_SWTS_MASK | TSI_DATA_TSICH(channel);
}
void tsiSetTreshold(uint16_t tresholdHigh,uint16_t tresholdLow){
unsigned int tshd = (tresholdLow&0xFFFF) | (tresholdHigh<<16);
TSI0->TSHD=tshd;
printf("treshold=%x\n\r",tshd);
}
void tsiEnableInterruptOnTreshold(){
TSI0->GENCS|=TSI_GENCS_TSIIEN_MASK;//The interrupt will wake MCU from low power mode if this interrupt is enabled.
TSI0->GENCS|=TSI_GENCS_STPE_MASK;//This bit enables TSI module function in low power modes
TSI0->GENCS&=~TSI_GENCS_ESOR_MASK;//0 Out-of-range interrupt is allowed.
}
void tsiEnableInterrupt(){
TSI0->GENCS|=TSI_GENCS_TSIIEN_MASK; //This bit enables TSI module interrupt request to CPU when the scan completes
TSI0->GENCS|=TSI_GENCS_ESOR_MASK;//1 End-of-scan interrupt is allowed.
}
void tsiDisableInterrupt(){
TSI0->GENCS&=~TSI_GENCS_TSIIEN_MASK;//The interrupt will wake MCU from low power mode if this interrupt is enabled.
TSI0->GENCS&=~TSI_GENCS_STPE_MASK;//This bit enables TSI module function in low power modes
}
void tsi_attachTSI0_IRQHandler(){
NVIC_EnableIRQ(TSI0_IRQn);
__enable_irq();
}
void tsi_attachInterrupt(void (*userFunc)(void)){
fTSI0 = userFunc;
NVIC_SetVector(TSI0_IRQn, (uint32_t)TSI0_IRQ_Handler);
NVIC_EnableIRQ(TSI0_IRQn);
__enable_irq();
}
void tsi_dettachInterrupt(){
NVIC_DisableIRQ(TSI0_IRQn);
}
// Function to read scan result; returns zero if not finished
uint16_t tsiRead() {
uint16_t aux;
aux = TSI0->DATA & 0x0000FFFF;
TSI0->GENCS |= TSI_GENCS_EOSF_MASK; // clears EOSF
return aux;
}
| 34.897959 | 151 | 0.64386 | jlsalvat |
b4d4abdff683cda1524438f03f2b408dfdc4a97d | 570 | cpp | C++ | CONTESTS/CODEFORCES/div2 835/835 B.cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | 1 | 2021-11-22T02:26:43.000Z | 2021-11-22T02:26:43.000Z | CONTESTS/CODEFORCES/div2 835/835 B.cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | CONTESTS/CODEFORCES/div2 835/835 B.cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string s;
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
std::ios_base::sync_with_stdio(false);
cin.tie(0);
ll k, cnt=0;
cin>>k>>s;
sort(s.begin(), s.end());
int len = s.size();
for(int i=0; i<len; i++) {
cnt+=(s[i]-'0');
}
int ans=0;
for(int i=0; cnt<k; i++) {
ans++;
cnt+= (9 - (s[i] - '0') );
}
cout<<ans<<endl;
return 0;
}
| 14.25 | 43 | 0.42807 | priojeetpriyom |
b4d4b3c7310008c7f8a6d6ded367e9df3489bfa7 | 62,613 | cxx | C++ | Libs/MRML/Logic/vtkMRMLColorLogic.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Libs/MRML/Logic/vtkMRMLColorLogic.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Libs/MRML/Logic/vtkMRMLColorLogic.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | /*=auto=========================================================================
Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $RCSfile: vtkMRMLColorLogic.cxx,v $
Date: $Date$
Version: $Revision$
=========================================================================auto=*/
// MRMLLogic includes
#include "vtkMRMLColorLogic.h"
// MRML includes
#include "vtkMRMLColorTableNode.h"
#include "vtkMRMLColorTableStorageNode.h"
#include "vtkMRMLFreeSurferProceduralColorNode.h"
#include "vtkMRMLdGEMRICProceduralColorNode.h"
#include "vtkMRMLPETProceduralColorNode.h"
#include "vtkMRMLProceduralColorStorageNode.h"
#include "vtkMRMLScene.h"
// VTK sys includes
#include <vtkLookupTable.h>
#include <vtksys/SystemTools.hxx>
// VTK includes
#include <vtkColorTransferFunction.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
// STD includes
#include <algorithm>
#include <cassert>
#include <ctype.h> // For isspace
#include <functional>
#include <sstream>
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::TempColorNodeID;
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkMRMLColorLogic);
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::DEFAULT_TERMINOLOGY_NAME = "GenericAnatomyColors";
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::StandardTerm::Print(std::ostream& os)
{
vtkIndent indent;
this->PrintSelf(os, indent.GetNextIndent());
}
//----------------------------------------------------------------------------
std::ostream& vtkMRMLColorLogic::StandardTerm::operator<<(std::ostream& os)
{
this->Print(os);
return os;
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::StandardTerm::PrintSelf(std::ostream &os, vtkIndent indent)
{
os << indent << "Code value: " << CodeValue.c_str() << std::endl
<< indent << "Code scheme designator: " << CodingSchemeDesignator.c_str() << std::endl
<< indent << "Code meaning: " << CodeMeaning.c_str()
<< std::endl;
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::ColorLabelCategorization::Print(std::ostream& os)
{
vtkIndent indent;
this->PrintSelf(os, indent.GetNextIndent());
}
//----------------------------------------------------------------------------
std::ostream& vtkMRMLColorLogic::ColorLabelCategorization::operator<<(std::ostream& os)
{
this->Print(os);
return os;
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::ColorLabelCategorization::PrintSelf(ostream &os, vtkIndent indent)
{
os << "Label: " << LabelValue << std::endl;
os << "Segmented property category:\n";
SegmentedPropertyCategory.PrintSelf(os, indent);
os << "Segmented property type:\n";
SegmentedPropertyType.PrintSelf(os, indent);
os << "Segmented property type modifier:\n";
SegmentedPropertyTypeModifier.PrintSelf(os, indent);
os << "Anatomic region:\n";
AnatomicRegion.PrintSelf(os, indent);
os << "Antatomic region modifier:\n";
AnatomicRegionModifier.PrintSelf(os, indent);
os << std::endl;
}
//----------------------------------------------------------------------------
vtkMRMLColorLogic::vtkMRMLColorLogic()
{
this->UserColorFilePaths = NULL;
}
//----------------------------------------------------------------------------
vtkMRMLColorLogic::~vtkMRMLColorLogic()
{
// remove the default color nodes
this->RemoveDefaultColorNodes();
// clear out the lists of files
this->ColorFiles.clear();
this->TerminologyColorFiles.clear();
this->UserColorFiles.clear();
if (this->UserColorFilePaths)
{
delete [] this->UserColorFilePaths;
this->UserColorFilePaths = NULL;
}
}
//------------------------------------------------------------------------------
void vtkMRMLColorLogic::SetMRMLSceneInternal(vtkMRMLScene* newScene)
{
// We are solely interested in vtkMRMLScene::NewSceneEvent,
// we don't want to listen to any other events.
vtkIntArray* sceneEvents = vtkIntArray::New();
sceneEvents->InsertNextValue(vtkMRMLScene::NewSceneEvent);
this->SetAndObserveMRMLSceneEventsInternal(newScene, sceneEvents);
sceneEvents->Delete();
if (newScene)
{
this->OnMRMLSceneNewEvent();
}
}
//------------------------------------------------------------------------------
void vtkMRMLColorLogic::OnMRMLSceneNewEvent()
{
this->AddDefaultColorNodes();
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkObject::PrintSelf(os, indent);
os << indent << "vtkMRMLColorLogic: " << this->GetClassName() << "\n";
os << indent << "UserColorFilePaths: " << this->GetUserColorFilePaths() << "\n";
os << indent << "Color Files:\n";
for (size_t i = 0; i < this->ColorFiles.size(); i++)
{
os << indent.GetNextIndent() << i << " " << this->ColorFiles[i].c_str() << "\n";
}
os << indent << "User Color Files:\n";
for (size_t i = 0; i < this->UserColorFiles.size(); i++)
{
os << indent.GetNextIndent() << i << " " << this->UserColorFiles[i].c_str() << "\n";
}
os << indent << "Terminology Color Files:\n";
for (size_t i = 0; i < this->TerminologyColorFiles.size(); i++)
{
os << indent.GetNextIndent() << i << " " << this->TerminologyColorFiles[i].c_str() << "\n";
}
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultColorNodes()
{
// create the default color nodes, they don't get saved with the scenes as
// they'll be created on start up, and when a new
// scene is opened
if (this->GetMRMLScene() == NULL)
{
vtkWarningMacro("vtkMRMLColorLogic::AddDefaultColorNodes: no scene to which to add nodes\n");
return;
}
this->GetMRMLScene()->StartState(vtkMRMLScene::BatchProcessState);
// add the labels first
this->AddLabelsNode();
// add the rest of the default color table nodes
this->AddDefaultTableNodes();
// add default procedural nodes, including a random one
this->AddDefaultProceduralNodes();
// add freesurfer nodes
this->AddFreeSurferNodes();
// add the PET nodes
this->AddPETNodes();
// add the dGEMRIC nodes
this->AddDGEMRICNodes();
// file based labels
// first check for any new ones
// load the one from the default resources directory
this->AddDefaultFileNodes();
// now add ones in files that the user pointed to, these ones are not hidden
// from the editors
this->AddUserFileNodes();
// now load in the terminology color files and associate them with the
// color nodes
this->AddDefaultTerminologyColors();
vtkDebugMacro("Done adding default color nodes");
this->GetMRMLScene()->EndState(vtkMRMLScene::BatchProcessState);
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::RemoveDefaultColorNodes()
{
// try to find any of the default colour nodes that are still in the scene
if (this->GetMRMLScene() == NULL)
{
// nothing can do, it's gone
return;
}
this->GetMRMLScene()->StartState(vtkMRMLScene::BatchProcessState);
vtkMRMLColorTableNode *basicNode = vtkMRMLColorTableNode::New();
vtkMRMLColorTableNode *node;
for (int i = basicNode->GetFirstType(); i <= basicNode->GetLastType(); i++)
{
// don't have a File node...
if (i != vtkMRMLColorTableNode::File
&& i != vtkMRMLColorTableNode::Obsolete)
{
//std::string id = std::string(this->GetColorTableNodeID(i));
const char* id = this->GetColorTableNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
}
}
basicNode->Delete();
// remove freesurfer nodes
vtkMRMLFreeSurferProceduralColorNode *basicFSNode = vtkMRMLFreeSurferProceduralColorNode::New();
vtkMRMLFreeSurferProceduralColorNode *fsnode;
for (int i = basicFSNode->GetFirstType(); i <= basicFSNode->GetLastType(); i++)
{
basicFSNode->SetType(i);
const char* id = this->GetFreeSurferColorNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
fsnode = vtkMRMLFreeSurferProceduralColorNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (fsnode != NULL)
{
this->GetMRMLScene()->RemoveNode(fsnode);
}
}
basicFSNode->Delete();
// remove the procedural color nodes (after the fs proc nodes as
// getting them by class)
std::vector<vtkMRMLNode *> procNodes;
int numProcNodes = this->GetMRMLScene()->GetNodesByClass("vtkMRMLProceduralColorNode", procNodes);
for (int i = 0; i < numProcNodes; i++)
{
vtkMRMLProceduralColorNode* procNode = vtkMRMLProceduralColorNode::SafeDownCast(procNodes[i]);
if (procNode != NULL &&
strcmp(procNode->GetID(), this->GetProceduralColorNodeID(procNode->GetName())) == 0)
{
// it's one we added
this->GetMRMLScene()->RemoveNode(procNode);
}
}
// remove the fs lookup table node
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(this->GetDefaultFreeSurferLabelMapColorNodeID()));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
// remove the PET nodes
vtkMRMLPETProceduralColorNode *basicPETNode = vtkMRMLPETProceduralColorNode::New();
vtkMRMLPETProceduralColorNode *PETnode;
for (int i = basicPETNode->GetFirstType(); i <= basicPETNode->GetLastType(); i++)
{
basicPETNode->SetType(i);
const char* id = this->GetPETColorNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
PETnode = vtkMRMLPETProceduralColorNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (PETnode != NULL)
{
this->GetMRMLScene()->RemoveNode(PETnode);
}
}
basicPETNode->Delete();
// remove the dGEMRIC nodes
vtkMRMLdGEMRICProceduralColorNode *basicdGEMRICNode = vtkMRMLdGEMRICProceduralColorNode::New();
vtkMRMLdGEMRICProceduralColorNode *dGEMRICnode;
for (int i = basicdGEMRICNode->GetFirstType(); i <= basicdGEMRICNode->GetLastType(); i++)
{
basicdGEMRICNode->SetType(i);
const char* id = this->GetdGEMRICColorNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
dGEMRICnode = vtkMRMLdGEMRICProceduralColorNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (dGEMRICnode != NULL)
{
this->GetMRMLScene()->RemoveNode(dGEMRICnode);
}
}
basicdGEMRICNode->Delete();
// remove the file based labels node
for (unsigned int i = 0; i < this->ColorFiles.size(); i++)
{
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(this->GetFileColorNodeID(this->ColorFiles[i].c_str())));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
}
for (unsigned int i = 0; i < this->UserColorFiles.size(); i++)
{
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(this->GetFileColorNodeID(this->UserColorFiles[i].c_str())));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
}
this->GetMRMLScene()->EndState(vtkMRMLScene::BatchProcessState);
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetColorTableNodeID(int type)
{
vtkNew<vtkMRMLColorTableNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetFreeSurferColorNodeID(int type)
{
vtkNew<vtkMRMLFreeSurferProceduralColorNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetPETColorNodeID (int type )
{
vtkNew<vtkMRMLPETProceduralColorNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetdGEMRICColorNodeID(int type)
{
vtkNew<vtkMRMLdGEMRICProceduralColorNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetColorNodeID(vtkMRMLColorNode* colorNode)
{
assert(colorNode);
std::string id = std::string(colorNode->GetClassName()) +
std::string(colorNode->GetTypeAsString());
vtkMRMLColorLogic::TempColorNodeID = id;
return vtkMRMLColorLogic::TempColorNodeID.c_str();
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetProceduralColorNodeID(const char *name)
{
std::string id = std::string("vtkMRMLProceduralColorNode") + std::string(name);
vtkMRMLColorLogic::TempColorNodeID = id;
return vtkMRMLColorLogic::TempColorNodeID.c_str();
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetFileColorNodeSingletonTag(const char * fileName)
{
std::string singleton = std::string("File") +
vtksys::SystemTools::GetFilenameName(fileName);
return singleton;
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetFileColorNodeID(const char * fileName)
{
std::string id = std::string("vtkMRMLColorTableNode") +
vtkMRMLColorLogic::GetFileColorNodeSingletonTag(fileName);
vtkMRMLColorLogic::TempColorNodeID = id;
return vtkMRMLColorLogic::TempColorNodeID.c_str();
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultVolumeColorNodeID()
{
return vtkMRMLColorLogic::GetColorTableNodeID(vtkMRMLColorTableNode::Grey);
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultLabelMapColorNodeID()
{
return vtkMRMLColorLogic::GetProceduralColorNodeID("RandomIntegers");
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultEditorColorNodeID()
{
return vtkMRMLColorLogic::GetProceduralColorNodeID("RandomIntegers");
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultModelColorNodeID()
{
return vtkMRMLColorLogic::GetFreeSurferColorNodeID(vtkMRMLFreeSurferProceduralColorNode::Heat);
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultChartColorNodeID()
{
return vtkMRMLColorLogic::GetProceduralColorNodeID("RandomIntegers");
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetDefaultFreeSurferLabelMapColorNodeID()
{
return vtkMRMLColorLogic::GetFreeSurferColorNodeID(vtkMRMLFreeSurferProceduralColorNode::Labels);
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::AddColorFile(const char *fileName, std::vector<std::string> *Files)
{
if (fileName == NULL)
{
vtkErrorMacro("AddColorFile: can't add a null color file name");
return;
}
if (Files == NULL)
{
vtkErrorMacro("AddColorFile: no array to which to add color file to!");
return;
}
// check if it's in the vector already
std::string fileNameStr = std::string(fileName);
for (unsigned int i = 0; i < Files->size(); i++)
{
std::string fileToCheck;
try
{
fileToCheck = Files->at(i);
}
catch (...)
{
// an out_of_range exception can be thrown.
}
if (fileToCheck.compare(fileNameStr) == 0)
{
vtkDebugMacro("AddColorFile: already have this file at index " << i << ", not adding it again: " << fileNameStr.c_str());
return;
}
}
vtkDebugMacro("AddColorFile: adding file name to Files: " << fileNameStr.c_str());
Files->push_back(fileNameStr);
}
//----------------------------------------------------------------------------
vtkMRMLColorNode* vtkMRMLColorLogic::LoadColorFile(const char *fileName, const char *nodeName)
{
// try loading it as a color table node first
vtkMRMLColorTableNode* node = this->CreateFileNode(fileName);
vtkMRMLColorNode * addedNode = NULL;
if (node)
{
node->SetAttribute("Category", "File");
node->SaveWithSceneOn();
node->GetStorageNode()->SaveWithSceneOn();
node->HideFromEditorsOff();
node->SetSingletonTag(NULL);
if (nodeName != NULL)
{
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(nodeName));
node->SetName(uname.c_str());
}
addedNode =
vtkMRMLColorNode::SafeDownCast(this->GetMRMLScene()->AddNode(node));
vtkDebugMacro("LoadColorFile: Done: Read and added file node: " << fileName);
node->Delete();
}
else
{
// try loading it as a procedural node
vtkWarningMacro("Trying to read color file as a procedural color node");
vtkMRMLProceduralColorNode *procNode = this->CreateProceduralFileNode(fileName);
if (procNode)
{
procNode->SetAttribute("Category", "File");
procNode->SaveWithSceneOn();
procNode->GetStorageNode()->SaveWithSceneOn();
procNode->HideFromEditorsOff();
procNode->SetSingletonTag(NULL);
if (nodeName != NULL)
{
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(nodeName));
procNode->SetName(uname.c_str());
}
addedNode =
vtkMRMLColorNode::SafeDownCast(this->GetMRMLScene()->AddNode(procNode));
vtkDebugMacro("LoadColorFile: Done: Read and added file procNode: " << fileName);
procNode->Delete();
}
}
return addedNode;
}
//------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateLabelsNode()
{
vtkMRMLColorTableNode *labelsNode = vtkMRMLColorTableNode::New();
labelsNode->SetTypeToLabels();
labelsNode->SetAttribute("Category", "Discrete");
labelsNode->SaveWithSceneOff();
labelsNode->SetName(labelsNode->GetTypeAsString());
labelsNode->SetSingletonTag(labelsNode->GetTypeAsString());
return labelsNode;
}
//------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateDefaultTableNode(int type)
{
vtkMRMLColorTableNode *node = vtkMRMLColorTableNode::New();
node->SetType(type);
const char* typeName = node->GetTypeAsString();
if (strstr(typeName, "Tint") != NULL)
{
node->SetAttribute("Category", "Tint");
}
else if (strstr(typeName, "Shade") != NULL)
{
node->SetAttribute("Category", "Shade");
}
else
{
node->SetAttribute("Category", "Discrete");
}
if (strcmp(typeName, "(unknown)") == 0)
{
return node;
}
node->SaveWithSceneOff();
node->SetName(node->GetTypeAsString());
node->SetSingletonTag(node->GetTypeAsString());
return node;
}
//------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CreateRandomNode()
{
vtkDebugMacro("vtkMRMLColorLogic::CreateRandomNode: making a random mrml proc color node");
vtkMRMLProceduralColorNode *procNode = vtkMRMLProceduralColorNode::New();
procNode->SetName("RandomIntegers");
procNode->SetAttribute("Category", "Discrete");
procNode->SaveWithSceneOff();
procNode->SetSingletonTag(procNode->GetTypeAsString());
vtkColorTransferFunction *func = procNode->GetColorTransferFunction();
const int dimension = 1000;
double table[3*dimension];
double* tablePtr = table;
for (int i = 0; i < dimension; ++i)
{
*tablePtr++ = static_cast<double>(rand())/RAND_MAX;
*tablePtr++ = static_cast<double>(rand())/RAND_MAX;
*tablePtr++ = static_cast<double>(rand())/RAND_MAX;
}
func->BuildFunctionFromTable(VTK_INT_MIN, VTK_INT_MAX, dimension, table);
func->Build();
procNode->SetNamesFromColors();
return procNode;
}
//------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CreateRedGreenBlueNode()
{
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: making a red - green - blue mrml proc color node");
vtkMRMLProceduralColorNode *procNode = vtkMRMLProceduralColorNode::New();
procNode->SetName("RedGreenBlue");
procNode->SetAttribute("Category", "Continuous");
procNode->SaveWithSceneOff();
procNode->SetSingletonTag(procNode->GetTypeAsString());
procNode->SetDescription("A color transfer function that maps from -6 to 6, red through green to blue");
vtkColorTransferFunction *func = procNode->GetColorTransferFunction();
func->SetColorSpaceToRGB();
func->AddRGBPoint(-6.0, 1.0, 0.0, 0.0);
func->AddRGBPoint(0.0, 0.0, 1.0, 0.0);
func->AddRGBPoint(6.0, 0.0, 0.0, 1.0);
procNode->SetNamesFromColors();
return procNode;
}
//------------------------------------------------------------------------------
vtkMRMLFreeSurferProceduralColorNode* vtkMRMLColorLogic::CreateFreeSurferNode(int type)
{
vtkMRMLFreeSurferProceduralColorNode *node = vtkMRMLFreeSurferProceduralColorNode::New();
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: setting free surfer proc color node type to " << type);
node->SetType(type);
node->SetAttribute("Category", "FreeSurfer");
node->SaveWithSceneOff();
if (node->GetTypeAsString() == NULL)
{
vtkWarningMacro("Node type as string is null");
node->SetName("NoName");
}
else
{
node->SetName(node->GetTypeAsString());
}
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: set proc node name to " << node->GetName());
/*
if (this->GetFreeSurferColorNodeID(i) == NULL)
{
vtkDebugMacro("Error getting default node id for freesurfer node " << i);
}
*/
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: Getting default fs color node id for type " << type);
node->SetSingletonTag(node->GetTypeAsString());
return node;
}
//------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateFreeSurferFileNode(const char* fileName)
{
if (fileName == NULL)
{
vtkErrorMacro("Unable to get the labels file name, not adding");
return 0;
}
vtkMRMLColorTableNode* node = this->CreateFileNode(fileName);
if (!node)
{
return 0;
}
node->SetAttribute("Category", "FreeSurfer");
node->SetName("FreeSurferLabels");
node->SetSingletonTag(node->GetTypeAsString());
return node;
}
//--------------------------------------------------------------------------------
vtkMRMLPETProceduralColorNode* vtkMRMLColorLogic::CreatePETColorNode(int type)
{
vtkMRMLPETProceduralColorNode *nodepcn = vtkMRMLPETProceduralColorNode::New();
nodepcn->SetType(type);
nodepcn->SetAttribute("Category", "PET");
nodepcn->SaveWithSceneOff();
if (nodepcn->GetTypeAsString() == NULL)
{
vtkWarningMacro("Node type as string is null");
nodepcn->SetName("NoName");
}
else
{
vtkDebugMacro("Got node type as string " << nodepcn->GetTypeAsString());
nodepcn->SetName(nodepcn->GetTypeAsString());
}
nodepcn->SetSingletonTag(nodepcn->GetTypeAsString());
return nodepcn;
}
//---------------------------------------------------------------------------------
vtkMRMLdGEMRICProceduralColorNode* vtkMRMLColorLogic::CreatedGEMRICColorNode(int type)
{
vtkMRMLdGEMRICProceduralColorNode *pcnode = vtkMRMLdGEMRICProceduralColorNode::New();
pcnode->SetType(type);
pcnode->SetAttribute("Category", "Cartilage MRI");
pcnode->SaveWithSceneOff();
if (pcnode->GetTypeAsString() == NULL)
{
vtkWarningMacro("Node type as string is null");
pcnode->SetName("NoName");
}
else
{
vtkDebugMacro("Got node type as string " << pcnode->GetTypeAsString());
pcnode->SetName(pcnode->GetTypeAsString());
}
pcnode->SetSingletonTag(pcnode->GetTypeAsString());
return pcnode;
}
//---------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateDefaultFileNode(const std::string& colorFileName)
{
vtkMRMLColorTableNode* ctnode = this->CreateFileNode(colorFileName.c_str());
if (!ctnode)
{
return 0;
}
if (strcmp(ctnode->GetName(),"GenericColors") == 0 ||
strcmp(ctnode->GetName(),"GenericAnatomyColors") == 0)
{
vtkDebugMacro("Found default lut node");
// No category to float to the top of the node
// can't unset an attribute, so just don't set it at all
}
else
{
ctnode->SetAttribute("Category", "Default Labels from File");
}
return ctnode;
}
//---------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateUserFileNode(const std::string& colorFileName)
{
vtkMRMLColorTableNode * ctnode = this->CreateFileNode(colorFileName.c_str());
if (ctnode == 0)
{
return 0;
}
ctnode->SetAttribute("Category", "Auto Loaded User Color Files");
ctnode->SaveWithSceneOn();
ctnode->HideFromEditorsOff();
return ctnode;
}
//--------------------------------------------------------------------------------
std::vector<std::string> vtkMRMLColorLogic::FindDefaultColorFiles()
{
return std::vector<std::string>();
}
//--------------------------------------------------------------------------------
std::vector<std::string> vtkMRMLColorLogic::FindDefaultTerminologyColorFiles()
{
return std::vector<std::string>();
}
//--------------------------------------------------------------------------------
std::vector<std::string> vtkMRMLColorLogic::FindUserColorFiles()
{
return std::vector<std::string>();
}
//--------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateFileNode(const char* fileName)
{
vtkMRMLColorTableNode * ctnode = vtkMRMLColorTableNode::New();
ctnode->SetTypeToFile();
ctnode->SaveWithSceneOff();
ctnode->HideFromEditorsOn();
ctnode->SetScene(this->GetMRMLScene());
// make a storage node
vtkNew<vtkMRMLColorTableStorageNode> colorStorageNode;
colorStorageNode->SaveWithSceneOff();
if (this->GetMRMLScene())
{
this->GetMRMLScene()->AddNode(colorStorageNode.GetPointer());
ctnode->SetAndObserveStorageNodeID(colorStorageNode->GetID());
}
ctnode->GetStorageNode()->SetFileName(fileName);
std::string basename = vtksys::SystemTools::GetFilenameWithoutExtension(fileName);
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(basename.c_str()));
ctnode->SetName(uname.c_str());
vtkDebugMacro("CreateFileNode: About to read user file " << fileName);
if (ctnode->GetStorageNode()->ReadData(ctnode) == 0)
{
vtkErrorMacro("Unable to read file as color table " << (ctnode->GetFileName() ? ctnode->GetFileName() : ""));
if (this->GetMRMLScene())
{
ctnode->SetAndObserveStorageNodeID(NULL);
ctnode->SetScene(NULL);
this->GetMRMLScene()->RemoveNode(colorStorageNode.GetPointer());
}
ctnode->Delete();
return 0;
}
vtkDebugMacro("CreateFileNode: finished reading user file " << fileName);
ctnode->SetSingletonTag(
this->GetFileColorNodeSingletonTag(fileName).c_str());
return ctnode;
}
//--------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CreateProceduralFileNode(const char* fileName)
{
vtkMRMLProceduralColorNode * cpnode = vtkMRMLProceduralColorNode::New();
cpnode->SetTypeToFile();
cpnode->SaveWithSceneOff();
cpnode->HideFromEditorsOn();
cpnode->SetScene(this->GetMRMLScene());
// make a storage node
vtkMRMLProceduralColorStorageNode *colorStorageNode = vtkMRMLProceduralColorStorageNode::New();
colorStorageNode->SaveWithSceneOff();
if (this->GetMRMLScene())
{
this->GetMRMLScene()->AddNode(colorStorageNode);
cpnode->SetAndObserveStorageNodeID(colorStorageNode->GetID());
}
colorStorageNode->Delete();
cpnode->GetStorageNode()->SetFileName(fileName);
std::string basename = vtksys::SystemTools::GetFilenameWithoutExtension(fileName);
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(basename.c_str()));
cpnode->SetName(uname.c_str());
vtkDebugMacro("CreateProceduralFileNode: About to read user file " << fileName);
if (cpnode->GetStorageNode()->ReadData(cpnode) == 0)
{
vtkErrorMacro("Unable to read procedural colour file " << (cpnode->GetFileName() ? cpnode->GetFileName() : ""));
if (this->GetMRMLScene())
{
cpnode->SetAndObserveStorageNodeID(NULL);
cpnode->SetScene(NULL);
this->GetMRMLScene()->RemoveNode(colorStorageNode);
}
cpnode->Delete();
return 0;
}
vtkDebugMacro("CreateProceduralFileNode: finished reading user procedural color file " << fileName);
cpnode->SetSingletonTag(
this->GetFileColorNodeSingletonTag(fileName).c_str());
return cpnode;
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddLabelsNode()
{
vtkMRMLColorTableNode* labelsNode = this->CreateLabelsNode();
//if (this->GetMRMLScene()->GetNodeByID(labelsNode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(labelsNode, labelsNode->GetSingletonTag());
this->GetMRMLScene()->AddNode(labelsNode);
}
labelsNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultTableNode(int i)
{
vtkMRMLColorTableNode* node = this->CreateDefaultTableNode(i);
//if (node->GetSingletonTag())
{
//if (this->GetMRMLScene()->GetNodeByID(node->GetSingletonTag()) == NULL)
{
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: requesting id " << node->GetSingletonTag() << endl);
//this->GetMRMLScene()->RequestNodeID(node, node->GetSingletonTag());
this->GetMRMLScene()->AddNode(node);
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: added node " << node->GetID() << ", requested id was " << node->GetSingletonTag() << ", type = " << node->GetTypeAsString() << endl);
}
//else
// {
// vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: didn't add node " << node->GetID() << " as it was already in the scene.\n");
// }
}
node->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultProceduralNodes()
{
// random one
vtkMRMLProceduralColorNode* randomNode = this->CreateRandomNode();
this->GetMRMLScene()->AddNode(randomNode);
randomNode->Delete();
// red green blue one
vtkMRMLProceduralColorNode* rgbNode = this->CreateRedGreenBlueNode();
this->GetMRMLScene()->AddNode(rgbNode);
rgbNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddFreeSurferNode(int type)
{
vtkMRMLFreeSurferProceduralColorNode* node = this->CreateFreeSurferNode(type);
//if (this->GetMRMLScene()->GetNodeByID(node->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(node, node->GetSingletonTag());
this->GetMRMLScene()->AddNode(node);
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: added node " << node->GetID() << ", requested id was " << node->GetSingletonTag()<< ", type = " << node->GetTypeAsString() << endl);
}
//else
// {
// vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: didn't add node " << node->GetID() << " as it was already in the scene.\n");
// }
node->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddFreeSurferFileNode(vtkMRMLFreeSurferProceduralColorNode* basicFSNode)
{
vtkMRMLColorTableNode* node = this->CreateFreeSurferFileNode(basicFSNode->GetLabelsFileName());
if (node)
{
//if (this->GetMRMLScene()->GetNodeByID(node->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(node, node->GetSingletonTag());
this->GetMRMLScene()->AddNode(node);
}
//else
// {
// vtkDebugMacro("Unable to add a new colour node " << node->GetSingletonTag()
// << " with freesurfer colours, from file: "
// << node->GetStorageNode()->GetFileName()
// << " as there is already a node with this id in the scene");
// }
node->Delete();
}
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddPETNode(int type)
{
vtkDebugMacro("AddDefaultColorNodes: adding PET nodes");
vtkMRMLPETProceduralColorNode *nodepcn = this->CreatePETColorNode(type);
//if (this->GetMRMLScene()->GetNodeByID( nodepcn->GetSingletonTag() ) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(nodepcn, nodepcn->GetSingletonTag() );
this->GetMRMLScene()->AddNode(nodepcn);
}
nodepcn->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDGEMRICNode(int type)
{
vtkDebugMacro("AddDefaultColorNodes: adding dGEMRIC nodes");
vtkMRMLdGEMRICProceduralColorNode *pcnode = this->CreatedGEMRICColorNode(type);
//if (this->GetMRMLScene()->GetNodeByID(pcnode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(pcnode, pcnode->GetSingletonTag());
this->GetMRMLScene()->AddNode(pcnode);
}
pcnode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultFileNode(int i)
{
vtkMRMLColorTableNode* ctnode = this->CreateDefaultFileNode(this->ColorFiles[i]);
if (ctnode)
{
//if (this->GetMRMLScene()->GetNodeByID(ctnode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(ctnode, ctnode->GetSingletonTag());
this->GetMRMLScene()->AddNode(ctnode);
ctnode->Delete();
vtkDebugMacro("AddDefaultColorFiles: Read and added file node: " << this->ColorFiles[i].c_str());
}
//else
// {
// vtkDebugMacro("AddDefaultColorFiles: node " << ctnode->GetSingletonTag() << " already in scene");
// }
}
else
{
vtkWarningMacro("Unable to read color file " << this->ColorFiles[i].c_str());
}
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddUserFileNode(int i)
{
vtkMRMLColorTableNode* ctnode = this->CreateUserFileNode(this->UserColorFiles[i]);
if (ctnode)
{
//if (this->GetMRMLScene()->GetNodeByID(ctnode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(ctnode, ctnode->GetSingletonTag());
this->GetMRMLScene()->AddNode(ctnode);
vtkDebugMacro("AddDefaultColorFiles: Read and added user file node: " << this->UserColorFiles[i].c_str());
}
//else
// {
// vtkDebugMacro("AddDefaultColorFiles: node " << ctnode->GetSingletonTag() << " already in scene");
// }
}
else
{
vtkWarningMacro("Unable to read user color file " << this->UserColorFiles[i].c_str());
}
ctnode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultTableNodes()
{
vtkMRMLColorTableNode* basicNode = vtkMRMLColorTableNode::New();
for (int i = basicNode->GetFirstType(); i <= basicNode->GetLastType(); i++)
{
// don't add a second Lables node, File node or the old atlas node
if (i != vtkMRMLColorTableNode::Labels &&
i != vtkMRMLColorTableNode::File &&
i != vtkMRMLColorTableNode::Obsolete &&
i != vtkMRMLColorTableNode::User)
{
this->AddDefaultTableNode(i);
}
}
basicNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddFreeSurferNodes()
{
vtkDebugMacro("AddDefaultColorNodes: Adding Freesurfer nodes");
vtkMRMLFreeSurferProceduralColorNode* basicFSNode = vtkMRMLFreeSurferProceduralColorNode::New();
vtkDebugMacro("AddDefaultColorNodes: first type = " << basicFSNode->GetFirstType() << ", last type = " << basicFSNode->GetLastType());
for (int type = basicFSNode->GetFirstType(); type <= basicFSNode->GetLastType(); ++type)
{
this->AddFreeSurferNode(type);
}
// add a regular colour tables holding the freesurfer volume file colours and
// surface colours
this->AddFreeSurferFileNode(basicFSNode);
basicFSNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddPETNodes()
{
vtkMRMLPETProceduralColorNode* basicPETNode = vtkMRMLPETProceduralColorNode::New();
for (int type = basicPETNode->GetFirstType(); type <= basicPETNode->GetLastType(); ++type)
{
this->AddPETNode(type);
}
basicPETNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDGEMRICNodes()
{
vtkMRMLdGEMRICProceduralColorNode* basicdGEMRICNode = vtkMRMLdGEMRICProceduralColorNode::New();
for (int type = basicdGEMRICNode->GetFirstType(); type <= basicdGEMRICNode->GetLastType(); ++type)
{
this->AddDGEMRICNode(type);
}
basicdGEMRICNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultFileNodes()
{
this->ColorFiles = this->FindDefaultColorFiles();
vtkDebugMacro("AddDefaultColorNodes: found " << this->ColorFiles.size() << " default color files");
for (unsigned int i = 0; i < this->ColorFiles.size(); i++)
{
this->AddDefaultFileNode(i);
}
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddUserFileNodes()
{
this->UserColorFiles = this->FindUserColorFiles();
vtkDebugMacro("AddDefaultColorNodes: found " << this->UserColorFiles.size() << " user color files");
for (unsigned int i = 0; i < this->UserColorFiles.size(); i++)
{
this->AddUserFileNode(i);
}
}
//----------------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CopyNode(vtkMRMLColorNode* nodeToCopy, const char* copyName)
{
vtkMRMLColorTableNode *colorNode = vtkMRMLColorTableNode::New();
colorNode->SetName(copyName);
colorNode->SetTypeToUser();
colorNode->SetAttribute("Category", "User Generated");
colorNode->SetHideFromEditors(false);
colorNode->SetNamesInitialised(nodeToCopy->GetNamesInitialised());
if (nodeToCopy->GetLookupTable())
{
double* range = nodeToCopy->GetLookupTable()->GetRange();
colorNode->GetLookupTable()->SetRange(range[0], range[1]);
}
colorNode->SetNumberOfColors(nodeToCopy->GetNumberOfColors());
for (int i = 0; i < nodeToCopy->GetNumberOfColors(); ++i)
{
double color[4];
nodeToCopy->GetColor(i, color);
colorNode->SetColor(i, nodeToCopy->GetColorName(i), color[0], color[1], color[2], color[3]);
}
return colorNode;
}
//----------------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CopyProceduralNode(vtkMRMLColorNode* nodeToCopy, const char* copyName)
{
vtkMRMLProceduralColorNode *colorNode = vtkMRMLProceduralColorNode::New();
if (nodeToCopy->IsA("vtkMRMLProceduralColorNode"))
{
colorNode->Copy(nodeToCopy);
// the copy will copy any singleton tag, make sure it's unset
colorNode->SetSingletonTag(NULL);
}
colorNode->SetName(copyName);
colorNode->SetTypeToUser();
colorNode->SetAttribute("Category", "User Generated");
colorNode->SetHideFromEditors(false);
return colorNode;
}
//------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultTerminologyColors()
{
this->TerminologyColorFiles = this->FindDefaultTerminologyColorFiles();
vtkDebugMacro("AddDefaultTerminologyColorNodes: found " << this->TerminologyColorFiles.size() << " default terminology color files");
for (unsigned int i = 0; i < this->TerminologyColorFiles.size(); i++)
{
this->InitializeTerminologyMappingFromFile(this->TerminologyColorFiles[i]);
}
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::CreateNewTerminology(std::string lutName)
{
if (lutName.length() == 0)
{
return false;
}
if (this->TerminologyExists(lutName))
{
vtkWarningMacro("Create new terminology: one already exists with name " << lutName);
return false;
}
this->ColorCategorizationMaps[lutName] = ColorCategorizationMapType();
return this->AssociateTerminologyWithColorNode(lutName);
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::TerminologyExists(std::string lutName)
{
if (lutName.length() == 0)
{
return false;
}
if (this->ColorCategorizationMaps.find(lutName) !=
this->ColorCategorizationMaps.end())
{
return true;
}
else
{
return false;
}
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic
::AddTermToTerminology(std::string lutName, int labelValue,
std::string categoryValue,
std::string categorySchemeDesignator,
std::string categoryMeaning,
std::string typeValue,
std::string typeSchemeDesignator,
std::string typeMeaning,
std::string modifierValue,
std::string modifierSchemeDesignator,
std::string modifierMeaning,
std::string regionValue,
std::string regionSchemeDesignator,
std::string regionMeaning,
std::string regionModifierValue,
std::string regionModifierSchemeDesignator,
std::string regionModifierMeaning)
{
StandardTerm category(categoryValue, categorySchemeDesignator, categoryMeaning);
StandardTerm type(typeValue, typeSchemeDesignator, typeMeaning);
StandardTerm modifier(modifierValue, modifierSchemeDesignator, modifierMeaning);
StandardTerm region(regionValue, regionSchemeDesignator, regionMeaning);
StandardTerm regionModifier(regionModifierValue, regionModifierSchemeDesignator, regionModifierMeaning);
return this->AddTermToTerminologyMapping(lutName, labelValue, category, type, modifier, region, regionModifier);
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::AddTermToTerminologyMapping(std::string lutName, int labelValue,
StandardTerm category, StandardTerm type, StandardTerm modifier,
StandardTerm region, StandardTerm regionModifier)
{
if (lutName.length() == 0)
{
return false;
}
// check if the terminology mapping exists already, if not, create it
if (!this->TerminologyExists(lutName))
{
vtkDebugMacro("Adding a new terminology for " << lutName);
bool createFlag = this->CreateNewTerminology(lutName);
if (!createFlag)
{
vtkWarningMacro("Unable to create new terminology for " << lutName.c_str() << " or associate it with a color node.");
return false;
}
}
ColorLabelCategorization termMapping;
termMapping.LabelValue = labelValue;
termMapping.SegmentedPropertyCategory = category;
termMapping.SegmentedPropertyType = type;
termMapping.SegmentedPropertyTypeModifier = modifier;
termMapping.AnatomicRegion = region;
termMapping.AnatomicRegionModifier = regionModifier;
this->ColorCategorizationMaps[lutName][termMapping.LabelValue] = termMapping;
return true;
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::AssociateTerminologyWithColorNode(std::string lutName)
{
if (lutName.length() == 0)
{
return false;
}
vtkMRMLNode *colorNode = this->GetMRMLScene()->GetFirstNodeByName(lutName.c_str());
if (!colorNode)
{
vtkWarningMacro("Unable to associate terminology with named color node: " << lutName);
return false;
}
colorNode->SetAttribute("TerminologyName", lutName.c_str());
return true;
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::InitializeTerminologyMappingFromFile(std::string mapFileName)
{
std::cout << "Initializing terminology mapping for map file " << mapFileName << std::endl;
std::ifstream mapFile(mapFileName.c_str());
bool status = mapFile.is_open();
std::string lutName = "";
bool addFlag = true;
bool assocFlag = true;
bool parseFlag = true;
if (status)
{
while (!mapFile.eof())
{
std::string lineIn;
std::getline(mapFile, lineIn);
if (lineIn[0] == '#')
{
continue;
}
if (lineIn.find("SlicerLUT=") == std::string::npos)
{
continue;
}
size_t delim = lineIn.find("=");
lutName = lineIn.substr(delim+1,lineIn.length()-delim);
assocFlag = this->CreateNewTerminology(lutName);
break;
}
while (!mapFile.eof())
{
std::string lineIn, lineLeft;
std::getline(mapFile, lineIn);
if (lineIn.length()<30 || lineIn[0] == '#')
{
continue;
}
std::vector<std::string> tokens;
std::stringstream ss(lineIn);
std::string item;
while (std::getline(ss,item,','))
{
tokens.push_back(item);
}
if (tokens.size() < 5)
{
vtkWarningMacro("InitializeTerminologyMappingFromFile: line has incorrect number of tokens: "
<< tokens.size()
<< " < 5");
parseFlag = false;
}
else
{
int labelValue = atoi(tokens[0].c_str());
StandardTerm category, type, modifier;
if (this->ParseTerm(tokens[2],category) &&
this->ParseTerm(tokens[3],type))
{
// modifier is optional, ParseTerm will return false on an empty string
this->ParseTerm(tokens[4],modifier);
// for now region doesn't appear in the file
StandardTerm region, regionModifier;
addFlag = addFlag && this->AddTermToTerminologyMapping(lutName, labelValue, category, type, modifier, region, regionModifier);
}
else
{
vtkWarningMacro("InitializeTerminologyMappingFromFile: failed to parse category or type: "
<< tokens[2].c_str() << "\n"
<< tokens[3].c_str() << "\n"
<< tokens[4].c_str());
parseFlag = false;
}
}
}
}
std::cout << this->ColorCategorizationMaps[lutName].size()
<< " terms were read for Slicer LUT " << lutName << std::endl;
return status && addFlag && assocFlag && parseFlag;
}
//-------------------------------------------------------------------------------
bool vtkMRMLColorLogic::
LookupCategorizationFromLabel(int label, ColorLabelCategorization& labelCat, const char *lutName)
{
bool success = false;
if (this->TerminologyExists(lutName))
{
// set the label value so that if it's not found, it's still a valid categorisation
labelCat.LabelValue = label;
if (this->ColorCategorizationMaps[lutName].find(label) !=
this->ColorCategorizationMaps[lutName].end())
{
labelCat = this->ColorCategorizationMaps[lutName][label];
success = true;
}
}
return success;
}
//---------------------------------------------------------------------------
std::string vtkMRMLColorLogic::
GetTerminologyFromLabel(const std::string& categorization,
const std::string& standardTerm,
int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
StandardTerm term;
if (categorization.compare("SegmentedPropertyCategory") == 0)
{
term = labelCat.SegmentedPropertyCategory;
}
else if (categorization.compare("SegmentedPropertyType") == 0)
{
term = labelCat.SegmentedPropertyType;
}
else if (categorization.compare("SegmentedPropertyTypeModifier") == 0)
{
term = labelCat.SegmentedPropertyTypeModifier;
}
else if (categorization.compare("AnatomicRegion") == 0)
{
term = labelCat.AnatomicRegion;
}
else if (categorization.compare("AnatomicRegionModifier") == 0)
{
term = labelCat.AnatomicRegionModifier;
}
// now get the requested coding from the standard term
if (standardTerm.compare("CodeValue") == 0)
{
returnString = term.CodeValue;
}
else if (standardTerm.compare("CodeMeaning") == 0)
{
returnString = term.CodeMeaning;
}
else if (standardTerm.compare("CodingSchemeDesignator") == 0)
{
returnString = term.CodingSchemeDesignator;
}
}
return returnString;
}
//---------------------------------------------------------------------------
bool vtkMRMLColorLogic::PrintCategorizationFromLabel(int label, const char *lutName)
{
ColorLabelCategorization labelCat;
if (!this->TerminologyExists(lutName))
{
return false;
}
if (this->ColorCategorizationMaps[lutName].find(label) !=
this->ColorCategorizationMaps[lutName].end())
{
labelCat = this->ColorCategorizationMaps[lutName][label];
labelCat.Print(std::cout);
return true;
}
return false;
}
//---------------------------------------------------------------------------
std::string vtkMRMLColorLogic::RemoveLeadAndTrailSpaces(std::string in)
{
std::string ret = in;
ret.erase(ret.begin(), std::find_if(ret.begin(),ret.end(),
std::not1(std::ptr_fun<int,int>(isspace))));
ret.erase(std::find_if(ret.rbegin(),ret.rend(),
std::not1(std::ptr_fun<int,int>(isspace))).base(), ret.end());
return ret;
}
//---------------------------------------------------------------------------
bool vtkMRMLColorLogic::ParseTerm(const std::string inputStr, StandardTerm& term)
{
std::string str = inputStr;
str = this->RemoveLeadAndTrailSpaces(str);
if (str.length() < 10)
{
// can get empty strings for optional modifiers
return false;
}
// format check, should be enclosed in parentheses, have two ;'s
if (str.at(0) != '(' ||
str.at(str.length()-1) != ')')
{
vtkWarningMacro(<< __LINE__
<< ": ParseTerm: input string doesn't start/end with parentheses "
<< str);
return false;
}
size_t n = std::count(str.begin(), str.end(), ';');
if (n != 2)
{
vtkWarningMacro(<< __LINE__
<< ": ParseTerm: input string doesn't have 2 semi colons "
<< str);
return false;
}
// get rid of parentheses
str = str.substr(1,str.length()-2);
size_t found = str.find(";");
term.CodeValue = str.substr(0,found);
str = str.substr(found+1,str.length());
found = str.find(";");
term.CodingSchemeDesignator = str.substr(0,found);
str = str.substr(found+1, str.length());
term.CodeMeaning = str;
return true;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategoryCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyCategory.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategoryCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyCategory.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategoryCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyCategory.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategory(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.SegmentedPropertyCategory.CodeValue
+ sep
+ labelCat.SegmentedPropertyCategory.CodingSchemeDesignator
+ sep
+ labelCat.SegmentedPropertyCategory.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyType.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyType.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyType.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyType(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.SegmentedPropertyType.CodeValue
+ sep
+ labelCat.SegmentedPropertyType.CodingSchemeDesignator
+ sep
+ labelCat.SegmentedPropertyType.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifierCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyTypeModifier.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifierCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyTypeModifier.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifierCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyTypeModifier.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifier(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.SegmentedPropertyTypeModifier.CodeValue
+ sep
+ labelCat.SegmentedPropertyTypeModifier.CodingSchemeDesignator
+ sep
+ labelCat.SegmentedPropertyTypeModifier.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegion.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegion.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegion.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegion(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.AnatomicRegion.CodeValue
+ sep
+ labelCat.AnatomicRegion.CodingSchemeDesignator
+ sep
+ labelCat.AnatomicRegion.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifierCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegionModifier.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifierCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegionModifier.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifierCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegionModifier.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifier(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.AnatomicRegionModifier.CodeValue
+ sep
+ labelCat.AnatomicRegionModifier.CodingSchemeDesignator
+ sep
+ labelCat.AnatomicRegionModifier.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
| 34.084377 | 195 | 0.60644 | TheInterventionCentre |
b4d5364d6f4d6a845e1119163c1bf5caec1b51c9 | 4,933 | hpp | C++ | iOS/G3MiOSSDK/Commons/Basic/CameraGoToPositionEffect.hpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | 1 | 2016-08-23T10:29:44.000Z | 2016-08-23T10:29:44.000Z | iOS/G3MiOSSDK/Commons/Basic/CameraGoToPositionEffect.hpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/Basic/CameraGoToPositionEffect.hpp | restjohn/g3m | 608657fd6f0e2898bd963d15136ff085b499e97e | [
"BSD-2-Clause"
] | null | null | null | //
// CameraGoToPositionEffect.hpp
// G3MiOSSDK
//
// Created by José Miguel S N on 24/10/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef G3MiOSSDK_CameraGoToPositionEffect
#define G3MiOSSDK_CameraGoToPositionEffect
#include "Geodetic3D.hpp"
class CameraGoToPositionEffect : public EffectWithDuration {
private:
const Geodetic3D _fromPosition;
const Geodetic3D _toPosition;
const Angle _fromHeading;
const Angle _toHeading;
const Angle _fromPitch;
const Angle _toPitch;
const bool _linearHeight;
double _middleHeight;
double calculateMaxHeight(const Planet* planet) {
// curve parameters
const double distanceInDegreesMaxHeight = 180;
const double maxHeight = planet->getRadii().axisAverage() * 5;
// rough estimation of distance using lat/lon degrees
const double deltaLatInDeg = _fromPosition._latitude._degrees - _toPosition._latitude._degrees;
const double deltaLonInDeg = _fromPosition._longitude._degrees - _toPosition._longitude._degrees;
const double distanceInDeg = IMathUtils::instance()->sqrt((deltaLatInDeg * deltaLatInDeg) +
(deltaLonInDeg * deltaLonInDeg));
if (distanceInDeg >= distanceInDegreesMaxHeight) {
return maxHeight;
}
const double middleHeight = (distanceInDeg / distanceInDegreesMaxHeight) * maxHeight;
const double averageHeight = (_fromPosition._height + _toPosition._height) / 2;
if (middleHeight < averageHeight) {
const double delta = (averageHeight - middleHeight) / 2.0;
return averageHeight + delta;
}
// const double averageHeight = (_fromPosition._height + _toPosition._height) / 2;
// if (middleHeight < averageHeight) {
// return (averageHeight + middleHeight) / 2.0;
// }
return middleHeight;
}
public:
CameraGoToPositionEffect(const TimeInterval& duration,
const Geodetic3D& fromPosition,
const Geodetic3D& toPosition,
const Angle& fromHeading,
const Angle& toHeading,
const Angle& fromPitch,
const Angle& toPitch,
const bool linearTiming,
const bool linearHeight):
EffectWithDuration(duration, linearTiming),
_fromPosition(fromPosition),
_toPosition(toPosition),
_fromHeading(fromHeading),
_toHeading(toHeading),
_fromPitch(fromPitch),
_toPitch(toPitch),
_linearHeight(linearHeight)
{
}
void doStep(const G3MRenderContext* rc,
const TimeInterval& when) {
const double alpha = getAlpha(when);
double height;
if (_linearHeight) {
height = IMathUtils::instance()->linearInterpolation(_fromPosition._height,
_toPosition._height,
alpha);
}
else {
height = IMathUtils::instance()->quadraticBezierInterpolation(_fromPosition._height,
_middleHeight,
_toPosition._height,
alpha);
}
Camera *camera = rc->getNextCamera();
camera->setGeodeticPosition(Angle::linearInterpolation(_fromPosition._latitude, _toPosition._latitude, alpha),
Angle::linearInterpolation(_fromPosition._longitude, _toPosition._longitude, alpha),
height);
const Angle heading = Angle::linearInterpolation(_fromHeading, _toHeading, alpha);
camera->setHeading(heading);
const Angle middlePitch = Angle::fromDegrees(-90);
// const Angle pitch = (alpha < 0.5)
// ? Angle::linearInterpolation(_fromPitch, middlePitch, alpha*2)
// : Angle::linearInterpolation(middlePitch, _toPitch, (alpha-0.5)*2);
if (alpha <= 0.1) {
camera->setPitch( Angle::linearInterpolation(_fromPitch, middlePitch, alpha*10) );
}
else if (alpha >= 0.9) {
camera->setPitch( Angle::linearInterpolation(middlePitch, _toPitch, (alpha-0.9)*10) );
}
else {
camera->setPitch(middlePitch);
}
}
void stop(const G3MRenderContext* rc,
const TimeInterval& when) {
Camera* camera = rc->getNextCamera();
camera->setGeodeticPosition(_toPosition);
camera->setPitch(_toPitch);
camera->setHeading(_toHeading);
}
void cancel(const TimeInterval& when) {
// do nothing, just leave the effect in the intermediate state
}
void start(const G3MRenderContext* rc,
const TimeInterval& when) {
EffectWithDuration::start(rc, when);
_middleHeight = calculateMaxHeight(rc->getPlanet());
}
};
#endif
| 33.331081 | 116 | 0.618285 | restjohn |
b4d580f9e0c0ddd4943739636a66ffdb9888716c | 4,402 | cc | C++ | cc/test/test_in_process_context_provider.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | cc/test/test_in_process_context_provider.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/test/test_in_process_context_provider.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright 2013 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 "cc/test/test_in_process_context_provider.h"
#include "base/lazy_instance.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gl_in_process_context.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/common/gles2_cmd_utils.h"
#include "gpu/skia_bindings/gl_bindings_skia_cmd_buffer.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/khronos/GLES2/gl2ext.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
#include "ui/gfx/native_widget_types.h"
namespace cc {
// static
scoped_ptr<gpu::GLInProcessContext> CreateTestInProcessContext() {
const bool is_offscreen = true;
const bool share_resources = true;
gpu::gles2::ContextCreationAttribHelper attribs;
attribs.alpha_size = 8;
attribs.blue_size = 8;
attribs.green_size = 8;
attribs.red_size = 8;
attribs.depth_size = 24;
attribs.stencil_size = 8;
attribs.samples = 0;
attribs.sample_buffers = 0;
attribs.fail_if_major_perf_caveat = false;
attribs.bind_generates_resource = false;
gfx::GpuPreference gpu_preference = gfx::PreferDiscreteGpu;
scoped_ptr<gpu::GLInProcessContext> context =
make_scoped_ptr(gpu::GLInProcessContext::Create(
NULL,
NULL,
is_offscreen,
gfx::kNullAcceleratedWidget,
gfx::Size(1, 1),
NULL,
share_resources,
attribs,
gpu_preference,
gpu::GLInProcessContextSharedMemoryLimits()));
DCHECK(context);
return context.Pass();
}
TestInProcessContextProvider::TestInProcessContextProvider()
: context_(CreateTestInProcessContext()) {}
TestInProcessContextProvider::~TestInProcessContextProvider() {
}
bool TestInProcessContextProvider::BindToCurrentThread() { return true; }
gpu::gles2::GLES2Interface* TestInProcessContextProvider::ContextGL() {
return context_->GetImplementation();
}
gpu::ContextSupport* TestInProcessContextProvider::ContextSupport() {
return context_->GetImplementation();
}
namespace {
// Singleton used to initialize and terminate the gles2 library.
class GLES2Initializer {
public:
GLES2Initializer() { ::gles2::Initialize(); }
~GLES2Initializer() { ::gles2::Terminate(); }
private:
DISALLOW_COPY_AND_ASSIGN(GLES2Initializer);
};
static base::LazyInstance<GLES2Initializer> g_gles2_initializer =
LAZY_INSTANCE_INITIALIZER;
} // namespace
static void BindGrContextCallback(const GrGLInterface* interface) {
TestInProcessContextProvider* context_provider =
reinterpret_cast<TestInProcessContextProvider*>(interface->fCallbackData);
gles2::SetGLContext(context_provider->ContextGL());
}
class GrContext* TestInProcessContextProvider::GrContext() {
if (gr_context_)
return gr_context_.get();
// The GrGLInterface factory will make GL calls using the C GLES2 interface.
// Make sure the gles2 library is initialized first on exactly one thread.
g_gles2_initializer.Get();
gles2::SetGLContext(ContextGL());
skia::RefPtr<GrGLInterface> interface =
skia::AdoptRef(skia_bindings::CreateCommandBufferSkiaGLBinding());
interface->fCallback = BindGrContextCallback;
interface->fCallbackData = reinterpret_cast<GrGLInterfaceCallbackData>(this);
gr_context_ = skia::AdoptRef(GrContext::Create(
kOpenGL_GrBackend, reinterpret_cast<GrBackendContext>(interface.get())));
return gr_context_.get();
}
ContextProvider::Capabilities
TestInProcessContextProvider::ContextCapabilities() {
return ContextProvider::Capabilities();
}
bool TestInProcessContextProvider::IsContextLost() { return false; }
void TestInProcessContextProvider::VerifyContexts() {}
void TestInProcessContextProvider::DeleteCachedResources() {
if (gr_context_)
gr_context_->freeGpuResources();
}
bool TestInProcessContextProvider::DestroyedOnMainThread() { return false; }
void TestInProcessContextProvider::SetLostContextCallback(
const LostContextCallback& lost_context_callback) {}
void TestInProcessContextProvider::SetMemoryPolicyChangedCallback(
const MemoryPolicyChangedCallback& memory_policy_changed_callback) {}
} // namespace cc
| 31.442857 | 80 | 0.76965 | Fusion-Rom |
b4d5dc235eabd6ec0fbe5f492ca7e75afea7c2e3 | 2,811 | cpp | C++ | src/machine_address_transfer.cpp | CyberZHG/MIXAL | 06ebe91bb5abcc1ed4ff4af71809a1a41272c4f3 | [
"MIT"
] | 5 | 2020-07-15T16:16:06.000Z | 2021-07-14T04:26:36.000Z | src/machine_address_transfer.cpp | CyberZHG/MIXAL | 06ebe91bb5abcc1ed4ff4af71809a1a41272c4f3 | [
"MIT"
] | 1 | 2020-08-15T16:13:40.000Z | 2020-08-15T16:13:40.000Z | src/machine_address_transfer.cpp | CyberZHG/MIXAL | 06ebe91bb5abcc1ed4ff4af71809a1a41272c4f3 | [
"MIT"
] | 2 | 2020-08-16T00:41:48.000Z | 2021-05-23T18:43:33.000Z | #include <iostream>
#include "machine.h"
/**
* @file
* @brief Address transfer operations.
*/
namespace mixal {
/** Increase rA or rX by the address value.
*
* @see overflow
*/
void Computer::executeINC(const InstructionWord& instruction, Register5* reg) {
int32_t value = reg->value();
int32_t address = getIndexedAddress(instruction);
value += address;
reg->set(checkRange(value));
}
/** Decrease rA or rX by the address value.
*
* @see overflow
*/
void Computer::executeDEC(const InstructionWord& instruction, Register5* reg) {
int32_t value = reg->value();
int32_t address = getIndexedAddress(instruction);
value -= address;
reg->set(checkRange(value));
}
/** Enter the immediate address value to rA or rX. */
void Computer::executeENT(const InstructionWord& instruction, Register5* reg) {
int32_t address = getIndexedAddress(instruction);
reg->set(address);
if (address == 0) {
reg->negative = instruction.negative;
}
}
/** Enter the negative immediate address value to rA or rX. */
void Computer::executeENN(const InstructionWord& instruction, Register5* reg) {
int32_t address = getIndexedAddress(instruction);
reg->set(-address);
if (address == 0) {
reg->negative = !instruction.negative;
}
}
/** Increase rI by the address value. */
void Computer::executeINCi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t value = rIi.value();
int16_t address = getIndexedAddress(instruction);
value += address;
rIi.set(checkRange(value, 2));
}
/** Decrease rI by the address value. */
void Computer::executeDECi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t value = rIi.value();
int16_t address = getIndexedAddress(instruction);
value -= address;
rIi.set(checkRange(value, 2));
}
/** Enter address value to rI. */
void Computer::executeENTi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t address = getIndexedAddress(instruction);
rIi.set(checkRange(address, 2));
if (address == 0) {
rIi.negative = instruction.negative;
}
}
/** Enter negative address value to rI. */
void Computer::executeENNi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t address = getIndexedAddress(instruction);
rIi.set(checkRange(-address, 2));
if (address == 0) {
rIi.negative = !instruction.negative;
}
}
}; // namespace mixal
| 29.904255 | 79 | 0.683742 | CyberZHG |
b4d729af309196232b690f0ee270d9d0e80326e3 | 3,723 | cpp | C++ | Core/Widgets/SiteIcon.cpp | Acidburn0zzz/navigateur-seilo-js | 097ef5f9996333eef903f8c7fbc419cfc28ae03d | [
"MIT"
] | 1 | 2018-06-19T06:17:48.000Z | 2018-06-19T06:17:48.000Z | Core/Widgets/SiteIcon.cpp | Acidburn0zzz/navigateur-seilo-js | 097ef5f9996333eef903f8c7fbc419cfc28ae03d | [
"MIT"
] | null | null | null | Core/Widgets/SiteIcon.cpp | Acidburn0zzz/navigateur-seilo-js | 097ef5f9996333eef903f8c7fbc419cfc28ae03d | [
"MIT"
] | null | null | null | /***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) **
** **
** 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 "SiteIcon.hpp"
#include "Web/WebView.hpp"
#include "Widgets/AddressBar/AddressBar.hpp"
#include "Widgets/SiteInfo.hpp"
#include "Widgets/SiteInfoWidget.hpp"
#include "BrowserWindow.hpp"
#include "Application.hpp"
namespace Sn {
SiteIcon::SiteIcon(BrowserWindow* window, Sn::AddressBar* parent) :
ToolButton(parent),
m_window(window),
m_addressBar(parent)
{
setObjectName(QLatin1String("addressbar-siteicon"));
setToolButtonStyle(Qt::ToolButtonIconOnly);
setCursor(Qt::ArrowCursor);
setToolTip(AddressBar::tr("Show information about this page"));
setFocusPolicy(Qt::ClickFocus);
}
SiteIcon::~SiteIcon()
{
// Empty
}
void SiteIcon::setWebView(Sn::WebView* view)
{
m_view = view;
}
void SiteIcon::updateIcon(bool secure)
{
if (secure)
ToolButton::setIcon(Application::getAppIcon("locked"));
else
ToolButton::setIcon(Application::getAppIcon("nonlocked"));
}
void SiteIcon::popupClosed()
{
setDown(false);
}
void SiteIcon::contextMenuEvent(QContextMenuEvent* event)
{
// It's just to prevent the propagation to the address bar
event->accept();
}
void SiteIcon::mouseReleaseEvent(QMouseEvent* event)
{
bool activated = false;
if (event->button() == Qt::LeftButton && rect().contains(event->pos()))
activated = showPopup();
if (activated)
setUpdatesEnabled(false);
ToolButton::mouseReleaseEvent(event);
if (activated) {
setDown(true);
setUpdatesEnabled(true);
}
}
bool SiteIcon::showPopup()
{
if (!m_view || !m_window)
return false;
QUrl url{m_view->url()};
if (!SiteInfo::canShowSiteInfo(url))
return false;
setDown(true);
SiteInfoWidget* info{new SiteInfoWidget(m_window)};
info->showAt(parentWidget());
connect(info, &SiteInfoWidget::destroyed, this, &SiteIcon::popupClosed);
return true;
}
} | 32.094828 | 84 | 0.583132 | Acidburn0zzz |
b4d83621cae5c1d2d77fddcdbb56b3331e22b7a9 | 252 | cpp | C++ | src/kriti/TimeValue.cpp | etherealvisage/kriti | 6397c4d20331d9f5ce07460df08bbac9653ffa8b | [
"BSD-3-Clause"
] | 2 | 2015-10-05T19:33:19.000Z | 2015-12-08T08:39:17.000Z | src/kriti/TimeValue.cpp | etherealvisage/kriti | 6397c4d20331d9f5ce07460df08bbac9653ffa8b | [
"BSD-3-Clause"
] | 1 | 2017-04-30T16:26:08.000Z | 2017-05-01T03:00:42.000Z | src/kriti/TimeValue.cpp | etherealvisage/kriti | 6397c4d20331d9f5ce07460df08bbac9653ffa8b | [
"BSD-3-Clause"
] | null | null | null | #include <time.h>
#include "TimeValue.h"
namespace Kriti {
TimeValue TimeValue::current() {
struct timespec current;
clock_gettime(CLOCK_MONOTONIC, ¤t);
return current.tv_nsec + current.tv_sec*1000000000;
}
} // namespace Kriti
| 16.8 | 55 | 0.718254 | etherealvisage |
b4d8f1b7d1c9ce6f4f1739de3b99b23960b45c80 | 4,471 | hpp | C++ | src/oatpp/codegen/api_controller/base_undef.hpp | Purlemon/oatpp | 128816a027ca82f8de8da5bad445641e71fb437f | [
"Apache-2.0"
] | 5,252 | 2018-04-04T13:52:44.000Z | 2022-03-31T13:42:28.000Z | src/oatpp/codegen/api_controller/base_undef.hpp | Purlemon/oatpp | 128816a027ca82f8de8da5bad445641e71fb437f | [
"Apache-2.0"
] | 416 | 2018-04-22T14:03:25.000Z | 2022-03-31T13:30:56.000Z | src/oatpp/codegen/api_controller/base_undef.hpp | Purlemon/oatpp | 128816a027ca82f8de8da5bad445641e71fb437f | [
"Apache-2.0"
] | 1,140 | 2018-07-31T10:09:52.000Z | 2022-03-31T19:18:13.000Z | /***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* 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.
*
***************************************************************************/
#undef OATPP_MACRO_API_CONTROLLER_PARAM_MACRO
#undef OATPP_MACRO_API_CONTROLLER_PARAM_INFO
#undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE
#undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME
#undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE_STR
#undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME_STR
#undef OATPP_MACRO_API_CONTROLLER_PARAM
#undef REQUEST
#undef HEADER
#undef PATH
#undef QUERIES
#undef QUERY
#undef BODY_STRING
#undef BODY_DTO
// INIT // ------------------------------------------------------
#undef REST_CONTROLLER_INIT
#undef OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR
// REQUEST MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_REQUEST
#undef OATPP_MACRO_API_CONTROLLER_REQUEST_INFO
// HEADER MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_HEADER_1
#undef OATPP_MACRO_API_CONTROLLER_HEADER_2
#undef OATPP_MACRO_API_CONTROLLER_HEADER
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_1
#undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_2
#undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO
// PATH MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_PATH_1
#undef OATPP_MACRO_API_CONTROLLER_PATH_2
#undef OATPP_MACRO_API_CONTROLLER_PATH
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_1
#undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_2
#undef OATPP_MACRO_API_CONTROLLER_PATH_INFO
// QUERIES MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_QUERIES
#undef OATPP_MACRO_API_CONTROLLER_QUERIES_INFO
// QUERY MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_QUERY_1
#undef OATPP_MACRO_API_CONTROLLER_QUERY_2
#undef OATPP_MACRO_API_CONTROLLER_QUERY
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_1
#undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_2
#undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO
// BODY_STRING MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_BODY_STRING
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO
// BODY_DTO MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_BODY_DTO
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO
// FOR EACH // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO
// ENDPOINT_INFO MACRO // ------------------------------------------------------
#undef ENDPOINT_INFO
// ENDPOINT MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_0
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_1
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_0
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_1
#undef ENDPOINT
#undef ENDPOINT_INTERCEPTOR
// ENDPOINT ASYNC MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL
#undef ENDPOINT_ASYNC
#undef ENDPOINT_ASYNC_INIT
#undef ENDPOINT_INTERCEPTOR_ASYNC
| 30.834483 | 81 | 0.669425 | Purlemon |
b4db1d7e68a00024cf8e4ef64494ce6f134282b0 | 26,522 | cpp | C++ | dependencies/FreeImage/FreeImage/PluginPNG.cpp | sumneko/BLPConverter | 792392375061b80f3275f04353715b183309f91f | [
"MIT"
] | 53 | 2015-01-21T02:20:04.000Z | 2022-03-14T20:52:10.000Z | dependencies/FreeImage/FreeImage/PluginPNG.cpp | sumneko/BLPConverter | 792392375061b80f3275f04353715b183309f91f | [
"MIT"
] | 5 | 2016-01-10T08:54:22.000Z | 2020-09-10T14:58:23.000Z | dependencies/FreeImage/FreeImage/PluginPNG.cpp | sumneko/BLPConverter | 792392375061b80f3275f04353715b183309f91f | [
"MIT"
] | 29 | 2015-02-13T13:42:23.000Z | 2021-12-22T16:04:47.000Z | // ==========================================================
// PNG Loader and Writer
//
// Design and implementation by
// - Floris van den Berg (flvdberg@wxs.nl)
// - Herve Drolon (drolon@infonie.fr)
// - Detlev Vendt (detlev.vendt@brillit.de)
// - Aaron Shumate (trek@startreker.com)
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
#ifdef _MSC_VER
#pragma warning (disable : 4786) // identifier was truncated to 'number' characters
#endif
#include "FreeImage.h"
#include "Utilities.h"
#include "../Metadata/FreeImageTag.h"
// ----------------------------------------------------------
#define PNG_BYTES_TO_CHECK 8
// ----------------------------------------------------------
#include "../LibPNG/png.h"
// ----------------------------------------------------------
typedef struct {
FreeImageIO *s_io;
fi_handle s_handle;
} fi_ioStructure, *pfi_ioStructure;
/////////////////////////////////////////////////////////////////////////////
// libpng interface
//
static void
_ReadProc(png_structp png_ptr, unsigned char *data, png_size_t size) {
pfi_ioStructure pfio = (pfi_ioStructure)png_get_io_ptr(png_ptr);
unsigned n = pfio->s_io->read_proc(data, (unsigned int)size, 1, pfio->s_handle);
if(size && (n == 0)) {
throw "Read error: invalid or corrupted PNG file";
}
}
static void
_WriteProc(png_structp png_ptr, unsigned char *data, png_size_t size) {
pfi_ioStructure pfio = (pfi_ioStructure)png_get_io_ptr(png_ptr);
pfio->s_io->write_proc(data, (unsigned int)size, 1, pfio->s_handle);
}
static void
_FlushProc(png_structp png_ptr) {
// empty flush implementation
}
static void
error_handler(png_structp png_ptr, const char *error) {
throw error;
}
// in FreeImage warnings disabled
static void
warning_handler(png_structp png_ptr, const char *warning) {
}
// ==========================================================
// Metadata routines
// ==========================================================
static BOOL
ReadMetadata(png_structp png_ptr, png_infop info_ptr, FIBITMAP *dib) {
// XMP keyword
char *g_png_xmp_keyword = "XML:com.adobe.xmp";
FITAG *tag = NULL;
png_textp text_ptr = NULL;
int num_text = 0;
// iTXt/tEXt/zTXt chuncks
if(png_get_text(png_ptr, info_ptr, &text_ptr, &num_text) > 0) {
for(int i = 0; i < num_text; i++) {
// create a tag
tag = FreeImage_CreateTag();
if(!tag) return FALSE;
DWORD tag_length = (DWORD) MAX(text_ptr[i].text_length, text_ptr[i].itxt_length);
FreeImage_SetTagLength(tag, tag_length);
FreeImage_SetTagCount(tag, tag_length);
FreeImage_SetTagType(tag, FIDT_ASCII);
FreeImage_SetTagValue(tag, text_ptr[i].text);
if(strcmp(text_ptr[i].key, g_png_xmp_keyword) == 0) {
// store the tag as XMP
FreeImage_SetTagKey(tag, g_TagLib_XMPFieldName);
FreeImage_SetMetadata(FIMD_XMP, dib, FreeImage_GetTagKey(tag), tag);
} else {
// store the tag as a comment
FreeImage_SetTagKey(tag, text_ptr[i].key);
FreeImage_SetMetadata(FIMD_COMMENTS, dib, FreeImage_GetTagKey(tag), tag);
}
// destroy the tag
FreeImage_DeleteTag(tag);
}
}
return TRUE;
}
static BOOL
WriteMetadata(png_structp png_ptr, png_infop info_ptr, FIBITMAP *dib) {
// XMP keyword
char *g_png_xmp_keyword = "XML:com.adobe.xmp";
FITAG *tag = NULL;
FIMETADATA *mdhandle = NULL;
BOOL bResult = TRUE;
png_text text_metadata;
// set the 'Comments' metadata as iTXt chuncks
mdhandle = FreeImage_FindFirstMetadata(FIMD_COMMENTS, dib, &tag);
if(mdhandle) {
do {
memset(&text_metadata, 0, sizeof(png_text));
text_metadata.compression = 1; // iTXt, none
text_metadata.key = (char*)FreeImage_GetTagKey(tag); // keyword, 1-79 character description of "text"
text_metadata.text = (char*)FreeImage_GetTagValue(tag); // comment, may be an empty string (ie "")
text_metadata.text_length = FreeImage_GetTagLength(tag);// length of the text string
text_metadata.itxt_length = FreeImage_GetTagLength(tag);// length of the itxt string
text_metadata.lang = 0; // language code, 0-79 characters or a NULL pointer
text_metadata.lang_key = 0; // keyword translated UTF-8 string, 0 or more chars or a NULL pointer
// set the tag
png_set_text(png_ptr, info_ptr, &text_metadata, 1);
} while(FreeImage_FindNextMetadata(mdhandle, &tag));
FreeImage_FindCloseMetadata(mdhandle);
bResult &= TRUE;
}
// set the 'XMP' metadata as iTXt chuncks
tag = NULL;
FreeImage_GetMetadata(FIMD_XMP, dib, g_TagLib_XMPFieldName, &tag);
if(tag && FreeImage_GetTagLength(tag)) {
memset(&text_metadata, 0, sizeof(png_text));
text_metadata.compression = 1; // iTXt, none
text_metadata.key = g_png_xmp_keyword; // keyword, 1-79 character description of "text"
text_metadata.text = (char*)FreeImage_GetTagValue(tag); // comment, may be an empty string (ie "")
text_metadata.text_length = FreeImage_GetTagLength(tag);// length of the text string
text_metadata.itxt_length = FreeImage_GetTagLength(tag);// length of the itxt string
text_metadata.lang = 0; // language code, 0-79 characters or a NULL pointer
text_metadata.lang_key = 0; // keyword translated UTF-8 string, 0 or more chars or a NULL pointer
// set the tag
png_set_text(png_ptr, info_ptr, &text_metadata, 1);
bResult &= TRUE;
}
return bResult;
}
// ==========================================================
// Plugin Interface
// ==========================================================
static int s_format_id;
// ==========================================================
// Plugin Implementation
// ==========================================================
static const char * DLL_CALLCONV
Format() {
return "PNG";
}
static const char * DLL_CALLCONV
Description() {
return "Portable Network Graphics";
}
static const char * DLL_CALLCONV
Extension() {
return "png";
}
static const char * DLL_CALLCONV
RegExpr() {
return "^.PNG\r";
}
static const char * DLL_CALLCONV
MimeType() {
return "image/png";
}
static BOOL DLL_CALLCONV
Validate(FreeImageIO *io, fi_handle handle) {
BYTE png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
BYTE signature[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
io->read_proc(&signature, 1, 8, handle);
return (memcmp(png_signature, signature, 8) == 0);
}
static BOOL DLL_CALLCONV
SupportsExportDepth(int depth) {
return (
(depth == 1) ||
(depth == 4) ||
(depth == 8) ||
(depth == 24) ||
(depth == 32)
);
}
static BOOL DLL_CALLCONV
SupportsExportType(FREE_IMAGE_TYPE type) {
return (
(type == FIT_BITMAP) ||
(type == FIT_UINT16) ||
(type == FIT_RGB16) ||
(type == FIT_RGBA16)
);
}
static BOOL DLL_CALLCONV
SupportsICCProfiles() {
return TRUE;
}
// ----------------------------------------------------------
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
png_structp png_ptr = NULL;
png_infop info_ptr;
png_uint_32 width, height;
png_colorp png_palette = NULL;
int color_type, palette_entries = 0;
int bit_depth, pixel_depth; // pixel_depth = bit_depth * channels
FIBITMAP *dib = NULL;
RGBQUAD *palette = NULL; // pointer to dib palette
png_bytepp row_pointers = NULL;
int i;
fi_ioStructure fio;
fio.s_handle = handle;
fio.s_io = io;
if (handle) {
try {
// check to see if the file is in fact a PNG file
BYTE png_check[PNG_BYTES_TO_CHECK];
io->read_proc(png_check, PNG_BYTES_TO_CHECK, 1, handle);
if (png_sig_cmp(png_check, (png_size_t)0, PNG_BYTES_TO_CHECK) != 0)
return NULL; // Bad signature
// create the chunk manage structure
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, error_handler, warning_handler);
if (!png_ptr)
return NULL;
// create the info structure
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
return NULL;
}
// init the IO
png_set_read_fn(png_ptr, &fio, _ReadProc);
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return NULL;
}
// because we have already read the signature...
png_set_sig_bytes(png_ptr, PNG_BYTES_TO_CHECK);
// read the IHDR chunk
png_read_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL);
pixel_depth = info_ptr->pixel_depth;
// get image data type (assume standard image type)
FREE_IMAGE_TYPE image_type = FIT_BITMAP;
if (bit_depth == 16) {
if ((pixel_depth == 16) && (color_type == PNG_COLOR_TYPE_GRAY)) {
image_type = FIT_UINT16;
}
else if ((pixel_depth == 48) && (color_type == PNG_COLOR_TYPE_RGB)) {
image_type = FIT_RGB16;
}
else if ((pixel_depth == 64) && (color_type == PNG_COLOR_TYPE_RGB_ALPHA)) {
image_type = FIT_RGBA16;
} else {
// tell libpng to strip 16 bit/color files down to 8 bits/color
png_set_strip_16(png_ptr);
bit_depth = 8;
}
}
#ifndef FREEIMAGE_BIGENDIAN
if((image_type == FIT_UINT16) || (image_type == FIT_RGB16) || (image_type == FIT_RGBA16)) {
// turn on 16 bit byte swapping
png_set_swap(png_ptr);
}
#endif
// set some additional flags
switch(color_type) {
case PNG_COLOR_TYPE_RGB:
case PNG_COLOR_TYPE_RGB_ALPHA:
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip the RGB pixels to BGR (or RGBA to BGRA)
if(image_type == FIT_BITMAP)
png_set_bgr(png_ptr);
#endif
break;
case PNG_COLOR_TYPE_PALETTE:
// expand palette images to the full 8 bits from 2 bits/pixel
if (pixel_depth == 2) {
png_set_packing(png_ptr);
pixel_depth = 8;
}
break;
case PNG_COLOR_TYPE_GRAY:
// expand grayscale images to the full 8 bits from 2 bits/pixel
// but *do not* expand fully transparent palette entries to a full alpha channel
if (pixel_depth == 2) {
png_set_expand_gray_1_2_4_to_8(png_ptr);
pixel_depth = 8;
}
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
// expand 8-bit greyscale + 8-bit alpha to 32-bit
png_set_gray_to_rgb(png_ptr);
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip the RGBA pixels to BGRA
png_set_bgr(png_ptr);
#endif
pixel_depth = 32;
break;
default:
throw FI_MSG_ERROR_UNSUPPORTED_FORMAT;
}
// Get the background color to draw transparent and alpha images over.
// Note that even if the PNG file supplies a background, you are not required to
// use it - you should use the (solid) application background if it has one.
png_color_16p image_background = NULL;
RGBQUAD rgbBkColor;
if (png_get_bKGD(png_ptr, info_ptr, &image_background)) {
rgbBkColor.rgbRed = (BYTE)image_background->red;
rgbBkColor.rgbGreen = (BYTE)image_background->green;
rgbBkColor.rgbBlue = (BYTE)image_background->blue;
rgbBkColor.rgbReserved = 0;
}
// unlike the example in the libpng documentation, we have *no* idea where
// this file may have come from--so if it doesn't have a file gamma, don't
// do any correction ("do no harm")
double gamma = 0;
double screen_gamma = 2.2;
if (png_get_gAMA(png_ptr, info_ptr, &gamma) && ( flags & PNG_IGNOREGAMMA ) != PNG_IGNOREGAMMA)
png_set_gamma(png_ptr, screen_gamma, gamma);
// all transformations have been registered; now update info_ptr data
png_read_update_info(png_ptr, info_ptr);
// color type may have changed, due to our transformations
color_type = png_get_color_type(png_ptr,info_ptr);
// create a DIB and write the bitmap header
// set up the DIB palette, if needed
switch (color_type) {
case PNG_COLOR_TYPE_RGB:
png_set_invert_alpha(png_ptr);
if(image_type == FIT_BITMAP) {
dib = FreeImage_Allocate(width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
} else {
dib = FreeImage_AllocateT(image_type, width, height, pixel_depth);
}
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
if(image_type == FIT_BITMAP) {
dib = FreeImage_Allocate(width, height, 32, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
} else {
dib = FreeImage_AllocateT(image_type, width, height, pixel_depth);
}
break;
case PNG_COLOR_TYPE_PALETTE:
dib = FreeImage_Allocate(width, height, pixel_depth);
png_get_PLTE(png_ptr,info_ptr, &png_palette,&palette_entries);
palette = FreeImage_GetPalette(dib);
// store the palette
for (i = 0; i < palette_entries; i++) {
palette[i].rgbRed = png_palette[i].red;
palette[i].rgbGreen = png_palette[i].green;
palette[i].rgbBlue = png_palette[i].blue;
}
// store the transparency table
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
int num_trans = 0;
png_bytep trans = NULL;
png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
FreeImage_SetTransparencyTable(dib, (BYTE *)trans, num_trans);
}
break;
case PNG_COLOR_TYPE_GRAY:
dib = FreeImage_AllocateT(image_type, width, height, pixel_depth);
if(pixel_depth <= 8) {
palette = FreeImage_GetPalette(dib);
palette_entries = 1 << pixel_depth;
for (i = 0; i < palette_entries; i++) {
palette[i].rgbRed =
palette[i].rgbGreen =
palette[i].rgbBlue = (BYTE)((i * 255) / (palette_entries - 1));
}
}
// store the transparency table
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_color_16p trans_values = NULL;
png_get_tRNS(png_ptr, info_ptr, NULL, NULL, &trans_values);
if(trans_values) {
if (trans_values->gray < palette_entries) {
BYTE table[256];
memset(table, 0xFF, palette_entries);
table[trans_values->gray] = 0;
FreeImage_SetTransparencyTable(dib, table, palette_entries);
}
}
}
break;
default:
throw FI_MSG_ERROR_UNSUPPORTED_FORMAT;
}
// store the background color
if(image_background) {
FreeImage_SetBackgroundColor(dib, &rgbBkColor);
}
// get physical resolution
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_pHYs)) {
png_uint_32 res_x, res_y;
// we'll overload this var and use 0 to mean no phys data,
// since if it's not in meters we can't use it anyway
int res_unit_type = 0;
png_get_pHYs(png_ptr,info_ptr,&res_x,&res_y,&res_unit_type);
if (res_unit_type == 1) {
FreeImage_SetDotsPerMeterX(dib, res_x);
FreeImage_SetDotsPerMeterY(dib, res_y);
}
}
// get possible ICC profile
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP)) {
png_charp profile_name = NULL;
png_charp profile_data = NULL;
png_uint_32 profile_length = 0;
int compression_type;
png_get_iCCP(png_ptr, info_ptr, &profile_name, &compression_type, &profile_data, &profile_length);
// copy ICC profile data (must be done after FreeImage_Allocate)
FreeImage_CreateICCProfile(dib, profile_data, profile_length);
}
// set the individual row_pointers to point at the correct offsets
row_pointers = (png_bytepp)malloc(height * sizeof(png_bytep));
if (!row_pointers) {
if (palette)
png_free(png_ptr, palette);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
FreeImage_Unload(dib);
return NULL;
}
// read in the bitmap bits via the pointer table
for (png_uint_32 k = 0; k < height; k++)
row_pointers[height - 1 - k] = FreeImage_GetScanLine(dib, k);
png_read_image(png_ptr, row_pointers);
// check if the bitmap contains transparency, if so enable it in the header
if (FreeImage_GetBPP(dib) == 32)
if (FreeImage_GetColorType(dib) == FIC_RGBALPHA)
FreeImage_SetTransparent(dib, TRUE);
else
FreeImage_SetTransparent(dib, FALSE);
// cleanup
if (row_pointers) {
free(row_pointers);
row_pointers = NULL;
}
// read the rest of the file, getting any additional chunks in info_ptr
png_read_end(png_ptr, info_ptr);
// get possible metadata (it can be located both before and after the image data)
ReadMetadata(png_ptr, info_ptr, dib);
if (png_ptr) {
// clean up after the read, and free any memory allocated - REQUIRED
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
}
return dib;
} catch (const char *text) {
if (png_ptr)
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
if (row_pointers)
free(row_pointers);
if (dib)
FreeImage_Unload(dib);
FreeImage_OutputMessageProc(s_format_id, text);
return NULL;
}
}
return NULL;
}
static BOOL DLL_CALLCONV
Save(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data) {
png_structp png_ptr;
png_infop info_ptr;
png_colorp palette = NULL;
png_uint_32 width, height;
BOOL has_alpha_channel = FALSE;
RGBQUAD *pal; // pointer to dib palette
int bit_depth, pixel_depth; // pixel_depth = bit_depth * channels
int palette_entries;
int interlace_type;
fi_ioStructure fio;
fio.s_handle = handle;
fio.s_io = io;
if ((dib) && (handle)) {
try {
// create the chunk manage structure
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, error_handler, warning_handler);
if (!png_ptr) {
return FALSE;
}
// allocate/initialize the image information data.
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
return FALSE;
}
// Set error handling. REQUIRED if you aren't supplying your own
// error handling functions in the png_create_write_struct() call.
if (setjmp(png_jmpbuf(png_ptr))) {
// if we get here, we had a problem reading the file
png_destroy_write_struct(&png_ptr, &info_ptr);
return FALSE;
}
// init the IO
png_set_write_fn(png_ptr, &fio, _WriteProc, _FlushProc);
// set physical resolution
png_uint_32 res_x = (png_uint_32)FreeImage_GetDotsPerMeterX(dib);
png_uint_32 res_y = (png_uint_32)FreeImage_GetDotsPerMeterY(dib);
if ((res_x > 0) && (res_y > 0)) {
png_set_pHYs(png_ptr, info_ptr, res_x, res_y, 1);
}
// Set the image information here. Width and height are up to 2^31,
// bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
// the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
// PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
// or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
// PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
// currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
width = FreeImage_GetWidth(dib);
height = FreeImage_GetHeight(dib);
pixel_depth = FreeImage_GetBPP(dib);
BOOL bInterlaced = FALSE;
if( (flags & PNG_INTERLACED) == PNG_INTERLACED) {
interlace_type = PNG_INTERLACE_ADAM7;
bInterlaced = TRUE;
} else {
interlace_type = PNG_INTERLACE_NONE;
}
// set the ZLIB compression level or default to PNG default compression level (ZLIB level = 6)
int zlib_level = flags & 0x0F;
if((zlib_level >= 1) && (zlib_level <= 9)) {
png_set_compression_level(png_ptr, zlib_level);
} else if((flags & PNG_Z_NO_COMPRESSION) == PNG_Z_NO_COMPRESSION) {
png_set_compression_level(png_ptr, Z_NO_COMPRESSION);
}
// filtered strategy works better for high color images
if(pixel_depth >= 16){
png_set_compression_strategy(png_ptr, Z_FILTERED);
png_set_filter(png_ptr, 0, PNG_FILTER_NONE|PNG_FILTER_SUB|PNG_FILTER_PAETH);
} else {
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
}
FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(dib);
if(image_type == FIT_BITMAP) {
// standard image type
bit_depth = (pixel_depth > 8) ? 8 : pixel_depth;
} else {
// 16-bit greyscale or 16-bit RGB(A)
bit_depth = 16;
}
switch (FreeImage_GetColorType(dib)) {
case FIC_MINISWHITE:
// Invert monochrome files to have 0 as black and 1 as white (no break here)
png_set_invert_mono(png_ptr);
case FIC_MINISBLACK:
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_GRAY, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
break;
case FIC_PALETTE:
{
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_PALETTE, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
// set the palette
palette_entries = 1 << bit_depth;
palette = (png_colorp)png_malloc(png_ptr, palette_entries * sizeof (png_color));
pal = FreeImage_GetPalette(dib);
for (int i = 0; i < palette_entries; i++) {
palette[i].red = pal[i].rgbRed;
palette[i].green = pal[i].rgbGreen;
palette[i].blue = pal[i].rgbBlue;
}
png_set_PLTE(png_ptr, info_ptr, palette, palette_entries);
// You must not free palette here, because png_set_PLTE only makes a link to
// the palette that you malloced. Wait until you are about to destroy
// the png structure.
break;
}
case FIC_RGBALPHA :
has_alpha_channel = TRUE;
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_RGBA, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip BGR pixels to RGB
if(image_type == FIT_BITMAP)
png_set_bgr(png_ptr);
#endif
break;
case FIC_RGB:
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_RGB, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip BGR pixels to RGB
if(image_type == FIT_BITMAP)
png_set_bgr(png_ptr);
#endif
break;
case FIC_CMYK:
break;
}
// write possible ICC profile
FIICCPROFILE *iccProfile = FreeImage_GetICCProfile(dib);
if (iccProfile->size && iccProfile->data) {
png_set_iCCP(png_ptr, info_ptr, "Embedded Profile", 0, (png_charp)iccProfile->data, iccProfile->size);
}
// write metadata
WriteMetadata(png_ptr, info_ptr, dib);
// Optional gamma chunk is strongly suggested if you have any guess
// as to the correct gamma of the image.
// png_set_gAMA(png_ptr, info_ptr, gamma);
// set the transparency table
if (FreeImage_IsTransparent(dib) && (FreeImage_GetTransparencyCount(dib) > 0)) {
png_set_tRNS(png_ptr, info_ptr, FreeImage_GetTransparencyTable(dib), FreeImage_GetTransparencyCount(dib), NULL);
}
// set the background color
if(FreeImage_HasBackgroundColor(dib)) {
png_color_16 image_background;
RGBQUAD rgbBkColor;
FreeImage_GetBackgroundColor(dib, &rgbBkColor);
memset(&image_background, 0, sizeof(png_color_16));
image_background.blue = rgbBkColor.rgbBlue;
image_background.green = rgbBkColor.rgbGreen;
image_background.red = rgbBkColor.rgbRed;
image_background.index = rgbBkColor.rgbReserved;
png_set_bKGD(png_ptr, info_ptr, &image_background);
}
// Write the file header information.
png_write_info(png_ptr, info_ptr);
// write out the image data
#ifndef FREEIMAGE_BIGENDIAN
if (bit_depth == 16) {
// turn on 16 bit byte swapping
png_set_swap(png_ptr);
}
#endif
int number_passes = 1;
if (bInterlaced) {
number_passes = png_set_interlace_handling(png_ptr);
}
if ((pixel_depth == 32) && (!has_alpha_channel)) {
BYTE *buffer = (BYTE *)malloc(width * 3);
// transparent conversion to 24-bit
// the number of passes is either 1 for non-interlaced images, or 7 for interlaced images
for (int pass = 0; pass < number_passes; pass++) {
for (png_uint_32 k = 0; k < height; k++) {
FreeImage_ConvertLine32To24(buffer, FreeImage_GetScanLine(dib, height - k - 1), width);
png_write_row(png_ptr, buffer);
}
}
free(buffer);
} else {
// the number of passes is either 1 for non-interlaced images, or 7 for interlaced images
for (int pass = 0; pass < number_passes; pass++) {
for (png_uint_32 k = 0; k < height; k++) {
png_write_row(png_ptr, FreeImage_GetScanLine(dib, height - k - 1));
}
}
}
// It is REQUIRED to call this to finish writing the rest of the file
// Bug with png_flush
png_write_end(png_ptr, info_ptr);
// clean up after the write, and free any memory allocated
if (palette) {
png_free(png_ptr, palette);
}
png_destroy_write_struct(&png_ptr, &info_ptr);
return TRUE;
} catch (const char *text) {
FreeImage_OutputMessageProc(s_format_id, text);
}
}
return FALSE;
}
// ==========================================================
// Init
// ==========================================================
void DLL_CALLCONV
InitPNG(Plugin *plugin, int format_id) {
s_format_id = format_id;
plugin->format_proc = Format;
plugin->description_proc = Description;
plugin->extension_proc = Extension;
plugin->regexpr_proc = RegExpr;
plugin->open_proc = NULL;
plugin->close_proc = NULL;
plugin->pagecount_proc = NULL;
plugin->pagecapability_proc = NULL;
plugin->load_proc = Load;
plugin->save_proc = Save;
plugin->validate_proc = Validate;
plugin->mime_proc = MimeType;
plugin->supports_export_bpp_proc = SupportsExportDepth;
plugin->supports_export_type_proc = SupportsExportType;
plugin->supports_icc_profiles_proc = SupportsICCProfiles;
}
| 28.922574 | 116 | 0.669557 | sumneko |
b4dd8f024ae515013e5bf490deb1d1acd9740376 | 4,249 | cpp | C++ | src/server/old/server_simulated/server_simple.cpp | EdgeLab-FHDO/ResourceAllocationE2EL | 426d0104ab3439c1b107262aeade340999a8bafb | [
"MIT"
] | null | null | null | src/server/old/server_simulated/server_simple.cpp | EdgeLab-FHDO/ResourceAllocationE2EL | 426d0104ab3439c1b107262aeade340999a8bafb | [
"MIT"
] | 1 | 2020-04-14T17:10:46.000Z | 2020-04-14T17:10:46.000Z | src/server/old/server_simulated/server_simple.cpp | EdgeLab-FHDO/ResourceAllocationE2EL | 426d0104ab3439c1b107262aeade340999a8bafb | [
"MIT"
] | null | null | null | /* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
//using namespace std;
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
//sleep(60);
//::cout << "after sleep\n";
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://meep-mg-manager"));
// Build request URI and start the request.
uri_builder builder(U("/v1/mg/mysrv/app/server"));
//builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::POST, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
//printf("Received response status code:%u\n", response.status_code());
std::cout << "Received response status code: " << response.status_code() << std::endl;
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
//printf("Error exception:%s\n", e.what());
std::cout << "Error exception: " << e.what() << std::endl;
}
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
bool connected = false;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
while(true)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
std::cout << "ERROR opening socket: " << strerror(errno) << std::endl;
}
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
std::cout << "ERROR on binding: " << strerror(errno) << std::endl;
}
std::cout << "listening on port: " << portno << std::endl;
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
std::cout << "ERROR on accept: " << strerror(errno) << std::endl;
}
close(sockfd); // so that no one else can connect until the current connection is closed
connected = true;
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
setsockopt(newsockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
while(connected)
{
bzero(buffer,256);
n = recv(newsockfd,buffer,1,0);
if (n < 0)
{
std::cout << "ERROR reading from socket: " << strerror(errno) << std::endl;
connected = false;
}
std::cout << "count: "<< (int)buffer[0] << std::endl;
buffer[0]++;
n = send(newsockfd,buffer,1,MSG_NOSIGNAL);
if (n < 0)
{
std::cout << "ERROR writing to socket: " << strerror(errno) << std::endl;
connected = false;
}
}
}
close(newsockfd);
close(sockfd);
return 0;
} | 27.590909 | 102 | 0.587197 | EdgeLab-FHDO |
b4de8f00ebe48a9ced52f6fa51080c759423ad08 | 1,461 | hpp | C++ | third_party/boost/simd/function/bitwise_and.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | 5 | 2018-02-20T11:21:12.000Z | 2019-11-12T13:45:09.000Z | third_party/boost/simd/function/bitwise_and.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/function/bitwise_and.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | 2 | 2017-12-12T12:29:52.000Z | 2019-04-08T15:55:25.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_BITWISE_AND_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_BITWISE_AND_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-bitwise
Function object implementing bitwise_and capabilities
Computes the bitwise and of the two parameters.
The operands must share the same bit size.
The result type is the one of the first operand.
Infix notation can be used with operator '&',
but this will not work in scalar mode if any
operand is floating point because of C++ limitations.
@par Semantic:
For every parameters of @c x of type @c T0, @c y of type @c T1:
@code
T0 r = bitwise_and(x,y);
@endcode
is similar to:
@code
T0 r = x & y;
@endcode
@see bitwise_or, bitwise_xor, bitwise_notand,
bitwise_andnot, bitwise_notor, bitwise_ornot, complement
**/
T0 bitwise_and(T0 const& x, T1 const& y);
} }
#endif
#include <boost/simd/function/scalar/bitwise_and.hpp>
#include <boost/simd/function/simd/bitwise_and.hpp>
#endif
| 24.762712 | 100 | 0.613963 | xmar |
b4dfbda23cada387b7d3ed387269647ba5ec2850 | 722 | cc | C++ | Contests/Virtual Judge/Summer 20190710/A.cc | DCTewi/My-Codes | 9904f8057ec96e21cbc8cf9c62a49658a0f6d392 | [
"MIT"
] | null | null | null | Contests/Virtual Judge/Summer 20190710/A.cc | DCTewi/My-Codes | 9904f8057ec96e21cbc8cf9c62a49658a0f6d392 | [
"MIT"
] | null | null | null | Contests/Virtual Judge/Summer 20190710/A.cc | DCTewi/My-Codes | 9904f8057ec96e21cbc8cf9c62a49658a0f6d392 | [
"MIT"
] | null | null | null | // A Calandar
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const string days[] = {"Friday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
string date;
ll yy1, yy2, m1, m2, d1, d2, offset;
int main()
{
int T; scanf("%d", &T);
while (T--)
{
scanf("%lld%lld%lld", &yy1, &m1, &d1);
cin >> date;
scanf("%lld%lld%lld", &yy2, &m2, &d2);
offset = (yy2 - yy1) *12 * 30 + (m2 - m1) * 30 + (d2 - d1);
for (int i = 1; i < 6; i++)
{
if (date == days[i])
{
offset += i; break;
}
}
offset = (offset % 5 + 5) % 5;
puts(days[offset].c_str());
}
return 0;
} | 21.878788 | 89 | 0.445983 | DCTewi |
b4e16904f5ba11c19ee99bfeb9e8205bcf639a10 | 728 | cc | C++ | cxx/satellite/src/SensitiveDetectorFactory.cc | Zelenyy/phd-code | d5b8bfefd2418a915dde89f7da2cb6683f438556 | [
"MIT"
] | null | null | null | cxx/satellite/src/SensitiveDetectorFactory.cc | Zelenyy/phd-code | d5b8bfefd2418a915dde89f7da2cb6683f438556 | [
"MIT"
] | null | null | null | cxx/satellite/src/SensitiveDetectorFactory.cc | Zelenyy/phd-code | d5b8bfefd2418a915dde89f7da2cb6683f438556 | [
"MIT"
] | null | null | null | //
// Created by zelenyy on 07.12.17.
//
#include "SensitiveDetectorFactory.hh"
#include "SensitiveScoredDetector.hh"
#include "G4SDManager.hh"
using namespace std;
G4VSensitiveDetector *SensitiveDetectorFactory::getSensitiveDetector(G4GDMLAuxListType::const_iterator vit) {
auto name = (*vit).value;
G4SDManager *fSDM = G4SDManager::GetSDMpointer();
G4VSensitiveDetector *tempDetector;
if (name == "SensitiveScoredDetector") {
tempDetector = new SensitiveScoredDetector(name, fSettings);
} else {
tempDetector = IDetectorFactory::getSensitiveDetector(vit);
}
fSDM->AddNewDetector(tempDetector);
G4cout << "Create new detector: " << name << endl;
return tempDetector;
}
| 26.962963 | 109 | 0.721154 | Zelenyy |
b4e2959d4569b3a2fe6e34d099433cc45686a1a4 | 924 | cpp | C++ | test/examples_test/02_module_test/02_module_tests.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-Ruby1909 | 3edea4f327aea2b8c9c7e788693339d1625a039f | [
"MIT"
] | null | null | null | test/examples_test/02_module_test/02_module_tests.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-Ruby1909 | 3edea4f327aea2b8c9c7e788693339d1625a039f | [
"MIT"
] | null | null | null | test/examples_test/02_module_test/02_module_tests.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-Ruby1909 | 3edea4f327aea2b8c9c7e788693339d1625a039f | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "if.h"
#include "if_else.h"
#include "switch.h"
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE(true == true);
}
TEST_CASE("Test is even function")
{
REQUIRE(is_even(2) == true);
}
TEST_CASE("Test get generation function")
{
REQUIRE(get_generation(2010) == "Centenial");
REQUIRE(get_generation(1990) == "Millenial");
REQUIRE(get_generation(1970) == "Generation X");
REQUIRE(get_generation(1950) == "Baby Boomer");
REQUIRE(get_generation(1930) == "Silent Generation");
//REQUIRE(get_generation(1000) == "Invalid Year");
}
TEST_CASE("Test menu function ")
{
REQUIRE(menu(0) == "Invalid Option");
REQUIRE(menu(1) == "Option 1");
REQUIRE(menu(2) == "Option 2");
REQUIRE(menu(3) == "Option 3");
REQUIRE(menu(4) == "Option 4");
REQUIRE(menu(5) == "Invalid Option");
} | 27.176471 | 97 | 0.685065 | acc-cosc-1337-spring-2020 |
b4e30396f958ebc6cf81d57b713635ac95a5406e | 2,658 | cpp | C++ | actions/SendMessageAction.cpp | horfee/alarmpi | e48e016d2378f0db0ef19abd47d144d0b1dbd904 | [
"Apache-2.0"
] | null | null | null | actions/SendMessageAction.cpp | horfee/alarmpi | e48e016d2378f0db0ef19abd47d144d0b1dbd904 | [
"Apache-2.0"
] | null | null | null | actions/SendMessageAction.cpp | horfee/alarmpi | e48e016d2378f0db0ef19abd47d144d0b1dbd904 | [
"Apache-2.0"
] | null | null | null | /*
* SendMessageAction.cpp
*
* Created on: 3 août 2015
* Author: horfee
*/
#include "SendMessageAction.h"
#include "../Properties.h"
#include <ctime>
#include <locale>
namespace alarmpi {
SendMessageAction::SendMessageAction(std::string name, std::string message, bool synchronous): Action(name, synchronous), message(message) {
}
SendMessageAction::~SendMessageAction() {
}
std::string SendMessageAction::getMessage() const {
return message;
}
void SendMessageAction::execute(Device* device, Mode* mode) {
// if ( !stopAsked() ) {
// setRunning();
size_t pos = message.find("$device");
std::string msg = message;
if ( pos != std::string::npos ) {
msg = message.substr(0, pos) + device->getDescription() + message.substr(pos + std::string("$device").length());
}
pos = msg.find("$mode");
if ( pos != std::string::npos ) {
msg = msg.substr(0, pos) + mode->getName() + msg.substr(pos + std::string("$mode").length());
}
pos = msg.find("$time");
if ( pos != std::string::npos ) {
std::time_t t = std::time(NULL);
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%X", std::localtime(&t));
msg = msg.substr(0, pos) + std::string(mbstr) + msg.substr(pos + std::string("$time").length());
}
pos = msg.find("$date");
if ( pos != std::string::npos ) {
std::time_t t = std::time(NULL);
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%x", std::localtime(&t));
msg = msg.substr(0, pos) + std::string(mbstr) + msg.substr(pos + std::string("$date").length());
}
pos = msg.find("$action.");
if ( pos != std::string::npos ) {
size_t pos2 = msg.find(" ", pos + 8);
std::string val = msg.substr(pos + 8, pos2 - (pos + 8));
Json::Value v = this->toJSON();
Json::Value v2 = v[val];
std::string res;
if ( v2.type() == Json::ValueType::stringValue ) {
res = v2.asString();
} else if ( v2.type() == Json::ValueType::intValue ) {
res = std::to_string(v2.asInt());
} else if ( v2.type() == Json::ValueType::realValue ) {
res = std::to_string(v2.asDouble());
} else if ( v2.type() == Json::ValueType::booleanValue ) {
res = std::to_string(v2.asBool());
} else if ( v2.type() == Json::ValueType::uintValue ) {
res = std::to_string(v2.asUInt());
}
msg = msg.substr(0, pos) + res + msg.substr(pos2);
}
// if ( !stopAsked() ) {
system->sendSMS(msg);
// }
// }
// Action::execute(device, mode);
}
Json::Value SendMessageAction::toJSON() const {
Json::Value res = Action::toJSON();
res["message"] = message;
return res;
}
std::string SendMessageAction::getType() const {
return "SENDMESSAGEACTION";
}
} /* namespace alarmpi */
| 29.208791 | 140 | 0.611362 | horfee |
b4e59b2d4ff7ae5363cb8830079782c204448464 | 7,679 | cpp | C++ | src/runtime_src/core/tools/common/XBMain.cpp | DavidMarec/XRT | 629f07123bff878a7916b82068b925acf5c4aa9c | [
"Apache-2.0"
] | null | null | null | src/runtime_src/core/tools/common/XBMain.cpp | DavidMarec/XRT | 629f07123bff878a7916b82068b925acf5c4aa9c | [
"Apache-2.0"
] | null | null | null | src/runtime_src/core/tools/common/XBMain.cpp | DavidMarec/XRT | 629f07123bff878a7916b82068b925acf5c4aa9c | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2019-2022 Xilinx, Inc
*
* 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://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.
*/
// ------ I N C L U D E F I L E S -------------------------------------------
// Local - Include Files
#include "SubCmd.h"
#include "XBHelpMenusCore.h"
#include "XBUtilitiesCore.h"
#include "XBHelpMenus.h"
#include "XBMain.h"
#include "XBUtilities.h"
namespace XBU = XBUtilities;
// 3rd Party Library - Include Files
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <cstdlib>
namespace po = boost::program_options;
// System - Include Files
#include <iostream>
// ------ Program entry point -------------------------------------------------
void main_(int argc, char** argv,
const std::string & _executable,
const std::string & _description,
const SubCmdsCollection &_subCmds)
{
bool isUserDomain = boost::iequals(_executable, "xbutil");
// Global options
bool bVerbose = false;
bool bTrace = false;
bool bHelp = false;
bool bBatchMode = false;
bool bShowHidden = false;
bool bForce = false;
bool bVersion = false;
std::string sDevice;
// Build Options
po::options_description globalSubCmdOptions("Global Command Options");
globalSubCmdOptions.add_options()
("verbose", boost::program_options::bool_switch(&bVerbose), "Turn on verbosity")
("batch", boost::program_options::bool_switch(&bBatchMode), "Enable batch mode (disables escape characters)")
("force", boost::program_options::bool_switch(&bForce), "When possible, force an operation")
;
po::options_description globalOptions("Global Options");
globalOptions.add_options()
("help", boost::program_options::bool_switch(&bHelp), "Help to use this application")
("version", boost::program_options::bool_switch(&bVersion), "Report the version of XRT and its drivers")
;
globalOptions.add(globalSubCmdOptions);
// Hidden Options
po::options_description hiddenOptions("Hidden Options");
hiddenOptions.add_options()
("device,d", boost::program_options::value<decltype(sDevice)>(&sDevice)->default_value("")->implicit_value("default"), "If specified with no BDF value and there is only 1 device, that device will be automatically selected.\n")
("trace", boost::program_options::bool_switch(&bTrace), "Enables code flow tracing")
("show-hidden", boost::program_options::bool_switch(&bShowHidden), "Shows hidden options and commands")
("subCmd", po::value<std::string>(), "Command to execute")
("subCmdArgs", po::value<std::vector<std::string> >(), "Arguments for command")
;
// Merge the options to one common collection
po::options_description allOptions("All Options");
allOptions.add(globalOptions).add(hiddenOptions);
// Create a sub-option command and arguments
po::positional_options_description positionalCommand;
positionalCommand.
add("subCmd", 1 /* max_count */).
add("subCmdArgs", -1 /* Unlimited max_count */);
// -- Parse the command line
po::parsed_options parsed = po::command_line_parser(argc, argv).
options(allOptions). // Global options
positional(positionalCommand). // Our commands
allow_unregistered(). // Allow for unregistered options (needed for sub options)
run(); // Parse the options
po::variables_map vm;
try {
po::store(parsed, vm); // Can throw
po::notify(vm); // Can throw
} catch (po::error& e) {
// Something bad happen with parsing our options
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
XBU::report_commands_help(_executable, _description, globalOptions, hiddenOptions, _subCmds);
throw xrt_core::error(std::errc::operation_canceled);
}
if(bVersion) {
std::cout << XBU::get_xrt_pretty_version();
return;
}
// -- Enable/Disable helper "global" options
XBU::disable_escape_codes( bBatchMode );
XBU::setVerbose( bVerbose );
XBU::setTrace( bTrace );
XBU::setShowHidden( bShowHidden );
XBU::setForce( bForce );
// Check to see if help was requested and no command was found
if (vm.count("subCmd") == 0) {
XBU::report_commands_help( _executable, _description, globalOptions, hiddenOptions, _subCmds);
return;
}
// -- Now see if there is a command to work with
// Get the command of choice
std::string sCommand = vm["subCmd"].as<std::string>();
// Search for the subcommand (case sensitive)
std::shared_ptr<SubCmd> subCommand;
for (auto & subCmdEntry : _subCmds) {
if (sCommand.compare(subCmdEntry->getName()) == 0) {
subCommand = subCmdEntry;
break;
}
}
if ( !subCommand) {
std::cerr << "ERROR: " << "Unknown command: '" << sCommand << "'" << std::endl;
XBU::report_commands_help( _executable, _description, globalOptions, hiddenOptions, _subCmds);
throw xrt_core::error(std::errc::operation_canceled);
}
// -- Prepare the data
std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
opts.erase(opts.begin());
if (bHelp == true)
opts.push_back("--help");
#ifdef ENABLE_DEFAULT_ONE_DEVICE_OPTION
// If the user has NOT specified a device AND the command to be executed
// is not the examine command, then automatically add the device.
// Note: "examine" produces different reports depending if the user has
// specified the --device option or not.
if ( sDevice.empty() &&
(subCommand->isDefaultDeviceValid())) {
sDevice = "default";
}
#endif
// Was default device requested?
if (boost::iequals(sDevice, "default")) {
sDevice.clear();
boost::property_tree::ptree available_devices = XBU::get_available_devices(isUserDomain);
// DRC: Are there any devices
if (available_devices.empty())
throw std::runtime_error("No devices found.");
// DRC: Are there multiple devices, if so then no default device can be found.
if (available_devices.size() > 1) {
std::cerr << "\nERROR: Multiple devices found. Please specify a single device using the --device option\n\n";
std::cerr << "List of available devices:" << std::endl;
for (auto &kd : available_devices) {
boost::property_tree::ptree& dev = kd.second;
std::cerr << boost::format(" [%s] : %s\n") % dev.get<std::string>("bdf") % dev.get<std::string>("vbnv");
}
std::cout << std::endl;
throw xrt_core::error(std::errc::operation_canceled);
}
// We have only 1 item in the array, get it
for (const auto &kd : available_devices)
sDevice = kd.second.get<std::string>("bdf"); // Exit after the first item
}
// If there is a device value, pass it to the sub commands.
if (!sDevice.empty()) {
opts.push_back("-d");
opts.push_back(sDevice);
}
subCommand->setGlobalOptions(globalSubCmdOptions);
// -- Execute the sub-command
subCommand->execute(opts);
}
| 37.096618 | 234 | 0.650345 | DavidMarec |
b4e868e08e9d479d724d5eff05c4abb63dbde16f | 569 | cpp | C++ | cpp/optimizers/ut/optimizer_ut.cpp | equivalence1/ml_lib | 92d75ab73bc2d77ba8fa66022c803c06cad66f21 | [
"Apache-2.0"
] | 1 | 2019-02-15T09:40:43.000Z | 2019-02-15T09:40:43.000Z | cpp/optimizers/ut/optimizer_ut.cpp | equivalence1/ml_lib | 92d75ab73bc2d77ba8fa66022c803c06cad66f21 | [
"Apache-2.0"
] | null | null | null | cpp/optimizers/ut/optimizer_ut.cpp | equivalence1/ml_lib | 92d75ab73bc2d77ba8fa66022c803c06cad66f21 | [
"Apache-2.0"
] | 2 | 2018-09-29T10:17:26.000Z | 2018-10-03T20:33:31.000Z | #include <core/vec_factory.h>
#include <core/optimizers/gradient_descent.h>
#include <core/vec_tools/fill.h>
#include <core/vec_tools/distance.h>
#include <core/funcs/lq.h>
#include <gtest/gtest.h>
TEST(Optimizer, GradientDescentTest) {
const int N = 10;
const double q = 2;
const double EPS = 0.01;
GradientDescent gd(EPS);
auto cursor = Vec(N);
VecTools::fill(1, cursor);
auto b = Vec(N);
VecTools::fill(2, b);
Lq distFunc(q, b);
gd.optimize(distFunc, cursor);
EXPECT_LE(VecTools::distanceLq(q, cursor, b), EPS);
}
| 20.321429 | 55 | 0.659051 | equivalence1 |
b4e8e9b3393dddbcf50e3367d317acd84f1c7744 | 18,826 | hpp | C++ | gsa/wit/COIN/Bcp/include/BCP_matrix.hpp | kant/CMMPPT | c64b339712db28a619880c4c04839aef7d3b6e2b | [
"Apache-2.0"
] | 1 | 2019-10-25T05:25:23.000Z | 2019-10-25T05:25:23.000Z | gsa/wit/COIN/Bcp/include/BCP_matrix.hpp | kant/CMMPPT | c64b339712db28a619880c4c04839aef7d3b6e2b | [
"Apache-2.0"
] | 2 | 2019-09-04T17:34:59.000Z | 2020-09-16T08:10:57.000Z | gsa/wit/COIN/Bcp/include/BCP_matrix.hpp | kant/CMMPPT | c64b339712db28a619880c4c04839aef7d3b6e2b | [
"Apache-2.0"
] | 18 | 2019-07-22T19:01:25.000Z | 2022-03-03T15:36:11.000Z | // Copyright (C) 2000, International Business Machines
// Corporation and others. All Rights Reserved.
#ifndef _BCP_MATRIX_H
#define _BCP_MATRIX_H
// This file is fully docified.
#include <cmath>
#include <cfloat>
#include "CoinPackedVector.hpp"
#include "CoinPackedMatrix.hpp"
#include "BCP_vector.hpp"
//#############################################################################
class BCP_buffer;
//#############################################################################
/** This class holds a column in a compressed form. That is, it is a packed
vector with an objective coefficient, lower and upper bound. */
class BCP_col : public CoinPackedVector {
protected:
/**@name Data members */
/*@{*/
/** The objective function coefficient corresponding to the column. */
double _Objective;
/** The lower bound corresponding to the column. */
double _LowerBound;
/** The upper bound corresponding to the column. */
double _UpperBound;
/*@}*/
//--------------------------------------------------------------------------
public:
/**@name Query methods */
/*@{*/
/** Return the objective coefficient. */
inline double Objective() const { return _Objective; }
/** Return the lower bound. */
inline double LowerBound() const { return _LowerBound; }
/** Return the upper bound. */
inline double UpperBound() const { return _UpperBound; }
/*@}*/
//--------------------------------------------------------------------------
/**@name General modifying methods */
/*@{*/
/** Set the objective coefficient to the given value. */
inline void Objective(const double obj) { _Objective = obj; }
/** Set the lower bound to the given value. */
inline void LowerBound(const double lb) { _LowerBound = lb; }
/** Set the upper bound to the given value. */
inline void UpperBound(const double ub) { _UpperBound = ub; }
/** Assignment operator: copy over the contents of <code>x</code>. */
BCP_col& operator=(const BCP_col& x) {
CoinPackedVector::operator=(x);
_Objective = x.Objective();
_LowerBound = x.LowerBound();
_UpperBound = x.UpperBound();
return *this;
}
/** Set the objective coefficient, lower and upper bounds to the given
values. Also invokes the assign method of the underlying packed vector.
*/
inline void
assign(const int size, int*& ElementIndices, double*& ElementValues,
const double Obj, const double LB, const double UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_Objective = Obj;
_LowerBound = LB;
_UpperBound = UB;
}
/** Copy the arguments into the appropriate data members. */
inline void
copy(const int size, const int* ElementIndices, const double* ElementValues,
const double Obj, const double LB, const double UB) {
CoinPackedVector::setVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_Objective = Obj;
_LowerBound = LB;
_UpperBound = UB;
}
/** Same as the other <code>copy()</code> method, except that instead of
using vectors the indices (values) are given in
<code>[firstind,lastind)</code> (<code>[firstval,lastval)</code>). */
inline void
copy(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double Obj, const double LB, const double UB) {
CoinPackedVector::setVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */);
_Objective = Obj;
_LowerBound = LB;
_UpperBound = UB;
}
/*@}*/
//--------------------------------------------------------------------------
/**@name Constructors / Destructor */
/*@{*/
/** The default constructor creates an empty column with 0 as objective
coefficient, 0.0 as lower and +infinity as upper bound. */
BCP_col() : CoinPackedVector(false /* no test for duplicate index */),
_Objective(0), _LowerBound(0.0), _UpperBound(1e31) {}
/** The copy constructor makes a copy of <code>x</code>. */
BCP_col(const BCP_col& x) :
CoinPackedVector(x), _Objective(x.Objective()),
_LowerBound(x.LowerBound()), _UpperBound(x.UpperBound()) {}
/** This constructor acts exactly like the <code>copy</code> method with
the same argument list. */
BCP_col(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double Obj, const double LB, const double UB) :
CoinPackedVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */),
_Objective(Obj), _LowerBound(LB), _UpperBound(UB) {}
/** This constructor acts exactly like the <code>assign</code> method with
the same argument list. */
BCP_col(const int size, int*& ElementIndices, double*& ElementValues,
const double Obj, const double LB, const double UB) :
CoinPackedVector(), _Objective(Obj), _LowerBound(LB), _UpperBound(UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
}
BCP_col(const CoinPackedVectorBase& vec,
const double Obj, const double LB, const double UB) :
CoinPackedVector(vec.getNumElements(),
vec.getIndices(), vec.getElements()),
_Objective(Obj), _LowerBound(LB), _UpperBound(UB) {}
/** The destructor deletes all data members. */
~BCP_col() {}
/*@}*/
};
//#############################################################################
/** This class holds a row in a compressed form. That is, it is a packed
vector with a lower and upper bound. */
class BCP_row : public CoinPackedVector {
protected:
/**@name Data members */
/*@{*/
/** The lower bound corresponding to the row. */
double _LowerBound;
/** The upper bound corresponding to the row. */
double _UpperBound;
/*@}*/
//--------------------------------------------------------------------------
public:
/**@name Query methods */
/*@{*/
/** Return the lower bound. */
inline double LowerBound() const { return _LowerBound; }
/** Return the upper bound. */
inline double UpperBound() const { return _UpperBound; }
/*@}*/
//--------------------------------------------------------------------------
/**@name General modifying methods */
/*@{*/
/** Set the lower bound to the given value. */
inline void LowerBound(double lb) { _LowerBound = lb; }
/** Set the upper bound to the given value. */
inline void UpperBound(double ub) { _UpperBound = ub; }
/** Assignment operator: copy over the contents of <code>x</code>. */
BCP_row& operator=(const BCP_row& x) {
CoinPackedVector::operator=(x);
_LowerBound = x.LowerBound();
_UpperBound = x.UpperBound();
return *this;
}
/** Set the lower and upper bounds to the given values. Also invokes the
assign method of the underlying packed vector. */
void
assign(const int size, int*& ElementIndices, double*& ElementValues,
const double LB, const double UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_LowerBound = LB;
_UpperBound = UB;
}
/** Copy the arguments into the appropriate data members. */
void
copy(const int size, const int* ElementIndices, const double* ElementValues,
const double LB, const double UB) {
CoinPackedVector::setVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_LowerBound = LB;
_UpperBound = UB;
}
/** Same as the other <code>copy()</code> method, except that instead of
using vectors the indices (values) are given in
<code>[firstind,lastind)</code> (<code>[firstval,lastval)</code>). */
void
copy(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double LB, const double UB) {
CoinPackedVector::setVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */);
_LowerBound = LB;
_UpperBound = UB;
}
/*@}*/
//--------------------------------------------------------------------------
/**@name Constructors / Destructor */
/*@{*/
/** The default constructor creates an empty row with -infinity as lower
and +infinity as upper bound. */
BCP_row() : CoinPackedVector(false /* no test for duplicate index */),
_LowerBound(-DBL_MAX), _UpperBound(DBL_MAX) {}
/** The copy constructor makes a copy of <code>x</code>. */
BCP_row(const BCP_row& x) :
CoinPackedVector(x),
_LowerBound(x.LowerBound()), _UpperBound(x.UpperBound()) {}
/** This constructor acts exactly like the <code>copy</code> method with
the same argument list. */
BCP_row(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double LB, const double UB) :
CoinPackedVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */),
_LowerBound(LB), _UpperBound(UB) {}
/** This constructor acts exactly like the <code>assign</code> method with
the same argument list. */
BCP_row(const int size, int*& ElementIndices, double*& ElementValues,
const double LB, const double UB) :
CoinPackedVector(), _LowerBound(LB), _UpperBound(UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
}
BCP_row(const CoinPackedVectorBase& vec, const double LB, const double UB) :
CoinPackedVector(vec.getNumElements(),
vec.getIndices(), vec.getElements()),
_LowerBound(LB), _UpperBound(UB) {}
/** The destructor deletes all data members. */
~BCP_row() {}
/*@}*/
};
//#############################################################################
//#############################################################################
/** An object of type <code>CBP_lp_relax</code> holds the description of an lp
relaxation. The matrix, lower/upper bounds on the variables and cuts and
objective coefficients for the variables. */
class BCP_lp_relax : public CoinPackedMatrix {
private:
/**@name Data members */
/*@{*/
/** The objective coefficients of the variables. */
BCP_vec<double> _Objective;
/** The lower bounds on the variables. */
BCP_vec<double> _ColLowerBound;
/** The upper bounds on the variables. */
BCP_vec<double> _ColUpperBound;
/** The lower bounds on the cuts. */
BCP_vec<double> _RowLowerBound;
/** The upper bounds on the cuts. */
BCP_vec<double> _RowUpperBound;
/*@}*/
//--------------------------------------------------------------------------
public:
/**@name Query methods */
/*@{*/
/** The number of columns. */
inline size_t colnum() const { return _ColLowerBound.size(); }
/** The number of rows. */
inline size_t rownum() const { return _RowLowerBound.size(); }
/** A const reference to the vector of objective coefficients. */
inline const BCP_vec<double>& Objective() const {return _Objective;}
/** A const reference to the vector of lower bounds on the variables. */
inline const BCP_vec<double>& ColLowerBound() const {return _ColLowerBound;}
/** A const reference to the vector of upper bounds on the variables. */
inline const BCP_vec<double>& ColUpperBound() const {return _ColUpperBound;}
/** A const reference to the vector of lower bounds on the cuts. */
inline const BCP_vec<double>& RowLowerBound() const {return _RowLowerBound;}
/** A const reference to the vector of upper bounds on the cuts. */
inline const BCP_vec<double>& RowUpperBound() const {return _RowUpperBound;}
/*@}*/
//--------------------------------------------------------------------------
/**@name Methods modifying the whole LP relaxation. */
/*@{*/
/** Copy the content of <code>x</code> into the LP relaxation. */
BCP_lp_relax& operator=(const BCP_lp_relax& mat);
/** Reserve space in the LP relaxation for at least <code>MaxColNum</code>
columns, <code>MaxRowNum</code> rows and <code>MaxNonzeros</code>
nonzero entries. This is useful when columns/rows are added to the LP
relaxation in small chunks and to avoid a series of reallocation we
reserve sufficient space up front. */
void reserve(const int MaxColNum, const int MaxRowNum,
const int MaxNonzeros);
/** Clear the LP relaxation. */
void clear();
/** Set up the LP relaxation by making a copy of the arguments */
void copyOf(const CoinPackedMatrix& m,
const double* OBJ, const double* CLB, const double* CUB,
const double* RLB, const double* RUB);
/** Set up the LP relaxation by taking over the pointers in the arguments */
void assign(CoinPackedMatrix& m,
double*& OBJ, double*& CLB, double*& CUB,
double*& RLB, double*& RUB);
/*@}*/
//--------------------------------------------------------------------------
/**@name Methods for expanding/shrinking the LP relaxation. */
/*@{*/
#if 0
/** Append the columns in the argument column set to the end of this LP
relaxation. */
void add_col_set(const BCP_col_set& Cols);
/** Append the rows in the argument row set to the end of this LP
relaxation. */
void add_row_set(const BCP_row_set& Rows);
#endif
/** Remove the columns whose indices are listed in <code>pos</code> from
the LP relaxation. */
void erase_col_set(const BCP_vec<int>& pos);
/** Remove the rows whose indices are listed in <code>pos</code> from
the LP relaxation. */
void erase_row_set(const BCP_vec<int>& pos);
/*@}*/
//--------------------------------------------------------------------------
#if 0
/**@name Dot product methods */
/*@{*/
/** Compute the dot product of the index-th column with the full vector
given in <code>col</code>. */
double dot_product_col(const int index, const BCP_vec<double>& col) const;
/** Compute the dot product of the index-th row with the full vector
given in <code>row</code>. */
double dot_product_row(const int index, const BCP_vec<double>& row) const;
/** Compute the dot product of the index-th column with the full vector
starting at <code>col</code>. */
double dot_product_col(const int index, const double* col) const;
/** Compute the dot product of the index-th row with the full vector
starting at <code>row</code>. */
double dot_product_row(const int index, const double* row) const;
/*@}*/
#endif
//--------------------------------------------------------------------------
/**@name Packing/unpacking */
/*@{*/
/** Pack the LP relaxation into the buffer. */
void pack(BCP_buffer& buf) const;
/** Unpack the LP relaxation from the buffer. */
void unpack(BCP_buffer& buf);
/*@}*/
//--------------------------------------------------------------------------
/**@name Constructors and destructor */
/*@{*/
/** Create an empty LP relaxation with given ordering. */
BCP_lp_relax(const bool colordered = true) :
CoinPackedMatrix(colordered, 0, 0, 0, NULL, NULL, NULL, NULL),
_Objective(), _ColLowerBound(), _ColUpperBound(),
_RowLowerBound(), _RowUpperBound() {}
/** The copy constructor makes a copy of the argument LP relaxation. */
BCP_lp_relax(const BCP_lp_relax& mat);
/** Create a row major ordered LP relaxation by assigning the content of
the arguments to the LP relaxation. When the constructor returns the
content of 'rows' doesn't change while that of CLB, CUB and OBJ will be
whatever the default constructor for those arguments create. */
BCP_lp_relax(BCP_vec<BCP_row*>& rows,
BCP_vec<double>& CLB, BCP_vec<double>& CUB,
BCP_vec<double>& OBJ);
/** Same as the previous method except that this method allows extra_gap
and extra_major to be specified. For the description of those see the
documentation of CoinPackedMatrix. (extra_gap will be used for adding
columns, while extra major for adding rows) */
BCP_lp_relax(BCP_vec<BCP_row*>& rows,
BCP_vec<double>& CLB, BCP_vec<double>& CUB,
BCP_vec<double>& OBJ,
double extra_gap, double extra_major);
/** Create a column major ordered LP relaxation by assigning the content of
the arguments to the LP relaxation. When the constructor returns the
content of 'cols' doesn't change while that of RLB and RUB will be
whatever the default constructor for those arguments create. */
BCP_lp_relax(BCP_vec<BCP_col*>& cols,
BCP_vec<double>& RLB, BCP_vec<double>& RUB);
/** Same as the previous method except that this method allows extra_gap
and extra_major to be specified. For the description of those see the
documentation of CoinPackedMatrix. (extra_gap will be used for adding
rows, while extra major for adding columns) */
BCP_lp_relax(BCP_vec<BCP_col*>& cols,
BCP_vec<double>& RLB, BCP_vec<double>& RUB,
double extra_gap, double extra_major);
/** Create an LP relaxation of the given ordering by copying the content
of the arguments to the LP relaxation. */
BCP_lp_relax(const bool colordered,
const BCP_vec<int>& VB, const BCP_vec<int>& EI,
const BCP_vec<double>& EV, const BCP_vec<double>& OBJ,
const BCP_vec<double>& CLB, const BCP_vec<double>& CUB,
const BCP_vec<double>& RLB, const BCP_vec<double>& RUB);
/** Create an LP relaxation of the given ordering by assigning the content
of the arguments to the LP relaxation. When the constructor returns the
content of the arguments will be NULL pointers. <br>
*/
BCP_lp_relax(const bool colordered,
const int rownum, const int colnum, const int nznum,
int*& VB, int*& EI, double*& EV,
double*& OBJ, double*& CLB, double*& CUB,
double*& RLB, double*& RUB);
/** The destructor deletes the data members */
~BCP_lp_relax() {}
/*@}*/
private:
/**@name helper functions for the constructors */
/*@{*/
///
void BCP_createColumnOrderedMatrix(BCP_vec<BCP_row*>& rows,
BCP_vec<double>& CLB,
BCP_vec<double>& CUB,
BCP_vec<double>& OBJ);
///
void BCP_createRowOrderedMatrix(BCP_vec<BCP_col*>& cols,
BCP_vec<double>& RLB,
BCP_vec<double>& RUB);
/*@}*/
};
#endif
| 41.650442 | 79 | 0.625783 | kant |
b4edd9903a9b291dca0cc419439d573b9a957efb | 5,512 | cpp | C++ | Desktop/Lib/CCore/src/video/lib/Shape.FixedFrame.cpp | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | 8 | 2017-12-21T07:00:16.000Z | 2020-04-02T09:05:55.000Z | Desktop/Lib/CCore/src/video/lib/Shape.FixedFrame.cpp | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | null | null | null | Desktop/Lib/CCore/src/video/lib/Shape.FixedFrame.cpp | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | 1 | 2020-03-30T09:54:18.000Z | 2020-03-30T09:54:18.000Z | /* Shape.FixedFrame.cpp */
//----------------------------------------------------------------------------------------
//
// Project: CCore 3.50
//
// Tag: Desktop
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2017 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <CCore/inc/video/lib/Shape.FixedFrame.h>
namespace CCore {
namespace Video {
/* class FixedFrameShape */
void FixedFrameShape::draw_Frame(const DrawBuf &buf,Pane part) const
{
VColor frame=+cfg.frame;
VColor small=+cfg.dragSmall;
VColor frameSmall = has_good_size? frame : small ;
if( hilight==DragType_Bar ) frameSmall=frame=+cfg.frameHilight;
if( drag_type==DragType_Bar ) frameSmall=frame=+cfg.frameDrag;
drawFrame(buf,Pane(Null,size),client,frame,frameSmall,part);
}
void FixedFrameShape::draw_Frame(const DrawBuf &buf) const
{
draw_Frame(buf,Pane(Null,size));
}
void FixedFrameShape::draw_Frame(const DrawBuf &buf,DragType drag_type) const
{
Pane part=getPane(drag_type);
draw_Frame(buf.cut(part),part);
}
void FixedFrameShape::draw_Bar(const DrawBuf &buf) const
{
drawBar(buf,titleBar);
}
void FixedFrameShape::draw_Alert(const DrawBuf &buf) const
{
drawAlert(buf,btnAlert);
}
void FixedFrameShape::draw_Help(const DrawBuf &buf) const
{
drawHelp(buf,btnHelp);
}
void FixedFrameShape::draw_Min(const DrawBuf &buf) const
{
drawMin(buf,btnMin);
}
void FixedFrameShape::draw_Close(const DrawBuf &buf) const
{
drawClose(buf,btnClose);
}
void FixedFrameShape::layout(Point size_)
{
size=size_;
Coord dxy=+cfg.frame_dxy;
Coord tdy=+cfg.title_dy;
Coord bdx=+cfg.btn_dx;
Coord bdy=+cfg.btn_dy;
Coord btn_len = is_main? 5*bdx : 3*bdx ;
if( size>Point( 2*dxy+btn_len+bdx/2+Max(tdy,dxy) , dxy+Max(tdy,dxy) ) )
{
Pane pane=Pane(Null,size);
SplitX(dxy,pane);
SplitX(pane,dxy);
Pane top=SplitY(tdy,pane);
SplitY(pane,dxy);
client=pane;
Coord yb=(tdy-bdy)/2;
Coord tx=top.dx-btn_len;
if( is_main )
{
Coord xb0=top.x+tx;
Coord xb1=xb0+bdx+bdx/8;
Coord xb2=xb1+bdx+bdx/8;
Coord xb3=xb2+bdx+bdx/2;
btnAlert=Pane(xb0,yb,bdx,bdy);
btnHelp=Pane(xb1,yb,bdx,bdy);
btnMin=Pane(xb2,yb,bdx,bdy);
btnClose=Pane(xb3,yb,bdx,bdy);
}
else
{
Coord xb0=top.x+tx;
Coord xb1=xb0+bdx+bdx/2;
btnAlert=Empty;
btnMin=Empty;
btnHelp=Pane(xb0,yb,bdx,bdy);
btnClose=Pane(xb1,yb,bdx,bdy);
}
Coord w=cfg.width.get().roundUp();
titleBar=Pane(top.x+bdx/4,w,tx-bdx/2,tdy-2*w);
}
else
{
client=Empty;
btnAlert=Empty;
btnHelp=Empty;
btnMin=Empty;
btnClose=Pane(Null,bdx,bdy);
titleBar=Empty;
}
}
Point FixedFrameShape::getDeltaSize() const
{
Coord dxy=+cfg.frame_dxy;
Coord tdy=+cfg.title_dy;
return Point(dxy,tdy)+Point(dxy,dxy);
}
Coord FixedFrameShape::getMinDX(bool is_main,StrLen title) const
{
Coord width=cfg.width.get().roundUp();
Coord tdy=+cfg.title_dy;
Coord dxy=+cfg.frame_dxy;
Coord bdx=+cfg.btn_dx;
Coord btn_len = is_main? 5*bdx : 3*bdx ;
Coord dx=getMinTitleDX(title,tdy-2*width);
Replace_max(dx,Max(tdy,dxy));
dx += 2*dxy+btn_len+bdx/2 ;
return dx;
}
DragType FixedFrameShape::dragTest(Point point) const
{
if( btnAlert.contains(point) ) return DragType_Alert;
if( btnHelp.contains(point) ) return DragType_Help;
if( btnMin.contains(point) ) return DragType_Min;
if( btnClose.contains(point) ) return DragType_Close;
return client.contains(point)?DragType_None:DragType_Bar;
}
Pane FixedFrameShape::getPane(DragType drag_type) const
{
switch( drag_type )
{
case DragType_Bar : return Pane(Null,size);
case DragType_Alert : return btnAlert;
case DragType_Help : return btnHelp;
case DragType_Min : return btnMin;
case DragType_Close : return btnClose;
default: return Empty;
}
}
Hint FixedFrameShape::getHint(Point point) const
{
switch( dragTest(point) )
{
case DragType_Alert : return {btnAlert,+cfg.hint_Alert};
case DragType_Help : return {btnHelp,+cfg.hint_Help};
case DragType_Min : return {btnMin,+cfg.hint_Minimize};
case DragType_Close : return {btnClose,+cfg.hint_Close};
default: return Null;
}
}
void FixedFrameShape::draw(const DrawBuf &buf) const
{
draw_Frame(buf);
draw_Bar(buf);
draw_Alert(buf);
draw_Help(buf);
draw_Min(buf);
draw_Close(buf);
}
void FixedFrameShape::draw(const DrawBuf &buf,DragType drag_type) const
{
if( drag_type==DragType_Bar )
{
draw_Frame(buf);
draw_Bar(buf);
draw_Alert(buf);
draw_Help(buf);
draw_Min(buf);
draw_Close(buf);
}
else
{
draw_Frame(buf,drag_type);
switch( drag_type )
{
case DragType_Alert : draw_Alert(buf); break;
case DragType_Help : draw_Help(buf); break;
case DragType_Min : draw_Min(buf); break;
case DragType_Close : draw_Close(buf); break;
}
}
}
void FixedFrameShape::drawHint(const DrawBuf &buf,Hint hint) const
{
FrameShapeBase::drawHint(buf,titleBar,hint);
}
} // namespace Video
} // namespace CCore
| 21.53125 | 90 | 0.630987 | SergeyStrukov |
b4eef0fcf4c0c5747f617ca484bff6622669060b | 11,488 | cc | C++ | algorithms/loopclosure/inverted-multi-index/test/test_inverted-multi-index.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 1,936 | 2017-11-27T23:11:37.000Z | 2022-03-30T14:24:14.000Z | algorithms/loopclosure/inverted-multi-index/test/test_inverted-multi-index.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 353 | 2017-11-29T18:40:39.000Z | 2022-03-30T15:53:46.000Z | algorithms/loopclosure/inverted-multi-index/test/test_inverted-multi-index.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 661 | 2017-11-28T07:20:08.000Z | 2022-03-28T08:06:29.000Z | #include <utility>
#include <vector>
#include <Eigen/Core>
#include <aslam/common/memory.h>
#include <maplab-common/test/testing-entrypoint.h>
#include <maplab-common/test/testing-predicates.h>
#include <inverted-multi-index/inverted-multi-index-common.h>
#include <inverted-multi-index/inverted-multi-index.h>
namespace loop_closure {
namespace inverted_multi_index {
namespace {
class TestableInvertedMultiIndex : public InvertedMultiIndex<3> {
public:
TestableInvertedMultiIndex(
const Eigen::MatrixXf& words1, const Eigen::MatrixXf& words2,
int num_closest_words_for_nn_search)
: InvertedMultiIndex<3>(words1, words2, num_closest_words_for_nn_search) {
}
using InvertedMultiIndex<3>::words_1_index_;
using InvertedMultiIndex<3>::words_2_index_;
using InvertedMultiIndex<3>::word_index_map_;
using InvertedMultiIndex<3>::inverted_files_;
using InvertedMultiIndex<3>::max_db_descriptor_index_;
};
class InvertedMultiIndexTest : public ::testing::Test {
public:
void SetUp() {
words1_.resize(3, 10);
words1_ << 0.751267059305653, 0.547215529963803, 0.814284826068816,
0.616044676146639, 0.917193663829810, 0.075854289563064,
0.568823660872193, 0.311215042044805, 0.689214503140008,
0.152378018969223, 0.255095115459269, 0.138624442828679,
0.243524968724989, 0.473288848902729, 0.285839018820374,
0.053950118666607, 0.469390641058206, 0.528533135506213,
0.748151592823709, 0.825816977489547, 0.505957051665142,
0.149294005559057, 0.929263623187228, 0.351659507062997,
0.757200229110721, 0.530797553008973, 0.011902069501241,
0.165648729499781, 0.450541598502498, 0.538342435260057;
words2_.resize(3, 5);
words2_ << 0.699076722656686, 0.257508254123736, 0.349983765984809,
0.830828627896291, 0.753729094278495, 0.890903252535798,
0.840717255983663, 0.196595250431208, 0.585264091152724,
0.380445846975357, 0.959291425205444, 0.254282178971531,
0.251083857976031, 0.549723608291140, 0.567821640725221;
}
Eigen::MatrixXf words1_;
Eigen::MatrixXf words2_;
};
TEST_F(InvertedMultiIndexTest, AddDescriptorsWorks) {
// FLAG used to control the amount of backtracking done during kd-tree-based
// nearest neighbor search. In order to work, this test needs a certain amount
// of backtracking.
FLAGS_lc_knn_epsilon = 0.2;
Eigen::MatrixXf descriptors(6, 50);
descriptors << 0.837, 0.298, 0.071, 0.971, 0.205, 0.170, 0.236, 0.043, 0.087,
0.638, 0.583, 0.727, 0.013, 0.741, 0.088, 0.465, 0.514, 0.948, 0.552,
0.118, 0.018, 0.719, 0.482, 0.343, 0.599, 0.984, 0.455, 0.568, 0.576,
0.678, 0.370, 0.506, 0.600, 0.867, 0.888, 0.520, 0.736, 0.227, 0.072,
0.176, 0.858, 0.497, 0.403, 0.861, 0.921, 0.425, 0.671, 0.998, 0.903,
0.938, 0.930, 0.721, 0.448, 0.799, 0.284, 0.239, 0.616, 0.298, 0.906,
0.573, 0.741, 0.156, 0.148, 0.379, 0.706, 0.703, 0.355, 0.351, 0.068,
0.969, 0.354, 0.875, 0.930, 0.869, 0.565, 0.213, 0.309, 0.106, 0.854,
0.163, 0.677, 0.443, 0.087, 0.276, 0.981, 0.792, 0.251, 0.918, 0.980,
0.026, 0.769, 0.473, 0.339, 0.565, 0.326, 0.986, 0.031, 0.662, 0.249,
0.035, 0.886, 0.901, 0.071, 0.524, 0.733, 0.091, 0.311, 0.473, 0.904,
0.531, 0.526, 0.849, 0.618, 0.361, 0.899, 0.763, 0.485, 0.668, 0.575,
0.861, 0.633, 0.427, 0.447, 0.930, 0.124, 0.250, 0.713, 0.405, 0.029,
0.250, 0.432, 0.096, 0.117, 0.666, 0.898, 0.608, 0.097, 0.468, 0.062,
0.943, 0.889, 0.583, 0.268, 0.101, 0.953, 0.780, 0.558, 0.219, 0.034,
0.378, 0.765, 0.044, 0.904, 0.320, 0.570, 0.855, 0.452, 0.344, 0.235,
0.919, 0.958, 0.052, 0.934, 0.927, 0.830, 0.992, 0.711, 0.888, 0.199,
0.056, 0.362, 0.465, 0.311, 0.337, 0.567, 0.951, 0.908, 0.336, 0.734,
0.975, 0.654, 0.448, 0.991, 0.075, 0.128, 0.767, 0.775, 0.565, 0.282,
0.388, 0.698, 0.721, 0.439, 0.631, 0.733, 0.555, 0.991, 0.568, 0.137,
0.178, 0.608, 0.342, 0.451, 0.838, 0.624, 0.879, 0.163, 0.829, 0.508,
0.016, 0.986, 0.644, 0.639, 0.408, 0.485, 0.720, 0.818, 0.689, 0.518,
0.810, 0.513, 0.134, 0.244, 0.271, 0.473, 0.743, 0.445, 0.259, 0.231,
0.772, 0.679, 0.817, 0.654, 0.055, 0.155, 0.941, 0.707, 0.637, 0.460,
0.132, 0.651, 0.524, 0.103, 0.482, 0.090, 0.633, 0.265, 0.352, 0.250,
0.035, 0.748, 0.238, 0.528, 0.061, 0.257, 0.691, 0.227, 0.143, 0.551,
0.207, 0.798, 0.442, 0.920, 0.016, 0.275, 0.457, 0.737, 0.763, 0.951,
0.274, 0.999, 0.092, 0.940, 0.526, 0.270, 0.512, 0.774, 0.466, 0.781,
0.848, 0.947, 0.413, 0.636, 0.867, 0.813, 0.664, 0.702, 0.687, 0.818,
0.825, 0.437, 0.302, 0.145, 0.855, 0.363, 0.091, 0.329, 0.044, 0.380,
0.876;
std::vector<int> nearest_word_per_descriptor = {
43, 47, 38, 41, 26, 35, 37, 26, 46, 44, 40, 11, 25, 18, 48, 43, 15,
23, 0, 46, 25, 42, 44, 47, 32, 3, 4, 2, 34, 5, 45, 31, 8, 22,
42, 40, 8, 48, 49, 29, 43, 18, 37, 34, 14, 46, 4, 42, 7, 2};
std::vector<bool> word_used(50, false);
std::vector<int> word_index(50, -1);
int counter = 0;
for (int i = 0; i < 50; ++i) {
if (!word_used[nearest_word_per_descriptor[i]]) {
word_index[nearest_word_per_descriptor[i]] = counter;
word_used[nearest_word_per_descriptor[i]] = true;
++counter;
}
}
TestableInvertedMultiIndex index(words1_, words2_, 10);
index.AddDescriptors(descriptors);
ASSERT_EQ(50, index.max_db_descriptor_index_);
ASSERT_EQ(32u, index.word_index_map_.size());
ASSERT_EQ(32u, index.inverted_files_.size());
// Ensures that every descriptor is stored in its correct place.
std::vector<int> word_counts(50, 0);
for (int i = 0; i < 50; ++i) {
int word = word_index[nearest_word_per_descriptor[i]];
ASSERT_GE(word, 0);
ASSERT_LT(word, 32);
ASSERT_EQ(
index.inverted_files_[word].descriptors_.size(),
index.inverted_files_[word].indices_.size());
ASSERT_GE(
static_cast<int>(index.inverted_files_[word].descriptors_.size()),
word_counts[word]);
EXPECT_EQ(index.inverted_files_[word].indices_[word_counts[word]], i);
EXPECT_NEAR_EIGEN(
index.inverted_files_[word].descriptors_[word_counts[word]],
descriptors.col(i), 1e-12);
word_counts[word] += 1;
}
index.Clear();
EXPECT_EQ(0, index.max_db_descriptor_index_);
}
TEST_F(InvertedMultiIndexTest, GetNNearestNeighborsWorks) {
Eigen::MatrixXf descriptors(6, 50);
descriptors << 0.837, 0.298, 0.071, 0.971, 0.205, 0.170, 0.236, 0.043, 0.087,
0.638, 0.583, 0.727, 0.013, 0.741, 0.088, 0.465, 0.514, 0.948, 0.552,
0.118, 0.018, 0.719, 0.482, 0.343, 0.599, 0.984, 0.455, 0.568, 0.576,
0.678, 0.370, 0.506, 0.600, 0.867, 0.888, 0.520, 0.736, 0.227, 0.072,
0.176, 0.858, 0.497, 0.403, 0.861, 0.921, 0.425, 0.671, 0.998, 0.903,
0.938, 0.930, 0.721, 0.448, 0.799, 0.284, 0.239, 0.616, 0.298, 0.906,
0.573, 0.741, 0.156, 0.148, 0.379, 0.706, 0.703, 0.355, 0.351, 0.068,
0.969, 0.354, 0.875, 0.930, 0.869, 0.565, 0.213, 0.309, 0.106, 0.854,
0.163, 0.677, 0.443, 0.087, 0.276, 0.981, 0.792, 0.251, 0.918, 0.980,
0.026, 0.769, 0.473, 0.339, 0.565, 0.326, 0.986, 0.031, 0.662, 0.249,
0.035, 0.886, 0.901, 0.071, 0.524, 0.733, 0.091, 0.311, 0.473, 0.904,
0.531, 0.526, 0.849, 0.618, 0.361, 0.899, 0.763, 0.485, 0.668, 0.575,
0.861, 0.633, 0.427, 0.447, 0.930, 0.124, 0.250, 0.713, 0.405, 0.029,
0.250, 0.432, 0.096, 0.117, 0.666, 0.898, 0.608, 0.097, 0.468, 0.062,
0.943, 0.889, 0.583, 0.268, 0.101, 0.953, 0.780, 0.558, 0.219, 0.034,
0.378, 0.765, 0.044, 0.904, 0.320, 0.570, 0.855, 0.452, 0.344, 0.235,
0.919, 0.958, 0.052, 0.934, 0.927, 0.830, 0.992, 0.711, 0.888, 0.199,
0.056, 0.362, 0.465, 0.311, 0.337, 0.567, 0.951, 0.908, 0.336, 0.734,
0.975, 0.654, 0.448, 0.991, 0.075, 0.128, 0.767, 0.775, 0.565, 0.282,
0.388, 0.698, 0.721, 0.439, 0.631, 0.733, 0.555, 0.991, 0.568, 0.137,
0.178, 0.608, 0.342, 0.451, 0.838, 0.624, 0.879, 0.163, 0.829, 0.508,
0.016, 0.986, 0.644, 0.639, 0.408, 0.485, 0.720, 0.818, 0.689, 0.518,
0.810, 0.513, 0.134, 0.244, 0.271, 0.473, 0.743, 0.445, 0.259, 0.231,
0.772, 0.679, 0.817, 0.654, 0.055, 0.155, 0.941, 0.707, 0.637, 0.460,
0.132, 0.651, 0.524, 0.103, 0.482, 0.090, 0.633, 0.265, 0.352, 0.250,
0.035, 0.748, 0.238, 0.528, 0.061, 0.257, 0.691, 0.227, 0.143, 0.551,
0.207, 0.798, 0.442, 0.920, 0.016, 0.275, 0.457, 0.737, 0.763, 0.951,
0.274, 0.999, 0.092, 0.940, 0.526, 0.270, 0.512, 0.774, 0.466, 0.781,
0.848, 0.947, 0.413, 0.636, 0.867, 0.813, 0.664, 0.702, 0.687, 0.818,
0.825, 0.437, 0.302, 0.145, 0.855, 0.363, 0.091, 0.329, 0.044, 0.380,
0.876;
std::vector<int> nearest_word_per_descriptor = {
43, 47, 38, 41, 26, 35, 37, 26, 46, 44, 40, 11, 25, 18, 48, 43, 15,
23, 0, 46, 25, 42, 44, 47, 32, 3, 4, 2, 34, 5, 45, 31, 8, 22,
42, 40, 8, 48, 49, 29, 43, 18, 37, 34, 14, 46, 4, 42, 7, 2};
Eigen::MatrixXf query_descriptors(6, 10);
query_descriptors << 0.971, 0.890, 0.610, 0.509, 0.017, 0.922, 0.901, 0.323,
0.321, 0.745, 0.581, 0.179, 0.900, 0.622, 0.827, 0.945, 0.020, 0.921,
0.409, 0.737, 0.369, 0.800, 0.027, 0.497, 0.493, 0.556, 0.168, 0.705,
0.107, 0.012, 0.913, 0.912, 0.232, 0.611, 0.513, 0.625, 0.543, 0.639,
0.716, 0.584, 0.638, 0.791, 0.944, 0.111, 0.226, 0.626, 0.105, 0.086,
0.834, 0.696, 0.470, 0.813, 0.640, 0.236, 0.182, 0.292, 0.039, 0.230,
0.707, 0.006;
TestableInvertedMultiIndex index(words1_, words2_, 10);
index.AddDescriptors(descriptors);
for (int i = 0; i < 10; ++i) {
std::vector<std::pair<int, int> > ten_closest_words;
common::FindClosestWords<3>(
query_descriptors.col(i), 10, *(index.words_1_index_),
*(index.words_2_index_), words1_.cols(), words2_.cols(),
&ten_closest_words);
std::vector<bool> word_activated(50, 0);
for (int j = 0; j < 10; ++j) {
int word_index = ten_closest_words[j].first * words2_.cols() +
ten_closest_words[j].second;
word_activated[word_index] = true;
}
static constexpr int kNumNeighbors = 10;
Eigen::VectorXi indices(kNumNeighbors, 1);
Eigen::VectorXf distances(kNumNeighbors, 1);
index.GetNNearestNeighbors(
query_descriptors.block<6, 1>(0, i), kNumNeighbors, indices, distances);
// Verifies that the nearest neighbors are correct through linear search.
std::vector<std::pair<float, int> > gt_distances;
int num_neighbors = 0;
for (int j = 0; j < 50; ++j) {
if (!word_activated[nearest_word_per_descriptor[j]])
continue;
float d = (descriptors.col(j) - query_descriptors.col(i)).squaredNorm();
gt_distances.push_back(std::make_pair(d, j));
++num_neighbors;
}
std::sort(gt_distances.begin(), gt_distances.end());
Eigen::VectorXi expected_indices(kNumNeighbors, 1);
int num_elements = std::min(kNumNeighbors, num_neighbors);
for (int j = 0; j < num_elements; ++j) {
EXPECT_FLOAT_EQ(gt_distances[j].first, distances[j]);
expected_indices(j, 0) = gt_distances[j].second;
}
EXPECT_TRUE(
::common::MatricesEqual(
indices.block(0, 0, num_elements, 1),
expected_indices.block(0, 0, num_elements, 1), 1e-9));
}
}
} // namespace
} // namespace inverted_multi_index
} // namespace loop_closure
MAPLAB_UNITTEST_ENTRYPOINT
| 48.677966 | 80 | 0.616382 | AdronTech |
b4f02c1822a80467f974b87e28504ea4c78819be | 12,609 | cpp | C++ | C++/6.cpp | pissmilk/old_homework | e7d07fc6773529df2fe09cfa61b751e3a18fbf28 | [
"MIT"
] | null | null | null | C++/6.cpp | pissmilk/old_homework | e7d07fc6773529df2fe09cfa61b751e3a18fbf28 | [
"MIT"
] | null | null | null | C++/6.cpp | pissmilk/old_homework | e7d07fc6773529df2fe09cfa61b751e3a18fbf28 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
using namespace std;
class Hole {
public:
bool isEmpty = true;
int id = -1;
Hole *upRight = nullptr;
Hole *upLeft = nullptr;
Hole *downLeft = nullptr;
Hole *downRight = nullptr;
Hole *left = nullptr;
Hole *right = nullptr;
Hole(bool e, int num) {
isEmpty = e;
id = num;
}
void printHoleID() {
cout << setw(4) << id;
}
void printHolePeg() {
if (isEmpty) {
cout << setw(4) << "-";
} else {
cout << setw(4) << "p";
}
}
};
class PegJumpGame {
private:
Hole *holes[15] = {
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr
};
public:
PegJumpGame() {
holes[0] = new Hole(true, 0);
holes[1] = new Hole(false, 1);
holes[2] = new Hole(false, 2);
holes[3] = new Hole(false, 3);
holes[4] = new Hole(false, 4);
holes[5] = new Hole(false, 5);
holes[6] = new Hole(false, 6);
holes[7] = new Hole(false, 7);
holes[8] = new Hole(false, 8);
holes[9] = new Hole(false, 9);
holes[10] = new Hole(false, 10);
holes[11] = new Hole(false, 11);
holes[12] = new Hole(false, 12);
holes[13] = new Hole(false, 13);
holes[14] = new Hole(false, 14);
holes[0]->downLeft = holes[1];
holes[0]->downRight = holes[2];
holes[1]->upRight = holes[0];
holes[1]->right = holes[2];
holes[1]->downLeft = holes[3];
holes[1]->downRight = holes[4];
holes[2]->upLeft = holes[0];
holes[2]->left = holes[1];
holes[2]->downLeft = holes[4];
holes[2]->downRight = holes[5];
holes[3]->upRight = holes[1];
holes[3]->right = holes[4];
holes[3]->downLeft = holes[6];
holes[3]->downRight = holes[7];
holes[4]->upLeft = holes[1];
holes[4]->upRight = holes[2];
holes[4]->left = holes[3];
holes[4]->right = holes[5];
holes[4]->downLeft = holes[7];
holes[4]->downRight = holes[8];
holes[5]->upLeft = holes[2];
holes[5]->left = holes[4];
holes[5]->downLeft = holes[8];
holes[5]->downRight = holes[9];
holes[6]->upRight = holes[3];
holes[6]->right = holes[7];
holes[6]->downLeft = holes[10];
holes[6]->downRight = holes[11];
holes[7]->upLeft = holes[3];
holes[7]->upRight = holes[4];
holes[7]->left = holes[6];
holes[7]->right = holes[8];
holes[7]->downLeft = holes[11];
holes[7]->downRight = holes[12];
holes[8]->upLeft = holes[4];
holes[8]->upRight = holes[5];
holes[8]->left = holes[7];
holes[8]->right = holes[9];
holes[8]->downLeft = holes[12];
holes[8]->downRight = holes[13];
holes[9]->upLeft = holes[5];
holes[9]->left = holes[8];
holes[9]->downLeft = holes[13];
holes[9]->downRight = holes[14];
holes[10]->upRight = holes[6];
holes[10]->right = holes[11];
holes[11]->upLeft = holes[6];
holes[11]->upRight = holes[7];
holes[11]->left = holes[10];
holes[11]->right = holes[12];
holes[12]->upLeft = holes[7];
holes[12]->upRight = holes[8];
holes[12]->left = holes[11];
holes[12]->right = holes[13];
holes[13]->upLeft = holes[8];
holes[13]->upRight = holes[9];
holes[13]->left = holes[12];
holes[13]->right = holes[14];
holes[14]->upLeft = holes[9];
holes[14]->left = holes[13];
}
bool movePeg(int fromID, string direction) {
Hole *holePtr = holes[fromID];
if (holePtr->isEmpty) {
cout << "\nSorry There is no peg I can use to jump at location " << fromID << ". Move aborted.\n\n";
return false;
}
Hole *jumpOverHole = nullptr;
Hole *jumpToHole = nullptr;
if (direction == "left") {
jumpOverHole = holePtr->left;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->left;
}
} else if (direction == "right") {
jumpOverHole = holePtr->right;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->right;
}
} else if (direction == "upRight" || direction == "upright") {
jumpOverHole = holePtr->upRight;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->upRight;
}
} else if (direction == "upLeft" || direction == "upleft") {
jumpOverHole = holePtr->upLeft;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->upLeft;
}
} else if (direction == "downLeft" || direction == "downleft") {
jumpOverHole = holePtr->downLeft;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->downLeft;
}
} else if (direction == "downRight" || direction == "downright") {
jumpOverHole = holePtr->downRight;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->downRight;
}
} else {
cout << "\nSorry I do not recognize the direction " << direction << ". Move aborted.\n" << endl;
return false;
}
return doJump(holePtr, jumpOverHole, jumpToHole);
}
bool doJump(Hole *jumpFromHolePtr, Hole *jumpOverHolePtr, Hole *jumpToHolePtr) {
if (jumpFromHolePtr == nullptr || jumpToHolePtr == nullptr || jumpOverHolePtr == nullptr) {
return false;
}
if (jumpToHolePtr->isEmpty == false) {
return false;
}
jumpToHolePtr->isEmpty = false;
jumpFromHolePtr->isEmpty = true;
jumpOverHolePtr->isEmpty = true;
return true;
}
bool printBoard() {
for (int loop = 0; loop < 2; ++loop) {
int holeCount = 0, holeIDProblems = 0, linkProblems = 0;
string pad(14, ' ');
Hole *holePtr = holes[0];
if (holePtr == nullptr) {
cout << "printBoard(): ERROR: holes[0] is null. Cannot print empty board.Abort" << endl;
return false;
}
if (loop == 0) {
cout << "Board Hole Position IDs are:" << endl;
} else {
cout << "\nYour Pegs are:" << endl;
}
cout << pad;
while (holePtr != nullptr) {
if (loop == 0) {
holePtr->printHoleID();
} else {
holePtr->printHolePeg();
}
if (holeCount++ != holePtr->id) {
holeIDProblems++;
}
if (loop == 0) {
linkProblems += (holePtr->left != nullptr ? (holePtr->left->right != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->right != nullptr ? (holePtr->right->left != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->upRight != nullptr ? (holePtr->upRight->downLeft != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->upLeft != nullptr ? (holePtr->upLeft->downRight != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->downLeft != nullptr ? (holePtr->downLeft->upRight != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->downRight != nullptr ? (holePtr->downRight->upLeft != holePtr ? 1 : 0) : 0 );
if (linkProblems > 0) {
cout << "\nPrintBoard(): Error: encountered " << linkProblems << " problems with the links on hole with ID == " << holePtr->id << ".Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->left == nullptr && (holePtr->id != 0 && holePtr->id != 1 && holePtr->id !=3 && holePtr->id !=6 && holePtr->id !=10)) {
cout << "\nPrintBoard(): Error: left pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->right == nullptr && (holePtr->id != 0 && holePtr->id != 2 && holePtr->id !=5 && holePtr->id !=9 && holePtr->id !=14)) {
cout << "\nPrintBoard(): Error: right pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->downLeft == nullptr && (holePtr->id != 10 && holePtr->id != 11 && holePtr->id !=12 && holePtr->id !=13 && holePtr->id !=14)) {
cout << "\nPrintBoard(): Error: downLeft pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->downRight == nullptr && (holePtr->id != 10 && holePtr->id != 11 && holePtr->id !=12 && holePtr->id !=13 && holePtr->id !=14)) {
cout << "\nPrintBoard(): Error: downRight pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
}
if (holePtr->right != nullptr) {
holePtr = holePtr->right;
} else {
while (holePtr->left != nullptr) {
holePtr = holePtr->left;
}
if (holePtr->downLeft != nullptr) {
holePtr = holePtr->downLeft;
pad.pop_back();
pad.pop_back();
cout << endl;
cout << pad;
} else {
break;
}
}
}
cout << endl;
if (loop == 0 && holeIDProblems != 0) {
cout << "\nPrintBoard(): Error: " << holeIDProblems << " of your hole IDs shown above are not correct! Please check your constructor. Abort." << endl;
return false;
}
}
return true;
}
};
int main() {
cout << "Calling PegJumpGame constructor...." << endl;
PegJumpGame p;
cout << "OK Let's play!!" << endl;
int pegToMove;
string direction;
bool moveSucceeded = false;
if (!p.printBoard()) {
cout << "printBoard found a problem... abort program." << endl;
return 1;
}
for (;;) {
cout << "\nWhat Hole ID would you like to move a peg from (0..14)? ";
cin >> pegToMove;
if (pegToMove <0 || pegToMove > 14) {
cout << "Sorry - that is not a valid number... please try again! " << endl;
continue;
}
cout << "In what direction would you like to move peg #" << pegToMove << " (upLeft, upRight, left, right, downLeft, or downRight) ? ";
cin >> direction;
moveSucceeded = p.movePeg(pegToMove, direction);
if (moveSucceeded) {
cout << "Well-played!" << endl;
if (!p.printBoard()) {
break;
}
} else {
cout << "Sorry that move did not work" << endl;
}
}
}
| 38.325228 | 207 | 0.44722 | pissmilk |
b4f0464df70ec90e1830f970cde7a89b2b9bf6db | 10,795 | cpp | C++ | example/oglplus/026_stencil_shadow.cpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | null | null | null | example/oglplus/026_stencil_shadow.cpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | null | null | null | example/oglplus/026_stencil_shadow.cpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | null | null | null | /**
* @example oglplus/026_stencil_shadow.cpp
* @brief Shows how to render shadows using geometry shader and stencil buffer
*
* @oglplus_screenshot{026_stencil_shadow}
*
* Copyright 2008-2015 Matus Chochlik. 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)
*
* @oglplus_example_uses_gl{GL_VERSION_3_3}
* @oglplus_example_uses_gl{GL_ARB_separate_shader_objects;GL_EXT_direct_state_access}
*/
#include <oglplus/gl.hpp>
#include <oglplus/all.hpp>
#include <oglplus/shapes/torus.hpp>
#include <cmath>
#include "example.hpp"
namespace oglplus {
class ShadowExample : public Example
{
private:
// the torus vertex attribute builder
shapes::Torus make_torus;
// here will be stored the indices used by the drawing instructions
shapes::Torus::IndexArray torus_indices;
// the instructions for drawing the torus
shapes::DrawingInstructions torus_instr;
// wrapper around the current OpenGL context
Context gl;
// Shaders and program for rendering of the objects
VertexShader vs_object;
FragmentShader fs_object;
Program object_prog;
// Shaders and program for rendering of the shadow effect
VertexShader vs_shadow;
GeometryShader gs_shadow;
FragmentShader fs_shadow;
Program shadow_prog;
// Uniforms
Uniform<Mat4f>
object_projection_matrix, object_camera_matrix, object_model_matrix,
shadow_projection_matrix, shadow_camera_matrix, shadow_model_matrix;
Uniform<Vec3f> object_color;
Uniform<GLfloat> object_light_mult;
// A vertex array object for the torus
VertexArray torus;
// VBOs for the torus' vertices and normals
Buffer torus_verts, torus_normals;
// A vertex array object for the shadowed plane
VertexArray plane;
// VBOs for the plane's vertices and normals
Buffer plane_verts, plane_normals;
public:
ShadowExample(void)
: make_torus(1.0, 0.7, 72, 48)
, torus_indices(make_torus.Indices())
, torus_instr(make_torus.Instructions())
, object_projection_matrix(object_prog)
, object_camera_matrix(object_prog)
, object_model_matrix(object_prog)
, shadow_projection_matrix(shadow_prog)
, shadow_camera_matrix(shadow_prog)
, shadow_model_matrix(shadow_prog)
, object_color(object_prog)
, object_light_mult(object_prog)
{
vs_object.Source(
"#version 140\n"
"in vec4 Position;"
"in vec3 Normal;"
"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
"uniform vec3 LightPos;"
"out vec3 vertNormal;"
"out vec3 vertLight;"
"void main(void)"
"{"
" gl_Position = ModelMatrix * Position;"
" vertNormal = mat3(ModelMatrix)*Normal;"
" vertLight = LightPos - gl_Position.xyz;"
" gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
"}"
);
vs_object.Compile();
fs_object.Source(
"#version 140\n"
"in vec3 vertNormal;"
"in vec3 vertLight;"
"uniform vec3 Color;"
"uniform float LightMult;"
"out vec4 fragColor;"
"void main(void)"
"{"
" float l = sqrt(length(vertLight));"
" float d = l > 0.0 ?"
" dot("
" vertNormal,"
" normalize(vertLight)"
" ) / l : 0.0;"
" float i = 0.3 + max(d, 0.0) * LightMult;"
" fragColor = vec4(Color*i, 1.0);"
"}"
);
fs_object.Compile();
object_prog.AttachShader(vs_object);
object_prog.AttachShader(fs_object);
object_prog.Link().Use();
object_projection_matrix.BindTo("ProjectionMatrix");
object_camera_matrix.BindTo("CameraMatrix");
object_model_matrix.BindTo("ModelMatrix");
object_color.BindTo("Color");
object_light_mult.BindTo("LightMult");
vs_shadow.Source(
"#version 150\n"
"in vec4 Position;"
"in vec3 Normal;"
"uniform mat4 ModelMatrix;"
"uniform vec3 LightPos;"
"out float ld;"
"void main(void)"
"{"
" gl_Position = ModelMatrix * Position;"
" vec3 geomNormal = mat3(ModelMatrix)*Normal;"
" vec3 lightDir = LightPos - gl_Position.xyz;"
" ld = dot(geomNormal, normalize(lightDir));"
"}"
);
vs_shadow.Compile();
gs_shadow.Source(
"#version 150\n"
"layout(triangles) in;"
"layout(triangle_strip, max_vertices = 12) out;"
"in float ld[];"
"uniform mat4 CameraMatrix, ProjectionMatrix;"
"uniform vec3 LightPos;"
"void main(void)"
"{"
" for(int v=0; v!=3; ++v)"
" {"
" int a = v, b = (v+1)%3, c = (v+2)%3;"
" vec4 pa = gl_in[a].gl_Position;"
" vec4 pb = gl_in[b].gl_Position;"
" vec4 pc = gl_in[c].gl_Position;"
" vec4 px, py;"
" if(ld[a] == 0.0 && ld[b] == 0.0)"
" {"
" px = pa;"
" py = pb;"
" }"
" else if(ld[a] > 0.0 && ld[b] < 0.0)"
" {"
" float x = ld[a]/(ld[a]-ld[b]);"
" float y;"
" px = mix(pa, pb, x);"
" if(ld[c] < 0.0)"
" {"
" y = ld[a]/(ld[a]-ld[c]);"
" py = mix(pa, pc, y);"
" }"
" else"
" {"
" y = ld[c]/(ld[c]-ld[b]);"
" py = mix(pc, pb, y);"
" }"
" }"
" else continue;"
" vec3 vx = px.xyz - LightPos;"
" vec3 vy = py.xyz - LightPos;"
" vec4 sx = vec4(px.xyz + vx*10.0, 1.0);"
" vec4 sy = vec4(py.xyz + vy*10.0, 1.0);"
" vec4 cpx = CameraMatrix * px;"
" vec4 cpy = CameraMatrix * py;"
" vec4 csx = CameraMatrix * sx;"
" vec4 csy = CameraMatrix * sy;"
" gl_Position = ProjectionMatrix * cpy;"
" EmitVertex();"
" gl_Position = ProjectionMatrix * cpx;"
" EmitVertex();"
" gl_Position = ProjectionMatrix * csy;"
" EmitVertex();"
" gl_Position = ProjectionMatrix * csx;"
" EmitVertex();"
" EndPrimitive();"
" break;"
" }"
"}"
);
gs_shadow.Compile();
fs_shadow.Source(
"#version 150\n"
"out vec4 fragColor;"
"void main(void)"
"{"
" fragColor = vec4(0.0, 0.0, 0.0, 1.0);"
"}"
);
fs_shadow.Compile();
shadow_prog.AttachShader(vs_shadow);
shadow_prog.AttachShader(gs_shadow);
shadow_prog.AttachShader(fs_shadow);
shadow_prog.Link().Use();
shadow_projection_matrix.BindTo("ProjectionMatrix");
shadow_camera_matrix.BindTo("CameraMatrix");
shadow_model_matrix.BindTo("ModelMatrix");
// bind the VAO for the torus
torus.Bind();
// bind the VBO for the torus vertices
torus_verts.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Positions(data);
Buffer::Data(Buffer::Target::Array, data);
VertexArrayAttrib attr(
VertexArrayAttrib::GetCommonLocation(
MakeGroup(object_prog, shadow_prog),
"Position"
)
);
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VBO for the torus normals
torus_normals.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Normals(data);
Buffer::Data(Buffer::Target::Array, data);
object_prog.Use();
VertexArrayAttrib attr(object_prog, "Normal");
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VAO for the plane
plane.Bind();
// bind the VBO for the plane vertices
plane_verts.Bind(Buffer::Target::Array);
{
GLfloat data[4*3] = {
-9.0f, 0.0f, -9.0f,
-9.0f, 0.0f, 9.0f,
9.0f, 0.0f, -9.0f,
9.0f, 0.0f, 9.0f
};
Buffer::Data(Buffer::Target::Array, 4*3, data);
object_prog.Use();
VertexArrayAttrib attr(object_prog, "Position");
attr.Setup<GLfloat>(3);
attr.Enable();
}
// bind the VBO for the torus normals
plane_normals.Bind(Buffer::Target::Array);
{
GLfloat data[4*3] = {
-0.1f, 1.0f, 0.1f,
-0.1f, 1.0f, -0.1f,
0.1f, 1.0f, 0.1f,
0.1f, 1.0f, -0.1f
};
Buffer::Data(Buffer::Target::Array, 4*3, data);
object_prog.Use();
VertexArrayAttrib attr(object_prog, "Normal");
attr.Setup<GLfloat>(3);
attr.Enable();
}
Vec3f lightPos(2.0f, 9.0f, 3.0f);
ProgramUniform<Vec3f>(object_prog, "LightPos").Set(lightPos);
ProgramUniform<Vec3f>(shadow_prog, "LightPos").Set(lightPos);
gl.ClearColor(0.2f, 0.2f, 0.2f, 0.0f);
gl.ClearDepth(1.0f);
gl.ClearStencil(0);
gl.Enable(Capability::DepthTest);
gl.Enable(Capability::CullFace);
gl.FrontFace(make_torus.FaceWinding());
}
void Reshape(GLuint width, GLuint height)
{
gl.Viewport(width, height);
Mat4f projection = CamMatrixf::PerspectiveX(
Degrees(70),
float(width)/height,
1, 30
);
object_prog.Use();
object_projection_matrix.Set(projection);
shadow_prog.Use();
shadow_projection_matrix.Set(projection);
}
void Render(double time)
{
gl.Clear().ColorBuffer().DepthBuffer().StencilBuffer();
auto camera = CamMatrixf::Orbiting(
Vec3f(),
9.0,
FullCircles(time * 0.1),
Degrees(15 + (-SineWave(0.25+time/12.5)+1.0)* 0.5 * 75)
);
ModelMatrixf identity;
ModelMatrixf model =
ModelMatrixf::Translation(0.0f, 2.5f, 0.0) *
ModelMatrixf::RotationA(
Vec3f(1.0f, 1.0f, 1.0f),
FullCircles(time * 0.2)
);
gl.CullFace(Face::Back);
gl.ColorMask(true, true, true, true);
gl.DepthMask(true);
gl.Disable(Capability::StencilTest);
object_prog.Use();
object_camera_matrix.Set(camera);
object_light_mult.Set(0.2f);
object_model_matrix.Set(identity);
plane.Bind();
gl.DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
object_model_matrix.Set(model);
torus.Bind();
torus_instr.Draw(torus_indices);
gl.ColorMask(false, false, false, false);
gl.DepthMask(false);
gl.Enable(Capability::StencilTest);
gl.StencilFunc(CompareFunction::Always, 0);
gl.StencilOpSeparate(
Face::Front,
StencilOp::Keep,
StencilOp::Keep,
StencilOp::Incr
);
gl.StencilOpSeparate(
Face::Back,
StencilOp::Keep,
StencilOp::Keep,
StencilOp::Decr
);
shadow_prog.Use();
shadow_camera_matrix.Set(camera);
shadow_model_matrix.Set(model);
gl.CullFace(Face::Back);
torus_instr.Draw(torus_indices);
gl.CullFace(Face::Front);
torus_instr.Draw(torus_indices);
gl.CullFace(Face::Back);
gl.ColorMask(true, true, true, true);
gl.DepthMask(true);
gl.Clear().DepthBuffer();
gl.StencilFunc(CompareFunction::Equal, 0);
gl.StencilOp(StencilOp::Keep, StencilOp::Keep, StencilOp::Keep);
object_prog.Use();
object_light_mult.Set(2.5);
object_model_matrix.Set(identity);
object_color.Set(0.8f, 0.7f, 0.4f);
plane.Bind();
gl.DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
object_model_matrix.Set(model);
object_color.Set(0.9f, 0.8f, 0.1f);
torus.Bind();
torus_instr.Draw(torus_indices);
}
bool Continue(double time)
{
return time < 60.0;
}
};
void setupExample(ExampleParams& /*params*/){ }
std::unique_ptr<ExampleThread> makeExampleThread(
Example& /*example*/,
unsigned /*thread_id*/,
const ExampleParams& /*params*/
){ return std::unique_ptr<ExampleThread>(); }
std::unique_ptr<Example> makeExample(const ExampleParams& /*params*/)
{
return std::unique_ptr<Example>(new ShadowExample);
}
} // namespace oglplus
| 25.459906 | 87 | 0.663733 | Extrunder |
b4f10f80f28b32110c8241615f73353e7c005a39 | 2,185 | hpp | C++ | extras/deprecated/vom/vom/l2_emulation_cmds.hpp | yasics/vpp | a4d0956082f12ac8269fd415134af7f605c1f3c9 | [
"Apache-2.0"
] | 751 | 2017-07-13T06:16:46.000Z | 2022-03-30T09:14:35.000Z | extras/deprecated/vom/vom/l2_emulation_cmds.hpp | yasics/vpp | a4d0956082f12ac8269fd415134af7f605c1f3c9 | [
"Apache-2.0"
] | 32 | 2021-03-24T06:04:08.000Z | 2021-09-14T02:02:22.000Z | extras/deprecated/vom/vom/l2_emulation_cmds.hpp | yasics/vpp | a4d0956082f12ac8269fd415134af7f605c1f3c9 | [
"Apache-2.0"
] | 479 | 2017-07-13T06:17:26.000Z | 2022-03-31T18:20:43.000Z | /*
* Copyright (c) 2017 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __VOM_L2_EMULATION_CMDS_H__
#define __VOM_L2_EMULATION_CMDS_H__
#include "vom/l2_emulation.hpp"
#include "vom/rpc_cmd.hpp"
#include <vapi/l2e.api.vapi.hpp>
namespace VOM {
namespace l2_emulation_cmds {
/**
* A functor class that enable L2 emulation to an interface
*/
class enable_cmd : public rpc_cmd<HW::item<bool>, vapi::L2_emulation>
{
public:
/**
* Constructor
*/
enable_cmd(HW::item<bool>& item, const handle_t& itf);
/**
* Issue the command to VPP/HW
*/
rc_t issue(connection& con);
/**
* convert to string format for debug purposes
*/
std::string to_string() const;
/**
* Comparison operator - only used for UT
*/
bool operator==(const enable_cmd& i) const;
private:
/**
* The interface to bind
*/
const handle_t m_itf;
};
/**
* A cmd class that Unbinds L2 configuration from an interface
*/
class disable_cmd : public rpc_cmd<HW::item<bool>, vapi::L2_emulation>
{
public:
/**
* Constructor
*/
disable_cmd(HW::item<bool>& item, const handle_t& itf);
/**
* Issue the command to VPP/HW
*/
rc_t issue(connection& con);
/**
* convert to string format for debug purposes
*/
std::string to_string() const;
/**
* Comparison operator - only used for UT
*/
bool operator==(const disable_cmd& i) const;
private:
/**
* The interface to bind
*/
const handle_t m_itf;
};
}; // namespace l2_emulation_cmds
}; // namespace VOM
/*
* fd.io coding-style-patch-verification: OFF
*
* Local Variables:
* eval: (c-set-style "mozilla")
* End:
*/
#endif
| 21.213592 | 75 | 0.679634 | yasics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.